diff --git "a/1412.jsonl" "b/1412.jsonl" new file mode 100644--- /dev/null +++ "b/1412.jsonl" @@ -0,0 +1,721 @@ +{"seq_id":"469332482","text":"import io\n\nclass Claim():\n def __init__(self, id, x1, y1, x2, y2):\n self.id = id\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n # print(\"{0} {1},{2} {3},{4}\".format(self.id, self.x1, self.y1, self.x2, self.y2))\n\n def layout(self, matrix):\n for x in range(x1, x2):\n for y in range(y1, y2):\n if matrix[x][y]:\n matrix[x][y] = matrix[x][y]+1\n else:\n matrix[x][y] = 1\n\n\nwidth, height = 1000, 1000;\nmatrix = [[0 for x in range(width)] for y in range(height)]\nclaims = []\n\nfor x in range(width):\n for y in range(height):\n matrix[x][y] = 0\n\n\nwith io.open('day3.input.txt', 'r', encoding='utf-8') as f:\n for line in f:\n tokens = line.split()\n # print(tokens)\n id = tokens[0][1:]\n coords = tokens[2].split(\",\")\n x1 = int(coords[0])\n y1 = int(coords[1][:-1])\n ranges = tokens[3].split(\"x\")\n x2 = x1 + int(ranges[0])\n y2 = y1 + int(ranges[1])\n claim = Claim(id=id, x1=x1, y1=y1, x2=x2, y2=y2)\n claim.layout(matrix)\n claims.append(claim)\n\noverlap_count = 0\nfor x in range(width):\n for y in range(height):\n if matrix[x][y]:\n if matrix[x][y] > 1:\n overlap_count += 1\n\nprint(overlap_count)\n\n\n","sub_path":"adventofcode/2018/day3/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337074956","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom licplot import lic_internal\n\n# create a 2d vector field\nvortex_spacing = 0.5\nextra_factor = 2.0\nsize = 700\n\na = np.array([1, 0]) * vortex_spacing\nb = np.array([np.cos(np.pi / 3), np.sin(np.pi / 3)]) * vortex_spacing\nrnv = int(2 * extra_factor / vortex_spacing)\nvortices = [n * a + m * b for n in range(-rnv, rnv) for m in range(-rnv, rnv)]\nvortices = [\n (x, y)\n for (x, y) in vortices\n if -extra_factor < x < extra_factor and -extra_factor < y < extra_factor\n]\n\n\nxs = np.linspace(-1, 1, size).astype(np.float32)[None, :]\nys = np.linspace(-1, 1, size).astype(np.float32)[:, None]\n\nu = np.zeros((size, size), dtype=np.float32)\nv = np.zeros((size, size), dtype=np.float32)\nfor (x, y) in vortices:\n rsq = (xs - x) ** 2 + (ys - y) ** 2\n u += (ys - y) / rsq\n v += -(xs - x) / rsq\n\ntexture = np.random.rand(size, size).astype(np.float32)\n\n# create a kernel\nkernel_length = 31\nkernel = np.sin(np.arange(kernel_length) * np.pi / kernel_length).astype(np.float32)\n\n\nimage = lic_internal.line_integral_convolution(u, v, texture, kernel)\n\nplt.clf()\nplt.axis(\"off\")\nplt.imshow(image, cmap=\"hot\")\nplt.show()\n","sub_path":"examples/lic_demo.py","file_name":"lic_demo.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320214614","text":"from jinja2 import TemplateNotFound\n\nfrom pyog.extensions.pyog.BaseExtension import BaseExtension\nfrom pyog.util import pagination, write_to_file, logger\n\n\nclass GenArchivesBase(BaseExtension):\n __type__ = \"generator\"\n\n def load(self):\n pass\n\n def generator_archives(self, posts=None, base_page=\"archives\", tag=None, category=None, template=\"archive.html\"):\n try:\n template = self.app.jinja_env.get_template(template)\n except TemplateNotFound:\n logger.error(f\"template {template} not found, skip generator\")\n return\n if len(base_page) > 1 and base_page[0] == \"/\":\n base_page = base_page[1:]\n file_path = self.app.path.public / base_page / \"index.html\"\n if posts is None:\n posts = self.app.get_posts()\n _posts, pages = pagination(self.app, posts=posts, base_page=base_page)\n write_to_file(file_path, self.app.render(template, posts=_posts, tag=tag, category=category, pages=pages))\n max_page = pages['max']\n for page in range(2, max_page + 1):\n file_path = self.app.path.public / base_page / \"page\" / str(page) / \"index.html\"\n _posts, pages = pagination(self.app, posts=posts, current=page, base_page=base_page)\n html = self.app.render(template, posts=_posts, pages=pages, tag=tag, category=category)\n write_to_file(file_path, html)\n","sub_path":"pyog/extensions/pyog/GenArchivesBase.py","file_name":"GenArchivesBase.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59355113","text":"\nimport argparse\n\nfrom Reversi import Reversi\nfrom dqn_agent import DQNAgent\n\n\nif __name__ == \"__main__\":\n # args\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--model_path\")\n parser.add_argument(\"-s\", \"--save\", dest=\"save\", action=\"store_true\")\n parser.set_defaults(save=False)\n args = parser.parse_args()\n\n # environmet, agent\n env = Reversi()\n agent = DQNAgent(env.enable_actions, env.name, env.screen_n_rows, env.screen_n_cols)\n agent.load_model(args.model_path)\n\n # game\n print(\"------------- GAME START ---------------\")\n while not env.isEnd():\n print(\"*** userターン○ ***\")\n env.print_screen()\n enables = env.get_enables(1)\n if len(enables) > 0:\n flg = False\n while not flg:\n print(\"番号を入力してください\")\n print(enables)\n inp = input('>>> ')\n action_t = int(inp)\n for i in enables: \n if action_t == i:\n flg = True \n break\n \n env.update(action_t, 1)\n else:\n print(\"パス\")\n \n \n if env.isEnd() == True:break\n \n print(\"*** AIターン● ***\")\n env.print_screen()\n enables = env.get_enables(2)\n if len(enables) > 0:\n qvalue, action_t = agent.select_enable_action(env.screen, enables)\n print('>>> {:}'.format(action_t)) \n env.update(action_t, 2)\n else:\n print(\"パス\")\n\n\n print(\"*** ゲーム終了 ***\")\n if env.winner() == 1:\n print(\"あなたの勝ち! スコアは、{:}です。\".format(env.get_score(1)))\n else:\n print(\"あなたの負け! AIのスコアは、{:}です。\".format(env.get_score(2)))\n \n","sub_path":"Reinforcement Learning/tf-dqn-reversi-master/FightWithAI.py","file_name":"FightWithAI.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"374255454","text":"# -*- coding: utf-8 -*-\n#########################################################################\n#\n# Copyright (C) 2016 OSGeo\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n#########################################################################\n\nfrom django.utils.translation import ugettext_lazy as _\n\nALL_LANGUAGES = (\n ('abk', 'Abkhazian'),\n ('aar', 'Afar'),\n ('afr', 'Afrikaans'),\n ('amh', 'Amharic'),\n ('ara', 'Arabic'),\n ('asm', 'Assamese'),\n ('aym', 'Aymara'),\n ('aze', 'Azerbaijani'),\n ('bak', 'Bashkir'),\n ('ben', 'Bengali'),\n ('bih', 'Bihari'),\n ('bis', 'Bislama'),\n ('bre', 'Breton'),\n ('bul', 'Bulgarian'),\n ('bel', 'Byelorussian'),\n ('cat', 'Catalan'),\n ('chi', 'Chinese'),\n ('cos', 'Corsican'),\n ('dan', 'Danish'),\n ('dzo', 'Dzongkha'),\n ('eng', 'English'),\n ('fra', 'French'),\n ('epo', 'Esperanto'),\n ('est', 'Estonian'),\n ('fao', 'Faroese'),\n ('fij', 'Fijian'),\n ('fin', 'Finnish'),\n ('fry', 'Frisian'),\n ('glg', 'Gallegan'),\n ('ger', 'German'),\n ('gre', 'Greek'),\n ('kal', 'Greenlandic'),\n ('grn', 'Guarani'),\n ('guj', 'Gujarati'),\n ('hau', 'Hausa'),\n ('heb', 'Hebrew'),\n ('hin', 'Hindi'),\n ('hun', 'Hungarian'),\n ('ind', 'Indonesian'),\n ('ina', 'Interlingua (International Auxiliary language Association)'),\n ('iku', 'Inuktitut'),\n ('ipk', 'Inupiak'),\n ('ita', 'Italian'),\n ('jpn', 'Japanese'),\n ('kan', 'Kannada'),\n ('kas', 'Kashmiri'),\n ('kaz', 'Kazakh'),\n ('khm', 'Khmer'),\n ('kin', 'Kinyarwanda'),\n ('kir', 'Kirghiz'),\n ('kor', 'Korean'),\n ('kur', 'Kurdish'),\n ('oci', 'Langue d \\'Oc (post 1500)'),\n ('lao', 'Lao'),\n ('lat', 'Latin'),\n ('lav', 'Latvian'),\n ('lin', 'Lingala'),\n ('lit', 'Lithuanian'),\n ('mlg', 'Malagasy'),\n ('mlt', 'Maltese'),\n ('mar', 'Marathi'),\n ('mol', 'Moldavian'),\n ('mon', 'Mongolian'),\n ('nau', 'Nauru'),\n ('nep', 'Nepali'),\n ('nor', 'Norwegian'),\n ('ori', 'Oriya'),\n ('orm', 'Oromo'),\n ('pan', 'Panjabi'),\n ('pol', 'Polish'),\n ('por', 'Portuguese'),\n ('pus', 'Pushto'),\n ('que', 'Quechua'),\n ('roh', 'Rhaeto-Romance'),\n ('run', 'Rundi'),\n ('rus', 'Russian'),\n ('smo', 'Samoan'),\n ('sag', 'Sango'),\n ('san', 'Sanskrit'),\n ('scr', 'Serbo-Croatian'),\n ('sna', 'Shona'),\n ('snd', 'Sindhi'),\n ('sin', 'Singhalese'),\n ('ssw', 'Siswant'),\n ('slv', 'Slovenian'),\n ('som', 'Somali'),\n ('sot', 'Sotho'),\n ('spa', 'Spanish'),\n ('sun', 'Sudanese'),\n ('swa', 'Swahili'),\n ('tgl', 'Tagalog'),\n ('tgk', 'Tajik'),\n ('tam', 'Tamil'),\n ('tat', 'Tatar'),\n ('tel', 'Telugu'),\n ('tha', 'Thai'),\n ('tir', 'Tigrinya'),\n ('tog', 'Tonga (Nyasa)'),\n ('tso', 'Tsonga'),\n ('tsn', 'Tswana'),\n ('tur', 'Turkish'),\n ('tuk', 'Turkmen'),\n ('twi', 'Twi'),\n ('uig', 'Uighur'),\n ('ukr', 'Ukrainian'),\n ('urd', 'Urdu'),\n ('uzb', 'Uzbek'),\n ('vie', 'Vietnamese'),\n ('vol', 'Volapük'),\n ('wol', 'Wolof'),\n ('xho', 'Xhosa'),\n ('yid', 'Yiddish'),\n ('yor', 'Yoruba'),\n ('zha', 'Zhuang'),\n ('zul', 'Zulu'),\n)\n","sub_path":"burger/base/enumarations.py","file_name":"enumarations.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461962412","text":"import sys\nsys.stdin = open('홈.txt','r')\n\ndef p(board):\n for b in board:\n print(b)\n print('')\n\ndef sqare(sy,sx,N):\n point = []\n for dy in range(N):\n i = N-dy\n for dx in range(-i,i-1):\n if 0 <= sy+dy < Y and 0 <= sx+dx+1 < Y :\n m[sy+dy][sx+dx+1] = 1\n point.append((sy+dy,sx+dx+1))\n for dy in range(N):\n i = N-dy\n for dx in range(-i,i-1):\n if 0 <= sy-dy < Y and 0 <= sx+dx+1 < Y :\n m[sy-dy][sx+dx+1] = 1\n point.append((sy-dy,sx+dx+1))\n return point\n\nT = int(input())\nfor tc in range(1,T+1):\n Y,M = map(int,input().split())\n board = [list(map(int,input().split())) for _ in range(Y)]\n m = [[0]*Y for _ in range(Y)]\n # p(board)\n # print(sqare(5,5,3))\n # p(m)\n cost = [0,1,5,13,25]\n Max = 0\n for k in range(1,5):\n for y in range(Y):\n for x in range(Y):\n point = sqare(y,x,k)\n cnt = 0\n for ny,nx in point:\n if board[ny][nx] == 1:\n cnt += 1\n if M * cnt - cost[k] >=0:\n Max = max(Max,cnt)\n print(Max)\n \n\n\n","sub_path":"1111/홈.py","file_name":"홈.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"31102417","text":"import urllib.request\nfrom urllib import parse\n\nimport re\n\n\ndef get_html(url):\n header = {\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) '\n 'AppleWebKit/604.1.38 (KHTML, like Gecko) '\n 'Version/11.0 Mobile/15A372 Safari/604.1'\n }\n req = urllib.request.Request(url, headers=header)\n res = urllib.request.urlopen(req)\n\n # reg = re.compile('.*{background:\"url(http.*?jpg)\"', re.S)\n content = res.read().decode('gb2312', 'ignore')\n\n return content\n\n\ndef get_url(ctx):\n result = re.findall('', ctx)\n return result\n\n\nif __name__ == '__main__':\n # msg = input('请输入搜索内容: ')\n # msg = '新垣结衣'\n # search = parse.urlencode({'wd': msg})\n # referer = 'https://www.baidu.com/s?%s' % search\n referer = 'http://pic.sogou.com/pics?query=%D0%C2%D4%AB%BD%E1%D2%C2&p=40230500&st=255&mode=255&policyType=1'\n # data = main(referer)\n # print(get_url(data))\n print(get_html(referer))\n","sub_path":"reptilian/day01/s_prctice.py","file_name":"s_prctice.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"634774978","text":"#!/usr/bin/env python3\nfrom sys import argv\nfrom math import pi\n\n\ndef calc_distance(c1, c2):\n dist = ((c1[0] - c2[0])**2 + (c1[1] - c2[1])**2)**0.5\n rotation_dist = abs(c1[2] - c2[2]) % pi\n rotation_dist = min(rotation_dist, pi - rotation_dist)\n return (dist, rotation_dist)\n\n\ndef calc_path_dist(coords):\n prev = coords[0]\n dist = (0, 0)\n for coord in coords[1:]:\n d, r = calc_distance(prev, coord)\n dist = dist[0] + d, dist[1] + r\n prev = coord\n return dist\n\nif __name__ == \"__main__\":\n if len(argv) != 2:\n print(\"Usage: ./dist_calculator.py \")\n with open(argv[1]) as f:\n lines = f.readlines()\n coords = [[float(c) for c in line.split(\" \")] for line in lines]\n c = calc_path_dist(coords)\n print(\"Distance: \" + str(c[0]))\n print(\"Total rotation (radians): \" + str(c[1]))","sub_path":"labb5/distance_calc.py","file_name":"distance_calc.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"21879632","text":"from uuid import UUID\n\nimport pytest\n\nfrom citrine.resources.process_spec import ProcessSpecCollection\nfrom tests.resources.test_data_concepts import run_noop_gemd_relation_search_test\nfrom tests.utils.session import FakeSession\n\n\n@pytest.fixture\ndef session() -> FakeSession:\n return FakeSession()\n\n\n@pytest.fixture\ndef collection(session) -> ProcessSpecCollection:\n return ProcessSpecCollection(\n project_id=UUID('6b608f78-e341-422c-8076-35adc8828545'),\n dataset_id=UUID('8da51e93-8b55-4dd3-8489-af8f65d4ad9a'),\n session=session)\n\n\ndef test_list_by_template(collection: ProcessSpecCollection):\n run_noop_gemd_relation_search_test(\n search_for='process-specs',\n search_with='process-templates',\n collection=collection,\n search_fn=collection.list_by_template,\n )\n","sub_path":"tests/resources/test_process_spec.py","file_name":"test_process_spec.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"43657763","text":"import sys, pygame\nimport random\nfrom pygame.locals import *\n\npygame.init()\n\nplayer = pygame.image.load(\"M:/groupPy/img/player.png\")\nbackground = pygame.image.load(\"M:/groupPy/img/background.png\")\n\nplayerRect = player.get_rect()\nbackgroundRect = background.get_rect()\n\nsize = (width, height) = background.get_size()\nscreen = pygame.display.set_mode(size)\n\nb3x = 200\nb3y = 750\nmovex = 3\nmovey = 0\n\nleft = False\nright = False\n\nwhile 1:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT: sys.exit()\n\t\t\n\t\tif event.type == pygame.KEYDOWN:\n\t\t\tif event.key == K_LEFT:\n\t\t\t\tleft = True\n\t\t\tif event.key == K_RIGHT:\n\t\t\t\tright = True\n\t\t\t\t\n\t\tif event.type == pygame.KEYUP:\n\t\t\tif event.key==pygame.K_LEFT:\n\t\t\t\tleft = False\n\t\t\tif event.key==pygame.K_RIGHT:\n\t\t\t\tright = False\n\t\n\tif b3x + movex < 0:\n\t\tleft = False\n\t\t\n\tif b3x + playerRect.width + movex > backgroundRect.width:\n\t\tright = False\n\t\n\tif right == True:\n\t\tb3x += movex\n\t\t\n\tif left == True:\n\t\tb3x -= movex\n\t\n\tscreen.blit(background, backgroundRect)\n\tscreen.blit(player,(b3x,b3y))\n\t\n\tpygame.display.flip()","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"321959874","text":"\nfrom __future__ import print_function\nimport numpy\nimport numpy.ctypeslib\nfrom numpy import log,interp,array,power,exp,pi,sqrt,zeros,max,min;\nimport ctypes as ct\n\n\ndef Weibull(x,shape,scale):\n\n k = shape;\n l = scale;\n\n arr = numpy.zeros(x.shape);\n arr[x>0] = k/l*power((x/l),k-1)*exp(-power(x/l,k));\n return arr;\n\n\ndef convertWind(onshoreconf,offshoreconf,windspeed10m,windspeed100m,onshoremap):\n\n \n result = numpy.zeros_like(windspeed10m);\n \n # C expects contigous arrays. Numpy does not guarantee this.\n windspeed10m = numpy.ascontiguousarray(windspeed10m,dtype=numpy.double);\n windspeed100m = numpy.ascontiguousarray(windspeed100m,dtype=numpy.double);\n onshoremap = numpy.ascontiguousarray(onshoremap,dtype=numpy.bool);\n\n dim = windspeed10m.shape;\n\n doublearray = numpy.ctypeslib.ndpointer(dtype=numpy.double,ndim=2,shape=windspeed10m.shape);\n boolarray = numpy.ctypeslib.ndpointer(dtype=numpy.bool,ndim=2,shape=windspeed10m.shape);\n onarray = numpy.ctypeslib.ndpointer(dtype=numpy.double,ndim=1,shape=(len(onshoreconf['POW']),));\n offarray = numpy.ctypeslib.ndpointer(dtype=numpy.double,ndim=1,shape=(len(offshoreconf['POW']),));\n size_t = ct.c_size_t;\n dbl = ct.c_double;\n\n windloop = ct.cdll.LoadLibrary(\"./windloop2.so\");\n\n windloop.argtypes = [size_t,size_t, doublearray, doublearray,\n boolarray,dbl,\n dbl,size_t,onarray,onarray,size_t,offarray,offarray,doublearray];\n windloop.windLoop(ct.c_size_t(dim[0]),ct.c_size_t(dim[1]),windspeed10m.ctypes,windspeed100m.ctypes,\n onshoremap.ctypes,ct.c_double(onshoreconf['H']),ct.c_double(offshoreconf['H']),\n ct.c_size_t(len(onshoreconf['POW'])), numpy.array(onshoreconf['V']).ctypes,\n numpy.array(onshoreconf['POW']).ctypes,\n ct.c_size_t(len(offshoreconf['V'])),numpy.array(offshoreconf['V']).ctypes,\n numpy.array(offshoreconf['POW']).ctypes,\n result.ctypes);\n\n return result;\n\n# Bypass all that. Call the C routine instead.\n\n # Get wind speed at hub height\n \n onhubHeight = onshoreconf['H'];\n offhubHeight = offshoreconf['H'];\n\n # BIG FAT WARNING: The following assumes neutral stability,\n # a condition that is only achieved during mid day.\n\n \n roughness[roughness<=0.0] = 0.0002; # From wikipedia...\n # probably happens at the poles, should be investigated\n\n d = 2.0/3.0*roughness;\n k = windspeed / log((10 - d)/roughness);\n\n onspeedAtHubHeight = zeros(windspeed.shape);\n offspeedAtHubHeight = zeros(windspeed.shape);\n\n onm = onshoremap;\n offm = numpy.logical_not(onshoremap);\n\n onspeedAtHubHeight[onm] = k[onm]*log((onhubHeight - d[onm])/roughness[onm]);\n offspeedAtHubHeight[offm] = k[offm]*log((offhubHeight - d[offm])/roughness[offm]);\n\n # Get Weibull distribution of wind speeds at hub height\n # The found speed is used as the average of the distribution.\n # For now, the shape parameter is held fixed at 2,\n # so we get a Rayleigh distribution.\n \n maxpoints = max((onshoreconf['V'][-1], offshoreconf['V'][-1]));\n\n vs = numpy.arange(0,maxpoints,1);\n\n onV = onshoreconf['V'];\n onPOW = onshoreconf['POW'];\n onshorepowercurve = interp(vs,onV,onPOW);\n\n offV = offshoreconf['V'];\n offPOW = offshoreconf['POW'];\n offshorepowercurve = interp(vs,offV,offPOW);\n\n # Generate Weibull distribution\n shape = 2.0; # A rough guess. The mean is scale * Gamma(1+1/shape)\n # Gamma(3/2) = 1/2 sqrt(pi)\n # The mean is taken to be the speed at hub height\n gamma32 = 1.0/2.0*sqrt(pi)\n onscale = onspeedAtHubHeight / gamma32;\n offscale = offspeedAtHubHeight / gamma32;\n \n # Loop over all grid cells, apply a smoothed power curve\n # to data point and fill out result array.\n # This turns out to be difficult to express in numpy,\n # so if the loop is too slow, it will have to be rewritten in C.\n\n maxi = windspeed.shape[0];\n maxj = windspeed.shape[1];\n result = numpy.zeros(windspeed.shape);\n\n for i in xrange(maxi):\n for j in xrange(maxj):\n if (onshoremap[i][j]):\n powercurve = onshorepowercurve;\n hubscale = onscale[i][j];\n v = onspeedAtHubHeight[i][j];\n else:\n powercurve = offshorepowercurve;\n hubscale = offscale[i][j];\n v = offspeedAtHubHeight[i][j];\n \n # Only need to take into account weibull distribution restricted\n # to the support of the power curve, since the integral\n # elsewhere will be zero. That's wrong..\n \n distribution = Weibull(vs,shape,hubscale);\n \n # It's probably a bit inefficient to calculate the entire\n # convolution, as you need at most two points to do the\n # linear interpolation to get the value at the point you're\n # interested in....\n # If this is ever rewritten in C, might aswell optimize that.\n \n smoothedPowerCurve = numpy.convolve(powercurve,distribution,mode='same');\n result[i][j] = (numpy.interp([v],vs,smoothedPowerCurve))[0];\n\n \n return result;\n\n\n\n","sub_path":"Scripts/Convert_Forecasts/windconversionfunctions2.py","file_name":"windconversionfunctions2.py","file_ext":"py","file_size_in_byte":5387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"419876026","text":"from collections import deque\n\n# 루트가 갈라질 수 있으므로 해당 루트의 move를 가지고 이동한다.\ndef bfs(start, maps):\n q = deque()\n q.append(start)\n direction = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n \n while q:\n y, x, move = q.popleft()\n maps[y][x] = 0\n for dy, dx in direction:\n ny = y + dy\n nx = x + dx\n # 가장 먼저 도착한 경우가 최단 거리\n # 현재 위치에서 다음위치로 이동했을 때 목적지이면, 지금까지의 move+1 반환\n if ny == len(maps)-1 and nx == len(maps[0])-1:\n return move+1\n \n if 0 <= ny < len(maps) and 0 <= nx < len(maps[0]) and maps[ny][nx] == 1:\n maps[ny][nx] = 0\n q.append((ny, nx, move+1))\n return -1\n\ndef solution(maps):\n return bfs((0, 0, 1), maps)","sub_path":"algorithm_study/gamemap_solution.py","file_name":"gamemap_solution.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"637217834","text":"#!/usr/bin/env python3\n\"\"\" Amazon SageMaker Debugger is an offering from AWS which helps you automate the debugging of machine learning training jobs.\nThis library powers Amazon SageMaker Debugger, and helps you develop better, faster and cheaper models by catching common errors quickly.\nIt allows you to save tensors from training jobs and makes these tensors available for analysis, all through a flexible and powerful API.\nIt supports TensorFlow, PyTorch, MXNet, and XGBoost on Python 3.6+.\n- Zero Script Change experience on SageMaker when using supported versions of SageMaker Framework containers or AWS Deep Learning containers\n- Full visibility into any tensor which is part of the training process\n- Real-time training job monitoring through Rules\n- Automated anomaly detection and state assertions\n- Interactive exploration of saved tensors\n- Distributed training support\n- TensorBoard support\n\n\"\"\"\n# Standard Library\nimport contextlib\nimport os\nimport sys\nfrom datetime import date\n\n# Third Party\nimport compile_protobuf\nimport setuptools\n\n# First Party\nimport smdebug\n\nDOCLINES = (__doc__ or \"\").split(\"\\n\")\nFRAMEWORKS = [\"tensorflow\", \"pytorch\", \"mxnet\", \"xgboost\"]\nTESTS_PACKAGES = [\"pytest\", \"torchvision\", \"pandas\"]\nINSTALL_REQUIRES = [\"protobuf>=3.6.0\", \"numpy\", \"packaging\", \"boto3>=1.10.32\"]\n\n\n@contextlib.contextmanager\ndef remember_cwd():\n \"\"\"\n Restore current directory when exiting context\n \"\"\"\n curdir = os.getcwd()\n try:\n yield\n finally:\n os.chdir(curdir)\n\n\ndef scan_git_secrets():\n from subprocess import check_call\n import os\n import tempfile\n import shutil\n\n if os.path.exists(\".git/hooks/pre-commit\"):\n print(\"git secrets: pre-commit hook already present\")\n return\n\n if shutil.which(\"git-secrets\"):\n check_call([\"git\", \"secrets\", \"--scan\"])\n print(\"scanned for git secrets\")\n\n else:\n with tempfile.TemporaryDirectory(prefix=\"git_secrets_\") as tmpdir:\n check_call([\"git\", \"clone\", \"https://github.com/awslabs/git-secrets.git\", tmpdir])\n check_call([os.path.join(tmpdir, \"git-secrets\"), \"--scan\"])\n print(\"scanned for git secrets\")\n\n\ndef build_package(version):\n compile_protobuf.compile_protobuf()\n packages = setuptools.find_packages(include=[\"smdebug\", \"smdebug.*\"])\n setuptools.setup(\n name=\"smdebug\",\n version=version,\n long_description=\"\\n\".join(DOCLINES[1:]),\n long_description_content_type=\"text/markdown\",\n author=\"AWS DeepLearning Team\",\n description=DOCLINES[0],\n url=\"https://github.com/awslabs/sagemaker-debugger\",\n packages=packages,\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3 :: Only\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=INSTALL_REQUIRES,\n setup_requires=[\"pytest-runner\"],\n tests_require=TESTS_PACKAGES,\n python_requires=\">=3.6\",\n license=\"Apache License Version 2.0\",\n )\n\n\ndef detect_smdebug_version():\n if \"--release\" in sys.argv:\n sys.argv.remove(\"--release\")\n return smdebug.__version__.strip()\n\n return smdebug.__version__.strip() + \"b\" + str(date.today()).replace(\"-\", \"\")\n\n\nversion = detect_smdebug_version()\nscan_git_secrets()\nbuild_package(version=version)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"106203812","text":"############################\n# Problem 1: Python Configuration and Data Loading\n############################\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn import svm\nfrom scipy import io\n\n# if sys.version_info[0] < 3:\n# \traise Exception(\"Python 3 not detected.\")\n# for data_name in [\"mnist\", \"spam\", \"cifar10\"]:\n# \tdata = io.loadmat(\"data/%s_data.mat\" % data_name)\n# \tprint(\"\\nloaded %s data!\" % data_name)\n# \tfields = \"test_data\", \"training_data\", \"training_labels\"\n# \tfor field in fields:\n# \t\tprint(field, data[field].shape)\n\n\n\n############################\n# Problem 2: Data Partitioning\n############################\n\n\n# a. For the MNIST dataset, write code that sets aside 10,000\n# training images as a validation set.\ndata = io.loadmat(\"data/mnist_data.mat\")\ntraining_data = data[\"training_data\"]\ntraining_labels = data[\"training_labels\"]\nax_train, ax_val, ay_train, ay_val = sklearn.model_selection.train_test_split(\n training_data, training_labels, test_size=10000, shuffle=True)\nprint(\"\\nsplited mnist data!\")\nprint(\"ax_train:\", ax_train.shape, \" ax_val:\", ax_val.shape)\nprint(\"ay_train:\", ay_train.shape, \" ay_val:\", ay_val.shape)\n\n\n# b. For the spam dataset, write code that sets aside 20% of the\n# training data as a validation set.\ndata = io.loadmat(\"data/spam_data.mat\")\ntraining_data = data[\"training_data\"]\ntraining_labels = data[\"training_labels\"]\nbx_train, bx_val, by_train, by_val = sklearn.model_selection.train_test_split(\n training_data, training_labels, test_size=0.2, shuffle=True)\nprint(\"\\nsplited spam data!\")\nprint(\"bx_train:\", bx_train.shape, \" bx_val:\", bx_val.shape)\nprint(\"by_train:\", by_train.shape, \" by_val:\", by_val.shape)\n\n\n# c. For the CIFAR-10 dataset, write code that sets aside 5,000\n# training images as a validation set.\ndata = io.loadmat(\"data/cifar10_data.mat\")\ntraining_data = data[\"training_data\"]\ntraining_labels = data[\"training_labels\"]\ncx_train, cx_val, cy_train, cy_val = sklearn.model_selection.train_test_split(\n training_data, training_labels, test_size=5000, shuffle=True)\nprint(\"\\nsplited cifar10 data!\")\nprint(\"cx_train:\", cx_train.shape, \" cx_val:\", cx_val.shape)\nprint(\"cy_train:\", cy_train.shape, \" cy_val:\", cy_val.shape)\n\n\n\n############################\n# Problem 3: Support Vector Machines\n############################\n\n\n# (a) For the MNIST dataset, use raw pixels as features. Train your\n# model with the following numbers of training examples:\n# 100, 200, 500, 1000, 2000, 5000, 10000.\nnums = [100, 200, 500, 1000, 2000, 5000, 10000]\nmodel = svm.LinearSVC()\nat_score, av_score = [], []\nfor i in nums:\n model.fit(ax_train[:i], ay_train[:i].ravel())\n t_pred = model.predict(ax_train[:i])\n v_pred = model.predict(ax_val)\n at_score.append(sklearn.metrics.accuracy_score(ay_train[:i], t_pred))\n av_score.append(sklearn.metrics.accuracy_score(ay_val, v_pred))\n\nplt.plot(nums, at_score, 'ro', label=\"training\")\nplt.plot(nums, av_score, 'yo', label=\"validation\")\nplt.xlabel('numbers of training examples')\nplt.ylabel('accuracy_score')\nplt.title('MNIST dataset SVM')\nplt.legend()\nplt.savefig('figure_2a.png')\nplt.close()\n\n\n# (b) For the spam dataset, use the provided word frequencies as\n# features. Train your model with the following numbers of training\n# examples: 100, 200, 500, 1,000, 2,000, ALL.\nnums = [100, 200, 500, 1000, 2000, len(by_train)]\nmodel = svm.LinearSVC(max_iter=5000)\nbt_score, bv_score = [], []\nfor i in nums:\n model.fit(bx_train[:i], by_train[:i].ravel())\n t_pred = model.predict(bx_train[:i])\n v_pred = model.predict(bx_val)\n bt_score.append(sklearn.metrics.accuracy_score(by_train[:i], t_pred))\n bv_score.append(sklearn.metrics.accuracy_score(by_val, v_pred))\n\nplt.plot(nums, bt_score, 'ro', label=\"training\")\nplt.plot(nums, bv_score, 'yo', label=\"validation\")\nplt.xlabel('numbers of training examples')\nplt.ylabel('accuracy_score')\nplt.title('spam dataset SVM')\nplt.legend()\nplt.savefig('figure_2b.png')\nplt.close()\n\n\n# (c) For the CIFAR-10 dataset, use raw pixels as features. Train your model\n# with the following numbers of training examples: 100, 200, 500, 1000,\n# 2000, 5000.\nnums = [100, 200, 500, 1000, 2000, 5000]\nmodel = svm.LinearSVC()\nct_score, cv_score = [], []\nfor i in nums:\n model.fit(cx_train[:i], cy_train[:i].ravel())\n t_pred = model.predict(cx_train[:i])\n v_pred = model.predict(cx_val)\n ct_score.append(sklearn.metrics.accuracy_score(cy_train[:i], t_pred))\n cv_score.append(sklearn.metrics.accuracy_score(cy_val, v_pred))\n\nplt.plot(nums, ct_score, 'ro', label=\"training\")\nplt.plot(nums, cv_score, 'yo', label=\"validation\")\nplt.xlabel('numbers of training examples')\nplt.ylabel('accuracy_score')\nplt.title('CIFAR-10 dataset SVM')\nplt.legend()\nplt.savefig('figure_2c.png')\nplt.close()\n\n\n\n############################\n# Problem 4: Hyper-parameter Tuning\n############################\n\n\n# (a) For the MNIST dataset, find the best C value.\nC = [0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1]\nav_score = []\nfor param in C:\n model = svm.LinearSVC(C=param)\n model.fit(ax_train[:10000], ay_train[:10000].ravel())\n v_pred = model.predict(ax_val)\n av_score.append(sklearn.metrics.accuracy_score(ay_val, v_pred))\n\nprint(\"accuracies:\", av_score)\nplt.plot(C, av_score, 'yo')\nplt.xscale('log')\nplt.xlabel('C values')\nplt.ylabel('accuracy_score')\nplt.title('MNIST dataset SVM')\n# plt.show()\nplt.savefig('figure_4.png')\nplt.close()\n\n\n\n############################\n# Problem 5: K-Fold Cross-Validation\n############################\n\n\n# (a) For the spam dataset, use 5-fold cross-validation to find\n# and report the best C value.\n\n# 1. Partition data into K folds\nK = 5\nval_xset, val_yset = [bx_val], [by_val]\nfor i in range(K - 2):\n bx_train, bx_val, by_train, by_val = sklearn.model_selection.\\\n train_test_split(bx_train, by_train, test_size=len(val_xset[0]), shuffle=True)\n val_xset.append(bx_val)\n val_yset.append(by_val)\nval_xset.append(bx_train)\nval_yset.append(by_train)\n\n# 2. Train with different C values\n# C = [0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1]\nC = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]\nbv_score = [0] * len(C)\nfor i in range(K):\n temp_x, temp_y = val_xset[:i] + val_xset[i + 1:], val_yset[:i] + val_yset[i + 1:]\n temp_x_train = np.concatenate((temp_x[0], temp_x[1], temp_x[2], temp_x[3]), axis=0)\n temp_y_train = np.concatenate((temp_y[0], temp_y[1], temp_y[2], temp_y[3]), axis=0)\n for j in range(len(C)):\n model = svm.LinearSVC(C=C[j])\n model.fit(temp_x_train, temp_y_train.ravel())\n v_pred = model.predict(val_xset[i])\n bv_score[j] += sklearn.metrics.accuracy_score(val_yset[i], v_pred)\nbv_score = [i/5 for i in bv_score]\n\n# 3. Plot the graph\nprint(\"accuracies:\", bv_score)\nplt.plot(C, bv_score, 'yo')\n# plt.xscale('log')\nplt.xlabel('C values')\nplt.ylabel('accuracy_score')\nplt.title('spam dataset K-Fold Cross-Validation')\n# plt.show()\nplt.savefig('figure_5.png')\nplt.close()\n\n\n\n############################\n# Problem 6: Kaggle\n############################\n\n\nimport save_csv\n\n# (a) For the MNIST dataset, use C=10^-6.\nmodel = svm.LinearSVC(C=0.000001)\nmodel.fit(training_data, training_labels.ravel())\nsave_csv.results_to_csv(model.predict(data[\"test_data\"]))\n\n# (b) For the spam dataset, use C=14\nmodel = svm.LinearSVC(C=14)\nmodel.fit(training_data, training_labels.ravel())\nsave_csv.results_to_csv(model.predict(data[\"test_data\"]))\n\n# (c) For the cifar10 dataset\nmodel = svm.LinearSVC()\nmodel.fit(training_data, training_labels.ravel())\nsave_csv.results_to_csv(model.predict(data[\"test_data\"]))\n","sub_path":"hw/hw1/code_chen.py","file_name":"code_chen.py","file_ext":"py","file_size_in_byte":7667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"66469745","text":"'''\nUses a graph-file as input and creates a Graph-Object out of Vertex and Edge Objects\n'''\nfrom vertex import Vertex\nfrom edge import Edge\nfrom graph import Graph\nfrom mendeleev import element\n\n\ndef parse(filename):\n\n # Properties of the graph. Characterized in the first block of a graph-file\n n_of_nodes = 0\n n_of_edges = 0\n nodes_label = False\n edges_label = False\n directed_graph = False\n\n # Vertex list is characterized in the 2nd block of a graph-file\n vertex_list = []\n\n # Edge list is characterized in the 3rd block of a graph-file\n edge_list = []\n\n # c is a counter to know in which block of the graph-file we are\n c = 0\n\n # dict für das Zugreifen auf die Vertices über ihre Namen\n vertex_dict = {}\n with open(filename, 'r') as file:\n file_content = file.readlines()\n for i in range(0, len(file_content)):\n temp = file_content[i].replace('\\n', '').split(';')\n if temp == ['']:\n c += 1\n elif temp != '' and c == 0:\n if temp[0] == '#nodes':\n n_of_nodes = temp[1]\n elif temp[0] == '#edges':\n n_of_edges = temp[1]\n elif temp[0] == 'Nodes labelled':\n if temp[1] == 'True':\n nodes_label = True\n else:\n nodes_label = False\n elif temp[0] == 'Edges labelled':\n if temp[1] == 'True':\n edges_label = True\n else:\n edges_label = False\n elif temp[0] == 'Directed graph':\n if temp[1] == 'True':\n directed_graph = True\n else:\n directed_graph = False\n elif c == 1:\n v = Vertex(temp[0])\n if nodes_label:\n v.set_node_label(temp[1])\n vertex_list.append(v)\n vertex_dict.update({v.name: v}) # Vertex wird für Edges-Initialiserung gespeichert (Name=Key)\n elif c == 2:\n e = Edge(vertex_dict.get(temp[0]), vertex_dict.get(temp[1]), None, None, directed_graph)\n if edges_label:\n e.set_label(temp[2])\n edge_list.append(e)\n\n graph = Graph(vertex_list, edge_list, n_of_nodes, n_of_edges, nodes_label, edges_label, directed_graph)\n return graph\n\n\ndef reverse_parser(g):\n '''\n :param g: Graph Object\n :return: .graph text\n USAGE run in terminal: python3 main.py >> newgraph.graph\n '''\n number_of_vertices = len(g.vertices)\n number_of_edges = len(g.edges)\n labelled_vertices = g.vertices_labelled\n labelled_edges = g.edges_labelled\n directed_graph = g.directed_graph\n\n Block2 = []\n Block3 = []\n\n # if-function is necessary because graph-Objects which were randomly created don't have labels\n if labelled_vertices != None:\n\n for vertex in g.vertices:\n if vertex.label != None:\n Block2.append(str(vertex.name)+';'+str(vertex.label))\n else:\n Block2.append(str(vertex.name)+';')\n\n for edge in g.edges:\n if edge.label != None:\n Block3.append(str(edge.vertex_a.name)+';'+str(edge.vertex_b.name)+';'+str(edge.label))\n else:\n Block3.append(str(edge.vertex_a.name)+';'+str(edge.vertex_b.name))\n\n else:\n\n labelled_vertices = False\n labelled_edges = False\n directed_graph = False\n\n for vertex in g.vertices:\n Block2.append(str(vertex.name) + ';')\n\n for edge in g.edges:\n Block3.append(str(edge.vertex_a.name) + ';' + str(edge.vertex_b.name))\n\n print('#nodes;',number_of_vertices,'\\n',\\\n '#edges;',number_of_edges,'\\n',\\\n 'Nodes labelled;',labelled_vertices,'\\n',\\\n 'Edges labelled;', labelled_edges,'\\n',\\\n 'Directed graph;',directed_graph,'\\n', sep='')\n\n for word in Block2:\n print(word)\n print()\n for word in Block3:\n print(word)\n\n\n\ndef parse_chem(filename):\n # Properties of the graph. Characterized in the first block of a graph-file\n n_of_nodes = 0\n n_of_edges = 0\n nodes_label = True\n edges_label = True\n directed_graph = False\n\n #Booleans to check in which part of the Chem-Graph we are\n into_vertices = False\n into_vertex_labels = False\n into_edges_one = False\n into_edges_two = False\n into_edges_label = False\n\n #Lists to save all vertices, edges and teh respective labels to then create the graph-object from\n vertices_all = []\n vertex_labels_all = []\n edges_one_all = []\n edges_two_all = []\n edges_labels_all = []\n\n\n # Vertex list is characterized in the 2nd block of a graph-file\n vertex_list = []\n\n # Edge list is characterized in the 3rd block of a graph-file\n edge_list = []\n\n # dict for accessing the vertices via their names\n vertex_dict = {}\n\n with open(filename, 'r') as file:\n file_content = file.readlines()\n for i in range(0, len(file_content)):\n temp: str = file_content[i].replace('\\n', '')\n temp = temp.replace(' ', '')\n #finish reading the file after the important first few blocks\n if temp == '\"coords\":[':\n break\n if temp == '\"aid\":[':\n into_vertices = True\n elif temp == '\"element\":[':\n into_vertex_labels = True\n elif temp == '\"aid1\":[':\n into_edges_one = True\n elif temp == '\"aid2\":[':\n into_edges_two = True\n elif temp == '\"order\":[':\n into_edges_label = True\n elif temp == '],' and into_edges_one:\n into_edges_one = False\n elif temp == '],' and into_edges_two:\n into_edges_two = False\n elif temp == ']' and into_edges_label:\n into_edges_label = False\n elif into_vertices and temp == '],':\n into_vertices = False\n elif into_vertex_labels and temp == ']':\n into_vertex_labels = False\n elif into_vertices:\n temp2 = temp.split(',')\n vertices_all.append(temp2[0])\n elif into_vertex_labels:\n temp2 = temp.split(',')\n vertex_labels_all.append(temp2[0])\n elif into_edges_one:\n temp2 = temp.split(',')\n edges_one_all.append(temp2[0])\n elif into_edges_two:\n temp2 = temp.split(',')\n edges_two_all.append(temp2[0])\n elif into_edges_label:\n temp2 = temp.split(',')\n edges_labels_all.append(temp2[0])\n # creating graph-object after finishing reading the file\n for i in range(0,len(vertices_all)):\n v = Vertex(vertices_all[i])\n e = element(int(vertex_labels_all[i]))\n v.set_node_label(e.symbol)\n vertex_list.append(v)\n vertex_dict.update({v.name: v})\n\n for i in range(0,len(edges_one_all)):\n e = Edge(vertex_dict.get(edges_one_all[i]), vertex_dict.get(edges_two_all[i]))\n e.set_label(edges_labels_all[i])\n edge_list.append(e)\n\n n_of_nodes = len(vertices_all)\n n_of_edges = len(edges_one_all)\n\n\n graph = Graph(vertex_list, edge_list, n_of_nodes, n_of_edges, nodes_label, edges_label, directed_graph)\n return graph\n\n","sub_path":"trier/showGraph/parser2.py","file_name":"parser2.py","file_ext":"py","file_size_in_byte":7573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"424276429","text":"\"\"\"\nThuật toán selection sort\n\"\"\"\nimport random as rd\nimport time\ndef SelectionSort(key):\n n = len(key)\n for i in range(n-1):\n k = i\n for j in range(i+1 ,n):\n if(key[k] > key[j]):\n k = j\n if (k!= i):\n key[i], key[k] = key[k] , key[i]\n\n\"\"\"\nTest\n\"\"\"\nsample = rd.sample(range(10000),10000)\nprint(\"Before: \", sample)\nstart = time.time()\nSelectionSort(sample)\nend = time.time()\nprint(\"After: \", sample)\nprint('Thời gian chạy là : ' , end - start)","sub_path":"Sorting_Algorithms/SelectionSort.py","file_name":"SelectionSort.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"140639939","text":"import theano\nfrom theano import tensor\nfrom theano.tensor.opt import register_canonicalize\nfrom theano.tensor.opt import register_specialize\nfrom theano.tensor.blas import local_optimizer\n\nfrom theano.tensor.basic import get_scalar_constant_value\nfrom theano.tensor.basic import NotScalarConstantError\n\nfrom logpy import (\n eq,\n conde,\n run,\n var,\n membero\n )\nfrom logpy.core import (\n lall as logical_all,\n EarlyGoalError,\n )\n\nfrom logpy.unify import(\n register_unify_object,\n register_unify_object_attrs,\n reify,\n reify_dispatch,\n reify_generator,\n reify_object,\n unify_dispatch,\n unify_object,\n unify_object_attrs,\n unify,\n )\n\n# XXX need context manager to get rid of this\nif 1: # DEBUGGING W OPS BUILT WITH RAW_INIT\n theano.gof.Apply.__repr__ = object.__repr__\n theano.gof.Apply.__str__ = object.__str__\n\nregister_unify_object_attrs(theano.Apply, ['op', 'inputs', 'outputs'])\nregister_unify_object_attrs(tensor.IncSubtensor, [\n 'idx_list', 'inplace', 'set_instead_of_inc',\n 'destroyhandler_tolerate_aliased'])\n\n\n\ndef raw_init(cls, **kwargs):\n rval = object.__new__(cls)\n rval.__dict__.update(kwargs)\n return rval\n\ndef match_shape_i(shape_of, x, i, shp_i):\n def goal_shape(s):\n # figure out how to call reify and unify here\n # to make it a proper goal\n if hasattr(x, 'token'):\n x_ = s[x]\n else:\n x_ = x\n if hasattr(i, 'token'):\n i_ = s[i]\n else:\n i_ = i\n if hasattr(shp_i, 'token'):\n shp_i_ = s[shp_i]\n else:\n shp_i_ = shp_i\n try:\n zval = int(get_scalar_constant_value(shape_of[x_][i_]))\n except NotScalarConstantError:\n return []\n if zval == shp_i_:\n return [s]\n return []\n return goal_shape\n\n@register_specialize\n@register_canonicalize\n@local_optimizer()\ndef logpy_cut_whole_incsubtensor(node):\n if not isinstance(node.op, tensor.IncSubtensor):\n return\n # -- declare some wild variables\n w = dict((name, var(name)) for name in [\n 'start', 'stop', 'step', 'set_instead_of_inc', 'inplace', 'dta',\n 'in_x', 'in_inc', 'outputs', 'rval',\n ])\n\n shape_of = node.fgraph.shape_feature.shape_of\n\n # -- use them in a pattern\n matches = run(0, w,\n logical_all(\n eq(\n node,\n raw_init(theano.Apply,\n op=raw_init(tensor.IncSubtensor,\n idx_list=[slice(0, w['stop'], w['step'])],\n inplace=w['inplace'],\n set_instead_of_inc=w['set_instead_of_inc'],\n destroyhandler_tolerate_aliased=w['dta']),\n inputs=[w['in_x'], w['in_inc']],\n outputs=w['outputs'])\n ),\n membero(w['step'], (1, None)),\n match_shape_i(shape_of, w['in_x'], 0, w['stop']),\n conde(\n [\n eq(w['set_instead_of_inc'], True),\n eq(w['rval'], (tensor.add, w['in_inc']))],\n [\n eq(w['set_instead_of_inc'], False),\n eq(w['rval'], (tensor.add, w['in_x'], w['in_inc']))]\n ),\n )\n )\n if matches:\n return [matches[0]['rval'][0](*matches[0]['rval'][1:])]\n","sub_path":"theano_workspace/logpy_opt.py","file_name":"logpy_opt.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410832832","text":"\"\"\" messageme.core.lib.hiddenURLs\n\n This module provides support for \"hidden URLs\" that link back to a user and\n optionally a topic. These can be used to hide the user's identity.\n\"\"\"\nimport random\nimport string\n\nfrom messageme.core.models import HiddenURL\nfrom messageme.core.lib import shortener\n\n#############################################################################\n\ndef generate(user, topic=None):\n \"\"\" Generate a new hidden URL for the given user and optionally a topic.\n\n We create a new HiddenURL record for the given user/topic. Upon\n completion, we return the newly-generated URL.\n \"\"\"\n # Create the initial HiddenURL record, with no URL.\n\n hiddenURL = HiddenURL()\n hiddenURL.url = None # initially.\n hiddenURL.user = user\n hiddenURL.topic = topic\n hiddenURL.save()\n\n # Now calculate the URL for this record, based on the record's ID.\n\n hiddenURL.url = shortener.encode(hiddenURL.id)\n hiddenURL.save()\n\n # Finally, return the URL back to the caller.\n\n return hiddenURL.url\n\n#############################################################################\n\ndef remove(user, topic=None):\n \"\"\" Remove the hidden URLs for the given user and optional topic.\n\n If a topic is supplied, all the hidden URLs for that topic and user\n will be removed. Otherwise, all the hidden URLs for the given user\n will be removed.\n \"\"\"\n if topic == None:\n HiddenURL.objects.filter(user=user).delete()\n else:\n HiddenURL.objects.filter(user=user, topic=topic).delete()\n\n#############################################################################\n\ndef search(url):\n \"\"\" See if the given URL matches one of our hidden URLs.\n\n If the given URL is one of our hidden URLs, we return a (user, topic)\n tuple, where 'user' is the user associated with that URL, and 'topic'\n is the Topic associated with that URL, or None if the URL isn't\n associated with a topic.\n\n If the given URL is not known, we return (None, None).\n \"\"\"\n try:\n hiddenURL = HiddenURL.objects.get(url=url)\n except HiddenURL.DoesNotExist:\n return (None, None)\n\n return (hiddenURL.user, hiddenURL.topic)\n\n","sub_path":"messageme/core/lib/hiddenURLs.py","file_name":"hiddenURLs.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"196505483","text":"import os\n\ntotal=0\n\n# 统计一个文件里一个字符串的数量\ndef count(file,s):\n\tf=open(file)\n\ts1=f.read()\n\tf.close()\n\tcnt=0\n\tidx=0\n\tnext_idx=0\n\twhile True:\n\t\tidx=s1.find(s,next_idx)\n\t\tif idx==-1:\n\t\t\tbreak\n\t\tcnt+=1\n\t\tnext_idx=idx+len(s)\n\treturn cnt\n\ndef getFile(s):\n\tglobal total\n\tfirst_dir='data'\n\tdirs=[]\n\n\tfor r, d, l in os.walk(first_dir):\n\t\tdirs.append(d)\n\n\tfor second_dir in dirs[0]:\n\t\ttmp=[]\n\t\tfor r,d,l in os.walk(first_dir+'/'+second_dir):\n\t\t\ttmp.append(d)\n\t\tfor third_dir in tmp[0]:\n\t\t\tif third_dir[0]=='o' and third_dir[-1]>='1' and third_dir[-1]<='9':\n\t\t\t\tl1=[]\n\t\t\t\tfor r,d,l in os.walk(first_dir+'/'+second_dir+'/'+third_dir):\n\t\t\t\t\t# print(d)\n\t\t\t\t\tl1.append(d)\n\t\t\t\tfor fourth_dir in l1[0]:\n\t\t\t\t\tfiles=[]\n\t\t\t\t\tfor r,d,l in os.walk(first_dir+'/'+second_dir+'/'+third_dir+'/'+fourth_dir):\n\t\t\t\t\t\tfiles=l\n\t\t\t\t\tfor file in files:\n\t\t\t\t\t\tif file!='all_methods.txt':\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcnt=count(first_dir+'/'+second_dir+'/'+third_dir+'/'+fourth_dir+'/'+file,s)\n\t\t\t\t\t\ttotal+=cnt\n\t\t\t\t\t\t# if cnt:\n\t\t\t\t\t\t# \tprint(first_dir+'/'+second_dir+'/'+third_dir+'/'+fourth_dir+'/'+file)\n\t\t\t\t\t\t\t# print(cnt)\n\n\ndef main():\n\ts=\"Photo\"\n\t# file=\"all_methods.txt\"\n\t# cnt=count(file,s)\n\tgetFile(s)\n\tprint(total)\n\n\n\nif __name__=='__main__':\n\tmain()","sub_path":"jingxin/脚本/getApi.py","file_name":"getApi.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"546671228","text":"import pygame as pg\nfrom collections import defaultdict\n\n\ndef bewertung():\n return sum([stein for stein in brett.values()])\n\n\ndef schlage(spieler,von,stein,zug,züge):\n dead_end = True\n for n in richtungen[stein]:\n for i in range(1, abs(stein)+1):\n über = von + n*i\n zu = über + n\n if über not in brett or zu not in brett or \\\n brett[über] in steine[spieler] or \\\n (brett[über] != 0 and brett[zu] != 0):\n break\n if brett[über] in steine[not spieler] and brett[zu] == 0:\n dead_end = False\n zug.extend([von,zu,über,stein,brett[über]])\n ziehe(spieler,zug[-5:])\n schlage(spieler, zu, stein, zug.copy(),züge)\n ziehe_rückgängig(spieler,zug[-5:])\n zug = zug[:-5]\n break\n if dead_end and zug:\n züge[zug[0]].append(zug)\n return züge \n\n \n\ndef generiere_zugliste(spieler):\n züge, schläge = defaultdict(list), defaultdict(list)\n for von,stein in brett.items(): \n if stein not in steine[spieler]: continue\n schläge.update(schlage(spieler,von,stein,[], defaultdict(list)))\n if schläge: continue\n for n in richtungen[stein]:\n for i in range(1, abs(stein)+1):\n zu = von+n*i\n if zu not in brett or brett[zu] != 0:\n break\n züge[von].append([von, zu, None, stein, None])\n return schläge if schläge else züge\n\ndef ziehe(spieler, zug):\n for i in range(0, len(zug), 5):\n von, zu, über, stein, _ = zug[i:i + 5]\n brett[von] = 0\n brett[zu] = stein\n if über: \n brett[über] = 0\n anz_steine[not spieler] -= 1\n if zu in umwandlung[spieler] and abs(stein) == 1:\n brett[zu] *= 8\n return anz_steine[not spieler] == 0\n\ndef ziehe_rückgängig(spieler, zug):\n for i in reversed(range(0, len(zug), 5)):\n von, zu, über, stein, geschlagen = zug[i:i+5]\n brett[von] = stein\n brett[zu] = 0\n if über:\n brett[über] = geschlagen\n anz_steine[not spieler] += 1\n\ndef minimax(tiefe, maxtiefe, alpha, beta, spieler, win):\n if win:\n score = -99999+tiefe if spieler else 99999-tiefe\n return (score, None)\n if tiefe == maxtiefe or 0 in anz_steine.values(): \n return (bewertung(), None) \n zugliste = generiere_zugliste(spieler)\n if not zugliste:\n return (-99999 if spieler else 99999, None)\n value = -999999 if spieler else 999999\n for züge in zugliste.values():\n for zug in züge:\n win = ziehe(spieler, zug)\n score,_ = minimax(tiefe+1, maxtiefe, alpha, beta, not spieler, win)\n ziehe_rückgängig(spieler,zug)\n if spieler:\n if score > value:\n bester_zug = zug\n value = score\n alpha = max(value, alpha)\n else:\n if score < value:\n bester_zug = zug\n value = score\n beta = min(value, beta)\n if alpha >= beta:\n break \n return (value, bester_zug)\n\n \n\ndef bester_zug(spieler):\n score, bester_zug = minimax(0,6,-999999, 999999, spieler, False)\n print(score, bester_zug)\n return bester_zug\n \n\ndef feld_zentrum(feld):\n s, z = feld % 8, feld // 8\n zentrum = ZELLE // 2\n return (s * ZELLE + zentrum, z * ZELLE + zentrum)\n\n\ndef xy2cell(pos):\n x, y = pos\n return y // ZELLE * 8 + x // ZELLE\n\n\ndef cell2xy(i):\n return i % 8 * ZELLE, i // 8 * ZELLE\n\n\nbrett = {i: 0 for i in range(64) if i % 8 % 2 != i // 8 % 2}\n\n# Teststellung für mehrfachschlagen\n# brett[26] = -8\n# brett[28] = -8\n# brett[33] = 1\n# brett[35] = 1\n# brett[53] = 1\n# brett[46] = 1\n# brett[21] = 1\n# brett[17] = 1\n# brett[19] = 1\n# brett[10] = 1\n\n# brett[7] = -1\n# brett[62] = -8\n# brett[28] = 1\n# brett[40] = 1\n\n# brett[62] = -8\n# brett[53] = -1\n# brett[17] = 1\n\nbrett[44] = 1\nbrett[37] = -1\nbrett[35] = -1\nbrett[17] = -1\nbrett[19] = -1\n\n\n# for i in brett:\n# if i < 24: brett[i] = -1\n# if i > 39: brett[i] = 1\nrichtungen = {1: (-7, -9), -1: (7, 9), -8: (-7, -9, 9, 7), 8: (-7, -9, 9, 7)}\nsteine = {True: {1, 8}, False: (-1, -8)}\nanz_steine = {True: sum([1 for feld in brett.values() if feld > 0]),\n False: sum([1 for feld in brett.values() if feld < 0])}\numwandlung = {True: {1, 3, 5, 7}, False: {56, 58, 60, 62}}\n\nweiss = True\n\nAUFLÖSUNG = 800\nZELLE = AUFLÖSUNG // 8\npg.init()\nscreen = pg.display.set_mode([AUFLÖSUNG, AUFLÖSUNG])\nweitermachen = True\nclock = pg.time.Clock()\nzüge = generiere_zugliste(weiss)\nstate = None\n\nwhile weitermachen:\n clock.tick(20)\n screen.fill((0, 0, 0))\n for ereignis in pg.event.get():\n if ereignis.type == pg.QUIT:\n weitermachen = False\n if ereignis.type == pg.MOUSEBUTTONDOWN and pg.mouse.get_pressed()[0]:\n if state == 'zeige_computerzug':\n ziehe(weiss,best)\n weiss = not weiss\n state = None\n züge = generiere_zugliste(weiss)\n if state == 'von':\n feld2 = xy2cell(pg.mouse.get_pos())\n if feld2 in {zug[1] for zug in züge[feld1]}:\n state = 'zu'\n else:\n state = None\n if not state:\n feld1 = xy2cell(pg.mouse.get_pos())\n if feld1 in züge:\n state = 'von'\n if state == 'zu':\n for zug in züge[feld1]:\n if zug[1] == feld2:\n if len(zug) > 5:\n win = ziehe(weiss, zug[:5])\n feld1 = zug[1]\n zug = zug[5:]\n züge[feld1] = [zug]\n state = 'von'\n else:\n ziehe(weiss, zug)\n weiss = not weiss\n best = bester_zug(weiss)\n state = 'zeige_computerzug'\n break\n\n for i in range(64):\n color = (209, 139, 71) if i in brett else (254, 206, 158)\n pg.draw.rect(screen, color, (cell2xy(i), (ZELLE, ZELLE)))\n for i in brett:\n if brett[i] != 0:\n color = (255, 255, 255) if brett[i] > 0 else (0, 0, 0)\n pg.draw.circle(screen, color, feld_zentrum(i), int(ZELLE * 0.2))\n if abs(brett[i]) == 8:\n color = (255, 255, 255) if brett[i] - 8 else (0, 0, 0)\n pg.draw.circle(screen, color, feld_zentrum(i),\n int(ZELLE * 0.05))\n if not state and i in züge:\n pg.draw.rect(screen, (0, 50, 0), (cell2xy(i), (ZELLE, ZELLE)),7)\n if state == 'zeige_computerzug':\n for n in range(0,len(best),5):\n pg.draw.line(screen, (0,0,100), feld_zentrum(best[n]), feld_zentrum(best[n+1]),10)\n \n if state == 'von':\n pg.draw.rect(screen, (255, 0, 0), (cell2xy(feld1), (ZELLE, ZELLE)), 7)\n for zug in züge[feld1]:\n pg.draw.circle(screen, (0, 0, 100), feld_zentrum(zug[1]),\n int(ZELLE * 0.1))\n pg.display.flip()\n\npg.quit()","sub_path":"Teil_xx_Dame_rekursiv1.py","file_name":"Teil_xx_Dame_rekursiv1.py","file_ext":"py","file_size_in_byte":6476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"153704512","text":"import matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nclass Hopfield:\n\n\tdef init(self,n, p):\n\t\tself.n = n\n\t\tself.p = p\n\t\tchoices = [1,-1]\n\t\tpatterns=[]\n\t\tfor x in range (0,p):\n\t\t\tpattern = np.random.choice(choices,(n,1))\n\t\t\tpatterns.append(pattern)\n\t\tstates = np.random.choice(choices,(n,1))\n\t\tself.states = states\n\t\tself.patterns = patterns\n\n\tdef calWeight(self):\n\t\tweights = np.zeros((self.n, self.n))\n\t\tfor x in range(0,self.p):\n\t\t\tw = (self.patterns[x] * np.transpose(self.patterns[x]))\n\t\t\tweights = np.add(weights, w)\n\t\tself.weights = weights/self.n\n\n\tdef feedInitPattern(self, index):\n\t\tself.initPattern = np.copy(self.patterns[index])\n\t\tself.states = np.copy(self.patterns[index])\n\n\tdef stepNetwork(self):\n\t\tsign = lambda x: -1 if x < 0 else 1\n\t\tres = np.dot(self.weights, self.states)\n\t\tshp = res.shape\n\t\tres = np.fromiter((sign(xi) for xi in res), res.dtype)\n\t\tres = np.reshape( res, shp)\n\t\tself.states = res\n\n\tdef getPError(self):\n\t\tresult = np.add(np.divide(self.states, self.initPattern), 1)\n\t\tresult = np.divide(result, 2)\n\t\treturn np.sum(result)\n\ndef getAvgPError(n, p, iterations):\n\thop = Hopfield()\n\tnCorrect = 0\n\tnTotal = 0\n\tfor x in range(0,iterations):\n\t\thop.init(n,p)\n\t\thop.calWeight()\n\t\tfor _p in range(p):\n\t\t\thop.feedInitPattern(_p)\n\t\t\thop.stepNetwork()\n\t\t\tnCorrect += hop.getPError()\n\t\t\tnTotal += n\n\tprint(hop.weights)\n\treturn 1- (nCorrect/nTotal)\n\ndef getTheoreticalPError(n, p):\n\treturn (1 - math.erf(np.sqrt(n/(2*p)) + np.sqrt(p/(2*n))))/2\n\nbitsToSee = 100000\nN = 200\nP = [1]\n\nx = np.divide(P, N)\nyReal = []\nyTheory = []\nfor p in P:\n\titerations = math.ceil(bitsToSee / (p*N))\n\trealPerror = getAvgPError(N, p, iterations)\n\ttheoryPerror = getTheoreticalPError(N,p)\n\tprint(p)\n\tprint('Real: ', realPerror)\n\tprint('Theory: ', theoryPerror)\n\tprint('\\n')\n\tyReal.append(realPerror)\n\tyTheory.append(theoryPerror)\n\nprint('Calculations done')\nplt.plot(x, yReal, 'r-', x, yTheory, 'g-')\nred_patch = mpatches.Patch(color='red', label='Real data')\nlegend1 = plt.legend(handles=[red_patch], loc=1)\nplt.gca().add_artist(legend1)\ngreen = mpatches.Patch(color='green', label='Theoretical data')\nplt.legend(handles=[green], loc=2)\nplt.xlabel('p/N')\nplt.ylabel('Perror')\n\nplt.show()","sub_path":"ProblemSheet1/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11489920","text":"from webtest import TestApp\nfrom u2fval.model import Base\nfrom u2fval.core.api import create_application\nfrom u2fval.client.controller import ClientController\nfrom u2fval.core import exc\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom .soft_u2f_v2 import SoftU2FDevice\nimport unittest\nimport os\n\n\nclass RestApiTest(unittest.TestCase):\n\n def setUp(self):\n os.environ['U2FVAL_SETTINGS'] = '/dev/null'\n from u2fval.config import settings\n settings['allow_untrusted'] = True\n\n engine = create_engine(settings['db'])\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n\n self.client_controller = ClientController(session)\n self.client_controller.create_client('fooclient',\n 'https://example.com',\n ['https://example.com'])\n\n self.app = TestApp(create_application(settings, session))\n\n def test_call_without_client(self):\n err = self.app.get('/', status=400)\n assert err.json['errorCode'] == exc.BadInputException.code\n\n def test_call_with_invalid_client(self):\n err = self.app.get('/', status=400,\n extra_environ={'REMOTE_USER': 'invalid'})\n assert err.json['errorCode'] == exc.BadInputException.code\n\n def test_get_trusted_facets(self):\n resp = self.app.get('/', extra_environ={'REMOTE_USER': 'fooclient'})\n assert 'https://example.com' in resp.json['trustedFacets'][0]['ids']\n\n def test_list_empty_devices(self):\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert resp.json == []\n\n def test_begin_auth_without_devices(self):\n err = self.app.get('/foouser/authenticate', status=400,\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert err.json['errorCode'] == exc.NoEligibleDevicesException.code\n\n def test_register(self):\n device = SoftU2FDevice()\n self.do_register(device, {'foo': 'bar'})\n\n def test_authenticate(self):\n device = SoftU2FDevice()\n self.do_register(device, {'foo': 'bar', 'baz': 'one'})\n descriptor = self.do_authenticate(device, {'baz': 'two'})\n assert descriptor['properties'] == {\n 'foo': 'bar',\n 'baz': 'two'\n }\n\n def test_get_properties(self):\n device = SoftU2FDevice()\n descriptor = self.do_register(device, {'foo': 'bar', 'baz': 'foo'})\n descriptor2 = self.app.get('/foouser/' + descriptor['handle'],\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert descriptor2.json['properties'] == {'foo': 'bar', 'baz': 'foo'}\n\n def test_get_devices(self):\n self.do_register(SoftU2FDevice())\n self.do_register(SoftU2FDevice())\n self.do_register(SoftU2FDevice())\n\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n descriptors = resp.json\n assert len(descriptors) == 3\n\n def test_delete_user(self):\n self.do_register(SoftU2FDevice())\n self.do_register(SoftU2FDevice())\n self.do_register(SoftU2FDevice())\n self.app.delete('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert resp.json == []\n\n def test_delete_devices(self):\n d1 = self.do_register(SoftU2FDevice())\n d2 = self.do_register(SoftU2FDevice())\n d3 = self.do_register(SoftU2FDevice())\n\n self.app.delete('/foouser/' + d2['handle'],\n extra_environ={'REMOTE_USER': 'fooclient'})\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert len(resp.json) == 2\n self.app.delete('/foouser/' + d1['handle'],\n extra_environ={'REMOTE_USER': 'fooclient'})\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert resp.json == [d3]\n self.app.delete('/foouser/' + d3['handle'],\n extra_environ={'REMOTE_USER': 'fooclient'})\n resp = self.app.get('/foouser',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert resp.json == []\n\n def do_register(self, device, properties=None):\n reg_req = self.app.get('/foouser/register',\n extra_environ={'REMOTE_USER': 'fooclient'})\n assert len(reg_req.json['authenticateRequests']) == \\\n len(reg_req.json['authenticateDescriptors'])\n\n reg_resp = device.register(reg_req.json['registerRequests'][0],\n 'https://example.com')\n\n if properties is None:\n properties = {}\n descriptor = self.app.post_json('/foouser/register', {\n 'registerResponse': reg_resp.json,\n 'properties': properties\n }, extra_environ={'REMOTE_USER': 'fooclient'})\n assert descriptor.json['properties'] == properties\n return descriptor.json\n\n def do_authenticate(self, device, properties=None):\n aut_req = self.app.get('/foouser/authenticate',\n extra_environ={'REMOTE_USER': 'fooclient'})\n aut_resp = device.getAssertion(aut_req.json['authenticateRequests'][0],\n 'https://example.com')\n if properties is None:\n properties = {}\n return self.app.post_json('/foouser/authenticate', {\n 'authenticateResponse': aut_resp.json,\n 'properties': properties\n }, extra_environ={'REMOTE_USER': 'fooclient'}).json\n","sub_path":"test/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"552586342","text":"from keras import backend as K\nfrom keras.callbacks import Callback\nfrom keras.layers import Layer\nfrom keras import metrics\n\n\nclass VariationalLayer(Layer):\n \"\"\"\n Define a custom layer that learns and performs the training\n \"\"\"\n def __init__(self, var_layer, mean_layer, original_dim, beta, loss,\n **kwargs):\n # https://keras.io/layers/writing-your-own-keras-layers/\n self.is_placeholder = True\n self.var_layer = var_layer\n self.mean_layer = mean_layer\n self.original_dim = original_dim\n self.beta = beta\n self.loss = loss\n super(VariationalLayer, self).__init__(**kwargs)\n\n def vae_loss(self, x_input, x_decoded):\n if self.loss == 'binary_crossentropy':\n recon_loss = self.original_dim * \\\n metrics.binary_crossentropy(x_input, x_decoded)\n elif self.loss == 'mean_squared_error':\n recon_loss = self.original_dim * \\\n metrics.mean_squared_error(x_input, x_decoded)\n\n kl_loss = - 0.5 * K.sum(1 + self.var_layer -\n K.square(self.mean_layer) -\n K.exp(self.var_layer), axis=-1)\n\n return K.mean(recon_loss + (K.get_value(self.beta) * kl_loss))\n\n def call(self, inputs):\n x, x_decoded = inputs\n loss = self.vae_loss(x, x_decoded)\n self.add_loss(loss, inputs=inputs)\n # We won't actually use the output.\n return x\n\n\nclass WarmUpCallback(Callback):\n def __init__(self, beta, kappa):\n self.beta = beta\n self.kappa = kappa\n\n def on_epoch_end(self, epoch, logs={}):\n \"\"\"\n Behavior on each epoch\n \"\"\"\n if K.get_value(self.beta) <= 1:\n K.set_value(self.beta, K.get_value(self.beta) + self.kappa)\n","sub_path":"tybalt/utils/vae_utils.py","file_name":"vae_utils.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"100666978","text":"#!/usr/bin/python3\n\"\"\" Database Storage Engine \"\"\"\n\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom sqlalchemy import (create_engine)\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nfrom models.base_model import BaseModel, Base\nfrom os import getenv\nimport sqlalchemy as db\n\n\nclass DBStorage:\n \"\"\"\n This class is the database storage engine\n \"\"\"\n __engine = None\n __session = None\n\n def __init__(self):\n \"\"\"\n Initialize an instance\n \"\"\"\n self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.\n format(getenv('HBNB_MYSQL_USER'),\n getenv('HBNB_MYSQL_PWD'),\n getenv('HBNB_MYSQL_HOST'),\n getenv('HBNB_MYSQL_DB')),\n pool_pre_ping=True)\n if getenv('HBNB_ENV') == 'test':\n Base.metadata.drop_all(self.__engine)\n\n def all(self, cls=None):\n \"\"\"\n query all objects from the current db session, based on class name\n \"\"\"\n my_list = [\"State\", \"City\", \"User\", \"Place\", \"Review\", \"Amenity\"]\n dictio = {}\n if cls is None:\n for table in my_list:\n query = self.__session.query(eval(table)).all()\n for obj in query:\n key = \"{}.{}\".format(type(obj).__name__, obj.id)\n dictio[key] = obj\n else:\n query = self.__session.query(eval(cls)).all()\n for obj in query:\n key = \"{}.{}\".format(type(obj).__name__, obj.id)\n dictio[key] = obj\n return dictio\n\n def new(self, obj):\n \"\"\"\n add the object to the current databse session\n \"\"\"\n if obj:\n self.__session.add(obj)\n\n def save(self):\n \"\"\"\n commit changes to the current database session\n \"\"\"\n self.__session.commit()\n\n def delete(self, obj=None):\n \"\"\"\n delete obj from the current database session\n \"\"\"\n if obj:\n self.__session.delete(obj)\n\n def reload(self):\n \"\"\"\n create all tables in the database\n \"\"\"\n Base.metadata.create_all(self.__engine)\n self.__session = scoped_session(sessionmaker(bind=self.__engine,\n expire_on_commit=False))\n\n def close(self):\n \"\"\"Thread specific storage\"\"\"\n self.__session.close()\n","sub_path":"models/engine/db_storage.py","file_name":"db_storage.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"226864997","text":"# import datetime\n# import time\n\n# datetime.timedelta()\n# datetime.date()\n# print(datetime.datetime.now())\n# print(datetime.datetime.today())\n# now_time = datetime.datetime.now()\n# print(now_time.date())\n# print(now_time.time())\n# print(now_time.year)\n# print(now_time.month)\n# print(now_time.day)\n# print(time.time())\n# time.sleep(2)\n\nfrom datetime import datetime, date, time, timedelta\nd = datetime(2020, 10, 30, 14, 5)\nprint(d)\nd2 = date(2019, 3, 23)\nprint(d2)\nt = time(9, 0)\nprint(t)\n# 日期、时间与字符串转换\nds = '2018/10/3T12:42:09'\nds_t = datetime.strptime(ds, '%Y/%m/%dT%H:%M:%S')\nn = datetime.now()\nn_str = n.strftime('%Y/%m/%dT%H:%M:%S')\n\nn = datetime.now()\nn_next = n + timedelta(days = 5, hours = 42)\nprint(n)\nprint(n_next)\nd1 = datetime(2018, 10, 15)\nd2 = datetime(2018, 11, 12)\nrest = d2 -d1\nprint(rest.days)","sub_path":"base/dateTimeNew.py","file_name":"dateTimeNew.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"248035188","text":"#!/usr/bin/env python\n\nfrom numpy import *\n\n# ASSUMPTIONS\n# -----------\n# * That the file is ordered thus: \n# t, x, v\n\n\ninfileName = \"f.dat\"\ninfile = open( infileName, mode='rb' )\n\ntsteps = 1\nxsteps = 40\nvsteps = 30\n\ndata = zeros( (tsteps,xsteps,vsteps) )\n\nfor t in range(1,tsteps) :\n\tfor x in range(1,xsteps):\n\t\tfor v in range(1,vsteps):\n\t\t\t\n\t\t\t\t# Read data\n\t\t\t\tinfile.read(4)\n\n\n\nclose(infile)\n\n\n\n\n\n\n\n# Open the file\ninfile = open(infileName, 'rb')\n\n# Read in a tstep\n\n\n\n#\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"diffusion_code/sandbox/convert_farray_to_histogram.py","file_name":"convert_farray_to_histogram.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"121334586","text":"import threading\nimport webbrowser\nimport BaseHTTPServer\nimport SimpleHTTPServer\nimport os\nimport sys\nimport logging\nimport json\n\nport = 8123\n\nclass TheApp(SimpleHTTPServer.SimpleHTTPRequestHandler):\n\n def do_POST(self):\n logging.info(\"Serving POST\")\n length = int(self.headers.getheader('content-length')) \n data_string = self.rfile.read(length)\n response = {'msg':'herro seniour'}\n logging.info(json.dumps(response))\n self.wfile.write(json.dumps(response))\n\ndef start_server():\n server_address = (\"\", port)\n server = BaseHTTPServer.HTTPServer(server_address, TheApp)\n server.serve_forever()\n\nthreading.Thread(target = start_server).start()\n\nif 'linux' in sys.platform:\n browser_path = '/usr/bin/firefox'\nelif 'windows' in sys.platform:\n browser_path = 'C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe'\n\nurl = 'http://localhost:%s/index.html' % port\nlogging.root.setLevel(logging.DEBUG)\nlogging.info(\"Serving at: %s\" % (url))\nos.system('%s -height 600 -width 800 -chrome %s' % (browser_path, url))\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"28353894","text":"#!/usr/bin/env python\n\"\"\"\nthe daily procedure (coming from OpenBSD)\n\"\"\"\nimport shutil\nimport os\nimport time\nimport datetime\nfrom common.maintenance import system_exec, logger\nfrom common.LoggingSystem import get_error_list\nfrom common.MailingSystem import add_paragraph_with_items, add_paragraph, add_paragraph_with_array, \\\n add_paragraph_with_lines\n\n\ndef setheaderlines():\n \"\"\"\n get information about kernel version and uptime\n :return: lines to be displayed in mail\n \"\"\"\n res = []\n cmd = \"sysctl -n kern.version\"\n ret, lines = system_exec(cmd)\n res.append(lines[0])\n ret, lines = system_exec(\"uptime\")\n res.append(lines[0])\n return res\n\n\ndef remove_tmp():\n \"\"\"\n clean the /tmp folder\n :return:\n \"\"\"\n if not os.path.exists(\"/tmp\"):\n return\n if os.path.islink(\"/tmp\"):\n return\n logger.log(\"daily\", \"Removing scratch and junk files\")\n cwd = os.getcwd()\n os.chdir(\"/tmp\")\n list_dir = os.listdir()\n now = time.time()\n for file in list_dir:\n if os.path.isfile(file):\n diff = datetime.date.fromtimestamp(now - os.path.getatime(file))\n if diff.day > 7:\n os.remove(file)\n continue\n if os.path.isdir(file):\n if file in [\".\", \".X11-unix\", \".ICE-unix\", \"vi.recover\"]:\n continue\n diff = datetime.date.fromtimestamp(now - os.path.getmtime(file))\n if diff.day > 1:\n shutil.rmtree(file)\n continue\n os.chdir(cwd)\n\n\ndef purge_account():\n \"\"\"\n purge the account data\n :return:\n \"\"\"\n if not os.path.exists(\"/var/account/acct\"):\n return\n logger.log(\"daily\", \"Purging accounting records\")\n if os.path.exists(\"/var/account/acct.2\"):\n os.rename(\"/var/account/acct.2\", \"/var/account/acct.3\")\n if os.path.exists(\"/var/account/acct.1\"):\n os.rename(\"/var/account/acct.1\", \"/var/account/acct.2\")\n if os.path.exists(\"/var/account/acct.0\"):\n os.rename(\"/var/account/acct.0\", \"/var/account/acct.1\")\n shutil.copy(\"/var/account/acct\", \"/var/account/acct.1\")\n\n\ndef services():\n \"\"\"\n check for service that are not runin\n :return:\n \"\"\"\n ret, lines = system_exec(\"rcctl ls failed\")\n if len(lines) == 0:\n # everything is OK!\n return\n logger.log(\"daily\", \"Services that should be running but aren't\\n\" + \"\\n\".join(lines))\n add_paragraph_with_items(\"Services that should be running but aren't\", lines=lines)\n\n\ndef disk():\n \"\"\"\n check disk space\n :return:\n \"\"\"\n ret, lines = system_exec(\"df -hl\")\n if len(lines) == 0:\n return\n logger.log(\"daily\", \"Disks:\\n\" + \"\\n\".join(lines))\n ct = []\n r = []\n for line in lines:\n if len(ct) == 0:\n ct = line.split(maxsplit=5)\n continue\n r.append(line.split(maxsplit=5))\n add_paragraph_with_array(\"Disks\", col_titles=ct, rows=r)\n\n\nMySQLParams = {\n 'host': \"localhost\",\n 'user': \"robot\",\n 'passwd': \"Robot123\",\n 'db': \"administration\"\n}\n\n\ndef check_daily_errors():\n \"\"\"\n check for error in database\n \"\"\"\n err_list = get_error_list()\n if len(err_list) == 0:\n add_paragraph(\"Error Status\", message=\"Everything is good!\")\n else:\n errors_md = []\n for err in err_list:\n errors_md.append(err.to_md_array())\n add_paragraph_with_array(\"Too Many Errors in one Hour\", col_titles=[\"time\", \"who\", \"message\"], rows=errors_md)\n\n\ndef main(dry_run: bool = False):\n \"\"\"\n main script execution\n :param dry_run: if the script should be run without system modification\n :return:\n \"\"\"\n logger.log(\"daily\", \"runing daily procedure\")\n #\n hlines = setheaderlines()\n add_paragraph_with_lines(\"DAILY procedure\", 3, lines=hlines)\n #\n if not dry_run:\n remove_tmp()\n #\n if not dry_run:\n purge_account()\n #\n services()\n #\n check_daily_errors()\n #\n disk()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"p03_day/daily.py","file_name":"daily.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528594235","text":"import requests\nimport re\nimport urllib\nimport os\nimport sys\ndef main_menu():\n os.system('cls')\n print(\"\")\n print(\"-------喜马拉雅FM音乐下载工具--------\")\n print(\"- 1~歌曲类型 -\")\n print(\"- 2~歌单编号 -\")\n print(\"- 0~退出下载 -\")\n print(\"----------------------------------\")\n selt = int(input(\"请选择对应的下载方式:\"))\n while 1:\n if selt == 1:\n gqmc=main_gqzl()\n break\n elif selt == 2:\n gqmc=input(\"请输入对应的歌单编号:\")\n break\n elif selt == 0:\n sys.exit(1)\n break\n else:\n selt = int(input(\"输入有误,请重新输入:\"))\n return gqmc\n\ndef main_gqzl():\n print(\"----------~~~请选择歌曲类型~~~~--------\")\n print(\"- 00~全部 10~嘻哈 20~雷鬼 30~纯音 -\")\n print(\"- 01~流行 11~电音 21~动漫 31~翻唱 -\")\n print(\"- 02~摇滚 12~后摇 22~影视 32~影视 -\")\n print(\"- 03~民谣 13~现代 23~朋克 33~欧美 -\")\n print(\"- 04~轻纯 14~民乐 24~舞台 34~催眠 -\")\n print(\"- 05~古风 15~声乐 25~儿歌 35~游戏 -\")\n print(\"- 06~爵士 16~拉丁 26~实验 36~日韩 -\")\n print(\"- 07~蓝调 17~金属 27~喜剧 37~电子 -\")\n print(\"- 08~乡村 18~独立 28~视频 38~铃声 -\")\n print(\"- 09~古典 19~灵魂 29~老歌 39~原创 -\")\n print(\"-----------请输入数字选择类型-----------\")\n zllb=[\"\",\"liuxing\",\"yaogun\",\"minyao\",\"qingyinyue\",\"gufeng\",\"jueshi\",\"landiao\",\"xiangcun\",\"gudian\",\n \"xiha\",\"dianyin\",\"houyao\",\"xinshiji\",\"minyue\",\"shengyue\",\"lading\",\"jinshu\",\"duli\",\"linghun\",\n \"leigui\",\"anime\",\"yingshiyuansheng\",\"punk\",\"wutai\",\"erge\",\"shiyanyinyue\",\"xiju\",\"reci820\",\"reci117\",\n \"reci310\",\"reci125\",\"reci121\",\"reci507\",\"reci322\",\"reci119\",\"reci506\",\"reci328\",\"reci130\",\"reci320\"]\n xzlx=int(input(\"请选择对应的歌曲类型:\"))\n if xzlx<0 or xzlx>39 : return zllb[0]\n else : return zllb[xzlx]\nhttp_head={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0'}\n\ndef music_search(tget_strs,tget_head):\n tget_urls='https://www.ximalaya.com/yinyue/'+tget_strs\n tget_html=requests.get(tget_urls,headers=tget_head)\n tget_html.encoding=tget_html.apparent_encoding\n return tget_html\n\ndef music_albums(gals_html):\n gals_text=re.findall(r'\"albumId\":(.*?),',(gals_html).text)\n gals_urlt=[]\n for x in (gals_text[:1]):\n gals_urls='https://www.ximalaya.com/revision/play/album?albumId='+x\n gals_htms=requests.get(gals_urls,headers=http_head)\n gals_urlt=(re.findall(r'\"src\":\"(.*?)\"',(gals_htms).text))\n return gals_urlt\n\ndef music_gettit(getf_html):\n getf_name=re.findall(r'\"title\":\"(.*?)\"',(getf_html).text)\n return getf_name\n\ndef music_downlo(urlt,title):\n n=0\n for y in urlt:\n print(n+1,\"----\"+str(title[n]))\n n = n + 1\n n=int(input(\"请输入下载编号:\"))\n try:\n print(\"正在下载:\"+str(title[n]))\n urllib.request.urlretrieve(urlt[n],str(title[n]+'.m4a'))\n print(\"下载成功:\"+str(title[n]))\n except:\n print(\"下载失败:\"+str(title[n]))\n return 0;\n\nhttp_selt=main_menu()\nhttp_html=music_search(http_selt,http_head)\nhttp_urlt=music_gettit(http_html)\nhttp_urlf=music_albums(http_html)\nhttp_rult=music_downlo(http_urlf,http_urlt)","sub_path":"喜马拉雅/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"120166758","text":"\"\"\"\n Name: train_model.py\n Created: 10/7/2017\n Description: Fine-tune vgg16 for Planet Amazon.\n\"\"\"\n#==============================================\n# Modules\n#==============================================\nimport os\nimport sys\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=sys.argv[1]\nimport numpy as np\nimport pandas as pd\nimport time\nimport gzip\nimport pickle\nfrom collections import Counter\nfrom keras.applications.vgg16 import VGG16\nfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array\nfrom keras.models import Model, model_from_json\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras import backend as K\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom keras.applications.imagenet_utils import decode_predictions\nfrom keras.optimizers import SGD, Adam\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import fbeta_score\nfrom tqdm import tqdm\n#==============================================\n# Files\n#==============================================\n_EPSILON = K.epsilon()\nfrom train_model_vgg16 import fbs, binary_crossentropy_weighted\n\n\n#==============================================\n# Functions\n#==============================================\ndef load_model(chosen_metrics=[fbs],\n vgg16_json=\"vgg16_mod.json\",\n vgg16_h5=\"vgg16_fine_tuned_2.h5\", verbose=1):\n \"\"\"\n Load the vgg16 and trained weights from disk.\n \"\"\"\n\n # load json and create model\n with open(vgg16_json, 'r') as iOF:\n loaded_model_json = iOF.read()\n loaded_model = model_from_json(loaded_model_json)\n # load weights into new model\n loaded_model.load_weights(vgg16_h5)\n if verbose >= 1: print(\"Loaded model from disk\")\n\n # evaluate loaded model on test data\n loaded_model.compile(optimizer=Adam(lr=0.0005), loss=binary_crossentropy_weighted, metrics=[fbs])\n\n return loaded_model\n\n\n\n\n\ndef infer(model, X_test, y_test, n_inference=100, batch_size=32, verbose=1):\n \"\"\"\n Infer with the vgg16.\n \"\"\"\n\n # number of samples\n nb_test_samples = len(y_test)\n\n # add fake entries to get batch size multiple\n nb_add = batch_size - nb_test_samples%batch_size\n y_test_add = y_test[-nb_add:, ...]\n X_test_add = X_test[-nb_add:, ...]\n y_test_stacked = np.vstack([y_test, y_test_add])\n X_test_stacked = np.vstack([X_test, X_test_add])\n\n y_pred_list = []\n y_test_list = []\n for inference_pass in range(n_inference):\n\n test_datagen = ImageDataGenerator(\n rescale=1./255,\n horizontal_flip=True,\n vertical_flip=True,\n zoom_range=0.15,\n width_shift_range=0.15,\n height_shift_range=0.15,\n rotation_range=180,\n fill_mode='reflect')\n\n test_generator = test_datagen.flow(\n X_test_stacked,\n y_test_stacked,\n batch_size=batch_size,\n shuffle=False)\n\n y_pred = model.predict_generator(\n test_generator,\n steps=(nb_test_samples + nb_add) // batch_size,\n verbose=1)\n\n # get predictions\n y_pred = y_pred[:-nb_add, ...]\n y_pred_list.append(y_pred)\n\n # append ground truth\n y_test = y_test_stacked[:-nb_add, ...]\n y_test_list.append(y_test)\n\n y_pred = np.array(y_pred_list)\n y_test = np.array(y_test_list)\n\n return y_pred, y_test\n\n\n\ndef main(verbose=1):\n \"\"\"\n Main function.\n \"\"\"\n\n if sys.argv[2] != 'test':\n\n ##### Validation\n fold_id = int(sys.argv[2])\n\n ### Load model\n if verbose >= 1: print(\"Loading model (fold %d)...\"%fold_id)\n model_dir = \"../data/planet_amazon/models/\"\n model = load_model(vgg16_json=model_dir+\"vgg16_mod_%d.json\"%fold_id,\n vgg16_h5=model_dir+\"vgg16_fine_tuned_check_point_3_%d.h5\"%fold_id,\n verbose=verbose)\n\n ### Load images\n if verbose >= 1: print(\"Loading images into RAM (fold %d)...\"%fold_id)\n image_dir=\"../data/planet_amazon/train-jpg/\"\n target_size = (256,256)\n df_val = pd.read_csv(\"../data/planet_amazon/val%d.csv\"%fold_id)\n X_val, y_val = [], []\n # for train and validation\n for image_id, y_lab in tqdm(list(zip(df_val.image_name, df_val.iloc[:,2:].values)), miniters=100):\n image_path = image_dir+str(image_id)+\".jpg\"\n if os.path.exists(image_path):\n try:\n img = load_img(image_path, target_size=target_size)\n arr = img_to_array(img)\n X_val.append(arr)\n y_val.append(y_lab)\n except OSError:\n if verbose >= 2: print(\"OSError on image %s.\"%image_path)\n else:\n raise(ValueError(\"Image %s does not exist.\"%image_path))\n X_val = np.array(X_val)\n y_val = np.array(y_val)\n if verbose >= 2:\n print(X_val.shape)\n print(y_val.shape)\n print(np.mean(y_val, axis=0))\n\n ### Infer\n if verbose >= 1: print(\"Inferring (fold %d)...\"%fold_id)\n n_inference = 20\n y_pred, y_test = infer(model, X_val, y_val, n_inference=n_inference, batch_size=32, verbose=verbose)\n if verbose >= 2:\n print(y_pred.shape)\n print(y_test.shape)\n print(y_pred[0,0,0])\n print(y_test[0,0,0])\n print(\"Fbeta score: \", fbeta_score(np.mean(y_test, axis=0), np.mean(y_pred, axis=0).round(), 2, average='samples'))\n\n ### Save preds\n if verbose >= 1: print(\"Saving preds (fold %d)...\"%fold_id)\n with open(\"../data/planet_amazon/vgg16_preds%d_%d.npy\"%(fold_id,n_inference), \"wb\") as iOF:\n np.save(iOF, y_pred)\n with open(\"../data/planet_amazon/vgg16_trues%d_%d.npy\"%(fold_id,n_inference), \"wb\") as iOF:\n np.save(iOF, y_test)\n\n else:\n\n ### Load images\n if verbose >= 1: print(\"Loading images into RAM...\")\n image_dir=\"../data/planet_amazon/test-jpg/\"\n target_size = (256,256)\n image_ids = [fname[:-4] for fname in os.listdir(image_dir) if fname.endswith(\".jpg\")]\n X_test, y_test = [], []\n # for train and validation\n for image_id in tqdm(image_ids, miniters=100):\n image_path = image_dir+str(image_id)+\".jpg\"\n if os.path.exists(image_path):\n try:\n img = load_img(image_path, target_size=target_size)\n arr = img_to_array(img)\n X_test.append(arr)\n y_lab = np.zeros((17,))\n y_test.append(y_lab)\n except OSError:\n if verbose >= 2: print(\"OSError on image %s.\"%image_path)\n else:\n raise(ValueError(\"Image %s does not exist.\"%image_path))\n X_test = np.array(X_test)\n y_test = np.array(y_test)\n if verbose >= 2:\n print(X_test.shape)\n print(y_test.shape)\n print(np.mean(y_test, axis=0))\n\n ##### Test\n y_pred_folds = []\n offset = 5\n for fold_id in range(offset,offset+5):\n ### Load model\n if verbose >= 1: print(\"Loading model (fold %d)...\"%fold_id)\n model_dir = \"../data/planet_amazon/models/\"\n model = load_model(vgg16_json=model_dir+\"vgg16_mod_%d.json\"%fold_id,\n vgg16_h5=model_dir+\"vgg16_fine_tuned_check_point_3_%d.h5\"%fold_id,\n verbose=verbose)\n\n ### Infer\n if verbose >= 1: print(\"Inferring (fold %d)...\"%fold_id)\n n_inference = 20\n y_pred, _ = infer(model, X_test, y_test, n_inference=n_inference//5, batch_size=32, verbose=verbose)\n y_pred_folds.append(y_pred)\n if verbose >= 2:\n print(y_pred.shape)\n print(y_pred[0,0,0])\n\n y_pred_folds = np.vstack(y_pred_folds)\n if verbose >= 2:\n print(y_pred_folds.shape)\n print(y_pred_folds[0,0,0])\n\n ### Save preds\n if verbose >= 1: print(\"Saving preds...\")\n with open(\"../data/planet_amazon/vgg16_predstest_%d.npy\"%n_inference, \"wb\") as iOF:\n np.save(iOF, y_pred_folds)\n with open(\"../data/planet_amazon/vgg16_idstest_%d.txt\"%n_inference, \"w\") as iOF:\n iOF.writelines([image_id+\"\\n\" for image_id in image_ids])\n\n\n\n\n\n#==============================================\n# Main\n#==============================================\nif __name__ == '__main__':\n main(2)\n","sub_path":"predict_model_vgg16.py","file_name":"predict_model_vgg16.py","file_ext":"py","file_size_in_byte":8698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"499913838","text":"\"\"\"DataLad container extension\"\"\"\n\n__docformat__ = 'restructuredtext'\n\nfrom .version import __version__\n\n# Imported to set singularity/apptainer version commands at init\nimport datalad_container.extractors._load_singularity_versions # noqa\n\n# defines a datalad command suite\n# this symbold must be identified as a setuptools entrypoint\n# to be found by datalad\ncommand_suite = (\n # description of the command suite, displayed in cmdline help\n \"Containerized environments\",\n [\n # specification of a command, any number of commands can be defined\n (\n # importable module that contains the command implementation\n 'datalad_container.containers_list',\n # name of the command class implementation in above module\n 'ContainersList',\n 'containers-list',\n 'containers_list',\n ),\n (\n 'datalad_container.containers_remove',\n # name of the command class implementation in above module\n 'ContainersRemove',\n 'containers-remove',\n 'containers_remove',\n\n ),\n (\n 'datalad_container.containers_add',\n # name of the command class implementation in above module\n 'ContainersAdd',\n 'containers-add',\n 'containers_add',\n\n ),\n (\n 'datalad_container.containers_run',\n 'ContainersRun',\n 'containers-run',\n 'containers_run',\n\n )\n ]\n)\n","sub_path":"datalad_container/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333386118","text":"'''\nThis modules covers the detailed implementation of the functions being used to carry out the test cases.\n\nThis modules provides an High level API to selenium way of interacting with the browser.\nThe functions are general enough to accomodate an array of usage (click_on(\"String\")),\nor sometimes designed for a specifc need, to cater a single purpose ( gallery_next() )\n\nThe purpose and usage of functions are defined.\n'''\n\nfrom selenium import webdriver\nimport unicodecsv as csv\nimport platform\nimport time\nfrom selenium.webdriver.common.keys import Keys\nimport os\nimport config\n\nchrome_options = webdriver.ChromeOptions()\nprefs = {\"profile.default_content_setting_values.notifications\" : 2}\nchrome_options.add_experimental_option(\"prefs\",prefs)\n\n\nif platform.system() == 'Darwin':\n driver = webdriver.Chrome('driver/macos/chromedriver', chrome_options=chrome_options)\nelif platform.system() == 'Linux':\n driver = webdriver.Chrome('driver/linux/chromedriver', chrome_options=chrome_options)\nelif platform.system() == 'Windows':\n driver = webdriver.Chrome('driver/windows/chromedriver.exe', chrome_options=chrome_options)\n\nWAIT_TIME = 1# number of seconds to wait after clicking something\n# user='maria_rdhorxy_zerosub@tfbnw.net ', pw='cloudkibo123'\ndriver.implicitly_wait(WAIT_TIME)\n\ndef open_new_window():\n \"\"\"\n Opens a new chrome window\n \"\"\"\n if platform.system() == 'Darwin':\n new_driver = webdriver.Chrome('driver/macos/chromedriver', chrome_options=chrome_options)\n elif platform.system() == 'Linux':\n new_driver = webdriver.Chrome('driver/linux/chromedriver', chrome_options=chrome_options)\n elif platform.system() == 'Windows':\n new_driver = webdriver.Chrome('driver/windows/chromedriver.exe', chrome_options=chrome_options)\n return new_driver\n\ndef wait(wait_time=WAIT_TIME):\n \"\"\"\n Suspends execution for the given number of seconds\n Keyword arguments:\n wait_time -- number of seconds to wait (default 1.0)\n \"\"\"\n # time.sleep(wait_time)\n pass\n\ndef open_kibopush():\n \"\"\"\n Opens staging.kibopush.com\n \"\"\"\n try:\n if config.platform == 'staging':\n driver.get('https://staging.kibopush.com/')\n elif config.platform == 'production':\n driver.get('https://app.kibopush.com/')\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef open_facebook(account_type='buyer'):\n \"\"\"\n Opens Facebook account for a given account type\n Keyword arguments:\n -----------------\n account_type (string): could be 'agent', 'admin', 'buyer' or 'individual' (default 'buyer')\n \"\"\"\n try:\n facebook_driver = open_new_window()\n facebook_driver.get(\"https://www.facebook.com/\")\n \n email = facebook_driver.find_element_by_id('email')\n password = facebook_driver.find_element_by_id('pass')\n login = facebook_driver.find_element_by_id('loginbutton')\n\n user_email = config.facebook_accounts[account_type]['facebook_email']\n user_password = config.facebook_accounts[account_type]['password']\n email.send_keys(user_email)\n password.send_keys(user_password)\n login.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\n\ndef delete_poll_templates():\n \"\"\"\n Deletes all poll templates from templates page\n \"\"\"\n try:\n poll_templates = driver.find_element_by_class_name('poll-templates')\n template_rows = poll_templates.find_elements_by_class_name('m-datatable__row--even')\n for row in template_rows:\n click_on('delete', scope=row)\n popup = driver.find_element_by_class_name('narcissus_17w311v')\n click_on('delete', scope=popup)\n if verify_alert() != \"Success\":\n return \"Error: no delete alert\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef delete_survey_templates():\n \"\"\"\n Deletes all survey templates from templates page\n \"\"\"\n try:\n survey_templates = driver.find_element_by_class_name('survey-templates')\n template_rows = poll_templates.find_elements_by_class_name('m-datatable__row--even')\n for row in template_rows:\n click_on('delete', scope=row)\n popup = driver.find_element_by_class_name('narcissus_17w311v')\n click_on('delete', scope=popup)\n if verify_alert() != \"Success\":\n return \"Error: no delete alert\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef delete_broadcast_templates():\n \"\"\"\n Deletes all broadcast templates from templates page\n \"\"\"\n try:\n broadcast_templates = driver.find_element_by_class_name('broadcast-templates')\n template_rows = poll_templates.find_elements_by_class_name('m-datatable__row--even')\n for row in template_rows:\n click_on('delete', scope=row)\n popup = driver.find_element_by_class_name('narcissus_17w311v')\n click_on('delete', scope=popup)\n if verify_alert() != \"Success\":\n return \"Error: no delete alert\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef verify_poll_templates_table():\n \"\"\"\n Verifies whether there are entries in poll templates (in templates page)\n \"\"\"\n try:\n poll_templates = driver.find_element_by_class_name('poll-templates')\n return verify_table(scope=poll_templates)\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef verify_survey_templates_table():\n \"\"\"\n Verifies whether there are entries in survey templates (in templates page)\n \"\"\"\n try:\n survey_templates = driver.find_element_by_class_name('survey-templates')\n return verify_table(scope=survey_templates)\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef verify_broadcast_templates_table():\n \"\"\"\n Verifies whether there are entries in broadcast templates (in templates page)\n \"\"\"\n try:\n broadcast_templates = driver.find_element_by_class_name('broadcast-templates')\n return verify_table(scope=broadcast_templates)\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef close_help_popup():\n \"\"\"\n Closes messenger help popup\n \"\"\"\n try:\n driver.switch_to.frame(driver.find_element_by_xpath('//iframe[contains(@src, \"https://www.facebook.com/v2.12/plugins/customerchat\")]'))\n close_button = driver.find_element_by_class_name('closeButtonContainer')\n close_button.click()\n wait()\n driver.switch_to.default_content()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef screenshot(filename):\n \"\"\"\n Screenshots the webpage\n Parameters:\n ----------\n filename (string) : name which to save the screenshot file.\n \"\"\"\n try:\n driver.save_screenshot('Screenshots/'+filename+'.png')\n except:\n return \"Error: \" + str(e)\n return \"Screenshot succesfully saved\"\n\ndef login(account_type='buyer'):\n \"\"\"\n Logs in a user of a particular account type (from initial login screen of KiboPush)\n Keyword arguments:\n account_type (string) : could be 'agent', 'admin', 'buyer' or 'individual' (default 'buyer')\n \"\"\"\n try:\n click_on('login')\n team_account = account_type == 'agent' or account_type == 'admin' or account_type == 'buyer'\n\n user_email = config.facebook_accounts[account_type]['login_email']\n user_password = config.facebook_accounts[account_type]['password']\n\n\n if team_account:\n user_domain = config.facebook_accounts[account_type]['domain']\n click_on('team account')\n else:\n click_on('individual account')\n\n login_form = driver.find_element_by_class_name('m-login__wrapper')\n\n if team_account:\n domain_input = login_form.find_element_by_xpath('.//input[@type=\"text\"]')\n password = login_form.find_element_by_xpath('.//input[@type=\"password\"]')\n email = login_form.find_element_by_xpath('.//input[@type=\"email\"]')\n\n login_button = login_form.find_element_by_id('m_login_signup_submit')\n \n if team_account:\n domain_input.send_keys(user_domain) \n email.send_keys(user_email)\n password.send_keys(user_password)\n login_button.click()\n wait(wait_time=5)\n if verify_failure() == \"Success\":\n return \"Error Invalid Login\" \n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef close_menu(x):\n \"\"\"\n Closes the xth menu (from top to down including submenus and nested menus) (from persistent menu page)\n Parameters:\n ----------\n x (string) : number of the menu from top to bottom (starting from 1)\n \"\"\"\n try:\n x = int(x)\n exes = driver.find_elements_by_class_name('fa-times')\n num_of_menu_items = len(exes)\n exes[x-1].click()\n wait()\n exes = driver.find_elements_by_class_name('fa-times')\n if (len(exes) >= num_of_menu_items):\n return \"Error: menu didn't delete\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\n\ndef add_menu():\n \"\"\"\n Adds a menu item (from persistent menu page)\n \"\"\"\n try:\n plus = driver.find_element_by_class_name('fa-plus')\n exes = driver.find_elements_by_class_name('fa-times')\n num_of_menu_items = len(exes)\n plus.click()\n wait()\n pluses = driver.find_elements_by_class_name('fa-plus')\n exes = driver.find_elements_by_class_name('fa-times')\n if (len(exes) <= num_of_menu_items):\n return \"Error: menu didn't add\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef send_broadcast_templates():\n \"\"\"\n Sends all broadcast templates\n \"\"\"\n try:\n templates = driver.find_element_by_class_name('m-widget4')\n template_buttons = templates.find_elements_by_class_name('m-btn')\n for i in range(len(template_buttons)):\n templates = driver.find_element_by_class_name('m-widget4')\n button = templates.find_elements_by_class_name('m-btn')[i]\n button.click()\n wait()\n click_on('next')\n click_on('send')\n if verify_alert() == \"Success\":\n driver.execute_script(\"window.history.go(-1)\")\n wait()\n else:\n return \"Error: broadcast didn't send\"\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef press_tab(times_to_press=\"1\"):\n \"\"\"\n Presses tab the specified number of times\n Keyword Arguments:\n -----------------\n times_to_press (string): number of times to press tab (default '1')\n \"\"\"\n try:\n for i in range(int(times_to_press)):\n focused_element = driver.switch_to.active_element\n focused_element.send_keys(Keys.TAB)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\n\n\ndef click_on(name, scope=driver):\n \"\"\"\n Clicks on the element with specified text.\n Preference is in the following order: anchor links, buttons, input placeholders, and then remaining element from the top of the page\n Parameters:\n ----------\n name (string) : the text of what to click on\n\n Keyword Arguments\n -----------------\n scope (WebElement): which element to search inside (default driver which is the entire page)\n \"\"\"\n try:\n #print('click_on')\n name = name.lower().strip()\n links = scope.find_elements_by_xpath(\".//a[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]\" % (name))\n for element in links:\n if element.is_displayed():\n try:\n element.click()\n except:\n driver.execute_script(\"arguments[0].click();\", element)\n #element.click()\n #print(element.text)\n wait()\n #print(\"Link\")\n return \"Success\"\n \n buttons = scope.find_elements_by_xpath(\".//button[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]\" % (name))\n for element in buttons:\n if element.is_displayed():\n try:\n element.click()\n except:\n driver.execute_script(\"arguments[0].click();\", element)\n #element.click()\n #print(element.text)\n wait()\n #print(\"Button\")\n return \"Success\"\n\n inputs = scope.find_elements_by_xpath(\".//input[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s') or contains(translate(@placeholder, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s') or contains(translate(@value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]\" % (name, name, name))\n for element in inputs:\n if element.is_displayed():\n try:\n element.click()\n except:\n driver.execute_script(\"arguments[0].click();\", element)\n #element.click()\n #print(element.text)\n wait()\n #print(\"Input\")\n return \"Success\"\n \n remaining_elements = scope.find_elements_by_xpath(\".//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s') or contains(translate(@placeholder, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s') or contains(translate(@value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '%s')]\" % (name, name, name))\n for element in remaining_elements:\n if element.is_displayed():\n try:\n element.click()\n except:\n driver.execute_script(\"arguments[0].click();\", element)\n #element.click()\n #print(element.text)\n wait()\n #print(\"Remaining\")\n return \"Success\"\n if len(remaining_elements) == 0:\n wait()\n return \"Error: no element with text '\" + name +\"' found\"\n except Exception as e:\n wait()\n return \"Error: \" + str(e)\n return \"Error: no element with text '\" + name +\"' found\"\n\ndef clear_field():\n \"\"\"\n Clears the content from the currently focused input field\n \"\"\"\n try:\n focused_element = driver.switch_to.active_element\n focused_element.clear()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef click_on_broadcast_title():\n \"\"\"\n Clicks on the edit broadcast title icon\n \"\"\"\n try:\n title = driver.find_element_by_id('convoTitle')\n title.click()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef press_enter():\n \"\"\"\n Presses enter on the currently focused element\n \"\"\"\n try:\n focused_element = driver.switch_to.active_element\n focused_element.send_keys(Keys.ENTER)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef logout():\n \"\"\"\n Logs out the currently logged in user\n \"\"\"\n try:\n user_pic = driver.find_element_by_class_name('m-topbar__userpic')\n user_pic.click()\n wait()\n click_on('Logout')\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\n\ndef sidebar_hamburger():\n \"\"\"\n Clicks on the collapse/expand icon at the top of the sidebar\n \"\"\"\n try:\n collapsed = driver.find_element_by_class_name('m-aside-left--minimize')\n collapsed = True\n except Exception as e:\n collapsed = False\n\n try:\n sidebar_hamburger = driver.find_element_by_id('m_aside_left_minimize_toggle')\n sidebar_hamburger.click()\n wait()\n if collapsed:\n try:\n driver.find_element_by_class_name('m-aside-left--minimize')\n except Exception as e:\n return \"Success\"\n else:\n driver.find_element_by_class_name('m-aside-left--minimize')\n return \"Success\" \n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n \n\ndef sidebar_click(sidebar_item):\n \"\"\"\n Clicks on an element with a certain text in the sidebar\n\n Parameters\n ----------\n sidebar_item (string) : the text of the element to click on\n \"\"\"\n #print('sidebar_click')\n sidebar = driver.find_element_by_class_name('m-menu__nav')\n return click_on(sidebar_item, scope=sidebar)\n\ndef write(text):\n \"\"\"\n writes text on the currently selected element\n\n Parameters\n ----------\n text (string): the text to write\n \"\"\"\n try:\n focused_element = driver.switch_to.active_element\n focused_element.send_keys(text)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef choose_select(select_label, select_item=None):\n \"\"\"\n Clicks on the select element with a certain label and selects a certain option from the select dropdown\n\n Parameters:\n ----------\n select_label (string): the label associated with the select element\n\n Keyword Arguments:\n -----------------\n select_item (string): the option inside the select dropdown (default will select first item)\n \"\"\"\n try:\n if select_item is not None:\n label = driver.find_element_by_xpath(\"//*[contains(text(), '%s')]\" % select_label)\n label_parent = label.find_element_by_xpath(\"..\")\n select = label_parent.find_element_by_tag_name('select')\n select.click()\n click_on(select_item, scope=select)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef broadcast_upload(type, component_number=None):\n \"\"\"\n Uploads a file to particular broadcast component (in broadcast creation)\n\n Keyword Arguments:\n -----------------\n component_number (string): the component number (from top to bottom starting from 1)\n \"\"\"\n try:\n broadcast_components = driver.find_elements_by_class_name('broadcast-component')\n if component_number == None:\n component_number = len(broadcast_components)-1\n else:\n component_number = int(component_number)-1\n component = broadcast_components[component_number]\n while not component.is_displayed() and component_number >= 0:\n component_number -= 1\n component = broadcast_components[component_number]\n return upload(type, scope=component)\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef gallery_upload(page_number=None):\n \"\"\"\n Uploads a file to a particular page in a gallery component (in broadcast creation)\n\n Keyword Arguments:\n -----------------\n page_number (string) : the page number which to upload a file\n \"\"\"\n try:\n if page_number == None:\n pages = driver.find_elements_by_xpath('//div[@data-index]')\n page_number = len(pages)\n else:\n page_number = int(page_number)\n page_number = int(page_number)\n component = driver.find_element_by_xpath('//div[@data-index=%d]' % (page_number-1))\n return upload('image', scope=component)\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef upload(type, wait_time=10, scope=driver):\n \"\"\"\n Uploads a file to the first file input component on the page\n\n Parameters:\n ----------\n type (string) : can be 'image', 'audio', 'video', 'file'\n\n Keyword Arguments:\n -----------------\n wait_time (int): number of seconds to wait after hitting upload (default 10 seconds)\n scope (WebElement): which element to search inside (default driver which is the entire page)\n \"\"\"\n try:\n attachment = scope.find_element_by_xpath('.//input[@type=\"file\"]')\n if type == 'image':\n attachment.send_keys(os.getcwd()+\"/Uploads/sample.jpg\")\n elif type == 'audio':\n attachment.send_keys(os.getcwd()+\"/Uploads/sample.mp3\")\n elif type == 'video':\n attachment.send_keys(os.getcwd()+\"/Uploads/sample.mp4\")\n wait(wait_time)\n elif type == 'file':\n attachment.send_keys(os.getcwd()+\"/Uploads/sample.pdf\")\n wait(wait_time)\n except Exception as e:\n return \"Error: \" + str(e)\n\n return \"Success\"\n\ndef remove_broadcast_component(component_number=None):\n \"\"\"\n Removes a particular broadcast component\n Keyword Arguments:\n -----------------\n component_number (string): the component number (from top to bottom starting from 1)\n \"\"\"\n try:\n if component_number == None:\n broadcast_components = driver.find_elements_by_class_name('broadcast-component')\n component_number = len(broadcast_components)-1\n else:\n component_number = int(component_number)-1\n component = broadcast_components[component_number]\n remove = component.find_element_by_class_name('fa-stack')\n remove.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n \ndef click_on_broadcast_component(text, component_number=None):\n \"\"\"\n Clicks on the text of a particular broadcast component\n\n Parameters:\n ----------\n text: the text of which to click on\n\n Keyword Arguments:\n -----------------\n component_number (string): the component number (from top to bottom starting from 1)\n \"\"\"\n try:\n broadcast_components = driver.find_elements_by_class_name('broadcast-component')\n if component_number == None:\n component_number = len(broadcast_components)-1\n else:\n component_number = int(component_number)-1\n component = broadcast_components[component_number]\n while not component.is_displayed() and component_number >= 0:\n component_number -= 1\n component = broadcast_components[component_number]\n return click_on(text, scope=component)\n \n except Exception as e:\n return \"Error: \" + str(e)\n\n\n\ndef add_broadcast_component(component_name):\n \"\"\"\n add broadcast component of a particular type\n\n Parameters:\n ----------\n component_name (string): the content type to add (e.g text, image, card, etc.)\n \"\"\"\n try:\n click_on(component_name)\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef gallery_next():\n \"\"\"\n Goes to the next page of the gallery component\n \"\"\"\n try:\n next = driver.find_element_by_class_name('slick-next')\n next.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef gallery_prev():\n \"\"\"\n Goes to the previous page of the gallery component\n \"\"\"\n try:\n prev = driver.find_element_by_class_name('slick-prev')\n prev.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef select_emoji():\n \"\"\"Selects an emoji and puts it in the input box (Live Chat)\"\"\"\n Selects\n try:\n emoji_icon = driver.find_element_by_xpath('//*[@id=\"content\"]/div/div/div/div[2]/div/div/div[2]/div[3]/div/div/div/div/div[5]/div[3]')\n emoji_icon.click()\n emojis = driver.find_elements_by_class_name('emoji-mart-emoji')\n emojis[0].click()\n click_on('type here')\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef send_sticker():\n \"\"\"Sends the first sticker in the sticker menu\"\"\" \n try:\n sticker_icon = driver.find_element_by_xpath('//*[@data-tip=\"stickers\"]')\n sticker_icon.click()\n wait(wait_time=10)\n sticker_pack = driver.find_element_by_class_name('sticker-pack')\n stickers = sticker_pack.find_elements_by_class_name('sticker')\n src = stickers[0].get_attribute('src')\n sticker_ID = src[src.index('sticker/') + len('sticker/'):]\n sticker_ID = sticker_ID[:sticker_ID.index('_')]\n stickers[0].click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n if verify_sticker_sent(sticker_ID):\n return \"Success\"\n else:\n return \"Error: sticker wasn't sent\"\n\ndef remove_autoposting():\n \"\"\"Removes the first autoposting channel\"\"\"\n try:\n autopost_delete = driver.find_element_by_class_name('btn-outline-danger')\n autopost_delete.click()\n click_on('delete')\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef autopost_settings():\n \"\"\"Clicks on the edit settings of the first autoposting channel\"\"\"\n try:\n autopost_settings = driver.find_element_by_class_name('btn-outline-brand')\n autopost_settings.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef verify_GIF_sent(gif_ID):\n \"\"\"\n Verifies whether the GIF was sent\n\n Parameters:\n ----------\n gid_ID: the id of the GIF\n \"\"\"\n try:\n messages = driver.find_elements_by_class_name('m-messenger__message-content')\n gif = messages[-1].find_element_by_tag_name('img')\n src = gif.get_attribute('src')\n actual_gif_ID = src[src.index('media/') + len('media/'):]\n actual_gif_ID = actual_gif_ID[:actual_gif_ID.index('/')]\n #print(gif_ID)\n #print(actual_gif_ID)\n return gif_ID == actual_gif_ID\n except Exception as e:\n #print(str(e))\n return False\n\ndef verify_sticker_sent(sticker_ID):\n \"\"\"\n Verifies whether the sticker was sent\n\n Parameters:\n ----------\n gid_ID: the id of the sticker\n \"\"\"\n try:\n messages = driver.find_elements_by_class_name('m-messenger__message-content')\n sticker = messages[-1].find_element_by_tag_name('img')\n src = sticker.get_attribute('src')\n actual_sticker_ID = src[src.index('sticker/') + len('sticker/'):]\n actual_sticker_ID = actual_sticker_ID[:actual_sticker_ID.index('_')]\n # print(sticker_ID)\n # print(actual_sticker_ID)\n return sticker_ID == actual_sticker_ID\n except Exception as e:\n #print(str(e))\n return False\n\n\ndef send_GIF():\n \"\"\"\n Sends a GIF (Live Chat)\n \"\"\"\n try:\n gif_icon = driver.find_element_by_xpath('//*[@data-tip=\"GIF\"]')\n gif_icon.click()\n wait(wait_time=10)\n gifs = driver.find_elements_by_class_name('giphy-gif')\n src = gifs[0].get_attribute('src')\n gif_ID = src[src.index('media/') + len('media/'):]\n gif_ID = gif_ID[:gif_ID.index('/')]\n gifs[0].click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n if verify_GIF_sent(gif_ID):\n return \"Success\"\n else:\n return \"Error: GIF wasn't sent\"\n\ndef close_browser():\n \"\"\"\n Closes the currently running browser\n \"\"\"\n driver.close()\n\ndef verify_table(scope=driver):\n \"\"\"\n Verifies if the table element has entries\n\n Keyword Arguments:\n -----------------\n scope (WebElement): which element to search inside (default driver which is the entire page)\n \"\"\"\n try:\n table = scope.find_element_by_tag_name('table')\n entries = table.find_elements_by_class_name('m-datatable__row--even')\n if len(entries) > 0:\n return \"Success\"\n else:\n return \"Error: No table entries\"\n except Exception as e:\n return \"Error: \" + str(e)\n\ndef num_of_broadcast_components():\n \"\"\"\n Returns the number of broadcast components currently being used\n \"\"\"\n try:\n broadcast_components = driver.find_elements_by_class_name('broadcast-component')\n return len(broadcast_components)\n except Exception as e:\n return \"No Broadcast components\"\n\ndef verify_alert():\n \"\"\"\n Checks if a successful alert is being shown\n \"\"\"\n try:\n success_alert = driver.find_element_by_xpath('//*[@class=\"css-rr2n0f\" or @class=\"toast-title\" or @class=\"alert-success\"]')\n if (success_alert.is_displayed()):\n #wait(7)\n return \"Success\"\n else:\n return \"No Alert detected\"\n except Exception as e:\n return \"No Alert detected\"\n\ndef verify_failure():\n \"\"\"\n Checks if a failure alert is being shown\n \"\"\"\n try:\n failure_alert = driver.find_element_by_class_name('css-1f1jd2h')\n if (failure_alert.is_displayed()):\n return \"Success\"\n else:\n return \"No Failure Alert\"\n except Exception as e:\n return \"No Failure Alert\"\n\n\ndef download_phone_csv():\n \"\"\"\n Downloads csv of phone numbers (in Invite using Phone Numebers)\n \"\"\"\n try:\n csv = driver.find_element_by_xpath('//*[@class=\"fa-download\"]')\n csv.click()\n wait(wait_time=10)\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef download_opdashboard_csv():\n \"\"\"\n Downloads csv of users (in Operational Dashboard)\n \"\"\"\n try:\n csv = driver.find_element_by_xpath('//*[@id=\"content\"]/div/div/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div[2]/div[2]')\n csv.click()\n wait(wait_time=10)\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\ndef send_thumbs_up():\n \"\"\"\n Sends a thumbs up in Live Chat\n \"\"\"\n try:\n thumbs_up = driver.find_element_by_class_name('la-thumbs-o-up')\n thumbs_up.click()\n wait()\n except Exception as e:\n return \"Error: \" + str(e)\n return \"Success\"\n\n\n\nif __name__ == \"__main__\":\n try:\n print(open_kibopush())\n print(login(domain='www.kibopush.com', user='mike_vrhkeqg_repeatuser@tfbnw.net', pw='kibo54321'))\n print(sidebar_click('polls'))\n print(click_on('send'))\n print(verify_alert())\n print(click_on('send'))\n print(verify_alert())\n #print(remove_autoposting())\n #print(select_emoji())\n finally:\n close_browser()\n\n\n","sub_path":"utils/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":30496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"170792221","text":"import numpy as np\nimport cv2\nimport os\nimport random\n\nimport tensorflow as tf\n\n\nclass Data(object):\n\n def __init__(self, dataset_dir, height, weight):\n self.dataset_dir = dataset_dir\n self.resize_h = height\n self.resize_w = weight\n\n self.cls = []\n self.label_to_index = {}\n self.cls_start_step = {}\n self.images, self.labels = self._prepare_data()\n\n\n def _prepare_data(self):\n classes = os.listdir(self.dataset_dir)\n classes.sort()\n tf.logging.info(\"classes: %s\", classes)\n\n labels_index = {}\n for index, cls in enumerate(classes):\n labels_index[cls] = index\n self.cls.append(index)\n self.label_to_index[index] = cls\n self.cls_start_step[index] = 0\n\n images = {}\n labels = {}\n for cls in classes:\n cls_images = []\n cls_labels = []\n l_train_path = os.path.join(self.dataset_dir, cls, 'train')\n imgs = os.listdir(l_train_path)\n # self.cls_data_size[cls] = len(imgs)\n # imgs.sort()\n for img in imgs:\n views_path = os.path.join(l_train_path, img)\n views = os.listdir(views_path)\n vp_lst = []\n # ls = []\n for v in views:\n v_path = os.path.join(views_path, v)\n vp_lst.append(v_path)\n # ls.append(cls)\n\n cls_images.append(vp_lst)\n cls_labels.append(labels_index[cls])\n\n images[labels_index[cls]] = cls_images\n labels[labels_index[cls]] = cls_labels\n\n return images, labels\n\n\n def shuffle_all(self):\n for key, value in self.images.items():\n combined = list(zip(self.images[key], self.labels[key]))\n random.shuffle(combined)\n self.images[key], self.labels[key] = zip(*combined)\n\n\n def _shuffle(self, selected):\n combined = list(zip(self.images[selected], self.labels[selected]))\n random.shuffle(combined)\n self.images[selected], self.labels[selected] = zip(*combined)\n\n\n def _parse_function(self, selected, start, end):\n images = []\n # labels = []\n batch = self.images[selected][start:end]\n for idx, views_path in enumerate(batch):\n # views_path.sort()\n views = []\n for view in views_path:\n image_string = tf.read_file(view)\n # image_decoded = tf.image.decode_png(image_string, channels=3)\n image_decoded = tf.image.decode_png(image_string, channels=3)\n # cropped_image = tf.image.central_crop(image_decoded, 0.7)\n # rotated_image = tf.image.rot90(image_decoded, 1)\n resized_image = tf.image.resize_images(image_decoded, [self.resize_h, self.resize_w])\n # image = tf.cast(image_decoded, tf.float32)\n # image = tf.image.convert_image_dtype(resized_image, dtype=tf.float32)\n # Finally, rescale to [-1,1] instead of [0, 1)\n # image = tf.subtract(image, 0.5)\n # image = tf.multiply(image, 2.0)\n views.append(resized_image)\n\n images.append(views)\n\n # labels = tf.convert_to_tensor(self.labels[start:end], dtype=tf.string)\n labels = self.labels[selected][start:end]\n\n return tf.stack(images, 0), labels\n\n\n def next_batch(self, batch_size):\n selected = random.choice(self.cls)\n\n start = self.cls_start_step[selected]\n end = start + batch_size\n if end > self.data_size(selected):\n self._shuffle(selected)\n start = 0\n end = start + batch_size\n self.cls_start_step[selected] = end\n\n batch_x, batch_y = self._parse_function(selected, start, end)\n\n return batch_x, batch_y\n\n\n def size(self):\n sum = 0\n for idx, _ in enumerate(self.cls):\n num = len(self.images[idx])\n sum += num\n\n return sum / len(self.cls)\n\n\n def data_size(self, selected):\n return len(self.images[selected])\n\n\n def get_label_to_index(self):\n return self.label_to_index\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298782415","text":"import lxml\nimport lxml.html\nimport re\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef extract_size(title):\n box_re = re.compile(\n '.*; bbox (?P\\d+) (?P\\d+) (?P\\d+) (?P\\d+);.*'\n )\n width = None\n height = None\n matched_obj = re.match(box_re, title)\n if matched_obj:\n width = int(matched_obj['x2'])\n height = int(matched_obj['y2'])\n\n return width, height\n\n\nclass OcrxWord:\n def __init__(self, el_class, el_id, title, text=''):\n \"\"\"\n span_elem is item from array returnd by lxml.html's xpath\n method\n \"\"\"\n self.el_class = el_class\n self.el_id = el_id\n self.title = title\n self.text = text\n self.x1 = 0\n self.x2 = 0\n self.y1 = 0\n self.y2 = 0\n self.wconf = 0\n self.build_bbox_attrs(self.title)\n\n def build_bbox_attrs(self, title):\n \"\"\"\n build x1, x2, y1, y2 and wconf attribues from title string.\n\n Example of title strings:\n\n 'bbox 102 448 120 457; x_wconf 38'\n \"\"\"\n box_re = re.compile(\n 'bbox (?P\\d+) (?P\\d+) (?P\\d+) (?P\\d+); x_wconf (?P\\d+)'\n )\n matched_obj = re.match(box_re, title)\n if matched_obj:\n self.x1 = int(matched_obj['x1'])\n self.y1 = int(matched_obj['y1'])\n self.x2 = int(matched_obj['x2'])\n self.y2 = int(matched_obj['y2'])\n self.wconf = int(matched_obj['wconf'])\n else:\n logger.info(\n f\"Word title mismatch.title={self.title}, el_id={self.el_id}.\"\n )\n\n def to_hash(self):\n \"\"\"\n returns hash structure from OcrxWord attributes.\n \"\"\"\n return {\n 'x1': self.x1,\n 'y1': self.y1,\n 'x2': self.x2,\n 'y2': self.y2,\n 'wconf': self.wconf,\n 'id': self.el_id,\n 'title': self.title,\n 'text': self.text,\n 'class': self.el_class\n }\n\n\nclass Hocr:\n \"\"\"Manages ocrx words from hocr file.\n \"\"\"\n\n def __init__(self, hocr_file_path, min_wconf=30):\n self.hocr_file_path = hocr_file_path\n self.ocrx_words = []\n self.min_wconf = min_wconf\n self._width = 0\n self._height = 0\n try:\n self.extract()\n except lxml.etree.ParserError:\n logger.warning(\n f\"Hocr file {hocr_file_path}\"\n \" is either empty of not of HOCR format\"\n )\n\n @property\n def width(self):\n return self._width\n\n @property\n def height(self):\n return self._height\n\n def extract(self):\n html = None\n\n with open(self.hocr_file_path, \"rb\") as f:\n text = f.read()\n html = lxml.html.fromstring(text)\n\n page = html.xpath(\"//div[@class='ocr_page']\")\n if len(page) > 0:\n self._width, self._height = extract_size(\n page[0].attrib['title']\n )\n\n for span in html.xpath(\"//span[@class='ocrx_word']\"):\n elem = OcrxWord(\n el_class=span.attrib['class'],\n el_id=span.attrib['id'],\n title=span.attrib['title'],\n text=span.text\n )\n self.ocrx_words.append(elem)\n\n return self.ocrx_words\n\n def good_json_words(self):\n \"\"\"Return only:\n * ocrx words with non empty text\n * ocrx words with w_conf > min_w_conf\n \"\"\"\n meta = self._filter_words()\n return meta['good_words']\n\n def _filter_words(self):\n meta = {}\n meta['count_all'] = len(self.ocrx_words)\n meta['bad_words'] = []\n meta['good_words'] = []\n meta['count_non_empty'] = 0\n meta['count_low_wconf'] = 0\n meta['width'] = self.width\n meta['height'] = self.height\n meta['min_wconf'] = self.min_wconf\n\n for word in self.ocrx_words:\n bad_word = False\n if word.text and len(word.text) == 0:\n bad_word = True\n meta['bad_words'].append(word.to_hash())\n meta['count_non_empty'] += 1\n\n if word.wconf < self.min_wconf:\n bad_word = True\n meta['bad_words'].append(word.to_hash())\n meta['count_low_wconf'] += 1\n\n if not bad_word:\n meta['good_words'].append(word.to_hash())\n\n meta['count_bad'] = len(meta['bad_words'])\n meta['count_good'] = len(meta['good_words'])\n\n return meta\n\n def get_meta(self):\n meta = self._filter_words()\n\n return {\n 'width': meta['width'],\n 'height': meta['height'],\n 'count_all': meta['count_all'],\n 'count_bad': meta['count_bad'],\n 'count_good': meta['count_good'],\n 'count_non_empty': meta['count_non_empty'],\n 'count_low_wconf': meta['count_low_wconf'],\n 'bad_words': meta['bad_words'],\n 'min_wconf': meta['min_wconf']\n }\n","sub_path":"papermerge/core/lib/hocr.py","file_name":"hocr.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"489885993","text":"n = int(input(\"Digite um número inteiro: \"))\n\ntamanho = len(str(n))\n\ni = 0\ntotal = 0\nwhile i < tamanho:\n singleNum = n % 10\n total += singleNum\n n = n // 10\n i += 1\n \nprint(total)","sub_path":"AulasPython/Parte1/Semana4/soma_digitos.py","file_name":"soma_digitos.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"118767429","text":"from unittest import TestCase\nimport itertools\n\nimport torch\nimport torch.nn as nn\n\nimport geotorch.parametrize as P\nfrom geotorch.lowrank import LowRank\nfrom geotorch.fixedrank import FixedRank\n\n\nclass TestLowRank(TestCase):\n def assertIsOrthogonal(self, X):\n if X.size(-2) < X.size(-1):\n X = X.transpose(-2, -1)\n Id = torch.eye(X.size(-1))\n if X.dim() > 2:\n Id = Id.repeat(*(X.size()[:-2] + (1, 1)))\n norm = torch.norm(X.transpose(-2, -1) @ X - Id, dim=(-2, -1))\n self.assertTrue((norm < 1e-3).all())\n\n def vector_error(self, X, Y):\n # Error relative to the size in infinity norm\n X_inf = X.abs().max(dim=-1).values\n abs_error = (Y - X).abs().max(dim=-1).values\n error = abs_error / X_inf\n # Unless X is very small, if so we do absolute error\n small = X_inf < 1e-5\n error[small] = abs_error[small]\n return error\n\n def assertHasSingularValues(self, X, S_orig):\n _, S, _ = torch.svd(X)\n # Sort the singular values from our parametrization\n S_orig = torch.sort(torch.abs(S_orig), descending=True).values\n # Add the missign dimensions\n batch_dim = S.size()[:-1]\n pad_dim = batch_dim + (S.size(-1) - S_orig.size(-1),)\n S_orig = torch.cat([S_orig, torch.zeros(pad_dim)], dim=-1)\n\n error = self.vector_error(S_orig, S)\n self.assertTrue((error < 1e-3).all())\n\n def test_lowrank(self):\n sizes = [\n (8, 1),\n (8, 4),\n (8, 8),\n (7, 1),\n (7, 3),\n (7, 4),\n (7, 7),\n (1, 7),\n (2, 7),\n (1, 8),\n (2, 8),\n (1, 1),\n (2, 1),\n (1, 2),\n ]\n\n rs = [1, 3, 8]\n\n with torch.random.fork_rng(devices=range(torch.cuda.device_count())):\n torch.random.manual_seed(8888)\n for cls in [FixedRank, LowRank]:\n for (n, k), r in itertools.product(sizes, rs):\n for layer in [nn.Linear(n, k), nn.Conv2d(n, 4, k)]:\n print(\n \"{}({}, {}, {}) on {}\".format(\n cls.__name__, n, k, r, str(layer)\n )\n )\n r = min(n, k, r)\n M = cls(size=layer.weight.size(), rank=r)\n P.register_parametrization(layer, \"weight\", M)\n self.assertTrue(P.is_parametrized(layer, \"weight\"))\n U_orig, S_orig, V_orig = M.original\n if cls == FixedRank:\n # Apply f, as S_orig is just the unconstrained vector in R^n\n S_orig = M.f(S_orig)\n self.assertIsOrthogonal(U_orig)\n self.assertIsOrthogonal(V_orig)\n self.assertHasSingularValues(layer.weight, S_orig)\n\n optim = torch.optim.SGD(layer.parameters(), lr=0.1)\n if isinstance(layer, nn.Linear):\n input_ = torch.rand(5, n)\n elif isinstance(layer, nn.Conv2d):\n # batch x in_channel x in_length x in_width\n input_ = torch.rand(6, n, 9, 8)\n\n for i in range(2):\n print(i)\n loss = layer(input_).sum()\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n U_orig, S_orig, V_orig = M.original\n if cls == FixedRank:\n # Apply f, as S_orig is just the unconstrained vector in R^n\n S_orig = M.f(S_orig)\n self.assertIsOrthogonal(U_orig)\n self.assertIsOrthogonal(V_orig)\n self.assertHasSingularValues(layer.weight, S_orig)\n\n # Test update_base\n prev_out = layer(input_)\n layer.parametrizations.weight.update_base()\n new_out = layer(input_)\n self.assertAlmostEqual(\n torch.norm(prev_out - new_out).abs().max().item(),\n 0.0,\n places=3,\n )\n\n def test_lowrank_errors(self):\n # rank always has to be <= min(n, k)\n for cls in [LowRank, FixedRank]:\n with self.assertRaises(ValueError):\n cls(size=(4, 3), rank=5)\n with self.assertRaises(ValueError):\n cls(size=(2, 3), rank=3)\n # Try to instantiate it in a vector rather than a matrix\n with self.assertRaises(ValueError):\n cls(size=(5,), rank=1)\n\n # On a non-callable\n with self.assertRaises(ValueError):\n FixedRank(size=(5, 3), rank=2, f=3)\n # On the wrong string\n with self.assertRaises(ValueError):\n FixedRank(size=(5, 3), rank=2, f=\"wrong\")\n","sub_path":"test/test_lowrank.py","file_name":"test_lowrank.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631565337","text":"# Read a row, if it is in the questionId, answerId thingy print it\nimport lxml.etree\nimport sys\n\ndef row_to_id(row_string):\n try:\n # print(row_string)\n elem = lxml.etree.fromstring(row_string)\n return elem.get('Id')\n except:\n return \"\"\n\ndef read_required_ids(filepath=\"./qaIds.txt\"):\n ids = []\n with open(filepath) as fp:\n ids = [line.strip() for line in fp.readlines()]\n return ids\n\nids = read_required_ids()\n# print(\"Read the ids\")\nrow = input()\n# print(\"Read rows\")\nwhile row:\n id_ = row_to_id(row.strip())\n # print(f'Got id:', id_)\n if id_ in ids:\n print(row.strip())\n row = input()\n\n","sub_path":"matching_row.py","file_name":"matching_row.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488375949","text":"class Node:\r\n\tdef __init__(self, key=None):\r\n\t\tself.key = key\r\n\t\tself.next = None\r\n\tdef __str__(self):\r\n\t\treturn str(self.key)\r\n\t\r\nclass SinglyLinkedList:\r\n\tdef __init__(self):\r\n\t\tself.head = None\r\n\t\tself.size = 0\r\n\t\r\n\tdef __len__(self):\r\n\t\treturn self.size\r\n\t\r\n\tdef __iter__(self):\r\n\t\tv = self.head\r\n\t\twhile v is not None:\r\n\t\t\tyield v\r\n\t\t\tv = v.next\r\n\t\r\n\tdef printList(self): # 변경없이 사용할 것!\r\n\t\tv = self.head\r\n\t\twhile(v):\r\n\t\t\tprint(v.key, \"->\", end=\" \")\r\n\t\t\tv = v.next\r\n\t\tprint(\"None\")\r\n\t\t\r\n\r\n\tdef pushFront(self, key):\r\n\t\tv = Node(key)\r\n\t\tv.next =self.head\r\n\t\tself.head = v\r\n\t\tself.size += 1\r\n\r\n\tdef pushBack(self, key):\r\n\t\tv = Node(key)\r\n\t\tif len(self) == 0:\r\n\t\t\tself.head = v\r\n\t\telse:\r\n\t\t\ttail = self.head\r\n\t\t\twhile tail.next is not None:\r\n\t\t\t\ttail = tail.next\r\n\t\t\ttail.next = v\r\n\t\tself.size += 1\r\n\r\n\tdef popFront(self):\r\n\t\t# head 노드의 값 리턴. empty list이면 None 리턴\r\n\t\tif len(self) == 0:\r\n\t\t\treturn None\r\n\t\telse:\r\n\t\t\tx = self.head\r\n\t\t\tkey = x.key\r\n\t\t\tself.head = x.next\r\n\t\t\tself.size -= 1\r\n\t\t\tdel x\r\n\t\t\treturn key\r\n\r\n\tdef popBack(self):\r\n\t\t# tail 노드의 값 리턴. empty list이면 None 리턴\r\n\t\tif len(self) == 0:\r\n\t\t\treturn None\r\n\t\telse: \r\n\t\t\tprev = None\r\n\t\t\ttail = self.head\r\n\t\t\twhile tail.next != None:\r\n\t\t\t\tprev = tail\r\n\t\t\t\ttail = tail.next\r\n\t\t\tif len(self) == 1:\r\n\t\t\t\tself.head = None\r\n\t\t\telse:\r\n\t\t\t\tprev.next = tail.next\r\n\t\t\tkey = tail.key\r\n\t\t\tdel tail\r\n\t\t\tself.size -= 1\r\n\t\t\treturn key\r\n\r\n\tdef search(self, key):\r\n\t\t# key 값을 저장된 노드 리턴. 없으면 None 리턴\r\n\t\tv = self.head\r\n\t\twhile v:\r\n\t\t\tif v.key == key:\r\n\t\t\t\treturn v\r\n\t\t\tv = v.next\r\n\t\treturn None\r\n\r\n\tdef remove(self, x):\r\n\t\t# 노드 x를 제거한 후 True리턴. 제거 실패면 False 리턴\r\n\t\t# x는 key 값이 아니라 노드임에 유의!\r\n\t\tv = self.head\r\n\t\tprev = None\r\n\t\tif x == None:\r\n\t\t\treturn False\r\n\t\telif x == self.head:\r\n\t\t\tself.head = v.next\r\n\t\t\tself.size -= 1\r\n\t\t\treturn True\r\n\t\twhile v:\r\n\t\t\tif v.next == x:\r\n\t\t\t\tv.next = x.next\r\n\t\t\t\tself.size -= 1\r\n\t\t\t\treturn True\r\n\t\t\tv = v.next\r\n\r\n\tdef sizeOfList(self):\r\n\t\treturn self.size","sub_path":"SinglyLinkedList/SinglyLinkedList.py","file_name":"SinglyLinkedList.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"399214430","text":"import sys\nfrom stub_final import *\nfrom optparse import OptionParser\nimport numpy as np\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n\n usage = \"Usage: %prog -m method -e epsilon_modify -g gravity_inf(pass -h for more info)\"\n parser = OptionParser(usage)\n\n parser.add_option(\"-m\", \"--method\", dest=\"method\",\n help=\"The method we use for RL, choose between SARSA and Q_Learning\")\n parser.add_option(\"-e\", \"--epsilon_modify\", dest=\"epsilon_modify\",\n help=\"Indicator to choose whether we use the epsilon modified method, input True or False\")\n parser.add_option(\"-g\", \"--gravity_inference\", dest=\"gravity_inf\",\n help=\"Indicator to choose whether we consider gravity inference, input True or False\")\n\n (options, args) = parser.parse_args(argv[1:])\n\n if options.method == \"Q_learning\" and options.epsilon_modify == 'False' and options.gravity_inf == 'False':\n agent = Learner(method = \"Q_learning\", e_greedy= False, gravity_inf = False)\n hist_q = []\n run_games(agent, hist_q, 400, 1)\n np.save('hist_q',np.array(hist_q))\n\n elif options.method == \"Q_learning\" and options.epsilon_modify == 'True' and options.gravity_inf == 'False':\n agent = Learner(method = \"Q_learning\", e_greedy= True, gravity_inf = False)\n hist_q_e = []\n run_games(agent, hist_q_e, 400, 1)\n np.save('hist_q_e',np.array(hist_q_e))\n\n elif options.method == \"Q_learning\" and options.epsilon_modify == 'True' and options.gravity_inf == 'True':\n agent = Learner(method = \"Q_learning\", e_greedy= True, gravity_inf = True)\n hist_q_e_g = []\n run_games(agent, hist_q_e_g, 400, 1)\n np.save('hist_q_e_g',np.array(hist_q_e_g))\n\n elif options.method == \"SARSA\" and options.epsilon_modify == 'False' and options.gravity_inf == 'False':\n agent = Learner(method = \"SARSA\", e_greedy= False, gravity_inf = False)\n hist_s = []\n run_games(agent, hist_s, 400, 1)\n np.save('hist_s',np.array(hist_s))\n\n elif options.method == \"SARSA\" and options.epsilon_modify == 'True' and options.gravity_inf == 'False':\n agent = Learner(method = \"SARSA\", e_greedy= True, gravity_inf = False)\n hist_s_e = []\n run_games(agent, hist_s_e, 400, 1)\n np.save('hist_s_e',np.array(hist_s_e))\n\n elif options.method == \"SARSA\" and options.epsilon_modify == 'True' and options.gravity_inf == 'True':\n agent = Learner(method = \"Q_learning\", e_greedy= True, gravity_inf = True)\n hist_q_e_g = []\n run_games(agent, hist_q_e_g, 400, 1)\n np.save('hist_q_e_g',np.array(hist_q_e_g))\n\n else:\n agent = Learner()\n hist = []\n run_games(agent, hist, 400, 1)\n np.save('hist',np.array(hist))\n\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n ","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"319236143","text":"# [START imports]\nimport endpoints\nfrom protorpc import message_types\nfrom protorpc import messages\nfrom protorpc import remote\n\nfrom secret import secret\n# [END imports]\n\n\n# [START messages]\nclass __apiclass__Request(messages.Message):\n content = messages.StringField(1)\n\n\nclass __apiclass__Response(messages.Message):\n \"\"\"A proto Message that contains a simple string field.\"\"\"\n content = messages.StringField(1)\n\n\nAPI_RESOURCE = endpoints.ResourceContainer(\n __apiclass__Request,\n n=messages.IntegerField(2, default=1))\n# [END messages]\n\n\n# [START __apiname___api]\n@endpoints.api(name='__apiname__', version='v1')\nclass __apiclass__Api(remote.Service):\n\n @endpoints.method(\n # This method takes a ResourceContainer defined above.\n API_RESOURCE,\n # This method returns an __apiclass__ message.\n __apiclass__Response,\n path='__apipath__',\n http_method='POST',\n name='echo')\n def echo(self, request):\n output_content = ' '.join([request.content] * request.n)\n return __apiclass__Response(content=output_content)\n\n @endpoints.method(\n # This method takes an empty request body.\n message_types.VoidMessage,\n # This method returns an __apiclass__ message.\n __apiclass__Response,\n path='__apipath__/getUserEmail',\n http_method='GET',\n allowed_client_ids = [secret.web_client_id],\n # Require auth tokens to have the following scopes to access this API.\n scopes=[endpoints.EMAIL_SCOPE],\n # OAuth2 audiences allowed in incoming tokens.\n audiences=[secret.web_client_id])\n\n def get_user_email(self, request):\n user = endpoints.get_current_user()\n # If there's no user defined, the request was unauthenticated, so we\n # raise 401 Unauthorized.\n if not user:\n raise endpoints.UnauthorizedException\n return __apiclass__Response(content=user.email())\n# [END __apiname___api]\n\n\n# [START api_server]\napi = endpoints.api_server([__apiclass__Api])\n# [END api_server]\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"93588593","text":"from general_utils import execute_command\nfrom general_utils import get_command_output\nfrom general_utils import cleanup_dir\nimport numpy as np\nimport time\n\n\nverbose = False\ndef set_verbose(v):\n global verbose\n verbose = v\n\n\n# GLOG_logtostderr=1 ./rs_cluster -gene_fasta=gene.fa -num_threads=4 -output=clustered.fa -rs_length=60\ndef cluster(transcriptome_reference_file, cluster_output, k, numthreads):\n command = \"rs_cluster -gene_fasta=\" \\\n + transcriptome_reference_file \\\n + \" -num_threads=\" \\\n + str(numthreads) \\\n + \" -output=\" \\\n + cluster_output \\\n + \" -rs_length=\" \\\n + str(k)\n\n execute_command(command, verbose)\n\n\n\n# GLOG_logtostderr=1 ./rs_index -transcript_fasta=clustered.fa -index_file=clustered_gene.fa.pb -rs_length=60 -num_threads 4\ndef build_index(cluster_output, index_file, k, numthreads):\n command = \"rs_index -transcript_fasta=\" \\\n + cluster_output \\\n + \" -index_file=\" \\\n + index_file \\\n + \" -rs_length=\" \\\n + str(k) \\\n + \" -num_threads=\" \\\n + str(numthreads)\n\n execute_command(command, verbose)\n\n\n\n# GLOG_logtostderr=1 ./rs_select -index_file=clustered_gene.fa.pb -selected_keys_file=clustered_gene.fa.sk\ndef select(index_file, selected_keys_file):\n command = \"rs_select -index_file=\" \\\n + index_file \\\n + \" -selected_keys_file=\" \\\n + selected_keys_file\n \n execute_command(command, verbose)\n\n\n# GLOG_logtostderr=1 ./rs_select -index_file=clustered_gene.fa.pb -selected_keys_file=clustered_gene.fa.sk -rs_length=60\ndef select_with_k(index_file, selected_keys_file, k):\n command = \"rs_select -index_file=\" \\\n + index_file \\\n + \" -selected_keys_file=\" \\\n + selected_keys_file \\\n + \" -rs_length=\" \\\n + str(k)\n \n execute_command(command, verbose)\n\n\n# GLOG_logtostderr=1 ../src/rs_count -selected_keys_file=clustered_gene.fa.sk -count_file=clustered_gene.fa.cf -read_files1=../test/test.fastq_1 -read_files2=../test/test.fastq_2 -num_threads=1\ndef count(selected_keys_file, count_file, sample_pair_1, sample_pair_2, numthreads):\n command = \"rs_count -selected_keys_file=\" \\\n + selected_keys_file \\\n + \" -count_file=\" \\\n + count_file \\\n + \" -read_files1=\" \\\n + sample_pair_1 \\\n + \" -read_files2=\" \\\n + sample_pair_2 \\\n + \" -num_threads=\" \\\n + str(numthreads)\n\n execute_command(command, verbose)\n\n\ndef estimate(count_file, estimation_file):\n command = \"rs_estimate -count_file=\" \\\n + count_file\n\n output = get_command_output(command, verbose)\n text_file = open(estimation_file, \"w\")\n text_file.write(str(output))\n text_file.close()\n #print(\"Command Output:\\n\")\n #print(output)\n #print(\"----------------------------\")\n\n\ndef get_result_dict(result_dir): \n matrix = np.genfromtxt(\n result_dir + '/estimation.txt',\n names = None,\n dtype=None,\n delimiter=\"\\t\")\n\n transcripts = [x[0] for x in matrix]\n num_reads = [x[2] for x in matrix]\n\n res = dict()\n\n for i in range(0, len(transcripts)):\n res[transcripts[i]] = num_reads[i]\n #print(result_dir + \": \" + str(len(res)))\n\n return res\n\n\ndef run(k, transcriptome_reference_file, index_dir, sample_dir, output_dir):\n cleanup_dir(index_dir)\n time1 = time.time()\n numthreads = 4\n cluster_output = index_dir + \"/clustered.fa\"\n index_file = index_dir + \"/clustered_gene.fa.pb\"\n selected_keys_file = index_dir + \"/clustered_gene.fa.sk\"\n\n cluster(transcriptome_reference_file, cluster_output, 60, numthreads)\n build_index(cluster_output, index_file, k, numthreads)\n select_with_k(index_file, selected_keys_file, k)\n\n\n res_dict = dict()\n for i in range(1, 11):\n if i < 10:\n sample_pair1 = sample_dir + '/sample_0' + str(i)+ '_1.fasta'\n sample_pair2 = sample_dir + '/sample_0' + str(i) + '_2.fasta'\n else:\n sample_pair1 = sample_dir + '/sample_' + str(i)+ '_1.fasta'\n sample_pair2 = sample_dir + '/sample_' + str(i) + '_2.fasta'\n result_output_dir = output_dir + '/sample' + str(i) + '_result'\n cleanup_dir(result_output_dir)\n count_file = result_output_dir + \"/clustered_gene.fa.cf\"\n estimation_file = result_output_dir + \"/estimation.txt\"\n\n count(selected_keys_file, count_file, sample_pair1, sample_pair2, numthreads)\n estimate(count_file, estimation_file)\n\n sample_dict = get_result_dict(result_output_dir)\n\n for key in sample_dict:\n if i == 1:\n res_dict[key] = sample_dict[key]\n else:\n res_dict[key] += sample_dict[key]\n\n\n for key in res_dict:\n res_dict[key] /= 10\n\n time2 = time.time()\n elapsed_ms = (time2-time1)*1000.0\n \n return res_dict, elapsed_ms\n\n\n# run_RNASkim(60, \"chr22_small.fa\", \"test_results/RNASkim/index\", \"simulated_reads\", \"test_results/RNASkim/results\", 4)\n\n\n\n# get_result_dict(\"/home/ubuntu/cs229/rnaskim\")\n\n\n\n# cluster(\"chr22_first4.fa\", \"RNASkim/src/test_results/clustered.fa\", 60, 4)\n# cluster(\"RNASkim/data/homo_sapiens/current/genes.fa\", \"RNASkim/src/test_results/clustered.fa\", 60, 4)\n# cluster(\"RNASkim/src/test_data/gene_fasta_example.fa\", \"RNASkim/src/test_results/clustered.fa\", 60, 4)\n# build_index(\"RNASkim/src/test_results/clustered.fa\", \"RNASkim/src/test_results/clustered_gene.fa.pb\", 60, 4)\n# select_with_k(\"RNASkim/src/test_results/clustered_gene.fa.pb\", \"RNASkim/src/test_results/clustered_gene.fa.sk\", 60)\n# count(\"RNASkim/src/test_results/clustered_gene.fa.sk\", \"RNASkim/src/test_results/clustered_gene.fa.cf\", \"RNASkim/src/test_data/fa_reader_test.fasta.1\", \"RNASkim/src/test_data/fa_reader_test.fasta.2\", 1)\n# estimate(\"RNASkim/src/test_results/clustered_gene.fa.cf\", \"RNASkim/src/test_results/estimation\")\n\n\n","sub_path":"rnaskim_adapter.py","file_name":"rnaskim_adapter.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283608051","text":"class BinaryTree:\n def __init__(self, node):\n self.key = node\n self.left_child = None\n self.right_child = None\n\n def insert_left(self, new_node):\n t = BinaryTree(new_node)\n if self.left_child is None:\n self.left_child = t\n else:\n t.left_child = self.left_child\n self.left_child = t\n\n def insert_right(self, new_node):\n t = BinaryTree(new_node)\n if self.right_child is None:\n self.right_child = t\n else:\n t.right_child = self.right_child\n self.right_child = t\n\n def get_right_child(self):\n return self.right_child\n\n def get_left_child(self):\n return self.left_child\n\n def get_root_val(self):\n return self.key\n\n def set_root_val(self, new_val):\n self.key = new_val\n\n def get_tree_height(self):\n left = 0\n right = 0\n if self.left_child is not None:\n left += self.left_child.get_tree_height()\n if self.right_child is not None:\n right += self.right_child.get_tree_height()\n return max([left, right]) + 1\n\n def preorder_print(self):\n result = str(self.key)\n if self.left_child:\n result += self.left_child.preorder_print()\n if self.right_child:\n result += self.right_child.preorder_print()\n return result\n\n def preorder_stack_traversal(self):\n result = \"\"\n node_stack = []\n t = self\n while t or node_stack:\n while t:\n result += t.key\n node_stack.append(t)\n t = t.left_child\n if node_stack:\n node = node_stack.pop()\n t = node.right_child\n return result\n\n def midorder_stack_traversal(self):\n \"\"\"\n 使用栈做中序遍历\n :return: \n \"\"\"\n result = \"\"\n node_stack = []\n t = self\n while t or node_stack:\n while t:\n node_stack.append(t)\n t = t.left_child\n if node_stack:\n node = node_stack.pop()\n result += str(node.key)\n t = node.right_child\n return result\n\n def postorder_stack_traversal(self):\n \"\"\"用栈做后序遍历\"\"\"\n node_record_set = set()\n result = \"\"\n node_stack = []\n t = self\n while t or node_stack:\n while t:\n node_stack.append(t)\n t = t.left_child\n if node_stack:\n node = node_stack.pop()\n if node.key in node_record_set:\n result += str(node.key)\n else:\n if node.right_child is None:\n result += str(node.key)\n else:\n node_stack.append(node)\n node_record_set.add(node.key)\n t = node.right_child\n return result\n\n def leaf_print(self):\n leafs = []\n queue = [self]\n while queue:\n node = queue.pop()\n if node.left_child:\n queue.append(node.left_child)\n if node.right_child:\n queue.append(node.right_child)\n if node.left_child is None and node.right_child is None:\n leafs.append(node.key)\n return leafs\n\n\ndef built_tree():\n \"\"\"\n 用以上树的定义构建这样一棵树\n a\n / \\ \n b c\n \\ / \\ \n d e f\n \"\"\"\n root = BinaryTree('a')\n root.insert_left('b')\n root.insert_right('c')\n root.get_left_child().insert_right('d')\n root.get_right_child().insert_left('e')\n root.get_right_child().insert_right('f')\n root.get_right_child().get_right_child().insert_right('m')\n root.get_right_child().get_right_child().get_right_child().insert_right('n')\n # abdcef\n print(root.get_right_child().preorder_print())\n print(root.preorder_print())\n print(root.preorder_stack_traversal())\n print(root.postorder_stack_traversal())\n print(root.leaf_print())\n print(root.get_tree_height())\n\nif __name__ == '__main__':\n built_tree()\n","sub_path":"learn_argorithms/week3/tree_node_representation.py","file_name":"tree_node_representation.py","file_ext":"py","file_size_in_byte":4210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"371829773","text":"from flask import Blueprint, render_template, redirect, url_for, flash, request\nfrom flask_login import login_required, current_user\nfrom application.models import Exam, Question, Answer\nfrom .forms import QuestionForm\nfrom application import db\nimport pickle\n\n# Blueprint Configuration\nexam_bp = Blueprint('exam_bp', __name__, url_prefix='/exam', template_folder='templates', static_folder='static')\n\n\n@exam_bp.route('/', methods=['GET'])\n@login_required\ndef exam_list():\n exams = Exam.query.filter_by(user_id=current_user.get_id()).all()\n return render_template('exam_list.html', exams=exams)\n\n\n@exam_bp.route('/new', methods=['GET', 'POST'])\n@login_required\ndef create_exam():\n if request.method == 'POST':\n exam_payload = {}\n answer_ids = request.form.getlist('answer')\n question_ids = request.form.getlist('question')\n questions = Question.query.filter(Question.id.in_(question_ids)).all()\n for question in questions:\n exam_payload.update({question.id: {'question': question.question_title, 'answers': {}}})\n for answer in question.answers:\n exam_payload[question.id]['answers'].update(\n {answer.id: {'answer': answer.answer_title, 'correct': answer.correct,\n 'marked': str(answer.id) in answer_ids}})\n exam_payload = pickle.dumps(exam_payload)\n # Save exam to database\n exam = Exam(user_id=current_user.id, result_payload=exam_payload)\n db.session.add(exam)\n db.session.commit()\n return redirect(url_for('exam_bp.view_exam', id=exam.id))\n\n questions_dict = {}\n questions_model = Question()\n # Check if database has less then 20 questions\n if questions_model.count_records() < 20:\n flash('Exam fail to start, there is less then 20 questions.', 'danger')\n return redirect(url_for('exam_bp.exam_list'))\n for i in range(20):\n questions = questions_model.random_questions()\n # This needs to be optimized it can create a lot of query\n while questions_dict.get(questions.id) is not None:\n questions = questions_model.random_questions()\n questions_dict.update({questions.id: questions})\n return render_template('create_exam.html', questions=questions_dict)\n\n\n@exam_bp.route('/', methods=['GET'])\n@login_required\ndef view_exam(id):\n exam = Exam.query.filter_by(id=id, user_id=current_user.get_id()).first_or_404()\n result_payload = pickle.loads(exam.result_payload)\n return render_template('view_exam.html', exam=exam, result_payload=result_payload)\n\n\n@exam_bp.route('delete/', methods=['GET'])\n@login_required\ndef delete_exam(id):\n exam = Exam.query.filter_by(id=id, user_id=current_user.get_id()).first_or_404()\n db.session.delete(exam)\n db.session.commit()\n flash('Exam successfully deleted.', 'success')\n return redirect(url_for('exam_bp.exam_list'))\n\n\n@exam_bp.route('/question', methods=['GET'])\n@login_required\ndef question_list():\n questions = Question.query.all()\n return render_template('question_list.html', questions=questions)\n\n\n@exam_bp.route('/question/new', methods=['GET', 'POST'])\n@login_required\ndef create_question():\n form = QuestionForm()\n if form.validate_on_submit():\n question = Question(question_title=form.question_title.data)\n db.session.add(question)\n for entry in form.answers.entries:\n answer = Answer(answer_title=entry.data['answer_title'], correct=entry.data['correct'], question=question)\n db.session.add(answer)\n db.session.commit()\n flash('Question successfully added.', 'success')\n return redirect(url_for('exam_bp.question_list'))\n return render_template('create_question.html', form=form)\n\n\n@exam_bp.route('/question/edit/', methods=['GET', 'POST'])\n@login_required\ndef edit_question(id):\n question = Question.query.filter_by(id=id).first_or_404()\n form = QuestionForm(obj=question)\n if form.validate_on_submit():\n form.populate_obj(question)\n db.session.commit()\n flash('Question successfully edited.', 'success')\n return redirect(url_for('exam_bp.question_list'))\n return render_template('create_question.html', form=form)\n\n\n@exam_bp.route('/question/delete/', methods=['GET'])\n@login_required\ndef delete_question(id):\n question = Question.query.filter_by(id=id).first_or_404()\n db.session.delete(question)\n db.session.commit()\n flash('Question successfully deleted.', 'success')\n return redirect(url_for('exam_bp.question_list'))\n","sub_path":"application/exam/exam_routes.py","file_name":"exam_routes.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"534592407","text":"import discord\nimport random\nfrom discord.ext import commands\n\nclass Cmds:\n def __init__(self, client):\n self.client = client\n\n def ping(self):\n @self.client.command(name='ping')\n async def ping(ctx):\n message='Pong! :ping_pong:'\n response = message\n await ctx.send(response)\n\n def roll_dice(self):\n @self.client.command(name='roll_dice', help='Simulates rolling dice.')\n async def roll(ctx, number_of_dice: int, number_of_sides: int):\n dice = [\n str(random.choice(range(1, number_of_sides + 1)))\n for _ in range(number_of_dice)\n ]\n await ctx.send(','.join(dice))\n\n def echo(self):\n @self.client.command(name='echo')\n async def echo(ctx, * ,content:str):\n await ctx.send(content)\n\n def clear(self):\n @self.client.command(pass_context=True,name='clear')\n @commands.has_role('Master')\n async def clear(ctx, *,amount:int):\n channel = ctx.channel\n messages = []\n async for message in channel.history(limit=amount+1):\n messages.append(message)\n await channel.delete_messages(messages)\n await ctx.send(\"Notre chat a été nettoyé\")\n","sub_path":"cmds.py","file_name":"cmds.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"329427918","text":"#!/usr/bin/env python\nimport sys\nimport os\nimport rospkg\nfrom jsk_apc2016_common.rbo_segmentation.apc_data import APCDataSet\nfrom jsk_apc2016_common.rbo_segmentation.probabilistic_segmentation\\\n import ProbabilisticSegmentationBP\nimport jsk_apc2016_common.rbo_segmentation.apc_data as apc_data\nimport pickle\n\nrospack = rospkg.RosPack()\ncommon_path = rospack.get_path('jsk_apc2016_common')\nmodule_path = common_path + '/python/jsk_apc2016_common'\nparams = {\n 'use_features': ['color', 'dist2shelf', 'height3D'],\n 'segmentation_method': \"max_smooth\", 'selection_method': \"max_smooth\",\n 'make_convex': True, 'do_shrinking_resegmentation': True,\n 'do_greedy_resegmentation': True}\n\n\n# previously declared in main.py\ndef combine_datasets(datasets):\n samples = []\n for d in datasets:\n samples += d.samples\n return APCDataSet(samples=samples)\n\n\ndef load_datasets(dataset_names, data_path, cache_path):\n datasets = dict()\n\n for dataset_name in dataset_names:\n dataset_path = os.path.join(\n data_path, 'rbo_apc/{}'.format(dataset_name))\n datasets[dataset_name] = APCDataSet(\n name=dataset_name, dataset_path=dataset_path,\n cache_path=cache_path, load_from_cache=True)\n\n return datasets\n\n\ndef train(pkl_path):\n sys.modules['apc_data'] = apc_data\n\n data_path = module_path + \"/rbo_segmentation/data\"\n cache_path = os.path.join(data_path, 'cache')\n dataset_path = os.path.join(data_path, 'rbo_apc')\n\n dataset_names = (\n [\"berlin_runs/\"+str(i+1) for i in range(3)] +\n [\"berlin_samples\", \"berlin_selected\"] +\n [\"seattle_runs/\"+str(i+1) for i in range(5)] +\n [\"seattle_test\"])\n # load from cached data\n datasets = load_datasets(dataset_names, dataset_path, cache_path)\n datasets['berlin_runs'] = combine_datasets(\n [datasets[\"berlin_runs/\"+str(i+1)] for i in range(3)])\n datasets['seattle_runs'] = combine_datasets(\n [datasets[\"seattle_runs/\"+str(i+1)] for i in range(5)])\n datasets['training_berlin_and_seattle'] = combine_datasets(\n [datasets['berlin_selected'], datasets['berlin_runs']])\n bp = ProbabilisticSegmentationBP(**params)\n\n train_set = datasets['berlin_selected']\n bp.fit(train_set)\n\n with open(pkl_path, 'wb') as f:\n pickle.dump(bp, f)\n print(\"saved\")\n\n\nif __name__ == '__main__':\n train(common_path + '/data/trained_segmenter.pkl')\n","sub_path":"jsk_apc2016_common/scripts/train_segmenter.py","file_name":"train_segmenter.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"59110124","text":"from mlxtend.preprocessing import TransactionEncoder\r\nfrom mlxtend.frequent_patterns import apriori, association_rules\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef loadDataSet():\r\n return [['m','o','n','k','e','y'],['d','o','n','k','e','y']\r\n ,['m','a','k','e'],['m','u','c','k','y']\r\n ,['c','o','o','k','i','e']]\r\n\r\ndatanew = np.array(loadDataSet())\r\noht = TransactionEncoder()\r\noht_ary = oht.fit(datanew).transform(datanew)\r\ndf = pd.DataFrame(oht_ary, columns=oht.columns_)\r\n# print(df.head())\r\ndf_dfe = apriori(df, min_support=0.6, use_colnames=True)\r\n# print(df_dfe)\r\n\r\nrule = association_rules(df_dfe, metric=\"confidence\", min_threshold=0.8)\r\nprint(rule)","sub_path":"Apriori2.py","file_name":"Apriori2.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278005547","text":"import sys\nfrom Ui_interfaz import Ui_MainWindow\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtGui import QPixmap\nfrom ProyectoPOO import clienteclass,servicioclass,vehiculoclass,facturasclass,contratoclass\nfrom PIL import Image, ImageOps\nfrom PyQt5.QtCore import Qt, pyqtSignal, QByteArray, QIODevice, QBuffer\nfrom PyQt5.QtWidgets import QApplication, QTableWidgetItem, QLineEdit, QFileDialog, QHeaderView, QLabel\nfrom Ui_ventana2 import Ui_ventana2\nfrom Ui_Agregarvehiculo import Ui_dialogo_vehiculo\nfrom Ui_dialogoservicio import Ui_dialogo_servicio\nfrom Ui_dialogo_contrato import Ui_dialogo_contrato \nfrom reportlab.pdfgen import canvas\nimport os\n\ndirectorio= os.getcwd()# para obtener la ruta de la carpeta que contiene el programa\n\n\n\nclass myapp(QtWidgets.QMainWindow,Ui_MainWindow,Ui_ventana2):\n def __init__(self):\n super(myapp, self).__init__()\n self.path1=\"\"\n self.path2=\"\"\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self) \n self.abrir_bdatos(\"2\",\"\",\"\")\n self.setWindowIcon(QtGui.QIcon(\"icon.png\"))\n\n self.ui.b_buscarCliente.clicked.connect(lambda: self.abrir_bdatos(\"1\",self.ui.le_busacarCliente.text(),self.ui.b_buscarCliente))\n self.ui.b_buscarVehiculo.clicked.connect(lambda: self.abrir_bdatos(\"1\",self.ui.le_buscarVehiculo.text(),self.ui.b_buscarVehiculo))\n self.ui.b_buscarServicio.clicked.connect(lambda: self.abrir_bdatos(\"1\",self.ui.le_buscarServicio.text(),self.ui.b_buscarServicio))\n self.ui.b_buscarContrato.clicked.connect(lambda: self.abrir_bdatos(\"1\",self.ui.le_buscarContrato.text(),self.ui.b_buscarContrato))\n self.ui.b_buscarFactura.clicked.connect(lambda: self.abrir_bdatos(\"1\",self.ui.le_BuscarFactura.text(),self.ui.b_buscarFactura))\n\n self.ui.bactualizarCliente.clicked.connect(lambda: self.abrir_bdatos(\"2\",self.ui.le_busacarCliente.text(),\"\"))\n self.ui.bactualizarVehiculo.clicked.connect(lambda: self.abrir_bdatos(\"2\",self.ui.le_buscarVehiculo.text(),\"\"))\n self.ui.bactualizarcontrato.clicked.connect(lambda: self.abrir_bdatos(\"2\",self.ui.le_buscarVehiculo.text(),\"\"))\n self.ui.bactualizarFacturas.clicked.connect(lambda: self.abrir_bdatos(\"2\",self.ui.le_buscarVehiculo.text(),\"\"))\n self.ui.bactualizarServicio.clicked.connect(lambda: self.abrir_bdatos(\"2\",self.ui.le_buscarVehiculo.text(),\"\"))\n\n\n\n\n self.ui.bactualizar.clicked.connect(lambda: self.iniciar_dialogo(Ui_ventana2(),clienteclass(),\"cliente\", False)) # importante usar lambda\n self.ui.ba_servicios.clicked.connect(lambda: self.iniciar_dialogo(Ui_dialogo_servicio(),servicioclass(),\"servicios\", False))\n self.ui.ba_contratos.clicked.connect(lambda: self.iniciar_dialogo(Ui_dialogo_contrato(),contratoclass(),\"contrato\", True))\n self.ui.ba_vehiculos.clicked.connect(lambda: self.iniciar_dialogo(Ui_dialogo_vehiculo(),vehiculoclass(),\"vehiculo\", False))\n self.ui.ba_facturas.clicked.connect(lambda: os.system(\"start \"+directorio+\"\\Facturas \"))\n \n\n def iniciar_dialogo(self,ventana,clase,origen,imagen): # abre la ventana para tomar datos\n self.ventana=QtWidgets.QMainWindow()\n ventana.setupUi(self.ventana)\n self.ventana.show()\n if imagen == True:\n ventana.badjuntar.clicked.connect(lambda: self.getImage(ventana, 1))\n ventana.badjuntar_2.clicked.connect(lambda: self.getImage(ventana, 2))\n ventana.bguardar.clicked.connect (lambda: self.crear_datos(clase,origen,ventana))#importante usar lambda\n \n def insertImageTable(self, path ,label):\n\n self.pixmap = QPixmap(path).scaled(266, 278, Qt.KeepAspectRatio,\n Qt.SmoothTransformation)\n \n label.setPixmap((self.pixmap))\n\n\n\n def getImage(self, ventana, label):\n self.fname = QFileDialog.getOpenFileName(parent=None, caption='Open file',directory='c:\\'',filter=\"Image files (*.jpg *.png)\")\n #para ajustar la imágen\n self.pixmap = QPixmap(self.fname[0]).scaled(166, 178, Qt.KeepAspectRatio,\n Qt.SmoothTransformation)\n \n self.imagePath = self.fname[0]\n print(self.imagePath)\n\n if self.imagePath == \"\":\n _translate = QtCore.QCoreApplication.translate\n if label == 1:\n ventana.lbantes.setText(_translate(\"dialogo_contrato\", \"FOTO ANTES\"))\n else:\n ventana.lbdespues.setText(_translate(\"dialogo_contrato\", \"FOTO DESPUÉS\"))\n else:\n if label == 1:\n ventana.lbantes.setPixmap(QPixmap(self.pixmap))\n self.path1=self.imagePath\n else:\n ventana.lbdespues.setPixmap(QPixmap(self.pixmap))\n self.path2=self.imagePath\n\n\n\n def guardarimagen(self,path,num,foto):\n global directorio\n ruta=directorio+\"\\imagenes\"\n img=Image.open(path)\n if foto==\"foto1\":\n\n path=(ruta+\"\\ \"+\"foto_antes\"+str(num)+\".jpg\")\n img.save(ruta+\"\\ \"+\"foto_antes\"+str(num)+\".jpg\") # se guarda la imagèn en la carpeta imagenes del còdigo\n else:\n path=(ruta+\"\\ \"+\"foto_despues\"+str(num)+\".jpg\")\n img.save(ruta+\"\\ \"+\"foto_despues\"+str(num)+\".jpg\")\n\n\n with open(\"bImagenes.txt\", \"a\") as baseDatos:\n baseDatos.write(path+\"\\n\")# se guarda la imágen en la base de datos con el número de fáctura\n baseDatos.close\n \n\n\n def crear_datos(self,clase,origen,ventana): # toma los datos de los qlineedit\n\n qlines=[child for child in ventana.centralwidget.findChildren(QtWidgets.QLineEdit)]\n qlines=[texto.text() for texto in qlines]\n self.ventana.close() # cierra la venta de diálogo\n \n\n if origen==\"cliente\":\n diccionario = clase.creardiccionario(qlines[5],qlines[1],qlines[4],qlines[0],qlines[2],qlines[3])\n clase.guardarInfo(diccionario, \"bClientes.txt\" )\n self.abrir_bdatos(\"2\",\"\",\"\")\n\n if origen==\"vehiculo\":\n diccionario = clase.creardiccionario(qlines[8],qlines[11],qlines[1],qlines[2],qlines[3],qlines[7],qlines[4],qlines[5],qlines[6],qlines[10],qlines[9],qlines[0])\n clase.guardarInfo(diccionario, \"bVehiculos.txt\" )\n self.abrir_bdatos(\"2\",\"\",\"\")\n\n if origen== \"servicios\":\n diccionario = clase.creardiccionario(qlines[0],qlines[1],qlines[2],qlines[3])\n clase.guardarInfo(diccionario, \"bServicios.txt\" )\n self.abrir_bdatos(\"2\",\"\",\"\")\n\n if origen== \"contrato\":\n diccionario = clase.creardiccionario(qlines[3],qlines[2],qlines[0],qlines[1],3)\n servicio=servicioclass()\n contrato=servicio.solServicio(qlines[0],qlines[1],qlines[2],qlines[3])\n if contrato != False:\n cliente = clienteclass()\n cliente.guardarInfo(contrato[0], \"bContratos.txt\")\n pdf=(contrato[1].split(sep='\\n'))\n self.guardarimagen(self.path1,contrato[2],\"foto1\")\n self.guardarimagen(self.path2,contrato[2],\"foto2\")\n self.generar_pdf(pdf,contrato[2])\n self.abrir_bdatos(\"2\",\"\",\"\")\n\n def generar_pdf(self,pdf,numero):\n c = canvas.Canvas(directorio+\"\\Facturas\"+\"\\Factura\"+str(numero)+\".pdf\")\n x=100\n y=750\n print(pdf)\n for i in pdf:\n \n n=i.split(\"\\t\\t\")\n for m in n:\n if len(n)==1 and m!='':\n c.line(x,y,500,y)\n c.drawString(x,y,m)\n y-=20\n\n file = open(\"bImagenes.txt\", \"r\")\n j=100\n for ruta in file.readlines(): \n if str(numero) in ruta: #busca por el número de factura\n if j==100:\n c.drawString(j,70,\"FOTO ANTES\")\n else:\n c.drawString(j,70,\"FOTO DESPUÉS\",)\n c.drawImage(ruta.replace(\"\\n\", \"\"), j, 100,104, 124)\n j+=200\n \n file.close\n c.save()\n os.system(\"start \"+directorio+\"\\Facturas\"+\"\\Factura\"+str(numero)+\".pdf &\")\n\n \n def abrir_bdatos(self, op, noid, boton):\n cliente=clienteclass()\n vehiculo=vehiculoclass()\n servicio=servicioclass()\n contrato=contratoclass()\n factura=facturasclass()\n\n if op==\"2\":\n cabecera_c, listac= cliente.datos, clienteclass.leerBase(\"bClientes.txt\",op,noid,False,0)\n cabecera_v, listav= vehiculo.datos, clienteclass.leerBase(\"bVehiculos.txt\",op,noid,False,0)\n cabecera_s, listas= servicio.datos, clienteclass.leerBase(\"bServicios.txt\",op,noid,False,0)\n cabecera_co, listaco= contrato.datos, clienteclass.leerBase(\"bContratos.txt\",op,noid,False,0)\n listaf=clienteclass.leerBase(\"bFacturas.txt\",\"2\",\"\",False,0)\n\n self.actualizar_tabla(listac,cabecera_c, self.ui.tabladatos)\n self.actualizar_tabla(listaco,cabecera_co, self.ui.tb_contratos)\n self.actualizar_tabla(listas,cabecera_s, self.ui.tb_servicios)\n self.actualizar_tabla(listav,cabecera_v, self.ui.td_vehiculos)\n self.actualizar_tabla(listaf,[\"factura\",\"foto antes\",\"foto después\"], self.ui.tb_facturas)\n else:\n if boton==self.ui.b_buscarCliente:\n cabecera_c, listac= cliente.datos, [(clienteclass.leerBase(\"bClientes.txt\",\"1\",noid,False,0)).split(\" \")]\n print(listac)\n self.actualizar_tabla(listac,cabecera_c, self.ui.tabladatos)\n if boton==self.ui.b_buscarVehiculo:\n cabecera_v, listav= vehiculo.datos, [(clienteclass.leerBase(\"bVehiculos.txt\",\"1\",noid,False,0)).split(\" \")]\n print(listav)\n self.actualizar_tabla(listav,cabecera_v, self.ui.td_vehiculos)\n if boton== self.ui.b_buscarServicio:\n cabecera_s, listas= servicio.datos, [(clienteclass.leerBase(\"bServicios.txt\",\"1\",noid,False,0)).split(\" \")]\n print(listas)\n self.actualizar_tabla(listas,cabecera_s, self.ui.tb_servicios)\n if boton== self.ui.b_buscarContrato:\n cabecera_co, listaco= contrato.datos, [(clienteclass.leerBase(\"bContratos.txt\",\"1\",noid,False,0)).split(\" \")]\n self.actualizar_tabla(listaco,cabecera_co, self.ui.tb_contratos)\n \n if boton== self.ui.b_buscarFactura:\n listaf=[[factura.buscarfactura(int(noid))]]\n print(noid)\n print(listaf)\n self.actualizar_tabla(listaf,[\"facturas\",\"foto antes\",\"foto después\"], self.ui.tb_facturas)\n \n\n\n\n\n \n\n\n def actualizar_tabla(self, info, cabecera,tabladatos):\n\n if info==\"Base de datos vacía\": # para imprimir una lista vacía en casao de que haya nada en la base de datos\n info=[]\n try:\n if (info[0][0])==\"No\":\n info=[]\n if (info[0][0])==\"No info\":\n info=[]\n except:\n pass\n\n\n \n tabladatos.setColumnCount(len(cabecera)) #pone el numero de columnas de la tabal\n tabladatos.setRowCount(len(info)) #pone el numero de filas\n tabladatos.setHorizontalHeaderLabels(cabecera)#pone los nombres alas columnas\n # Hacer que la última sección visible del encabezado ocupa todo el espacio disponible\n tabladatos.horizontalHeader().setStretchLastSection ( True )\n tabladatos.setSortingEnabled(True)#ordena por columnas cuando elusuario presiona una columna\n tabladatos.setAlternatingRowColors ( True )\n if len(cabecera)==3:\n tabladatos.horizontalHeader().setStretchLastSection ( False )\n tabladatos.verticalHeader().setDefaultSectionSize(300)\n header_view = tabladatos.horizontalHeader()\n header_view.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)# ajusta el espacio de la celda para que se alcance a ver toda la información\n header_view.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)\n header_view.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)\n\n\n\n if tabladatos== self.ui.tb_facturas:\n file = open(\"bImagenes.txt\", \"r\")\n listimage=file.readlines()\n\n\n\n fila=0 \n for registro in info:\n columna=0\n for dato in registro:\n if len(registro)==2:\n cellinfo=QTableWidgetItem(registro[1])\n else:\n cellinfo=QTableWidgetItem(dato)\n \n cellinfo.setFlags(QtCore.Qt.ItemIsSelectable| QtCore.Qt.ItemIsEditable)#hace que las celdas no sean editables\n\n \n if tabladatos== self.ui.tb_facturas:\n if columna==0:\n tabladatos.setItem(fila,columna,cellinfo)\n\n qlabel= QtWidgets.QLabel()#SE CREA EL QLABEL\n qlabel2= QtWidgets.QLabel()\n\n \n self.insertImageTable(directorio+\"\\imagenes\"+\"\\ foto_antes\"+str(fila),qlabel)# se llama la funcíon que inserta la imágen en el qlabel\n \n self.insertImageTable(directorio+\"\\imagenes\"+\"\\ foto_despues\"+str(fila)+\".jpg\",qlabel2)\n\n tabladatos.setCellWidget(fila,1,qlabel)\n tabladatos.setCellWidget(fila,2,qlabel2)# se inserta el qlabel en la tabla\n \n else:\n tabladatos.setItem(fila,columna,cellinfo)\n columna+=1\n fila+=1\n\n\n\n \n \n \n\n\n\n\n\n\n\napp = QtWidgets.QApplication([])\napplication = myapp()\napplication.show()\nsys.exit(app.exec_())","sub_path":"control_interfaz.py","file_name":"control_interfaz.py","file_ext":"py","file_size_in_byte":13913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"538416054","text":"# Time Complexity : O(N) number of elements in a list\r\n# Space Complexity : O(1)\r\n# Did this code successfully run on Leetcode: Yes\r\n# Any problem you faced while coding this : No\r\n#we will keep a count of elemenst that has to be skipped in hashmap. then we will iterate through the imput list. When e encounter a skip we will check if current el is the skip el #if yes then we will bypass it if not reduce it count in hashmap and \r\n\r\nfrom collections import defaultdict\r\nclass SkipIterator():\r\n\r\n def __init__(self, nums):\r\n\r\n self.nums = nums\r\n self.pos = 0\r\n self.skip_ = defaultdict(lambda : 0)\r\n\r\n\r\n def hasNext(self):\r\n\r\n if self.pos < len(self.nums):\r\n return True \r\n\r\n def next(self):\r\n cur = self.pos\r\n\r\n #we check if cur position contains a element that is supposed to be skipped\r\n while cur < len(self.nums):\r\n # if hashmpa has element at currnt position with value > 0, we decrease and move the cursor, and continue the loop\r\n if self.skip_[self.nums[cur]] > 0:\r\n self.skip_[self.nums[cur]] -= 1\r\n cur += 1\r\n continue\r\n #If not present in hashmap, break out\r\n else:\r\n break\r\n #move pos to next position \r\n self.pos = cur+1 \r\n return self.nums[cur]\r\n\r\n def skip(self, num):\r\n\r\n self.skip_[num] += 1\r\n''' \r\nitr = SkipIterator([2, 3, 5, 6, 5, 7, 5, -1, 5, 10])\r\nprint (itr.hasNext())#; // true\r\nprint (itr.skip(2))\r\nprint (itr.next())#; // returns 2\r\nprint (itr.skip(5))#;\r\nprint (itr.next())#; // returns 3\r\nprint (itr.next())#; // returns 6 because 5 should be skipped\r\nprint (itr.next())#; // returns 5\r\nprint (itr.skip(5))#;\r\nprint (itr.skip(5))#;\r\nprint (itr.next())#; // returns 7\r\nprint (itr.next())#; // returns -1\r\nprint (itr.hasNext())\r\nprint (itr.next())#; // returns 10\r\n#; // false\r\nprint (itr.next())#; // error\r\n''' \r\n\r\nclass SkipIterator:\r\n\r\n def __init__(self,it):\r\n self.mapp = {}\r\n self.advance()\r\n self.it = it\r\n self.nextEl = None\r\n \r\n\r\n # Time = O(1)\r\n def hasNext(self):\r\n return self.nextEl != None\r\n\r\n # Time = O(1)\r\n def next(self): \r\n temp = self.nextEl\r\n self.advance()\r\n return temp\r\n\r\n \r\n # Time = O(n) in worst case if all n elements are distinct\r\n def skip(self,val): \r\n if self.nextEl == val:\r\n self.advance()\r\n else:\r\n if val in self.mapp:\r\n self.mapp[val] += 1\r\n else:\r\n self.mapp[val] = 1\r\n\r\n # Time = O(n) in worst case if all n elements are distinct\r\n def __advance(self):\r\n self.nextEl = None\r\n nextVal = self.next(self.it,None)\r\n while nextEl == None and nextVal != None:\r\n if self.nextVal not in self.mapp:\r\n self.nextEl = self.nextVal\r\n break\r\n else:\r\n self.mapp[nextVal] -= 1\r\n if self.mapp[nextVal] == 0:\r\n del self.mapp[nextVal]\r\n nextVal = self.next(self.it,None)\r\n \r\n if __name__ ==\"__main__\":\r\n itr = SkipIterator(iter([2, 3, 5, 6, 5, 7, 5, -1, 5, 10]))\r\n print(itr.hasNext()) # true\r\n print(itr.next()) # returns 2\r\n itr.skip(5)\r\n print(itr.next()) # returns 3\r\n print(itr.next()) # returns 6 because 5 should be skipped\r\n print(itr.next()) # returns 5\r\n itr.skip(5)\r\n itr.skip(5)\r\n print(itr.next()) # returns 7\r\n print(itr.next()) # returns -1\r\n print(itr.next()) # returns 10\r\n print(itr.hasNext()) # returns false\r\n print(itr.next()) # None \r\n \r\n","sub_path":"SkipIterator.py","file_name":"SkipIterator.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"252840460","text":"'''\nThis file contains all constants used in this program. Currently, this includes:\n - Configuration variables. These are used to change the operation of the code\n across the board, and include convenient commonly used settings.\n - Symbolic constants. These are variable names that represent meaningful\n values in different contexts through the code.\n'''\n\n'''\nConfiguration variables\n'''\n# The number of nodes in the generated graph\nGENERATED_GRAPH_SIZE = 10\n# Probability of infecting a neighbor in the independent cascade model\nTRANSITION_PROBABILITY = 0.3\n# The (negative) cost to purchase an agent. Could be made to vary per agent!\nAGENT_COST = -2.5\n\n'''\nSymbolic constants\n'''\n# The string name of the constraint function on edges\nCONSTRAINT_FUNCTION_NAME = 'constraint function'\n# The string name of the transition probability on edges\nWEIGHT_NAME = 'weight'\n# The string name of the agent cost on nodes\nAGENT_COST_NAME = 'agent cost'\n# A general-purpose delimiter used for, for instance, delimiting rounds in BFS\nDELIMITER = '__DELIMITER__'\n","sub_path":"Code/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"556652915","text":" # LIBRERIAS\nimport numpy as np\nimport cv2\nfrom time import sleep\nimport picamera\nimport funciones as fun\n\ncamera=picamera.PiCamera()\ncamera.vflip=True\ncamera.sharpness = 100\ncamera.contrast = 0\n#inicializacion de variables\n# acomodacion de camara\n#camera.start_preview()\n#sleep(0)\n#camera.stop_preview()\n#<<<<<<<<<<<<<<<<<< inicio calibracion >>>>>>>>>>>>>>>>>\ninp='';\nwhile(inp.upper()!='Y'):\n i=1\n name='caln1.jpg'\n camera.capture(name,0)\n Im= cv2.imread(name)\n# cv2.imshow('imagen',Im)\n gray=cv2.cvtColor(Im,cv2.COLOR_BGR2GRAY);\n warp=fun.encuadre(gray,Im)\n (war,(xf,yf))=fun.calibracion(Im)\n cv2.imshow('CAL',war)\n cv2.waitKey(0);\n print(xf)\n print(yf)\n\n #inp=input('la cuadricula esta bien ubicada? y/n ')\n inp='y'\n cv2.destroyAllWindows()\n#<<<<<<<<<<<<<<<<<< fin calibracion >>>>>>>>>>>>>>>>> \n\nprint('/----------------------/')\nprint(xf)\nprint(yf)\nprint('/----------------------/')\n\n#<<<<<<<<<<<<<<<<<< reconocimiento >>>>>>>>>>>>>>>>>\ni=2\ninp=''\nboard1=np.zeros((8,8))\ncboard1=board1\ntrn=1\nk=0;\ninp='';\nwhile(inp.upper()!='Y'):\n #### ------ Captura de imagen \n name='rec'+str(i)+'.jpg'\n ## camera.capture(name,0)\n Im= cv2.imread(name)\n # cv2.imshow('imagen',Im)\n gray=cv2.cvtColor(Im,cv2.COLOR_BGR2GRAY)\n warp=fun.encuadre(gray,Im)\n\n \n #### ------ imagen capturada y procesada para reconocimiento\n ## grw = la imagen \n \n k+=1\n if trn==0:\n trn=1\n else:\n trn=0\n if k>1:\n cboard1=cboard\n board1=board\n cv2.imshow('tablero',warp)\n (q,board,cboard)=fun.recon(warp,xf,yf)\n \n print('--')\n print(q)\n print('*****')\n print(board)\n print('*****')\n print(cboard)\n print('*****')\n \n if k>1:\n cambio=np.equal(board.flatten(),board1.flatten());\n cambio=1-(1*cambio);\n change=cambio.nonzero();\n change=change[0]\n print(change)\n print(change % 8) #columna\n print(change // 8) # fila\n \n print('*****')\n turno=1*(np.equal(cboard,trn))\n turno=turno.flatten()\n otr=(not(trn))*1\n oturno=1*(np.equal(cboard,otr))\n oturno=oturno.flatten()\n print(turno)\n print((change[0],change[1]))\n j1=(turno[change[0]],turno[change[1]])\n j2=(oturno[change[0]],oturno[change[1]])\n print(j1)# orden 1 es la nueva 0 la vieja\n print(j2)\n print((j1[0]*j2[0],j1[1]*j2[1]))# si hay transferencia alguno tiene que ser =1\n print('*****') \n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nimport chess\ntab=chess.Board()\n# traduccion fen a array\n(lb,lc)=fun.tran_chess(tab)\nprint(lb)","sub_path":"tesis/recog.py","file_name":"recog.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238817375","text":"import dash_multidropdown\nimport dash, json\nfrom dash.dependencies import Input, Output\nimport dash_html_components as html\n\napp = dash.Dash(__name__)\n\napp.scripts.config.serve_locally = True\napp.css.config.serve_locally = True\n\napp.layout = html.Div([html.Div([\n html.Div([\n dash_multidropdown.MultiSelectList(\n id='input',\n value=[],\n options=[\n {'label': u'opcja długi tekst zobaczymy jak'+str(i), 'value': 'opcja długi text'+str(i)} for i in range(20)],\n isMulti=True\n )], style={'height':'200px', 'width':'200px'})\n], style={'width':'400px', 'display':'flex'}),\nhtml.Div(id='output')])\n\n\n@app.callback(Output('output', 'children'), [Input('input', 'value')])\ndef display_output(value):\n print(value[0]) if len(value)>0 else print('empty')\n return json.dumps(value, ensure_ascii=False)\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"usage.py","file_name":"usage.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256180024","text":"'''Split the SIGNS dataset into train/dev/test and resize images to 224x224.\nbuild_dataset.py\n\n1. Purpose of script is to resize the dataset\n2. Split training into training and dev set\n3. Describe statistics of training set, distribution of class labels\nOriginal images are (3024, 3024)\nWe plan to reduce size by (224,224), as loading smaller images makes\ntraining faster\n\nTest set is already created, so splitting \"train_signs\" into train and dev sets\nWant statistics on dev to be as representative as possible,\nwill take 20% of \"train_signs\" as dev set\n'''\n\nimport argparse\nimport random\nimport os\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndef compute_statistics(args):\n '''\n Will take in a list of filenames, parse to get class labels\n and return distribution of labels\n '''\n train_data_dir = os.path.join(args.data_dir,'train_signs')\n test_data_dir = os.path.join(args.data_dir,'test_signs')\n print(train_data_dir)\n # Get the filenames in each directory (train and test)\n filenames = os.listdir(train_data_dir)\n filenames = [os.path.join(train_data_dir,f) for f in filenames if f.endswith('jpg')]\n tr_labels = np.array([int(f.split('/')[-1][0]) for f in filenames])\n\n test_filenames = os.listdir(test_data_dir)\n test_filenames = [os.path.join(test_data_dir,f) for f in test_filenames if f.endswith('jpg')]\n test_labels = np.array([int(f.split('/')[-1][0]) for f in test_filenames])\n ax = sns.countplot(tr_labels)\n ax.set_title(\"Distribution of train labels\")\n plt.show()\n ax=sns.countplot(test_labels)\n ax.set_title(\"Distribution of test labels\")\n plt.show()\n return\n\nSIZE=224\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir',default='data/SIGNS',\n help=\"Directory that contains the SIGNS dataset\",\n )\nparser.add_argument('--output_dir',default='data/224x224_SIGNS',help='Where to write the new data')\nparser.add_argument('--compute_stats',default=0,help='Used to Compute stats')\ndef resize_and_save(filename,output_dir,size=SIZE):\n '''Resize the image contained in `filename` and save it to\n `output_dir`'''\n\n image = Image.open(filename)\n # Bilinear interpolation instead of nearest neighbor method\n image = image.resize((size,size),Image.BILINEAR)\n image.save(os.path.join(output_dir,filename.split('/')[-1 ]))\n return\n\nif __name__=='__main__':\n\n # read and parse arguments\n args = parser.parse_args()\n if args.compute_stats==1:\n compute_statistics(args)\n else:\n # Check if data set argument passsed exists\n assert os.path.isdir(args.data_dir),\"Couldnt find the dataset at {}\".format(args.data_dir)\n\n # Define the data directories\n train_data_dir = os.path.join(args.data_dir,'train_signs')\n test_data_dir = os.path.join(args.data_dir,'test_signs')\n print(train_data_dir)\n # Get the filenames in each directory (train and test)\n filenames = os.listdir(train_data_dir)\n filenames = [os.path.join(train_data_dir,f) for f in filenames if f.endswith('jpg')]\n\n test_filenames = os.listdir(test_data_dir)\n test_filenames = [os.path.join(test_data_dir,f) for f in test_filenames if f.endswith('jpg')]\n # print(filenames)\n\n # Split the images into 'train_signs' into 80% train and 20% dev\n # Make sure to always shuffle with a fixed seed so that the split is reproducible\n\n random.seed(230)\n filenames.sort()\n random.shuffle(filenames)# strategy: shuffle and then split\n\n split = int(0.8*len(filenames))\n\n train_filenames = filenames[:split]\n dev_filenames = filenames[split:]\n\n filenames={\n 'train':train_filenames,\n 'dev':dev_filenames,\n 'test':test_filenames\n }\n\n # make output dir if not exists\n if not os.path.exists(args.output_dir):\n os.mkdir(args.output_dir)\n else:\n print(\"Warning: output_dir {} already exists\".format(args.output_dir))\n\n # Preprocess train, dev, and test\n\n # Make all outputs for inside the output dir\n for split in ['train','dev','test']:\n output_dir_split=os.path.join(args.output_dir,'{}_signs'.format(split))\n if not os.path.exists(output_dir_split):\n os.mkdir(output_dir_split)\n else:\n print(\"Warning: dir {} already exists\".format(output_dir_split))\n \n print(\"Processing {} data, saving preprocessed data to {}\".format(split,\n output_dir_split))\n for filename in tqdm(filenames[split]):\n # print()\n resize_and_save(filename,output_dir_split,size=SIZE)\n \n print(\"Done building dataset\")","sub_path":"build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"503021767","text":"#!/usr/bin/env python\n\"\"\"Subprocess test-case is meant to be used to debug communications with subprocesses\"\"\"\n\nimport threading\nimport sys\nfrom time import sleep\n\nimport src.subprocs.communicator as communicator\nimport src.resource_logger as resource_logger\n\n\nclass Test_Subprocess(object):\n\n def __init__(self, stdin, stdout, stderr):\n\n logger = resource_logger.Fallback_Logger()\n self._comm = communicator.Communicator(\n logger, self, stdin, stdout, stderr)\n\n self._comm_thread = threading.Thread(target=self._comm.run)\n self._comm_thread.start()\n\n self._running = True\n self._paused = False\n self._current = 0\n self._total = 10000\n\n def run(self):\n\n while self._running:\n\n if self._current >= self._total:\n self._running = False\n\n if not self._paused:\n self._current += 1\n\n sleep(1)\n\n def get_current_step(self):\n\n return self._current\n\n def get_total_iterations(self):\n\n return self._total\n\n def get_progress(self):\n\n return float(self.get_current_step()) / self.get_total_iterations()\n\n def get_paused(self):\n\n return self._paused\n\n def set_terminate(self):\n\n self._running = False\n return True\n\n def set_pause(self):\n\n self._paused = True\n return True\n\n def set_unpause(self):\n\n self._paused = False\n return True\n\n def get_info(self):\n\n return (\"__NAME__ Test Case\",\n \"__TOTAL__ {0}\".format(self._total))\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 3:\n fpath = \"_test_case.std\"\n else:\n fpath = sys.argv[-1]\n\n main = Test_Subprocess(fpath + \"in\", fpath + \"out\", fpath + \"err\")\n main.run()\n","sub_path":"dev/subproc_test_case.py","file_name":"subproc_test_case.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"180653530","text":"from zipfile import ZipFile\nimport os\n\ndef file_paths(directory):\n file_paths=[]\n for root,directories,files in os.walk(directory):\n for filename in files:\n filepath=os.path.join(root,filename)\n file_paths.append(filepath)\n\n return file_paths\ntry:\n directory=input() \n file_pths=file_paths(directory)\n \n print(\"files are\")\n for file in file_pths:\n print(file)\n \nexcept:\n print ((sys.exc_info()[0]),\"occured\")\nelse:\n print(\"Files printed successfully\") \n","sub_path":"Zip_File_Assignment/Display_File_Names.py","file_name":"Display_File_Names.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332481276","text":"from django.urls import path\n\nfrom . import views\n\napp = 'courses'\nurlpatterns = [\n path('', views.CourseListView.as_view(), name='courses_list_url'),\n path('/', views.CourseView.as_view(), name='courses_detail_url'),\n path('create/', views.CourseCreateView.as_view(), name='course_create_url'),\n path('/update', views.CourseUpdateView.as_view(), name='course_update.url'),\n path('/delete', views.CourseDeleteView.as_view(), name='course_delete.url'),\n]","sub_path":"trydjango/courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508217044","text":"import numpy as np\nimport taichi as ti\nimport taichi_glsl as ts\nfrom .geometry import *\nfrom .transform import *\nfrom .common import *\nimport math\n\n\n@ti.data_oriented\nclass Model(AutoInit):\n def __init__(self, f_n=None, f_m=None,\n vi_n=None, vt_n=None, vn_n=None, tex_n=None,\n obj=None, tex=None):\n self.L2W = Affine.field(())\n\n self.faces = None\n self.vi = None\n self.vt = None\n self.vn = None\n self.tex = None\n\n if obj is not None:\n f_n = None if obj['f'] is None else obj['f'].shape[0]\n vi_n = None if obj['vi'] is None else obj['vi'].shape[0]\n vt_n = None if obj['vt'] is None else obj['vt'].shape[0]\n vn_n = None if obj['vn'] is None else obj['vn'].shape[0]\n\n if tex is not None:\n tex_n = tex.shape[:2]\n\n if f_m is None:\n f_m = 1\n if vt_n is not None:\n f_m = 2\n if vn_n is not None:\n f_m = 3\n\n if vi_n is None:\n vi_n = 1\n if vt_n is None:\n vt_n = 1\n if vn_n is None:\n vn_n = 1\n\n if f_n is not None:\n self.faces = ti.Matrix.field(3, f_m, ti.i32, f_n)\n if vi_n is not None:\n self.vi = ti.Vector.field(3, ti.f32, vi_n)\n if vt_n is not None:\n self.vt = ti.Vector.field(2, ti.f32, vt_n)\n if vn_n is not None:\n self.vn = ti.Vector.field(3, ti.f32, vn_n)\n if tex_n is not None:\n self.tex = ti.Vector.field(3, ti.f32, tex_n)\n\n if obj is not None:\n self.init_obj = obj\n if tex is not None:\n self.init_tex = tex\n\n def from_obj(self, obj):\n if obj['f'] is not None:\n self.faces.from_numpy(obj['f'])\n if obj['vi'] is not None:\n self.vi.from_numpy(obj['vi'])\n if obj['vt'] is not None:\n self.vt.from_numpy(obj['vt'])\n if obj['vn'] is not None:\n self.vn.from_numpy(obj['vn'])\n\n def _init(self):\n self.L2W.init()\n if hasattr(self, 'init_obj'):\n self.from_obj(self.init_obj)\n if hasattr(self, 'init_tex'):\n self.tex.from_numpy(self.init_tex.astype(np.float32) / 255)\n\n @ti.func\n def render(self, camera):\n for i in ti.grouped(self.faces):\n render_triangle(self, camera, self.faces[i])\n\n @ti.func\n def texSample(self, coor):\n if ti.static(self.tex is not None):\n return ts.bilerp(self.tex, coor * ts.vec(*self.tex.shape))\n else:\n return 1\n","sub_path":"taichi_three/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"619218350","text":"from __future__ import unicode_literals\nfrom builtins import dict, str\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport multiprocessing as mp\nimport hcl\nimport os\nimport popper.utils as pu\nimport popper.scm as scm\nfrom spython.main import Client\n\n\nclass Workflow(object):\n \"\"\"A GHA workflow.\n \"\"\"\n\n def __init__(self, wfile, workspace, quiet, debug, dry_run):\n wfile = pu.find_default_wfile(wfile)\n\n with open(wfile, 'r') as fp:\n self.wf = hcl.load(fp)\n\n self.workspace = workspace\n self.debug = debug\n if debug:\n self.quiet = False\n else:\n self.quiet = quiet\n self.dry_run = dry_run\n\n self.actions_cache_path = os.path.join('/', 'tmp', 'actions')\n self.validate_syntax()\n self.check_secrets()\n self.normalize()\n self.complete_graph()\n\n self.env = {\n 'GITHUB_WORKSPACE': self.workspace,\n 'GITHUB_WORKFLOW': self.wf['name'],\n 'GITHUB_ACTOR': 'popper',\n 'GITHUB_REPOSITORY': '{}/{}'.format(scm.get_user(),\n scm.get_name()),\n 'GITHUB_EVENT_NAME': self.wf['on'],\n 'GITHUB_EVENT_PATH': '/{}/{}'.format(self.workspace,\n 'workflow/event.json'),\n 'GITHUB_SHA': scm.get_sha(),\n 'GITHUB_REF': scm.get_ref()\n }\n\n for e in dict(self.env):\n self.env.update({e.replace('GITHUB_', 'POPPER_'): self.env[e]})\n\n def validate_syntax(self):\n \"\"\" Validates the .workflow file.\n \"\"\"\n resolves_present = False\n uses_present = False\n if not self.wf.get('workflow', None):\n pu.fail('A workflow block must be present\\n')\n else:\n for _, wf_block in dict(self.wf['workflow']).items():\n if wf_block.get('resolves', None):\n resolves_present = True\n if not resolves_present:\n pu.fail('[resolves] attribute must be present\\n')\n if not self.wf.get('action', None):\n pu.fail('Atleast one action block must be present\\n')\n else:\n for _, a_block in self.wf['action'].items():\n if a_block.get('uses', None):\n uses_present = True\n if not uses_present:\n pu.fail('[uses] attribute must be present\\n')\n\n def is_list_of_strings(self, lst):\n try:\n basestring\n except UnboundLocalError:\n basestring = str\n return bool(lst) and isinstance(lst, list) and all(\n isinstance(elem, basestring) for elem in lst)\n\n def normalize(self):\n \"\"\"normalize the dictionary representation of the workflow\"\"\"\n\n # modify from this:\n #\n # \"workflow\": {\n # \"test-and-deploy\": {\n # \"resolves\": \"deploy\"\n # }\n # }\n #\n # to this:\n #\n # \"workflow\": {\n # \"name\": \"test-and-deploy\",\n # \"on\": \"push\",\n # \"resolves\": \"deploy\"\n # }\n for wf_name, wf_block in dict(self.wf['workflow']).items():\n self.wf['name'] = wf_name\n self.wf['on'] = wf_block.get('on', 'push')\n self.wf['resolves'] = wf_block['resolves']\n\n # python 2 to 3 compatibility\n try:\n basestring\n except UnboundLocalError:\n basestring = str\n\n # create a list for all attributes that can be either string or list\n if isinstance(self.wf['resolves'], basestring):\n self.wf['resolves'] = [self.wf['resolves']]\n elif not self.is_list_of_strings(self.wf['resolves']):\n pu.fail('[resolves] must be a list of strings or a string\\n')\n if not isinstance(self.wf['on'], basestring):\n pu.fail('[on] attribute must be a string\\n')\n for _, a_block in self.wf['action'].items():\n if not isinstance(a_block['uses'], basestring):\n pu.fail('[uses] attribute must be a string\\n')\n if a_block.get('needs', None):\n if isinstance(a_block['needs'], basestring):\n a_block['needs'] = [a_block['needs']]\n elif not self.is_list_of_strings(a_block['needs']):\n pu.fail(\n '[needs] attribute must be a list of strings \\\n or a string\\n')\n if a_block.get('runs', None):\n if isinstance(a_block['runs'], basestring):\n a_block['runs'] = [a_block['runs']]\n elif not self.is_list_of_strings(a_block['runs']):\n pu.fail(\n '[runs] attribute must be a list of strings \\\n or a string\\n')\n if a_block.get('args', None):\n if isinstance(a_block['args'], basestring):\n a_block['args'] = a_block['args'].split()\n elif not self.is_list_of_strings(a_block['args']):\n pu.fail(\n '[args] attribute must be a list of strings \\\n or a string\\n')\n if a_block.get('env', None):\n if not isinstance(a_block['env'], dict):\n pu.fail('[env] attribute must be a dict\\n')\n if a_block.get('secrets', None):\n if not self.is_list_of_strings(a_block['secrets']):\n pu.fail('[secrets] attribute must be a list of strings\\n')\n\n def complete_graph(self):\n \"\"\"A GHA workflow is defined by specifying edges that point to the\n previous nodes they depend on. To make the workflow easier to process,\n we add forward edges. We also obtains the root nodes.\n \"\"\"\n root_nodes = set()\n\n for name, a_block in self.wf['action'].items():\n\n a_block['name'] = name\n\n for n in a_block.get('needs', []):\n if not self.wf['action'][n].get('next', None):\n self.wf['action'][n]['next'] = set()\n self.wf['action'][n]['next'].add(name)\n\n if not a_block.get('needs', None):\n root_nodes.add(name)\n\n self.wf['root'] = root_nodes\n\n def check_secrets(self):\n for _, a in self.wf['action'].items():\n for s in a.get('secrets', []):\n if s not in os.environ:\n pu.fail('Secret {} not defined\\n.'.format(s))\n\n def download_actions(self):\n \"\"\"Clone actions that reference a repository.\"\"\"\n cloned = set()\n infoed = False\n for _, a in self.wf['action'].items():\n if ('docker://' in a['uses'] or\n 'shub://' in a['uses'] or\n './' in a['uses']):\n continue\n\n action = None\n\n if a['uses'].startswith('https://'):\n a['uses'] = a['uses'][8:]\n parts = a['uses'].split('/')\n url = 'https://' + parts[0]\n service = parts[0]\n user = parts[1]\n repo = parts[2]\n elif a['uses'].startswith('http://'):\n a['uses'] = a['uses'][7:]\n parts = a['uses'].split('/')\n url = 'http://' + parts[0]\n service = parts[0]\n user = parts[1]\n repo = parts[2]\n elif a['uses'].startswith('git@'):\n url, rest = a['uses'].split(':')\n user, repo = rest.split('/')\n service = url[4:]\n elif a['uses'].startswith('ssh://'):\n pu.fail(\"The ssh protocol is not supported yet.\")\n else:\n url = 'https://github.com'\n service = 'github.com'\n parts = a['uses'].split('/')\n user = a['uses'].split('/')[0]\n repo = a['uses'].split('/')[1]\n action = '/'.join(a['uses'].split('/')[1:])\n\n if '@' in repo:\n action_dir = '/'.join(a['uses'].split('@')[-2].split('/')[-1:])\n version = a['uses'].split('@')[-1]\n elif '@' in action:\n action_dir = '/'.join(action.split('@')[-2].split('/')[-1:])\n version = action.split('@')[-1]\n else:\n action_dir = '/'.join(a['uses'].split('/')[2:])\n version = None\n action_dir = os.path.join('./', action_dir)\n\n repo_parent_dir = os.path.join(\n self.actions_cache_path, service, user\n )\n a['repo_dir'] = os.path.join(repo_parent_dir, repo)\n a['action_dir'] = action_dir\n if '{}/{}'.format(user, repo) in cloned:\n continue\n\n if not os.path.exists(repo_parent_dir):\n os.makedirs(repo_parent_dir)\n\n if not self.dry_run:\n if not infoed:\n pu.info('', '[popper]',\n ' cloning actions from repositories\\n')\n infoed = True\n\n scm.clone(url, user, repo, repo_parent_dir, version,\n debug=self.debug)\n\n cloned.add('{}/{}'.format(user, repo))\n\n def instantiate_runners(self):\n \"\"\"Factory of ActionRunner instances, one for each action\"\"\"\n for _, a in self.wf['action'].items():\n if 'docker://' in a['uses']:\n a['runner'] = DockerRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n continue\n\n if 'shub://' in a['uses']:\n a['runner'] = SingularityRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n continue\n\n if './' in a['uses']:\n if os.path.exists(os.path.join(a['uses'], 'Dockerfile')):\n a['runner'] = DockerRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n elif os.path.exists(os.path.join(a['uses'],\n 'singularity.def')):\n a['runner'] = SingularityRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n else:\n a['runner'] = HostRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n continue\n\n dockerfile_path = os.path.join(a['repo_dir'], a['action_dir'],\n 'Dockerfile')\n singularityfile_path = os.path.join(a['repo_dir'], a['action_dir'],\n 'singularity.def')\n\n if os.path.exists(dockerfile_path):\n a['runner'] = DockerRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n elif os.path.exists(singularityfile_path):\n a['runner'] = SingularityRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n else:\n a['runner'] = HostRunner(\n a, self.workspace, self.env,\n self.quiet, self.debug, self.dry_run)\n\n def run(self, action_name=None, reuse=False, parallel=False):\n \"\"\"Run the pipeline or a specific action\"\"\"\n os.environ['WORKSPACE'] = self.workspace\n\n self.download_actions()\n self.instantiate_runners()\n\n if action_name:\n self.wf['action'][action_name]['runner'].run(reuse)\n else:\n for s in self.get_stages():\n self.run_stage(s, reuse, parallel)\n\n def run_stage(self, stage, reuse=False, parallel=False):\n if parallel:\n with ThreadPoolExecutor(max_workers=mp.cpu_count()) as ex:\n flist = {\n ex.submit(self.wf['action'][a]['runner'].run, reuse):\n a for a in stage\n }\n for future in as_completed(flist):\n try:\n future.result()\n pu.info('', '', 'Action ran successfully !\\n')\n except Exception:\n sys.exit(1)\n else:\n for action in stage:\n self.wf['action'][action]['runner'].run(reuse)\n\n @pu.threadsafe_generator\n def get_stages(self):\n \"\"\"Generator of stages. A stages is a list of actions that can be\n executed in parallel.\n \"\"\"\n current_stage = self.wf['root']\n\n while current_stage:\n yield current_stage\n next_stage = set()\n for n in current_stage:\n next_stage.update(self.wf['action'][n].get('next', set()))\n current_stage = next_stage\n\n\nclass ActionRunner(object):\n \"\"\"An action runner.\n \"\"\"\n\n def __init__(self, action, workspace, env, quiet, debug, dry_run):\n self.action = action\n self.workspace = workspace\n self.env = env\n self.quiet = quiet\n self.debug = debug\n self.dry_run = dry_run\n self.msg_prefix = \"DRYRUN: \" if dry_run else \"\"\n\n if not os.path.exists(self.workspace):\n os.makedirs(self.workspace)\n\n self.log_path = os.path.join(self.workspace, 'popper_logs')\n if not os.path.exists(self.log_path):\n os.makedirs(self.log_path)\n self.log_filename = os.path.join(\n self.log_path, self.action['name'].replace(' ', '-'))\n\n def run(self, reuse=False):\n raise NotImplementedError(\n \"This method is required to be implemented in derived classes.\"\n )\n\n\nclass DockerRunner(ActionRunner):\n def __init__(self, action, workspace, env, q, d, dry):\n super(DockerRunner, self).__init__(action, workspace, env, q, d, dry)\n self.cid = self.action['name'].replace(' ', '_')\n\n def run(self, reuse):\n build = True\n if 'docker://' in self.action['uses']:\n tag = self.action['uses'].replace('docker://', '')\n build = False\n elif './' in self.action['uses']:\n tag = 'action/' + os.path.basename(self.action['uses'])\n dockerfile_path = os.path.join(os.getcwd(), self.action['uses'])\n else:\n tag = '/'.join(self.action['uses'].split('/')[:2])\n dockerfile_path = os.path.join(self.action['repo_dir'],\n self.action['action_dir'])\n if not reuse:\n if self.docker_exists():\n self.docker_rm()\n if build:\n self.docker_build(tag, dockerfile_path)\n else:\n self.docker_pull(tag)\n self.docker_create(tag)\n else:\n if not self.docker_exists():\n if build:\n self.docker_build(tag, dockerfile_path)\n else:\n self.docker_pull(tag)\n self.docker_create(tag)\n\n e = self.docker_start()\n\n if e != 0:\n pu.fail('Action {} failed!\\n'.format(self.action['name']))\n\n def docker_exists(self):\n cmd_out, _ = pu.exec_cmd('docker ps -a',\n debug=self.debug, dry_run=self.dry_run)\n\n if self.cid in cmd_out:\n return True\n\n return False\n\n def docker_rm(self):\n pu.exec_cmd('docker rm {}'.format(self.cid),\n debug=self.debug, dry_run=self.dry_run)\n\n def docker_create(self, img):\n env_vars = self.action.get('env', {})\n\n for s in self.action.get('secrets', []):\n env_vars.update({s: os.environ[s]})\n\n for e, v in self.env.items():\n env_vars.update({e: v})\n\n env_vars.update({'HOME': os.environ['HOME']})\n\n env_flags = [\" -e {}='{}'\".format(k, v) for k, v in env_vars.items()]\n\n docker_cmd = 'docker create '\n docker_cmd += ' --name={}'.format(self.cid)\n docker_cmd += ' --volume {0}:{0}'.format(self.workspace)\n docker_cmd += ' --volume {0}:{0}'.format(os.environ['HOME'])\n docker_cmd += ' --volume {0}:{0}'.format('/var/run/docker.sock')\n docker_cmd += ' --workdir={} '.format(self.workspace)\n docker_cmd += ''.join(env_flags)\n if self.action.get('runs', None):\n docker_cmd += ' --entrypoint={} '.format(self.action['runs'])\n docker_cmd += ' {}'.format(img)\n docker_cmd += ' {}'.format(' '.join(self.action.get('args', '')))\n\n pu.info(self.msg_prefix, '['+self.action['name']+']',\n 'docker create {} {}\\n'.format(img, ' '.join(self.action.get('args', ''))\n ))\n\n pu.exec_cmd(docker_cmd, debug=self.debug, dry_run=self.dry_run)\n\n def docker_start(self):\n pu.info(self.msg_prefix, '['+self.action['name']+']',\n 'docker start \\n')\n\n cmd = 'docker start --attach {}'.format(self.cid)\n _, ecode = pu.exec_cmd(\n cmd, verbose=(not self.quiet), debug=self.debug,\n log_file=self.log_filename, dry_run=self.dry_run)\n return ecode\n\n def docker_pull(self, img):\n pu.info(self.msg_prefix, '['+self.action['name']+']',\n 'docker pull {}\\n'.format(img))\n pu.exec_cmd('docker pull {}'.format(img),\n debug=self.debug, dry_run=self.dry_run)\n\n def docker_build(self, tag, path):\n cmd = 'docker build -t {} {}'.format(tag, path)\n pu.info(self.msg_prefix, '['+self.action['name']+']',\n '{}\\n'.format(cmd))\n pu.exec_cmd(cmd, debug=self.debug, dry_run=self.dry_run)\n\n\nclass SingularityRunner(ActionRunner):\n \"\"\"Singularity Action Runner Class\n \"\"\"\n\n def __init__(self, action, workspace, env, q, d, dry):\n super(SingularityRunner, self).__init__(action, workspace, env,\n q, d, dry)\n self.pid = self.action['name'].replace(' ', '_')\n Client.quiet = q\n\n def run(self, reuse=False):\n \"\"\"Runs the singularity action\n \"\"\"\n build = True\n if 'shub://' in self.action['uses']:\n image = self.action['uses']\n build = False\n elif './' in self.action['uses']:\n image = 'action/' + os.path.basename(self.action['uses'])\n singularityfile_path = os.path.join(\n os.getcwd(), self.action['uses'])\n else:\n image = '/'.join(self.action['uses'].split('/')[:2])\n singularityfile_path = os.path.join(self.action['repo_dir'],\n self.action['action_dir'])\n\n if not reuse:\n if self.singularity_exists():\n self.singularity_rm()\n if build:\n self.singularity_build(singularityfile_path, image)\n else:\n self.singularity_pull(image)\n else:\n if not self.singularity_exists():\n if build:\n self.singularity_build(singularityfile_path, image)\n else:\n self.singularity_pull(image)\n\n e = self.singularity_start(image)\n\n if e != 0:\n pu.fail('Action {} failed!\\n'.format(self.action['name']))\n\n def generate_image_name(self, image):\n \"\"\"Generates the image name from the image url.\n \"\"\"\n return image.replace('shub://', '').replace('/', '-') + '.simg'\n\n def singularity_exists(self):\n \"\"\"Check whether an instance exists or not.\n \"\"\"\n instances = Client.instances(quiet=self.quiet)\n for instance in instances:\n if self.pid in instance.name:\n return True\n return False\n\n def singularity_rm(self):\n \"\"\"Stops and removes an instance.\n \"\"\"\n Client.instances(self.pid, quiet=self.quiet).stop()\n\n def singularity_pull(self, image):\n \"\"\"Pulls an docker or singularity images from hub.\n \"\"\"\n Client.pull(image)\n\n def singularity_build(self, path, image):\n \"\"\"Builds an image from a recipefile.\n \"\"\"\n Client.build(os.path.join(\n path, 'singularity.def'\n ), self.generate_image_name(image))\n\n def singularity_start(self, image):\n \"\"\"Starts a singularity instance based on the image.\n \"\"\"\n env_vars = self.action.get('env', {})\n\n for s in self.action.get('secrets', []):\n env_vars.update({s: os.environ[s]})\n\n for e, v in self.env.items():\n env_vars.update({e: v})\n\n env_vars.update({'HOME': os.environ['HOME']})\n\n # sets the env variables\n for k, v in env_vars.items():\n Client.setenv(k, v)\n\n e = Client.run(image=self.generate_image_name(image),\n args=' '.join(self.action.get('args', '')),\n return_result=True)\n return e['return_code']\n\n\nclass HostRunner(ActionRunner):\n def __init__(self, action, workspace, env, q, d, dry):\n super(HostRunner, self).__init__(action, workspace, env, q, d, dry)\n\n def run(self, reuse=False):\n cmd = self.action.get('runs', ['entrypoint.sh'])\n cmd[0] = os.path.join('./', cmd[0])\n cmd.extend(self.action.get('args', ''))\n\n cwd = os.getcwd()\n if not self.dry_run:\n if 'repo_dir' in self.action:\n os.chdir(self.action['repo_dir'])\n else:\n os.chdir(os.path.join(cwd, self.action['uses']))\n\n os.environ.update(self.action.get('env', {}))\n\n pu.info(self.msg_prefix, '['+self.action['name']+']',\n '{}\\n'.format(' '.join(cmd)))\n\n _, ecode = pu.exec_cmd(\n ' '.join(cmd), verbose=(not self.quiet), debug=self.debug,\n ignore_error=True, log_file=self.log_filename,\n dry_run=self.dry_run)\n\n for i in self.action.get('env', {}):\n os.environ.pop(i)\n\n os.chdir(cwd)\n\n if ecode != 0:\n pu.fail(\"\\n\\nAction '{}' failed.\\n.\".format(self.action['name']))\n","sub_path":"cli/popper/gha.py","file_name":"gha.py","file_ext":"py","file_size_in_byte":22343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"254315807","text":"from __future__ import print_function\ncau_do = [\n [7,8,0,4,0,0,1,2,0],\n [6,0,0,0,7,5,0,0,9],\n [0,0,0,6,0,1,0,7,8],\n [0,0,7,0,4,0,2,6,0],\n [0,0,1,0,5,0,9,3,0],\n [9,0,4,0,6,0,0,0,5],\n [0,7,0,3,0,0,0,1,2],\n [1,2,0,0,0,7,4,0,0],\n [0,4,9,2,0,6,0,0,7]\n]\n#Ham in ra sudoku\ndef sudoku(q):\n for d in range(len(q)):\n if d%3 == 0 and d != 0 : #d la dong va c la cot\n print(\"- - - - - - - - - - -\")\n for c in range(len(q[0])):\n if c%3 and c!=0:\n print(\"|\")\n if c == 8:\n print(str(q[d][c]))\n else:\n print(str(q[d][c]) + \"\" )\n\n\n#Ham tim loi giai cho Sudoku\n\ndef solution(q):\n tim_thay = findEmpty(q)\n if not tim_thay:\n return True\n else:\n d,c = tim_thay\n for i in range(1,10):\n if test(q, i, d, c):\n q[d][c] = i\n if solution(q):\n return True\n else:\n q[d][c] = 0\n return False\n\n#Ham tim o trong\ndef findEmpty(q):\n for d in range(len(q)):\n for c in range(len(q[0])):\n if q[d][c] == 0 :\n return d,c\n return None\n#Ham kiem tra tinh hop le cua mot cau do\ndef test(q, value, row ,col):\n for i in range(len(q[0])):\n if q[i][col] == value and i!= row:\n return False\n for i in range(len(q)):\n if q[row][i] == value and i != col:\n return False\n \n x = col // 3\n y = row // 3\n\n for i in range(y*3,y*3+3):\n for j in range(x*3,x*3+3):\n if q[i][j] == value and i!= row and j!= col :\n return False\n return True\nsudoku(cau_do)\nsolution(cau_do)\nprint('Loi giai cua cau do tren la: ')\nsudoku(cau_do)\n\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404619098","text":"import matplotlib as mpl\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nimport matplotlib.pylab as plb\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import curve_fit \nimport datetime\nfrom pandas.plotting import register_matplotlib_converters\nimport matplotlib.dates as mdates\nregister_matplotlib_converters()\nimport time\n\nimport requests\n\n# account_id = 'vrYTiexpWDh_8et0s2ay4unXtfBu-m0P3I3e3g-ZbZ3ibg' #frank\n# summoner_id = 'oS992syEwEl4RHwId4maA_Voz_uhvpk3BszwUiASzjEeXQ0' #frank\n# summoner_name_global = 'Frank Drebin'\n\napi_key = 'RGAPI-1511c5f9-3875-4d70-a7d6-374e6c31cba4'\n\naccount_id = 'REwF0pRNRdEV0MCSVwEYBSwGy1s6jeEw3l7U39wg1oVQug' #beware\nsummoner_id = 'zI2FIMMuLs4IEYsaOm6zsLDmW2797EBBPw5jVN_UAswPUwI' #beware\nsummoner_name_global = 'bewareoftraps'\n\n \n\ndef matchlist_url_maker(api_key, account_id, queue, beginIndex, endIndex):\n url = \"https://euw1.api.riotgames.com/lol/match/v4/matchlists/by-account/\"\n url += account_id + '?'\n url += 'queue=' + str(queue) + '&'\n url += 'beginIndex=' + str(beginIndex) + '&'\n url += 'endIndex=' + str(endIndex) + '&'\n url += 'api_key=' + api_key \n\n return url\n\ndef game_url_maker(api_key, game_id):\n url = 'https://euw1.api.riotgames.com/lol/match/v4/matches/'\n url += str(game_id) + '?'\n url += 'api_key=' + api_key\n\n return url\n\ndef get_match_list(account_id):\n\n url = matchlist_url_maker(api_key, account_id, 450, 0, 5)\n # fail_count = 0\n \n \n response = requests.get(url)\n match_dict = response.json()['matches'] #list of dicts corresponding to matches\n df_matchlist = pd.DataFrame.from_dict(match_dict)\n\n \n # time.sleep(1)\n # fail_count += 1\n # if fail_count == 10:\n # df_matchlist = pd.DataFrame()\n # break\n # continue\n \n \n # print(df_match.columns)\n\n # for i in range(100000):\n # beginIndex = (i+1)*100\n # url = matchlist_url_maker(api_key, account_id, 450, beginIndex)\n # response = requests.get(url)\n # match_dict = response.json()['matches']\n # if len(match_dict) == 0:\n # break\n # # df_dum = pd.DataFrame.from_dict(match_dict)\n # df_matchlist = df_matchlist.append(pd.DataFrame.from_dict(match_dict))\n\n\n return df_matchlist\n\ndef get_participant_id(list_identities):\n\n for i in range(len(list_identities)):\n\n str_summoner_name = list_identities[i]['player']['summonerName']\n if str_summoner_name == summoner_name_global:\n my_id = i+1\n break\n\n return my_id\n\n\ndef get_team_dmg(response):\n\n team_1_dmg = 0\n team_2_dmg = 0\n for participant in range(1,6):\n team_1_dmg += response.json()['participants'][participant-1]['stats']['totalDamageDealtToChampions']\n\n for participant in range(6,11):\n team_2_dmg += response.json()['participants'][participant-1]['stats']['totalDamageDealtToChampions']\n\n return team_1_dmg, team_2_dmg\n\n\n\ndef get_player_game_info(api_key, game_id): #, player_id\n\n url = game_url_maker(api_key, game_id)\n # print(url)\n while True:\n try:\n response = requests.get(url)\n list_identities = response.json()['participantIdentities']\n except:\n print('exception occured')\n time.sleep(1)\n continue\n else:\n break\n list_data_all_players_one_game = []\n\n for player_id in range(1,11):\n my_id = player_id\n dict_player = response.json()['participants'][my_id-1]['stats']\n dict_player['gameDuration'] = response.json()['gameDuration']\n dict_player['gameCreation'] = response.json()['gameCreation']\n dict_player['championId'] = response.json()['participants'][my_id-1]['championId']\n dict_player['gameId'] = response.json()['gameId']\n teamId = response.json()['participants'][my_id-1]['teamId']\n dict_player['teamId'] = teamId\n\n team_1_dmg, team_2_dmg = get_team_dmg(response)\n dict_player['team1dmg'] = team_1_dmg\n dict_player['team2dmg'] = team_2_dmg\n dmg_dealt = response.json()['participants'][my_id-1]['stats']['totalDamageDealtToChampions']\n\n dmg_share = 0\n if teamId == 100:\n dmg_share = dmg_dealt/team_1_dmg\n if teamId == 200:\n dmg_share = dmg_dealt/team_2_dmg\n dict_player['dmgShare'] = dmg_share\n list_data_all_players_one_game.append(dict_player)\n\n list_account_ids = [ list_identities[i]['player']['accountId'] for i in range(10) ]\n\n df_1_game = pd.DataFrame.from_dict(list_data_all_players_one_game)\n \n return df_1_game, list_account_ids\n\n\n\ndef get_player_info(df_matchlist):\n\n # list_player_info = []\n matchlist = df_matchlist['gameId'].to_numpy()\n counter = 0\n for game_id in matchlist:\n counter += 1\n # print(counter, game_id)\n df_1_game, list_account_ids = get_player_game_info(api_key, game_id) #, player_id\n time.sleep(1.3)\n if counter == 1:\n df_gameinfo = df_1_game\n continue\n df_gameinfo = df_gameinfo.append(df_1_game, ignore_index = True)\n \n # if counter == 2:\n # break\n \n # df_gameinfo = pd.DataFrame.from_dict(list_player_info)\n \n return df_gameinfo, list_account_ids\n\n\nfor i in range(2000):\n print('account id:', account_id)\n print('summoner number:', i)\n while True:\n try:\n df_matchlist = get_match_list( account_id )\n df_matchlist['time'] = pd.to_datetime(df_matchlist['timestamp'], unit='ms') \n except:\n while True:\n j = np.random.randint(0,10)\n new_account_id = list_account_ids[j]\n if new_account_id != account_id:\n account_id = new_account_id\n break\n continue\n else:\n df_gameinfo_dum, list_account_ids = get_player_info( df_matchlist )\n while True:\n j = np.random.randint(0,10)\n new_account_id = list_account_ids[j]\n if new_account_id != account_id:\n account_id = new_account_id\n break\n break\n \n print('shape of dataframe of this game:', df_gameinfo_dum.shape)\n if i == 0:\n df_gameinfo = df_gameinfo_dum\n continue\n df_gameinfo = df_gameinfo.append(df_gameinfo_dum, ignore_index = True)\n print('shape of total dataframe:', df_gameinfo.shape)\n\n\n\n\ndf_gameinfo.to_csv('C:/Users/U2JD7FU/Desktop/Private/Programmieren/Python/Lol/game-data.csv')\ndf_gameinfo.to_excel('C:/Users/U2JD7FU/Desktop/Private/Programmieren/Python/Lol/game-data.xlsx')\n\n\nprint(df_gameinfo.columns)\nprint(df_gameinfo.shape)\n\n","sub_path":"game-scraping_random_games.py","file_name":"game-scraping_random_games.py","file_ext":"py","file_size_in_byte":6730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"165080307","text":"import gpiozero, os, time\n\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\nfrom devices import pump\n\nstart = time.time()\n\nprint(time.strftime(\"%Y-%m-%d %H:%M:%S\"), 0.0) # Redirect to pump.log\n\npump.on()\ntime.sleep(121.970)\npump.off()\n","sub_path":"pump.py","file_name":"pump.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569424210","text":"import re\nfrom collections import Counter\nFILESOURCE = '0004.txt'\n\ndef getMostCommonWord(articlefilesource):\n '''输入一个英文的纯文本文件,统计其中的单词出现的个数'''\n pattern = r'''[A-Za-z]+|\\$?\\d+%?$'''\n with open(articlefilesource) as f:\n r = re.findall(pattern,f.read())\n words=[]\n for word in r:\n word=word.lower()\n words.append(word)\n# print(type(Counter(words)))\n m=Counter(words)\n f=open('0004new_out.txt','w')\n for each in m:\n f.write(each+':'+str(m[each])+'\\n')\n\n return Counter(words)\n\nif __name__ == '__main__':\n getMostCommonWord(FILESOURCE)\n","sub_path":"0004/0004new.py","file_name":"0004new.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"599810116","text":"from __future__ import division, print_function\nfrom libtbx.program_template import ProgramTemplate\nimport mmtbx.nci.hbond\n\n# =============================================================================\n\nclass Program(ProgramTemplate):\n\n description = '''\nphenix.hbond: tool to find H bonds in an atomic model\n\nUsage example:\n phenix.hbond model.pdb\n '''\n\n datatypes = ['model', 'phil']\n\n master_phil_str = mmtbx.nci.hbond.master_phil_str\n\n # ---------------------------------------------------------------------------\n def validate(self):\n print('Validating inputs', file=self.logger)\n self.data_manager.has_models(raise_sorry=True)\n\n # ---------------------------------------------------------------------------\n def run(self):\n print('Using model: %s' % self.data_manager.get_default_model_name(),\n file=self.logger)\n model = self.data_manager.get_model()\n self.results = mmtbx.nci.hbond.find(model = model)\n self.results.show(log = self.logger)\n print(\"-\"*79, file=self.logger)\n self.results.show_summary(log = self.logger)\n if self.params.hbond.output_pymol_files:\n self.results.as_pymol()\n\n # ---------------------------------------------------------------------------\n def get_results(self):\n return self.results\n\n# =============================================================================\n# end\n","sub_path":"mmtbx/programs/hbond.py","file_name":"hbond.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401150929","text":"# -*- coding: utf-8 -*-\r\nimport json\r\nimport urllib2\r\n\r\nfrom bottle import route, run, request\r\nimport bottle\r\n\r\n\r\nbottle.BaseRequest.MEMFILE_MAX = 1024 * 1024\r\n\r\n\r\ndef getPOIs(start_point, radius):\r\n radius = float(radius) * 1000\r\n #grocery, shopping, park & entertainment, book\r\n #usage: node[shop=bakery]\r\n osm_feature_list = {\r\n 'grocery': ['shop=alcohol', 'shop=bakery', 'shop=beverages', 'shop=butcher', 'shop=convenience', 'shop=general',\r\n 'shop=department_store', 'shop=farm', 'shop=mall', 'shop=supermarket'], #grocery\r\n 'shopping': ['shop'], #shopping\r\n 'park&entertainment': ['leisure', 'historic', 'sport'], #entertainment\r\n 'bookstore': ['shop=books'] #library\r\n }\r\n\r\n #bank, restaurant & cafe, park & entertainment, school, book, hospital\r\n #usage: node[\"amenity=atm\"]\r\n osm_amenity_list = {'atm', 'bank', #bank\r\n 'bar', 'pub', 'restaurant', 'fast_food', 'food_court', 'cafe', #restaurant\r\n 'marketplace', #shopping\r\n 'arts_centre', 'cinema', 'nightclub', 'theatre',\r\n #entertainment and also from osm_feature_list\r\n 'school', 'kindergarten', 'college', 'university', #school\r\n 'library', #library and also from osm_feature_list\r\n 'clinic', 'dentist', 'doctors', 'hospital', 'pharmacy', 'veterinary' #health\r\n }\r\n\r\n #query example: (\r\n # node(around:2000,51.0461,-114.0712)[shop=convenience];\r\n # node(around:2000,51.0461,-114.0712)[\"amenity\"=\"pub\"];\r\n # );\r\n # out body;\r\n\r\n _amenity_query = ''\r\n for item in osm_amenity_list:\r\n _amenity_query += 'node(around:%s,%s)[\"amenity\"=\"%s\"];' % (radius, start_point, item)\r\n\r\n _feature_query = ''\r\n for item in osm_feature_list:\r\n _category_member = osm_feature_list[item]\r\n if len(_category_member) == 1:\r\n _feature_query += 'node(around:%s,%s)[%s];' % (radius, start_point, _category_member[0])\r\n else:\r\n for sub_item in _category_member:\r\n _feature_query += 'node(around:%s,%s)[%s];' % (radius, start_point, sub_item)\r\n\r\n _output = 'json'\r\n\r\n _query = '[out:%s];(%s);out body;' % (_output, _feature_query + _amenity_query)\r\n\r\n _overpass_url = 'http://overpass-api.de/api/interpreter'\r\n\r\n _overpass_request = urllib2.Request(url=_overpass_url, data=_query, headers={'Content-Type': 'application/json'})\r\n\r\n poi_data = urllib2.urlopen(_overpass_request).read()\r\n\r\n #getting rid of non-ASCII characters\r\n poi_data = removeNonAscii(poi_data)\r\n\r\n #getting rid of special characters like &\r\n poi_data = poi_data.replace('&', 'and')\r\n poi_data = poi_data.replace(';', ' ')\r\n\r\n poi_data_json = json.loads(poi_data)\r\n\r\n _elements = poi_data_json['elements']\r\n\r\n result_json = '\"NULL\"'\r\n\r\n if len(_elements) >= 1:\r\n\r\n result_json = '{\"type\": \"FeatureCollection\", \"features\": ['\r\n\r\n for item in _elements:\r\n _lat = item['lat']\r\n _lon = item['lon']\r\n _location = \"[%s,%s]\" % (_lon, _lat)\r\n _tags = item['tags']\r\n\r\n _icon = 'http://webmapping.ucalgary.ca/maki/marker-18.png'\r\n _type = 'POI'\r\n #POI types: Bank, Restaurant, Shopping, Grocery, Entertainment, School, Library, Health\r\n if 'shop' in _tags:\r\n _type = 'Grocery'\r\n if _tags['shop'] == 'alcohol' or _tags['shop'] == 'beverages':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/alcohol-shop-18.png'\r\n elif _tags['shop'] == 'bakery':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/bakery-18.png'\r\n elif _tags['shop'] == 'books':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/library-18.png'\r\n else:\r\n _icon = 'http://webmapping.ucalgary.ca/maki/shop-18.png'\r\n _type = 'Shopping'\r\n elif 'leisure' in _tags:\r\n _icon = 'http://webmapping.ucalgary.ca/maki/playground-18.png'\r\n _type = 'Entertainment'\r\n elif 'sport' in _tags:\r\n _icon = 'http://webmapping.ucalgary.ca/maki/basketball-18.png'\r\n _type = 'Entertainment'\r\n elif 'historic' in _tags:\r\n _icon = 'http://webmapping.ucalgary.ca/maki/town-hall-18.png'\r\n _type = 'Entertainment'\r\n elif 'amenity' in _tags:\r\n if _tags['amenity'] == 'atm' or _tags['amenity'] == 'bank':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/bank-18.png'\r\n _type = 'Bank'\r\n elif _tags['amenity'] == 'bar' or _tags['amenity'] == 'pub':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/bar-18.png'\r\n _type = 'Restaurant'\r\n elif _tags['amenity'] == 'restaurant':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/restaurant-18.png'\r\n _type = 'Restaurant'\r\n elif _tags['amenity'] == 'cafe':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/cafe-18.png'\r\n _type = 'Restaurant'\r\n elif _tags['amenity'] == 'fast_food' or _tags['amenity'] == 'food_court':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/fast-food-18.png'\r\n _type = 'Restaurant'\r\n elif _tags['amenity'] == 'marketplace':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/shop-18.png'\r\n _type = 'Grocery'\r\n elif _tags['amenity'] == 'arts_centre':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/art-gallery-18.png'\r\n _type = 'Entertainment'\r\n elif _tags['amenity'] == 'cinema':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/cinema-18.png'\r\n _type = 'Entertainment'\r\n elif _tags['amenity'] == 'nightclub':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/music-18.png'\r\n _type = 'Entertainment'\r\n elif _tags['amenity'] == 'theatre':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/theatre-18.png'\r\n _type = 'Entertainment'\r\n elif _tags['amenity'] == 'school' or _tags['amenity'] == 'kindergarten':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/school-18.png'\r\n _type = 'School'\r\n elif _tags['amenity'] == 'college' or _tags['amenity'] == 'university':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/college-18.png'\r\n _type = 'School'\r\n elif _tags['amenity'] == 'library':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/library-18.png'\r\n _type = 'Library'\r\n elif _tags['amenity'] == 'hospital' or _tags['amenity'] == 'clinic' or _tags['amenity'] == 'dentist' or \\\r\n _tags['amenity'] == 'doctors' or _tags['amenity'] == 'veterinary':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/hospital-18.png'\r\n _type = 'Health'\r\n elif _tags['amenity'] == 'pharmacy':\r\n _icon = 'http://webmapping.ucalgary.ca/maki/pharmacy-18.png'\r\n _type = 'Health'\r\n\r\n if 'name' in _tags:\r\n _name = _tags['name']\r\n else:\r\n _name = _type\r\n result_json += '{\"type\": \"Feature\",\"geometry\": {\"type\": \"Point\", \"coordinates\":%s}, \"properties\": {\"name\": \"%s\", \"type\": \"%s\", \"icon\": \"%s\"}},' % (\r\n _location, _name, _type, _icon)\r\n\r\n result_json = result_json[:-1]\r\n result_json += ']}'\r\n\r\n return result_json\r\n\r\n\r\n#To get rid of non-ASCII characters\r\ndef removeNonAscii(s):\r\n return \"\".join(i for i in s if ord(i) < 128)\r\n\r\n\r\n# start_point = '51.098239989909565,-114.14949417114258'\r\n# radius = '1.25' #unit: m\r\n# print getPOIs(start_point, radius)\r\n\r\n@route('/poi')\r\ndef service():\r\n start_point = request.GET.get('start_point', default=None)\r\n radius = request.GET.get('radius', default=None)\r\n if start_point and radius is not None:\r\n return getPOIs(start_point, radius)\r\n\r\n\r\nrun(host='0.0.0.0', port=6365, debug=True)\r\n\r\n#http://127.0.0.1:6365/poi?start_point=51.05723044585338,-114.11717891693115&radius=1.60934\r\n","sub_path":"WalkYourPlace/POIService.py","file_name":"POIService.py","file_ext":"py","file_size_in_byte":8559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"638689428","text":"\"\"\"\n\nConsecutive prime sum\n\nThe prime 41, can be written as the sum of six consecutive primes:\n41 = 2 + 3 + 5 + 7 + 11 + 13\nThis is the longest sum of consecutive primes that adds to a prime below one-hundred.\nThe longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.\nWhich prime, below one-million, can be written as the sum of the most consecutive primes?\n\n\"\"\"\n\ndef prime(n):\n for i in range(2, int(n**.5)+1):\n if n % i == 0:\n return False\n return True\n\nprimes = []\ncount = 2\nlongest = 0, 0\n\nwhile sum(primes) < 1000000:\n if prime(count):\n l = len(primes)\n for a in range(l):\n if l-a > longest[0]:\n s = sum(primes[a:])\n if prime(s):\n longest = l-a,s\n break\n primes.append(count)\n count += 1\n\nprint(longest[1])\n","sub_path":"Problem 050.py","file_name":"Problem 050.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"302967925","text":"__AUTHOR__ = 'Reverier Xu'\n\nimport copy\n\nfrom DataFlowPanel.DataFlowNodeEditor import *\nfrom DataFlowPanel.ui_DataFlowPanel import ui_DataFlowPanel\nfrom ui_Widgets.qtpynodeeditor import *\n\nimport importlib\nimport os\n\nModules = {}\n\n\ndef get_modules(package=\".\"):\n \"\"\"\n 获取包名下所有非__init__的模块名\n \"\"\"\n modules = []\n files = os.listdir(package)\n\n for file in files:\n if not file.startswith(\"__\"):\n name, ext = os.path.splitext(file)\n modules.append(\".\" + name)\n\n return modules\n\n\ndef ScanModules():\n Modules.clear()\n for module in get_modules('Modules/DataFlow'):\n module = importlib.import_module(module, 'Modules.DataFlow')\n try:\n Modules[module.properties['name']] = module\n except:\n pass\n\n\nclass DataFlowPanel(ui_DataFlowPanel):\n def __init__(self):\n super(DataFlowPanel, self).__init__()\n self.ToolsSearchBox.textChanged.connect(self.ToolsList.filter)\n self.RegisterModule()\n try:\n self.CryptoToolNodeEditor.scene.load('UserConfig/NodeEditorCurrent.rxf')\n except:\n pass\n self.SaveButton.clicked.connect(lambda **kwargs: self.CryptoToolNodeEditor._scene.save())\n\n def RegisterModule(self):\n self.ToolsList.clear()\n ScanModules()\n self.ToolsList.addDIYItem('Input', '基本')\n self.ToolsList.addDIYItem('File Input', '基本')\n self.ToolsList.addDIYItem('Output', '基本')\n self.ToolsList.addDIYItem('Image Output', '基本')\n self.ToolsList.addDIYItem('File Output', '基本')\n for i in Modules:\n self.ToolsList.addDIYItem(i, Modules[i].properties['categories'])\n reg = DataModelRegistry()\n reg.register_model(InputModel, category='Basic')\n reg.register_model(OutputModel, category='Basic')\n reg.register_model(ImageShowModel, category='Basic')\n reg.register_model(FileInputModel, category='Basic')\n reg.register_model(FileOutputModel, category='Basic')\n for i in Modules:\n class DIYNodesDataModule(CryptoComputeModel):\n port_caption_visible = True\n data_type = StringData.data_type\n module = Modules[i]\n properties = module.properties\n num_ports = {PortType.input: len(module.properties['input']),\n PortType.output: len(module.properties['output'])}\n port_caption = {'input': module.properties['input'],\n 'output': module.properties['output']}\n name = Modules[i].properties['name']\n\n def __init__(self, *args, **kwargs):\n self.settings = copy(self.module.defaults)\n self.func = self.module.main\n self.inputs = {}\n self.outputs = {}\n super().__init__(self.module, *args, **kwargs)\n\n def save(self):\n doc = super().save()\n if self.settings:\n doc['settings'] = self.settings\n return doc\n\n def restore(self, doc: dict):\n try:\n value = copy(doc[\"settings\"])\n except Exception:\n ...\n else:\n self.settings = value\n\n reg.register_model(DIYNodesDataModule,\n category=Modules[i].properties['categories'])\n scene = FlowScene(reg)\n self.CryptoToolNodeEditor.setScene(scene)\n self.CryptoToolNodeEditor.scene.node_double_clicked.connect(\n self.OptionsBox.LoadOptions)\n\n def closeEvent(self, QCloseEvent):\n self.CryptoToolNodeEditor.scene.save('UserConfig/NodeEditorCurrent.rxf')\n","sub_path":"DataFlowPanel/DataFlowPanel.py","file_name":"DataFlowPanel.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"640010433","text":"\"\"\"Dataset for speaker embedding.\"\"\"\n\nimport os\nimport pickle\nfrom random import randint, sample\n\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.nn.utils.rnn import pad_sequence\n\n\nclass SEDataset(Dataset):\n \"\"\"Sample utterances from a single speaker.\"\"\"\n\n def __init__(self, data_dir, n_utterances=5, seg_len=128):\n \"\"\"\n Args:\n data_dir (string): path to the directory of pickle files.\n n_utterances (int): # of utterances per speaker to be sampled.\n seg_len (int): the minimum length of segments of utterances.\n \"\"\"\n\n assert os.path.isdir(data_dir)\n\n self.data_paths = []\n self.n_uttrances = n_utterances\n self.seg_len = seg_len\n\n for spkr_dir in os.listdir(data_dir):\n data_path = os.path.join(data_dir, spkr_dir)\n data = pickle.load(open(data_path, \"rb\"))\n if len(data) < n_utterances:\n continue\n self.data_paths.append(data_path)\n\n def __len__(self):\n return len(self.data_paths)\n\n def __getitem__(self, sid):\n data = pickle.load(open(self.data_paths[sid], \"rb\"))\n uttrs = sample(data, self.n_uttrances)\n lefts = [randint(0, len(uttr) - self.seg_len)\n if len(uttr) > self.seg_len else None\n for uttr in uttrs]\n sgmts = [uttr[left:left+self.seg_len, :]\n if left is not None else uttr\n for uttr, left in zip(uttrs, lefts)]\n return [torch.from_numpy(sgmt) for sgmt in sgmts]\n\n\ndef pad_batch(batch):\n \"\"\"Pad a whole batch of utterances.\"\"\"\n flatten = [u for s in batch for u in s]\n return pad_sequence(flatten, batch_first=True, padding_value=0)\n","sub_path":"modules/se_dataset.py","file_name":"se_dataset.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"412981456","text":"from dolfin import *\n\ndef set_brinkman_problem(\n mesh,\n subdomains,\n boundaries,\n subodmainMarkers = {\n 'sub1': 1,\n 'sub2': 2\n },\n boundaryMarkers = {\n 'inlet': 1,\n 'outlet': 2,\n },\n mu=0.001003, # Water Viscosity [Pa.s]\n k=9.869233e-15, #permeability of porous matrix\n pin=Constant(1.0), # Input Pressure [Pa]\n pout=Constant(-1.0), # Output Pressure [Pa\n f=Constant((0.0, 0.0, 0.0)) # external force\n ):\n\n V = VectorElement('P', mesh.ufl_cell(), 2)\n Q = FiniteElement('P', mesh.ufl_cell(), 1)\n Element = MixedElement([V, Q])\n\n W = FunctionSpace(mesh, Element)\n (u, p) = TrialFunctions(W)\n (v, q) = TestFunctions(W)\n\n # Markers to integral infinitesimal terms\n ds = Measure('ds', domain=mesh, subdomain_data=boundaries)\n dx = Measure('dx', domain=mesh, subdomain_data=subdomains)\n\n # normal vector\n n = FacetNormal(mesh)\n\n # boundary conditions\n bc1 = DirichletBC(W.sub(0).sub(1),Constant(0.0),boundaries,3) #y direction\n bc2 = DirichletBC(W.sub(0).sub(2),Constant(0.0),boundaries,4) #z direction\n bcs = [bc1, bc2]\n\n # Variational terms\n aD = lambda k, u, v: ((mu / k) * inner(u, v))\n aS = lambda u, v: 2 * mu * inner((grad(u)), grad(v))\n b = lambda u, q: (div(u) * q)\n lf = lambda f, v: inner(f, v)\n\n # complete variational form\n aB = aS(u, v) * dx(subodmainMarkers['sub1']) + aD(k, u, v) * dx(subodmainMarkers['sub2']) - b(v, p) * dx - b(u, q) * dx\n\n l = lf(f, v) * dx - pin * dot(v, n) * ds(boundaryMarkers['inlet']) - pout * dot(v, n) * ds(boundaryMarkers['outlet'])\n\n A = assemble(aB)\n L = assemble(l)\n for bc in bcs:\n bc.apply(A,L)\n\n return A, L, W\n\ndef solve_linear_system(A, L, W):\n w = Function(W)\n solve(A, w.vector(), L, 'mumps', 'none')\n\n return w\n","sub_path":"src/Simulator/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"149942275","text":"from django.conf import settings\nfrom rest_framework.exceptions import ValidationError\n\nfrom .serializers import LogSerializer\n\nlogger = settings.LOGGER\n\n\ndef report_event(msg, ltype='default', callback=None):\n \"\"\"事件报告写入日志\"\"\"\n try:\n data = {\n 'ltype': ltype,\n 'info': {\n 'data': msg,\n },\n }\n serializer = LogSerializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n if callback and callable(callback):\n callable(data)\n except ValidationError as e:\n logger.error(f'写入日志错误: {e}')\n\ndef report_auth_event(msg, callback=None):\n report_event(msg, ltype='auth', callback=callback)\n","sub_path":"homados/apps/userauth/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"75852795","text":"import builtins\nimport json\nimport os\nimport types\nfrom datetime import timedelta\nfrom pathlib import Path\nfrom io import StringIO\nfrom typing import Any, Union, Dict, Tuple, List\n\n\ndef number_to_path_string(number):\n\tpath = '%08x' % (number & 0xffffffff) # TODO does this do anything?\n\tpp = StringIO(path)\n\tp = '/'.join([pp.read(2), pp.read(2), pp.read(2), pp.read(2)])\n\treturn p\n\n\nclass LeafPage(object):\n\tdef __init__(self, number, store):\n\t\tself._flush_actions = []\n\t\tself.number = number\n\t\tself.store = store\n\t\tif type(number) is int:\n\t\t\tself.path_string = number_to_path_string(number)\n\t\telse:\n\t\t\tself.path_string = number\n\t\tself.path = Path(self.path_string)\n\t\t\n\tdef exists(self) -> bool:\n\t\treturn Path(self.store.root, self.path, \"HiStore.info\").exists()\n\t\n\tdef read(self): # -> Optional[HiStoreKey]:\n\t\tif not self.exists():\n\t\t\treturn None\n\t\twith open(Path(self.store.root, self.path, \"HiStore.info\"), 'r') as fp:\n\t\t\tx = json.loads(fp.read())\n\t\t\tprint (10034, x)\n\t\t\t#\n\t\t\t# TODO Support reservation on Content not whole directory\n\t\t\t#\n\t\t\tif x['type']=='reservation':\n\t\t\t\tk = HiStoreKey(self.path_string, x['type'], timedelta(seconds=self.store._default_timeout), self.path)\n\t\t\telse:\n\t\t\t\tk = HiStoreKey(self.path_string, x['type'], 0, self.path)\n\t\t\treturn k\n\t\t\n\tdef flush(self) -> List[Tuple]:\n\t\terrs = []\n\t\tfor each in self._flush_actions:\n\t\t\tb = each.act()\n\t\t\tif b:\n\t\t\t\tself._flush_actions.remove(each)\n\t\t\telse:\n\t\t\t\terrs += (each, b)\n\t\treturn errs\n\t\n\tdef openReader(self, filename: str):\n\t\tif filename == 'HiStore.info':\n\t\t\treturn None\n\t\tr = HiStoreReader(filename, Path(self.store.root, self.path), self)\n\t\treturn r\n\t\n\tdef openWriter(self, filename):\n\t\tif filename == 'HiStore.info':\n\t\t\treturn None\n\t\tr = HiStoreWriter(filename, Path(self.store.root, self.path), self)\n\t\treturn r\n\n\tdef hasContent(self, filename):\n\t\tif filename == 'HiStore.info':\n\t\t\treturn None\n\t\tr = Path(self.store.root, self.path, filename).exists()\n\t\treturn r\n\t\n\tdef listInternal(self):\n\t\tpth = Path(self.store.root, self.path)\n\t\tx = [(x, x.parts[-1]) for x in pth.iterdir()]\n\t\treturn x\n\n\t__slots__ = ('_flush_actions', 'number', 'store', 'path_string', 'path')\n\n\nclass HiStoreKey:\n\tpage: LeafPage\n\ttype: str # content | reservation\n\tpath: str\n\texpiry: timedelta\n\t\n\tdef __init__(self, path, type_, expiry, page):\n\t\tself.path = path\n\t\tself.type = type_\n\t\tself.expiry = expiry\n\t\tself.page = page\n\t\t\n\t__slots__ = ('path',\n\t\t\t\t 'type', # type is Reservation or Content\n\t\t\t\t 'expiry',\n\t 'page')\n\t\n\nclass HiStore(object):\n\tpagecache: Dict[int, LeafPage]\n\t\n\tdef __init__(self, root: str):\n\t\tself._default_timeout = 30 # seconds\n\t\tself.root = root\n\t\tself.pagecache = {}\n\t\tself.freepage = None\n\t\tif not Path(root).exists():\n\t\t\tos.makedirs(Path(root))\n\n\tdef allocate(self) -> HiStoreKey:\n\t\tp = self.find_next_page()\n\t\tk = HiStoreKey(p.path_string, 'reservation', timedelta(seconds=self._default_timeout), p)\n\t\treturn k\n\t\n\tdef resolve(self, key: int) -> HiStoreKey:\n\t\tp, f = self._get_page(key)\n\t\tk = HiStoreKey(p.path_string, 'content', timedelta(seconds=self._default_timeout), p)\n\t\treturn k\n\n\tdef resolve_key(self, skey: str) -> HiStoreKey:\n\t\tkey = int(skey.replace('/', ''), 16)\n\t\treturn self.resolve(key)\n\n\tdef find_next_page(self):\n\t\tif self.freepage is None:\n\t\t\tself.freepage, f = self._get_page(0)\n\t\t\t\n\t\tif self.freepage.exists():\n\t\t\twhile self.freepage.exists():\n\t\t\t\t(self.freepage, new_page) = self._get_page(self.freepage.number+1, True)\n\t\t\t\tif new_page:\n\t\t\t\t\tbreak\n\t\t\n\t\treturn self.freepage\n\t\n\tdef _get_page(self, number, reservation=False) -> Tuple[LeafPage, bool]:\n\t\tnew_page = False\n\t\tif number in self.pagecache:\n\t\t\treturn (self.pagecache[number], False)\n\t\tp = LeafPage(number, self)\n\t\tx = p.read()\n\t\tif x is None:\n\t\t\tos.makedirs(Path(self.root, p.path), exist_ok=True)\n\t\t\twith open(Path(self.root, p.path, \"HiStore.info\"), 'w') as fp:\n\t\t\t\tif reservation:\n\t\t\t\t\ty = {'type': 'reservation'}\n\t\t\t\t\tnew_page = True # TODO\n\t\t\t\telse:\n\t\t\t\t\ty = {'type': 'content'}\n\t\t\t\tfp.write(json.dumps(y))\n\t\t\tx = p.read()\n\t\tself.pagecache[number] = p\n\t\treturn (p, new_page)\n\n\tdef openReader(self, key: HiStoreKey, filename: str):\n\t\t# print (10123, filename)\n\t\treturn key.page.openReader(filename)\n\n\tdef openWriter(self, key: HiStoreKey, filename: str):\n\t\t\"\"\"\n\n\t\t:param key:\n\t\t:type filename: basestring\n\t\t\"\"\"\n\t\treturn key.page.openWriter(filename)\n\t\n\tdef validKeys(self):\n\t\t\"\"\"\n\t\tImplement a naive version for now\n\t\tShould read a HiStore.info file at every level, or you could just walk the dirs\n\t\t\n\t\t:return: a list of valid key strings\n\t\t\"\"\"\n\t\tr = []\n\t\tx = 0\n\t\twhile True:\n\t\t\tdp = LeafPage(x, self)\n\t\t\tif dp.exists():\n\t\t\t\tr.append(dp.path_string)\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\tx = x + 1\n\t\treturn r\n\nclass HiStoreWriter(object):\n\tfilename: str\n\tpath: Path\n\tstore: LeafPage\n\t\n\tdef __init__(self, filename, path, store):\n\t\tself.filename = filename\n\t\tself.path = Path(path, filename)\n\t\tself.key_path = path\n\t\tself.store = store\n\t\tself.fp = open(self.path, 'wb')\n\n\tdef write(self, content: bytes, offset: int = None):\n\t\tif content is not None:\n\t\t\tif offset is not None:\n\t\t\t\tself.fp.seek(offset)\n\t\tif type(content) is str:\n\t\t\tcontent = content.encode() # convert to bytes\n\t\tself.fp.write(content)\n\n\tdef close(self):\n\t\tif self.fp is not None:\n\t\t\twith open(Path(self.key_path, \"HiStore.info\"), 'w') as fp:\n\t\t\t\ty = {'type': 'content'}\n\t\t\t\tfp.write(json.dumps(y))\n\n\t\t\tself.fp.close()\n\t\t\tself.fp = None\n\n\nclass HandleError(Exception):\n\tpass\n\n\nclass HiStoreReader(object):\n\tfilename: str\n\tpath: Path\n\tstore: HiStore\n\t\n\tdef __init__(self, filename, path, store):\n\t\tself.filename = filename\n\t\tif not path.exists():\n\t\t\tos.makedirs(path)\n\t\tself.path = Path(path, filename)\n\t\tself.store = store\n\t\tif os.path.exists(self.path):\n\t\t\tself.fp = open(self.path, 'rb')\n\t\telse:\n\t\t\tself.fp = None\n\t\t\t\n\tdef read(self, amount: int = None) -> bytes:\n\t\tif self.fp is not None:\n\t\t\tif amount is None:\n\t\t\t\treturn self.fp.read()\n\t\t\telse:\n\t\t\t\treturn self.fp.read(amount)\n\t\telse:\n\t\t\traise HandleError(self)\n\n\tdef close(self):\n\t\tif self.fp is not None:\n\t\t\tself.fp.close()\n\t\t\tself.fp = None\n","sub_path":"src/histore/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"176207054","text":"__author__ = 'Frederik Diehl'\n\nfrom abc import ABCMeta, abstractmethod\nfrom time import sleep\nimport multiprocessing\nimport Queue\n\n\nclass Optimizer(object):\n \"\"\"\n This defines a basic Optimizer interface.\n\n An optimizer contains an _experiment, which represents the last known state\n of the experiment. It can be updated using update, while the next\n candidates can be generated with get_next_candidates, which represent the\n actual work of the optimizer.\n Additionally, it contains an exit function, which can be used to cleanly\n exit the optimizer. Since the optimizer may well implement multicore or\n distributed architectures, it is necessary to cleanly exit.\n\n Parameters\n ----------\n SUPPORTED_PARAM_TYPES : list\n A list of the supported parameters for this optimizer. Not all\n parameters may be supported by any optimizer.\n _experiment : Experiment\n The current state of the experiment. Is used as a base for the the\n optimization.\n \"\"\"\n __metaclass__ = ABCMeta\n\n SUPPORTED_PARAM_TYPES = []\n\n _experiment = None\n\n def __init__(self, experiment, optimizer_params):\n \"\"\"\n Initializes the optimizer.\n\n Parameters\n ----------\n experiment : Experiment\n The experiment representing the current state of the execution.\n optimizer_params : dict, optional\n Dictionary of the optimizer parameters. If None, some standard\n parameters will be assumed.\n\n Raises\n ------\n ValueError\n Iff the experiment is not supported.\n \"\"\"\n if not self._is_experiment_supported(experiment):\n raise ValueError(\"Experiment contains unsupported parameters. \"\n \"Optimizer %s supports %s, experiment parameters \"\n \"are %s.\" %(self.__class__.__name__,\n self.SUPPORTED_PARAM_TYPES,\n experiment.parameter_definitions))\n self._experiment = experiment\n\n def update(self, experiment):\n \"\"\"\n Updates the experiment.\n\n Implementation note: This function (for the base class) only sets\n the new _experiment. Subclasses can call it to ensure correct setting\n of the experiment parameter.\n\n Parameters\n ----------\n experiment : Experiment\n The experiment representing the current state of the execution.\n\n Raises\n ------\n ValueError\n Iff the experiment is not supported.\n \"\"\"\n if not self._is_experiment_supported(experiment):\n raise ValueError(\"Experiment contains unsupported parameters. \"\n \"Optimizer %s supports %s, experiment parameters \"\n \"are %s.\" %(self.__class__.__name__,\n self.SUPPORTED_PARAM_TYPES,\n experiment.parameter_definitions))\n self._experiment = experiment\n\n @abstractmethod\n def get_next_candidates(self, num_candidates=1):\n \"\"\"\n Returns a number of candidates.\n\n Parameters\n ----------\n num_candidates : strictly positive int, optional\n The maximum number of candidates returned. Note that there may\n be less than that in the list.\n\n Returns\n -------\n candidates : list of candidates\n The list of candidates to evaluate next. May be None (which\n represents no current candidates being available), and may have\n between one and num_candidates candidates.\n \"\"\"\n pass\n\n def exit(self):\n \"\"\"\n Cleanly exits this optimizer.\n\n Note that, since optimizers may be of a multiprocessing or\n distributed nature, this function is important for stopping.\n\n Internal Note: This function, which will be inherited, does nothing. If\n an optimizer does not require another any other behaviour, it will not\n be necessary to redefine it.\n \"\"\"\n pass\n\n def _is_experiment_supported(self, experiment):\n \"\"\"\n Tests whether all parameter types in experiment are supported by this\n optimizer.\n\n Parameters\n ----------\n experiment : Experiment\n The experiment to test.\n\n Returns\n -------\n supported : bool\n False iff one or more of experiment's parameter definitions are not\n supported.\n \"\"\"\n for name, pd in experiment.parameter_definitions.iteritems():\n if not self._is_supported_param_type(pd):\n return False\n return True\n\n def _is_supported_param_type(self, param):\n \"\"\"\n Tests whether a certain parameter is supported by the optimizer.\n\n Parameters\n ----------\n param :\n The parameter to be tested\n\n Result\n ------\n is_supported : bool\n True iff param is supported by this optimizer.\n \"\"\"\n if isinstance(self.SUPPORTED_PARAM_TYPES, list):\n for sup in self.SUPPORTED_PARAM_TYPES:\n if isinstance(param, sup):\n return True\n\n return False\n\n\nclass QueueBasedOptimizer(Optimizer):\n \"\"\"\n This implements a queue-based optimizer.\n\n A queue-based optimizer is an abstraction of another optimizer. It works by\n putting the other optimizer into another process, then communicating\n with it via queues and a QueueBackend instance. This means easy\n deployability without having to change code.\n\n Internally, the QueueBackend puts new candidates onto the\n optimizer_out_queue, keeping it at min_candidates, until it receives a\n new update. In that case, all current candidates in the out_queue are\n deleted.\n\n Parameters\n ----------\n _optimizer_in_queue : Queue\n The queue with which you can send data (experiments) to the optimizer.\n _optimizer_out_queue : Queue\n The queue on which you can receive data.\n \"\"\"\n _optimizer_in_queue = None\n _optimizer_out_queue = None\n\n _optimizer_process = None\n\n _manager = None\n\n def __init__(self, optimizer_class, experiment, optimizer_params=None):\n \"\"\"\n Initializes a new QueueBasedOptimizer class.\n\n Parameters\n ----------\n optimizer_class : an Optimizer subclass\n The class of optimizer this should abstract from. The optimizer is\n then initialized here.\n experiment : Experiment\n The experiment representing the current state of the execution.\n optimizer_params : dict, optional\n Dictionary of the optimizer parameters. If None, some standard\n parameters will be assumed.\n Supports the parameter \"min_candidates\", which sets the number\n of candidates that should be kept ready. Default is 5.\n Supports the parameter \"update_time\", which sets the minimum time\n in seconds between checking for updates. Default is 0.1s\n \"\"\"\n self._manager = multiprocessing.Manager()\n self._optimizer_in_queue = self._manager.Queue()\n self._optimizer_out_queue = self._manager.Queue()\n\n self.SUPPORTED_PARAM_TYPES = optimizer_class.SUPPORTED_PARAM_TYPES\n\n p = multiprocessing.Process(target=dispatch_queue_backend,\n args=(optimizer_class, optimizer_params, experiment,\n self._optimizer_out_queue, self._optimizer_in_queue))\n p.start()\n super(QueueBasedOptimizer, self).__init__(experiment, optimizer_params)\n\n def get_next_candidates(self, num_candidates=1):\n next_candidates = []\n try:\n for i in range(num_candidates):\n new_candidate = self._optimizer_out_queue.get_nowait()\n next_candidates.append(new_candidate)\n except Queue.Empty:\n pass\n return next_candidates\n\n\n def update(self, experiment):\n self._optimizer_in_queue.put(experiment)\n\n def exit(self):\n \"\"\"\n Also closes the optimizer.\n\n It does so by putting \"exit\" into the in_queue and closing both queues.\n \"\"\"\n if self._optimizer_in_queue is not None:\n self._optimizer_in_queue.put(\"exit\")\n\n\nclass QueueBackend(object):\n \"\"\"\n This is the backend for QueueBasedOptimizer.\n\n It ensures there's a compatible request to the stored optimizer.\n\n Parameters\n ----------\n _experiment : Experiment\n The current state of the experiment.\n _out_queue : Queue\n The queue on which to put the candidates.\n _in_queue : Queue\n The queue on which to receive the new experiments.\n _optimizer : Optimizer\n The optimizer this abstracts from\n _min_candidates : int\n The minimum numbers of candidates to keep ready.\n _exited : bool\n Whether this process should exit (has seen the exit signal).\n \"\"\"\n _experiment = None\n _out_queue = None\n _in_queue = None\n\n _optimizer = None\n\n _min_candidates = None\n _exited = None\n _update_time = None\n\n def __init__(self, optimizer_class, experiment, out_queue, in_queue, optimizer_params=None):\n \"\"\"\n Initializes this backend.\n\n Parameters\n ----------\n optimizer_class : an Optimizer subclass\n The class of optimizer this should abstract from. The optimizer is\n then initialized here.\n experiment : Experiment\n The experiment representing the current state of the execution.\n optimizer_params : dict, optional\n Dictionary of the optimizer parameters. If None, some standard\n parameters will be assumed.\n Supports the parameter \"min_candidates\", which sets the number\n of candidates that should be kept ready.\n out_queue : Queue\n The queue on which to put the candidates.\n in_queue : Queue\n The queue on which to receive the new experiments.\n \"\"\"\n self._out_queue = out_queue\n self._in_queue = in_queue\n if optimizer_params is None:\n optimizer_params = {}\n self._min_candidates = optimizer_params.get(\"min_candidates\", 5)\n self._update_time = optimizer_params.get(\"update_time\", 0.1)\n self._optimizer = optimizer_class(experiment, optimizer_params)\n self._exited = False\n self._experiment = experiment\n #multiprocessing.Process.__init__(self)\n\n def run(self):\n \"\"\"\n The run function of this process, checking for new updates.\n\n Every _update_time seconds, it checks both the necessity of a new\n generation of candidates, and whether an update is necessary.\n\n It also makes sure all queues will be closed.\n \"\"\"\n try:\n while not self._exited:\n self._check_generation()\n self._check_update()\n sleep(0.1)\n finally:\n pass\n\n def _check_update(self):\n \"\"\"\n This checks for the availability of updates.\n\n Specifically, it does the following:\n If the in_queue is not empty (that is, there are one or more\n experiments available) it takes the last, most recently added. If\n one of the elements is \"exit\", it will exit instead.\n The latest experiment is then used to call the update function of the\n abstracted optimizer.\n Additionally, it will empty the out_queue, since we assume it has more,\n better information available.\n \"\"\"\n new_update = None\n while not self._in_queue.empty():\n try:\n new_update = self._in_queue.get_nowait()\n except Queue.Empty:\n pass\n if new_update == \"exit\":\n self._exited = True\n return\n if new_update is not None:\n # clear the out queue. We'll soon have new information.\n try:\n while not self._out_queue.empty():\n self._out_queue.get_nowait()\n except Queue.Empty:\n pass\n self._experiment = new_update\n self._optimizer.update(self._experiment)\n\n def _check_generation(self):\n \"\"\"\n This checks whether new candidates should be generated.\n\n Specifically, it tests whether less than min_candidates are available\n in the out_queue. If so, it will (via optimizer.get_next_candidates)\n try to add min_candidates candidates.\n \"\"\"\n try:\n if (self._out_queue.empty() or\n self._out_queue.qsize < self._min_candidates):\n new_candidates = self._optimizer.get_next_candidates(\n num_candidates=self._min_candidates)\n if new_candidates is None:\n return\n for c in new_candidates:\n self._out_queue.put_nowait(c)\n except Queue.Full:\n return\n\n\ndef dispatch_queue_backend(optimizer_class, optimizer_params, experiment, out_queue, in_queue):\n optimizer = QueueBackend(optimizer_class, experiment, out_queue,\n in_queue, optimizer_params)\n optimizer.run()\n","sub_path":"code/apsis/optimizers/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":13436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"542097456","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: AC4Fun\n@contact: kingsleynuaa AT gmail DOT com\n@file: 2. Add Two Numbers\n@time: 2019-08-31 10:09\n@desc:\nYou are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\nExample:\n\nInput: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\nExplanation: 342 + 465 = 807.\n\n此题可以很好的熟悉链表的一些基础操作\n有空可以复习一下C语言对链表的操作\n\"\"\"\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n carry = 0\n p = None\n head = None\n l1_p = l1\n l2_p = l2\n while l1_p or l2_p:\n if l1_p and l2_p:\n val = l1_p.val + l2_p.val + carry\n l1_p = l1_p.next\n l2_p = l2_p.next\n elif l1_p:\n val = l1_p.val + carry\n l1_p = l1_p.next\n else:\n val = l2_p.val + carry\n l2_p = l2_p.next\n carry = val // 10\n val = val - carry * 10\n if not head:\n p = ListNode(val)\n head = p\n else:\n p.next = ListNode(val)\n p = p.next\n if carry == 1:\n p.next = ListNode(carry)\n\n return head\n","sub_path":"python3/2. Add Two Numbers.py","file_name":"2. Add Two Numbers.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238862874","text":"from scrapy.loader import ItemLoader\nfrom scrapy.selector import Selector\nfrom urllib.parse import urlparse\nimport scrapy, re, json,sys, json, html\nfrom slugify import slugify\nfrom ..database.Queries import Queries\n\nclass TimesNownewsSub(scrapy.Spider):\n name='page_timesnownewsSub'\n start_urls=[\n # 'https://www.timesnownews.com/videos/times-now',\n # 'https://www.timesnownews.com/videos/et-now',\n # 'https://www.timesnownews.com/videos/health',\n # 'https://www.timesnownews.com/videos/lifestyle',\n # 'https://www.timesnownews.com/videos/mirror-now',\n # 'https://www.timesnownews.com/videos/foodie',\n 'https://www.timesnownews.com/videos/times-drive',\n 'https://www.timesnownews.com/videos/times-now',\n 'https://www.timesnownews.com/videos/news-plus',\n 'https://www.timesnownews.com/videos/zoom',\n 'https://www.timesnownews.com/videos/web-series',\n 'https://www.timesnownews.com/videos'\n ]\n user_agent = \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36\"\n\n def parse(self, response):\n hxs = Selector(response)\n parsed_uri = urlparse(response.url)\n domain = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)\n lang = \"english\"\n category = '{uri.path}'.format(uri=parsed_uri)\n category = category.split('/')\n print(category)\n if (\"times-now\" in category):\n category = \"news\"\n if (\"et-now\" in category):\n category = \"economics\"\n if (\"health\" in category):\n category = \"health\"\n if (\"lifestyle\" in category):\n category = \"lifestyle\"\n if (\"mirror-now\" in category):\n category = \"news\"\n if (\"foodie\" in category):\n category = \"food\"\n if (\"times-drive\" in category):\n category = \"automobiles\"\n if (\"times-now\" in category):\n category = \"news\"\n if (\"news-plus\" in category):\n category = \"news\"\n if(\"web-series\" in category) :\n category =\"entertainment\"\n if (\"zoom\" in category):\n category = \"celebrity\"\n\n if(\"videos\" in category and len(category) ==2 ) :\n category = \"news\"\n links = hxs.xpath(\"//a[@class='video']/@href\").extract()\n else:\n links1 = hxs.xpath(\"//a[@class='banner-slot']/@href\").extract()\n links2 = hxs.xpath(\"//a[@class='video']/@href\").extract()\n links = links1 + links2\n\n links = links[0:50]\n print(len(links))\n for link in links:\n url = link\n request = scrapy.Request(url, callback=self.parse_subpage)\n request.meta['category'] = category\n request.meta['lang'] = lang\n yield request\n\n def parse_subpage(self, response):\n try:\n global video_url, url, duration, video_keywords, title, description, image, modified_video_keywords, modified_time, news_keywords, category, lang\n try:\n video_url = response.xpath(\"//div[@class='video-pod']/div/@data-src\").extract_first()\n duration = response.xpath(\"//input[@id='ad_duration']/@value\").extract_first()\n duration = duration.replace('T','').replace('MIN', ':').replace('SEC','').replace(' ', '')\n title = response.xpath(\"//meta[@property = 'og:title']/@content\").extract_first()\n news_keywords = response.xpath(\"//meta[@name ='keywords']/@content\").extract_first()\n description = response.xpath(\"//meta[@property = 'og:description']/@content\").extract_first()\n image = response.xpath(\"//meta[@property = 'og:image']/@content\").extract_first()\n duration = '0:'+duration\n category = response.meta['category']\n lang = response.meta['lang']\n except:\n print(\"EXCEPTION HIT\")\n try:\n time = duration.split(':')\n if (len(time[0]) < 2):\n time[0] = '0' + time[0]\n if (len(time[1]) < 2):\n time[1] = '0' + time[1]\n if (len(time[2]) < 2):\n time[2] = '0' + time[2]\n modified_time = str(time[0] + \":\" + time[1] + \":\" + time[2])\n except:\n print(\"TIME ERROR\")\n try:\n modified_video_keywords = [x.strip() for x in news_keywords.split()]\n except:\n print(\"SPLIT ERROR\")\n keywords = Queries.insert_keywords(self, modified_video_keywords)\n insertObject = {\n \"video_title\" : title,\n \"video_slug\" : slugify(title),\n \"video_link\" : video_url,\n \"video_description\" : description,\n \"broadcaster\" : \"5d1ef58d43eefdb023bf9d85\",\n \"videoformat\" : \"5ce4f7ffa5c038104cb76649\",\n \"video_image\" : image,\n \"videokeywords\" : keywords,\n \"page_url\": response.url,\n \"duration\" : modified_time,\n \"category\": category,\n \"language\": lang,\n \"keywords\": ' | '.join(map(str, modified_video_keywords))\n }\n if ((len(video_url)>0 and len(image)>0 and len(modified_time)==8) and\n (video_url.endswith('.mp4') or video_url.endswith('.m3u8'))) :\n # print(\"aaa------------------aaaa\")\n # print(title)\n # print(video_url)\n # print(modified_time)\n # print(image)\n # print(category)\n # print(lang)\n # # print(insertObject)\n # print(\"bbb------------------bbb\")\n result = Queries.insert_api(self, insertObject)\n if result.status_code == 200:\n print(\"INSERTED\")\n else:\n print(result.status_code)\n print(result)\n except:\n print(\"URL MISSING\")","sub_path":"page_scraping/spiders/TimesNownewsSub.py","file_name":"TimesNownewsSub.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"35193636","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom collections import Counter\n\nimport numpy as np\nfrom itertools import chain\nimport json\nimport torch\nfrom typing import List\nimport sentencepiece as spm\nimport os\n\ndef pad_sents(sents, pad_token):\n sents_padded = []\n maxlen = max([len(sent) for sent in sents])\n sents_padded = [sent + (maxlen - len(sent))*[pad_token] for sent in sents]\n sents_padded = list(np.array(sents_padded).T)\n return sents_padded\n\n\ndef read_corpus(file_path, source, vocab_size=2500):\n data = []\n sp = spm.SentencePieceProcessor()\n sp.load('{}.model'.format(source))\n with open(file_path, 'r', encoding='utf8') as f:\n for line in f:\n subword_tokens = sp.encode_as_pieces(line)\n if source == 'tgt':\n subword_tokens = [''] + subword_tokens + ['']\n data.append(subword_tokens)\n\n return data\n\n\nclass VocabEntry(object):\n def __init__(self, word2id=None):\n if word2id:\n self.word2id = word2id\n else:\n self.word2id = dict()\n self.word2id[''] = 0 # Pad Token\n self.word2id[''] = 1 # Start Token\n self.word2id[''] = 2 # End Token\n self.word2id[''] = 3 # Unknown Token\n self.unk_id = self.word2id['']\n self.id2word = {v: k for k, v in self.word2id.items()}\n\n def __getitem__(self, word):\n if word in self.word2id:\n return self.word2id[word]\n return self.unk_id\n\n def __contains__(self, word):\n return word in self.word2id\n\n def __setitem__(self, key, value):\n raise ValueError('vocabulary is readonly')\n\n def __len__(self):\n return len(self.word2id)\n\n def __repr__(self):\n return 'Vocabulary[size=%d]' % len(self)\n\n def id2word(self, wid):\n return self.id2word[wid]\n\n def add(self, word):\n if word not in self:\n wid = self.word2id[word] = len(self)\n self.id2word[wid] = word\n return wid\n else:\n return self[word]\n\n def words2indices(self, sents):\n if type(sents[0]) == list:\n return [[self[w] for w in s] for s in sents]\n else:\n return [self[w] for w in sents]\n\n def indices2words(self, word_ids):\n return [self.id2word[w_id] for w_id in word_ids]\n\n def to_input_tensor(self, sents: List[List[str]], device: torch.device) -> torch.Tensor:\n word_ids = self.words2indices(sents)\n sents_t = pad_sents(word_ids, self[''])\n sents_var = torch.tensor(sents_t, dtype=torch.long, device=device)\n return sents_var\n\n @staticmethod\n def from_corpus(corpus, size, freq_cutoff=2):\n vocab_entry = VocabEntry()\n word_freq = Counter(chain(*corpus))\n valid_words = [w for w, v in word_freq.items() if v >= freq_cutoff]\n print('number of word types: {}, number of word types w/ frequency >= {}: {}'\n .format(len(word_freq), freq_cutoff, len(valid_words)))\n top_k_words = sorted(valid_words, key=lambda w: word_freq[w], reverse=True)[:size]\n for word in top_k_words:\n vocab_entry.add(word)\n return vocab_entry\n \n @staticmethod\n def from_subword_list(subword_list):\n vocab_entry = VocabEntry()\n for subword in subword_list:\n vocab_entry.add(subword)\n return vocab_entry\n\n\nclass Vocab(object):\n def __init__(self, vocab: VocabEntry):\n self.src = vocab\n\n @staticmethod\n def build(sents) -> 'Vocab':\n print('initialize vocabulary ..')\n src = VocabEntry.from_subword_list(sents)\n return Vocab(src)\n\n def save(self, file_path):\n if not os.path.exists('models/tokenization'):\n os.mkdir('models/tokenization')\n with open(file_path, 'w') as f:\n json.dump(dict(src_word2id=self.src.word2id), f, indent=2, ensure_ascii=False)\n\n @staticmethod\n def load(file_path):\n entry = json.load(open(file_path, 'r'))\n word2id = entry['word2id']\n return Vocab(VocabEntry(word2id))\n\n def __repr__(self):\n return 'Vocab(source %d words)' % (len(self.src))\n\n\ndef get_vocab_list(type_tokens,file_path_src, source, vocab_size):\n if type_tokens == 'word':\n spm.SentencePieceTrainer.train(input=file_path_src, model_prefix=source, vocab_size=vocab_size,model_type='word',pad_id=0,unk_id=3,bos_id=-1) # train the spm model\n else:\n spm.SentencePieceTrainer.train(input=file_path_src, model_prefix=source, vocab_size=vocab_size,unk_id=3,bos_id=-1) # train the spm model\n sp = spm.SentencePieceProcessor() # create an instance; this saves .model and .vocab files\n sp.load('{}.model'.format(source)) # loads tgt.model or src.model\n sp_list = [sp.id_to_piece(piece_id) for piece_id in range(sp.get_piece_size())] # this is the list of subwords\n return sp_list\n\ndef generate_five_set(src_path,dest_path):\n # save 5 shuffled file in temp directory\n all_text = []\n with open(src_path, 'r') as sent_file:\n all_text = [text for text in sent_file]\n sen_num = len(all_text)\n train_num = int(0.8*sen_num)\n all_text = np.array(all_text)\n for i in range(1, 6):\n np.random.shuffle(all_text)\n with open(dest_path+'/sentences_train{}.txt'.format(i), 'a') as out_file:\n out_file.writelines(all_text[:train_num])\n with open(dest_path+'/sentences_dev{}.txt'.format(i), 'a') as out_file:\n out_file.writelines(all_text[train_num:])\n\n\n# def eval_dev(dest_path,source):\n# sp = spm.SentencePieceProcessor() # create an instance; this saves .model and .vocab files\n# sp.load('{}.model'.format(source)) # loads tgt.model or src.model\n# sent_dev = []\n# with open(dest_path, 'r') as outfile:\n# sent_dev = [sent for sent in outfile]\n# tokenized = sp.Encode(input=sent_dev, out_type=int)\n# return tokenized\n\nif __name__ == '__main__':\n if not os.path.exists('data/dataset_noen.txt'):\n with open('data/dataset_sentences.txt','r') as withen_file:\n all_text = [txt.lower() for txt in withen_file]\n en = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','t','u','s','v','w','x','y','z', '\"', '\"', '»', '«', '/']\n print(len(en))\n cleaned = []\n for txt in all_text:\n newtxt = txt\n for e in en:\n newtxt = newtxt.replace(e,'')\n newtxt = newtxt.replace('▁','')\n cleaned.append(newtxt)\n with open('data/dataset_noen.txt', 'a') as cleaned_file:\n cleaned_file.writelines(cleaned)\n\n src = 'data/dataset_noen.txt'\n dest = 'src/tokenization/working_dir'\n vocab_sizes = [15000,10000,5000,1000]\n\n if not os.path.exists('src/tokenization/working_dir'):\n os.mkdir('src/tokenization/working_dir')\n generate_five_set(src, dest)\n if not os.path.exists('src/tokenization/working_dir/outs'):\n os.mkdir('src/tokenization/working_dir/outs')\n if not os.path.exists('src/tokenization/working_dir/words_outs'):\n os.mkdir('src/tokenization/working_dir/words_outs')\n type_tokens = 'word' #'word'/'subword'\n out_dir_name = 'outs' if type_tokens == 'subword' else 'words_outs'\n model_reports = []\n for vocab_size in vocab_sizes:\n for i in range(1, 6):\n if not os.path.exists(dest + '/{}/{}_{}'.format(out_dir_name,i, vocab_size)):\n os.mkdir(dest + '/{}/{}_{}'.format(out_dir_name,i, vocab_size))\n\n sent_path_train = dest+'/sentences_train{}.txt'.format(i)\n sent_path_dev = dest + '/sentences_dev{}.txt'.format(i)\n sents = get_vocab_list(type_tokens,sent_path_train, source=dest+'/{}/{}_{}/src{}_{}'.format(out_dir_name,i, vocab_size,i, vocab_size), vocab_size=vocab_size)\n vocab = Vocab.build(sents)\n final_vocab_file = dest + '/{}/{}_{}/vocab_file.json'.format(out_dir_name,i, vocab_size)\n vocab.save(final_vocab_file)\n with open( 'src/tokenization/working_dir/sentences_dev{}.txt'.format(i), 'r') as dev_data_file:\n dev_sents = [['▁'+de for de in d.split(' ') ] for d in dev_data_file]\n dev_token = vocab.src.words2indices(dev_sents)\n dev_token_np = []\n for devtok in dev_token:\n for tok in devtok:\n dev_token_np.append(tok)\n dev_token_np = np.array(dev_token_np)\n unk_num = np.count_nonzero(dev_token_np == 3)\n model_reports.append(\"-Vocab size:{}\\ti:{}\\tNum tokens= {}\\tNum unks:{}\\tunkp:{}\\n\"\\\n .format(vocab_size,i,dev_token_np.shape[0],100*unk_num,unk_num/dev_token_np.shape[0]))\n with open(dest + '/{}/{}_{}/dev.json'.format(out_dir_name,i,vocab_size) , 'a') as devfile:\n json.dump(dict(tokens=dev_token), devfile, ensure_ascii=False)\n with open(\"reports/word2vec_{}.txt\".format(type_tokens),'a') as report_file:\n report_file.writelines(model_reports)\n\n\n vocab_sizes = 10000\n sents = get_vocab_list(type_tokens,src, source='models/tokenization/src{}'.format(type_tokens), vocab_size=vocab_size)\n vocab = Vocab.build(sents)\n final_vocab_file = 'models/tokenization/vocab_file_{}.json'.format(type_tokens)\n vocab.save(final_vocab_file)\n","sub_path":"src/tokenization/vocab.py","file_name":"vocab.py","file_ext":"py","file_size_in_byte":9505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"474771607","text":"\"\"\"-----------------------------------------------------------------------------\nProject: Prime Brokerage Project\nDepartment: Prime Services\nRequester: Francois Henrion\nDeveloper: Paul Jacot-Guillarmod\nCR Number: 666125 (Initial Deployment)\n\nHISTORY\n================================================================================\nDate Change no Developer Description\n--------------------------------------------------------------------------------\n2011-06-17 685737 Paul J.-Guillarmod Added a completed succesfully print statement\n2013-04-10 935599 Peter Fabian Added support for sweeping Int fut fees\n2014-06-05 2018619 Hynek Urban Handling errors in PB overnight batch correctly\n2015-07-14 2961517 Jakub Tomaga Sweeping report added.\n2015-09-11 3090331 Jakub Tomaga Portfolio independent sweeping.\n2019-11-21 FAPE-147 Tibor Reiss Propagate error\n-----------------------------------------------------------------------------\"\"\"\nimport acm\nimport string\n\nimport PS_CallAccountSweeperFunctions\nfrom at_logging import getLogger, bp_start\nfrom sweeping_report import CallAccountSweepingReport\nfrom PS_Functions import (TODAY, START_DATE_KEYS, START_DATE_LIST, END_DATE_KEYS, END_DATE_LIST)\n\n\nLOGGER = getLogger()\n\n\ndef enable_custom_start_date(index, field_values):\n ael_variables[2][9] = (field_values[1] == 'Custom Date')\n return field_values\n\n\ndef enable_custom_end_date(index, field_values):\n ael_variables[4][9] = (field_values[3] == 'Custom Date')\n return field_values\n\n\n# Variable Name, Display Name, Type, Candidate Values, Default, Mandatory, Multiple, Description, Input Hook, Enabled\nael_variables = [['portfolioSwaps', 'Portfolio Swaps', 'FInstrument', None, None, 0, 1, 'Portfolio swaps that call account sweeping will be performed for', None, 1],\n ['startDate', 'Start Date', 'string', START_DATE_KEYS, 'Now', 1, 0, 'Date from which call account sweeping will take place.', enable_custom_start_date, 1],\n ['startDateCustom', 'Start Date Custom', 'string', None, TODAY, 0, 0, 'Custom from date', None, 0],\n ['endDate', 'End Date', 'string', END_DATE_KEYS, 'Now', 1, 0, 'Date to which call account sweeping will be run.', enable_custom_end_date, 1],\n ['endDateCustom', 'End Date Custom', 'string', None, TODAY, 0, 0, 'Custom to date', None, 0],\n ['sweepingReport', 'Sweeping Report', 'string', None, None, 0, 0, 'Report with detailed breakdown of swept amounts', None, 1],\n ['clientName', 'Short name', 'string', None, 'CLIENT', 0, 0]\n ]\n\n\ndef ael_main(ael_dict):\n LOGGER.msg_tracker.reset()\n process_name = \"ps.call_account_sweeper.{0}\".format(ael_dict[\"clientName\"])\n \n with bp_start(process_name, ael_main_args=ael_dict):\n if ael_dict['startDate'] == 'Custom Date':\n start_date = ael_dict['startDateCustom']\n else:\n start_date = START_DATE_LIST[ael_dict['startDate']]\n \n if ael_dict['endDate'] == 'Custom Date':\n end_date = ael_dict['endDateCustom']\n else:\n end_date = END_DATE_LIST[ael_dict['endDate']]\n \n # Validate the date input (otherwise strange things might happen).\n if not acm.Time.IsValidDateTime(start_date):\n raise ValueError('Invalid date: %s' % start_date)\n if not acm.Time.IsValidDateTime(end_date):\n raise ValueError('Invalid date: %s' % end_date)\n if not start_date <= end_date:\n raise ValueError('Start date must be prior or equal to end date.')\n \n current_tpl = {}\n historical_tpl = {}\n call_account_tpl = {}\n current_tpl_breakdown = {}\n historical_tpl_breakdown = {}\n \n for portfolioSwap in ael_dict['portfolioSwaps']:\n name = portfolioSwap.Name()\n (\n current_tpl[name],\n historical_tpl[name],\n call_account_tpl[name],\n current_tpl_breakdown[name],\n historical_tpl_breakdown[name]\n ) = PS_CallAccountSweeperFunctions.TPLSweeper(\n portfolioSwap, start_date, end_date)\n\n report_filename = ael_dict[\"sweepingReport\"]\n if report_filename:\n try:\n data = (\n current_tpl,\n historical_tpl,\n call_account_tpl,\n current_tpl_breakdown,\n historical_tpl_breakdown\n )\n file_path_template = string.Template(report_filename)\n file_path = file_path_template.substitute(DATE=end_date.replace(\"-\", \"\"))\n report = CallAccountSweepingReport(file_path, data)\n report.create_report()\n LOGGER.info(\"Wrote secondary output to {0}\".format(file_path))\n except:\n LOGGER.exception(\"Sweeping report wasn't generated.\")\n\n if LOGGER.msg_tracker.errors_counter:\n raise RuntimeError(\"ERRORS occurred. Please check the log.\")\n\n LOGGER.info(\"Completed Successfully\")\n","sub_path":"Python modules/PS_CallAccountSweeper.py","file_name":"PS_CallAccountSweeper.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"289033106","text":"from django.contrib import admin\r\nfrom insurance.models import *\r\nfrom django.contrib.auth.admin import UserAdmin\r\n\r\n\r\nclass ProfileInline(admin.StackedInline):\r\n model = Profile\r\n can_delete = False\r\n verbose_name_plural = 'Profile'\r\n fk_name = 'user'\r\n\r\n\r\nclass UserRoleInline(admin.TabularInline):\r\n model = UserRole\r\n verbose_name_plural = 'Roles'\r\n fk_name = 'user'\r\n extra = 0\r\n\r\n\r\nclass PermissionUserInline(admin.TabularInline):\r\n model = PermissionUser\r\n verbose_name_plural = 'Permissions'\r\n fk_name = 'user'\r\n extra = 0\r\n\r\n\r\nclass CustomUserAdmin(UserAdmin):\r\n inlines = (ProfileInline, UserRoleInline, PermissionUserInline)\r\n\r\n def get_inline_instances(self, request, obj=None):\r\n if not obj:\r\n return list()\r\n return super(CustomUserAdmin, self).get_inline_instances(request, obj)\r\n\r\n\r\nadmin.site.unregister(User)\r\nadmin.site.register(User, CustomUserAdmin)\r\n\r\n\r\n@admin.register(Position)\r\nclass PositionAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(Permission)\r\nclass PermissionAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'code_name', 'title')\r\n readonly_fields = ('cr_by', 'cr_on', 'up_by', 'up_on')\r\n\r\n def save_model(self, request, obj, form, change):\r\n if change:\r\n obj.up_by = request.user\r\n else:\r\n obj.cr_by = request.user\r\n super().save_model(request, obj, form, change)\r\n\r\n\r\n@admin.register(OfficeWorkers)\r\nclass OfficeWorkersAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'user', 'office')\r\n readonly_fields = ('cr_by', 'cr_on', 'up_by', 'up_on')\r\n\r\n\r\nclass PermissionRoleInline(admin.TabularInline):\r\n model = PermissionRole\r\n fk_name = 'role'\r\n verbose_name_plural = 'ROLE PERMISSIONS'\r\n verbose_name = 'PERMISSION'\r\n extra = 0\r\n\r\n\r\n@admin.register(Role)\r\nclass RoleAdmin(admin.ModelAdmin):\r\n list_display = ('title', 'is_active')\r\n inlines = (PermissionRoleInline, )\r\n\r\n\r\n@admin.register(UserRole)\r\nclass UserRoleAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'user', 'role')\r\n #readonly_fields = ('cr_by', 'cr_on')\r\n\r\n def save_model(self, request, obj, form, change):\r\n if change:\r\n obj.cr_by = request.user\r\n else:\r\n obj.cr_by = request.user\r\n permissions = PermissionRole.objects.filter(role=obj.role)\r\n for p in permissions:\r\n PermissionUser.objects.create(permission=p.permission,\r\n user=obj.user,\r\n grant=p.grant,\r\n cr_by=request.user)\r\n super().save_model(request, obj, form, change)\r\n\r\n def delete_model(self, request, obj):\r\n permission_ids = PermissionRole.objects.filter(role=obj.role).values_list('permission_id')\r\n PermissionUser.objects.filter(user=obj.user, permission__in=permission_ids).delete()\r\n obj.delete()\r\n\r\n def delete_queryset(self, request, queryset):\r\n for obj in queryset:\r\n permission_ids = PermissionRole.objects.filter(role=obj.role).values_list('permission_id')\r\n PermissionUser.objects.filter(user=obj.user, permission__in=permission_ids).delete()\r\n obj.delete()\r\n\r\n\r\n@admin.register(PermissionRole)\r\nclass PermissionRoleAdmin(admin.ModelAdmin):\r\n list_display = ('role', 'permission')\r\n\r\n\r\n def save_model(self, request, obj, form, change):\r\n if change:\r\n obj.cr_by = request.user\r\n else:\r\n obj.cr_by = request.user\r\n super().save_model(request, obj, form, change)\r\n\r\n\r\n@admin.register(PermissionUser)\r\nclass PermissionUserAdmin(admin.ModelAdmin):\r\n list_display = ('user', 'permission', 'grant')\r\n\r\n def save_model(self, request, obj, form, change):\r\n if change:\r\n obj.cr_by = request.user\r\n else:\r\n obj.cr_by = request.user\r\n super().save_model(request, obj, form, change)\r\n\r\n\r\nclass GridColsInline(admin.TabularInline):\r\n model = GridCols\r\n extra = 0\r\n fields = ('order_num', 'title', 'data', 'name', 'type', 'className', 'defaultContent',\r\n 'width', 'searchable', 'orderable', 'visible')\r\n\r\n\r\n@admin.register(Dt_Option)\r\nclass GridAdmin(admin.ModelAdmin):\r\n list_display = ('codeName', 'title')\r\n inlines = [GridColsInline]\r\n\r\n\r\n@admin.register(IndividualClient)\r\nclass IndividualClientAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(Group)\r\nclass GroupAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(ProductTypeClass)\r\nclass KlassAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(Bank)\r\nclass BankAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(InsuranceOffice)\r\nclass BranchAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(Currency)\r\nclass CurrencyAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\n@admin.register(LegalClient)\r\nclass LegalClientAdmin(admin.ModelAdmin):\r\n pass\r\n\r\n\r\nclass ProductFieldInline(admin.TabularInline):\r\n model = ProductField\r\n extra = 0\r\n fields = ('type', 'name', 'value', 'order')\r\n\r\n\r\n@admin.register(ProductType)\r\nclass ProductAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'name', 'klass', 'group', 'vid')\r\n inlines = [ProductFieldInline]\r\n\r\n\r\n@admin.register(PoliciesIncome)\r\nclass PoliciesIncomeAdmin(admin.ModelAdmin):\r\n list_display = ['act_number', 'act_date', 'policy_number_from', 'policy_number_to']\r\n\r\n\r\n@admin.register(PolicySeriesType)\r\nclass PolicySeriesType(admin.ModelAdmin):\r\n list_display = ['code', 'cr_by']\r\n\r\n\r\n@admin.register(Policy)\r\nclass PolicyAdmin(admin.ModelAdmin):\r\n list_display = ('id', str, 'is_free_generated', 'is_active')\r\n\r\n\r\n@admin.register(Beneficiary)\r\nclass BeneficiaryAdmin(admin.ModelAdmin):\r\n list_display = (str, 'person', 'fax_number', 'checking_account', 'bank', 'inn', 'mfo')\r\n\r\n\r\n@admin.register(Pledger)\r\nclass PledgerAdmin(admin.ModelAdmin):\r\n list_display = ('person', 'fax_number', 'inn')\r\n\r\n\r\n@admin.register(Human)\r\nclass PledgerAdmin(admin.ModelAdmin):\r\n list_display = ('first_name', 'last_name', 'phone')\r\n\r\n\r\n@admin.register(PolicyTransfers)\r\nclass PolicyTransfersAdmin(admin.ModelAdmin):\r\n list_display = ('id', 'to_office', 'cr_by', 'cr_on')\r\n\r\n\r\n@admin.register(PolicyRetransfer)\r\nclass PolicyRetransferAdmin(admin.ModelAdmin):\r\n list_display = (\r\n 'id', 'transfer', 'to_user', 'cr_on', 'cr_by'\r\n )\r\n\r\n\r\n@admin.register(OfficeType)\r\nclass OfficeTypeAdmin(admin.ModelAdmin):\r\n list_display = (\r\n 'title', 'description'\r\n )","sub_path":"insurance/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":6532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"506248996","text":"\"\"\"\nName: Venkata Adilakshmi Rajitha Kalapatapu\nStudent ID: 1001682465\nLogin ID: vxk2465\n\"\"\"\n\nimport tkinter as tk\nfrom tkinter import ttk, scrolledtext, messagebox, END\nimport socket\nfrom threading import Thread, Timer\nfrom http_helper import *\n\n\n# References:\n# Python GUI cookbook by Packtpub\n# https://docs.python.org/3/howto/sockets.html#creating-a-socket\n# https://pymotw.com/3/select/\n# https://pymotw.com/3/selectors/\n# https://docs.python.org/3/library/queue.html\n# http://net-informations.com/python/net/thread.htm\n# https://www.geeksforgeeks.org/socket-programming-multi-threading-python/\n# https://medium.com/swlh/lets-write-a-chat-app-in-python-f6783a9ac170\n\n\n# a global socket object for all functions to access and send/recv\nnotification_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n# a global connected status - true if connection is active, false otherwise\nconnected = False\n# a global tkinter window instance - accessed by thread and main\nnotification_window = tk.Tk()\n# a global label to show connection status - accessed by thread and main\nconnection_status = ttk.Label(notification_window, text=\"Not connected to server\")\n# a global variable to show incoming message - scrollbox - accessed by thread and main\nscroll_width = 64\nscroll_height = 15\nmsg_area = scrolledtext.ScrolledText(\n notification_window, width=scroll_width, height=scroll_height, wrap=tk.WORD\n)\n\n\ndef exit_program():\n \"\"\"\n Exit the program by closing socket connection and destroying client window\n :return: None\n \"\"\"\n # exit cleanly by closing socket and destroying the tkinter window\n notification_socket.close()\n notification_window.destroy()\n\n\ndef add_msg_to_scrollbox(msg):\n \"\"\"\n Add a given message to the scrollbox end\n :param msg: message to display\n :return: None\n \"\"\"\n # add message to the end of scrollbox\n msg_area.insert(END, msg)\n # auto scroll the scrollbox to the end\n msg_area.see(END)\n\n\ndef parse_connection_request_response(msg):\n \"\"\"\n if server sent 200 OK for our user name registration\n GUI displays message indicating success of connection\n else shows an error and asks user to retry again\n \"\"\"\n if \"200 OK\" in msg:\n # the server sent us a 200 OK (success) for our request\n global connected\n connected = True\n connection_status.config(text=\"Connected to server...\")\n else:\n # the server did not send us 200 OK - so some failure happened\n connection_status.config(text=\"Try connecting again...\")\n\n\ndef display_incoming_message(msg):\n \"\"\"\n displays incoming message in the scrollbox area\n\n if we received 200 OK for our sent message, we show \"Message sent successfully!\"\n if we received a new incoming message, we show where we got it from and if it\n was 1:1 or 1:N and the actual message content\n :param msg: message received from the server\n :return: None\n \"\"\"\n if \"200 OK\" in msg:\n # the server sent us a 200 OK (success) for our request\n display_msg = \"Message sent successfully!\"\n add_msg_to_scrollbox(\"{}\\n\".format(display_msg))\n elif SEND_MESSAGE in msg:\n import json\n\n # this is the HTTP response message with\n # one status line (200 OK) [index 0]\n # 5 header lines [index 1,2,3,4,5]\n # one blank line [index 6]\n # and then the body of the response [index 7]\n # the message is now in a list - each element is a line from the original msg\n msg = msg.split(\"\\n\")\n # we want only the response body which is in index 7 (8th element of the list)\n response_body = msg[7]\n print(\"we are going to process {}\".format(response_body))\n\n mode, source, message = extract_message_details(response_body)\n display_msg = \"{} sent a {}: \\n {}\".format(source, mode, message)\n add_msg_to_scrollbox(\"{}\\n\".format(display_msg))\n else:\n # some failure happened\n print(\"Sending message failed {}\".format(msg))\n\n\ndef process_cleared_requests(msg):\n \"\"\"\n parses response containing all pending clearance requests\n :return: None\n \"\"\"\n \"\"\"\n This is the HTTP response message with \n\n HTTP/1.0 200 OK --- status line [index 0]\n Content-Type:Application/json -- headers [index 1]\n Content-Length:2\n Host:127.0.0.1\n Date:2019-04-21 00:51:56.592347\n User-Agent:Custom HTTP endpoint written for CSE5306 lab [index 5]\n [index 6]\n [[\"get/cleared/requests\"], [\"sss\", \"ccc\", true]] actual data [index 7]\n \"\"\"\n # see above that index 7 is the line we care about\n msg = msg.split(\"\\n\")\n response_body = msg[7]\n import json\n\n clearance_requests = json.loads(response_body)\n # if there's more than one entry, we have some data to process\n if len(clearance_requests) > 1:\n # start from entry 2 as first entry is dummy entry\n clearance_requests = clearance_requests[1:]\n\n for request in clearance_requests:\n if request[2]:\n status = \"Approved\"\n else:\n status = \"Rejected\"\n # show approval status in UI\n add_msg_to_scrollbox(\n \"Student name {} \\nCourse Requested: {} \\nAdvisor Decision: {}\\n\".format(\n request[0], request[1], status\n )\n )\n else:\n add_msg_to_scrollbox(\"No message found\\n\")\n\n\ndef parse_incoming_message(msg):\n \"\"\"\n Responsible for parsing and understanding data\n received from the server\n\n Takes 3 actions\n 1. Parses user-name registration request response message\n 2. Parses get-all-client names request response message\n 3. Parses send-message request response message\n \"\"\"\n print(\"Received {} from server\".format(msg))\n if GET_ALL_CLIENTS in msg:\n # we got a response to our request to get all client names\n print(\"An unsupported operation happened! {}\".format(msg))\n elif REGISTER_CLIENT_NAME in msg:\n # we got a response to our request to register a client name\n parse_connection_request_response(msg)\n elif SEND_MESSAGE in msg:\n # we got incoming message from a client forwarded by the server\n display_incoming_message(msg)\n elif GET_CLEARED_REQUESTS in msg:\n # we got a response to our request to get all cleared requests\n process_cleared_requests(msg)\n else:\n print(\"An unsupported operation happened! {}\".format(msg))\n\n\ndef receive_from_server():\n \"\"\"\n A while True loop to receive data from the server\n - if data is empty, it means server has disconnected/exited\n - if data is not empty, we parse the msg and take action\n - see parse_incoming_message for details about parsing\n \"\"\"\n try:\n while True:\n data_from_server = notification_socket.recv(MAX_MESSAGE_SIZE)\n data_from_server = data_from_server.decode(\"UTF-8\")\n if data_from_server:\n # non-empty data - so parse this\n parse_incoming_message(data_from_server)\n else:\n # empty data - only sent when the server exits\n print(\"Closing this window as the server exited.\")\n exit_program()\n break\n except OSError as e:\n print(e)\n\n\ndef connect_to_server():\n \"\"\"\n responsible for\n - connect socket to the server\n - send client name to the server in HTTP format (sendall)\n - launch thread to start receiving data from server\n :return:\n \"\"\"\n try:\n notification_name = \"notification\"\n global notification_socket\n notification_socket.connect((server_host, server_port)) # connection to server\n notification_socket.sendall(\n bytes(prepare_post_client_name_request(notification_name), \"UTF-8\")\n ) # send user-name to server\n # start thread to receive data from server\n t = Thread(target=receive_from_server)\n # daemonize it so it will run in the background and start the thread\n t.daemon = True\n t.start()\n except OSError:\n global connected\n connected = False\n\n\ndef setup_notification_window():\n \"\"\"\n setup tkinter based client window and its widgets\n \"\"\"\n\n # set up client window details\n notification_window.title(\"Notification Window\")\n notification_window.geometry(\"800x640\")\n notification_window.resizable(False, False)\n\n # set up a label to show connection status to the server\n connection_status.grid(column=1, row=4, padx=30, pady=15)\n\n # set up text area to see incoming messages\n msg_area.grid(column=1, row=5, padx=5, pady=5)\n\n # set up a button to exit the client UI\n # when this button is clicked, \"exit_program\"\n # is called to close the socket connection and exit the program\n exit_button = ttk.Button(notification_window, text=\"Exit\", command=exit_program)\n exit_button.grid(column=1, row=30, padx=10, pady=10)\n\n # cleanly close the socket and destroy the tkinter window when X button is clicked\n notification_window.protocol(\"WM_DELETE_WINDOW\", exit_program)\n\n\ndef send_request_to_get_all_cleared_courses():\n \"\"\"\n Send the HTTP request to MQS to get all pending clerances\n :return:\n \"\"\"\n # prepare body of the http request\n body = {\"action\": GET_CLEARED_REQUESTS}\n import json\n\n # send a HTTP POST message to the server\n # body contains the action (requesting course clearance in this case), student name and course name\n sent_bytes = notification_socket.send(\n bytes(\n prepare_http_msg_request(\"GET\", GET_CLEARED_REQUESTS, json.dumps(body)),\n \"UTF-8\",\n )\n )\n # if there's an error, show error in GUI\n if not sent_bytes:\n add_msg_to_scrollbox(\n \"Error sending request to get all pending course clearance requests \\n\"\n )\n\n\ndef get_all_cleared_requests():\n \"\"\"\n Get all pending messages from the MQS\n Restart the timer once again for 3 seconds\n :return: None\n \"\"\"\n\n send_request_to_get_all_cleared_courses()\n\n # Restart the timer again to one second - at the end of 7 second, we call\n # get_all_cleared_requests again\n t = Timer(7.0, get_all_cleared_requests)\n t.daemon = True\n t.start()\n\n\ndef main():\n \"\"\"\n main method of the program\n - responsible for setting up the tkinter based client UI\n - responsible for calling the tkinter main loop (event loop)\n \"\"\"\n try:\n setup_notification_window()\n connect_to_server()\n # Instantiate a timer for 7 second - at the end of one second call \"get_all_cleared_requests\"\n t = Timer(7.0, get_all_cleared_requests)\n # make the timer a background thread\n t.daemon = True\n # Start the timer object\n t.start()\n\n notification_window.mainloop()\n except RuntimeError:\n print(\"Exiting...\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"396856378","text":"import numpy as np\nimport joblib\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import precision_score,recall_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import RepeatedStratifiedKFold\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import train_test_split\nfrom xgboost.sklearn import XGBClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\ndef train_model(train_df):\n #### feature map\n numeric_features = [\n 'PatientPopulationPercentageBelowPoverty',\n 'Age'\n ]\n categorical_features = ['PatientGender',\n 'PatientRace',\n 'PatientMaritalStatus',\n 'PatientLanguage',\n 'AdmissionID',\n 'PrimaryDiagnosisCode']\n vector_features= 'PrimaryDiagnosisDescription'\n\n numeric_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='median')),\n ('scaler', StandardScaler())])\n categorical_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n vector_transformer = Pipeline(steps=[\n ('vect', CountVectorizer( max_features=10, stop_words='english')),\n ('tfidf', TfidfTransformer())])\n\n preprocessor = ColumnTransformer(\n transformers=[\n ('num', numeric_transformer, numeric_features),\n ('cat', categorical_transformer, categorical_features)])#,\n# ('vect', vector_transformer,vector_features)])\n\n model_rf = Pipeline(steps=[('preprocessor', preprocessor),\n ('model', RandomForestClassifier(max_depth=10,random_state=2))])\n \n #hyper parameter tune\n # Number of trees in random forest\n n_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n # Number of features to consider at every split\n max_features = ['auto', 'sqrt']\n # Maximum number of levels in tree\n max_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\n max_depth.append(None)\n # Minimum number of samples required to split a node\n min_samples_split = [2, 5, 10]\n # Minimum number of samples required at each leaf node\n min_samples_leaf = [1, 2, 4]\n # Method of selecting samples for training each tree\n bootstrap = [True, False]\n # Create the random grid\n rf_param = {'model__n_estimators': n_estimators,\n 'model__max_features': max_features,\n 'model__max_depth': max_depth,\n 'model__min_samples_split': min_samples_split,\n 'model__min_samples_leaf': min_samples_leaf,\n 'model__bootstrap': bootstrap}\n\n \n cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=1)\n\n model = RandomizedSearchCV(model_rf, rf_param, n_iter=100, scoring='roc_auc', n_jobs=-1, cv=cv, random_state=1,verbose=1)\n \n X_train, X_test, y_train, y_test = train_test_split(train_df.drop(['Target'], axis=1), train_df.Target, test_size=0.2)\n\n model.fit(X_train,y_train)\n\n y_pred_train=model.predict(X_train)\n y_pred_test=model.predict(X_test)\n\n test_precision,test_recall=precision_score(y_test,y_pred_test),recall_score(y_test,y_pred_test)\n print(f\"Precision: {test_precision},Recall: {test_recall}\")\n train_precision,train_recall=precision_score(y_train,y_pred_train),recall_score(y_train,y_pred_train)\n# print(f\"Precision: {train_precision},Recall: {train_recall}\")\n \n # save the model to disk\n print(\"Model save..\")\n filename = 'save_model/model.pkl'\n joblib.dump(model, filename)\n\n return model,(test_precision,test_recall),(train_precision,train_recall)\n","sub_path":"models/model2.py","file_name":"model2.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203104375","text":"import telepot\nimport configparser\nfrom pprint import pprint\nimport time\n\n# read bot's token from configfile\ndef getBotToken(configFilePath):\n\tconfig = configparser.ConfigParser()\n\tconfig.read(configFilePath)\n\tTOKEN = config.get('bbkim_test_bot_INFO', 'TOKEN')\n\n\treturn TOKEN\n\ndef handle(msg):\n\tpprint(msg)\n\nif __name__ == \"__main__\":\n\n\tconfigFilePath = 'bbkimBot_config.conf'\n\tTOKEN = getBotToken(configFilePath)\n\n\tbot = telepot.Bot(TOKEN)\n\t# Before update, you have to send it a message first.\n\tprint(\"Send a message to the bot using a telegram\")\n\ttime.sleep(3)\t# wait for 3 Sec for the time you send the message.\n\tresponse = bot.getUpdates()\n\tpprint(response)\n\n\t# An easier way to receive messages\n\tprint(\"An easier way to receive messages\")\n\tprint(\"Start : message Loop\")\n\tbot.message_loop(handle)\n\ttime.sleep(3)\t# wait for 3 Sec for the time you send the message.","sub_path":"introductionExample/receiveMessage.py","file_name":"receiveMessage.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30888518","text":"import json\r\nimport os\r\nimport shutil\r\nimport random\r\nimport time\r\nimport pickle\r\nimport multiprocessing\r\nimport math\r\nfrom tqdm import tqdm\r\nfrom copy import copy, deepcopy\r\nfrom functools import partial\r\nfrom collections import Counter, defaultdict\r\nfrom aser.extract.sentence_parser import SentenceParser\r\nfrom aser.extract.parsed_reader import ParsedReader\r\nfrom aser.extract.aser_extractor import SeedRuleASERExtractor, DiscourseASERExtractor1, DiscourseASERExtractor2, DiscourseASERExtractor3\r\nfrom aser.extract.utils import EMPTY_SENT_PARSED_RESULT\r\nfrom aser.extract.utils import iter_files, parse_sentense_with_stanford\r\nfrom aser.utils.logging import init_logger, close_logger\r\nfrom aser.eventuality import Eventuality\r\nfrom aser.relation import Relation\r\nfrom aser.database.kg_connection import ASERKGConnection\r\n\r\n\r\n\r\ndef run_files(raw_paths=None, processed_paths=None, prefix_to_be_removed=\"\",\r\n sentence_parser=None, parsed_reader=None, aser_extractor=None):\r\n eid2sids = defaultdict(list)\r\n rid2sids = defaultdict(list)\r\n eid2eventuality = dict()\r\n rid2relation = dict()\r\n if raw_paths:\r\n for raw_path, processed_path in zip(raw_paths, processed_paths):\r\n x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation = \\\r\n run_file(raw_path, processed_path, prefix_to_be_removed,\r\n sentence_parser, parsed_reader, aser_extractor)\r\n for eid, sids in x_eid2sids.items():\r\n eid2sids[eid].extend(sids)\r\n for rid, sids in x_rid2sids.items():\r\n rid2sids[rid].extend(sids)\r\n for eid, eventuality in x_eid2eventuality.items():\r\n if eid not in eid2eventuality:\r\n eid2eventuality[eid] = eventuality\r\n else:\r\n eid2eventuality[eid].update(eventuality)\r\n for rid, relation in x_rid2relation.items():\r\n if rid not in rid2relation:\r\n rid2relation[rid] = relation\r\n else:\r\n rid2relation[rid].update(relation)\r\n else:\r\n for processed_path in processed_paths:\r\n x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation = \\\r\n run_file(None, processed_path, prefix_to_be_removed,\r\n sentence_parser, parsed_reader, aser_extractor)\r\n for eid, sids in x_eid2sids.items():\r\n eid2sids[eid].extend(sids)\r\n for rid, sids in x_rid2sids.items():\r\n rid2sids[rid].extend(sids)\r\n for eid, eventuality in x_eid2eventuality.items():\r\n if eid not in eid2eventuality:\r\n eid2eventuality[eid] = eventuality\r\n else:\r\n eid2eventuality[eid].update(eventuality)\r\n for rid, relation in x_rid2relation.items():\r\n if rid not in rid2relation:\r\n rid2relation[rid] = relation\r\n else:\r\n rid2relation[rid].update(relation)\r\n del x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation\r\n return eid2sids, rid2sids, eid2eventuality, rid2relation\r\n\r\ndef run_file(raw_path=None, processed_path=None, prefix_to_be_removed=\"\",\r\n sentence_parser=None, parsed_reader=None, aser_extractor=None):\r\n\r\n # process raw data or load processed data\r\n if os.path.exists(processed_path):\r\n processed_data = load_processed_data(processed_path, parsed_reader)\r\n elif os.path.exists(raw_path):\r\n processed_data = process_raw_file(raw_path, processed_path, sentence_parser)\r\n else:\r\n raise ValueError(\"Error: at least one of raw_path and processed_path should not be None.\")\r\n \r\n # remove prefix of sids\r\n document = list()\r\n for paragraph in processed_data:\r\n for sentence in paragraph:\r\n sentence[\"doc\"] = os.path.splitext(os.path.basename(processed_path))[0]\r\n sentence[\"sid\"] = sentence[\"sid\"].replace(prefix_to_be_removed, \"\", 1)\r\n document.append(sentence)\r\n # document.append(EMPTY_SENT_PARSED_RESULT)\r\n\r\n eventuality_lists, relation_lists = aser_extractor.extract_from_parsed_result(document)\r\n\r\n # merge eventualities\r\n eid2sids = defaultdict(list)\r\n eid2eventuality = dict()\r\n for sentence, eventuality_list in zip(document, eventuality_lists):\r\n for eventuality in eventuality_list:\r\n eid2sids[eventuality.eid].append(sentence[\"sid\"])\r\n if eventuality.eid not in eid2eventuality:\r\n eid2eventuality[eventuality.eid] = deepcopy(eventuality)\r\n else:\r\n eid2eventuality[eventuality.eid].update(eventuality)\r\n\r\n # merge relations\r\n rid2sids = defaultdict(list)\r\n rid2relation = dict()\r\n len_doc = len(document)\r\n\r\n # SS\r\n for idx in range(len_doc):\r\n relation_list = relation_lists[idx]\r\n for relation in relation_list:\r\n if sum(relation.relations.values()) > 0:\r\n rid2sids[relation.rid].append((document[idx][\"sid\"], document[idx][\"sid\"]))\r\n if relation.rid not in rid2relation:\r\n rid2relation[relation.rid] = deepcopy(relation)\r\n else:\r\n rid2relation[relation.rid].update(relation)\r\n # PS\r\n for idx in range(len_doc-1):\r\n relation_list = relation_lists[len_doc+idx]\r\n for relation in relation_list:\r\n if sum(relation.relations.values()) > 0:\r\n rid2sids[relation.rid].append((document[idx][\"sid\"], document[idx+1][\"sid\"]))\r\n if relation.rid not in rid2relation:\r\n rid2relation[relation.rid] = deepcopy(relation)\r\n else:\r\n rid2relation[relation.rid].update(relation)\r\n \r\n return eid2sids, rid2sids, eid2eventuality, rid2relation\r\n\r\ndef process_raw_file(raw_path, processed_path, sentence_parser):\r\n return sentence_parser.parse_raw_file(raw_path, processed_path, max_len=1000)\r\n\r\ndef load_processed_data(processed_path, parsed_reader):\r\n return parsed_reader.get_parsed_paragraphs_from_file(processed_path)\r\n\r\nclass ASERPipe(object):\r\n def __init__(self, opt):\r\n self.opt = opt\r\n self.n_workers = opt.n_workers\r\n self.n_extractors = opt.n_extractors\r\n self.sentence_parsers = [SentenceParser(\r\n corenlp_path=opt.corenlp_path, corenlp_port=opt.base_corenlp_port+_id) for _id in range(self.n_extractors)]\r\n self.parsed_readers = [ParsedReader() for _id in range(self.n_extractors)]\r\n # self.aser_extractors = [SeedRuleASERExtractor() for _id in range(self.n_extractors)]\r\n # self.aser_extractors = [DiscourseASERExtractor1() for _id in range(self.n_extractors)]\r\n self.aser_extractors = [DiscourseASERExtractor2() for _id in range(self.n_extractors)]\r\n # self.aser_extractors = [DiscourseASERExtractor3() for _id in range(self.n_extractors)]\r\n self.logger = init_logger(log_file=opt.log_path)\r\n\r\n def __del__(self):\r\n self.close()\r\n\r\n def close(self):\r\n for _id in range(self.n_extractors):\r\n self.sentence_parsers[_id].close()\r\n self.parsed_readers[_id].close()\r\n self.aser_extractors[_id].close()\r\n self.logger.info(\"%d ASER Extractors are closed.\" % (len(self.aser_extractors)))\r\n close_logger(self.logger)\r\n\r\n def run(self):\r\n self.logger.info(\"Start the pipeline.\")\r\n if os.path.exists(self.opt.raw_dir):\r\n if not os.path.exists(self.opt.processed_dir):\r\n os.mkdir(self.opt.processed_dir)\r\n self.logger.info(\"Processing raw data from %s.\" % (self.opt.raw_dir))\r\n raw_paths, processed_paths = list(), list()\r\n for file_name in iter_files(self.opt.raw_dir):\r\n raw_paths.append(file_name)\r\n processed_paths.append(\r\n os.path.splitext(file_name)[0].replace(self.opt.raw_dir, self.opt.processed_dir, 1) + \".jsonl\")\r\n elif os.path.exists(self.opt.processed_dir):\r\n self.logger.info(\"Loading processed data from %s.\" % (self.opt.processed_dir))\r\n raw_paths = list()\r\n processed_paths = [file_name for file_name in iter_files(self.opt.processed_dir) if file_name.endswith(\".jsonl\")]\r\n else:\r\n raise ValueError(\"Error: at least one of raw_dir and processed_dir should not be None.\")\r\n self.logger.info(\"Number of files: %d.\" % (len(processed_paths)))\r\n prefix_to_be_removed = self.opt.processed_dir+os.sep\r\n\r\n \r\n if self.n_workers > 1:\r\n with multiprocessing.Pool(self.n_workers) as pool:\r\n results = list()\r\n if len(processed_paths) < 10000:\r\n for worker_idx, (raw_path, processed_path) in enumerate(zip(raw_paths, processed_paths)):\r\n extractor_idx = worker_idx%self.n_extractors\r\n results.append(pool.apply_async(run_file, args=(\r\n raw_path, processed_path, prefix_to_be_removed, \r\n self.sentence_parsers[extractor_idx], self.parsed_readers[extractor_idx], \r\n self.aser_extractors[extractor_idx])))\r\n else:\r\n chunk_size = 10\r\n while math.ceil(len(processed_paths)/chunk_size) > 10000:\r\n chunk_size *= 10\r\n for worker_idx in range(math.ceil(len(processed_paths)/chunk_size)):\r\n extractor_idx = worker_idx%self.n_extractors\r\n i = worker_idx * chunk_size\r\n j = min(i + chunk_size, len(processed_paths))\r\n results.append(pool.apply_async(run_files, args=(\r\n raw_paths[i:j], processed_paths[i:j], prefix_to_be_removed, \r\n self.sentence_parsers[extractor_idx], self.parsed_readers[extractor_idx], \r\n self.aser_extractors[extractor_idx])))\r\n pool.close()\r\n \r\n # merge all results\r\n eid2sids, rid2sids, eid2eventuality, rid2relation = defaultdict(list), defaultdict(list), dict(), dict()\r\n eventuality_counter, relation_counter = Counter(), Counter()\r\n for x in tqdm(results):\r\n x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation = x.get()\r\n if len(eid2eventuality) == 0 and len(rid2relation) == 0:\r\n eid2sids, rid2sids, eid2eventuality, rid2relation = x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation\r\n for eid, eventuality in x_eid2eventuality.items():\r\n eventuality_counter[eid] += eventuality.frequency\r\n for rid, relation in x_rid2relation.items():\r\n relation_counter[rid] += sum(relation.relations.values())\r\n else:\r\n for eid, sids in x_eid2sids.items():\r\n eid2sids[eid].extend(sids)\r\n for rid, sids in x_rid2sids.items():\r\n rid2sids[rid].extend(sids)\r\n for eid, eventuality in x_eid2eventuality.items():\r\n eventuality_counter[eid] += eventuality.frequency\r\n if eid not in eid2eventuality:\r\n eid2eventuality[eid] = eventuality\r\n else:\r\n eid2eventuality[eid].update(eventuality)\r\n for rid, relation in x_rid2relation.items():\r\n relation_counter[rid] += sum(relation.relations.values())\r\n if rid not in rid2relation:\r\n rid2relation[rid] = relation\r\n else:\r\n rid2relation[rid].update(relation)\r\n if len(eid2sids) > 0 or len(rid2sids) > 0:\r\n del x_eid2sids, x_rid2sids, x_eid2eventuality, x_rid2relation\r\n else:\r\n eid2sids, rid2sids, eid2eventuality, rid2relation = run_files(\r\n raw_paths, processed_paths, prefix_to_be_removed, \r\n self.sentence_parsers[0], self.parsed_readers[0], \r\n self.aser_extractors[0])\r\n eventuality_counter, relation_counter = Counter(), Counter()\r\n for eid, eventuality in eid2eventuality.items():\r\n eventuality_counter[eid] += eventuality.frequency\r\n for rid, relation in rid2relation.items():\r\n relation_counter[rid] += sum(relation.relations.values())\r\n\r\n total_eventuality, total_relation = sum(eventuality_counter.values()), sum(relation_counter.values())\r\n self.logger.info(\"%d eventualities (%d unique) have been extracted.\" % (total_eventuality, len(eid2eventuality)))\r\n self.logger.info(\"%d relations (%d unique) have been extracted.\" % (total_relation, len(rid2relation)))\r\n\r\n if self.opt.full_kg_dir:\r\n # build eventuality KG\r\n self.logger.info(\"Storing inverted tables.\")\r\n if not os.path.exists(self.opt.full_kg_dir):\r\n os.mkdir(self.opt.full_kg_dir)\r\n with open(os.path.join(self.opt.full_kg_dir, \"eid2sids.pkl\"), \"wb\") as f:\r\n pickle.dump(eid2sids, f)\r\n with open(os.path.join(self.opt.full_kg_dir, \"rid2sids.pkl\"), \"wb\") as f:\r\n pickle.dump(rid2sids, f)\r\n\r\n self.logger.info(\"Building the full KG.\")\r\n kg_conn = ASERKGConnection(os.path.join(self.opt.full_kg_dir, \"KG.db\"), mode='insert')\r\n kg_conn.insert_eventualities(eid2eventuality.values())\r\n kg_conn.insert_relations(rid2relation.values())\r\n kg_conn.close()\r\n self.logger.info(\"Done.\")\r\n\r\n if self.opt.core_kg_dir:\r\n # filter high-frequency and low-frequency eventualities\r\n self.logger.info(\"Filtering high-frequency and low-frequency eventualities.\")\r\n eventuality_frequency_lower_cnt_threshold = self.opt.eventuality_frequency_lower_cnt_threshold\r\n eventuality_frequency_upper_cnt_threshold = self.opt.eventuality_frequency_upper_percent_threshold * total_eventuality\r\n filtered_eids = set([eid for eid, freq in eventuality_counter.items() \\\r\n if freq < eventuality_frequency_lower_cnt_threshold or freq > eventuality_frequency_upper_cnt_threshold])\r\n for filtered_eid in filtered_eids:\r\n eid2sids.pop(filtered_eid)\r\n eid2eventuality.pop(filtered_eid)\r\n total_eventuality -= eventuality_counter.pop(filtered_eid)\r\n # del eventuality_counter\r\n self.logger.info(\"%d eventualities (%d unique) will be inserted into the core KG.\" % (total_eventuality, len(eid2eventuality)))\r\n\r\n # filter high-frequency and low-frequency relations\r\n self.logger.info(\"Filtering high-frequency and low-frequency relations.\")\r\n relation_frequency_lower_cnt_threshold = self.opt.relation_frequency_lower_cnt_threshold\r\n relation_frequency_upper_cnt_threshold = self.opt.relation_frequency_upper_percent_threshold * total_relation\r\n filtered_rids = set([rid for rid, freq in relation_counter.items() \\\r\n if freq < relation_frequency_lower_cnt_threshold or freq > relation_frequency_upper_cnt_threshold])\r\n filtered_rids.update(set([rid for rid, relation in rid2relation.items() \\\r\n if relation.hid in filtered_eids or relation.tid in filtered_eids]))\r\n for filtered_rid in filtered_rids:\r\n rid2sids.pop(filtered_rid)\r\n rid2relation.pop(filtered_rid)\r\n total_relation -= relation_counter.pop(filtered_rid)\r\n # del relation_counter\r\n self.logger.info(\"%d relations (%d unique) will be inserted into the core KG.\" % (total_relation, len(rid2relation)))\r\n\r\n if len(filtered_eids) == 0 and len(filtered_rids) == 0 and self.opt.full_kg_dir:\r\n # copy KG\r\n self.logger.info(\"Copying the full KG as the core KG.\")\r\n if not os.path.exists(self.opt.core_kg_dir):\r\n os.mkdir(self.opt.core_kg_dir)\r\n shutil.copyfile(os.path.join(self.opt.full_kg_dir, \"eid2sids.pkl\"), os.path.join(self.opt.core_kg_dir, \"eid2sids.pkl\"))\r\n shutil.copyfile(os.path.join(self.opt.full_kg_dir, \"rid2sids.pkl\"), os.path.join(self.opt.core_kg_dir, \"rid2sids.pkl\"))\r\n shutil.copyfile(os.path.join(self.opt.full_kg_dir, \"KG.db\"), os.path.join(self.opt.core_kg_dir, \"KG.db\"))\r\n else:\r\n # build eventuality KG\r\n self.logger.info(\"Storing inverted tables.\")\r\n if not os.path.exists(self.opt.core_kg_dir):\r\n os.mkdir(self.opt.core_kg_dir)\r\n with open(os.path.join(self.opt.core_kg_dir, \"eid2sids.pkl\"), \"wb\") as f:\r\n pickle.dump(eid2sids, f)\r\n with open(os.path.join(self.opt.core_kg_dir, \"rid2sids.pkl\"), \"wb\") as f:\r\n pickle.dump(rid2sids, f)\r\n # del eid2sids, rid2sids\r\n\r\n self.logger.info(\"Building the core KG.\")\r\n kg_conn = ASERKGConnection(os.path.join(self.opt.core_kg_dir, \"KG.db\"), mode='insert')\r\n kg_conn.insert_eventualities(eid2eventuality.values())\r\n kg_conn.insert_relations(rid2relation.values())\r\n kg_conn.close()\r\n # del eid2eventuality, rid2relation\r\n self.logger.info(\"Done.\")","sub_path":"aser/pipe/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":17855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237535525","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 24 14:58:36 2016\n\n@author: Hugo\n\"\"\"\nimport tkinter as tk\nfrom gameplay import *\n\nclass tabuleiro:\n def __init__(self,height,width,row,column):\n self.height = height\n self.width = width\n self.row = row\n self.column = column\n \n def criar_tabuleiro(botão):\n printar = tk.Label(window)\n botãox = tk.Button(window)\n# botãox.config( height = 10,width = 20)\n botãox.grid(row = botão.row,column = botão.column)\n botãox.configure(bg = \"gray\")\n botõesx.append(botãox)\n a = Base.verifica_ganhador()\n if a == -1:\n botãox.configure(command= lambda: tabuleiro.rodar(botão.row,botão.column))\n \n if a == 1:\n printar.configure(text=\"Jogador X ganhou!\",font=(\"Helvetica\",11),background=\"white\",foreground = \"dark blue\")\n printar.grid(row=1,column=1)\n tabuleiro.tentar_novamente()\n \n elif a == 0:\n printar.configure(text=\"DEU VELHA\",font=(\"Helvetica\",15),background=\"black\",foreground = \"white\")\n printar.grid(row=1,column=1)\n tabuleiro.tentar_novamente()\n if a == 2:\n printar.configure(text=\"Jogador O ganhou!\",font=(\"Helvetica\",11),background=\"black\",foreground = \"orange\")\n printar.grid(row=1,column=1)\n tabuleiro.tentar_novamente()\n elif a == 0:\n printar.configure(text=\"DEU VELHA\",background=\"black\",foreground = \"white\")\n printar.grid(row=1,column=1)\n tabuleiro.tentar_novamente() \n \n if jogo.matriz[botão.row][botão.column] == 0 and jogo.turno == 1:\n botãox.configure(text=\"x\",font=(\"Helvetica\",70),background=\"gray\",foreground = \"gray\")\n \n if jogo.matriz[botão.row][botão.column] == 0 and jogo.turno == 2:\n botãox.configure(text=\"o\",font=(\"Helvetica\",70),background=\"gray\",foreground = \"gray\")\n \n if jogo.matriz[botão.row][botão.column] == -1:\n botãox.configure(text=\"x\",font=(\"Helvetica\",70),background=\"white\",foreground=\"dark blue\")\n\n elif jogo.matriz[botão.row][botão.column]== 1:\n botãox.configure(text=\"o\",font=(\"Helvetica\",69),background=\"black\",foreground=\"orange\")\n\n def rodar(i,n):\n Base.recebe_jogada(i,n)\n for p in botões:\n tabuleiro.criar_tabuleiro(p)\n \n if jogo.turno == 2:\n label.configure(text=\"VEZ DO JOGADOR O\")\n label.grid(row=3,column=1)\n elif jogo.turno == 1:\n label.configure(text=\"VEZ DO JOGADOR X\")\n label.grid(row=3,column=1)\n \n def tentar_novamente():\n tente = tk.Button(window)\n tente.configure(text=\"Recomeçar\")\n tente.configure(command=tabuleiro.resetar_tabuleiro)\n tente.grid(row=4,column=1)\n \n def resetar_tabuleiro():\n Base.limpar_jogadas()\n for p in botões:\n tabuleiro.criar_tabuleiro(p)\n \nwindow = tk.Tk() \nlabel =tk.Label(window) \n\nbotão1 = tabuleiro(10,20,0,0)\nbotão2 = tabuleiro(10,20,0,1)\nbotão3 = tabuleiro(10,20,0,2)\nbotão4 = tabuleiro(10,20,1,0)\nbotão5= tabuleiro(10,20,1,1)\nbotão6 = tabuleiro(10,20,1,2)\nbotão7 = tabuleiro(10,20,2,0)\nbotão8= tabuleiro(10,20,2,1)\nbotão9 = tabuleiro(10,20,2,2)\n \nbotões = [botão1,botão2,botão3,botão4,botão5,botão6,botão7,botão8,botão9]\nbotõesx= []\n\njogo_is_on = 1\n\nlabel = tk.Label(window) \nwindow.title(\"Jogo da Velha\")\n \nfor p in botões:\n tabuleiro.criar_tabuleiro(p)\n\nlabel =tk.Label(window)\nlabel.configure(text=\"VEZ DO JOGADOR X\")\nlabel.grid(row=3,column=1)\n \nwindow.mainloop()\n","sub_path":"tabuleiroalt.py","file_name":"tabuleiroalt.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"542271490","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom vcomm import Checkbar,label_entry,img_tool,one_label_entry,one_radion_box,param_input\nfrom vresult_data_reward import ana_reward\nfrom vresult_data_loss import ana_loss\nfrom vresult_data_pbsv import ana_pbsv, ana_pbsv_detail\nimport tkinter as tk\nfrom vresult_data_com import are_base\nimport recorder\nclass vresult(tk.Frame):\n def __init__(self, container, param):\n tk.Frame.__init__(self, container)\n self.system_name=param[\"system_name\"]\n self.eval_process_name=param[\"eval_process_name\"]\n self.ip=are_base(self.system_name, self.eval_process_name)\n self.Lstock, self.LEvalT, self.LYM=self.ip.get_init_data()\n\n self.Cidx_stock,self.Cidx_EvalT,self.Cidx_LYM=0,0,0\n self.Cidx_stock2, self.Cidx_EvalT2, self.Cidx_LYM2 = 0, 0, 0\n\n self.i_ana_reward = ana_reward(self.system_name, self.eval_process_name)\n\n self.i_ana_loss= ana_loss(self.system_name)\n\n\n self.lfield, self.lstat=self.i_ana_loss.i_loss_summary_recorder.get_column_choices()\n self.i_ana_pbsv = ana_pbsv(self.system_name, self.eval_process_name)\n self.i_ana_pbsv_detail = ana_pbsv_detail(self.system_name, self.eval_process_name)\n\n self.fig = Figure(figsize=(5, 5), dpi=100)\n self.canvas = FigureCanvasTkAgg(self.fig, self)\n self.canvas.show()\n self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)\n toolbar = NavigationToolbar2TkAgg(self.canvas, self)\n toolbar.update()\n self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)\n\n self.frame_update(\"\")\n self.init_control_frame()\n\n\n def frame_update(self, Event):\n if Event==\"\": #this only for the init start\n show_type = \"reward_summary\"\n EvalT=1000\n stock2, EvalT2, YM2=\"\",\"\",\"\"\n Cidx_stock2,Cidx_LYM2,Cidx_EvalT2=0,0,0\n rd_param = []\n hist_param = []\n\n ETP_param=[]\n stock=\"\"\n YM=\"\"\n selected_sv_pb=[]\n reward_dist_sub_choice=\"\"\n Dreward_img_customized=[]\n\n l_selected_loss_summary =\"\"\n l_selected_loss_summary_fun =\"\"\n\n else:\n #prilimary SEY\n stock= self.input_stock.entry()\n self.Cidx_stock=self.Lstock.index(stock)\n\n YM=self.input_month.entry()\n self.Cidx_LYM = self.LYM.index(YM)\n\n EvalT=int(self.input_eval_count.entry())\n self.Cidx_EvalT=self.LEvalT.index(EvalT)\n\n # secondary SEY\n stock2 = self.input_stock2.entry()\n self.Cidx_stock2 = self.Lstock.index(stock2)\n\n YM2 = self.input_month2.entry()\n self.Cidx_LYM2 = self.LYM.index(YM2)\n\n EvalT2 = int(self.input_eval_count2.entry())\n self.Cidx_EvalT2 = self.LEvalT.index(EvalT2)\n\n show_type=self.show_type.get()#self.cb.selcted_item()\n\n selected_sv_pb=self.sv_pb.selcted_item()\n\n rd_param=self.i_rd_param.get_param()\n\n hist_param=self.i_hist_param.get_param()\n\n ETP_param=self.i_ETP_param.get_param()\n\n reward_dist_sub_choice=self.i_reward_dist_sub_choice.get()\n\n Dreward_img_customized=self.i_reward_img_customize.get_param()\n\n\n l_selected_loss_summary=self.loss_content.selcted_item()\n if len(l_selected_loss_summary)>3:\n return\n l_selected_loss_summary_fun=self.loss_fun.selcted_item()\n if len(l_selected_loss_summary_fun)<1:\n return\n if show_type==\"reward_summary\":\n self.i_ana_reward.show_reward(self.fig,EvalT,rd_param=rd_param, hist_param=hist_param)\n elif show_type==\"reward_detail\":\n self.i_ana_reward.show_reward_detail(self.fig, stock, EvalT, YM,Dimgc=Dreward_img_customized)\n elif show_type==\"reward_distribution\":\n self.i_ana_reward.show_reward_distribution(self.fig, stock, EvalT, Dimgc=Dreward_img_customized,\n sub_choice=reward_dist_sub_choice)\n elif show_type == \"reward_compare_ET\":\n lpriliminary_choice= [stock, EvalT,YM]\n lsecondary_choice = [stock2, EvalT2,YM2]\n self.i_ana_reward.show_reward_compare_ET(self.fig,lpriliminary_choice, lsecondary_choice,hist_param,\n Dimgc=Dreward_img_customized,sub_choice=reward_dist_sub_choice)\n elif show_type == \"reward_compare_ET(stock)\":\n lpriliminary_choice= [stock, EvalT,YM]\n lsecondary_choice = [stock2, EvalT2,YM2]\n if stock!=stock2:\n return\n self.i_ana_reward.show_reward_compare_ET__stock(self.fig, lpriliminary_choice, lsecondary_choice,\n hist_param, Dimgc=Dreward_img_customized,sub_choice=reward_dist_sub_choice)\n elif show_type==\"pbsv_summary\":\n if len(selected_sv_pb) <2:\n return\n self.i_ana_pbsv.show(self.fig, stock,selected_sv_pb, ETP_param=ETP_param, flag_trend=False)\n elif show_type==\"pbsv_summary_trend\":\n if len(selected_sv_pb) <2:\n return\n self.i_ana_pbsv.show(self.fig, stock,selected_sv_pb, ETP_param=ETP_param, flag_trend=True)\n elif show_type == \"pbsv_detail\":\n if \"state_value\" in selected_sv_pb:\n selected_sv_pb.remove(\"state_value\")\n if len(selected_sv_pb) ==0:\n return\n self.i_ana_pbsv_detail.show(self.fig, stock, EvalT,selected_sv_pb)\n elif show_type == \"loss_detail_ET\":\n self.i_ana_loss.show_loss(self.fig,EvalT,self.LEvalT,l_selected_loss_summary,\n self.i_ana_loss.i_loss_summary_recorder,self.i_ana_reward.plot_reward_count)\n elif show_type == \"loss_summary\":\n self.i_ana_loss.show_loss_summary(self.fig,l_selected_loss_summary, l_selected_loss_summary_fun,EvalT,\n self.i_ana_reward.plot_reward_count, self.LEvalT,self.i_ana_loss.i_loss_summary_recorder)\n\n elif show_type == \"loss_detail_ET_tb(quick)\":\n self.i_ana_loss.show_loss(self.fig,EvalT,self.LEvalT,l_selected_loss_summary,\n self.i_ana_loss.i_loss_summary_tb,self.i_ana_reward.plot_reward_count)\n elif show_type == \"loss_summary_tb(quick)\":\n self.i_ana_loss.show_loss_summary(self.fig,l_selected_loss_summary, l_selected_loss_summary_fun,EvalT,\n self.i_ana_reward.plot_reward_count, self.LEvalT, self.i_ana_loss.i_loss_summary_tb)\n\n else:\n assert False, \"unexpect show_type choice {0}\".format(show_type)\n\n self.canvas.draw()\n\n\n\n def init_control_frame(self):\n layout_column=0\n xiamian=tk.Frame(self)\n xiamian.pack(anchor=tk.W)\n\n cfc0 = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cfc0.grid(column=layout_column,row=0,sticky=tk.NW)\n\n\n tk.Label(cfc0, text = \"Pliminary Choice\").grid(column=0, row=0, sticky=tk.W)\n cfc0r1= tk.Frame(cfc0)\n cfc0r1.grid(column=0, row=1, sticky=tk.W)\n self.input_stock = label_entry(cfc0r1, \"Stock\", self.Lstock[self.Cidx_stock] )\n\n cfc0r2= tk.Frame(cfc0)\n cfc0r2.grid(column=0, row=2, sticky=tk.W)\n self.input_month = label_entry(cfc0r2, \"Month\", self.LYM[self.Cidx_LYM])\n\n cfc0r3= tk.Frame(cfc0)\n cfc0r3.grid(column=0, row=3, sticky=tk.W)\n self.input_eval_count = label_entry(cfc0r3, \"EvalT\", self.LEvalT[self.Cidx_EvalT])\n layout_column+=1\n\n cfc0 = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cfc0.grid(column=layout_column,row=0,sticky=tk.NW)\n tk.Label(cfc0, text=\"Secondary Choice\").grid(column=0, row=0, sticky=tk.W)\n\n cfc0r1= tk.Frame(cfc0)\n cfc0r1.grid(column=0, row=1, sticky=tk.W)\n self.input_stock2 = label_entry(cfc0r1, \"Stock\", self.Lstock[self.Cidx_stock2] )\n\n cfc0r2= tk.Frame(cfc0)\n cfc0r2.grid(column=0, row=2, sticky=tk.W)\n self.input_month2 = label_entry(cfc0r2, \"Month\", self.LYM[self.Cidx_LYM2])\n\n cfc0r3= tk.Frame(cfc0)\n cfc0r3.grid(column=0, row=3, sticky=tk.W)\n self.input_eval_count2 = label_entry(cfc0r3, \"EvalT\", self.LEvalT[self.Cidx_EvalT2])\n layout_column+=1\n\n\n # radio box show type\n title_show_type = [\n (\"reward_summary\", \"reward_summary\"),\n (\"reward_detail\", \"reward_detail\"),\n (\"reward_distribution\", \"reward_distribution\"),\n (\"reward_compare_ET\", \"reward_compare_ET\"),\n (\"reward_compare_ET(stock)\", \"reward_compare_ET(stock)\"),\n (\"pbsv_summary\", \"pbsv_summary\"),\n (\"pbsv_summary_trend\", \"pbsv_summary_trend\"),\n (\"pbsv_detail\", \"pbsv_detail\"),\n (\"loss_detail_ET\", \"loss_detail_ET\"),\n (\"loss_summary\", \"loss_summary\"),\n (\"loss_detail_ET_tb(quick)\", \"loss_detail_ET_tb(quick)\"),\n (\"loss_summary_tb(quick)\", \"loss_summary_tb(quick)\")\n ]\n cfc1 = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cfc1.grid(column=layout_column,row=0,sticky=tk.NW)\n self.show_type=one_radion_box(cfc1,title_show_type, main_title=\"main menu\")\n layout_column+=1\n\n # check box sv ap choice\n title_sv_pb = [\"state_value\"]\n for idx in range(self.ip.lgc.num_action):\n label=\"Action_Prob_{0}\".format(idx)\n title_sv_pb.append(label)\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.sv_pb=Checkbar(cf, title_sv_pb,[title_sv_pb[0],title_sv_pb[1]],flag_divide=False,main_title=\"choice_pbsv\" )\n layout_column += 1\n\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n title_reward_duration = [\n (\"rd(origin)\", \"reward vs duration(origin)\"),\n (\"rd(threadhold)\", \"reward vs duration(threadhold)\")\n ]\n self.i_rd_param=param_input(cf,title_reward_duration,[\"reward_max\",\"reward_min\",\"duration_max\"],main_title=\"reward_summary_rd\" )\n self.i_rd_param.show_elements()\n layout_column += 1\n\n title_hist = [\n (\"hist(origin)\", \"hist(origin)\"),\n (\"hist(threadhold)\", \"hist(threadhold)\")\n ]\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.i_hist_param=param_input(cf,title_hist,[\"hist_max\",\"hist_min\",\"hist_step\"],main_title=\"reward_summary_hist\" )\n self.i_hist_param.show_elements()\n layout_column += 1\n\n title_EvalT_period = [\n (\"ET_period(origin)\", \"ET_period(origin)\"),\n (\"ET_period(threadhold)\", \"ET_period(threadhold)\")\n ]\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.i_ETP_param=param_input(cf,title_EvalT_period,[\"ET_max\",\"ET_min\"],main_title=\"pbsv_clip\" )\n self.i_ETP_param.show_elements()\n layout_column += 1\n\n # radio box show type\n title_sub_choice = [\n (\"mean\", \"mean\"),\n (\"median\", \"median\"),\n (\"count\", \"count\"),\n (\"std\", \"std\")\n ]\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.i_reward_dist_sub_choice=one_radion_box(cf,title_sub_choice, main_title=\"reward_dist_sub_choice\")\n layout_column+=1\n\n\n title_hist = [\n (\"Origin\", \"Origin\"),\n (\"Greater E\", \"Greater\"),\n (\"Less E\", \"Less\")\n ]\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.i_reward_img_customize=param_input(cf,title_hist,[\"threadhold\"],main_title=\"custom_reward_img\" )\n self.i_reward_img_customize.show_elements()\n layout_column += 1\n\n\n # check box sv ap choice\n title_loss = [\"loss_summary_choice\"]\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n\n\n cfsub = tk.Frame(cf, width=200, height=200, bd= 0)\n cfsub.grid(column=0,row=0,sticky=tk.NW)\n self.loss_content = Checkbar(cfsub, self.lfield,[self.lfield[0],self.lfield[1],self.lfield[2]], flag_divide=False,\n main_title=\"choice_content\")\n\n cfsub = tk.Frame(cf,width=200, height=200, bd= 0)\n cfsub.grid(column=0,row=1,sticky=tk.NW)\n self.loss_fun = Checkbar(cfsub, self.lstat,[self.lstat[0],self.lstat[2],self.lstat[3]] ,flag_divide=True,\n main_title=\"choice_fun\")\n\n layout_column += 1\n\n # update buttom\n cf = tk.Frame(xiamian,highlightbackground=\"green\", highlightcolor=\"green\", highlightthickness=2,\n width=200, height=200, bd= 0)\n cf.grid(column=layout_column,row=0,sticky=tk.NW)\n self.update_button = tk.Button(cf, text=\"update\",width=10)\n self.update_button.pack(anchor=tk.W)\n self.prepare_loss_button = tk.Button(cf, text=\"prepare_loss\",width=10)\n self.prepare_loss_button.pack(anchor=tk.W)\n\n layout_column += 1\n\n\n\n\n #prilimary SEY\n self.stock_pre_button=self.pre_button_common(self.Lstock, \"Cidx_stock\",self.input_stock)\n self.stock_next_button=self.next_button_common(self.Lstock, \"Cidx_stock\",self.input_stock)\n self.input_stock.get_prev_button().bind(\"\", func=self.stock_pre_button)\n self.input_stock.get_next_button().bind(\"\", func=self.stock_next_button)\n\n\n self.month_pre_button=self.pre_button_common(self.LYM, \"Cidx_LYM\",self.input_month)\n self.month_next_button = self.next_button_common(self.LYM, \"Cidx_LYM\", self.input_month)\n self.input_month.get_prev_button().bind(\"\", func=self.month_pre_button)\n self.input_month.get_next_button().bind(\"\", func=self.month_next_button)\n\n self.eval_count_pre_button=self.pre_button_common(self.LEvalT, \"Cidx_EvalT\",self.input_eval_count)\n self.eval_count_next_button = self.next_button_common(self.LEvalT, \"Cidx_EvalT\", self.input_eval_count)\n self.input_eval_count.get_prev_button().bind(\"\", func=self.eval_count_pre_button)\n self.input_eval_count.get_next_button().bind(\"\", func=self.eval_count_next_button)\n\n # secondary SEY\n self.stock_pre_button2=self.pre_button_common(self.Lstock, \"Cidx_stock2\",self.input_stock2)\n self.stock_next_button2=self.next_button_common(self.Lstock, \"Cidx_stock2\",self.input_stock2)\n self.input_stock2.get_prev_button().bind(\"\", func=self.stock_pre_button2)\n self.input_stock2.get_next_button().bind(\"\", func=self.stock_next_button2)\n\n\n self.month_pre_button2=self.pre_button_common(self.LYM, \"Cidx_LYM2\",self.input_month2)\n self.month_next_button2 = self.next_button_common(self.LYM, \"Cidx_LYM2\", self.input_month2)\n self.input_month2.get_prev_button().bind(\"\", func=self.month_pre_button2)\n self.input_month2.get_next_button().bind(\"\", func=self.month_next_button2)\n\n self.eval_count_pre_button2=self.pre_button_common(self.LEvalT, \"Cidx_EvalT2\",self.input_eval_count2)\n self.eval_count_next_button2 = self.next_button_common(self.LEvalT, \"Cidx_EvalT2\", self.input_eval_count2)\n self.input_eval_count2.get_prev_button().bind(\"\", func=self.eval_count_pre_button2)\n self.input_eval_count2.get_next_button().bind(\"\", func=self.eval_count_next_button2)\n\n self.update_button.bind(\"\", func=self.frame_update)\n\n self.prepare_loss_button.bind(\"\", func=self.prepare_loss)\n\n\n def prepare_loss(self,Event):\n i=recorder.get_recorder_OS_losses(self.system_name)\n i.get_losses()\n\n def pre_button_common(self, List_content, list_index_name,control):\n def pre_button_core(Event):\n Cidx=getattr(self,list_index_name)\n if Cidx == 0:\n Cidx = len(List_content) - 1\n else:\n Cidx -= 1\n selected_content = List_content[Cidx]\n control.set_entry(selected_content)\n self.frame_update(Event)\n return pre_button_core\n\n def next_button_common(self,List_content, list_index_name,control):\n def next_button_core(Event):\n Cidx = getattr(self, list_index_name)\n if Cidx == len(List_content) - 1:\n Cidx = 0\n else:\n Cidx += 1\n selected_content = List_content[Cidx]\n control.set_entry(selected_content)\n self.frame_update(Event)\n return next_button_core\n","sub_path":"vresult.py","file_name":"vresult.py","file_ext":"py","file_size_in_byte":18591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263014228","text":"\nimport unittest\nimport time\nfrom eta.api.session import Session, SessionError, RequestError\nfrom eta.api.credentials import EtaCredentials\nfrom eta.api.user import User\nfrom . import CONFIG\n\nclass SessionCase(unittest.TestCase):\n\n def test_invalid_key(self):\n with self.assertRaises(RequestError):\n session = Session(CONFIG['url'], \"not valid\", \"not valid\")\n session.create() # create session.\n\n def test_request_error_json(self):\n try:\n session = Session(CONFIG['url'], \"not valid\", \"not valid\")\n session.create() # create session.\n except RequestError as e:\n self.assertIsInstance(e.json(), dict) \n\n def test_request_error_formatting(self):\n try:\n session = Session(CONFIG['url'], \"not valid\", \"not valid\")\n session.create() # create session.\n self.assertTrue(False) #should not hit this part\n except RequestError as e:\n r = repr(e)\n self.assertTrue(\"1102\" in r) #1102 is the error code for Invalid API key\n\n def test_error_on_empty_session_signature(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n with self.assertRaises(SessionError):\n sign = session.signature()\n\n def test_create(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create() # try to create it\n session.delete() # and delete it again\n\n def test_create_explicit_api_key_safeguard(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n with self.assertRaises(SessionError):\n session.create({\n \"api_key\": CONFIG['key']\n })\n #since we did not create a session, delete will also fail:\n with self.assertRaises(SessionError):\n session.delete()\n\n def test_setting_client_id(self):\n cid = \"dummy-client-id\"\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'], client_id=cid)\n session.create()\n self.assertEqual(session.client_id, cid)\n session.delete()\n\n def test_double_create(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create() # try to create it\n with self.assertRaises(SessionError):\n session.create()\n session.delete() # and delete it again\n\n def test_delete_throws(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n with self.assertRaises(SessionError):\n session.delete() # and delete it again\n\n def test_update_empty_session(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n with self.assertRaises(SessionError):\n session.update() #not-created session should throw session error on call to update\n\n def test_refresh(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create() # create\n token = session.token\n expires = session.expires\n client_id = session.client_id\n reference = session.reference\n time.sleep(1) # we need to wait a bit to ensure time has changed between tokens\n session.renew() # renew, token should change\n self.assertNotEqual(token, session.token)\n self.assertNotEqual(expires, session.expires)\n self.assertEqual(client_id, session.client_id)\n self.assertEqual(reference, session.reference)\n session.delete() # and delete it again\n with self.assertRaises(SessionError):\n token = session.token\n\n def test_reload(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create() # create\n token = session.token\n session.reload() # reload, token should NOT change\n self.assertEqual(token, session.token)\n session.delete() # and delete it again\n with self.assertRaises(SessionError):\n token = session.token\n\n def test_revalidate(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create()\n self.assertTrue(session.revalidate())\n session.delete()\n\n def test_revalidate_on_non_existing_session(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n self.assertFalse(session.revalidate())\n\n def test_empty_update(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create()\n token = session.token\n session.update()\n self.assertNotEqual(token, session.token) #token should change, even on empty update\n session.delete()\n\n def test_reload_throws(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create() # create\n session.delete() # and delete it again\n with self.assertRaises(SessionError):\n session.reload() # reload should throw as we just destroyed the session\n\n def test_login_direct(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.login(EtaCredentials(CONFIG['email'], CONFIG['password']))\n self.assertEqual(session.provider, 'etilbudsavis') #expect that EtaCredentials is etilbudsavis provided login\n self.assertTrue(session.has_user)\n session.delete()\n\n def test_login_invalid_credentials(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n with self.assertRaises(ValueError):\n session.login({\n \"email\": CONFIG[\"email\"],\n \"password\": CONFIG[\"password\"]\n })\n\n def test_login_logout(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.login(EtaCredentials(CONFIG['email'], CONFIG['password']))\n self.assertEqual(session.provider, 'etilbudsavis') #expect that EtaCredentials is etilbudsavis provided login\n self.assertTrue(session.has_user)\n session.logout()\n self.assertEqual(session.provider, None) # no provider on non-user session\n self.assertFalse(session.has_user) # no user should exist\n session.delete()\n\n def test_permissions_allows_call(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.login(EtaCredentials(CONFIG['email'], CONFIG['password']))\n session.allows(\"public.**\")\n session.delete()\n\n def test_login_on_existing(self):\n session = Session(CONFIG['url'], CONFIG['key'], CONFIG['secret'])\n session.create()\n self.assertIsNone(session.user)\n session.login(EtaCredentials(CONFIG['email'], CONFIG['password']))\n self.assertIsInstance(session.user, User)\n session.delete()\n","sub_path":"eta/tests_blackbox/test_session.py","file_name":"test_session.py","file_ext":"py","file_size_in_byte":6825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466306868","text":"#Brendan Creek Programming 2017\n\nimport random #for random.choice\ndictionary=['Word'] #Replace word with word\nword=random.choice(dictionary)\noriginal=list(word)\ntemp=list(word)\nguess=[] #null list\ntrial=int(0) #for keeping track of guessess\nuserinput=''\ncounter=int(0) #keeping track of position of element in list (if found)\n\nfor i in range(len(original)): #creating the '_ _**....' list\n if (original[i]=='A') or (original[i]=='E') or (original[i]=='I') or (original[i]=='O') or (original[i]=='U'):\n guess.append(\"*\") #* for vowels\n else:\n guess.append(\"_\")#_ for all other alphabets\nprint(\"\\n\", guess, \"\\n\", \"\\n\")\n\nwhile trial<10:\n userinput=str.upper(input('Input : '))\n\n if len(userinput)>1: #checking for multiple characters\n print('Error : Input only a single character')\n continue\n\n if userinput in original:\n \n while userinput in temp: #loop for checking redundant characters\n counter=temp.index(userinput)\n guess[counter]=userinput\n temp.remove(userinput)\n temp.insert(counter,'_')\n\n\n for i in range(0,len(temp)): #checking for final guess match with original\n if temp[i]=='_':\n counter+=1\n\n if counter==len(original): #if guess matches original\n print('Correct\\n', guess)\n print('You Win !')\n trial=10\n break\n\n print('Correct \\n \\n' , guess , 'Trials left: ', (10-trial), \"\\n\")\n\n else:\n trial+=1\n print('Incorrect \\n \\n', 'Trials left: ', (10-trial), \"\\n\")\nelse:\n print('You Lose!')\n print('Correct answer was\\t', original)\n","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482577971","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nimg = cv2.imread(\"Norway.jpg\",0)\r\ncv2.namedWindow('image', cv2.WINDOW_NORMAL)\r\ncv2.imshow('image', img)\r\nk=cv2.waitKey(0)\r\nif k==27:\r\n\tcv2.destroyAllWindows()\r\nelif k==ord('s'):\r\n\tfont = cv2.FONT_HERSHEY_SIMPLEX\r\n\tcv2.putText(img, 'Norway', (10,500), font, 4, (255,255,255), 2, cv2.LINE_AA)\r\n\tcv2.imwrite('grayNorway.png',img)\r\n\tcv2.destroyAllWindows()\r\n# plt.imshow(img, cmap='gray', interpolation = 'bicubic')\r\n# plt.xticks([]), plt.yticks([])\r\n# plt.show()","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"149901971","text":"from pybrain.structure.modules import TanhLayer, SigmoidLayer, LinearLayer, StateDependentLayer, SoftmaxLayer\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.datasets import SupervisedDataSet\nfrom pybrain.supervised.trainers import BackpropTrainer\n\n# Add a data set\nvalidData = [\n [(0, 0), (0)],\n [(0, 1), (1)],\n [(1, 0), (1)],\n [(1, 1), (0)],\n]\n# create a data set for valid data\nds = SupervisedDataSet(2, 1)\nfor input, target in validData:\n ds.addSample(input, target)\n\n# create a large random data set\nimport random\nrandom.seed()\ntrainingSet = SupervisedDataSet(2, 1);\n\nmaxTrainingData = 100; # value of training dataset\nfor randomInput in range(0, maxTrainingData):\n input, target = validData[random.getrandbits(2)];\n trainingSet.addSample(input, target)\n\n# print length of datasets (4; maxTrainingData)\nprint('network length:', len(ds))\nprint('training set length:', len(trainingSet))\n\n# print valid und training datasets\nprint(\"Data set:\")\nfor input, target in ds:\n print (input, target)\n\n# print(\"\\nTraining set:\")\n# for input, target in trainingSet:\n# print (input, target)\n\n\nnetwork = buildNetwork(2, 3, 1, bias=True, hiddenclass=SigmoidLayer)\n#Метод стохастического градиента learningrate - чем меньше, тем медленне сходится\ntrainer = BackpropTrainer(network, ds, learningrate=0.5)\n\n#trainer.setData(trainingSet)\n#trainer.train()\n# print ('0 XOR 0:',network.activate([0,0]))\n# print ('1 XOR 0:',network.activate([1,0]))\n# print ('0 XOR 0:',network.activate([0,1]))\n# print ('1 XOR 1:',network.activate([1,1]))\n\ntrainer.trainUntilConvergence(verbose=None,\n trainingData=trainingSet,\n validationData=ds,\n continueEpochs=5)\n# print results for tests\n\nerr = trainer.trainingErrors\nerrVal = trainer.validationErrors\nepochs = []\nfor i in range(trainer.totalepochs):\n epochs.append(i)\n\nprint (\"epochs:\", trainer.totalepochs)\nprint (\"validation errors:\", trainer.validationErrors)\nprint (\"training errors:\", trainer.trainingErrors)\nprint ('0 XOR 0:',network.activate([0,0]))\nprint ('1 XOR 0:',network.activate([1,0]))\nprint ('0 XOR 0:',network.activate([0,1]))\nprint ('1 XOR 1:',network.activate([1,1]))\n\n# graphic rusults\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nplot1 = plt.plot(epochs, err)\n\n# add one\nepochs.append(trainer.totalepochs)\nplot2 = plt.plot(epochs, errVal)\n\nplt.xlabel(u'epochs')\nplt.ylabel(u'errors')\ngrid1 = plt.grid(True)\n\nplt.show()\n","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"204024119","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\n\nimport odrive\nfrom odrive.enums import * # a checker\nimport time\nfrom math import *\n\nclass Param:\n def __init__(self):\n print(\"finding an odrive...\")\n self.odrv0 = odrive.find_any()\n print('Odrive found ! ')\n\n def config(self):\n # 40Amp max dans le moteur (gros couple et sécurité pour pas fumer le moteur)\n self.odrv0.axis0.motor.config.current_lim = 10\n self.odrv0.axis1.motor.config.current_lim = 10\n\n # vmax en tick/s les encodeurs font 8192 tick/tours\n # controller.*.vel_limite prend le pas sur trap_traj.*.vel_limt\n self.odrv0.axis0.controller.config.vel_limit = 5000\n self.odrv0.axis1.controller.config.vel_limit = 5000\n\n # trap_traj parametrage des valeurs limit du comportement dynamique\n self.odrv0.axis1.trap_traj.config.vel_limit = 3000\n self.odrv0.axis0.trap_traj.config.vel_limit = 3000\n\n self.odrv0.axis0.trap_traj.config.accel_limit = 1000\n self.odrv0.axis1.trap_traj.config.accel_limit = 1000\n\n self.odrv0.axis0.trap_traj.config.decel_limit = 1000\n self.odrv0.axis1.trap_traj.config.decel_limit = 1000\n\n # test avec calib_saved.py\n # self.odrv0.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\n # self.odrv0.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\n\n def calib(self):\n # Fonction de calibration sans condition\n\n # Lance la calibration moteur si pas déjà faite\n print(\"starting calibration...\")\n self.odrv0.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE\n self.odrv0.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE\n\n while self.odrv0.axis0.current_state != 1 and self.odrv0.axis1.current_state != 1:\n time.sleep(0.1)\n\n # Met les moteurs en boucle fermée\n self.odrv0.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\n self.odrv0.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL\n\n def unlock_wheels(self):\n # AXIS_STATE_IDLE , libère le moteur : boucle ouverte\n self.odrv0.axis0.requested_state = AXIS_STATE_IDLE\n self.odrv0.axis1.requested_state = AXIS_STATE_IDLE\n\n def current_control(self):\n target = 81920\n # valeur (A) avant glissement des roues\n seuil = 1\n # self.odrv0.axis0.config.control_mode = CTRL_MODE_CURRENT_CONTROL\n self.odrv0.axis0.controller.move_to_pos(target)\n self.odrv0.axis1.controller.move_to_pos(-target)\n while self.odrv0.axis0.encoder.pos_estimate < target:\n print(self.odrv0.axis0.motor.current_control.Iq_measured)\n if abs(self.odrv0.axis0.motor.current_control.Iq_measured) >= seuil and abs(self.odrv0.axis1.motor.current_control.Iq_measured) >= seuil:\n print(\"Robot en butée\")\n self.odrv0.axis0.controller.set_vel_setpoint(0, 0)\n self.odrv0.axis1.controller.set_vel_setpoint(0, 0)\n time.sleep(0.1)\n return\n\n\ndef test():\n param = Param()\n param.config()\n param.calib()\n param.current_control()\n\n\nif __name__ == '__main__':\n # Pour ne pas lancer l'expérience : 'python3 main.py False ___'\n # Pour lancer l'homologation par Mat : 'python3 main.py ___ True\n Param.test()\n","sub_path":"Movement/current_control.py","file_name":"current_control.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"486539420","text":"'''\nCreated on 28-Jul-2015\n\n@author: ansh\n'''\nimport sys\ndef decrypt(raw_code):\n# Assume 'a' is at 0 and 'z' at 25\n atoz_indexing = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i': 8,'j': 9,'k': 10,'l': 11,'m': 12,'n': 13,'o': 14,'p': 15,'q': 16,'r': 17,'s': 18,'t': 19,'u': 20,'v': 21,'w': 22,'x': 23,'y': 24,'z': 25}\n atoz = 'abcdefghijklmnopqrstuvwxyz'\n decrypted_code=''\n for i in raw_code:\n i = i.lower()\n # If character is an alphabet, then decrypt it\n if i in atoz_indexing:\n # Each corresponding character has an index difference of 3.\n # Check for upper case\n if i.isupper():\n decrypted_code += atoz[atoz_indexing[i]-3].upper()\n # For lower case\n else:\n decrypted_code += atoz[atoz_indexing[i]-3]\n # If character is not an alphabet, then just attach it to resulting string\n else:\n decrypted_code += i\n \n return decrypted_code\n\n\n#Can't use raw_input() as it will take only first line as input others are ignored.\nraw_code=sys.stdin.read()\nprint(decrypt(raw_code))","sub_path":"predict_pattern.py","file_name":"predict_pattern.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"443212253","text":"import scipy\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as stats\n\ndef SWEEPOperator(pDim, inputM, tol):\n # pDim: dimension of matrix inputM, integer greater than one\n # inputM: a square and symmetric matrix, numpy array\n # tol: singularity tolerance, positive real\n\n aliasParam = []\n nonAliasParam = []\n \n A = np.copy(inputM)\n diagA = np.diagonal(inputM)\n\n for k in range(pDim):\n Akk = A[k,k]\n if (Akk >= (tol * diagA[k])):\n nonAliasParam.append(k)\n ANext = A - np.outer(A[:, k], A[k, :]) / Akk\n ANext[:, k] = A[:, k] / Akk\n ANext[k, :] = ANext[:, k]\n ANext[k, k] = -1.0 / Akk\n else:\n aliasParam.append(k)\n ANext[:, k] = 0.0 * A[:, k]\n ANext[k, :] = ANext[:, k]\n A = ANext\n return (A, aliasParam, nonAliasParam)\n\n# A function that find the non-aliased columns, fit a logistic model, and return the full parameter estimates\ndef build_mnlogit(fullX, y):\n\n # Find the non-redundant columns in the design matrix fullX\n nFullParam = fullX.shape[1]\n XtX = np.transpose(fullX).dot(fullX)\n invXtX, aliasParam, nonAliasParam = SWEEPOperator(pDim = nFullParam, inputM = XtX, tol = 1e-7)\n\n # Build a multinomial logistic model\n X = fullX.iloc[:, list(nonAliasParam)]\n logit = stats.MNLogit(y, X)\n thisFit = logit.fit(method = 'newton', maxiter = 1000, gtol = 1e-6, full_output = True, disp = True)\n thisParameter = thisFit.params\n thisLLK = logit.loglike(thisParameter.values)\n\n # The number of free parameters\n nYCat = thisFit.J\n thisDF = len(nonAliasParam) * (nYCat - 1)\n\n # Return model statistics\n return (thisLLK, thisDF, thisParameter, thisFit)\n\n\ncredit = pd.read_csv('Q11.csv').dropna()\n\n# create dummy indicators for the categorical input features\n# Reorder the categories in ascending order of frequencies, and then Create dummy indicators xCat = []\ncatName = ['ActiveLifestyle','Gender','MaritalStatus','Retired']\nxCat = []\nfor thisName in catName:\n catFreq = credit[thisName].value_counts() \n catFreq = catFreq.sort_values(ascending = True) \n newCat = catFreq.index\n u = credit[thisName].astype('category') \n xCat.append(pd.get_dummies(u.cat.reorder_categories(newCat))) \n\n# Reorder the categories in descending order of frequencies of the target field\ncatFreq = credit['CreditCard'].value_counts()\ncatFreq = catFreq.sort_values(ascending = False)\nnewCat = catFreq.index\nu = credit['CreditCard'].astype('category')\ny = u.cat.reorder_categories(newCat)\n\nchi_dict = {}\n\n# Model 0: Intercept only model \nu = y.isnull()\ndesignX = pd.DataFrame(u.where(u, 1)).rename(columns = {'CreditCard': 'const'}) \nLLK0, DF0, fullParams0, thisFit = build_mnlogit(designX, y)\nprint('\\nModel 0 = Intercept\\n')\n\n# Model 1: Intercept + ?\nfirst_model = ['ActiveLifestyle','Gender','MaritalStatus','Retired']\nfor r in range(4):\n trainData = xCat[r].dropna()\n trainData = stats.add_constant(trainData, prepend = True)\n LLK1, DF1, fullParams1, thisFit = build_mnlogit(trainData, y)\n testDev = 2.0 * (LLK1 - LLK0)\n testDF = DF1 - DF0\n testPValue = scipy.stats.chi2.sf(testDev, testDF)\n if testPValue < 0.01:\n chi_dict[first_model[r]] = testPValue\nkey_min = min(chi_dict.keys(), key=(lambda k: chi_dict[k]))\nprint('\\nModel 1 = Intercept +', key_min,'\\n')\n\n\n# Model 2 = Intercept + Gender + ?\nsecond_model = [('Gender','ActiveLifestyle'),('Gender','Gender'),('Gender','MaritalStatus'),\n ('Gender','Retired')]\nfor r in range(4):\n trainData = xCat[1]\n if r!= 1:\n trainData = trainData.join(xCat[r])\n trainData = stats.add_constant(trainData, prepend = True)\n LLK1, DF1, fullParams1, thisFit = build_mnlogit(trainData, y)\n testDev = 2.0 * (LLK1 - LLK0)\n testDF = DF1 - DF0\n testPValue = scipy.stats.chi2.sf(testDev, testDF) \n if testPValue < 0.01:\n chi_dict[second_model[r]] = testPValue\nkey_min = min(chi_dict.keys(), key=(lambda k: chi_dict[k]))\nprint('\\nModel 2 = Intercept +',' + '.join(''.join(t) for t in key_min),'\\n')\n\n# Model 3 = Intercept + Gender + Retired + ?\nthird_model = [('Gender','Retired','ActiveLifestyle'),0, ('Gender','Retired','MaritalStatus'),0]\nfor r in range(4):\n if r == 0:\n xCat[0].columns = ['Y','N']\n trainData = xCat[1]\n trainData = trainData.join(xCat[3])\n if r!= 1 and r!=3:\n trainData = trainData.join(xCat[r])\n trainData = stats.add_constant(trainData, prepend = True)\n LLK1, DF1, fullParams1, thisFit = build_mnlogit(trainData, y)\n testDev = 2.0 * (LLK1 - LLK0)\n testDF = DF1 - DF0\n testPValue = scipy.stats.chi2.sf(testDev, testDF) \n if testPValue < 0.01:\n chi_dict[third_model[r]] = testPValue\nkey_min = min(chi_dict.keys(), key=(lambda k: chi_dict[k]))\nprint('\\nModel 3 = Intercept +',' + '.join(''.join(t) for t in key_min),'\\n')\n\n# Model 4 = Intercept + Gender + Retired + MaritalStatus\nfourth_model = [('Gender','Retired','MaritalStatus','ActiveLifestyle')]\n\nxCat[0].columns = ['Y','N']\ntrainData = xCat[1]\ntrainData = trainData.join(xCat[3])\ntrainData = trainData.join(xCat[2])\ntrainData = trainData.join(xCat[0])\ntrainData = stats.add_constant(trainData, prepend=True)\nLLK1, DF1, fullParams1, thisFit = build_mnlogit(trainData, y)\ntestDev = 2.0 * (LLK1 - LLK0)\ntestDF = DF1 - DF0\ntestPValue = scipy.stats.chi2.sf(testDev, testDF)\nif testPValue < 0.01:\n chi_dict[fourth_model[0]] = testPValue\nkey_min = min(chi_dict.keys(), key=(lambda k: chi_dict[k]))\nprint('\\nModel 4 = Intercept +',' + '.join(''.join(t) for t in key_min),'\\n')\n\nprint('the last feature that enters into the model is ActiveLifestyle')\n\n\n","sub_path":"Final Exam/Discord/Question_11.py","file_name":"Question_11.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541962872","text":"#\n# @lc app=leetcode.cn id=45 lang=python3\n#\n# [45] 跳跃游戏 II\n#\n\n# @lc code=start\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n reach, end, count = 0, 0, 0\n for i in range(len(nums) - 1):\n if i <= reach:\n reach = max(reach, nums[i] + i)\n if i == end:\n end =reach\n count += 1\n\n return count","sub_path":"Week_04/45.跳跃游戏-ii.py","file_name":"45.跳跃游戏-ii.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"143535215","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom trajectory_base import TrajectoryPlot, PiecewisePolynomial\n\n\nclass CubicPolynomial(TrajectoryPlot):\n def __init__(self, x0=None, dx0=None, x1=None, dx1=None, deltaT=None):\n if x0 is not None:\n self.x0 = x0\n self.dx0 = dx0\n self.x1 = x1\n self.dx1 = dx1\n self.deltaT = deltaT\n self.calcCoeff()\n\n def __repr__(self):\n return \"\".format(\n self.x0, self.dx0, self.x1, self.dx1, self.deltaT)\n\n def calcCoeff(self):\n a0 = self.x0\n a1 = self.dx0\n a2 = - (3 * (self.x0 - self.x1) + self.deltaT * (2 * self.dx0 + self.dx1)) \\\n / (self.deltaT * self.deltaT)\n a3 = (2 * (self.x0 - self.x1) + self.deltaT * (self.dx0 + self.dx1)) \\\n / (self.deltaT * self.deltaT * self.deltaT)\n self.param = np.array([a0, a1, a2, a3])\n\n def setStartConstValue(self, value=0.):\n self.x0 = value\n self.dx0 = 0\n\n def setEndConstValue(self, value=0.):\n self.x1 = value\n self.dx1 = 0.\n\n def setConstValue(self, value=0.):\n self.setStartConstValue(value)\n self.setEndConstValue(value)\n\n def setStartConstDerivative(self, derivative=0.):\n self.dx0 = derivative\n\n def setEndConstDerivative(self, derivative=0.):\n self.dx1 = derivative\n\n def setConstDerivative(self, derivative=0.):\n self.setStartConstDerivative(derivative)\n self.setEndConstDerivative(derivative)\n\n def getValue(self, t):\n t_powered = np.array([1, t, t*t, t*t*t])\n return np.dot(self.param, t_powered)\n\n def getDerivative(self, t):\n derived_t_powered = np.array([1, 2*t, 3*t*t])\n return np.dot(self.param[1:], derived_t_powered)\n\n def getDerivative2(self, t):\n derived_t_powered = np.array([2, 6*t])\n return np.dot(self.param[2:], derived_t_powered)\n\n def plot(self, **kwargs):\n super(CubicPolynomial, self).plot(end_time=self.deltaT, **kwargs)\n plt.pause(0.01)\n\n\nclass EefTrajectory(PiecewisePolynomial):\n def __init__(self, nswitch):\n self.nswitch = nswitch\n self.ndeltaT = 6\n self.final_ndeltaT = 3\n self.deltaTs_dim = self.ndeltaT * self.nswitch + self.final_ndeltaT\n self.poly_list = [CubicPolynomial() for i in range(self.deltaTs_dim)]\n\n def isSupportPhase(self, t):\n return self.getIdxFromTime(t)[0] % self.ndeltaT < self.ndeltaT // 2\n\n def plot(self, **kwargs):\n super(EefTrajectory, self).plot(ndivide=300*self.nswitch, **kwargs)\n plt.sca(self.fig.get_axes()[0])\n time = 0.\n for i in range(self.nswitch):\n start_time = time\n for j in range(self.ndeltaT):\n time += self.poly_list[i*self.ndeltaT+j].deltaT\n if j == 2:\n plt.axvspan(start_time, time, facecolor=\"gray\", alpha=0.3)\n start_time = time\n for i in range(self.final_ndeltaT):\n time += self.poly_list[-1-i].deltaT\n plt.axvspan(start_time, time, facecolor=\"gray\", alpha=0.3)\n plt.pause(0.01)\n\n\nclass EefForceTrajectory(EefTrajectory):\n def __init__(self, **kwargs):\n super(EefForceTrajectory, self).__init__(**kwargs)\n self.nparam = 4\n self.final_nparam = self.final_ndeltaT * 2 - 1\n self.param_dim = self.nparam * self.nswitch + self.final_nparam\n self.presetFixedParam()\n\n def __repr__(self):\n return \"\".format(self.nswitch)\n\n def presetFixedParam(self):\n # set value and derivative\n for i in range(self.nswitch):\n self.poly_list[self.ndeltaT*i+0].setStartConstValue()\n self.poly_list[self.ndeltaT*i+2].setEndConstValue()\n self.poly_list[self.ndeltaT*i+3].setConstValue()\n self.poly_list[self.ndeltaT*i+4].setConstValue()\n self.poly_list[self.ndeltaT*i+5].setConstValue()\n # set final value and derivative\n self.poly_list[-self.final_ndeltaT].setStartConstValue()\n self.poly_list[-1].setEndConstDerivative()\n\n def setParam(self, param, deltaTs):\n # param (dim: 4 * nswitch):\n # for each phase of swing and support:\n # [dim:1] 1st f in support phase\n # [dim:1] 1st df in support phase\n # [dim:1] 2nd f in support phase\n # [dim:1] 2nd df in support phase\n # deltaTs (dim: 6 * nswitch):\n # [dim:3] deltaT in support phase\n # [dim:3] deltaT in swing phase\n assert len(param) == self.param_dim\n assert len(deltaTs) == self.deltaTs_dim\n assert np.issubdtype(param.dtype, np.floating)\n assert np.issubdtype(deltaTs.dtype, np.floating)\n # set value and derivative\n for i in range(self.nswitch):\n param_i = param[i*self.nparam:(i+1)*self.nparam]\n poly_list_i = self.poly_list[i*self.ndeltaT:(i+1)*self.ndeltaT]\n poly_list_i[0].x1 = poly_list_i[1].x0 = param_i[0]\n poly_list_i[0].dx1 = poly_list_i[1].dx0 = param_i[1]\n poly_list_i[1].x1 = poly_list_i[2].x0 = param_i[2]\n poly_list_i[1].dx1 = poly_list_i[2].dx0 = param_i[3]\n # set final value and derivative\n for i in range(self.final_ndeltaT-1):\n self.poly_list[self.ndeltaT*self.nswitch+i].x1 \\\n = self.poly_list[self.ndeltaT*self.nswitch+i+1].x0 \\\n = param[self.nswitch*self.nparam+2*i]\n self.poly_list[self.ndeltaT*self.nswitch+i].dx1 \\\n = self.poly_list[self.ndeltaT*self.nswitch+i+1].dx0 \\\n = param[self.nswitch*self.nparam+2*i+1]\n self.poly_list[-1].x1 = param[-1]\n # set delta time\n for poly, deltaT in zip(self.poly_list, deltaTs):\n poly.deltaT = deltaT\n # calc coeff\n for poly in self.poly_list:\n poly.calcCoeff()\n\n\nclass EefPositionTrajectory(EefTrajectory):\n def __init__(self, initial_pos=0., vertical_fix=False, **kwargs):\n self.vertical_fix = vertical_fix\n super(EefPositionTrajectory, self).__init__(**kwargs)\n if self.vertical_fix:\n self.nparam = 4\n else:\n self.nparam = 5\n self.final_nparam = 0\n self.param_dim = self.nparam * self.nswitch + self.final_nparam\n self.presetFixedParam(initial_pos)\n\n def __repr__(self):\n return \"\".format(self.nswitch)\n\n def presetFixedParam(self, initial_pos):\n # the position of first support phase is given\n self.poly_list[0].setConstValue(value=initial_pos)\n self.poly_list[1].setConstValue(value=initial_pos)\n self.poly_list[2].setConstValue(value=initial_pos)\n self.poly_list[3].setStartConstValue(value=initial_pos)\n # set value and derivative\n for i in range(self.nswitch):\n if self.vertical_fix:\n self.poly_list[self.ndeltaT*i+0].setConstValue()\n self.poly_list[self.ndeltaT*i+1].setConstValue()\n self.poly_list[self.ndeltaT*i+2].setConstValue()\n self.poly_list[self.ndeltaT*i+3].setStartConstValue()\n self.poly_list[self.ndeltaT*i+5].setEndConstValue()\n else:\n self.poly_list[self.ndeltaT*i+0].setConstDerivative()\n self.poly_list[self.ndeltaT*i+1].setConstDerivative()\n self.poly_list[self.ndeltaT*i+2].setConstDerivative()\n self.poly_list[self.ndeltaT*i+3].setStartConstDerivative()\n self.poly_list[self.ndeltaT*i+5].setEndConstDerivative()\n # set final value and derivative\n for i in range(self.final_ndeltaT):\n if self.vertical_fix:\n self.poly_list[-i-1].setConstValue()\n else:\n self.poly_list[-i-1].setConstDerivative()\n\n def setParam(self, param, deltaTs):\n # param (dim: 5 * nswitch):\n # for each phase of swing and support:\n # [dim:1] 1st p in swing phase\n # [dim:1] 1st dp in swing phase\n # [dim:1] 2nd p in swing phase\n # [dim:1] 2nd dp in swing phase\n # [dim:1] 3rd p in swing phase (= next support phase)\n # (only when vertical_fix is False)\n # deltaTs (dim: 6 * nswitch):\n # [dim:3] deltaT in support phase\n # [dim:3] deltaT in swing phase\n assert len(param) == self.param_dim\n assert len(deltaTs) == self.deltaTs_dim\n assert np.issubdtype(param.dtype, np.floating)\n assert np.issubdtype(deltaTs.dtype, np.floating)\n # set value and derivative\n for i in range(self.nswitch):\n param_i = param[i*self.nparam:(i+1)*self.nparam]\n poly_list_i = self.poly_list[i*self.ndeltaT:(i+1)*self.ndeltaT]\n if (not self.vertical_fix) and (i > 0):\n poly_list_i[0].x0 \\\n = poly_list_i[0].x1 \\\n = poly_list_i[1].x0 \\\n = poly_list_i[1].x1 \\\n = poly_list_i[2].x0 \\\n = poly_list_i[2].x1 \\\n = poly_list_i[3].x0 \\\n = param[i*self.nparam-1]\n poly_list_i[3].x1 = poly_list_i[4].x0 = param_i[0]\n poly_list_i[3].dx1 = poly_list_i[4].dx0 = param_i[1]\n poly_list_i[4].x1 = poly_list_i[5].x0 = param_i[2]\n poly_list_i[4].dx1 = poly_list_i[5].dx0 = param_i[3]\n if not self.vertical_fix:\n poly_list_i[5].x1 = param_i[4]\n # set final value and derivative\n if not self.vertical_fix:\n for i in range(self.final_ndeltaT):\n self.poly_list[-i-1].x0 \\\n = self.poly_list[-i-1].x1 \\\n = param[-1]\n # set delta time\n for poly, deltaT in zip(self.poly_list, deltaTs):\n poly.deltaT = deltaT\n # calc coeff\n for poly in self.poly_list:\n poly.calcCoeff()\n\n\nif __name__ == '__main__':\n cp = CubicPolynomial(-1., 0., 3., -10., 4.)\n cp.plot(window_title=\"CubicPolynomial\")\n\n deltaTs = np.array([2, 2, 2, 2, 2, 5,\n 4, 3, 5, 4, 5, 6,\n 4, 2, 3],\n dtype=np.float32)\n\n force_traj = EefForceTrajectory(nswitch=2)\n force_traj.setParam(np.array([10, 1, 5, -1,\n 6, -1, 4, 3,\n 2, 3, 4, 5, 6],\n dtype=np.float32),\n deltaTs)\n force_traj.plot(window_title=\"EefForceTrajectory\", plot_tangent=True)\n\n pos_traj = EefPositionTrajectory(nswitch=2)\n pos_traj.setParam(np.array([10, -2, 5, 0, 12,\n 10, -2, 5, 10, -4],\n dtype=np.float32),\n deltaTs)\n pos_traj.plot(window_title=\"EefPositionTrajectory\", plot_tangent=True)\n\n pos_traj = EefPositionTrajectory(vertical_fix=True, nswitch=2)\n pos_traj.setParam(np.array([10, -2, 5, 0,\n 10, -2, 5, 10],\n dtype=np.float32),\n deltaTs)\n pos_traj.plot(window_title=\"EefPositionTrajectory (vertical_fix)\", plot_tangent=True)\n","sub_path":"control/winkler-ral2018/eef_trajectory.py","file_name":"eef_trajectory.py","file_ext":"py","file_size_in_byte":11330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"96609719","text":"\nfrom gym.spaces import Discrete\nfrom open_spiel.python.rl_environment import TimeStep, StepType\n\nfrom abmarl.sim.agent_based_simulation import Agent\nfrom abmarl.managers import TurnBasedManager, SimulationManager\n\n\nclass OpenSpielWrapper:\n \"\"\"\n Enable connection between Abmarl's SimulationManager and OpenSpiel agents.\n\n OpenSpiel support turn-based and simultaneous simulations, which Abmarl provides\n through the TurnBasedManager and AllStepManager. OpenSpiel expects TimeStep\n objects as output, which include the observations, rewards, and step type.\n Among the observations, it expects a list of legal actions available to the agent.\n The OpenSpielWrapper converts output from the simulation manager to the expected\n format. Furthermore, OpenSpiel provides actions as a list. The OpenSpielWrapper converts\n those actions to a dict before forwarding it to the underlying simulation manager.\n\n OpenSpiel does not support the ability for some agents in a simulation to finish\n before others. The simulation is either ongoing, in which all agents are providing\n actions, or else it is done for all agents. In contrast, Abmarl allows some agents to be\n done before others as the simulation progresses. Abmarl expects that done\n agents will not provide actions. OpenSpiel, however, will always provide actions\n for all agents. The OpenSpielWrapper removes the actions from agents that are\n already done before forwarding the action to the underlying simulation manager.\n Furthermore, OpenSpiel expects every agent to be present in the TimeStep outputs.\n Normally, Abmarl will not provide output for agents that are done since they\n have finished generating data in the episode. In order to work with OpenSpiel,\n the OpenSpielWrapper forces output from all agents at every step, including\n those already done.\n\n Currently, the OpenSpielWrapper only works with simulations in which the action and\n observation space of every agent is Discrete. Most simulations will need to\n be wrapped with the RavelDiscreteWrapper.\n \"\"\"\n def __init__(self, sim, discounts=1.0, **kwargs):\n assert isinstance(sim, SimulationManager)\n\n # We keep track of the learning agents separately so that we can append\n # observations and rewards for each of these agents. OpenSpiel expects\n # them to all be present in every time_step.\n self._learning_agents = {\n agent.id: agent for agent in sim.agents.values() if isinstance(agent, Agent)\n }\n\n # The wrapper assumes that each space is discrete, so we check for that.\n for agent in self._learning_agents.values():\n assert isinstance(agent.observation_space, Discrete) and \\\n isinstance(agent.action_space, Discrete), \\\n \"OpenSpielWrapper can only work with simulations that have all Discrete spaces.\"\n self.sim = sim\n\n self.discounts = discounts\n self._should_reset = True\n\n @property\n def discounts(self):\n \"\"\"\n The learing discounts for each agent.\n\n If provided as a number, then that value wil apply to all the agents.\n Make seperate discounts for each agent by providing a dictionary assigning\n each agent to its own discounted value.\n \"\"\"\n return self._discounts\n\n @discounts.setter\n def discounts(self, value):\n assert type(value) in (int, float, dict), \\\n \"The discounts must be either a number or a dict.\"\n if type(value) in (float, int):\n self._discounts = {\n agent_id: value for agent_id in self._learning_agents\n }\n else: # type(value) == dict\n for discount_id, discount in value.items():\n assert discount_id in self._learning_agents, \\\n \"id for the discount must be an agent id.\"\n assert type(discount) in (float, int), \\\n \"discount values must be a number.\"\n assert all([\n True if agent_id in value.keys() else False for agent_id in self._learning_agents\n ]), \"All agents must be given a discount.\"\n self._discounts = value\n\n @property\n def num_players(self):\n \"\"\"\n The number of learning agents in the simulation.\n \"\"\"\n return sum([1 for _ in self._learning_agents])\n\n @property\n def is_turn_based(self):\n \"\"\"\n TurnBasedManager.\n \"\"\"\n return isinstance(self.sim, TurnBasedManager)\n\n @property\n def current_player(self):\n \"\"\"\n The agent that currently provides the action.\n\n Current player is used in the observation part of the TimeStep output. If it\n is a turn based simulation, then the current player is the single agent who\n is providing an action. If it is a simultaneous simulation, then OpenSpiel does\n not use this property and the current player is just the first agent\n in the list of agents in the simulation.\n \"\"\"\n return self._current_player\n\n @current_player.setter\n def current_player(self, value):\n assert value in self._learning_agents, \"Current player must be an agent in the simulation.\"\n self._current_player = value\n\n def reset(self, **kwargs):\n \"\"\"\n Reset the simulation.\n\n Return:\n TimeStep object containing the initial observations. Uniquely at reset,\n the rewards and discounts are None and the step type is StepType.FIRST.\n \"\"\"\n self._should_reset = False\n obs = self.sim.reset(**kwargs)\n self.current_player = next(iter(obs))\n\n observations = {\n \"info_state\": self._append_obs(obs),\n \"legal_actions\": self._get_all_legal_actions(),\n \"current_player\": self.current_player,\n }\n\n return TimeStep(\n observations=observations,\n rewards=None,\n discounts=None,\n step_type=StepType.FIRST\n )\n\n def step(self, action_list, **kwargs):\n \"\"\"\n Step the simulation forward using the reported actions.\n\n OpenSpiel provides an action list of either (1) the agent whose turn it\n is in a turn-based simulation or (2) all the agents in a simultaneous simulation. The\n OpenSpielWrapper converts the list of actions to a dictionary before passing\n it to the underlying simulation.\n\n OpenSpiel does not support the ability for some agents of a simulation to finish\n before others. As such, it may provide actions for agents that are already\n done. To work with Abmarl, the OpenSpielWrapper removes actions for agents that\n are already done.\n\n Args:\n action_list: list of actions for the agents.\n\n Returns:\n TimeStep object containing the observations of the new state, the rewards,\n and StepType.MID if the simulation is still progressing, otherwise\n StepType.LAST.\n\n \"\"\"\n if self._should_reset:\n return self.reset(**kwargs)\n\n # Actions come in as a list, so we need to convert to a dict before forwarding\n # to the SimulationManager.\n if self.is_turn_based:\n action_dict = {self.current_player: action_list[0]}\n else:\n assert len(action_list) == len(self._learning_agents), \\\n \"The number of actions must match the number of learning agents \" + \\\n \"in a simultaneous simulation.\"\n action_dict = {\n agent_id: action_list[i]\n for i, agent_id in enumerate(self._learning_agents)\n }\n # OpenSpiel can send actions for agents that are already done, which doesn't\n # work with our simulation managers. So we filter out these actions before\n # passing them to the manager.\n for agent_id in self.sim.done_agents:\n try:\n del action_dict[agent_id]\n except KeyError:\n pass\n # We have just deleted actions for agents that are already done, which\n # can result in an empty action dictionary (e.g. in a turn-based simulation).\n # In this case, we just take a fake step.\n if not action_dict: # No actions\n return self._take_fake_step()\n\n obs, reward, done, info = self.sim.step(action_dict, **kwargs)\n self.current_player = next(iter(obs))\n\n step_type = StepType.LAST if done['__all__'] else StepType.MID\n self._should_reset = step_type == StepType.LAST\n\n observations = {\n \"info_state\": self._append_obs(obs),\n \"legal_actions\": self._get_all_legal_actions(),\n \"current_player\": self.current_player,\n }\n\n return TimeStep(\n observations=observations,\n rewards=self._append_reward(reward),\n discounts=self._discounts,\n step_type=step_type\n )\n\n def observation_spec(self):\n \"\"\"\n The agents' observations spaces.\n\n Abmarl uses gym spaces for the observation space. The OpenSpielWrapper converts\n the gym space into a format that OpenSpiel expects.\n \"\"\"\n return {\n agent.id: {\n 'info_state': (agent.observation_space.n,),\n 'legal_actions': (agent.action_space.n,),\n 'current_player': ()\n } for agent in self._learning_agents.values()\n }\n\n def action_spec(self):\n \"\"\"\n The agents' action spaces.\n\n Abmarl uses gym spaces for the action space. The OpenSpielWrapper converts\n the gym space into a format that OpenSpiel expects.\n \"\"\"\n return {\n agent.id: {\n 'num_actions': agent.action_space.n,\n 'min': 0,\n 'max': agent.action_space.n - 1,\n 'dtype': int\n } for agent in self._learning_agents.values()\n }\n\n def get_legal_actions(self, agent_id):\n \"\"\"\n Return the legal actions available to the agent.\n\n By default, the OpenSpielWrapper uses the agent's entire action space\n as its legal actions in each time step. This function can be overwritten in a derived class\n to add logic for obtaining the actual legal actions available.\n \"\"\"\n return [*range(self._learning_agents[agent_id].action_space.n)]\n\n def _append_obs(self, obs):\n # OpenSpiel expects every agent to appear in the observation at every\n # time step. The simulation manager won't produce an observation for a\n # done agent, so we have to add it ourselves.\n for agent_id in self._learning_agents:\n if agent_id not in obs:\n obs[agent_id] = self.sim.sim.get_obs(agent_id)\n return obs\n\n def _append_reward(self, reward):\n # OpenSpiel expects every agent to appear in the reward at every\n # time step. The simulation manager won't produce a reward for a\n # done agent, so we have to add it ourselves.\n for agent_id in self._learning_agents:\n if agent_id not in reward:\n reward[agent_id] = 0\n return reward\n\n def _get_all_legal_actions(self):\n # Shorcut function for getting all the legal actions\n return {\n agent_id: self.get_legal_actions(agent_id)\n for agent_id in self._learning_agents\n }\n\n def _take_fake_step(self):\n # This is used when all the actions are from done agents. In that case,\n # we just move along with no state update.\n obs = self._append_obs({})\n self.current_player = next(iter(obs))\n observations = {\n \"info_state\": obs,\n \"legal_actions\": self._get_all_legal_actions(),\n \"current_player\": self.current_player,\n }\n return TimeStep(\n observations=observations,\n rewards=self._append_reward({}),\n discounts=self._discounts,\n step_type=StepType.MID\n )\n","sub_path":"abmarl/external/open_spiel_env_wrapper.py","file_name":"open_spiel_env_wrapper.py","file_ext":"py","file_size_in_byte":12105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"420935334","text":"from django.conf.urls import url\nfrom easyblog import views\n\nurlpatterns = [\n # url(r'^$', views.IndexView.as_view(),name='index'),\n url(r'^$',views.BlogIndex,name='index'),\n url(r'^article/(?P\\d+)$', views.ArticleDetailView.as_view(),name='detail'),\n url(r'^category/(?P\\d+)$', views.CategoryView.as_view(), name='category'),\n url(r'^tags/(?P\\d+)$',views.TagView.as_view(),name='tags'),\n url(r'^archive/(?P\\d+)/(?P\\d+)$',views.ArchiveView.as_view(),name='archive'),\n]\n","sub_path":"easyblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"282122845","text":"import traceback\r\n\r\nfrom discord.ext import commands\r\nimport asyncio\r\nimport aiohttp\r\n\r\nfrom bot.bot_client import Bot\r\n\r\n\r\nclass RsAtlantis(commands.Cog):\r\n\r\n def __init__(self, bot: Bot):\r\n self.bot = bot\r\n\r\n # Temporarily cancelled\r\n if self.bot.setting.mode == 'prod' and False:\r\n self.update_clans_task = self.bot.loop.create_task(self.update_all_clans())\r\n\r\n def cog_unload(self):\r\n if self.bot.setting.mode == 'prod':\r\n self.update_clans_task.cancel()\r\n\r\n @staticmethod\r\n async def update_all_clans():\r\n base_url = 'https://nriver.pythonanywhere.com'\r\n while True:\r\n try:\r\n async with aiohttp.ClientSession() as cs:\r\n async with cs.get(f'{base_url}/clan/update-all/') as r:\r\n if r.status != 200:\r\n print(f'Erro ao atualizar clãs: {r.status}')\r\n else:\r\n print(f'Exp dos Clãs atualizada com sucesso.')\r\n await asyncio.sleep(60 * 5)\r\n except Exception as e:\r\n print(f'{e}: {traceback.format_exc()}')\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(RsAtlantis(bot))\r\n","sub_path":"bot/cogs/rsatlantis.py","file_name":"rsatlantis.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199818613","text":"## For logging purpose\n#!/usr/bin/python\n\nimport os\nimport sys\nimport logging\nfrom logging.handlers import TimedRotatingFileHandler\n\nclass LogAdmin(object):\n def __init__ (self, loggername, logfile):\n self.logger = logging.getLogger(loggername)\n self.logger.setLevel(logging.DEBUG)\n fileLogHandler = TimedRotatingFileHandler(logfile, 'midnight', 1, 31)\n fileLogHandler.setLevel(logging.DEBUG)\n logOutputFormat = logging.Formatter(\"%(asctime)-10s %(name)-10s %(levelname)-5s %(message)-30s\")\n fileLogHandler.setFormatter(logOutputFormat)\n self.logger.addHandler(fileLogHandler)\n \n def setLog (self, level, message):\n if level == 'DEBUG':\n self.logger.debug(message)\n elif level == 'INFO':\n self.logger.info(message)\n elif level == 'WARNING':\n self.logger.warning(message)\n elif level == 'ERROR':\n self.logger.error(message)\n elif level == 'CRITICAL':\n self.logger.critical(message)\n","sub_path":"src/lib/Logger.py","file_name":"Logger.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"220691648","text":"from time import time\n\n# start the timer\nstart = time()\n\npublic_key = int(input(\"enter any number as your public key: \"))\n\n\n# store the discovered factors in a list\nfactors = []\n\n# Begin testing at 2\ntest_number = 2\n\n# loop through all numbers from 2 up until the one below the you are testing\nwhile test_number < public_key:\n\n # if the public key divides exactly into the test_number, it is a factor\n if public_key % test_number == 0:\n\n # add this factor to the list\n factors.append(test_number)\n\n # move on to the next test number\n test_number += 1\nend = time()\ntotal = end - start\nprint(str(total) + \"seconds\")\nprint(factors)\n \n","sub_path":"finding_factors.py","file_name":"finding_factors.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582455121","text":"# calling libs\r\nimport urllib.request\r\nimport urllib.parse\r\nimport urllib.error\r\nimport re\r\nimport time\r\nimport socket\r\nimport http.client\r\nimport sys\r\nimport random\r\nimport os\r\nimport getopt\r\nimport base64\r\nimport hashlib\r\n\r\n############################################################################################################################################################################################################################################################################################################\r\n## Gnu General Public License \r\n## \r\n## [::] Author : Suicedal-Virus\r\n## [::] Facebook : https://www.facebook.com/BarmajiyatTreeZero\r\n## [::} Github : https://github.com/Suicedal-Virus\r\n## |::] Youtube : https://www.youtube.com/channel/UCRR-0urV992N8hrBBaPmzVA\r\n##\r\n############################################################################################################################################################################################################################################################################################################\r\n############################################################################################################################################################################################################################################################################################################\r\n## CLASS SCREEN ==> LOGO && HELP && CLEAR SCREEN\r\n#############\r\n\r\nclass screen () :\r\n\r\n def __init__ (self, platformUser, argumentProgram):\r\n # colors \r\n if platformUser == \"linux\" :\r\n self.Color = (\"\\033[0;30m\", \"\\033[1;30m\", \"\\033[1;31m\", \"\\033[0;32m\", \"\\033[0;33m\", \"\\033[1;33m\", \"\\033[0;34m\", \"\\033[0;35m\",\r\n \"\\033[0;36m\", \"\\033[1;36m\", \"\\033[0;37m\", \"\\033[1;37m\", \"\\033[1;34m\")\r\n else :\r\n self.Color = (\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\")\r\n\r\n self.argumentList = [\"Url=\", \"Dork=\", \"sqlInjection\",\"saveRs\", \"tcpPorts\",\"udpPorts\", \"Dir\",\"pageAdmin\",\"wp\", \"jom\",\r\n \"count=\", \"Base64Decry=\", \"Base64Encry=\", \"md5Encry=\", \"motor=\",\"noInfo\", \"help\", \"update\"]\r\n\r\n self.dialogTxt = [\"\",\"Url\", \"Ip\", \"Query\", \"Shema\", \"Version\", \"Server-status\",\"Server\", \"Server-Ip\", \"User Agent\", \"Vulnerability sqlInjection\",\r\n \"Motor\", \"Method\"]\r\n self.scanTitle = [\"SEARCH DORK \", \"SCAN URL\", \"ENCRYPT BASE64\", \"DECRYPT BASE64\", \"FIND ADMIN PAGE\", \"MD5 ENCRYPT\",\"CHECK UPDATE\"]\r\n self.platformUser = platformUser\r\n self.argumentUser = argumentProgram\r\n self.version = \"1.2\"\r\n self.Dork , self.Url, self.Errors , self.base64Encry, self.base64Decry, self.md5Encrypt, self.motor , self.count= \"\",\"\",\"\",\"\",\"\",\"\",int(0), int(10)\r\n self.tcpPorts, self.udpPorts, self.getInfo , self.findAdmin , self.sqlFind, self.wordPress, self.joomla , self.exSqlMap, self.noInfo, self.saveResult, self.update= False, False, False, False, False, False , False, False, False , False, False\r\n pass\r\n\r\n def Logo(self) :\r\n #\r\n # Random logo for program\r\n #\r\n lRandom = random.randrange(0,4)\r\n provRandom = random.randrange(0,4)\r\n logo = [(\" __________ ________ _________\\n\"\r\n \" / / |__ __| |__ __|\\n\"\r\n \" / ________/ \\ \\ / /\\n\"\r\n \"| | \\ \\ / / \\n\"\r\n \"| | uicedal | | irus | |\\n\"\r\n \"\\ \\ -------------- | | | |\\n\"\r\n \" \\ \\______ | | | | | |\\n\"\r\n \" \\_______ \\ | | | | | |\\n\"\r\n \" | | -------------- \\ \\ / /\\n\"\r\n \" | | \\ \\ / /\\n\"\r\n \" / / \\ \\ / /\\n\"\r\n \" _______/ / | | | |\\n\"\r\n \" / / \\ \\_________/ /\\n\"\r\n \"/__________/ |_______________|\\n\"\r\n ),\r\n (\"\\t __________\\n\"\r\n \" \\t / 0 10 001 \\ \\n\"\r\n \"\\t| 110 1 0 |\\n\"\r\n \"\\t| ( 0 ) ( 0 ) |\\n\"\r\n \"\\t| 00 1 1 11 |\\n\"\r\n \"\\t| R . I . P |\\n\"\r\n \"\\t| you have been|\\n\"\r\n \"\\t|____hacked____|\\n\"\r\n \"\\t \\ a b c d e f \\ \\n\"\r\n \"\\t \\ g h i j k l \\ \\n\"\r\n \"\\t \\_____________\\ \\n\"\r\n ),\r\n (\" ___________\\n\"\r\n \"\\t|\\ |°| \\\\ / || \\ \\n\"\r\n \"\\t| -------------------| |------------***/ $$$$ |*\\n\"\r\n \"\\t| ----------------------------------***\\ $$$$ |*\\n\"\r\n \"\\t\\/ ||* || // \\_____||____/\\n\"\r\n \"\\t || ** // \\n\"\r\n \"\\t \\\\__// RPG-7\\n\"\r\n ),\r\n (\"\\t \\\\\\///\\n\"\r\n \"\\t **--------\\n\"\r\n \"\\t */ \\ \\n\"\r\n \"\\t | $$$$ |\\n\"\r\n \"\\t | |\\n\"\r\n \"\\t \\________/\\n\"\r\n )\r\n ]\r\n prov = [\"[::] keep calm and hack any thing\", \"[::] Keep calm and be Black-Hacker\",\r\n \"[::] Web site ==> K.O\", \"[::] UserName Password Found !!!\"]\r\n print(self.Color[2],\"\\tNO SYSTEM IS SAFE !!!\")\r\n print(self.Color[1],logo[lRandom],\"\\n\",self.Color[2], prov[provRandom])\r\n\r\n print(self.Color[3],\"\\n [+] usage : python 'scanner Web.py' [OPTIONS] || \",self.dialogTxt[+5],\" : \",self.version,\"\\n\")\r\n print(\" [!} Example : python 'scanner Web.py' --Dork [DORK] --wp --pageAdmin\\n\")\r\n\r\n def help(self):\r\n ##\r\n ## Help and option can use white programme\r\n ##\r\n print(self.Color[4],\" [+] Options : \\n\")\r\n print(self.Color[-1],\" --Url \",self.Color[5],\":\",self.Color[-2],\" url of web-site\")\r\n print(self.Color[-1],\" --Dork \",self.Color[5],\":\",self.Color[-2],\" Use dork \")\r\n print(self.Color[-1],\" --motor \",self.Color[5],\":\",self.Color[-2],\" Set your engine \")\r\n print(self.Color[-1],\" \",self.Color[5],\":\",self.Color[-2],\" 1 => Sogou 2=> Yandex \")\r\n print(self.Color[-1],\" \",self.Color[5],\":\",self.Color[-2],\" 3 => Google 4=> Bing 5 => Ask\")\r\n print(self.Color[-1],\" --sqlInjection \",self.Color[5],\":\",self.Color[-2],\" Scan Sql Injection vulnerability\")\r\n print(self.Color[-1],\" --noInfo \",self.Color[5],\":\",self.Color[-2],\" Don't show information web-site\")\r\n print(self.Color[-1],\" --tcpPorts \",self.Color[5],\":\",self.Color[-2],\" Scan tcp port of server \")\r\n print(self.Color[-1],\" --udpPorts \",self.Color[5],\":\",self.Color[-2],\" Scan udp port of server \")\r\n print(self.Color[-1],\" --pageAdmin \",self.Color[5],\":\",self.Color[-2],\" Find page admin \")\r\n print(self.Color[-1],\" --count \",self.Color[5],\":\",self.Color[-2],\" Number of search engine results\")\r\n print(self.Color[-1],\" --Base64Decry \",self.Color[5],\":\",self.Color[-2],\" Decrypt string to base64\")\r\n print(self.Color[-1],\" --Base64Encry \",self.Color[5],\":\",self.Color[-2],\" Encrypt string to base64\")\r\n print(self.Color[-1],\" --md5Encry \",self.Color[5],\":\",self.Color[-2],\" Encrypt string to md5\")\r\n print(self.Color[-1],\" --wp \",self.Color[5],\":\",self.Color[-2],\" Check if the web-site from Word-Press \")\r\n print(self.Color[-1],\" --jom \",self.Color[5],\":\",self.Color[-2],\" Check if the web-site from Joomla\")\r\n print(self.Color[-1],\" --update \",self.Color[5],\":\",self.Color[-2],\" Check for update\")\r\n print(self.Color[-1],\" --saveRs \",self.Color[5],\":\",self.Color[-2],\" Save results \")\r\n print(self.Color[-1],\" --help \",self.Color[5],\":\",self.Color[-2],\" Help\")\r\n print(self.Color[4],\"\\n [!] Examples : \")\r\n print(self.Color[-2],\" [+] python scannerWeb.py --Url [SITE YOU WANT SCANNING] --pageAdmin\")\r\n print(self.Color[-2],\" [+] python scannerWeb.py --Dork [YOUR DORK] --sqlInjection \")\r\n\r\n\r\n def checkArgument(self):\r\n #\r\n # Get argument used by user and if it on the list argument of the programme\r\n #\r\n try:\r\n argv = getopt.getopt(argumentuser, shortopts=\"\", longopts=self.argumentList)\r\n if argv == ([], []):\r\n self.Errors =\"\\n [!] Error : No argument found .\"\r\n except getopt.GetoptError as err:\r\n argv = [[]]\r\n self.Errors =\"\\n Error : {0}\".format(err)\r\n\r\n\r\n ########################################################################################################################################\r\n # checking argument #################################################################################################################\r\n for opt, argum in argv[0] :\r\n if opt == \"--Url\":\r\n if \"--\" in argum or argum == \"\":\r\n self.Errors = \"[!] Error : {0} require argument\".format(opt)\r\n self.Url = argum\r\n elif opt == \"--Dork\":\r\n if \"--\" in argum or argum == \"\":\r\n self.Errors = \"[!] Error : {0} require argument\".format(opt)\r\n self.Dork = argum\r\n elif opt == \"--sqlInjection\":\r\n self.sqlFind = True\r\n elif opt == \"--noInfo\":\r\n self.noInfo = True\r\n elif opt == \"--About\":\r\n self.getInfo = True\r\n elif opt == \"--pageAdmin\":\r\n self.findAdmin = True\r\n elif opt == \"--wp\":\r\n self.wordPress = True\r\n elif opt == \"--jom\":\r\n self.joomla = True\r\n elif opt == \"--count\":\r\n try:\r\n argum = int(argum)\r\n self.count = argum\r\n except ValueError:\r\n self.Errors = \"[!] Pleas use integer in option --count\"\r\n elif opt == \"--tcpPorts\":\r\n self.tcpPorts = True\r\n elif opt == \"--udpPorts\":\r\n self.udpPorts = True\r\n elif opt == \"--Base64Decry\":\r\n self.base64Decry = argum\r\n elif opt == \"--Base64Encry\":\r\n self.base64Encry = argum\r\n elif opt == \"--md5Encry\":\r\n self.md5Encrypt = argum\r\n elif opt == \"--saveRs\" :\r\n self.saveResult = True\r\n elif opt == \"--motor\":\r\n if \"--\" in argum :\r\n self.Errors = \"[!] Error : {0} require argument\".format(opt)\r\n try:\r\n argum = int(argum)\r\n self.motor = argum\r\n except ValueError:\r\n self.Errors = \"[!] Pleas use integer in option --motor\"\r\n elif opt == \"--help\":\r\n screen.help(self)\r\n sys.exit()\r\n elif opt == \"--update\":\r\n self.update = True\r\n if self.Url and self.Dork:\r\n self.Errors = \"\\n[!] You cant use options --Url and --Dork in the same time\"\r\n\r\n pass\r\n def Show(self):\r\n if self.Errors :\r\n screen.help(self)\r\n print(self.Color[2],self.Errors)\r\n print(\"\\033[0;0m\")\r\n sys.exit()\r\n pass\r\n############################################################################################################################################################################################################################################################################################################\r\n#### CLASS CONNECTION AND SEARCH DORK AND MORE FUNCTION #################################################################################################################################################################################################################################################\r\n####\r\n\r\nclass connection(screen):\r\n\r\n browserLang = [\"af\", \"am\", \"ar-SA\", \"as\", \"az-Latn\", \"be\", \"bg\", \"bn-BD\", \"bn-IN\", \"bs\", \"ca\", \"ca-ES-valencia\",\r\n \"cs\", \"da\", \"de\", \"de-DE\", \"el\", \"en-CA\", \"en-GB\", \"en-IN\", \"en-AU\", \"en-US\", \"es\", \"es-ES\", \"es-US\",\r\n \"es-MX\", \"et\", \"eu\", \"fa\", \"fi\", \"fil-Latn\", \"fr\", \"fr-FR\", \"fr-CA\", \"ga\", \"gd-Latn\", \"gl\", \"gu\",\r\n \"ha-Latn\", \"he\", \"hi\", \"hr\", \"hu\", \"hy\", \"id\", \"ig-Latn\", \"is\", \"it\", \"it-IT\", \"ja\", \"ka\", \"kk\",\r\n \"km\", \"kn\", \"ko\", \"kok\", \"ku-Arab\", \"ky-Cyrl\", \"lb\", \"lt\", \"lv\", \"mi-Latn\", \"mk\", \"ml\", \"mn-Cyrl\",\r\n \"mr\", \"ms\", \"mt\", \"nb\", \"ne\", \"nl\", \"nl-BE\", \"nn\", \"nso\", \"or\", \"pa\", \"pa-Arab\", \"pl\", \"prs-Arab\",\r\n \"pt-BR\", \"pt-PT\", \"qut-Latn\", \"quz\", \"ro\", \"ru\", \"rw\", \"sd-Arab\", \"si\", \"sk\", \"sl\", \"sq\",\r\n \"sr-Cyrl-BA\", \"sr-Cyrl-RS\", \"sr-Latn-RS\", \"sv\", \"sw\", \"ta\", \"te\", \"tg-Cyrl\", \"th\", \"ti\", \"tk-Latn\",\r\n \"tn\", \"tr\", \"tt-Cyrl\", \"ug-Arab\", \"uk\", \"ur\", \"uz-Latn\", \"vi\", \"zh-Hans\", \"zh-Hant\", \"zu\"]\r\n browserLang = random.choice(browserLang)\r\n userAgents = ['Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.10) Gecko/2009042513 Ubuntu/8.04 (hardy) Firefox/3.0.10',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.10) Gecko/2009042523 Ubuntu/8.10 (intrepid) Firefox/3.0.10',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.11) Gecko/2009060214 Firefox/3.0.11',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.11) Gecko/2009060308 Ubuntu/9.04 (jaunty) Firefox/3.0.11 GTB5',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.11) Gecko/2009060309 Firefox/3.0.11',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.13) Gecko/2009080316 Ubuntu/8.04 (hardy) Firefox/3.0.13',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.18) Gecko/2010021501 Ubuntu/9.04 (jaunty) Firefox/3.0.18',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.19) Gecko/2010040118 Ubuntu/8.10 (intrepid) Firefox/3.0.19 GTB7.1',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.0.2) Gecko/2008092313 Ubuntu/8.04 (hardy) Firefox/3.0.2', 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.1.15) Gecko/20101027 Fedora/3.5.15-1.fc12 Firefox/3.5.15',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 GTB5', 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.1.6) Gecko/20091215 Ubuntu/9.10 (karmic) Firefox/3.5.6 GTB6',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.2.11) Gecko/20101013 Ubuntu/10.10 (maverick) Firefox/3.6.10',\r\n 'Mozilla/5.0 (X11; U; Linux i686; {0}; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12 GTB7.1']\r\n\r\n ########################################################################################################################################\r\n ## CREATE USER AGENT#####################################################################################################################\r\n userAgent = random.choice(userAgents).format(browserLang)\r\n\r\n googleDomainName = [\"com\", \"ac\", \"com.om\", \"ad\", \"ae\", \"com.af\", \"com.ag\", \"com.ai\", \"am\", \"it.ao\", \"com.ar\", \"cat\", \"as\", \"at\", \"com.au\", \"az\", \"ba\",\r\n \"com.bd\", \"be\", \"bf\", \"bg\", \"com.bh\", \"bi\", \"bj\", \"com.bn\", \"com.bo\", \"com.br\", \"bs\", \"co.bw\", \"com.by\", \"com.bz\", \"ca\", \"com.kh\",\r\n \"cc\", \"cd\", \"cf\", \"cn\", \"com.co\", \"co.nz\", \"cg\", \"ch\", \"ci\", \"co.ck\", \"cl\", \"cm\", \"co.cr\", \"com.cu\", \"cv\", \"cz\", \"de\", \"nu\", \"dj\",\r\n \"dk\", \"dm\", \"com.do\", \"dz\", \"no\", \"com.ec\", \"ee\", \"com.eg\", \"es\", \"com.et\", \"com.np\", \"fi\", \"com.fj\", \"fm\", \"fr\", \"ga\", \"nl\", \"ge\",\r\n \"gf\", \"gg\", \"com.gh\", \"com.gi\", \"nr\", \"gl\", \"gm\", \"gp\", \"gr\", \"com.gt\", \"com.ni\", \"gy\", \"com.hk\", \"hn\", \"hr\", \"ht\", \"com.ng\", \"hu\",\r\n \"co.id\", \"iq\", \"ie\", \"co.il\", \"com.nf\", \"im\", \"co.in\", \"io\", \"is\", \"it\", \"ne\", \"je\", \"com.jm\", \"jo\", \"co.jp\", \"co.ke\", \"com.na\", \"ki\",\r\n \"kg\", \"co.kr\", \"com.kw\", \"kz\", \"co.mz\", \"la\", \"com.lb\", \"com.lc\", \"li\", \"lk\", \"com.my\", \"co.ls\", \"lt\", \"lu\", \"lv\", \"com.ly\", \"com.mx\",\r\n \"co.ma\", \"md\", \"me\", \"mg\", \"mk\", \"mw\", \"ml\", \"mn\", \"ms\", \"com.mt\", \"mu\", \"mv\", \"com.pa\", \"com.pe\", \"com.ph\", \"com.pk\", \"pn\", \"com.pr\",\r\n \"ps\", \"pt\", \"com.py\", \"com.qa\", \"ro\", \"rs\", \"ru\", \"rw\", \"com.sa\", \"com.sb\", \"sc\", \"se\", \"com.sg\", \"sh\", \"si\", \"sk\", \"com.sl\", \"sn\", \"sm\",\r\n \"so\", \"st\", \"com.sv\", \"td\", \"tg\", \"co.th\", \"tk\", \"tl\", \"tm\", \"to\", \"com.tn\", \"com.tr\", \"tt\", \"com.tw\", \"co.tz\", \"com.ua\", \"co.ug\", \"co.uk\",\r\n \"us\", \"com.uy\", \"co.uz\", \"com.vc\", \"co.ve\", \"vg\", \"co.vi\", \"com.vn\", \"vu\", \"ws\", \"co.za\", \"co.zm\", \"co.zw\"]\r\n ########################################################################################################################################\r\n ## RAND A GOOGLE DOMAIN ################################################################################################################\r\n googleDomainName = random.choice(googleDomainName)\r\n\r\n ########################################################################################################################################\r\n ## IDS USE FOR ENGINE###################################################################################################################\r\n Ids = (\r\n \"5D4B3C17298B25CC309D9A0951C6BA04\", \"761446B6C1810068798CA09C88BE0776\", \"76DE276369845330D17C7CD111A536DD\",\r\n \"A0A6BD56DD1A054B1FF32E7FE3A44D27\", \"F856B0C416AEBE6E6C7610C3B89B5245\",\r\n \"88ADADC7E5DB1A344000A6F8C2B0BFA9\", \"6B815A7FDAF8A283440CD6AEB586CED3\", \"B6B0770CB0F48619CA0EDE35E451F9E5\",\r\n \"D6EA6D2A00270CA431DD36486EE53F35\", \"7E84432C6967B7DC0AA29A493A1B8FD0\"\r\n )\r\n Ids = random.choice(Ids)\r\n\r\n ########################################################################################################################################\r\n ## MSID USE FOR ENGINGE YANDEX##########################################################################################################\r\n MsIds = (\r\n \"1462902128.39925.22889.22408\", \"1462902552.15536.22876.27365\", \"1462902586.95962.22874.20936\",\r\n \"1462902627.17116.22876.27348\", \"1462902668.37045.20953.58001\",\r\n \"1462902238.39125.22589.29408\", \"1462902129.37521.22479.24410\", \"1462902113.35935.22853.22412\",\r\n \"1462902138.59225.22845.22478\", \"1462902145.39925.22812.22432\",\r\n )\r\n MsIds = random.choice(MsIds)\r\n\r\n ########################################################################################################################################\r\n ## FIND WORDPRESS WEB-SITE##############################################################################################################\r\n wordpressTag = [\"Proudly powered by WordPress\", \" SELF.DORK######################################################################################################\r\n def setEngine(self):\r\n\r\n \t# encrypt dork \r\n queryEncode = urllib.parse.quote(self.Dork)\r\n \r\n # set motor if type scan \"search whit dork\"\r\n if self.motor == 1:\r\n \t## sougo\r\n self.engin = connection.motors[0]\r\n self.engin = self.engin.format(queryEncode, \"{0}\")\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Sogou\")\r\n\r\n elif self.motor == 2:\r\n \t## Yandex\r\n self.engin = connection.motors[1]\r\n self.engin = self.engin.format(connection.MsIds, queryEncode, \"{0}\")\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Yandex\")\r\n \r\n elif self.motor == 3:\r\n \t## google\r\n self.engin = connection.motors[2]\r\n self.engin = self.engin.format(connection.googleDomainName, queryEncode, \"{0}\")\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Google\")\r\n \r\n elif self.motor == 4:\r\n \t## Bing \r\n self.engin = connection.motors[3]\r\n self.engin = self.engin.format(queryEncode, \"{0}\", connection.browserLang)\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Bing\")\r\n \r\n elif self.motor == 5:\r\n \t## Ask\r\n self.engin = connection.motors[4]\r\n self.engin = self.engin.format(queryEncode, \"{0}\", connection.Ids)\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Ask\")\r\n \r\n else:\r\n \t## Default google \r\n self.engin = connection.motors[2]\r\n self.engin = self.engin.format(connection.googleDomainName, queryEncode, \"{0}\")\r\n print(self.Color[5], \"[+] Engine :\", self.Color[-2], \" Google\")\r\n pass\r\n def searchDork(self, engine):\r\n try : \r\n\r\n urlToChange = engine\r\n \r\n ## PREPAIR ENGINE\r\n engine = engine.format(self.npage)\r\n request = urllib.request.Request(engine)\r\n \r\n ## SET URSER-AGENT \r\n request.add_header(\"User-Agent\", connection.userAgent)\r\n \r\n ## GET COGE HTML OF PAGE \r\n response = urllib.request.urlopen(request).read()\r\n connection.getResult(self,response, engine)\r\n except Exception : \r\n print(\"[+] Error in connection to the engine\")\r\n print(\"\\033[0;0m\")\r\n sys.exit()\r\n\t\t\t\r\n ########################################################################################################################################\r\n ## SEARCH DORK +++> SELF.DORK###########################################################################################################\r\n def getResult(self, response, engine):\r\n ## IF USER CHOICE BING OR GOOGLE ENGINES\r\n if \"www.googel.\" or \"www.bing\" in engine :\r\n self.npage = self.npage +10\r\n ## USE REGEX TO GET RESULT URL\r\n if \"www.bing\"in engine :\r\n ## REGEX FOR GET RESULT FROM BING ENGINE\r\n self.getResult = re.findall(r'

SELF.URL ##############################################################################################\r\n def connectionTarget(self, Url):\r\n\r\n self.Urlparse = urllib.parse.urlparse(Url)\r\n print(self.Color[12], \":\" * 75) \r\n print(self.Color[5], \"[+] \", self.dialogTxt[1], \" : \", self.Color[-2], Url)\r\n try:\r\n \r\n self.opener = urllib.request.Request(Url)\r\n ## SET USER AGENT\r\n \r\n self.opener.add_header(\"User-Agent\", self.userAgent)\r\n \r\n getResult = urllib.request.urlopen(self.opener)\r\n \r\n html = getResult.read()\r\n \r\n if self.noInfo == False :\r\n ## GET TYPE OF SERVER\r\n self.header = getResult.getheader(\"Server\")\r\n \r\n self.ipServer = socket.gethostbyname(self.Urlparse[1])\r\n \r\n print(self.Color[5], \"[+] \", self.dialogTxt[7], \" : \", self.Color[-2], self.header)\r\n print(self.Color[5], \"[+] \", self.dialogTxt[6], \" : \", self.Color[-2], getResult.status)\r\n print(self.Color[5], \"[+] \", self.dialogTxt[8], \": \", self.Color[-2], self.ipServer)\r\n\r\n if self.wordPress :\r\n if Url :\r\n for tag in connection.wordpressTag :\r\n if tag in str(html):\r\n print(self.Color[5], \"[+] WordPress :\",self.Color[3],\" Yes\")\r\n self.wp = 0\r\n break\r\n if self.wp != 0 :\r\n print(self.Color[5],\"[+] WordPress : \",self.Color[-2],\" No\")\r\n\r\n if self.joomla :\r\n if Url :\r\n if connect.joomlaTag in str(html) :\r\n print(self.Color[5], \"[+] Joomla :\",self.Color[3],\" Yes\")\r\n self.jm = 0\r\n\r\n if self.jm != 0 :\r\n print(self.Color[5], \"[+] Joomla : \", self.Color[-2], \" No\")\r\n except ValueError:\r\n print(\"\\n\",self.Color[2],\"[!] Error : check your url\")\r\n print(\"\\n\\t\", self.Color[5],\r\n \"[+] Some advices :\",self.Color[-2],\" \\n\\t\\t- Add http or https to your url\\n\\t\\t- Set your url into double cama \\n\\t\\t- Don't set an Ip\")\r\n print(\"\\033[0;0m\")\r\n sys.exit()\r\n except urllib.error.URLError as e :\r\n print(self.Color[5],\"[+] Url : \",self.Color[-2],Url)\r\n print(\"\\n\", self.Color[2],\" [!] Error : \",e)\r\n pass\r\n\r\n ########################################################################################################################################################\r\n ## SCAN PORTS ########################################################################################################################################\r\n def portsScan(self, url):\r\n \r\n print(\"-\"*70)\r\n urlParse = urllib.parse.urlparse(url)\r\n ports = [20,21,22,23,24,25,35,37,53,80,88,130,135,161,162,443,445,530,546,547,561,1433,1434,1701,1723,2082,2087,2121,2222,3306,3389,8080]\r\n \r\n SocketTcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # SOCKET TCP\r\n SocketUdp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # SOCKET UDP\r\n\r\n if self.tcpPorts :\r\n print(self.Color[5],\"\\n====> Scan port tcp (open) :\", end=\" \")\r\n self.tcpport = []\r\n for port in range(len(ports)):\r\n resPort = SocketTcp.connect_ex((urlParse[1], ports[port]))\r\n if resPort == 0 :\r\n print(self.Color[-2],ports[port], end=\" || \")\r\n self.tcpport.append(ports[port])\r\n\r\n SocketTcp.close()\r\n if self.udpPorts :\r\n\r\n print(self.Color[5],\"\\n====> Scan port udp (open) :\", end=\" \")\r\n self.udpport = []\r\n for port in range(len(ports)):\r\n resPort = SocketUdp.connect_ex((urlParse[1], ports[port]))\r\n if resPort == 0 :\r\n print(self.Color[-2],ports[port], end=\" || \")\r\n self.udpport.append(ports[port])\r\n pass\r\n ########################################################################################################################################################\r\n ## FIND ADMIN PAGE +++++> SELF.DORK AND SELF.URL #######################################################################################################\r\n def pageAdmin(self, Url):\r\n Lurl = self.Urlparse\r\n urllocal = Lurl.netloc\r\n for paths in connection.adminPage:\r\n fullUrl = urllocal + paths\r\n connectionPage = http.client.HTTPConnection(urllocal)\r\n connectionPage.request(\"GET\",paths)\r\n response = connectionPage.getresponse().status\r\n connectionPage.close()\r\n if response == 200 :\r\n print(self.Color[5],\"[+] Page Admin Found ==> \",self.Color[4],fullUrl)\r\n self.findAdminFound = fullUrl\r\n break\r\n else:\r\n print(self.Color[5],\"[+] Page Admin Not Found For ==>\",self.Color[4],fullUrl)\r\n self.findAdminFound = \"Admin page not found .\"\r\n pass\r\n\r\n def saveResults (self, scanType, Url, urlNumb) :\r\n fileSave = open(\"save result.txt\", \"a\")\r\n \r\n if urlNumb == 1 :\r\n textToSave = \"\\n\\n:::::::::::::::::::::::::: SCAN BY ==> {0} - {1} ::::::::::::::::::::::::::::::\".format(os.getlogin(),Time())\r\n textToSave += \"\\n [::] Type Scan : {0}\".format(scanType)\r\n else :\r\n textToSave = \"\\n\"\r\n textToSave += \"\\n [::] Url : {0}\".format(Url)\r\n \r\n if connect.noInfo == False :\r\n\r\n textToSave += \"\\n [::] Server : {0}\".format(connect.header)\r\n textToSave += \"\\n [::] Server-Ip : {0}\".format(connect.ipServer)\r\n\r\n if connect.tcpPorts :\r\n textToSave += \"\\n [::] Port Tcp opened : {0}\".format(connect.tcpport)\r\n\r\n if connect.udpPorts :\r\n textToSave += \"\\n [::] Port Udp opened : {0}\".format(connect.udpport)\r\n\r\n if connect.findAdminFound :\r\n textToSave += \"\\n [::] page Admin : {0}\".format(connect.findAdminFound)\r\n if connect.wordPress :\r\n if connect.wp == 0 :\r\n textToSave += \"\\n [::] WordPress : Yes\"\r\n else:\r\n textToSave += \"\\n [::] WordPress : No\"\r\n if connect.joomla :\r\n if connect.jm == 0:\r\n textToSave += \"\\n [::] Joomla : Yes\"\r\n else:\r\n textToSave += \"\\n [::] Joomla : No\"\r\n\r\n if connect.sqlFind :\r\n if vulnerabil.sqlErrrorFound == 0 :\r\n textToSave += \"\\n [::] Sql Injection : Error Found In This Url\"\r\n else :\r\n textToSave += \"\\n [::] Sql Injection : Error Not Found In This Url\"\r\n fileSave.writelines(textToSave)\r\n fileSave.close()\r\n pass\r\n\r\n###########################################################################################################################################################\r\n#### VULNERABILITY ###################################################################################################################################\r\nclass vulnerability(connection) :\r\n\r\n sqlErrors = [\"You have an error in your\", \"MySQL server\", \"MySql Error\", \"syntax error\", \"syntax error,\", \"mysql error\", \"MySQL result \", \"MySQL Error\"]\r\n\r\n def __init__(self, url):\r\n connection.__init__(self, connection.userAgent)\r\n self.urlTscan = url\r\n self.parsUrlTScan = urllib.parse.urlparse(url)\r\n self.sqlErrrorFound = 1\r\n pass\r\n\r\n ##########################################################################################################################################\r\n ## METHOD FIND SQL ERRORS ################################################################################################################\r\n def sqlInjiction (self):\r\n try :\r\n if self.parsUrlTScan[4] :\r\n self.makeUrlSql = self.urlTscan+\"%27\"\r\n openUrl = urllib.request.urlopen(self.makeUrlSql).read()\r\n for msgError in vulnerability.sqlErrors :\r\n if msgError in str(openUrl):\r\n print(self.Color[5],\"[+] Sql Errors :\",self.Color[3],\" Error Found :)\")\r\n self.sqlErrrorFound = 0\r\n break\r\n if self.sqlErrrorFound != 0 :\r\n print(self.Color[5],\"[!] Sql Errors :\",self.Color[2],\" Error Not Found !\")\r\n pass\r\n else :\r\n print(self.Color[5],\"[!] Sql Ijection :\",self.Color[2],\" Noo ! --no query found in the url-- \")\r\n except Exception as e :\r\n print(self.Color[2],\"[+] Error : \",e)\r\n pass\r\n pass\r\n\r\n## ENCRYPT BASE64\r\ndef base64Encrypt(textEncrypt):\r\n strEncrypted = base64.encodebytes(textEncrypt.encode('ascii'))\r\n time.sleep(3)\r\n print(Screen.Color[5],\"\\t\\t=====>\",Screen.Color[-2],strEncrypted)\r\n pass\r\n\r\n## DECRYPT BASE64\r\ndef base64Decrypt(textDecrypt):\r\n try:\r\n strEncrypted = base64.decodebytes(textDecrypt.encode('ascii'))\r\n time.sleep(3)\r\n print(Screen.Color[5],\"\\t\\t=====>\",Screen.Color[-2],strEncrypted)\r\n except :\r\n time.sleep(3)\r\n print(Screen.Color[2],\"[!] Error in decrypt your string\")\r\n pass\r\n\r\n## ENCRYPT MD5\r\ndef md5Encrypt(textEncrypt):\r\n encryptedString = hashlib.md5(textEncrypt.encode(\"utf\")).hexdigest()\r\n time.sleep(3)\r\n print(Screen.Color[5],\"\\t\\t=====>\",Screen.Color[-2], encryptedString)\r\n pass\r\n\r\n## GET TIME\r\ndef Time():\r\n localTime = \"{0}-{1}-{2} {3}:{4}:{5}\".format(time.localtime()[0],time.localtime()[1],time.localtime()[2],time.localtime()[3],time.localtime()[4],time.localtime()[5])\r\n return localTime\r\n\r\n## CHECK PYTHON VERSION\r\ndef checkVersion():\r\n getVersion = re.findall(r\"\",str(urllib.request.urlopen(\"https://raw.githubusercontent.com/Suicedal-Virus/Scanner-web/master/README.md\").read()))[0]\r\n if float(getVersion) > 1.2 :\r\n \tprint(Screen.Color[2],\"[!] New version available Download it .\")\r\n\t\t\r\n else :\r\n \tprint(Screen.Color[3],\"[+] Aucun new version available .\")\r\n\t\r\nif __name__ == \"__main__\" :\r\n\r\n try :\r\n # get argument in the path .\r\n argumentuser = sys.argv[1:]\r\n # call class screen\r\n Screen = screen(sys.platform, argumentuser)\r\n # show logo\r\n Screen.Logo()\r\n # checking argument\r\n Screen.checkArgument()\r\n # call method show\r\n Screen.Show()\r\n # call class connection and add user agent \r\n connect = connection(connection.userAgent)\r\n\r\n ## CHECK UPDATE \r\n if Screen.update :\r\n print(Screen.Color[12],\"::::::::::::::::::::::::::::::: \",Screen.scanTitle[-1],\" ::::::::::::::::::::::::::::::: \") \r\n checkVersion()\r\n sys.exit()\r\n ## IF USER WANT DECRYPT BASE64 TO STRING\r\n if Screen.base64Decry :\r\n print(\"\\t\\t\", Screen.Color[12],\" \"*10,Time())\r\n print(Screen.Color[12],\"::::::::::::::::::::::::::::::: \", Screen.scanTitle[3], \" ::::::::::::::::::::::::::::::: \")\r\n print(Screen.Color[5],\"[+] String Decrypted : \",Screen.Color[-2],Screen.base64Decry)\r\n base64Decrypt(Screen.base64Decry)\r\n\r\n ## IF USER WANT ENCRYPT STRING TO BASE64\r\n if Screen.base64Encry :\r\n print(\"\\t\\t\", Screen.Color[12],\" \"*10,Time())\r\n print(Screen.Color[12],\"::::::::::::::::::::::::::::::: \", Screen.scanTitle[2], \" ::::::::::::::::::::::::::::::: \")\r\n print(Screen.Color[5],\"[+] String Encrypted : \",Screen.Color[-2],Screen.base64Encry)\r\n base64Encrypt(Screen.base64Encry)\r\n\r\n ## IF USER WANT ENCRYPT STRING TO MD5\r\n if Screen.md5Encrypt :\r\n print(\"\\t\\t\", Screen.Color[12], \" \" * 10, Time())\r\n print(Screen.Color[12], \"::::::::::::::::::::::::::::::: \", Screen.scanTitle[-2],\" ::::::::::::::::::::::::::::::: \")\r\n print(Screen.Color[5],\"[+] String Encrypted : \", Screen.Color[-2],Screen.md5Encrypt)\r\n md5Encrypt(Screen.md5Encrypt)\r\n\r\n ## IF USER USE DORK PARAMETER\r\n if connect.Dork:\r\n print(\"\\t\\t\", Screen.Color[12], \" \" * 10, Time())\r\n print(Screen.Color[12], \"::::::::::::::::::::::::::::::: \", Screen.scanTitle[0],\" ::::::::::::::::::::::::::::::\")\r\n \r\n ## PREPARE ENTGINE FOR SEARCHING\r\n connect.setEngine()\r\n \r\n ## SEARCH DORK AND ADD IT TO A LIST\r\n while connect.count > len(connect.getResultAll):\r\n connect.searchDork(connect.engin)\r\n\r\n print(Screen.Color[5],\"[+]\",Screen.Color[-2],int(len(connect.urlGetedByEngin)),\"result found !\")\r\n \r\n ## GET URL FROM THE LIST AND CONNECTING TO THIS URL \r\n numb = 0\r\n for urlFromDork in connect.urlGetedByEngin :\r\n numb +=1\r\n print(\"\\n\",Screen.Color[5],\"[+]\",Screen.Color[-2],\"Result N : \",numb,\"/\",len(connect.urlGetedByEngin))\r\n connect.connectionTarget(urlFromDork)\r\n \r\n if connect.sqlFind :\r\n vulnerabil = vulnerability(urlFromDork)\r\n vulnerabil.sqlInjiction()\r\n \r\n if connect.tcpPorts or connect.udpPorts :\r\n connect.portsScan(urlFromDork)\r\n \r\n if connect.findAdmin :\r\n print(\"\\n\", Screen.Color[12], \"::::::::::::::::::::::::::: \", connect.scanTitle[4],\" :::::::::::::::::::::::::::::::::\")\r\n connect.pageAdmin(connect.Url)\r\n \r\n if connect.saveResult :\r\n connect.saveResults(Screen.scanTitle[0], urlFromDork, numb)\r\n \r\n if connect.saveResult : \r\n print(\"\\n\",Screen.Color[4],\"[::] Good Bye ! !--Hacker--! || your result is saved on save result.txt\")\r\n \r\n ## IF USER USE URL PARAMETER\r\n elif connect.Url:\r\n print(\"\\t\\t\", Screen.Color[12], \" \" * 10, Time())\r\n print(Screen.Color[12], \":::::::::::::::::::::::::::::: \",Screen.scanTitle[1] ,\" :::::::::::::::::::::::::::::::\")\r\n connect.connectionTarget(connect.Url)\r\n\r\n if connect.sqlFind:\r\n vulnerabil = vulnerability(connect.Url)\r\n vulnerabil.sqlInjiction()\r\n\r\n if connect.tcpPorts or connect.udpPorts:\r\n connect.portsScan(connect.Url)\r\n\r\n if connect.findAdmin:\r\n print(\"\\n\", Screen.Color[12], \"::::::::::::::::::::::::::: \", connect.scanTitle[4],\" :::::::::::::::::::::::::::::::::\")\r\n connect.pageAdmin(connect.Url)\r\n if connect.saveResult :\r\n connect.saveResults(Screen.scanTitle[1], connect.Url , 1)\r\n print(\"\\n\",Screen.Color[4],\"[::] Good Bye ! !--Hacker--! || your result is saved on save result.txt\")\r\n print(\"\\033[0;0m\")\r\n except KeyboardInterrupt :\r\n print(Screen.Color[2],\"\\n\\t[!] Good bye bro process stopped by user.\")\r\n print(\"\\033[0;0m\")\r\n","sub_path":"scanner Web.py","file_name":"scanner Web.py","file_ext":"py","file_size_in_byte":46691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"475543579","text":"import logging\nimport pandas as pd\n\n# init logging\nlog_fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\nlogging.basicConfig(level=logging.INFO, format=log_fmt)\nlogger = logging.getLogger(__name__)\n\n\ndef load_from_database(connection, table_name, input_cols, output_col):\n if not output_col['name'] in input_cols:\n input_cols.append(output_col['name'])\n column_str = ', '.join(str(col) for col in input_cols)\n filter_vals = ', '.join('\"{}\"'.format(str(val)) for val in output_col['values'])\n result = load_values(connection, table_name, column_str, output_col['name'], filter_vals)\n logger.info('loaded value: {val}'.format(val=result.index))\n return result\n\n\ndef load_output_values(conn, table_name, output_col):\n query = 'SELECT {col}, count({col}) FROM {tn} GROUP BY {col};' \\\n .format(col=output_col['name'], tn=table_name)\n df = pd.read_sql_query(query, conn)\n return df\n\n\ndef load_values(conn, table_name, cols, filter_col, filter_vals):\n query = 'SELECT {cls} FROM {tn} WHERE {name} in ({val});' \\\n .format(cls=cols, tn=table_name, name=filter_col, val=filter_vals)\n logger.info('created query: {}'.format(query))\n df = pd.read_sql_query(query, conn)\n return df\n\n\ndef get_table_info(connection, table_name):\n df = pd.read_sql_query('PRAGMA TABLE_INFO({})'.format(table_name), connection, 'name')\n return df","sub_path":"src/data/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"288947459","text":"from PIL import Image, ImageOps\nimport numpy as np\nfrom tensorflow.keras import models\n\n\ndef predictClothes(filenameImage, filenameModel):\n image = Image.open(filenameImage) # buscar imagem no diretório enviado\n image = image.resize((28,28)) #organização do shape de entrada\n image = ImageOps.grayscale(image) #tranformar para o formato grayscaler\n image = np.array(image, ndmin=3)/255 #normalização da imagem\n\n model = models.load_model(filenameModel)\n\n result_predict = int(np.argmax(model.predict(image),axis=-1)) #faz a previsão\n print(np.argmax(model.predict(image),axis=-1))\n print(model.predict(image))\n\n nome_classes = [\"Camiseta\", \"Calça\", \"Suéter\", \"Vestido\", \"Casaco\",\"Sandália\",\"Camisa\",\"Tênis\", \"Bolsa\",\"Botas\"]\n result = str(nome_classes[result_predict])\n return result\n\n","sub_path":"src/classification/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458666028","text":"\r\ntodo_modal = {\r\n\t\"type\": \"modal\",\r\n\t\"title\": {\r\n\t\t\"type\": \"plain_text\",\r\n\t\t\"text\": \"Create a task :scroll:\",\r\n\t\t\"emoji\": True\r\n\t},\r\n\t\"submit\": {\r\n\t\t\"type\": \"plain_text\",\r\n\t\t\"text\": \"Submit\",\r\n\t\t\"emoji\": True\r\n\t},\r\n\t\"close\": {\r\n\t\t\"type\": \"plain_text\",\r\n\t\t\"text\": \"Cancel\",\r\n\t\t\"emoji\": True\r\n\t},\r\n\t\"blocks\": [\r\n\t\t{\r\n\t\t\t\"type\": \"input\",\r\n\t\t\t\"block_id\": \"my_block\",\r\n\t\t\t\"element\": {\r\n\t\t\t\t\"type\": \"plain_text_input\",\r\n\t\t\t\t\"action_id\": \"my_action\"\r\n\t\t\t},\r\n\t\t\t\"label\": {\r\n\t\t\t\t\"type\": \"plain_text\",\r\n\t\t\t\t\"text\": \"what task do you want to add?\",\r\n\t\t\t\t\"emoji\": True\r\n\t\t\t}\r\n\t\t}\r\n\t]\r\n}\r\nstart_text = \"Welcome to *HomeFocus* :wave: Ready to get *focused*? Simply choose a feature \" + \\\r\n \"that might help you *focus*. :raised_hands: \\n\\n\"\r\n\r\nend_text = \"If you have any questions, check out the Frequently Asked Questions or email us at Focus@Home\"\r\n\r\n\r\nrecommendation_buttons = [{\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"1. To-Do Lists Create Order \\n\" +\r\n \"2. To-Do Lists Help You Create Accountability\\n\" +\r\n \"3. To-Do Lists Help Relieve Your Stress\\n\" +\r\n \"4. You get the point :wink:\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Create a To-Do List!\"\r\n },\r\n \"value\": \"v_todo\",\r\n \"action_id\": \"v_todo\"\r\n },\r\n}, {\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"The timer can provide motivation as the employee can try to “beat” the clock. Some employees respond better to an object setting boundaries than an adult telling them what to do.\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Timer Time!\"\r\n },\r\n \"value\": \"v_timer\",\r\n \"action_id\": \"v_timer\"\r\n },\r\n}, {\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"It reduces distractions and improves focus. Music helps boost motivation when starting a new task. It is beneficial to listen to something you are familiar with for focusing intensely on your project. Researchers recommend listening to instrumental music if you want to hear music while working.\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Play Focus Music\"\r\n },\r\n \"value\": \"v_music\",\r\n \"action_id\": \"v_music\"\r\n },\r\n}, {\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"Want to feel like you are just at your work?\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Working Sounds!\"\r\n },\r\n \"value\": \"v_work_sounds\",\r\n \"action_id\": \"v_work_sounds\"\r\n },\r\n}, {\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"keep each other company and keep yourselves accountable while you work.\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Have a working companion!\"\r\n },\r\n\t\t\"url\": \"https://www.youtube.com/watch?v=KsVCufHLVsg&t=3799s\",\r\n \"value\": \"v_work_companion\",\r\n # \"action_id\": \"v_work_companion\"\r\n },\r\n},\r\n {\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": \"Don't be disturbed by others... It might distract you! :eyes:\"\r\n },\r\n \"accessory\": {\r\n \"type\": \"button\",\r\n \"text\": {\r\n \"type\": \"plain_text\",\r\n \"text\": \"Deep Focus\"\r\n },\r\n \"value\": \"v_deep_focus\",\r\n \"action_id\": \"v_deep_focus\"\r\n },\r\n},\r\n]\r\n\r\ndivider = [{\r\n \"type\": \"divider\"\r\n}]\r\n\r\nstart = [{\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": start_text\r\n },\r\n}, ]\r\n\r\nend = [{\r\n \"type\": \"section\",\r\n \"text\": {\r\n \"type\": \"mrkdwn\",\r\n \"text\": end_text\r\n },\r\n}, ]\r\n\r\ndeepfocus_status = {\r\n \"status_text\": \"riding a train\",\r\n \"status_emoji\": \":mountain_railway:\",\r\n \"status_expiration\": 0\r\n}\r\n\r\nrecommendations = start + divider + recommendation_buttons + divider + end\r\n","sub_path":"data_jsons.py","file_name":"data_jsons.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516494776","text":"# Created by Vinay Jakkali on 11/25/2019\n\n\"\"\"\n--------------------------------------------------------------------------------------\nInclude code description here:\n\n--------------------------------------------------------------------------------------\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom univariate import univariatescan as interval\nfrom bisection import bisection as bisect\n\n\ndef routing(p=(5.0, 3.0), cent=(2.0, 2.0), r=1.0, rho=20, x0=10, tol=1e-8):\n \"\"\" The routing function defined here takes following parameters as input\n INPUT:\n p : it is a tuple that takes target point coordinates as input P(x.0,y.0)\n cent: it is a tuple that takes the center of the circle as input C(x.0,y.0)\n r : it is the radius of the circle and takes float value as input\n rho : it the penalty term\n x0 : it is initial guess required for univariate scan to bracket the interval\n tol : This is the tolerance accepted for the minimized objective function\n\n OUTPUT:\n Plots showing bracketed interval, objective function with the minimum point and the optimized robot path\n Also prints the values of minimum x, minimum F(x) to the console\"\"\"\n\n aa = lambda x: (x - p[0]) ** 2 + (p[1]) ** 2\n bb = lambda x: 2 * ((p[0] - x) * (x - cent[0]) - (p[1] * cent[1]))\n cc = lambda x: (x - cent[0]) ** 2 + (cent[1]) ** 2 - r ** 2\n delta = lambda x: bb(x) ** 2 - 4 * aa(x) * cc(x)\n f = lambda x: (x + ((aa(x)) ** 0.5) * (1 + rho * abs((((delta(x)) ** 0.5) / (aa(x)))))) if delta(x) > 0 else x + (\n (aa(x)) ** 0.5)\n [a, b, k] = interval(f, x0)\n minimum, ok = bisect(f, a, b, tol)\n print(\"The minimum distance on x axis = \", round(minimum, 4))\n print(\"The minimum F(x) =\", round(f(minimum), 4))\n circle = plt.Circle(cent, r, color='b', fill=False)\n plt.gcf().gca().add_artist(circle)\n plt.scatter(cent[0], cent[1], color='r', marker='*')\n plt.scatter(0, 0, color='g', marker='x')\n plt.scatter(minimum, 0, color='r', marker='x')\n plt.scatter(p[0], p[1], color='b', marker='o')\n plt.plot([0, minimum], [0, 0], color='r')\n plt.plot([minimum, p[0]], [0, p[1]], color='k')\n plt.title('Optimal Robot Path', fontsize=24)\n plt.xlabel('x axis', fontsize=24)\n plt.ylabel('y axis', fontsize=24)\n plt.xlim(0, 5.5)\n plt.ylim(-0.5, 5.5)\n plt.grid()\n # plt.axes().set_aspect('equal')\n plt.axes().axhline(y=0, color='g')\n plt.axes().axvline(x=0, color='k')\n plt.show()\n\n\nrouting(p=(2.0, 5.0), cent=(2.0, 2.0), r=1.0, rho=20, x0=0.5, tol=1e-8)\n","sub_path":"JakkaliVinay_Assignment1/Problem5.py","file_name":"Problem5.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"418559494","text":"import requests\nfrom bs4 import BeautifulSoup\npath=\"E:/爬虫成果/斗破苍穹小说/\"\nmurl=\"http://www.doupoxs.com\"\nurl=\"http://www.doupoxs.com/doupocangqiong/\"\nheaders={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' \n 'AppleWebKit/537.36 (KHTML, like Gecko)'\n 'Chrome/67.0.3396.87 Safari/537.36'}\nresponse=requests.get(url,headers)\nsoup=BeautifulSoup(response.content,\"lxml\")\nplists=soup.select(\"body > div > div > ul > li > a\")\n# 每一个章节的链接\nfor plist in plists:\n # 章节对象\n pname= open(path + plist.text + \".txt\", \"a+\")\n # 单张的文件名\n purl=murl+plist[\"href\"]\n # 单章节实际地址\n pdata=requests.get(purl)\n # 访问页面\n psoup=BeautifulSoup(pdata.content,\"lxml\")\n # BS4读取\n mps=psoup.select(\"body > div > div > div > div > p\")\n # print(mps)\n # 获取页面所有的P标签\n for p in mps:\n pmain=p.text\n pname.write(pmain)\n pname.write(\"\\n\")\n pname.close()\n # 单章节的文件名\n # pname.write(p.text)\n # pname.close()\n","sub_path":"PythonProjects/爬虫/作业/小说获取2.py","file_name":"小说获取2.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"260906358","text":"import csv\r\nfrom collections import OrderedDict\r\n\r\nwith open('C:\\\\Users\\Sasanka\\Desktop\\Python Scripts\\Test_reference.txt', 'r') as f:\r\n r = csv.reader(f)\r\n dict2 = {row[0]: row[1:] for row in r}\r\n print (dict2)\r\n \r\n\r\nwith open('C:\\\\Users\\Sasanka\\Desktop\\Python Scripts\\input.txt', 'r') as f1:\r\n r1 = csv.reader(f1)\r\n dict1 = OrderedDict((row1[0], row1[1:]) for row1 in r1)\r\n print (dict1)\r\nresult = OrderedDict()\r\nfor d in (dict1, dict2):\r\n for key, value in d.items():\r\n result.setdefault(key, []).extend(value)\r\n\r\nwith open('C:\\\\Users\\Sasanka\\Desktop\\Python Scripts\\Test_reference_result.txt', 'w') as f:\r\n w = csv.writer(f)\r\n for key, value in result.items():\r\n w.writerow([key] + value)","sub_path":"merge_two_files.py","file_name":"merge_two_files.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"390279078","text":"import pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn import svm\nimport numpy as np\n\nfrom sklearn import tree\n\n############### PANDAS DATA IMPORT HELPER FUNCTIONS #########################\n\ndef get_ri_stops_df():\n \"\"\"\n Helper function. Will return a Pandas DataFrame for the RI Traffic Stops dataset\n \"\"\"\n ri_stops_path = getcurdir() + f\"{os.sep}..{os.sep}data{os.sep}ri_traffic_stops.csv\"\n return pd.read_csv(ri_stops_path)\n\n\ndef get_banknote_df():\n \"\"\"\n Helper function. Will return a Pandas DataFrame for the Banknote Authentication Dataset\n \"\"\"\n banknote_path = getcurdir() + f\"{os.sep}..{os.sep}data{os.sep}banknote_authentication.csv\"\n return pd.read_csv(banknote_path)\n \n \n############### MACHINE LEARNING MODELS ###############\n\nTEST_SIZE = 0.2 # TODO: Feel free to modify this!\nKNN_NUM_NEIGHBORS = 5 # TODO: Feel free to modify this!\nRANDOM_SEED = 0\nTRAFFIC_STOPS_NONNUMERICAL_COLS = [\"county_name\", \"driver_gender\", \"driver_race\", \"violation\", \"search_conducted\",\\\n \"stop_outcome\", \"is_arrested\", \"drugs_related_stop\"]\n\n\ndef get_trained_model(dataset_name, model_name, target_name=None, feature_names=None):\n \"\"\"\n Input:\n - dataset_name: str, a dataset name. One of [\"ri_traffic_stops\", \"banknote_authentication\"]\n - A model name: str, a model name. One of [\"decision_tree\", \"k_nearest_neighbor\", \"logistic_regression\", \"dummy\"]\n - target_name: str, the name of the variable that you want to make the label of the regression/classification model\n - feature_names: list[str], the list of strings of the variable names that you want to be the features of your\n regression/classification model\n \n What it does:\n - Create a model that matches with the model_name, and then fit to the One-Hot-Encoded dataset\n\n Output: A tuple of four things:\n - model: The model associated with the model_name - **TRAINED**\n - ohe: The one hot encoder that is used to encode non-numeric features in the dataset\n - train_df: The training dataset (DataFrame)\n - test_df: The testing dataset (DataFrame)\n \"\"\"\n # first, check if the inputs are valid\n assert dataset_name in [\"ri_traffic_stops\", \"banknote_authentication\"], \\\n f\"Invalid input for function get_model: dataset_name = {dataset_name}, supposed to be in ['ri_traffic_stops', 'banknote_authentication']\"\n assert model_name in [\"decision_tree\", \"k_nearest_neighbor\", \"logistic_regression\", \"dummy\"], \\\n f\"Invalid input for function get_model: model_name = {model_name}, supposed to be in ['decision_tree', 'k_nearest_neighbor', 'logistic_regression', 'dummy']\"\n \n # creating a OneHotEncoder for non-numeric features\n ohe = OneHotEncoder(handle_unknown='ignore')\n\n # getting the exact model - the formatting is a lil cursed :P\n if model_name == \"decision_tree\": model = DecisionTreeClassifier(random_state=RANDOM_SEED)\n if model_name == \"logistic_regression\": model = LogisticRegression(random_state=RANDOM_SEED)\n if model_name == \"k_nearest_neighbor\": model = KNeighborsClassifier(n_neighbors=KNN_NUM_NEIGHBORS)\n # this model is a dummy model - for baseline model! :)\n if model_name == \"dummy\": model = DummyClassifier(random_state=RANDOM_SEED)\n\n if dataset_name == \"ri_traffic_stops\":\n \"\"\"\n Default assumption: target label is `stop_outcome`, feature_names are the rest\n \"\"\"\n data = get_ri_stops_df()\n if target_name == None:\n target_name = \"stop_outcome\" # default assumption\n\n if feature_names == None:\n feature_names = [e for e in data.columns if e != target_name] # default assumption\n\n if dataset_name == \"banknote_authentication\":\n \"\"\"\n Assumption: target label is `Class`, feature_names are the rest\n \"\"\"\n data = get_banknote_df()\n if target_name == None:\n target_name = \"Class\" # default assumption\n\n if feature_names == None:\n feature_names = [e for e in data.columns if e != target_name] # default assumption\n\n # now assert a few things to make sure all the column names are valid\n assert target_name in data.columns, f\"Column not found: {target_name}\"\n for lbl in feature_names:\n assert lbl in data.columns, f\"Column not found: {lbl}\"\n \n\n train_df, test_df = train_test_split(data, test_size=TEST_SIZE)\n\n if dataset_name == \"ri_traffic_stops\":\n X = ohe.fit_transform(train_df[[e for e in feature_names if e in TRAFFIC_STOPS_NONNUMERICAL_COLS]]).toarray()\n X_PRIME = train_df[[e for e in feature_names if e not in TRAFFIC_STOPS_NONNUMERICAL_COLS]].to_numpy()\n train_data = np.concatenate((X, X_PRIME), axis=1)\n\n if dataset_name == \"banknote_authentication\":\n train_data = train_df[feature_names].copy()\n\n\n model.fit(train_data, train_df[target_name])\n return model, ohe, train_df, test_df\n \n\ndef get_model_accuracy(model, df, one_hot_encoder, dataset_name=None, target_name=None, feature_names=None):\n \"\"\"\n Inputs:\n - model: sklearn model that was returned by get_model (or created yourself)\n - df: The dataframe that contains the features and the target\n - one_hot_encoder: The sklearn OneHotEncoder that was returned by get_model (or created yourself)\n that learns how to encode the non-numeric features in the dataset df\n - dataset_name: if not None, has to be one of [\"ri_traffic_stops\", \"banknote_authentication\"]\n - target_name, feature_names: if not None, has to be in df.columns\n\n Outputs: A tuple of three things:\n - acc: Accuracy score\n - y_pred: The model's predictions (numpy array)\n - y_targ: The target labels (numpy array)\n \"\"\"\n ##### INPUT ASSERTIONS #####\n # if either target_name == None or feature_names == None, dataset_name has to be != None\n if target_name == None or feature_names == None:\n assert dataset_name in [\"ri_traffic_stops\", \"banknote_authentication\"], \\\n \"\"\"if either target_name == None or feature_names == None, dataset_name has to be != None.\n Check input to get_model_accuracy\"\"\"\n \n # if nothing is passed to target_name and feature_names, we'll use the default\n default_targ_label = {\n \"ri_traffic_stops\": \"stop_outcome\",\n \"banknote_authentication\": \"Class\"\n }\n\n # if nothing was inputted into target_lalbel, use the default target label\n if target_name == None:\n target_name = default_targ_label[dataset_name]\n \n if feature_names == None:\n feature_names = [e for e in df.columns if e != target_name]\n\n # and then assert that target_name and each of feature_names in df\n ohe_bool = False\n assert target_name in df.columns, f\"Column not found: {target_name}\"\n for lbl in feature_names:\n assert lbl in df.columns, f\"Column not found: {lbl}\"\n # alright, and check if we need to slap one hot encoding on top of this or nah\n if lbl in TRAFFIC_STOPS_NONNUMERICAL_COLS:\n ohe_bool = True\n\n\n ##### Alright. Now onto the meat of the function! #####\n # encode the features\n if not ohe_bool:\n encoded = df[feature_names]\n else:\n X = one_hot_encoder.transform(df[[e for e in feature_names if e in TRAFFIC_STOPS_NONNUMERICAL_COLS]]).toarray()\n X_PRIME = df[[e for e in feature_names if e not in TRAFFIC_STOPS_NONNUMERICAL_COLS]].to_numpy()\n encoded = np.concatenate((X, X_PRIME), axis=1)\n\n # and then use the model to predict\n y_pred = model.predict(encoded)\n \n # get the y_target\n y_targ = df[target_name].to_numpy()\n\n # get the accuracy\n acc = (y_pred == y_targ).sum() / len(y_pred) \n \n return acc, y_pred, y_targ\n\n\n############### UTILS HELPER FUNCTIONS ###############\n\ndef getcurdir():\n \"\"\"\n Helper function to get the absolute path of utils.py\n \"\"\"\n return os.path.dirname(os.path.realpath(__file__))\n\n \n ","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496351107","text":"import os\nimport ctypes\nfrom ctypes import c_int, c_double, POINTER, Structure\n\n\n__doc__ = \"\"\"\nPython wrapper for RamanOpticalControl.c\nCompile with:\ngcc -O3 -shared -o RamanOpticalControl.so RamanOpticalControl.c -lm -fopenmp -fPIC\n\"\"\"\n\n\nclass c_complex(Structure):\n \"\"\"\n Complex double ctypes\n \"\"\"\n _fields_ = [\n ('real', c_double),\n ('imag', c_double)\n ]\n\n\nclass Parameters(Structure):\n \"\"\"\n Parameters structure ctypes\n \"\"\"\n _fields_ = [\n\n ('rho_0', POINTER(c_complex)),\n ('nDIM', c_int),\n ('N_exc', c_int),\n ('time_A', POINTER(c_double)),\n ('time_R', POINTER(c_double)),\n ('timeAMP_A', c_double),\n ('timeAMP_R', c_double),\n ('timeDIM_A', c_int),\n ('timeDIM_R', c_int),\n ('field_amp_A', c_double),\n ('field_amp_R', c_double),\n ('omega_R', c_double),\n ('omega_v', c_double),\n ('omega_e', c_double),\n ('d_alpha', c_double),\n ('thread_num', c_int),\n ('prob_guess_num', c_int),\n ('spectra_lower', POINTER(c_double)),\n ('spectra_upper', POINTER(c_double)),\n ('max_iter', c_int),\n ('control_guess', POINTER(c_double)),\n ('control_lower', POINTER(c_double)),\n ('control_upper', POINTER(c_double)),\n ('guess_num', c_int),\n ('max_iter_control', c_int)\n ]\n\n\nclass Molecule(Structure):\n \"\"\"\n Parameters structure ctypes\n \"\"\"\n _fields_ = [\n ('nDIM', c_int),\n ('energies', POINTER(c_double)),\n ('matrix_gamma_pd', POINTER(c_double)),\n ('matrix_gamma_dep', POINTER(c_double)),\n ('gamma_dep', c_double),\n ('frequency_A', POINTER(c_double)),\n ('freqDIM_A', c_int),\n ('rho_0', POINTER(c_complex)),\n ('mu', POINTER(c_complex)),\n ('field_A', POINTER(c_complex)),\n ('field_R', POINTER(c_complex)),\n ('rho', POINTER(c_complex)),\n ('abs_spectra', POINTER(c_double)),\n ('abs_dist', POINTER(c_double)),\n ('ref_spectra', POINTER(c_double)),\n ('Raman_levels', POINTER(c_double)),\n ('levels', POINTER(c_double)),\n ('dyn_rho_A', POINTER(c_complex)),\n ('dyn_rho_R', POINTER(c_complex)),\n ('prob', POINTER(c_double))\n ]\n\n\ntry:\n # Load the shared library assuming that it is in the same directory\n lib1 = ctypes.cdll.LoadLibrary(os.getcwd() + \"/RamanOpticalControl.so\")\nexcept OSError:\n raise NotImplementedError(\n \"\"\"\n The library is absent. You must compile the C shared library using the commands:\n gcc -O3 -shared -o RamanOpticalControl.so RamanOpticalControl.c -lm -lnlopt -fopenmp -fPIC\n \"\"\"\n )\n\n\nlib1.CalculateSpectra.argtypes = (\n POINTER(Molecule), # molecule mol\n POINTER(Parameters), # parameter field_params\n)\nlib1.CalculateSpectra.restype = POINTER(c_complex)\n\n\nlib1.CalculateControl.argtypes = (\n POINTER(Molecule), # molecule molA\n POINTER(Molecule), # molecule molB\n POINTER(Parameters), # parameter field_params\n)\nlib1.CalculateControl.restype = POINTER(c_complex)\n\n\ndef CalculateSpectra(mol, params):\n return lib1.CalculateSpectra(\n mol,\n params\n )\n\ndef CalculateControl(molA, molB, params):\n return lib1.CalculateControl(\n molA,\n molB,\n params\n )\n","sub_path":"wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"456502495","text":"\n# -*- coding: utf-8 -*-\n\nfrom models.LSTM2L import LSTM2L\nfrom models.CNN import CNN\nfrom models.BiLSTM import BiLSTM\nfrom models.BiLSTM2L import BiLSTM2L\nfrom models.Transformer import Transformer\n\n\n\ndef setup(opt):\n \n if opt.contatenate==1:\n opt.max_sequence_length = opt.max_sequence_length_long \n \n if opt.model == \"lstm_2L\":\n model = LSTM2L(opt)\n elif opt.model == \"cnn\":\n model = CNN(opt)\n elif opt.model == \"bilstm\":\n model = BiLSTM(opt)\n elif opt.model == \"bilstm_2L\":\n model = BiLSTM2L(opt)\n elif opt.model == \"transformer\":\n model = Transformer(opt)\n elif opt.model == \"bilstm_2inputs\":\n model = BiLSTM_2inputs(opt)\n else:\n raise Exception(\"model not supported: {}\".format(opt.model))\n\n return model","sub_path":"models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332720633","text":"\"\"\"\nKeyboard\n\n1. Has access to CPU instance so it can call an interrupt, access memory (DMA)\n2. Runs in its own thread to allow for simultaneous execution of CPU cycle and keyboard polling loop\n\"\"\"\n\nimport sys\nimport threading\nfrom time import sleep\n\n\nclass Keyboard:\n def __init__(self, emulator):\n # Get access to emulator as a 'peripheral'\n self._emulator = emulator\n # Create keyboard polling thread\n self._keyboard_thread = threading.Thread(target=self._poll)\n # Making thread a daemon will allow for auto cleanup on main program exit\n self._keyboard_thread.daemon = True\n\n def connect(self):\n # Start thread\n self._keyboard_thread.start()\n\n def _poll(self):\n # Enter keyboard polling loop\n while True:\n char = sys.stdin.read(1) # Read one byte (char)\n if char:\n # Set char in memory\n self._emulator.ram[0xF4] = ord(char)\n # Raise keyboard interrupt\n self._emulator.reg[self._emulator.isr] = self._emulator._set_nth_bit(\n self._emulator.reg[self._emulator.isr], 1\n )\n\n # Sleep 50 ms to keep cpu usage down\n # Technically this makes it poll the keyboard at 20hz\n sleep(0.05)\n","sub_path":"ls8/keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"143813753","text":"\"\"\"\nRecursion\n\"\"\"\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.search(root, 0)\n\n def search(self, node, i):\n if node is None:\n return i\n else:\n i += 1\n a = self.search(node.left, i)\n b = self.search(node.right, i)\n if a > b:\n return a\n else:\n return b\n","sub_path":"Maximum Depth of Binary Tree.py","file_name":"Maximum Depth of Binary Tree.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"485391350","text":"import funcs.hdf as hdf\nimport pandas as pd\nfrom funcs.fig.scatter import plot\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom funcs.fig.color import hex_to_rgba\nsns.set(font_scale=2.5, style=\"white\", color_codes=True)\n\n\ndef timecource_feature_rearrange(df, ts=[0, 0, 5, 5, 15, 15, 30, 30]):\n o = pd.DataFrame()\n for i in range(len(df)):\n o = o.append(pd.DataFrame(\n {'time': ts, 'expr': df.iloc[i].tolist(), 'index': [df.iloc[i].name] * len(ts)}))\n o = o[['time', 'expr', 'index']]\n return o\n\n\nclass draw_timecourse(object):\n \"\"\"docstring for draw_timecourse.\"\"\"\n\n def __init__(self, which):\n super(draw_timecourse, self).__init__()\n if isinstance(which, str):\n self.which = [which]\n elif isinstance(which, list):\n self.which = which\n else:\n raise TypeError\n self.h5file = r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\timecourse.h5\"\n\n def query_timecourse():\n tc = hdf.read(self.h5file)[0]\n return tc.loc[tc['index'].isin(self.which)]\n self.timecourse = query_timecourse()\n\n def draw(self, color=None, palette=None, legend_loc=None, rm_legend=False):\n if len(self.timecourse['index'].value_counts()) == 1:\n self.timecourse = self.timecourse[self.timecourse.columns[0:2]]\n g = plot(self.timecourse, color=color, palette=palette, pointplot=True)\n if legend_loc is not None:\n g.axes.legend(loc='center right', bbox_to_anchor=(1.6, 0.5))\n if rm_legend == True:\n g.axes.legend().remove()\n self.fig = g\n\n# h = hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\jiaoshenmehaoen.h5\")[0]\n# test = h[h.columns[-8:]]\n\n\n# def query_timecourse(which=['lSSLsLNLSNQPAAIAAR']):\n# tc=hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\timecourse.h5\")[0]\n# return tc.loc[tc['index'].isin(which)]\n\ndef batch_draw_timecourse(df, df_pos=None, outputroot=r'C:\\Users\\evans\\Dropbox\\Shade\\figures\\FIGURE4\\\\'):\n\n if df_pos == True:\n df_pos = pd.read_csv(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\Profile_all2076_B_withlocation.csv\", index_col=0)\n if 'Annotations' in df.columns:\n for i in df.index:\n if df.loc[i]['label'] == 1:\n colr = '#3c6d95'\n else:\n colr = '#ad4a32'\n\n dtc = draw_timecourse(\n which=i)\n\n dtc.draw(color=colr,\n legend_loc='1', rm_legend=False)\n anno = df.loc[i, 'Annotations']\n if not df_pos is None:\n site = df_pos.loc[i, 'Phospho']\n pos = df_pos.loc[i, 'Location']\n # dtc.fig.axes.legend(['{}_{}{}'.format(anno, site, pos)])\n dtc.fig.set_title('{}_{}{}'.format(anno, site, pos))\n else:\n # dtc.fig.axes.legend([anno])\n dtc.fig.set_title(anno)\n\n anno = anno.replace('/', '_')\n dtc.fig.set_ylim(0, 2)\n dtc.fig.set_xlabel('')\n dtc.fig.set_ylabel('')\n dtc.fig.get_figure().savefig('{}{}_{}.png'.format(outputroot, anno, i))\n else:\n raise RuntimeError('Annotations not in df.columns')\n\n\nif __name__ == '__main__':\n # sns.set(font_scale=2.5, style=\"white\", color_codes=True)\n # sigs = hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\sigs.h5\")[0]\n # batch_draw_timecourse(sigs, df_pos=True)\n # sigs\n\n sigs = hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\jiaoshenmehaoen.h5\")[0]\n # endomemberane system\n # sigs=sigs.loc[['gSSGISDDMESSsPR','aEsISDLENk','ssDSLSGTNELLNINSETPMk','ssSDVQMTk','tQsLNPk','SDVsSPEAk','sEsLGHR','lEASYsV','nISGSMQsPR','sDsQSELSSGNSDALAIEQR']]\n\n sigs\n sigs['label'] = 1\n batch_draw_timecourse(sigs, df_pos=True)\n\n # dtc = draw_timecourse(\n # which=['gSSGISDDMESSsPR','aEsISDLENk','ssDSLSGTNELLNINSETPMk','ssSDVQMTk','tQsLNPk','SDVsSPEAk','sEsLGHR','lEASYsV','nISGSMQsPR','sDsQSELSSGNSDALAIEQR'])\n # dtc.draw(color=None, legend_loc='1', rm_legend=False)\n\n # hdf.read(r\"C:\\Users\\evans\\Dropbox\\Shade\\raw\\timecourse.h5\")[0]\n #\n # hdf.read(filename)\n","sub_path":"drawlines.py","file_name":"drawlines.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333234276","text":"import os\nimport numpy as np\nimport random\n\nfrom Image import Image\n\nclass Classifier:\n SIDE_SIZE = 1\n K = 10\n TRAIN_SIZE = 20 # Number of probes that will be taken from every image in train set\n TRAIN_PATH = 'assets/training_set/'\n test_image = None\n\n def __init__(self):\n # We assume that files in 'original' directory have the same names as files in 'result' directory\n # Get file names and read files\n file_names = os.listdir(self.TRAIN_PATH + 'original/')\n self.training_cases = []\n for name in file_names:\n image = Image(self.TRAIN_PATH, name)\n for _ in range(self.TRAIN_SIZE):\n self.training_cases.append(image.random_sample(self.SIDE_SIZE))\n\n def process_image(self, image):\n self.test_image = image\n result_image = [[0 for _ in range(image.COLS)] for _ in range(image.ROWS)]\n for row in range(self.SIDE_SIZE, image.ROWS -1 - self.SIDE_SIZE):\n print(row)\n for column in range(self.SIDE_SIZE, image.COLS -1 - self.SIDE_SIZE):\n result_image[row][column] = self.classify(row, column)\n return result_image\n\n def classify(self, row, column):\n # Get all comparison results\n comparison_results = []\n image_tuple = self.test_image.create_tuple(row, column, self.SIDE_SIZE)\n for case in self.training_cases:\n comparison = case.compare(image_tuple)\n comparison_results.append((comparison, case.result))\n # Sort results and get K best results\n comparison_results.sort()\n comparison_results = comparison_results[:self.K]\n # Take average value from results.\n mean = np.mean([r[1] for r in comparison_results])\n return mean\n\n","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"393553195","text":"#!/usr/bin/env python3\n\nimport objects_3d\nimport random\nimport pygame\nfrom pygame.locals import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nface = []\nverticies = []\nedge = []\n\ndef draw():\n\n obj_count = 7\n pyramids = [ objects_3d.Pyramid() for _ in range(obj_count)]\n\n glBegin(GL_LINES)\n\n for py in pyramids:\n\n #box.resize(f_hight= random.random() * 4)\n #print(box.info())\n\n for pol in py.polygons():\n py.info()\n print(\"pol:\",pol)\n glVertex3fv(pol[0])\n glVertex3fv(pol[1])\n\n glEnd()\n\n \ndef move():\n glTranslatef(0.01, 0.01, 0.01)\n\ndef scale():\n glScalef(1.01, 1.01, 1.01)\n\ndef turn():\n glRotatef(1, 3, 1, 3)\n\n\ndef main():\n pygame.init()\n display = (1000,800)\n pygame.display.set_mode(display, DOUBLEBUF|OPENGL)\n gluPerspective(145, (display[0]/display[1]), 0.1, 50.0)\n glTranslatef(0.0,0.0, -5)\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n draw()\n# gen_lines()\n# move()\n turn()\n# scale()\n pygame.display.flip()\n pygame.time.wait(10)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pyramide_test.py","file_name":"pyramide_test.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"381300368","text":"\"\"\"CMPT 370 Group 5 Project: NAME (Nearly Analogous Music Engine)\n Credits: Michael Coquet\n Elizabeth Reid\n Ben Camplin\n Laurence Craig Garcia\n Sean Warren\n\"\"\"\n# imports\nimport spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\nfrom name.backend_classes.song import Artist\nfrom name.backend_classes.song import Album\nfrom name.backend_classes.song import Song\nfrom name.backend_classes.song import SongDetails\nfrom name.backend_classes.playlist import Playlist\n\n\nclass SpotifyAPIManager:\n\n def __init__(self):\n \"\"\" Instantiation function. Sets up all required attributes\n for the authorization code flow.\n \"\"\"\n self.client_id = \"0e48c2ec84d3401e9262a2159a277d82\"\n self.client_secret = \"aa650130a5b544598f4b058bfd264b21\"\n self.redirect_uri = \"http://127.0.0.1:8080/callback/q\"\n self.scopes = '''user-read-recently-played user-top-read playlist-modify-public\n playlist-modify-private playlist-read-private'''\n # default auth manager for a guest\n self.auth_manager = SpotifyClientCredentials(client_id=self.client_id,\n client_secret=self.client_secret)\n # sets the default connection to the API\n self.spotify = spotipy.Spotify(auth_manager=self.auth_manager)\n\n def link_spotify_account(self):\n \"\"\" Attempts to log in to Spotify.\n Returns: True if successful, False otherwise.\n \"\"\"\n try:\n # reset the auth manager for Authorization\n self.auth_manager = SpotifyOAuth(client_id=self.client_id,\n client_secret=self.client_secret,\n redirect_uri=self.redirect_uri,\n scope=self.scopes)\n # attempt to get log in credentials from a user\n response = self.auth_manager.get_auth_response(open_browser=True)\n code = self.auth_manager.parse_response_code(response)\n token = self.auth_manager.get_access_token(code, as_dict=False)\n # reset the connection to the API, providing the new auth value\n self.spotify = spotipy.Spotify(auth=token, auth_manager=self.auth_manager)\n return True\n except:\n print(\"Failed to link account.\")\n # reset the auth manager back to the guest format\n self.auth_manager = SpotifyClientCredentials(client_id=self.client_id,\n client_secret=self.client_secret)\n return False\n\n def get_user_id(self):\n \"\"\" Gets the user_id if the user is logged in to Spotify. \"\"\"\n try:\n user_id = self.spotify.current_user()[\"id\"]\n return user_id\n except:\n # Either the user is a guest, or the api request failed\n return None\n\n def search_songs(self, song_list, offset=0):\n \"\"\" Searches the spotify api for the given list of songs.\n song_list: list of songs to search for.\n offset: offset of song results to return. Defaults to 0, which\n would return the first page (e.g. first 10 songs).\n returns: a dictionary with the song titles from song list,\n as well as a list of dictionaries containing info for all\n the songs that were returned for that song title\n \"\"\"\n search_results = {\"query title\": [],\n \"found songs\": []}\n for song in song_list:\n search_results[\"query title\"].append(song)\n result = self.spotify.search(q=song, limit=10, type=\"track\", offset=offset)\n # go through list of found songs and save results\n # in the dictionary\n for found_song in result[\"tracks\"][\"items\"]:\n song_info = {\"name\": found_song[\"name\"],\n \"id\": found_song[\"id\"],\n \"artists\": found_song[\"artists\"],\n \"album\": found_song[\"album\"]}\n # get song details for the song\n song_details = self.get_audio_features(found_song[\"id\"])\n # convert to a Song object\n song = Song(song_info, song_details)\n search_results[\"found songs\"].append(song)\n return search_results\n\n def get_album(self, id):\n \"\"\" Given an album id, search for album info\n and return an Album object.\n id: string value of the album id\n returns: an album object.\n \"\"\"\n album_data = self.spotify.album(id)\n album = Album(album_data)\n return album\n\n def get_artist(self, id):\n \"\"\" Given an artist id, search for artist info\n and return an Artist object.\n id: string value of the artist id\n returns: an artist object.\n \"\"\"\n artist_data = self.spotify.artist(id)\n artist = Artist(artist_data)\n return artist\n\n def get_audio_features(self, id):\n \"\"\" Gets audio features for the given song id\n id: a song id (string)\n returns: a SongDetails object\n \"\"\"\n features = self.spotify.audio_features(tracks=[id])[0]\n if features == None:\n return SongDetails(details={\"duration_ms\": 0,\n \"key\": 0,\n \"tempo\": 0,\n \"danceability\": 0,\n \"energy\": 0,\n \"loudness\": 0,\n \"mode\": 0,\n \"speechiness\": 0,\n \"acousticness\": 0,\n \"instrumentalness\": 0,\n \"liveness\": 0,\n \"valence\": 0,\n \"time_signature\": 0})\n\n song_details = SongDetails(features)\n return song_details\n\n def create_playlist_object(self, playlist_data):\n \"\"\" Given the json object Spotify returns as a playlist,\n convert it to one of our Playlist objects.\n playlist_data: a json formatted spotify playlist\n \"\"\"\n songs = self.spotify.playlist_items(playlist_data[\"id\"])[\"items\"]\n songs_list = []\n # Get the tracks of the playlist\n for song in songs:\n song_details = self.get_audio_features(song[\"track\"][\"id\"])\n songs_list.append(Song(song[\"track\"], song_details))\n # Convert into Playlist Object\n playlist = Playlist(playlist_data, songs_list)\n return playlist\n\n def get_member_playlists(self):\n \"\"\" Gets a list of all playlists for the current user.\n returns: a list of playlist objects\n \"\"\"\n # make sure the auth token is valid and refresh if needed\n self.refresh_auth_token()\n # get the playlists\n user_id = self.get_user_id()\n playlists_data = self.spotify.user_playlists(user_id)\n # convert to a list of playlist objects\n playlist_list = []\n for playlist_data in playlists_data[\"items\"]:\n playlist = self.create_playlist_object(playlist_data)\n playlist_list.append(playlist)\n return playlist_list\n\n def add_member_playlist(self, playlist):\n \"\"\" Saves the given playlist object to the\n the playlist owner's Spotify account.\n playlist: a playlist object\n returns: A copy of the new playlist object that was created\n (for verification purposes)\n \"\"\"\n # Make sure the access token is valid and refresh if needed\n self.refresh_auth_token()\n # First, create a new empty playlist in spotify\n user_id = self.get_user_id()\n playlist_name = playlist.playlist_name\n description = \"A N.A.M.E. similarity playlist\"\n new_playlist = self.spotify.user_playlist_create(user=user_id, name=playlist_name,\n description=description)\n new_playlist_id = new_playlist[\"id\"]\n # Get spotify track objects for each song in the given playlist\n ids = [song.id for song in playlist.songs]\n # Add all the tracks to the new playlist\n self.spotify.playlist_add_items(new_playlist_id, ids)\n return self.create_playlist_object(new_playlist)\n\n def get_recently_played_songs(self, limit):\n \"\"\" Gets a list of the current member's last played tracks\n limit: the total number of tracks to return\n returns: a list of up to the limit of song objects\n \"\"\"\n # Make sure the access token is valid and refresh if needed\n self.refresh_auth_token()\n # Get recent tracks\n recent_tracks = self.spotify.current_user_recently_played(limit)\n # convert to song objects\n songs = []\n for track in recent_tracks[\"items\"]:\n song_details = self.get_audio_features(track[\"track\"][\"id\"])\n song = Song(track[\"track\"], song_details)\n # don't add duplicates to the list\n if len(songs) == 0 or song.song_name not in [song.song_name for song in songs]:\n songs.append(song)\n return songs\n\n def get_top_songs(self):\n \"\"\" Gets a list of the current member's top tracks.\n The maximum number that can be returned is 20.\n returns: at most a list of 20 song objects\n \"\"\"\n # Make sure the access token is valid and refresh if needed\n self.refresh_auth_token()\n # Get top tracks\n top_tracks = self.spotify.current_user_top_tracks()\n # convert to song objects\n songs = []\n for track in top_tracks[\"items\"]:\n song_details = self.get_audio_features(track[\"id\"])\n song = Song(track, song_details)\n # don't add duplicates to the list\n if len(songs) == 0 or song.song_name not in [song.song_name for song in songs]:\n songs.append(song)\n return songs\n\n def get_top_artists(self):\n \"\"\" Gets a list of the current member's top artists.\n The maximum number that can be returned is 20.\n returns: at most a list of 20 artist objects.\n \"\"\"\n # Make sure the access token is valid and refresh if needed\n self.refresh_auth_token()\n # Get top artists\n top_artists = self.spotify.current_user_top_artists()\n # convert to artists objects\n artists = []\n for artist in top_artists[\"items\"]:\n new_artist = self.get_artist(artist[\"id\"])\n # don't add duplicates to the list\n if len(artists) == 0 or new_artist.name not in [artist.name for artist in artists]:\n artists.append(new_artist)\n return artists\n\n def get_song_genres(self, song):\n \"\"\" Given a song object, find all the genres\n associated with the song.\n song: a song object\n returns: a list of genres (strings)\n \"\"\"\n # to get genres, we need to look at the artist info\n artists = song.song_artist\n # get a list of genres for each artist\n genres = []\n for artist in artists:\n artist_info = self.spotify.artist(artist.id)\n genres.extend(artist_info[\"genres\"])\n return genres\n\n def refresh_auth_token(self):\n \"\"\" Checks to see if the member's auth token is\n expired or not. If it is expired, creates a new auth token.\n \"\"\"\n token = self.auth_manager.get_cached_token()\n expired = self.auth_manager.is_token_expired(token)\n if expired:\n self.auth_manager.refresh_access_token(token[\"refresh_token\"])\n","sub_path":"name/backend_classes/spotify_api_manager.py","file_name":"spotify_api_manager.py","file_ext":"py","file_size_in_byte":12015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"533539186","text":"from itertools import product\nfrom functools import reduce\nfrom copy import deepcopy\n\nfrom variables import Vars\n\n\n\ndef deriv_penalty(func, var):\n n = len(var.points)\n derivs = {\n (v, i): func.penalty_deriv_by(var.get_var(v, i))\n for v, i in all_vars(n)\n }\n \n def derivative_by_var(arg_var, coef):\n v = coef * Vars(\n [\n (derivs['x', i](arg_var), derivs['y', i](arg_var))\n for i in range(n)\n ],\n (derivs['a', 0](arg_var), derivs['b', 0](arg_var))\n )\n # print(v)\n return v\n return derivative_by_var\n\n\ndef deriv(func, var):\n n = len(var.points)\n derivs = {\n (v, i): func.deriv_by(var.get_var(v, i))\n for v, i in all_vars(n)\n }\n \n def derivative_by_var(arg_var):\n v = Vars(\n [\n (derivs['x', i](arg_var), derivs['y', i](arg_var))\n for i in range(n)\n ],\n (derivs['a', 0](arg_var), derivs['b', 0](arg_var))\n )\n # print(v)\n return v\n return derivative_by_var\n \n\ndef get_penalty(penalties):\n def penalty(var, params):\n return sum([\n params.get_parameter(g) * g.penalty(var) for g in penalties\n ])\n\n return penalty\n\n\ndef get_sum_of_func(funcs):\n return lambda var, params: reduce(\n lambda x, y: x + y,\n map(lambda f: f(var, params.get_parameter(f)), funcs)\n )\n","sub_path":"src/packing/penalty_method/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"460251416","text":"import numpy as np\nfrom netCDF4 import Dataset\nimport pylab as plt\nimport os\nimport time\nfrom units import unit\nfrom units.predefined import define_units\nimport datetime\nfrom mpl_toolkits.basemap import Basemap\nimport netCDF4 as nc\nimport math\nfrom urllib.request import urlretrieve\nfrom scipy.interpolate import griddata\nfrom subroutines import *\n\n# set up Data directory\nDataDir = \"/Users/mingquan/newDATA\"\n\n# set up initial and final years of data\nstart_yr = 2000\nend_yr = 2018\n\nVarID = \"rlds\"\nRawVarID = \"sfc_lw_down_all_mon\"\nstandard_name = \"surface downwelling longwave radiation\"\n\n# Set general information for the data source\nremote_source = \"https://ceres.larc.nasa.gov/products-info.php?product=EBAF\"\ngist_source = \"https://github.com/mmu2019/Datasets/blob/master/read-llds-ceres.py\"\nlocal_source = 'CERES_EBAF_Ed4.1_Subset_200003-201809.nc'\nstamp1 = '2019-06-25'\n\ndatestr = str(datetime.datetime.now())\nTmpStr = datestr.split(' ')\nstamp2 = TmpStr[0]\n\n# set up institutions where created the original dataset\nsourceID = \"CERES.ed4.1\"\ninstit1 = \"NASA Langley Research Center\"\n\n# Create temporal dimension\nnyears = end_yr - start_yr + 1\nnmonth = 12\nsmonth = np.asarray(['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'])\nmonth_bnd = np.asarray([0,31,59,90,120,151,181,212,243,273,304,334,365],dtype=float)\ntbnd = np.asarray([((np.arange(nyears)*365)[:,np.newaxis]+month_bnd[:-1]).flatten(),\n ((np.arange(nyears)*365)[:,np.newaxis]+month_bnd[+1:]).flatten()]).T\ntbnd += (start_yr - 1850)*365\ntbnd.shape\nt = tbnd.mean(axis=1)\n\n# set up the temporal and spatial resolutions for the original and final dataset\nperiod = str(start_yr) + \"-01 through \" + str(end_yr) + \"-12\"\norigtr = \"monthly\"\norigsr = \"1 degree\"\norigut = \"W m-2\"\nfinltr = \"monthly\"\nfinlsr = \"0.5 degree\"\nfinlut = \"W m-2\"\n\n# Create new spatial dimension\nres = 0.5\nlatbnd = np.asarray([np.arange(- 90 , 90 ,res),\n np.arange(- 90+res, 90+0.01,res)]).T\nlonbnd = np.asarray([np.arange(-180 ,180 ,res),\n np.arange(-180+res,180+0.01,res)]).T\nlat = latbnd.mean(axis=1)\nlon = lonbnd.mean(axis=1)\n\n# Create some fake data\ndata = np.ma.masked_array(np.random.rand(t.size,lat.size,lon.size))\n\ndata[:,:,:] = -999\n\nntim = t.size\nnlat = lat.size\nnlon = lon.size\n\n# read single netCDF file\nfilename = DataDir + '/' + sourceID + '/' + local_source\nprint(filename)\ngpcp=Dataset(filename,'r',format='NETCDF3')\nprint(gpcp) \nprint(gpcp.variables) \n\ntime1= gpcp.variables['time']\nlat1 = gpcp.variables['lat']\nlon1 = gpcp.variables['lon']\npr1 = gpcp.variables[RawVarID]\nlong_name = pr1.long_name\noriginal_unit = pr1.units\n\nntim1 = time1.size\nnlat1 = lat1.size\nnlon1 = lon1.size\n\n# convert lon1 from 0-360 to 180W-180E\nif lon1[0]>0:\n nlon12=int(nlon1/2)\n lon0 = np.ma.masked_array(np.random.rand(nlon1), type=lon1.dtype)\n pr0 = np.ma.masked_array(np.random.rand(ntim1,nlat1,nlon1), dtype=pr1.dtype)\n\n print(pr1.dtype)\n print(pr0.dtype)\n for i in range(nlon12):\n lon0[i] = lon1[i] - 180.0\n lon0[i+nlon12] = lon1[i+nlon12] - 180.0\n pr0[:,:,i] = pr1[:,:,i+nlon12]\n pr0[:,:,i+nlon12] = pr1[:,:,i]\n\n del pr1\n del lon1\n lon1 = lon0\n pr1 = pr0\n del pr0\n del lon0\n\n# cut data in the required period\npr = np.ma.masked_array(np.random.rand(t.size,lat1.size,lon1.size))\npr[:,:,:] = -999.\npr[2:2+ntim1,:,:] = pr1[:,:,:]\n\nij = 0\nfor i in range(nyears):\n year = i + start_yr\n for j in range(nmonth):\n temp = pr[ij,:,:]\n data[ij,:,:] = NearestNeighborInterpolation(lat1,lon1,temp,lat,lon)\n ij = ij + 1\n\ndata_min = data.min()\ndata_max = data.max()\n\nwith Dataset(DataDir + \"/rlds.nc\", mode=\"w\") as dset:\n\n # Create netCDF dimensions\n dset.createDimension(\"time\",size= t.size)\n dset.createDimension(\"lat\" ,size=lat.size)\n dset.createDimension(\"lon\" ,size=lon.size)\n dset.createDimension(\"nb\" ,size=2 )\n\n # Create netCDF variables\n T = dset.createVariable(\"time\" ,t.dtype ,(\"time\" ))\n TB = dset.createVariable(\"time_bounds\",t.dtype ,(\"time\",\"nb\"))\n X = dset.createVariable(\"lat\" ,lat.dtype ,(\"lat\" ))\n XB = dset.createVariable(\"lat_bounds\" ,lat.dtype ,(\"lat\",\"nb\" ))\n Y = dset.createVariable(\"lon\" ,lon.dtype ,(\"lon\" ))\n YB = dset.createVariable(\"lon_bounds\" ,lon.dtype ,(\"lon\",\"nb\" ))\n D = dset.createVariable(VarID ,data.dtype,(\"time\",\"lat\",\"lon\"), fill_value = -999.)\n\n print(D.shape)\n\n # Load data and encode attributes\n # time\n T [...] = t\n T.units = \"days since 1850-01-01\"\n T.calendar = \"noleap\"\n T.bounds = \"time_bounds\"\n TB[...] = tbnd\n T.standard_name = \"time\"\n T.long_name = \"time\"\n\n # lat\n X [...] = lat\n X.units = \"degrees_north\"\n XB[...] = latbnd\n X.standard_name = \"latitude\"\n X.long_name = \"latitude\"\n\n # lon\n Y [...] = lon\n Y.units = \"degrees_east\"\n YB[...] = lonbnd\n Y.standard_name = \"longitude\"\n Y.long_name = \"longitude\"\n\n # data\n D[...] = data\n D.units = \"W m-2\"\n D.standard_name = standard_name\n D.long_name = long_name\n D.actual_range = np.asarray([data_min,data_max])\n\n dset.title = \"CERES EBAF TOA and Surface Fluxes\"\n dset.version = \"Ed4.1\"\n dset.institutions = \"%s\" % (instit1)\n dset.source = \"Monhtly mean surface fluxes calculated by a radiative transfer model and constrained by the combined Terra and Aqua SSF1deg measurements\"\n dset.history = \"\"\"\n%s: downloaded source from %s;\n%s: converted to netCDF with %s\"\"\" % (stamp1, remote_source, stamp2, gist_source)\n dset.references = \"\"\"\n@ARTICLE{Loeb2018,\n author = {Loeb, N.G., D.R. Doelling, H. Wang, W. Su, C. Nguyen, J.G. Corbett, L. Liang, C. Mitrescu, F.G. Rose, and S. Kato},\n title = {Clouds and the Earth's Radiant Energy System (CERES) Energy Balanced and Filled (EBAF) Top-of-Atmosphere (TOA) Edition-4.0 Data Product},\n journal = {Journal of Climate},\n year = {2018},\n number = {31(2)},\n page = {895-918},\n doi = {https://doi.org/10.1175/JCLI-D-17-0208.1}\n}\n@ARTICLE{Kato2018,\n author = {Kato, S., F. G. Rose, D. A. Rutan, T. E. Thorsen, N. G. Loeb, D. R. Doelling, X. Huang, W. L. Smith, W. Su, and S.-H. Ham},\n title = {Surface irradiances of Edition 4.0 Clouds and the Earth's Radiant Energy System (CERES) Energy Balanced and Filled (EBAF) data product},\n journal = {Journal of Climate},\n year = {2018},\n number = {31},\n page = {4501-4527},\n doi = {https://doi.org/10.1175/JCLI-D-17-0523.1}\n}\"\"\"\n dset.comments = \"\"\"\ntime_period: %s; original_temporal_resolution: %s; original_spatial_resolution: %s; original_units: %s; final_temporal_resolution: %s; final_spatial_resolution: %s; final_units: %s\"\"\" % (period, origtr, origsr, origut, finltr, finlsr, finlut)\n dset.convention = \"CF-1.7\"\n","sub_path":"read-rlds-ceres.py","file_name":"read-rlds-ceres.py","file_ext":"py","file_size_in_byte":6962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"450434959","text":"\"\"\" Pytest behavior customizations.\n\"\"\"\n\nimport os\nimport sys\nimport time\nimport re\n\nimport pytest\nfrom _pytest.terminal import TerminalReporter\n\nfrom config import load_config, default\nfrom reporting import ReportSingleton, TestFunction, TestReport\n\n\nclass AgentTerminalReporter(TerminalReporter):\n \"\"\" Customized PyTest Output \"\"\"\n @pytest.hookimpl(trylast=True)\n def pytest_sessionstart(self, session):\n self._session = session\n self._sessionstarttime = time.time()\n\n def pytest_runtest_logstart(self, nodeid, location):\n line = self._locationline(nodeid, *location)\n self.write_sep('=', line, bold=True)\n self.write('\\n')\n\n\ndef pytest_addoption(parser):\n \"\"\" Load in config path. \"\"\"\n group = parser.getgroup(\n \"Aries Protocol Test Suite Configuration\",\n \"Aries Protocol Test Suite Configuration\",\n after=\"general\"\n )\n group.addoption(\n \"--sc\",\n \"--suite-config\",\n dest='suite_config',\n action=\"store\",\n metavar=\"SUITE_CONFIG\",\n help=\"Load suite configuration from SUITE_CONFIG\",\n )\n group.addoption(\n \"-F\",\n \"--feature-select\",\n dest='select',\n action='store',\n metavar='SELECT_REGEX',\n help='Run tests matching SELECT_REGEX. '\n 'Overrides tests selected in configuration.'\n )\n group.addoption(\n \"-O\",\n \"--output\",\n dest=\"save_path\",\n action=\"store\",\n metavar=\"PATH\",\n help=\"Save interop profile to PATH.\"\n )\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config):\n \"\"\" Load Test Suite Configuration. \"\"\"\n dirname = os.getcwd()\n config_path = config.getoption('suite_config')\n config_path = 'config.toml' if not config_path else config_path\n config_path = os.path.join(dirname, config_path)\n print(\n '\\nLoading Agent Test Suite configuration from file: %s\\n' %\n config_path\n )\n\n try:\n config.suite_config = load_config(config_path)\n except FileNotFoundError:\n config.suite_config = default()\n config.suite_config['save_path'] = config.getoption('save_path')\n\n # register additional markers\n config.addinivalue_line(\n \"markers\", \"features(name[, name, ...]):\"\n \"Define what features the test belongs to.\"\n )\n config.addinivalue_line(\n \"markers\", \"priority(int): Define test priority for \"\n \"ordering tests. Higher numbers occur first.\"\n )\n\n # Override default terminal reporter for better test output\n reporter = config.pluginmanager.get_plugin('terminalreporter')\n agent_reporter = AgentTerminalReporter(config, sys.stdout)\n config.pluginmanager.unregister(reporter)\n config.pluginmanager.register(agent_reporter, 'terminalreporter')\n\n # Compile SELECT_REGEX if given\n select_regex = config.getoption('select')\n config.select_regex = re.compile(select_regex) if select_regex else None\n config.features = config.suite_config['features']\n\n\ndef pytest_collection_modifyitems(session, config, items):\n \"\"\" Select tests based on config or args. \"\"\"\n if not items:\n return\n\n def feature_filter(item):\n feature_names = [\n mark.args for mark in item.iter_markers(name=\"features\")\n ]\n feature_names = [item for sublist in feature_names for item in sublist]\n if feature_names:\n for selected_test in config.features:\n if selected_test in feature_names:\n item.selected_feature = selected_test\n return True\n\n return False\n\n def regex_feature_filter(item):\n feature_names = [\n mark.args for mark in item.iter_markers(name=\"features\")\n ]\n feature_names = [item for sublist in feature_names for item in sublist]\n for feature in feature_names:\n if config.select_regex.match(feature):\n item.selected_feature = feature\n return True\n\n return False\n\n def feature_priority_map(item):\n priorities = [\n mark.args[0] for mark in item.iter_markers(name=\"priority\")\n ]\n if priorities:\n item.priority = sorted(priorities, reverse=True)[0]\n else:\n item.priority = 0\n return item\n\n def priority_sort(item):\n return item.priority\n\n filtered_items = items\n if config.select_regex:\n filtered_items = filter(regex_feature_filter, filtered_items)\n if config.features:\n filtered_items = filter(feature_filter, filtered_items)\n\n priority_mapped_items = map(feature_priority_map, filtered_items)\n items[:] = sorted(priority_mapped_items, key=priority_sort, reverse=True)\n\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\" Customize reporting \"\"\"\n outcome = yield\n report = outcome.get_result()\n\n setattr(item, \"report_\" + report.when, report)\n\n term_reporter = item.config.pluginmanager.get_plugin('terminalreporter')\n if report.when == 'call' and report.failed:\n if hasattr(item, 'selected_feature'):\n term_reporter.write_sep(\n '=',\n 'Failure! Feature: %s, Test: %s' % (\n item.selected_feature,\n item.name\n ),\n red=True,\n bold=True\n )\n else:\n term_reporter.write_sep(\n '=',\n 'Failure! Test: %s' % item.name,\n red=True,\n bold=True\n )\n report.toterminal(term_reporter.writer)\n\n\ndef pytest_terminal_summary(terminalreporter, exitstatus, config):\n \"\"\"Write Interop Profile to terminal summary.\"\"\"\n terminalreporter.write('\\n')\n terminalreporter.write_sep('=', 'Interop Profile', bold=True, yellow=True)\n terminalreporter.write('\\n')\n terminalreporter.write(ReportSingleton(config.suite_config).to_json())\n terminalreporter.write('\\n')\n\n\n@pytest.fixture(scope='session')\ndef report(config):\n \"\"\"Report fixture.\"\"\"\n report_instance = ReportSingleton(config)\n yield report_instance\n save_path = config.get('save_path')\n if save_path:\n report_instance.save(save_path)\n\n\n@pytest.fixture\ndef report_on_test(request, recwarn, report):\n \"\"\"Universally loaded fixture for getting test reports.\"\"\"\n yield\n passed = False\n if hasattr(request.node, 'report_call') and \\\n request.node.report_call.outcome == 'passed':\n passed = True\n\n report.add_report(\n TestReport(\n TestFunction(\n protocol=request.function.protocol,\n version=request.function.version,\n role=request.function.role,\n name=request.function.name,\n description=request.function.__doc__\n ),\n passed,\n recwarn.list\n )\n )\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278763002","text":"import argparse\nimport jpeg\nimport wav\nfrom os import path\n\nif __name__ == \"__main__\":\n\n p = argparse.ArgumentParser()\n p.add_argument(\"file\", type=str, help=\"name/path of the input file\")\n p.add_argument(\"-w\", action=\"store_true\", help=\"extract and parse WAV files\")\n p.add_argument(\"-j\", action=\"store_true\", help=\"extract and parse JPEG files\")\n args = p.parse_args()\n\n if path.exists(args.file):\n if not path.isfile(args.file):\n raise Exception(\"Given path is not a file!\")\n else:\n raise Exception(\"Given path does not exist!\")\n\n if args.w:\n carved = wav.carve_wav(args.file)\n print(\"List of Sizes of Carved WAVs: %s\" % ([len(x) for x in carved]))\n for i, x in enumerate(carved):\n print(\"Parsed WAV %s Headers: %s\" % (i, wav.parse_wav_header(carved[i])))\n\n if args.j:\n carved = jpeg.carve_jpeg(args.file)\n print(\"List of Sizes of Carved JPEGs: %s\" % ([len(x) for x in carved]))\n for i, x in enumerate(carved):\n print(\"Parsed JPEG %s EXIF Data: %s\" % (i, jpeg.parse_exif(carved[i])))\n","sub_path":"Assignment 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"41095135","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pytest\nfrom click.testing import CliRunner\nfrom jak.app import main as jak\nimport jak.crypto_services as cs\nfrom jak.compat import b\n\n\n@pytest.fixture\ndef runner():\n return CliRunner()\n\n\ndef test_empty(runner):\n result = runner.invoke(jak)\n assert result.exit_code == 0\n assert not result.exception\n\n\n@pytest.mark.parametrize('version_flag', ['--version', '-v'])\ndef test_version(runner, version_flag):\n result = runner.invoke(jak, [version_flag])\n assert not result.exception\n assert result.exit_code == 0\n assert '(Troubled Toddler)' in result.output.strip()\n\n\n@pytest.mark.parametrize('cmd, filepath', [\n ('encrypt', 'filethatdoesnotexist'),\n ('decrypt', 'filethatdoesnotexist2')])\ndef test_file_not_found(runner, cmd, filepath):\n result = runner.invoke(jak, [cmd, filepath, '-k', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'])\n assert 'find the file:' in result.output\n\n\ndef test_encrypt_smoke(runner):\n \"\"\"This one has proven to be an absolute godsend for finding\n weirdness, especially between python versions.\"\"\"\n with runner.isolated_filesystem():\n with open('secret.txt', 'wb') as f:\n f.write(b('secret'))\n runner.invoke(jak,\n ['encrypt',\n os.path.abspath('secret.txt'),\n '--key',\n 'f40ec5d3ef66166720b24b3f8716c2c31ffc6b45295ff72024a45d90e5fddb56'])\n\n with open('secret.txt', 'rb') as f:\n result = f.read()\n assert b(cs.ENCRYPTED_BY_HEADER) in result\n\n\ndef test_decrypt_smoke(runner):\n contents = '''- - - Encrypted by jak - - -\n\nSkFLLTAwMHM0jlOUIaTUeVwbfS459sfDJ1SUW9_3wFFcm2rCxTnLvy1N-Ndb\nO7t2Vcol566PnyniPGn9IadqwWFNykZdaycRJG7aL8P4pZnb4gnJcp08OLwR\nLiFC7wcITbo6l3Q7Lw=='''\n with runner.isolated_filesystem():\n\n with open('secret.txt', 'w') as f:\n f.write(contents)\n\n runner.invoke(jak,\n ['decrypt',\n os.path.abspath('secret.txt'),\n '--key',\n 'f40ec5d3ef66166720b24b3f8716c2c31ffc6b45295ff72024a45d90e5fddb56'])\n\n with open('secret.txt', 'rb') as f:\n result = f.read()\n assert b(cs.ENCRYPTED_BY_HEADER) not in result\n assert result.strip(b('\\n')) == b('attack at dawn')\n","sub_path":"tests/test_jak.py","file_name":"test_jak.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"539406141","text":"import gdsfactory as gf\nfrom gdsfactory.components.bend_euler import bend_euler\nfrom gdsfactory.components.contact import contact_heater_m3\nfrom gdsfactory.components.coupler_ring import coupler_ring as _coupler_ring\nfrom gdsfactory.components.straight import straight as _straight\nfrom gdsfactory.types import ComponentFactory, CrossSectionFactory, Float2\n\ncontact_heater_m3_mini = gf.partial(contact_heater_m3, size=(4, 4))\n\n\n@gf.cell\ndef ring_single_heater(\n gap: float = 0.2,\n radius: float = 10.0,\n length_x: float = 4.0,\n length_y: float = 0.6,\n coupler_ring: ComponentFactory = _coupler_ring,\n straight: ComponentFactory = _straight,\n bend: ComponentFactory = bend_euler,\n cross_section_heater: CrossSectionFactory = gf.cross_section.strip_heater_metal,\n cross_section: CrossSectionFactory = gf.cross_section.strip,\n contact: ComponentFactory = contact_heater_m3_mini,\n port_orientation: float = 90,\n contact_offset: Float2 = (0, 0),\n **kwargs\n) -> gf.Component:\n \"\"\"Single bus ring made of a ring coupler (cb: bottom)\n connected with two vertical straights (sl: left, sr: right)\n two bends (bl, br) and horizontal straight (wg: top)\n includes heater\n\n Args:\n gap: gap between for coupler\n radius: for the bend and coupler\n length_x: ring coupler length\n length_y: vertical straight length\n coupler_ring: ring coupler function\n straight: straight function\n bend: 90 degrees bend function\n cross_section_heater:\n cross_section:\n contact:\n port_orientation: for electrical ports to promote from contact\n kwargs: cross_section settings\n\n\n .. code::\n\n bl-st-br\n | |\n sl sr length_y\n | |\n --==cb==-- gap\n\n length_x\n\n \"\"\"\n gf.snap.assert_on_2nm_grid(gap)\n\n coupler_ring = gf.partial(\n coupler_ring,\n bend=bend,\n gap=gap,\n radius=radius,\n length_x=length_x,\n cross_section=cross_section,\n bend_cross_section=cross_section_heater,\n **kwargs\n )\n\n straight_side = gf.partial(\n straight, length=length_y, cross_section=cross_section_heater, **kwargs\n )\n straight_top = gf.partial(\n straight, length=length_x, cross_section=cross_section_heater, **kwargs\n )\n\n bend = gf.partial(bend, radius=radius, cross_section=cross_section_heater, **kwargs)\n\n c = gf.Component()\n cb = c << coupler_ring()\n sl = c << straight_side()\n sr = c << straight_side()\n bl = c << bend()\n br = c << bend()\n st = c << straight_top()\n # st.mirror(p1=(0, 0), p2=(1, 0))\n\n sl.connect(port=\"o1\", destination=cb.ports[\"o2\"])\n bl.connect(port=\"o2\", destination=sl.ports[\"o2\"])\n\n st.connect(port=\"o2\", destination=bl.ports[\"o1\"])\n br.connect(port=\"o2\", destination=st.ports[\"o1\"])\n sr.connect(port=\"o1\", destination=br.ports[\"o1\"])\n sr.connect(port=\"o2\", destination=cb.ports[\"o3\"])\n\n c.add_port(\"o2\", port=cb.ports[\"o4\"])\n c.add_port(\"o1\", port=cb.ports[\"o1\"])\n\n c1 = c << contact()\n c2 = c << contact()\n c1.xmax = -length_x / 2 + cb.x - contact_offset[0]\n c2.xmin = +length_x / 2 + cb.x + contact_offset[0]\n c1.movey(contact_offset[1])\n c2.movey(contact_offset[1])\n c.add_ports(c1.get_ports_list(orientation=port_orientation), prefix=\"e1\")\n c.add_ports(c2.get_ports_list(orientation=port_orientation), prefix=\"e2\")\n c.auto_rename_ports()\n return c\n\n\nif __name__ == \"__main__\":\n c = ring_single_heater(width=0.5, gap=1, layer=(2, 0), radius=10, length_y=1)\n print(c.ports)\n c.show(show_subports=False)\n\n # cc = gf.add_pins(c)\n # print(c.settings)\n # print(c.settings)\n # cc.show()\n","sub_path":"gdsfactory/components/ring_single_heater.py","file_name":"ring_single_heater.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320098370","text":"from contextlib import contextmanager\nfrom io import StringIO\n\nfrom django.core import management\nfrom django.core.management.base import BaseCommand\nfrom django.db import connection\n\n\ndef reset_db():\n \"\"\"\n Reset database to a blank state by removing all the tables and recreating them.\n \"\"\"\n with connection.cursor() as cursor:\n cursor.execute(\"select tablename from pg_tables where schemaname = 'public'\")\n tables = [row[0] for row in cursor.fetchall()]\n\n # Can't use query parameters here as they'll add single quotes which are not\n # supported by postgres\n for table in tables:\n cursor.execute('drop table \"' + table + '\" cascade')\n\n # Call migrate so that post-migrate hooks such as generating a default Site object\n # are run\n management.call_command(\"migrate\", \"--noinput\", stdout=StringIO())\n\n\nclass Command(BaseCommand):\n help = \"Reset the database and load test data\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"-y\",\n \"--yes\",\n action=\"store_true\",\n dest=\"force_yes\",\n default=False,\n help=\"Don't ask for confirmation.\",\n )\n\n @contextmanager\n def print_step(self, message):\n self.stdout.write(message, ending=\" \")\n self.stdout.flush()\n yield\n self.stdout.write(self.style.SUCCESS(\"OK\"))\n\n def handle(self, *args, **options):\n with self.print_step(\"Resetting the database...\"):\n reset_db()\n","sub_path":"{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/core/management/commands/fixturize.py","file_name":"fixturize.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"260555033","text":"from scipy.sparse import lil_matrix\nimport random\n\n\ndef tsv_to_matrix(f, rows=None, cols=None):\n \"\"\"\n Convert file in tsv format to a csr matrix\n \"\"\"\n # Read the size of our matrix\n # We know it can't be the best way to do that, but it is the simplest\n user_max_value = rows-1 if rows is not None else 0\n item_max_value = cols-1 if cols is not None else 0\n\n with open(f) as input_file:\n for line in input_file:\n u, i, _ = line.split(' ')\n u, i = int(u), int(i)\n\n if u > user_max_value:\n user_max_value = u\n\n if i > item_max_value:\n item_max_value = i\n\n # Building the matrix\n data = lil_matrix((user_max_value + 1, item_max_value + 1))\n\n with open(f) as input_file:\n for line in input_file:\n x, y, v = line.split(' ')\n x, y = int(x), int(y)\n v = float(v.strip())\n data[x, y] = v\n\n return data\n\ndef show_matplot_fig():\n \"\"\"\n Store and show an image from matplotlib that is in the context.\n\n We are using it to avoid installing several libraries only to show a graphic\n \"\"\"\n import PIL\n from matplotlib import pyplot as plt\n\n path = './img/test.png'\n\n plt.savefig(path)\n img = PIL.Image.open(path)\n img.show()\n\ndef split_train_test(file_tsv):\n \"\"\"\n Split a tsv file into two others:\n 1) Train file with 80 perc of the data\n 2) Test file with 20 perc of the data\n \"\"\"\n M = tsv_to_matrix(file_tsv)\n\n m, _ = M.shape\n\n train_list = []\n test_list = []\n\n for i in range(m):\n data = M[i].nonzero()[1]\n random.shuffle(data)\n\n # 80%\n mark = int(len(data) * 0.8)\n\n train = data[:mark]\n test = data[mark:]\n\n train_list.append(train)\n test_list.append(test)\n\n def store_matrix(data_list, ofile):\n result = []\n for i, data in enumerate(data_list):\n for d in data:\n result.append('%s %s %s' % (i, d, '1.0'))\n result = \"\\n\".join(result)\n\n f = open(ofile, 'w')\n f.write(result)\n f.close()\n\n file_without_ext = file_tsv.rsplit('.', 1)[0]\n file_train = '%s_train.tsv' % file_without_ext\n file_test = '%s_test.tsv' % file_without_ext\n\n store_matrix(train_list, file_train)\n store_matrix(test_list, file_test)\n mark = int(len(data) * 0.8)\n\n return file_train, file_test\n\ndef mm2csr(M, ofile):\n \"\"\"\n Convert a matrix to a csr file in the format specified in:\n http://www-users.cs.umn.edu/~xning/slim/html/index.html#examples\n \"\"\"\n m, n = M.shape\n\n fhdl = open(ofile, 'w')\n for i in range(m):\n line = []\n for z in M[i].nonzero()[0]:\n # .csr files begins with 1 and not zero, by this we put z+1\n line.append(str(z))\n # TODO: change it, SSLIM only accepts 1 or 0 values\n #line.append(str(M[i][z]))\n line.append(\"1\")\n line = \"%s\\n\" % \" \".join(line)\n fhdl.write(line)\n\n fhdl.close()\n\ndef generate_slices(total_columns):\n \"\"\"\n Generate slices that will be processed based on the number of cores\n available on the machine.\n \"\"\"\n from multiprocessing import cpu_count\n\n cores = cpu_count()\n\n segment_length = total_columns/cores\n\n ranges = []\n now = 0\n\n while now < total_columns:\n end = now + segment_length\n\n # The last part can be a little greater that others in some cases, but\n # we can't generate more than #cores ranges\n end = end if end + segment_length <= total_columns else total_columns\n ranges.append((now, end))\n now = end\n\n return ranges\n\n\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"331272509","text":"from django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nimport datetime # for checking renewal date range\nfrom django.contrib.auth.models import User\n\nfrom django import forms\n\n\nclass CreateBidForm(forms.Form):\n \"\"\"Form for a librarian to renew books.\n fields = ['text', 'type_bid', 'location', 'telephone_num', 'bider', 'maker', 'helper']\"\"\"\n text = forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'cols': 28, 'rows': 6}), label='Содержание')\n\n TYPE_OF_BID = (\n ('h', 'Железо'),\n ('c', 'Картридж'),\n ('pr', 'Принтер'),\n ('w', 'Сеть'),\n ('t', 'Телефон'),\n ('v', 'Вирусы'),\n ('s', 'Софт'),\n ('pa', 'Парус'),\n ('br', 'Бюрократия'),\n )\n\n boys = User.objects.all()\n\n type_bid = forms.ChoiceField(choices=TYPE_OF_BID, initial='h', label='Тип заявки')\n location = forms.CharField(max_length=200, initial='', required=False, label='Место')\n # location = models.ForeignKey('Location', on_delete=models.SET_NULL, null=True)\n telephone_num = forms.CharField(max_length=200, initial='', required=False, label='Телефон')\n # telephone_num = models.ForeignKey('Telephone', on_delete=models.SET_NULL, null=True)\n bider = forms.CharField(max_length=200, initial='', required=False, label='Заявитель')\n # bider = models.ForeignKey('Bider', on_delete=models.SET_NULL, null=True)\n maker = forms.ModelChoiceField(boys, required=False, label='Исполнитель')\n helper = forms.CharField(max_length=200, initial='', required=False, label='Ассистент')\n # helper = models.ManyToManyField('Helper')\n # time_creation = forms.DateTimeField()\n # time_start = forms.DateTimeField()\n # time_done = forms.DateTimeField()\n\n STATUS = (\n ('a', 'Принята'),\n ('w', 'В работе'),\n ('f', 'Выполнена'),\n )\n\n status = forms.ChoiceField(choices=STATUS, initial='a', label='Состояние')\n comment = forms.CharField(widget=forms.Textarea(attrs={'cols': 28, 'rows': 6}), max_length=200, initial='', required=False, label='Комментарий')\n result = forms.CharField(widget=forms.Textarea(attrs={'cols': 28, 'rows': 6}), max_length=300, initial='', required=False, label='Результат')\n\n def clean_location(self):\n data = self.cleaned_data['location']\n if data == \"\":\n raise ValidationError(_('Вы не указали место, в котором локализована проблема'))\n\n return data\n\n def clean_telephone_num(self):\n data = self.cleaned_data['telephone_num']\n if data == \"\":\n raise ValidationError(_('Вы не указали номер телефона для связи с заявителем'))\n return data\n\n\n def clean(self):\n cleaned_data = super(CreateBidForm, self).clean()\n status = cleaned_data.get(\"status\")\n result = cleaned_data.get(\"result\")\n maker = cleaned_data.get(\"maker\")\n\n if status == 'f' and result == '':\n raise ValidationError(_('Для завершения работы по заявке укажите результат работы'))\n if status in ('w', 'f') and maker is None:\n raise ValidationError(_('Для изменения статуса заявки укажите исполнителя'))\n\n\n\nclass CreateStickerForm(forms.Form):\n\n name = forms.CharField(initial='', required=False, widget=forms.TextInput(attrs={'size': 45}), label='Название')\n text = forms.CharField(initial='', required=False, widget=forms.Textarea(attrs={'cols': 44, 'rows': 6}), label='Содержание')\n\n def clean_name(self):\n data = self.cleaned_data['name']\n if data == \"\":\n raise ValidationError(_('Напишите хоть что-нибудь'))\n elif len(data) >= 100:\n raise ValidationError(_('Слишком много букв'))\n return data\n\n def clean_text(self):\n data = self.cleaned_data['text']\n if data == \"\":\n raise ValidationError(_('Напишите хоть что-нибудь'))\n elif len(data) >= 500:\n raise ValidationError(_('Слишком много букв'))\n return data\n\n\nclass SearchForm(forms.Form):\n query = forms.IntegerField(label='Введите номер заявки')\n # query = forms.CharField()\n","sub_path":"system/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"435328537","text":"from rest_framework.serializers import ModelSerializer, StringRelatedField, RelatedField\n\nfrom newspaper.models import Newspaper, Face, Column, Advert\nfrom companies.models import CustomUser\nfrom companies.api.serializers import UserDetailSeralizer\n\nfrom rest_framework.authtoken.models import Token\n\nfrom rest_framework.serializers import CharField, ValidationError\n\n\nclass NewspaperCreateFaceSerializer(ModelSerializer):\n \n class Meta:\n model = Face\n fields = [\n 'title',\n 'description',\n ]\n\n\nclass NewspaperCreateСolumnSerializer(ModelSerializer):\n \n class Meta:\n model = Column\n fields = [\n 'title',\n 'description',\n ]\n\n\nclass NewspaperCreateAdvertSerializer(ModelSerializer):\n \n class Meta:\n model = Advert\n fields = [\n 'text',\n ]\n\nclass NewspaperCreateSerializer(ModelSerializer):\n columns = NewspaperCreateСolumnSerializer(many=True)\n adverts = NewspaperCreateAdvertSerializer(many=True)\n token = CharField(allow_blank=True, required=False)\n \n class Meta:\n model = Newspaper\n fields = [\n 'name',\n 'description',\n 'premium',\n 'face_title',\n 'face_description',\n 'columns',\n 'adverts',\n 'token',\n ]\n \n def create(self, validated_data):\n \n token = validated_data['token']\n\n if Token.objects.filter(key=token):\n token_obj = Token.objects.get(key=token)\n user = token_obj.user\n if user.user_type == \"user\":\n raise ValidationError(\"User can't create newspaper.\")\n else:\n raise ValidationError(\"Token doesn't exist.\")\n\n newspaper = Newspaper.objects.create(user=user,\n name=validated_data['name'],\n description=validated_data['description'],\n premium=validated_data['premium'],\n face_title=validated_data['face_title'],\n face_description=validated_data['face_description'],\n )\n for column in validated_data['columns']:\n colobj = Column.objects.create(title=column['title'],\n description=column['description'],\n )\n newspaper.columns.add(colobj)\n\n for advert in validated_data['adverts']:\n advobj = Advert.objects.create(text=advert['text'])\n newspaper.adverts.add(advobj)\n \n return newspaper\n\n\nclass NewspaperListSerializer(ModelSerializer):\n \n user = UserDetailSeralizer(read_only=True)\n \n class Meta:\n model = Newspaper\n fields = [\n 'id',\n 'user',\n 'name',\n 'description',\n 'premium',\n 'date',\n ]\n\n\nclass NewspaperFaceSerializer(ModelSerializer):\n \n class Meta:\n model = Face\n fields = ['title',\n 'description',\n 'image'\n ]\n\n\nclass NewspaperColumnSerializer(ModelSerializer):\n \n class Meta:\n model = Column\n fields = ['title',\n 'description'\n ]\n\n\nclass NewspaperAdvertSerializer(ModelSerializer):\n \n class Meta:\n model = Advert\n fields = ['text']\n\n\nclass NewspaperDetailSerializer(ModelSerializer):\n \n user = UserDetailSeralizer(read_only=True)\n columns_page = NewspaperColumnSerializer(source='columns', many=True)\n adverts_page = NewspaperAdvertSerializer(source='adverts', many=True)\n\n class Meta:\n model = Newspaper\n fields = [\n 'id',\n 'user',\n 'name',\n 'description',\n 'premium',\n 'face_title',\n 'face_description',\n 'columns_page',\n 'adverts_page',\n 'date',\n ]\n\n\nclass NewspaperFaceDetailSerializer(ModelSerializer):\n face_page = NewspaperFaceSerializer(source='face')\n\n class Meta:\n model = Newspaper\n fields = [\n 'face_page'\n ]\n\n\nclass NewspaperColumnDetailSerializer(ModelSerializer):\n \n columns_page = NewspaperColumnSerializer(source='columns', many=True)\n\n class Meta:\n model = Newspaper\n fields = [\n 'columns_page'\n ]\n\n\nclass NewspaperAdvertDetailSerializer(ModelSerializer):\n \n adverts_page = NewspaperAdvertSerializer(source='adverts', many=True)\n\n class Meta:\n model = Newspaper\n fields = [\n 'adverts_page'\n ]\n\n\nclass NewspaperEditSerizlizer(ModelSerializer):\n\n class Meta:\n model = Newspaper\n fields = [\n 'name',\n 'description',\n 'premium',\n ]","sub_path":"newspaper/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"206612202","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\nimport re\n\n\n#程序开始时间\nstart_time = time.perf_counter() #开始时间\n\n#1、获取url,headers\npage = eval(input(\"请输入你想要的页码(如第10页输入10):\"))\nwith open(\"./data/Second_hand_room.csv\",\"a\",encoding=\"GBK\") as f:\n f.write(\"{},{},{},{}\\n\".format(\"房屋简介\",\"房屋价格\",\"房屋参数\",\"房屋面积\"))\n for i in range(page):\n url = \"https://bj.lianjia.com/ershoufang/pg\"+str(i)\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\"}\n\n # 2、发送请求,获取数据响应\n response = requests.get(url,headers=headers)\n response.encoding = response.apparent_encoding\n data = response.text\n\n # 3、煲汤\n soup = BeautifulSoup(data,\"html.parser\")\n infos = soup.find(\"ul\",{\"class\":\"sellListContent\"}).find_all(\"li\")\n for info in infos:\n name = info.find(\"div\",{\"class\":\"title\"}).find(\"a\").get_text()\n price = info.find(\"div\",{\"class\":\"priceInfo\"}).find(\"div\",{\"class\":\"totalPrice\"}).find(\"span\").get_text()\n address = info.find(\"div\",{\"class\":\"address\"}).find(\"div\",{\"class\":\"houseInfo\"}).get_text()\n list = re.split(r\"\\|\",address)\n area = list[1]\n f.write(\"{},{},{},{}\\n\".format(name,price,address,area))\n\n# 程序结束时间\nend_time = time.perf_counter()\n\n# 程序执行时间\nall_time = end_time - start_time\nprint(\"程序执行了\"+str(all_time)+\"秒\")","sub_path":"爬虫例子/链家二手房信息/Second_hand_room.py","file_name":"Second_hand_room.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"296458590","text":"# encoding: UTF-8\n\n# 从tdx下载股票数据.\n# 收盘后的数据基本正确, 但盘中实时拿数据时:\n# 1. 1Min的Bar可能不是最新的, 会缺几分钟.\n# 2. 当周期>1Min时, 最后一根Bar可能不是完整的, 强制修改后\n# - 5min修改后freq基本正确\n# - 1day在VNPY合成时不关心已经收到多少Bar, 所以影响也不大\n# - 但其它分钟周期因为不好精确到每个品种, 修改后的freq可能有错\n# https://rainx.gitbooks.io/pytdx/content/pytdx_hq.html\n# 华富资产\n\nimport sys\nimport os\nimport pickle\nimport bz2\nimport traceback\nimport pandas as pd\nimport random\nfrom time import sleep\n\nfrom datetime import datetime, timedelta\nfrom logging import ERROR\nfrom pytdx.hq import TdxHq_API\nfrom pytdx.params import TDXParams\n\nfrom vnpy.trader.object import BarData\nfrom vnpy.trader.constant import Exchange\nfrom vnpy.data.tdx.tdx_common import (\n PERIOD_MAPPING,\n get_tdx_market_code,\n get_cache_config,\n get_cache_json,\n save_cache_config,\n get_stock_type,\n TDX_STOCK_CONFIG,\n TDX_PROXY_CONFIG)\n\n# 每个周期包含多少分钟\nNUM_MINUTE_MAPPING = {}\nNUM_MINUTE_MAPPING['1min'] = 1\nNUM_MINUTE_MAPPING['5min'] = 5\nNUM_MINUTE_MAPPING['15min'] = 15\nNUM_MINUTE_MAPPING['30min'] = 30\nNUM_MINUTE_MAPPING['1hour'] = 60\nNUM_MINUTE_MAPPING['1day'] = 60 * 5.5 # 股票,收盘时间是15:00,开盘是9:30\n\n# 常量\nQSIZE = 800\n\n# 通达信 <=> 交易所代码 映射\nTDX_VN_STOCK_MARKET_MAP = {\n TDXParams.MARKET_SH: Exchange.SSE, # 1: 上交所\n TDXParams.MARKET_SZ: Exchange.SZSE # 0: 深交所\n}\nVN_TDX_STOCK_MARKET_MAP = {v: k for k, v in TDX_VN_STOCK_MARKET_MAP.items()}\n\n# 通达信 <=> rq交易所代码 映射\nTDX_RQ_STOCK_MARKET_MAP = {\n TDXParams.MARKET_SH: 'XSHG', # 1: 上交所\n TDXParams.MARKET_SZ: 'XSHE' # 0: 深交所\n}\nRQ_TDX_STOCK_MARKET_MAP = {v: k for k, v in TDX_RQ_STOCK_MARKET_MAP.items()}\n\n\n# 本地缓存文件\n\nclass TdxStockData(object):\n exclude_ips = []\n\n def __init__(self, strategy=None, proxy_ip=\"\", proxy_port=0):\n \"\"\"\n 构造函数\n :param strategy: 上层策略,主要用与使用write_log()\n \"\"\"\n self.strategy = strategy\n\n self.proxy_ip = proxy_ip\n self.proxy_port = proxy_port\n\n if self.proxy_port == 0 and len(self.proxy_ip) == 0:\n proxy_config = get_cache_json(TDX_PROXY_CONFIG)\n proxy_ip = proxy_config.get('proxy_ip', '')\n proxy_port = proxy_config.get('proxy_port', 0)\n if len(proxy_ip) > 0 and proxy_port > 0:\n self.proxy_ip = proxy_ip\n self.proxy_port = proxy_port\n self.write_log(f'使用vnpy/data/tdx/{TDX_PROXY_CONFIG}的proxy:{proxy_ip}:{proxy_port}')\n\n self.api = None\n self.connection_status = False # 连接状态\n\n self.best_ip = None\n self.symbol_market_dict = {} # tdx合约与tdx市场的字典\n\n self.config = get_cache_config(TDX_STOCK_CONFIG)\n self.symbol_dict = self.config.get('symbol_dict', {})\n self.cache_time = self.config.get('cache_time', datetime.now() - timedelta(days=7))\n self.best_ip = self.config.get('best_ip', {})\n self.exclude_ips = self.config.get('exclude_ips', [])\n\n if len(self.symbol_dict) == 0 or self.cache_time < datetime.now() - timedelta(days=1):\n self.cache_config()\n\n def write_log(self, content):\n \"\"\"记录日志\"\"\"\n if self.strategy:\n self.strategy.write_log(content)\n else:\n print(content)\n\n def write_error(self, content):\n \"\"\"记录错误\"\"\"\n if self.strategy:\n self.strategy.write_log(content, level=ERROR)\n else:\n print(content, file=sys.stderr)\n\n def select_best_ip(self, ip_list, proxy_ip=\"\", proxy_port=0, exclude_ips=[]):\n \"\"\"\n 选取最快的IP\n :param ip_list:\n :param proxy_ip: 代理\n :param proxy_port: 代理端口\n :param exclude_ips: 排除清单\n :return:\n \"\"\"\n from pytdx.util.best_ip import ping\n data = [ping(ip=x['ip'], port=x['port'], type_='stock', proxy_ip=proxy_ip, proxy_port=proxy_port) for x in\n ip_list if x['ip'] not in exclude_ips]\n results = []\n for i in range(len(data)):\n # 删除ping不通的数据\n if data[i] < timedelta(0, 9, 0):\n results.append((data[i], ip_list[i]))\n else:\n if ip_list[i].get('ip') not in self.exclude_ips:\n self.exclude_ips.append(ip_list[i].get('ip'))\n\n # 按照ping值从小大大排序\n results = [x[1] for x in sorted(results, key=lambda x: x[0])]\n\n return results[0]\n\n def connect(self, is_reconnect: bool = False):\n \"\"\"\n 连接API\n :param:is_reconnect, 是否重新连接\n :return:\n \"\"\"\n # 创建api连接对象实例\n try:\n if self.api is None or not self.connection_status:\n self.write_log(u'开始连接通达信股票行情服务器')\n self.api = TdxHq_API(heartbeat=True, auto_retry=True, raise_exception=True)\n\n # 选取最佳服务器\n if is_reconnect or self.best_ip is None:\n self.best_ip = self.config.get('best_ip', {})\n if is_reconnect:\n selected_ip = self.best_ip.get('ip')\n if selected_ip not in self.exclude_ips:\n self.exclude_ips.append(selected_ip)\n self.best_ip = {}\n else:\n # 超时的话,重新选择\n last_datetime_str = self.best_ip.get('datetime', None)\n if last_datetime_str:\n try:\n last_datetime = datetime.strptime(last_datetime_str, '%Y-%m-%d %H:%M:%S')\n ip = self.best_ip.get('ip')\n is_bad_ip = ip and ip in self.best_ip.get('exclude_ips', [])\n if (datetime.now() - last_datetime).total_seconds() > 60 * 60 * 2 or is_bad_ip:\n self.best_ip = {}\n if not is_bad_ip:\n self.exclude_ips = []\n except Exception as ex: # noqa\n self.best_ip = {}\n else:\n self.best_ip = {}\n\n if len(self.best_ip) == 0:\n from pytdx.util.best_ip import stock_ip\n self.best_ip = self.select_best_ip(ip_list=stock_ip,\n proxy_ip=self.proxy_ip,\n proxy_port=self.proxy_port,\n exclude_ips=self.exclude_ips)\n # 保存最新的选择,排除\n self.config.update({'best_ip': self.best_ip,\n 'select_dt': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n 'exclude_ips': self.exclude_ips})\n save_cache_config(self.config, TDX_STOCK_CONFIG)\n\n # 如果配置proxy5,使用vnpy项目下的pytdx\n if len(self.proxy_ip) > 0 and self.proxy_port > 0:\n self.api.connect(ip=self.best_ip['ip'], port=self.best_ip['port'],\n proxy_ip=self.proxy_ip, proxy_port=self.proxy_port)\n else:\n # 使用pip install pytdx\n self.api.connect(ip=self.best_ip['ip'], port=self.best_ip['port'])\n\n self.write_log(f'创建tdx连接, : {self.best_ip}')\n self.connection_status = True\n\n except Exception as ex:\n self.write_log(u'连接服务器{}tdx异常:{},{}'.format(self.best_ip, str(ex), traceback.format_exc()))\n cur_ip = self.best_ip.get('ip', None)\n if cur_ip is not None and cur_ip not in self.exclude_ips:\n self.write_log(f'排除{cur_ip}')\n self.exclude_ips.append(cur_ip)\n self.best_ip = {}\n\n return\n\n def disconnect(self):\n \"\"\"断开连接\"\"\"\n if self.api is not None:\n self.api = None\n\n def cache_config(self):\n \"\"\"缓存所有股票的清单\"\"\"\n for market_id in range(2):\n print('get market_id:{}'.format(market_id))\n security_list = self.get_security_list(market_id)\n if len(security_list) == 0:\n continue\n for security in security_list:\n tdx_symbol = security.get('code', None)\n exchange = Exchange.SZSE.value if market_id == 0 else Exchange.SSE.value\n stock_type = get_stock_type(tdx_symbol)\n security.update({'market_id': market_id})\n security.update({'stock_type': stock_type})\n security.update({'exchange': exchange})\n\n if tdx_symbol:\n self.symbol_dict.update({f'{tdx_symbol}_{market_id}': security})\n\n self.config.update({'symbol_dict': self.symbol_dict, 'cache_time': datetime.now()})\n save_cache_config(data=self.config, config_file_name=TDX_STOCK_CONFIG)\n\n def get_security_list(self, market_id: int = 0):\n \"\"\"\n 获取市场代码\n :param: market_id: 1,上交所 , 0, 深交所\n :return:\n \"\"\"\n if self.api is None:\n self.connect()\n\n start = 0\n results = []\n # 接口有数据量连续,循环获取,直至取不到结果为止\n while True:\n try:\n result = self.api.get_security_list(market_id, start)\n except Exception:\n break\n if len(result) > 0:\n start += len(result)\n else:\n break\n results.extend(result)\n\n return results\n\n def get_name(self, symbol, market_id=None):\n \"\"\"\n 获取名称\n :param symbol: 代码 或者 代码.交易所\n :param market_id: 如果存在代码.交易所时,不使用该值\n :return:\n \"\"\"\n if '.' in symbol:\n symbol, exchange = symbol.split('.')\n if exchange == Exchange.SSE.value:\n market_id = 1\n elif exchange == Exchange.SZSE.value:\n market_id = 0\n\n symbol_info = self.symbol_dict.get(f'{symbol}_{market_id}')\n if symbol_info:\n return symbol_info.get('name', symbol)\n\n return symbol\n\n # ----------------------------------------------------------------------\n def get_bars(self,\n symbol: str,\n period: str,\n callback=None,\n bar_freq: int = 1,\n start_dt: datetime = None,\n return_bar: bool = True):\n \"\"\"\n 返回k线数据\n symbol:股票 000001.XG\n period: 周期: 1min,5min,15min,30min,1hour,1day,\n \"\"\"\n if not self.api:\n self.connect()\n ret_bars = []\n if self.api is None:\n return False, []\n\n # symbol => tdx_code, market_id\n if '.' in symbol:\n tdx_code, market_str = symbol.split('.')\n # 1, 上交所 , 0, 深交所\n market_id = 1 if market_str.upper() in ['XSHG', Exchange.SSE.value] else 0\n self.symbol_market_dict.update({tdx_code: market_id}) # tdx合约与tdx市场的字典\n else:\n market_id = get_tdx_market_code(symbol)\n tdx_code = symbol\n self.symbol_market_dict.update({symbol: market_id}) # tdx合约与tdx市场的字典\n name = self.get_name(tdx_code, market_id)\n\n # period => tdx_period\n if period not in PERIOD_MAPPING.keys():\n self.write_error(u'{} 周期{}不在下载清单中: {}'\n .format(datetime.now(), period, list(PERIOD_MAPPING.keys())))\n # print(u'{} 周期{}不在下载清单中: {}'.format(datetime.now(), period, list(PERIOD_MAPPING.keys())))\n return False, ret_bars\n tdx_period = PERIOD_MAPPING.get(period)\n\n # start_dt => qry_start_dt & qry_end_dt\n if start_dt is None:\n self.write_log(u'没有设置开始时间,缺省为10天前')\n qry_start_date = datetime.now() - timedelta(days=10)\n start_dt = qry_start_date\n else:\n qry_start_date = start_dt\n qry_end_date = datetime.now()\n if qry_start_date > qry_end_date:\n qry_start_date = qry_end_date\n\n self.write_log('{}开始下载tdx股票: {},代码:{} {}数据, {} to {}.'\n .format(datetime.now(), name, tdx_code, tdx_period, qry_start_date, qry_end_date))\n stock_type = get_stock_type(tdx_code, market_id)\n if stock_type == 'index_cn':\n get_bar_func = self.api.get_index_bars\n else:\n get_bar_func = self.api.get_security_bars\n\n try:\n _start_date = qry_end_date\n _bars = []\n _pos = 0\n while _start_date > qry_start_date:\n _res = get_bar_func(\n category=PERIOD_MAPPING[period],\n market=market_id,\n code=tdx_code,\n start=_pos,\n count=QSIZE)\n if _res is not None:\n _bars = _res + _bars\n _pos += QSIZE\n if _res is not None and len(_res) > 0:\n _start_date = _res[0]['datetime']\n _start_date = datetime.strptime(_start_date, '%Y-%m-%d %H:%M')\n self.write_log(u'分段取数据开始:{}'.format(_start_date))\n else:\n break\n if len(_bars) == 0:\n self.write_error('{} Handling {}, len1={}..., continue'.format(\n str(datetime.now()), tdx_code, len(_bars)))\n sleep(3 * random.random())\n return False, ret_bars\n\n current_datetime = datetime.now()\n data = self.api.to_df(_bars)\n data = data.assign(datetime=pd.to_datetime(data['datetime']))\n data = data.assign(ticker=symbol)\n data['symbol'] = symbol\n data = data.drop(\n ['year', 'month', 'day', 'hour', 'minute', 'price', 'ticker'],\n errors='ignore',\n axis=1)\n data = data.rename(\n index=str,\n columns={'vol': 'volume'})\n\n if len(data) == 0:\n print('{} Handling {}, len2={}..., continue'.format(\n str(datetime.now()), tdx_code, len(data)))\n return False, ret_bars\n\n # 通达信是以bar的结束时间标记的,vnpy是以bar开始时间标记的,所以要扣减bar本身的分钟数\n data['datetime'] = data['datetime'].apply(\n lambda x: x - timedelta(minutes=NUM_MINUTE_MAPPING.get(period, 1)))\n data['trading_date'] = data['datetime'].apply(lambda x: (x.strftime('%Y-%m-%d')))\n data['date'] = data['datetime'].apply(lambda x: (x.strftime('%Y-%m-%d')))\n data['time'] = data['datetime'].apply(lambda x: (x.strftime('%H:%M:%S')))\n data = data.set_index('datetime', drop=False)\n\n if return_bar:\n self.write_log('dataframe => [BarData]')\n exchange = TDX_VN_STOCK_MARKET_MAP.get(market_id, Exchange.LOCAL)\n for index, row in data.iterrows():\n try:\n add_bar = BarData(\n gateway_name='tdx',\n symbol=symbol,\n exchange=exchange,\n datetime=index\n )\n add_bar.date = row['date']\n add_bar.time = row['time']\n add_bar.trading_day = row['trading_date']\n add_bar.open_price = float(row['open'])\n add_bar.high_price = float(row['high'])\n add_bar.low_price = float(row['low'])\n add_bar.close_price = float(row['close'])\n add_bar.volume = float(row['volume'])\n except Exception as ex:\n self.write_error('error when convert bar:{},ex:{},t:{}'\n .format(row, str(ex), traceback.format_exc()))\n # print('error when convert bar:{},ex:{},t:{}'.format(row, str(ex), traceback.format_exc()))\n return False, ret_bars\n\n if start_dt is not None and index < start_dt:\n continue\n ret_bars.append(add_bar)\n\n if callback is not None:\n freq = bar_freq\n bar_is_completed = True\n if period != '1min' and index == data['datetime'][-1]:\n # 最后一个bar,可能是不完整的,强制修改\n # - 5min修改后freq基本正确\n # - 1day在VNPY合成时不关心已经收到多少Bar, 所以影响也不大\n # - 但其它分钟周期因为不好精确到每个品种, 修改后的freq可能有错\n if index > current_datetime:\n bar_is_completed = False\n # 根据秒数算的话,要+1,例如13:31,freq=31,第31根bar\n freq = NUM_MINUTE_MAPPING[period] - int((index - current_datetime).total_seconds() / 60)\n callback(add_bar, bar_is_completed, freq)\n\n else:\n self.write_log('dataframe => [ dict ]')\n ret_bars = list(data.T.to_dict().values())\n return True, ret_bars\n except Exception as ex:\n self.write_error('exception in get:{},{},{}'.format(tdx_code, str(ex), traceback.format_exc()))\n # print('exception in get:{},{},{}'.format(tdx_symbol,str(ex), traceback.format_exc()))\n self.write_log(u'重置连接')\n self.api = None\n self.connect(is_reconnect=True)\n return False, ret_bars\n\n def get_last_bars(self, symbol: str, period: str = '1min', n: int = 2, return_bar: bool = True):\n \"\"\"\n 获取最后n根bar\n :param symbol:\n :param period:\n :param n:取bar数量\n :param return_bar:\n :return:\n \"\"\"\n if not self.api:\n self.connect()\n ret_bars = []\n if self.api is None:\n return False, []\n\n # symbol => tdx_code, market_id\n if '.' in symbol:\n tdx_code, market_str = symbol.split('.')\n # 1, 上交所 , 0, 深交所\n market_id = 1 if market_str.upper() in ['XSHG', Exchange.SSE.value] else 0\n self.symbol_market_dict.update({tdx_code: market_id}) # tdx合约与tdx市场的字典\n else:\n market_id = get_tdx_market_code(symbol)\n tdx_code = symbol\n self.symbol_market_dict.update({symbol: market_id}) # tdx合约与tdx市场的字典\n # period => tdx_period\n if period not in PERIOD_MAPPING.keys():\n self.write_error(u'{} 周期{}不在下载清单中: {}'\n .format(datetime.now(), period, list(PERIOD_MAPPING.keys())))\n return False, ret_bars\n tdx_period = PERIOD_MAPPING.get(period)\n stock_type = get_stock_type(tdx_code)\n if stock_type == 'index_cn':\n get_bar_func = self.api.get_index_bars\n else:\n get_bar_func = self.api.get_security_bars\n try:\n datas = get_bar_func(\n category=PERIOD_MAPPING[period],\n market=market_id,\n code=tdx_code,\n start=0,\n count=n)\n if not datas or len(datas) == 0:\n return False, ret_bars\n\n if not return_bar:\n return True, datas\n\n exchange = TDX_VN_STOCK_MARKET_MAP.get(market_id, Exchange.LOCAL)\n delta_minutes = NUM_MINUTE_MAPPING.get(period, 1)\n for data in datas:\n bar_dt = datetime.strptime(data.get('datetime'), '%Y-%m-%d %H:%M')\n bar_dt = bar_dt - timedelta(minutes=delta_minutes)\n add_bar = BarData(\n gateway_name='tdx',\n symbol=symbol,\n exchange=exchange,\n datetime=bar_dt\n )\n add_bar.date = bar_dt.strftime('%Y-%m-%d')\n add_bar.time = bar_dt.strftime('%H:%M:%S')\n add_bar.trading_day = add_bar.date\n add_bar.open_price = float(data['open'])\n add_bar.high_price = float(data['high'])\n add_bar.low_price = float(data['low'])\n add_bar.close_price = float(data['close'])\n add_bar.volume = float(data['vol'])\n ret_bars.append(add_bar)\n return True, ret_bars\n except Exception as ex:\n self.write_error(f'获取{symbol}数据失败:{str(ex)}')\n return False, ret_bars\n\n # ----------------------------------------------------------------------\n\n def save_cache(self,\n cache_folder: str,\n cache_symbol: str,\n cache_date: str,\n data_list: list):\n \"\"\"保存文件到缓存\"\"\"\n\n os.makedirs(cache_folder, exist_ok=True)\n\n if not os.path.exists(cache_folder):\n self.write_error('缓存目录不存在:{},不能保存'.format(cache_folder))\n return\n cache_folder_year_month = os.path.join(cache_folder, cache_date[:6])\n os.makedirs(cache_folder_year_month, exist_ok=True)\n\n save_file = os.path.join(cache_folder_year_month, '{}_{}.pkb2'.format(cache_symbol, cache_date))\n with bz2.BZ2File(save_file, 'wb') as f:\n pickle.dump(data_list, f)\n self.write_log(u'缓存成功:{}'.format(save_file))\n\n def load_cache(self,\n cache_folder: str,\n cache_symbol: str,\n cache_date: str):\n \"\"\"加载缓存数据\"\"\"\n if not os.path.exists(cache_folder):\n # self.write_error('缓存目录:{}不存在,不能读取'.format(cache_folder))\n return None\n cache_folder_year_month = os.path.join(cache_folder, cache_date[:6])\n if not os.path.exists(cache_folder_year_month):\n # self.write_error('缓存目录:{}不存在,不能读取'.format(cache_folder_year_month))\n return None\n\n cache_file = os.path.join(cache_folder_year_month, '{}_{}.pkb2'.format(cache_symbol, cache_date))\n if not os.path.isfile(cache_file):\n # self.write_error('缓存文件:{}不存在,不能读取'.format(cache_file))\n return None\n with bz2.BZ2File(cache_file, 'rb') as f:\n data = pickle.load(f)\n return data\n\n return None\n\n def get_history_transaction_data(self,\n symbol: str,\n trading_date,\n cache_folder: str = None):\n \"\"\"\n 获取当某一交易日的历史成交记录\n :param symbol: 查询合约 xxxxxx.交易所\n :param trading_date: 可以是日期参数,或者字符串参数,支持 2019-01-01 或 20190101格式\n :param cache_folder:\n :return:\n \"\"\"\n if not self.api:\n self.connect()\n\n ret_datas = []\n\n # trading_date ,转为为查询数字类型\n if isinstance(trading_date, datetime):\n trading_date = trading_date.strftime('%Y%m%d')\n if isinstance(trading_date, str):\n trading_date = int(trading_date.replace('-', ''))\n\n cache_symbol = symbol\n cache_date = str(trading_date)\n\n max_data_size = sys.maxsize\n # symbol.exchange => tdx_code market_code\n if '.' in symbol:\n tdx_code, market_str = symbol.split('.')\n market_code = 1 if market_str.upper() in ['XSHG', Exchange.SSE.value] else 0\n self.symbol_market_dict.update({tdx_code: market_code}) # tdx合约与tdx市场的字典\n else:\n market_code = get_tdx_market_code(symbol)\n tdx_code = symbol\n self.symbol_market_dict.update({symbol: market_code}) # tdx合约与tdx市场的字典\n\n symbol_config = self.symbol_dict.get(f'{tdx_code}_{market_code}', {})\n decimal_point = symbol_config.get('decimal_point', 2)\n\n q_size = QSIZE * 5\n # 每秒 2个, 10小时\n max_data_size = 1000000\n # 优先从缓存加载\n if cache_folder:\n buffer_data = self.load_cache(cache_folder, cache_symbol, cache_date)\n if buffer_data:\n return True, buffer_data\n\n self.write_log(u'开始下载{} 历史{}分笔数据'.format(trading_date, symbol))\n\n is_today = False\n if trading_date == int(datetime.now().strftime('%Y%m%d')):\n is_today = True\n\n try:\n _datas = []\n _pos = 0\n\n while True:\n if is_today:\n # 获取当前交易日得交易记录\n _res = self.api.get_transaction_data(\n market=self.symbol_market_dict[tdx_code],\n code=tdx_code,\n start=_pos,\n count=q_size)\n else:\n # 获取历史交易记录\n _res = self.api.get_history_transaction_data(\n market=self.symbol_market_dict[tdx_code],\n date=trading_date,\n code=tdx_code,\n start=_pos,\n count=q_size)\n last_dt = None\n if _res is not None:\n _datas = _res + _datas\n _pos += min(q_size, len(_res))\n\n if _res is not None and len(_res) > 0:\n self.write_log(u'分段取{}分笔数据:{} ~{}, {}条,累计:{}条'\n .format(trading_date, _res[0]['time'], _res[-1]['time'], len(_res), _pos))\n else:\n break\n\n if len(_datas) >= max_data_size:\n break\n\n if len(_datas) == 0:\n self.write_error(u'{}分笔成交数据获取为空'.format(trading_date))\n return False, _datas\n\n for d in _datas:\n dt = datetime.strptime(str(trading_date) + ' ' + d.get('time'), '%Y%m%d %H:%M')\n if last_dt is None or last_dt < dt:\n last_dt = dt\n else:\n if last_dt < dt + timedelta(seconds=59):\n last_dt = last_dt + timedelta(seconds=1)\n d.update({'datetime': last_dt})\n d.update({'volume': d.pop('vol', 0)})\n if decimal_point > 2:\n price = round(d.get('price') / (10 ** (decimal_point - 2)), decimal_point)\n d.update({'price': price})\n\n d.update({'trading_date': last_dt.strftime('%Y-%m-%d')})\n\n _datas = sorted(_datas, key=lambda s: s['datetime'])\n\n # 缓存文件\n if cache_folder and not is_today:\n self.save_cache(cache_folder, cache_symbol, cache_date, _datas)\n\n return True, _datas\n\n except Exception as ex:\n self.write_error(\n 'exception in get_transaction_data:{},{},{}'.format(symbol, str(ex), traceback.format_exc()))\n return False, ret_datas\n\n def get_stock_list(self, types=[\"stock_cn\", \"etf_cn\", \"bond_cn\", \"cb_cn\"]):\n \"\"\"股票所有的code&name列表\"\"\"\n if self.api is None:\n self.connect()\n\n data = pd.concat(\n [pd.concat(\n [self.api.to_df(self.api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index(\n ['code', 'sse'], drop=False) for i in range(int(self.api.get_security_count(j) / 1000) + 1)],\n axis=0) for j\n in range(2)], axis=0)\n sz = data.query('sse==\"sz\"')\n sh = data.query('sse==\"sh\"')\n sz = sz.assign(sec=sz.code.apply(get_stock_type))\n sh = sh.assign(sec=sh.code.apply(get_stock_type))\n\n temp_df = pd.concat([sz, sh]).query('sec in [\"{}\"]'.format(types)).sort_index().assign(\n name=data['name'].apply(lambda x: str(x)[0:6]))\n\n hq_codelist = []\n\n for i in range(0, len(temp_df)):\n row = temp_df.iloc[i]\n hq_codelist.append(\n {\n \"code\": row['code'],\n \"exchange\": Exchange.SSE.value if row['sse'] == 'sh' else Exchange.SZSE.value,\n \"market_id\": 1 if row['sse'] == 'sh' else 0,\n \"name\": row['name']\n\n }\n )\n\n return hq_codelist\n\n def get_security_quotes(self, all_stock, code=None):\n \"\"\"\n 支持三种形式的参数\n get_security_quotes(market, code )\n get_security_quotes((market, code))\n get_security_quotes([(market1, code1), (market2, code2)] )\n :param all_stock (market, code) 的数组\n :param code{optional} code to query\n :return:\n \"\"\"\n if self.api is None:\n self.connect()\n\n return self.api.get_security_quotes(all_stock, code)\n\n def get_stock_quotes_by_type(self, stock_type):\n \"\"\"根据股票代码类型,获取其最新行情\"\"\"\n stock_list = [(stock.get('market_id'), stock.get('code')) for stock in self.symbol_dict.values() if\n stock.get('stock_type') == stock_type]\n\n num_per_count = 60\n results = []\n for i in range(0, len(stock_list) + 1, num_per_count):\n cur_results = self.get_security_quotes(stock_list[i:i + num_per_count])\n results.extend(cur_results)\n\n return results\n","sub_path":"vnpy/data/tdx/tdx_stock_data.py","file_name":"tdx_stock_data.py","file_ext":"py","file_size_in_byte":30772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"31638051","text":"from __future__ import print_function, unicode_literals\n\nfrom .. import hexdigits, _Atom, _Comp, TestCase\n\n\ndef setup():\n class Bit(_Atom):\n base = 2\n words = r'FT'\n\n class Tri(_Atom):\n words = r'TRI'\n base = words.__len__()\n\n class Quad(_Comp):\n elem_types = Bit, Bit\n\n class Hex(_Comp):\n elem_types = Quad, Quad\n words = hexdigits\n\n class Hex2(_Comp):\n elem_types = Quad, Quad\n words = tuple(hexdigits)\n\n class Byte(_Comp):\n elem_types = Hex, Hex\n\n return Bit, Tri, Quad, Hex, Hex2, Byte\n\n\nclass T(TestCase):\n Bit, Tri, Quad, Hex, Hex2, Byte = setup()\n\n def test0(self):\n expected = self.Quad[-1]\n actual = self.Quad(-1, self.Bit[-1])\n self.assertIs(expected, actual)\n\n def test1(self):\n expected = self.Quad[3]\n actual = self.Quad(self.Bit(1), 1)\n self.assertIs(expected, actual)\n\n def test2(self):\n Quad, Hex = self.Quad, self.Hex\n\n expected = Hex[-1]\n actual = Hex((1, self.Bit[1]), Quad[-1])\n self.assertIs(expected, actual)\n\n def test(self):\n Bit, Quad, Hex = self.Bit, self.Quad, self.Hex\n max_int = -1\n max_bit, max_quad = (y - 1 for y in (2, 4))\n _b, _q, _h = (catalog[-1] for catalog in (Bit, Quad, Hex))\n expected = _b, _b, _q, _q, _q, _h, _h, _h\n b0 = Bit(max_int)\n b1 = Bit[max_int]\n q0 = Quad(max_bit, max_int)\n q1 = Quad(max_bit, b0)\n q2 = Quad(max_int, b1)\n h0 = Hex(max_int, max_quad)\n h1 = Hex((b0, max_bit), max_int)\n h2 = Hex((max_int, max_bit), max_int)\n actual = b0, b1, q0, q1, q2, h0, h1, h2\n self.assert_are(expected, actual)\n\n def test3(self):\n Quad, Hex, Byte = self.Quad, self.Hex, self.Byte\n\n expected = Hex[-1], Byte[-1], Byte[-1]\n g = Quad[-1], (-1, 1)\n actual = Hex(*g), Byte(g, g), Byte(-1, g)\n self.assert_are(expected, actual)\n\n def test4(self):\n Bit, Tri = self.Bit, self.Tri\n bad_stor_elem = Tri[-1]\n expected = self.repr_obj(bad_stor_elem.__str__()), Bit, Tri\n with self.assert_raises_obj(TypeError, expected):\n self.Quad(bad_stor_elem, 1)\n\n def test5(self):\n with self.assert_raises_obj(ValueError, (3, self.Bit, 2)):\n self.Quad(3, 1)\n\n r'''\n if Quad is a compound of Bit and Bit, stor may be:\n Quad(1, Bit(-1))\n Quad(Bit[-1], -1)\n , etc.\n '''\n def test6(self):\n class Bit(_Atom):\n base = 2\n\n class Quad(_Comp):\n elem_types = Bit, Bit\n\n p = Quad[3]\n q = Quad(1, Bit(-1))\n r = Quad(Bit[-1], -1)\n\n expected = True, True\n actual = p is q, q is r\n self.assertEqual(expected, actual)\n\n r'''\n if Hex is a compound of Quad and Quad, stor may be:\n Hex(Quad[-1], (-1, 1))\n Hex((1, -1), Quad(1, Bit[-1]))\n , etc.\n '''\n def test7(self):\n class Bit(_Atom):\n base = 2\n\n class Quad(_Comp):\n elem_types = Bit, Bit\n\n class Hex(_Comp):\n elem_types = Quad, Quad\n\n p = Hex[-1]\n try:\n _0 = Quad[-1]\n _1 = Hex(_0, _0)\n except Exception as e:\n raise e\n q = Hex(Quad[-1], (-1, 1))\n r = Hex((1, -1), -1) # Quad(1, Bit[-1]))\n\n expected = True, True\n actual = p is q, q is r\n self.assertEqual(expected, actual)\n","sub_path":"catalog/test/impl/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"229801708","text":"#coding:utf-8\n\nimport socket\nimport time\nimport sys\n\nHOST_IP = \"182.61.61.133\"\nHOST_PORT = 17799\nhost_addr = (\"\", HOST_PORT)\n \ndef tcp_server(argv=None):\n print(\"Starting socket: TCP server\")\n #1.create socket object:socket=socket.socket(family,type)\n socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # print(\"TCP server listen @ %s:%d!\" %(HOST_IP, HOST_PORT) )\n\n #2.bind socket to addr:socket.bind(address)\n socket_tcp.bind(host_addr)\n #3.listen connection request:socket.listen(backlog)\n socket_tcp.listen(5)\n #4.waite for client:connection,address=socket.accept()\n socket_con, (client_ip, client_port) = socket_tcp.accept()\n print(\"Connection accepted from %s.\" %(client_ip))\n socket_con.send(b\"Welcome to TCP server!\")\n\n while True:\n try:\n data=socket_con.recv(512)\n if len(data)>0:\n print(\"Received:%s\"%data)\n socket_con.send(data)\n time.sleep(1)\n continue\n except Exception:\n socket_tcp.close()\n sys.exit(1)\n \n\nif __name__ == \"__main__\":\n sys.exit(tcp_server())\n","sub_path":"src/python/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"512512826","text":"### Task 4.5\n# Implement a function `get_digits(num: int) -> Tuple[int]` which returns a tuple\n# of a given integer's digits.\n# Example:\n# ```python\n# >>> split_by_index(87178291199) # func name >> 'get_digits'\n# (8, 7, 1, 7, 8, 2, 9, 1, 1, 9, 9)\n# ```\n\ndef get_digits(num: int):\n output = ()\n str_num = str(num)\n for n in str_num:\n output = list(output) # is this kind of cheating ?\n output.append(int(n))\n output = tuple(output) # mean 'can i just write it here?'\n return (output)\n\nsome_entered_int = 87178291199\nprint(get_digits(some_entered_int))","sub_path":"02_Functions/Task 4.5.py","file_name":"Task 4.5.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466823345","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 26 00:44:34 2020\n\n@author: gyjung\n\"\"\"\n\nimport os\nimport csv\nimport pickle\nimport time\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\n\nfrom dotenv import load_dotenv\n\nfrom ase.io.vasp import read_vasp\n\nfrom pymatgen import MPRester, Structure\nfrom pymatgen.io.vasp import Vasprun, BSVasprun, Oszicar, Outcar\nfrom pymatgen.symmetry.analyzer import SpacegroupAnalyzer\nfrom pymatgen.electronic_structure.plotter import BSDOSPlotter\n\n###############################################################################\ndef createFolder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print('Error: Creating directory. ' + directory)\n\n###############################################################################\nwith open('form_E_ref.csv', 'r') as f:\n ref_data = pd.read_csv(f)\n ref_dict = dict.fromkeys(ref_data['element'])\n for i in range(len(ref_data)):\n ref_dict.update({ref_data['element'][i]:ref_data['E'][i]})\n\n# add O2_corr ref. energy\nref_dict['O2_corr'] = -8.45572061\n\n# define U correction values\nU_corr_dict = {'V':1.682, 'Cr':2.013, 'Mn':1.68085, 'Fe':2.733,\n 'Co':1.874, 'Ni':2.164, 'Mo':3.531, 'W':5.159}\n\n###############################################################################\n\nload_dotenv('.env')\nMATERIAL_API_KEY = os.getenv('MATERIAL_API_KEY')\n\nmpr = MPRester(MATERIAL_API_KEY)\n\ndf = pd.read_csv('mpid_list_v3.csv')\n\nentries_from_list = mpr.query(criteria = {'material_id':{'$in':list(df.mp_id.values)}},\n properties = [\"material_id\",\"task_id\",\"pretty_formula\",\n \"formation_energy_per_atom\",\"cif\", \"energy\",\"energy_per_atom\",\n \"structure\",\"input.incar\",\"magnetic_type\",\"total_magnetization\",\n \"e_above_hull\",\"band_gap\",\"volume\",\"theoretical\"])\n\nprint(\"Total %d structures were identified from %d mp-ID\" % (len(entries_from_list), len(df)))\n\ndf_entries_ori = pd.DataFrame(entries_from_list)\ndf_entries = pd.DataFrame(entries_from_list)\n\n\nindex_list = []\nfor i in range(len(df)):\n formula = df.formula[i]\n for k, entry in enumerate(df_entries_ori):\n index = df_entries_ori[df_entries_ori['pretty_formula'] == formula].index[0]\n \n# print(i,\" \",formula,\" \",index,\" \",df_entries_ori['pretty_formula'][index])\n index_list.append(index)\n \n\nfor n, idx in enumerate(index_list):\n df_entries.iloc[n] = df_entries_ori.iloc[idx] \n\n\"\"\"\natoms_list = []\nfor i in range(len(df_entries)):\n print(i,\" \",df_entries['pretty_formula'][i])\n for atom in df_entries['structure'][i].species:\n if str(atom) not in atoms_list:\n atoms_list.append(str(atom))\n\"\"\"\n###############################################################################\n\ncreateFolder('results')\ncreateFolder('results/plots')\n\nproperties = ['MP_ID', 'formula',\n 'PREC', 'ALGO', 'ISPIN', 'IMIX', 'NELM', 'IBRION', 'EDIFF', 'NSW',\n 'ISIF', 'ENCUT', 'MAGMOM', 'ISMEAR', 'SIGMA', 'LDAU', 'LDAUU',\n 'total_E_ref', 'E_atom', 'total_E', 'cell_param', 'angle',\n 'Magm_ref', 'Mag_O_ref','Magm','Mag_O','tot_mag_ref','tot_mag',\n 'DHf_ref', 'DHf', 'Err_DHf', 'Ehull_ref', 'Eg_ref', 'Eg',\n 'Volume_ref', 'Volume', 'Err_V_percent', 'Theoretical',\n 'VBM', 'E_fermi', 'CBM', 'bgtype', 'bgpath', 'structure'\n ]\n\nAsite_elements = ['Na', 'K', 'Rb', 'Cs', 'Mg', 'Ca', 'Sr', 'Ba']\n\n\nproperties_Asite = ['formula_Na','total_E_Na', 'tot_mag_Na','DHf_Na', 'Ehull_ref_Na', 'Eg_Na', 'Volume_Na',\n 'formula_K','total_E_K', 'tot_mag_K','DHf_K', 'Ehull_ref_K', 'Eg_K', 'Volume_K',\n 'formula_Rb','total_E_Rb', 'tot_mag_Rb','DHf_Rb', 'Ehull_ref_Rb', 'Eg_Rb', 'Volume_Rb',\n 'formula_Cs','total_E_Cs', 'tot_mag_Cs','DHf_Cs', 'Ehull_ref_Cs', 'Eg_Cs', 'Volume_Cs',\n 'formula_Mg','total_E_Mg', 'tot_mag_Mg','DHf_Mg', 'Ehull_ref_Mg', 'Eg_Mg', 'Volume_Mg',\n 'formula_Ca','total_E_Ca', 'tot_mag_Ca','DHf_Ca', 'Ehull_ref_Ca', 'Eg_Ca', 'Volume_Ca',\n 'formula_Sr','total_E_Sr', 'tot_mag_Sr','DHf_Sr', 'Ehull_ref_Sr', 'Eg_Sr', 'Volume_Sr',\n 'formula_Ba','total_E_Ba', 'tot_mag_Ba','DHf_Ba', 'Ehull_ref_Ba', 'Eg_Ba', 'Volume_Ba']\n\n###############################################################################\n\nwith open('results/bulk_analysis.log', 'w') as f:\n start_time = time.time()\n f.writelines('No\\tformula\\tEg_MP(eV)\\tEg(eV)\\tVBM\\tE_fermi\\tCBM\\tbgtype\\tBandgap_path\\n')\n \n # insert the number of index(models) for analysis\n num_ini = 0\n num = len(df_entries) # len(df_entries) \n \n df_bulk = pd.DataFrame(np.array([['NaN' for i in range(len(properties))] for j in range(num)]),\n index = [m for m in range(1,num+1)],\n columns = properties)\n \n df_Asite = pd.DataFrame(np.array([['NaN' for i in range(len(properties_Asite))] for j in range(num)]),\n index = [m for m in range(1, num+1)],\n columns = properties_Asite)\n\n for idx in range(num_ini, num):\n \"\"\"\n Import from MP_INCAR\n \"\"\"\n formula = df_entries['pretty_formula'][idx]\n incar = df_entries['input.incar'][idx]\n\n df_bulk.MP_ID[idx+1] = df_entries['material_id'][idx]\n df_bulk.formula[idx+1] = formula\n \n df_bulk.PREC[idx+1] = incar['PREC']\n df_bulk.ALGO[idx+1] = incar['ALGO']\n \n try:\n df_bulk.IMIX[idx+1] = incar['IMIX']\n except KeyError:\n df_bulk.IMIX[idx+1] = 4 # default value\n \n df_bulk.ISPIN[idx+1] = incar['ISPIN']\n df_bulk.NELM[idx+1] = incar['NELM']\n df_bulk.IBRION[idx+1] = incar['IBRION']\n \n try:\n df_bulk.EDIFF[idx+1] = incar['EDIFF']\n except KeyError:\n df_bulk.EDIFF[idx+1] = 1e-4 # default value\n \n df_bulk.ISIF[idx+1] = incar['ISIF']\n df_bulk.NSW[idx+1] = incar['NSW']\n df_bulk.ENCUT[idx+1] = incar['ENCUT']\n df_bulk.MAGMOM[idx+1] = incar['MAGMOM']\n df_bulk.ISMEAR[idx+1] = incar['ISMEAR']\n df_bulk.SIGMA[idx+1] = incar['SIGMA']\n \n try:\n df_bulk.LDAU[idx+1] = incar['LDAU']\n df_bulk.LDAUU[idx+1] = incar['LDAUU']\n except KeyError:\n df_bulk.LDAU[idx+1] = None\n df_bulk.LDAUU[idx+1] = None\n \n \"\"\"\n Import from MP_results\n \"\"\"\n struc = df_entries['structure'][idx]\n \n # getting conventional unit cell\n sga = SpacegroupAnalyzer(struc, symprec = 0.1)\n conv_struc = sga.get_conventional_standard_structure()\n if len(conv_struc) != 5:\n print('%s : number of atoms - Error' % file_path)\n\n scaling = len(conv_struc)/len(struc)\n \n df_bulk.total_E_ref[idx+1] = df_entries['energy'][idx] * scaling\n df_bulk.E_atom[idx+1] = df_entries['energy_per_atom'][idx]\n \n df_bulk.cell_param[idx+1] = struc.lattice.abc\n df_bulk.angle[idx+1] = struc.lattice.angles\n \n try:\n magm_f = struc.site_properties['magmom']\n df_bulk.Magm_ref[idx+1] = magm_f\n except:\n df_bulk.Magm_ref[idx+1] = None\n \n df_bulk.tot_mag_ref[idx+1] = df_entries['total_magnetization'][idx] * scaling\n df_bulk.Mag_O_ref[idx+1] = df_entries['magnetic_type'][idx]\n df_bulk.DHf_ref[idx+1] = df_entries['formation_energy_per_atom'][idx]\n df_bulk.Ehull_ref[idx+1] = df_entries['e_above_hull'][idx]\n df_bulk.Eg_ref[idx+1] = df_entries['band_gap'][idx]\n df_bulk.Theoretical[idx+1] = df_entries['theoretical'][idx]\n \n volume_ref = df_entries['volume'][idx] * scaling\n df_bulk.Volume_ref[idx+1] = volume_ref\n \n # save conventional unit cell\n createFolder('results/bulk_models') \n conv_struc.to(filename = \"results/bulk_models/POSCAR_%s\" % (formula))\n conv_struc.to(filename = \"results/bulk_models/%s.cif\" % (formula))\n \n \"\"\"\n Import from my results\n \"\"\"\n if os.path.exists('%03d_%s/2nd/' % (idx + 1.0, formula)):\n if os.path.exists('%03d_%s/2nd/cont/' % (idx + 1.0, formula)):\n file_path = '%03d_%s/2nd/cont/' % (idx + 1.0, formula)\n else:\n file_path = '%03d_%s/2nd/' % (idx + 1.0, formula)\n elif os.path.exists('%03d_%s/2nd_opt/' % (idx + 1.0, formula)):\n if os.path.exists('%03d_%s/2nd_opt/cont/' % (idx + 1.0, formula)):\n file_path = '%03d_%s/2nd_opt/cont/' % (idx + 1.0, formula)\n else:\n file_path = '%03d_%s/2nd_opt/' % (idx + 1.0, formula)\n \n print(file_path)\n \n try:\n oszicar = Oszicar(file_path + 'OSZICAR')\n tot_E = oszicar.ionic_steps[-1]['F']\n tot_mag = oszicar.ionic_steps[-1]['mag']\n \n df_bulk.total_E[idx+1] = tot_E\n df_bulk.tot_mag[idx+1] = tot_mag\n\n v = Vasprun(file_path + 'vasprun.xml')\n volume = v.as_dict()['output']['crystal']['lattice']['volume']\n \n \n df_bulk.Volume[idx+1] = volume\n df_bulk.Err_V_percent[idx+1] = (volume_ref - volume) / volume_ref * 100\n\n el = v.as_dict()['elements']\n el.remove('O')\n\n fE = tot_E - ref_dict[el[0]] - ref_dict[el[1]] - 1.5*ref_dict['O2_corr']\n \n if el[0] or el[1] in U_corr_dict:\n for x in range(len(el)):\n if el[x] in U_corr_dict:\n fE = fE - U_corr_dict[el[x]]\n fE = fE/len(conv_struc) # eV/atom\n \n df_bulk.DHf[idx+1] = fE\n df_bulk.Err_DHf[idx+1] = df_bulk.DHf_ref[idx+1] - df_bulk.DHf[idx+1]\n \n outcar = Outcar(file_path + 'OUTCAR')\n \n magm_list = []\n for atom in range(len(conv_struc)): \n magm_list.append(outcar.magnetization[atom]['tot'])\n df_bulk.Magm[idx + 1] = magm_list\n \n if tot_mag >= 0.5: # not a physical definition \n df_bulk.Mag_O[idx+1] = 'FM'\n elif tot_mag < 0.5:\n df_bulk.Mag_O[idx+1] = 'NM'\n \n bulk_opt = read_vasp(file_path + 'CONTCAR')\n elements = []\n for element in bulk_opt.get_chemical_symbols():\n if element not in elements:\n elements.append(element)\n\n struc = Structure.from_file(file_path + 'CONTCAR')\n df_bulk.structure[idx+1] = bulk_opt # use ase.Atoms object\n \n # Asite dataframe\n for Asite_element in Asite_elements:\n if Asite_element in elements:\n \n df_Asite['formula_%s' % (Asite_element)][idx + 1] = formula\n df_Asite['total_E_%s' % (Asite_element)][idx + 1] = tot_E\n df_Asite['tot_mag_%s' % (Asite_element)][idx + 1] = tot_mag\n df_Asite['DHf_%s' % (Asite_element)][idx + 1] = fE\n df_Asite['Ehull_ref_%s' % (Asite_element)][idx + 1] = df_entries['e_above_hull'][idx]\n df_Asite['Volume_%s' % (Asite_element)][idx + 1] = volume\n \n except FileNotFoundError:\n # print('%03d_%s/2nd files are not found' % (idx + 1.0, formula))\n f.writelines('%s files are not found\\n' % (file_path))\n continue\n\n try:\n bsv = BSVasprun(file_path + 'DOS/vasprun.xml', parse_projected_eigen = True)\n bs = bsv.get_band_structure(kpoints_filename = file_path + 'DOS/KPOINTS', line_mode = True)\n vbm = bs.as_dict()['vbm']['energy']\n e_fermi = bs.as_dict()['efermi']\n cbm = bs.as_dict()['cbm']['energy']\n \n df_bulk.VBM[idx+1] = vbm\n df_bulk.E_fermi[idx+1] = e_fermi\n df_bulk.CBM[idx+1] = cbm\n\n bg = bs.get_band_gap()['energy']\n bgpath = bs.get_band_gap()['transition']\n \n if bs.get_band_gap()['direct'] == True:\n bgtype = 'Direct'\n elif bs.get_band_gap()['direct'] == False:\n bgtype = 'Indirect'\n elif bg is None:\n bg = 0.0\n bgtype = None\n \n df_bulk.Eg[idx+1] = bg\n df_bulk.bgpath[idx+1] = bgpath\n df_bulk.bgtype[idx+1] = bgtype\n\n f.writelines(\"%03d\\t%s\\t\" % (idx + 1.0, formula))\n \n if (type(vbm) and type(cbm)) == float:\n f.writelines(\"%4.3f\\t%4.3f\\t%4.3f\\t%4.3f\\t%4.3f\\t\" % (df_entries['band_gap'][idx], bg, vbm, e_fermi, cbm))\n f.writelines(\"%s\\t%s\\n\" % (bgtype, bgpath))\n elif (vbm and cbm) == None:\n f.writelines(\"%4.3f\\tNone\\tNone\\t%4.3f\\tNone\\t\" % (df_entries['band_gap'][idx], e_fermi))\n f.writelines(\"%s\\t%s\\n\" % (bgtype, bgpath))\n\n \"\"\"\n Plot DOS & Band\n \"\"\"\n dosv = Vasprun(file_path + 'DOS/vasprun.xml', parse_dos = True)\n cdos = dosv.complete_dos\n\n bsdosplot = BSDOSPlotter(bs_projection = \"elements\", dos_projection = \"elements\",\n vb_energy_range = 10, cb_energy_range = 10, egrid_interval = 2,\n font = 'DejaVu Sans')\n bsdosplot.get_plot(bs, cdos).savefig('results/plots/%03d_%s.png' % (idx + 1.0, formula), dpi = 300)\n if idx < 20:\n print(df_bulk.head(20))\n else:\n print(df_bulk[idx-20:idx])\n\n except FileNotFoundError:\n f.writelines('%s are not found\\n' % (file_path))\n print('%s are not found' % (file_path))\n continue\n \n except:\n f.writelines('%sDOS files - unknown error\\n' % (file_path))\n print('%sDOS files - unknown error' % (file_path))\n continue\n\n df_bulk.to_csv('results/df_bulk_v2.csv')\n df_bulk.to_pickle('results/df_bulk_v2.pkl')\n \n df_Asite.to_csv('results/df_Asite.csv')\n df_Asite.to_pickle('results/df_Asite.pkl')\n\n end_time = time.time()\n f.writelines('Execution time for script (sec) : %6.1f\\n' % (end_time - start_time))\n\n\n","sub_path":"krict_ML/ABO3/automation/for_group/02_bulk_analysis/bulk_analysis_v7.py","file_name":"bulk_analysis_v7.py","file_ext":"py","file_size_in_byte":14703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"257708143","text":"class Interface:\n def __init__(self, name,type,enabled, phy_saddress, mtu, oper_status, speed,ip,prefix_length):\n self.name = name\n self.type = type\n self.enabled = enabled\n self.phys_address = phy_saddress\n self.mtu = mtu\n self.oper_status = oper_status\n self.speed = speed\n self.ip =ip\n self.prefix_length=prefix_length\n\n\n","sub_path":"SwitchDBCP/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"300370796","text":"# 3.2 Co jest zlego w kodzie\nif __name__ == \"__main__\":\n\n L = [3, 5, 4]\n L = L.sort()\n # Przypisujemy zmiennej l wywołanie funkcji sort na liście L, podczas gdy metoda sort() sortuje listę w\n # miejscu, nie zwraca nowej wartosci, L.sort() zwraca None\n\n x, y = 1, 2, 3\n # nie wiadomo którą wartośc chcieliśmy przyporządkować do którejś zmiennej(ValueError), za mało zmiennych, nierówne długości sekwencji\n\n X = 1, 2, 3\n X[1] = 4\n # X jest krotką, nie można jej modyfikować , ponieważ ma ustalony rozmiar\n\n X = [1, 2, 3]\n X[3] = 4\n # W liscie elementy liczymy od 0, więc indeks 3 wychodzi poza listę\n\n X = \"abc\"\n X.append(\"d\")\n # metodę append możemy wykonywać tylko na listach a X jest stringiem(stringi są niezmienne)\n\n L = list(map(pow, range(8)))\n # metoda pow podnosząca liczbe do wyzbnaczonej potegi potrzebuje 2 argumentow, a ma podany 1 argument\n","sub_path":"Zestaw3/3_2.py","file_name":"3_2.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"453769608","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org)\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# See also: http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/tkFileDialog.html\n# http://tkinter.unpythonic.net/wiki/tkFileDialog\n\n# Intended for cases where the user wants to create a new file or replace an\n# existing file. If the user selects an existing file, a pop-up will appear\n# informing that the file already exists, and asking if they really want to\n# replace it. \n\nimport os\nimport tkinter as tk\nimport tkinter.filedialog\n\n# FILE_TYPES = [(label1, pattern1), (label2, pattern2), ...]\nFILE_TYPES = [\n ('Python Source Files', '.py'),\n ('C++ Source Files', '.cpp .cc .c .h .hpp'),\n ('All Files', '.*')\n ]\n\nHOME = os.path.expanduser(\"~\")\n\nroot = tk.Tk()\n\ndef save_file():\n path = tk.filedialog.asksaveasfilename(parent=root,\n filetypes=FILE_TYPES, # optional\n defaultextension='.py', # optional\n initialdir=HOME, # optional\n initialfile='foo.py', # optional\n title='Select your file') # optional\n\n print(\"FILEPATH:\", path)\n\nsave_button = tk.Button(root, text=\"Save\", command=save_file)\nsave_button.pack()\n\ntk.mainloop()\n\n","sub_path":"python/tkinter/python3/file_dialog_save_file_path.py","file_name":"file_dialog_save_file_path.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"343285425","text":"# Задание 1: Посчитать количество гласных в каждом слове текста.\n# Вывести максимальное количество гласных в одном слове\n\ntext = \"Proineeeeeee eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada.\"\n\nwordList = text.split()\nprint(wordList)\n\nfor word in wordList:\n print(word)\n letters = 'aeiouy'\n counter = 0\n for x in letters:\n counter += word.count(x)\n print(counter)\n\n check = counter\nwhile check > counter:\n print('max =', check)\n print('_ _ ' * 30)\n\n\n","sub_path":"Lesson_3.py","file_name":"Lesson_3.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239468194","text":"from pong.exporter import Exporter\nfrom pong.exporter import get_test_run\nimport ssl\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--project\", help=\"Project ID\",\n default=\"RedHatEnterpriseLinux7\")\nparser.add_argument(\"--test-run-id\", help=\"Unique ID of a Test Run\")\nparser.add_argument(\"--pong-path\", help=\"Path to pong-results.xml file\",\n default=\"../../pong-results.xml\")\n\nargs = parser.parse_args()\n\ntr = get_test_run(project_id=args.project, test_run_id=args.test_run_id)\nif tr.query is not None:\n # tr.query = \"(title:rhsm.cli.* OR title:rhsm.gui.*)\"\n tr.query = None\nif tr.select_test_cases_by != \"automatedProcess\":\n #tr.select_test_cases_by = \"staticQueryResult\"\n tr.select_test_cases_by = \"automatedProcess\"\nif not tr.project_id:\n tr.project_id = \"RedHatEnterpriseLinux7\"\nif not tr.template:\n tr.template = \"sean toner test template\"\n\ndone = 3\nwhile done > 0:\n try:\n tr.update()\n done = 0\n except ssl.SSLError as se:\n # give 3 tries total\n done -= 1\n\nsuite = Exporter(args.testng_path)\nsuite.update_test_run(tr)\n","sub_path":"pong/tests/test_updaterun.py","file_name":"test_updaterun.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"306546721","text":"#coding=utf8\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom Item.MainList import MainList\nfrom Function.DataManager import imgs\nfrom Item.ImgFrame import ImgFrame\n\nclass FaceList(MainList):\n def __init__(self, viewer):\n MainList.__init__(self)\n self.viewer = viewer\n for num in viewer.getFaceNum():\n self.feedTitle(str(num))\n self.clicked.connect(self.changeViewer)\n\n\n def changeViewer(self, item):\n num = item.data().toInt()[0]\n self.viewer.displayFaceInformation(num)\n\n # 设置切换页面\n def feedTitle(self, title):\n item = QListWidgetItem(QIcon('../icon/face.png'),title)\n item.setSizeHint(QSize(140,40))\n self.addItem(item)\n\nclass FaceView(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.setLayout(QHBoxLayout())\n self.curFrame = None\n\n # 获取标签列表(此处是数字)\n def getFaceNum(self):\n return range(len(imgs))\n\n #切换标签,显示页面信息\n def displayFaceInformation(self, num):\n frame = ImgFrame(imgs[num], num)\n\n if self.curFrame != None:\n self.curFrame.deleteLater()\n self.layout().removeWidget(self.curFrame)\n self.layout().addWidget(frame)\n self.curFrame = frame\n \nclass FaceWidget(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n\n layout = QHBoxLayout()\n self.faceView = FaceView()\n self.list = FaceList(self.faceView)\n \n layout.addWidget(self.list)\n layout.addWidget(self.faceView)\n\n self.setLayout(layout)\n self.setMinimumWidth(840)\n\n\n\n","sub_path":"face/Widget/FaceWidget.py","file_name":"FaceWidget.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"34797665","text":"from xworld3d_env import XWorld3DEnv\nfrom py_gflags import get_flag\nfrom py_gflags import log_info\nimport os\nimport random\n\nclass XWorld3DNav(XWorld3DEnv):\n def __init__(self, asset_path):\n super(XWorld3DNav, self).__init__(\n asset_path=asset_path,\n max_height=7,\n max_width=7)\n self.curriculum = get_flag(\"curriculum\")\n self.current_level = 0\n\n def _configure(self):\n self.set_goal_subtrees([\"animal\", \"others\", \"furniture\"])\n self.set_entity(type=\"agent\")\n\n goal_names = self.get_all_possible_names(\"goal\")\n\n ## compute world dims\n min_dim = 3\n max_h, max_w = self.get_max_dims()\n n_levels = max_h - min_dim + 1\n max_num_goals, min_num_goals = 2, 2\n max_goal_classes, min_goal_classes = len(goal_names), len(goal_names)\n max_num_blocks, min_num_blocks = 10, 1\n\n def compute(current_level):\n def interpolate(min_, max_, rate):\n return int(rate * (max_ - min_) + min_)\n\n rate = 0\n if n_levels - 1 > 0:\n rate = float(current_level) / (n_levels - 1)\n return min_dim + current_level, \\\n interpolate(min_num_goals, max_num_goals, rate), \\\n interpolate(min_num_blocks, max_num_blocks, rate), \\\n interpolate(min_goal_classes, max_goal_classes, rate)\n\n if self.curriculum == 0:\n progress = 1.0\n current_dim = max_h\n num_goals = max_num_goals\n num_blocks = max_num_blocks\n num_goal_classes = max_goal_classes\n else:\n flag = False\n if self.get_current_usage() >= self.curriculum \\\n and self.current_level < n_levels - 1:\n log_info(\"~~~~~~ Entering the next level: ~~~~~~~\")\n current_dim, num_goals, num_blocks, num_goal_classes = compute(self.current_level)\n msg = \"%dx%d map, %d goals, %d goal classes, %d blocks -> \" \\\n % (current_dim, current_dim, num_goals, num_goal_classes, num_blocks)\n ## move to the next stage\n self.current_level += 1\n flag = True\n\n current_dim, num_goals, num_blocks, num_goal_classes = compute(self.current_level)\n if flag:\n msg += \"%dx%d map, %d goals, %d goal classes, %d blocks\" \\\n % (current_dim, current_dim, num_goals, num_goal_classes, num_blocks)\n log_info(msg)\n\n self.set_dims(current_dim, current_dim)\n ## set goals\n goal_names = sorted(goal_names)[:num_goal_classes]\n random.shuffle(goal_names)\n assert num_goal_classes >= num_goals\n for i in range(num_goals):\n self.set_entity(type=\"goal\", name=goal_names.pop())\n ## set blocks\n for i in range(num_blocks):\n self.set_entity(type=\"block\", name=random.choice([\"brick\"]))\n","sub_path":"games/xworld3d/maps/XWorld3DNav.py","file_name":"XWorld3DNav.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216497968","text":"from dataclasses import dataclass\n\nfrom geo.address_parser import AddressParser\nfrom geo.geo_answer import GeoAnswer\nfrom geo.repository import GeoDatabase\n\n\n@dataclass\nclass Geocoder:\n raw_address: str\n database: GeoDatabase\n\n def find_geo_data(self) -> GeoAnswer:\n address_parser = AddressParser()\n parse_address = address_parser.get_parse_address(self.raw_address,\n self.database)\n region_id, region = self.database.select_region(parse_address.city)\n city_id = self.database.select_city_id(parse_address.city)\n street_id = self.database.select_street_id(city_id,\n address_parser.street)\n building_id = self.database.select_building_id(street_id,\n parse_address.house)\n coordinate = self.database.get_coordinate(region_id, city_id,\n street_id, building_id)\n return GeoAnswer(region=region, city=parse_address.city,\n street=parse_address.street,\n building=parse_address.house,\n latitude=float(coordinate[0]),\n longitude=float(coordinate[1]))\n","sub_path":"geo/geocoder.py","file_name":"geocoder.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"591203876","text":"# -*- coding: utf-8 -*-\n\n# /*************************************************************************\n# Copyright (C), 2013-2014, SHENZHEN GONGJIN ELECTRONICS. Co., Ltd.\n# module name: xmloperate\n# function: 处理xml文件的创建和xml节点的创建,以及xml文件的解析\n#\n# Author: ATT development group\n# version: V1.1\n# date: 2013.06.20\n# change log:\n# lana 20130619 created\n# cheng 20130625 changed\n# ***************************************************************************\n\nimport time\nimport hashlib\nfrom xml.etree import ElementTree as ET\nfrom xml.etree.ElementTree import ElementTree\nfrom xml.etree.ElementTree import Element\nfrom xml.etree.ElementTree import SubElement\n\n#将各全局变量初始化单独到config模块里\nfrom config import *\nfrom msgdef import *\nfrom utils import json,unjson\n\n\ndef create_empty_xml_file(file_path, root):\n \"\"\"\n 生成一个空的xml文件,只包含root一个根元素\n \"\"\"\n\n # 添加根元素对象\n root_obj = Element(root)\n\n # 创建树对象\n tree = ElementTree(root_obj)\n\n # 写xml文件\n tree.write(file_path, encoding='utf-8', xml_declaration=True)\n\n\ndef create_single_element(name, value=\"\", attr={}):\n \"\"\"\n 创建一个单独的元素,返回元素对象\n \"\"\"\n\n element = Element(name, attrib=attr)\n if value:\n element.text = value\n\n return element\n\n\ndef add_xml_element(file_path, element, parent=None):\n \"\"\"\n 添加xml element到父节点下\n \"\"\"\n if parent is not None:\n assert isinstance(parent,Element)\n else:\n parent = ET.parse(file_path).getroot()\n parent.append(element)\n tree = ElementTree(parent)\n tree.write(file_path, encoding='utf-8', xml_declaration=True)\n\n\n# def parse_xml_file(file_path):\n# \"\"\"\n# 解析xml文件,返回所有子元素的[name,value,attr]列表\n# \"\"\"\n#\n# root = ET.parse(file_path).getroot()\n#\n# return get_children_value(root)\n#\n#\n# def get_children_value(element_object):\n# \"\"\"\n# 返回所有子元素的[name,value,attr]列表\n# \"\"\"\n#\n# tmp_list = []\n#\n# children_element_list = element_object.getchildren()\n# if len(children_element_list) == 0:\n# log.debug(\"element_object have no children\")\n# return None\n# for element in children_element_list:\n# sub_children_list = element.getchildren()\n# if len(sub_children_list) == 0:\n# tmp_list.append([element.tag, element.text, element.attrib])\n# else:\n# tmp_list.append([element.tag, get_children_value(element)])\n#\n# return tmp_list\n\n######################################\n#一级文件(main_property.xml)操作接口\n######################################\ndef insert_lib_node(xml_path, name, path=''):\n \"\"\"\n main.xml插入一条测试库新记录\n @param xml_path: xml文件路径\n @param name: 节点name属性值\n @param path: 节点path属性值\n @return: None\n \"\"\"\n if not path: path = _getPathByName(name)\n root = ET.parse(xml_path).getroot()\n libinfo = {\n \"name\": name,\n #这里存放的path没有实际用到\n \"path\": path\n }\n element1 = create_single_element(\"testlib\", attr=libinfo)\n add_xml_element(xml_path, element1, root)\n log.debug(\"%s插入测试库信息%s\" % (os.path.basename(xml_path), libinfo))\n\n\ndef find_element(file_path, name, parent=None):\n \"\"\"\n 在main.xml的root节点下查找\"name\"属性为name的节点\n @param file_path: xml文件路径\n @param name: 查找的子节点name属性的值\n @param parent: 在该父节点下进行查找,默认root节点\n @return: 查找到则返回True,否则反悔False\n \"\"\"\n if parent is not None:\n assert isinstance(parent,Element)\n else:\n parent = ET.parse(file_path).getroot()\n children = list(parent)\n for child in children:\n if name == child.attrib.get(\"name\", \"\"):\n return True\n return False\n\n\ndef get_all_libinfos(file_path,args):\n \"\"\"\n 获取所有测试库信息\n @param file_path: main.xml文件路径\n @param args:字典键\n @return:\n \"\"\"\n root = ET.parse(file_path).getroot()\n #取出所有测试库名字\n libs = root.getchildren()\n libname_list = []\n for lib in libs:\n lib_name = lib.attrib.get(\"name\", \"\")\n if lib_name:\n libname_list.append(lib_name)\n result = dict().fromkeys(libname_list, [])\n for lib_name in libname_list:\n #处理2级文件\n lib_info = get_nodes_info(getLibXmlPath(lib_name),args)\n result[lib_name] = lib_info\n return result\n\n######################\n#二级xml文件操作接口\n######################\ndef insert_sub_node(file_path, kw):\n \"\"\"\n 在对应测试库xml文件中插入一条节点信息,如果没有该xml文件,则创建\n @param file_path: 测试库.xml文件路径\n @param kw: 节点信息\n @return:\n \"\"\"\n #changed by chenguo7-8\n #该函数功能被ZipFile.update_xml方法替代\n pass\n # libfile_path = kw.get(ZIP_FILE_PATH,'')\n # ZipFile(libfile_path).update_xml()\n #log.info(\"这里新建节点\")\n # if not os.path.exists(file_path):\n # open(file_path, 'wb').close()\n # create_empty_xml_file(file_path, \"root\")\n # node = create_single_element(\"node\")\n # for k, v in kw.items():\n # sub_node = SubElement(node, k)\n # # 对非字符串值处理\n # sub_node.text = json(v)\n # #增加时间标签(也要jason序列化)\n # SubElement(node, UPLOAD_TIME).text = json(time.strftime('%Y-%m-%d %H:%M:%S'))\n # add_xml_element(file_path, node)\n\ndef get_nodes_info(file_path,args=()):\n \"\"\"\n 获取2级xml文件所有节点的属性。\n @param file_path:\n @param args:需要返回的字典关键字tuple\n @return:[{'md5': 'FBD7894B3CB89DD90E98F5FEADF805F6',\n 'time': '2013-06-25 14:38:37',\n 'version': 'V1.0.1'},...,{}\n ]\n \"\"\"\n root = ET.parse(file_path).getroot()\n nodes = root.findall('node')\n nodes_info_dict = []\n for node in nodes:\n #获取每个节点的标签和值\n if args:\n # condition = lambda n,: n.tag\n # filter()\n property_list = [(c.tag, unjson(c.text)) for c in node.getchildren() if c.tag in args]\n else:\n property_list = [(c.tag, unjson(c.text)) for c in node.getchildren()]\n #反序列化\n node_info = dict(property_list)\n version = node_info.get(TESTLIB_VERSION, '')\n if not version:\n continue\n nodes_info_dict.append(node_info)\n return nodes_info_dict\n\n#################################\n#私有方法(测试库二级xml配置文件命名规则)\n#################################\ndef _getPathByName(libname):\n \"\"\"\n @param libname: 测试库名\n @return: 测试库xml文件名\n \"\"\"\n return '.'.join([libname, 'xml']).lower()\n\n#########\n#公共方法\n#########\ndef getLibXmlPath(libname=''):\n \"\"\"\n 获取测试库二级xml配置文件的全路径,无参数则返回一级xml文件(main_property.xml)\n @param libname: 测试库名\n @return: 测试库二级xml配置文件全路径\n \"\"\"\n if not libname :\n return os.path.join(XML_FILE_DIR, ROOT_FILE)\n return os.path.join(XML_FILE_DIR,_getPathByName(libname))\n\ndef update_config(name,node_info):\n\n root_xml_path = getLibXmlPath()\n if not os.path.exists(root_xml_path):\n XmlRepairer().reBuild()\n return None\n #changed by chenguo 7-4\n #这个函数功能用ZipFile.update_xml()方法实现\n\n #判断main.xml是否存在记录\n # if not find_element(root_xml_path, name):\n # 不存在该测试库节点,允许上传,并更新1级xml文件\n # insert_lib_node(root_xml_path, name, path='')\n #找到二级xml文件路径\n # libfile_path = getLibXmlPath(name)\n #在二级xml文件里插入节点\n # insert_sub_node(libfile_path, node_info)\n zip_file_path = node_info.get(ZIP_FILE_PATH,'')\n assert zip_file_path\n ZipFile(zip_file_path).update_xml()\n\ndef get_file_md5(data):\n \"\"\"\n 获取md5\n @param data: str object\n @return: MD5值字符串\n \"\"\"\n md5o = hashlib.md5()\n md5o.update(data)\n return md5o.hexdigest()\n\nclass ZipFile(object):\n \"\"\"\n zip压缩文件对象\n \"\"\"\n lib_name = \"\"\n lib_version = \"\"\n att_version = \"\"\n upload_time = \"\"\n md5 = \"\"\n is_remote = False\n def __init__(self,abspath):\n assert os.path.isfile(abspath)\n self.abspath = abspath\n dir_index = abspath.find('zippackage')\n if dir_index > 0:\n self.path = abspath[dir_index:]\n else:\n log.error(\"文件存放路径[%s]出错,无法解析\"%abspath)\n self.path = abspath\n self.init_info()\n self.info = {\n BASED_ATTROBOT_VERSION : self.att_version,\n ZIP_FILE_PATH :self.path,\n ZIP_FILE_MD5 : self.md5,\n TESTLIB_VERSION :self.lib_version,\n UPLOAD_TIME : self.upload_time,\n TESTLIB_REMOTE_FLAG : self.is_remote,\n }\n\n def init_info(self):\n curdir,filename = os.path.split(self.abspath)\n #目录结构被修改成先库名,再平台版本\n _ ,self.att_version = os.path.split(curdir)\n _ ,self.lib_name = os.path.split(_)\n with open(self.abspath,\"rb\") as f:\n self.md5 = get_file_md5(f.read())\n f.close()\n self.upload_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.path.getmtime(self.abspath)))\n file_split = filename.split(REMOTE_SEP)\n if len(file_split) == 2:\n self.is_remote = True\n self.lib_version = file_split[0]\n else:\n self.lib_version = os.path.splitext(filename)[0]\n\n\n def update_xml(self):\n \"\"\"\n 将文件信息更新至xml配置文件\n \"\"\"\n root_config = getLibXmlPath()\n #先检查一级xml配置文件是否有该文件对应库的信息\n if not find_element(root_config, self.lib_name):\n insert_lib_node(root_config, self.lib_name)\n #在二级xml配置文件中插入信息\n lib_config = getLibXmlPath(self.lib_name)\n if not os.path.exists(lib_config):\n open(lib_config, 'wb').close()\n create_empty_xml_file(lib_config, \"root\")\n log.debug(\"更新库%s的xml配置文件\"%self.lib_name)\n node = create_single_element(\"node\")\n for k, v in self.info.items():\n sub_node = SubElement(node, k)\n sub_node.text = json(v)\n add_xml_element(lib_config, node)\n\n\nclass XmlRepairer(object):\n \"\"\"\n xml文件维护类\n \"\"\"\n #待修复文件列表\n def __init__(self,root_file_path = ZIP_FILE_DIR):\n self.filelist = []\n if not os.path.exists(root_file_path):\n os.mkdir(root_file_path)\n self.root_file_path = root_file_path\n self.root_xml_path = getLibXmlPath()\n\n def __del__(self):\n del self\n\n def listAll(self,path=''):\n \"\"\"\n 返回目录下所有zip文件对象\n @param path:\n @return:\n \"\"\"\n if not path:\n path = self.root_file_path\n for filedir,_,filenames in os.walk(path):\n if not len(filenames):\n continue\n for filename in filenames:\n if os.path.splitext(filename)[1] != \".zip\":\n continue\n self.filelist.append(ZipFile(os.sep.join([filedir,filename])))\n\n def reBuild(self):\n \"\"\"\n 开始维护\n @return:\n \"\"\"\n #重置所有xml配置文件\n from shutil import rmtree\n def onerror(*args):\n log.exception(\"对'%s'执行%s时出错:\\n\"%(args[1],args[0].__name__))\n rmtree(XML_FILE_DIR,False,onerror)\n log.debug(\"重建xml配置文件目录\")\n os.mkdir(XML_FILE_DIR)\n #重建一级xml配置文件\n open(self.root_xml_path, 'wb').close()\n create_empty_xml_file(self.root_xml_path, \"root\")\n log.debug(\"创建一级xml文件%s\"%os.path.basename(self.root_xml_path))\n self.listAll(self.root_file_path)\n for f in self.filelist:\n f.update_xml()\n #重建完重置待修复文件列表\n self.filelist = []\nif __name__ == '__main__':\n # name = 'test'\n # node_info = {'version': 'V1.0.1', 'md5': 'FBD7894B3CB89DD90E98F5FEADF805F6'}\n # update_config(name,node_info)\n log.setLevel(10)\n xr = XmlRepairer()\n xr.reBuild()","sub_path":"python/UpgradeServer/upgrade/xmloperate.py","file_name":"xmloperate.py","file_ext":"py","file_size_in_byte":12666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368397937","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom sqlalchemy import create_engine\n\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\nfrom settings import logger\n\nquant_path = os.path.dirname(os.path.abspath(__file__))\nworkers_path = os.path.dirname(quant_path)\nsrc_path = os.path.dirname(workers_path)\nif src_path not in sys.path:\n sys.path.append(src_path)\n\nfrom share.conf import mysql\n\naddress = 'mysql+pymysql://%s:%s@%s:%s/%s' % (mysql.get('user'),\n mysql.get('password'),\n mysql.get('host'),\n mysql.get('port'),\n mysql.get('db'))\nconn = create_engine(address)\n\n\ndef read_day_kline(varieties, start_date, end_date):\n contractname = varieties + '9999' # 主力合约\n\n sql = 'select date_time,contract,price_open,price_low,price_high,price_close from alpha.day_kline\\\n where contract=\"' + contractname + '\" and date_time between \"' + start_date + '\" and \"' + end_date + '\"'\n\n day_kline_data = pd.read_sql(sql, conn)\n\n t_close = np.array(day_kline_data['price_close'][1:])\n y_close = np.array(\n day_kline_data['price_close'][0:len(day_kline_data) - 1])\n rise = (t_close - y_close) / y_close\n b = np.insert(rise, 0, 'NaN')\n day_kline_data['rise'] = b\n day_kline_data['varieties'] = varieties\n\n return day_kline_data\n\n\ndef read_last_history(varieties):\n sql = 'select max(date) from alpha.cross_star_history where varieties = \"' + varieties + '\"'\n date = pd.read_sql(sql, conn)\n\n return date['max(date)'][0]\n\n\ndef to_cross_star_history(dataset):\n if isinstance(dataset, pd.DataFrame) and not dataset.empty:\n try:\n logger.info(\"品类%s 日期%s历史写入数据到表cross_star_history\",dataset['varieties'][0],dataset['date'].tolist())\n dataset.to_sql(\"cross_star_history\", conn, if_exists='append',\n index=False)\n except:\n logger.error(\"表cross_star_history中内容已存在,写入失败\")\n else:\n logger.info(\"表cross_star_history数据写入成功\")\n\n\ndef to_cross_star_threshold(dataset):\n if isinstance(dataset, pd.DataFrame) and not dataset.empty:\n try:\n logger.info(\"品类%s 日期%s阀值写入数据到表cross_star_threshold\",dataset['varieties'][0],dataset['date'].tolist())\n dataset.to_sql(\"cross_star_threshold\", conn, if_exists='append',\n index=False)\n except:\n logger.error(\"表cross_star_threshold内容已存在,写入失败\")\n else:\n logger.info(\"表cross_star_threshold数据写入成功\")\n","sub_path":"src/workers/futures_quant/read_alpha.py","file_name":"read_alpha.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"385323731","text":"import copy\nimport logging\nimport os\nfrom typing import Any, Dict, Iterator, List\n\nfrom kubernetes.watch import Watch\n\nfrom ray.autoscaler._private.kubernetes import custom_objects_api\n\nRAY_NAMESPACE = os.environ.get(\"RAY_OPERATOR_POD_NAMESPACE\")\n\nRAY_CONFIG_DIR = os.path.expanduser(\"~/ray_cluster_configs\")\nCONFIG_SUFFIX = \"_config.yaml\"\n\nCONFIG_FIELDS = {\n \"maxWorkers\": \"max_workers\",\n \"upscalingSpeed\": \"upscaling_speed\",\n \"idleTimeoutMinutes\": \"idle_timeout_minutes\",\n \"headPodType\": \"head_node_type\",\n \"workerDefaultPodType\": \"worker_default_node_type\",\n \"workerStartRayCommands\": \"worker_start_ray_commands\",\n \"headStartRayCommands\": \"head_start_ray_commands\",\n \"podTypes\": \"available_node_types\"\n}\n\nNODE_TYPE_FIELDS = {\n \"minWorkers\": \"min_workers\",\n \"maxWorkers\": \"max_workers\",\n \"podConfig\": \"node_config\",\n \"rayResources\": \"resources\",\n \"setupCommands\": \"worker_setup_commands\"\n}\n\nPROVIDER_CONFIG = {\n \"type\": \"kubernetes\",\n \"use_internal_ips\": True,\n \"namespace\": RAY_NAMESPACE\n}\n\nroot_logger = logging.getLogger(\"ray\")\nroot_logger.setLevel(logging.getLevelName(\"DEBUG\"))\n\"\"\"\nownerReferences:\n - apiVersion: apps/v1\n controller: true\n blockOwnerDeletion: true\n kind: ReplicaSet\n name: my-repset\n uid: d9607e19-f88f-11e6-a518-42010a800195\n\"\"\"\n\n\ndef config_path(cluster_name: str) -> str:\n file_name = cluster_name + CONFIG_SUFFIX\n return os.path.join(RAY_CONFIG_DIR, file_name)\n\n\ndef cluster_cr_stream() -> Iterator:\n w = Watch()\n return w.stream(\n custom_objects_api().list_namespaced_custom_object,\n namespace=RAY_NAMESPACE,\n group=\"cluster.ray.io\",\n version=\"v1\",\n plural=\"rayclusters\")\n\n\ndef cr_to_config(cluster_resource: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Convert RayCluster custom resource to a ray cluster config for use by the\n autoscaler.\"\"\"\n cr_spec = cluster_resource[\"spec\"]\n cr_meta = cluster_resource[\"metadata\"]\n config = translate(cr_spec, dictionary=CONFIG_FIELDS)\n pod_types = cr_spec[\"podTypes\"]\n config[\"available_node_types\"] = get_node_types(\n pod_types, cluster_name=cr_meta[\"name\"], cluster_uid=cr_meta[\"uid\"])\n config[\"cluster_name\"] = cr_meta[\"name\"]\n config[\"provider\"] = PROVIDER_CONFIG\n return config\n\n\ndef get_node_types(pod_types: List[Dict[str, Any]], cluster_name: str,\n cluster_uid: str) -> Dict[str, Any]:\n cluster_owner_reference = get_cluster_owner_reference(\n cluster_name, cluster_uid)\n node_types = {}\n for pod_type in pod_types:\n name = pod_type[\"name\"]\n pod_type_copy = copy.deepcopy(pod_type)\n pod_type_copy.pop(\"name\")\n node_types[name] = translate(\n pod_type_copy, dictionary=NODE_TYPE_FIELDS)\n # Deleting a RayCluster CR will also delete the associated pods.\n node_types[name][\"node_config\"][\"metadata\"].update({\n \"ownerReferences\": [cluster_owner_reference]\n })\n return node_types\n\n\ndef get_cluster_owner_reference(cluster_name: str,\n cluster_uid: str) -> Dict[str, Any]:\n return {\n \"apiVersion\": \"apps/v1\",\n \"controller\": True,\n \"blockOwnerDeletion\": True,\n \"kind\": \"RayCluster\",\n \"name\": cluster_name,\n \"uid\": cluster_uid\n }\n\n\ndef translate(configuration: Dict[str, Any],\n dictionary: Dict[str, str]) -> Dict[str, Any]:\n return {dictionary[field]: configuration[field] for field in configuration}\n","sub_path":"python/ray/operator/operator_utils.py","file_name":"operator_utils.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"236263978","text":"#!/usr/bin/env python\n# ! -*- coding: utf-8 -*\nfrom __future__ import absolute_import\nfrom __future__ import print_function\n\n# from requests.packages.urllib3 import request\nfrom django.shortcuts import render\nfrom django.contrib import messages\nfrom django.shortcuts import redirect\n\n\n__author__ = \"Oliver Guggenbuehl\"\n__copyright__ = \"Copyright 2013, The GUOPY Project\"\n__credits__ = [\"Oliver Guggenbuehl\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"Oliver Guggenbuehl\"\n__email__ = \"me@oliver-guggenbuehl.com\"\n__status__ = \"Test\"\n\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\nfrom .saltcore.apitest import SaltApiManager\nfrom saltmaster.saltcore.saltredis import _get_serv\nfrom .forms import NameForm\nimport json\nimport requests\n\n\n#the decorator\ndef myuser_login_required(f):\n def wrap(request, *args, **kwargs):\n #this check the session if userid key exist, if not it will redirect to login page\n if 'userid' not in request.session.keys():\n return HttpResponseRedirect(\"/\")\n return f(request, *args, **kwargs)\n wrap.__doc__=f.__doc__\n wrap.__name__=f.__name__\n return wrap\n\n#how you use this decor\n#@myuser_login_required\n\ndef get_jobs_details(request, job):\n job = job\n serv = _get_serv(ret=None)\n #redis_keys = serv.keys('fedora-lamp.home:*')\n if job:\n redis_keys = serv.get(str(job))\n print(redis_keys)\n return render(request, 'jobsdetails.html', { 'jobs': [json.loads(redis_keys)]})\n else:\n return None\n\ndef get_jobs(request, id):\n tgt = id\n serv = _get_serv(ret=None)\n #redis_keys = serv.keys('fedora-lamp.home:*')\n if id:\n redis_keys = serv.keys('{0}:*'.format(id))\n print(redis_keys)\n return render(request, 'jobs.html', { 'jobs': sorted(redis_keys)})\n else:\n return None\n #redis_keys = [ serv.get('fedora-lamp.home:20151201201940681246') for a in redis_keys ]\n #print(serv.get('fedora-lamp.home:20151201201940681246'))\n #print(redis_keys)\n\n #serv.getset('minioncount',{'up': 2, 'down': 2})\n\n #redis_keys = []\n #redis_keys = [ serv.lindex(a, 0) for a in redis_keys ]\n #redis_keys = [ serv.get(a) for a in redis_keys ]\n #print(redis_keys)\n #print(type(redis_keys))\n #return HttpResponse(json.dumps(redis_keys))\n #jobs = json.loads(redis_keys)\n #jobs = json.dumps(redis_keys)\n #jobs = redis_keys\n #print(type(redis_keys))\n #return render(request, 'jobs.html', { 'jobs': jobs})\n #return HttpResponse(content=json.dumps(redis_keys),\n # content_type=\"application/json\"\n # )\ndef loggout(request):\n return HttpResponse(saltrun.logout())\n\n\"\"\"\nrequest.session['foo'] = 'bar'\nRetrieve a session key:\n request.session.get('foo')\nDelete a key you stored in the session:\ndel request.session['foo']\n\"\"\"\n\ndef login(request):\n if request.POST.get('username') is not None:\n username = request.POST['username']\n password = request.POST['password']\n saltrun = SaltApiManager(user=username,\n password=password,\n SALT_API=settings.SALT_API,\n PORT=settings.SALT_PORT\n )\n request.session['salttoken'] = saltrun.gettoken()\n request.session['username'] = username\n request.session['password'] = password\n request.session['headers'] = saltrun.getheaders()\n request.session['saltapi'] = saltrun.getsaltapi()\n request.session['keys'] = saltrun.listkeys()\n print('headers: ', request.session.get('headers'))\n\n if request.session.get('salttoken', False):\n messages.success(request, 'Login successfully')\n messages.warning(request, 'Waring not all actions were successfully')\n return redirect('dashboard')\n #return render(request, 'dashboard.html', minions)\n\n else:\n messages.error(request, 'Login Failed!')\n #return HttpResponse(\"Your username and password didn't match.\")\n\n\n return render(request, 'login.html', {'form': NameForm()})\n\n\ndef dash(request):\n \"\"\"\n self.data = {\n 'fun': 'key.list_all',\n 'client':'wheel',\n 'tgt':'*',\n 'match': ''\n }\n \"\"\"\n if request.session.get('salttoken', False):\n keys = runsalt(request, tgt='*', fun='key.list_all', client='wheel')['return'][0]['data']['return']['minions']\n # (r.json()['return'])\n #keys[0]['data']['return']['minions']\n #print(keys[0]['data']['return']['minions'])\n\n #keys = request.session.get('keys', [])\n #print('keys: ', keys)\n grains = runsalt(request, tgt='*', fun='grains.items')['return'][0]\n minions = {'minions': keys,\n 'grains': grains,\n 'grains2': []}\n #messages.warning(request, 'Waring not all actions were successfully')\n messages.success(request, 'get minions')\n return render(request, 'dashboard.html', minions)\n else:\n return redirect('saltlogin')\n\n\ndef runsalt(request, tgt=None, fun='test.ping', client='local', arg=None):\n tgt = tgt\n fun = fun\n data = {\n 'tgt': tgt,\n 'fun': fun,\n 'client': 'local',\n }\n if client:\n data['client'] = client\n data['match'] = ''\n if arg:\n data['arg'] = arg\n print(request.session.get('saltapi') + '/',\n json.dumps(data),\n request.session.get('headers')\n )\n r = requests.post(request.session.get('saltapi') + '/',\n data=json.dumps(data),\n headers=request.session.get('headers')\n )\n #print('content: ', json.loads(r.content)[\"return\"][0]['data']['jid'])\n print('content: ', json.loads(r.content)[\"return\"][0])\n if 'data' in json.loads(r.content)[\"return\"][0].keys():\n print('JID: ', json.loads(r.content)[\"return\"][0]['data']['jid'])\n #\"data\": {\"jid\"])\n if r.status_code == 200:\n return r.json()\n #self.r.json()['return'][0]['data']['return']['minions']\n else:\n return None\n\ndef getstatus(request, id):\n tgt = id\n fun = 'status.loadavg'\n returnsalt = runsalt(request, tgt=tgt, fun='status.loadavg')\n print(returnsalt['return'])\n if returnsalt is not None:\n #return HttpResponse(returnsalt)\n return render(request, 'jobs.html', { 'jobs': returnsalt['return'] })\n\n\"\"\"\n# curl -k http://myip:8888/run -d client=runner -d fun='jobs.list_jobs' -d username='xxxx' -d password='xxxx' -d eauth='pam'\n# curl -k http://myip:8888/run -d client=runner -d fun='jobs.lookup_jid' -d jid=XXX -d username='xxxx' -d password='xxxx' -d eauth='pam'\n\"\"\"\n\ndef runsingle(request, id):\n tgt = id\n fun = 'status.loadavg'\n #self.r.json()['return'][0]['data']['return']['minions']\n returnsalt = runsalt(request, tgt=tgt, fun='state.single', arg='service.status sshd')\n print(type(returnsalt))\n if returnsalt is not None:\n return HttpResponse(returnsalt)\n\n\ndef saltconnect(request):\n saltrun = SaltApiManager(user='user',\n password='pass',\n SALT_API=settings.SALT_API,\n PORT=settings.SALT_PORT\n )\n print(saltrun)\n return HttpResponse(saltrun)\n\ndef grains_get(request, id):\n tgt = id\n returnsalt = runsalt(request, tgt=tgt, fun='grains.items')['return'][0]\n print('grains: ', returnsalt)\n if returnsalt is not None:\n #return HttpResponse(returnsalt)\n return render(request, 'grains.html', { 'grains': returnsalt })\n\ndef index(request):\n return HttpResponse(\"Hello, world. You're at the polls index.\")\n","sub_path":"saltmaster/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"639932352","text":"from flask.ext.wtf import Form\nfrom wtforms import StringField, BooleanField, IntegerField, SubmitField\nfrom wtforms.validators import DataRequired, Length\n\n\nclass LoginForm(Form):\n openid = StringField('openid', validators=[DataRequired()])\n remember_me = BooleanField('remember_me', default=False)\n\nclass ClassForm(Form):\n classCode = StringField('Class Code', validators=[DataRequired()])\n cohort = IntegerField('Cohort', validators=[DataRequired()])\n\nclass AddClassForm(ClassForm):\n submit = SubmitField('Submit')\n\nclass EditClassForm(ClassForm):\n submit = SubmitField('Submit')\n delete = SubmitField('Delete')\n\nclass DeleteClassForm(ClassForm):\n confirmDelete = SubmitField('Confirm Delete')\n","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281055785","text":"import smartpy as sp\n\nclass Counter(sp.Contract):\n def __init__(self, initial_value):\n self.init(stored_value=initial_value)\n\n @sp.entry_point\n def increment(self, params):\n self.data.stored_value += params.value\n\n @sp.entry_point\n def decrement(self, params):\n self.data.stored_value -= params.value\n\n\n@sp.add_test(name=\"Counter\")\ndef test():\n scenario = sp.test_scenario()\n counter = Counter(initial_value=0)\n scenario += counter\n\n scenario.verify(counter.data.stored_value == 0)\n\n scenario += counter.increment(value = 1)\n scenario.verify(counter.data.stored_value == 1)\n\n\n scenario += counter.decrement(value = 1)\n scenario.verify(counter.data.stored_value == 0)\n\nsp.add_compilation_target(\"counter\", Counter(initial_value=0))","sub_path":"contracts/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"559645364","text":"#!/usr/bin/python\n# -*- coding: utf-8\nfrom scipy import integrate\nimport matplotlib.pyplot as plt\nimport json\n\nNch = 0.97 ** 5 # 传动装置效率\ng = 9.8 # 重力加速度\nC = 0.5 # 空气阻力系数\nm = 0.8 # 修正系数\nB = 2.79 # 履带中心矩\nG = 500000 # 战斗全重\nH = 2.19 # 坦克高\nrz = 0.318 # 主动轮半径\nPsmax = 116 # 风扇损失功率\nf0 = 0.047 # 地面阻力系数\nQ1 = (3.903, 1.823, 1.539, 1.394, 1.304, 1.257) # 质量增加系数\niq = 0.68 # 前传动比\nib = (7.353, 3.783, 2.713, 1.945, 1.395, 1) # 变速箱传动比\nic = 5.387 # 侧传动比\ndata = {}\ni_zcdb = [] # 总传动比\nfor item in ib:\n i_zcdb.append(iq * item * ic)\n\n# 已知条件\nNep = 2300 # 最大转速\nNe = (1000, 1200, 1400, 1600, 1800, 2000, 2200, 2300)\nPe = (474, 589, 697, 792, 867, 918, 935, 935)\nTe = (4531, 4690, 4754, 4725, 4601, 4384, 4059, 3882)\nne = [] # 各转速传动效率\n\nfor i, j in zip(Ne, Pe):\n Ps = Psmax * (i / Nep) ** 3\n ne.append((j - Ps) / j)\n\nfor i, j in enumerate(i_zcdb):\n v = []\n n = []\n D = []\n A = []\n a = []\n Fj = []\n count = 0\n\n for k, x in zip(Ne, ne):\n v_tmp = 0.377 * rz * k / j\n n_tmp = (0.95 - 0.0017 * v_tmp) * Nch * x\n fj = Te[count] * j * n_tmp / rz\n d = (Te[count] * j * n_tmp / rz - m *\n B * H * C * v_tmp ** 2 / 21.15) / G\n a_tmp = g * (d - f0) / Q1[i]\n A_tmp = 1 / (g * (d - f0) / Q1[i])\n D.append(d) # 动力因数\n v.append(v_tmp) # 速度\n n.append(n_tmp) # 坦克效率\n a.append(a_tmp) # 加速度\n A.append(A_tmp) # 加速度倒数\n Fj.append(fj) # 牵引力\n count += 1\n\n data['d' + str(i + 1)] = dict(v=v, n=n, i=j, D=D, A=A, a=a, Fj=Fj)\nwith open('json.txt', 'w') as f:\n f.write(json.dumps(data, indent=4))\n\n\ndef integrate_t_s(fj, q, x, s):\n y1 = lambda v: 1 / \\\n (g * ((fj - m * B * H * C * v ** 2 / 21.15) / G - f0) / q)\n y2 = lambda v: v / \\\n (g * ((fj - m * B * H * C * v ** 2 / 21.15) / G - f0) / q)\n t, fm = integrate.quad(y1, x, s)\n s, fm = integrate.quad(\n y2, data['d2']['v'][2] / 3.6, data['d2']['v'][7] / 3.6)\n return t, s\n\n# 第一阶段\na1 = g * (2 * data['d2']['D'][0] - 0.04) / 1.2\nt1 = data['d2']['v'][2] / 3.6 / a1\ns1 = 0.5 * a1 * t1 ** 2\nv1 = data['d2']['v'][2]\nwith open('json.txt', 'a+') as f:\n f.write(json.dumps(dict(a1=a1, t1=t1, s1=s1), indent=4))\n\n# 第二阶段\nfj2 = data['d2']['Fj'][0]\nq2 = Q1[1]\nshang = data['d2']['v'][7] / 3.6\nxia = data['d2']['v'][2] / 3.6\nt2, s2 = integrate_t_s(fj2, q2, xia, shang)\nv2 = data['d2']['v'][7]\na2 = (data['d2']['D'][7] - f0) * g / q2\nwith open('json.txt', 'a+') as f:\n f.write(\n json.dumps(dict(q2=q2, fj2=fj2, shang=shang, xia=xia, t2=t2, s2=s2), indent=4))\n\n# 第三阶段\na3 = g * (0 - f0) / Q1[1]\nt3 = 1.0\ns3 = data['d2']['v'][7] * t3 / 3.6 - 0.5 * a3 * t3 ** 2\nv3 = data['d2']['v'][7] + 3.6 * a3 * t3\nwith open('json.txt', 'a+') as f:\n f.write(json.dumps(dict(a3=a3, v3=v3, t3=t3, s3=s3), indent=4))\n# 第四阶段\nfj4 = data['d3']['Fj'][0]\nq4 = Q1[2]\nxia = v3 / 3.6\nshang = data['d3']['v'][7] / 3.6\nt4, s4 = integrate_t_s(fj4, q4, xia, shang)\nv4 = data['d3']['v'][7]\na4 = (data['d3']['D'][7] - f0) * g / q4\n\nwith open('json.txt', 'a+') as f:\n f.write(\n json.dumps(dict(q4=q4, fj4=fj4, shang=shang, xia=xia, t4=t4, s4=s4), indent=4))\n\n# 第五阶段\na5 = g * (0 - f0) / Q1[2]\nt5 = 1.0\ns5 = data['d3']['v'][7] * t5 / 3.6 + 0.5 * a5 * t5 ** 2\nv5 = data['d3']['v'][7] - 3.6 * a5 * t5\n\nwith open('json.txt', 'a+') as f:\n f.write(json.dumps(dict(a5=a5, v5=v5, t5=t5, s5=s5), indent=4))\n\n# 第六阶段\nq6 = Q1[3]\nxia = v5 / 3.6\nv6 = data['d4']['v'][7]\nshang = data['d4']['v'][7] / 3.6\nfj6 = data['d4']['Fj'][0]\nt6, s6 = integrate_t_s(fj6, q6, xia, shang)\na6 = (data['d4']['D'][7] - f0) * g / q6\n\nwith open('json.txt', 'a+') as f:\n f.write(\n json.dumps(dict(q6=q6, shang=shang, xia=xia, fj6=fj6, t6=t6, s6=s6), indent=4))\n\n# 总的时间与距离\nT = t1 + t2 + t3 + t4 + t5 + t6\nS = s1 + s2 + s3 + s4 + s5 + s6\nTZ = [0, t1, t1 + t2, t1 + t2 + t3, t1 + t2 + t3 + t4,\n t1 + t2 + t3 + t4 + t5, t1 + t2 + t3 + t4 + t5 + t6]\nVZ = [0, v1, v2, v3, v4, v5, v6]\nAZ = [0, a1, a2, a3, a4, a5, a6]\nSZ = [0, s1, s1 + s2, s1 + s2 + s3, s1 + s2 + s3 + s4,\n s1 + s2 + s3 + s4 + s5, s1 + s2 + s3 + s4 + s5 + s6]\n\nwith open('json.txt', 'a+') as f:\n f.write(json.dumps(dict(T=T, S=S), indent=4))\n\n\ndef drawpic():\n plt.plot(TZ, VZ, label=\"Velocity\")\n plt.plot(TZ, AZ, label=\"Acceleration\")\n plt.plot(TZ, SZ, label=\"Distance\")\n plt.legend(loc='upper left')\n plt.grid(True)\n plt.title(r't-a/t-v/t-S Curve')\n plt.xlabel('Time (s)')\n plt.show()\n\n\ndef drawpic_1():\n plt.plot(Ne, Pe)\n plt.plot(Ne, Te)\n plt.grid(True)\n plt.show()\n\n\ndef drawpic_2():\n plt.plot(data['d1']['v'], data['d1']['D'], label=\"First Gear\",)\n plt.plot(data['d2']['v'], data['d2']['D'], label=\"Second Gear\",)\n plt.plot(data['d3']['v'], data['d3']['D'], label=\"Third Gear\",)\n plt.plot(data['d4']['v'], data['d4']['D'], label=\"Fourth Gear\",)\n plt.plot(data['d5']['v'], data['d5']['D'], label=\"Fifth Gear\",)\n plt.plot(data['d6']['v'], data['d6']['D'], label=\"Sixth Gear\")\n plt.title(r'Power Characteristic Curve')\n plt.legend(loc='upper right')\n plt.xlabel('Velocity (km/h)')\n plt.ylabel('Power Factor D')\n plt.grid(True)\n plt.show()\n\n\ndef drawpic_3():\n plt.plot(data['d1']['v'], data['d1']['A'], label=\"First Gear\",)\n plt.plot(data['d2']['v'], data['d2']['A'], label=\"Second Gear\",)\n plt.plot(data['d3']['v'], data['d3']['A'], label=\"Third Gear\",)\n plt.plot(data['d4']['v'], data['d4']['A'], label=\"Fourth Gear\",)\n plt.plot(data['d5']['v'], data['d5']['A'], label=\"Fifth Gear\",)\n plt.plot(data['d6']['v'], data['d6']['A'], label=\"Sixth Gear\",)\n plt.title(r'1/a-v Curve')\n plt.legend(loc='upper left')\n plt.xlabel('Velocity (km/h)')\n plt.ylabel('1/a (s2/m)')\n plt.grid(True)\n plt.show()\n\n\ndrawpic()\n","sub_path":"python/chuandongbi.py","file_name":"chuandongbi.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"448903725","text":"import os\nimport json\n\nfrom peachy.db.models import User\nfrom peachy.db.base import scoped_session\n\n\nPACK_PATH = os.path.dirname(os.path.abspath(__file__))\nPEOPLE_PATH = os.path.join(PACK_PATH, \"people.json\")\n\n\nclass Person:\n def __init__(self, firstname, lastname):\n self.firstname = firstname\n self.lastname = lastname\n\n def __repr__(self):\n return f\"{self.fullname}\"\n\n @property\n def fullname(self):\n return f\"{self.firstname} {self.lastname}\"\n\n\ndef load_people(filename):\n people = {}\n\n with open(filename, 'r') as infile:\n raw_data = json.load(infile)\n\n for raw_key, raw_person in raw_data.items():\n key = int(raw_key)\n first_name = raw_person['first_name']\n last_name = raw_person['last_name']\n\n people[key] = Person(first_name, last_name)\n\n return people\n\n\nUSER_MAP = load_people(PEOPLE_PATH)\n\n\ndef import_users():\n people = load_people(PEOPLE_PATH)\n users = []\n\n for discord_id, person in people.items():\n user = User(discord_id=discord_id, first_name=person.firstname, last_name=person.lastname)\n users.append(user)\n\n with scoped_session() as session:\n session.add_all(users)\n","sub_path":"scripts/import_users.py","file_name":"import_users.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"44111215","text":"import os\nimport sys\nimport ROOT\nimport array\nimport AtlasStyle\n\nAtlasStyle.SetAtlasStyle()\n\nfr = ROOT.TFile(\"/work/users/lcerdaal/condor/A/A.root\")\nfr2 = ROOT.TFile(\"/work/users/lcerdaal/condor/b/B.root\")\ntext = ROOT.TLatex()\nline = ROOT.TLine()\nleg1 = ROOT.TLegend(0.37,0.4,0.68,0.2)\n\nsrun=\"/eop\"\n\n\nc1 = ROOT.TCanvas(\"c1\",\"c1\",800,600)\nc1.cd(1)\nhs1 = ROOT.THStack()\nh_eopa = SetBinContent(fr.GetYAxis(\"/%s/EopallclVsP_p_1_#DeltaR_1_Isol_1_Eloss_1_RatioTileLar_1_ClusterCell_2\"%srun),1)\nh_eopa.SetLineColor(2)\nhs1.Add(h_eopa)\nh_eopa = SetBinContent(fr2.GetYAxis(\"/%s/EopallclVsP_p_1_#DeltaR_1_Isol_1_Eloss_1_RatioTileLar_1_ClusterCell_2\"%srun),2)\nh_eopa.SetLineColor(1)\nhs1.Add(h_eopa)\nhs1.SetTitle(\"Eop;Eop\")\nhs1.Draw(\"NOSTACK\")\nc1.SaveAs(\"Eopperiods.pdf\")\n","sub_path":"Eop/scripts/eopvsperiods.py","file_name":"eopvsperiods.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458929717","text":"#simple calculator - Python\n#Mohamad Darwiche\n\ndef handleAdd(x,y):\n return x+y\n\ndef handleSub(x,y):\n return x-y\n\ndef handleDiv(x,y):\n return x/y\n\ndef handleMult(x,y):\n return x*y\n\ndef displayChoices():\n print(\"1-Addition\")\n print(\"2-Subtraction\")\n print(\"3-Division\")\n print(\"4-Multiplication\")\n print(\"5-Quit\")\n\ndef handleChoice(ch,x,y):\n if(ch==1):\n print(\"Adding \", x ,\"+\", y, \"gives you\",handleAdd(x,y))\n elif(ch==2):\n print(\"Subtracting \" , x , \"-\" , y , \"gives you\" , handleSub(x, y))\n elif (ch == 3):\n print(\"Dividing \" , x , \"/\" , y , \"gives you\" , handleDiv(x, y))\n elif (ch == 4):\n print(\"Multiplying \" , x , \"*\" , y , \"gives you\" , handleMult(x, y))\n elif (ch == 5):\n print(\"Quitting...\")\n else:\n print(\"invalid input\")\n\ndef main():\n print(\"this is the main function\")\n\n choice=1\n while(choice != 5):\n print(\"\\n Please select an option \")\n displayChoices()\n inp = input(\"your choice >> \")\n choice = int(inp)\n if(choice==5):\n break\n inp=input(\"enter the first number >> \")\n num1=int(inp) #because input is a string and i need to convert to a number\n inp = input(\"enter the second number >> \")\n num2 = int(inp) # because input is a string and i need to convert to a number\n handleChoice(choice,num1,num2)\n\n print(\"Thank you for using simple calculator!\")\n\nif __name__=='__main__':\n main()","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"249040890","text":"# -*- coding: utf-8 -*-\n\"\"\"\n This spider is a Job_178 spider created on top of the ATSSpider\n scrapy crawl job_178 -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.job178.com.tw/jobs/find_jobs?\"\n\n sample job url:\n http://www.job178.com.tw/job_8446\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, RemoveBadElements\n\nRef_Num = compile(r\"job_(\\d+)\")\n\n\nclass Job_178(ATSSpider):\n\n name = \"job_178\"\n\n def parse(self, response):\n selector = Selector(response)\n if not self.expected_job_count_set:\n self.expected_job_count = selector.xpath('//div[@class=\"result\"]/span/strong/text()').extract()\n\n jobs = selector.xpath('//div[@class=\"joblist\"]//tr')\n for job in jobs[1:]:\n url = job.xpath('./td//a[@class=\"wd-hide job\"]/@href').extract()\n if url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': job.xpath('./td//a/text()').extract(),\n 'company': job.xpath('./td//a[contains(@href, \"company_\")]/text()').extract(),\n 'experience': job.xpath('./td[@class=\"sp\"]/text()').extract(),\n 'location': job.xpath('./td[5]/text()').extract(),\n },\n url=urljoin(response.url, url[0])\n )\n\n next_page_url = selector.xpath('//a[contains(text(), \"%s\")]/@href' % unicode('下一頁', 'utf-8')).extract()\n if next_page_url:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, next_page_url[0])\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_xpath(\n 'description',\n [\n '//div[@class=\"Cr2\"]',\n '//div[@class=\"Cr3\"]',\n ],\n RemoveBadElements(['img', 'a'])\n )\n\n loader.add_value('apply_url', response.url)\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('experiencerequirements', response.meta.get('experience'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('referencenumber', response.url, Prefix('%s-' % self.name), re=Ref_Num)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/job_178.py","file_name":"job_178.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77417846","text":"class Solution:\n \"\"\"\n 62. 不同路径\n https://leetcode-cn.com/problems/unique-paths/\n 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。\n 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。\n 问总共有多少条不同的路径?\n \"\"\"\n def uniquePaths(self, m: int, n: int) -> int:\n cur = [1] * n\n for i in range(1, m):\n for j in range(1, n):\n cur[j] += cur[j - 1]\n print('curr', i + 1, j + 1, cur[j-1], cur[j])\n return cur[-1]\n\n def uniquePathsByArr(self, m: int, n: int) -> int:\n # 生成缓存数组\n dp = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)]\n print(dp)\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n return dp[-1][-1]\n\n def uniquePathsByDy(self, m: int, n: int) -> int:\n if m == 1:\n return 1\n\n if n == 1:\n return 1\n\n return self.uniquePaths(m - 1, n) + self.uniquePaths(m, n - 1)\n\n\nso = Solution()\nprint(so.uniquePaths(7, 3))\n","sub_path":"dp.unique-paths.py","file_name":"dp.unique-paths.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"95923173","text":"import random\r\ndef dice():\r\n # range of the values of a dice\r\n min_val = 1\r\n max_val = 6\r\n\r\n # to loop the rolling through user input\r\n roll_again = \"yes\"\r\n\r\n # loop\r\n while roll_again == \"yes\" or roll_again == \"y\":\r\n #print(\"Rolling The Dices...\")\r\n #print(\"The Values are :\")\r\n\r\n # generating and printing 1st random integer from 1 to 6\r\n #print(random.randint(min_val, max_val))\r\n\r\n # generating and printing 2nd random integer from 1 to 6\r\n #print(random.randint(min_val, max_val))\r\n roll_again = \"no\"\r\n out = str(random.randint(min_val, max_val))\r\n return out","sub_path":"diceroll.py","file_name":"diceroll.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73537939","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom flask import render_template,redirect,url_for,abort,flash,request,current_app,make_response\nfrom flask.ext.login import login_required,current_user\nfrom . import main\nfrom .forms import EditProfileForm,EditProfileAdminForm,PostForm,CommentForm\nfrom .. import db\nfrom ..models import Permission,User,Role,Post,Comment\n\n#@main.route('/',methods=['GET','POST'])\n#def index():\n# form = NameForm()\n# if form.validate_on_submit():\n# #...\n# return redirect(url_for('.index'))\n# return render_template('index.html',\n# form=form,name=session.get('name'),\n# known=session.get('known',False),\n# current_time=datetime.utcnow())\n#\n'''查看用户信息''' \n@main.route('/user/')\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n if user is None:\n abort(404)\n posts = user.posts.order_by(Post.timestamp.desc()).all()\n return render_template('user.html',user=user,posts=posts)\n\n'''编辑个人资料'''\n@main.route('/edit_profile',methods=['GET','POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm()\n if form.validate_on_submit():\n current_user.name = form.name.data\n current_user.location = form.location.data\n current_user.about_me = form.about_me.data\n db.session.add(current_user)\n flash('your profile has been update')\n return redirect(url_for('.user',username=current_user.username))\n form.name.data = current_user.name\n form.location.data = current_user.location\n form.about_me.data = current_user.about_me\n return render_template('edit_profile.html',form=form)\n\n'''管理员的资料编辑'''\n@main.route('/edit_profile/',methods=['GET','POST'])\n@login_required\ndef edit_profile_admin(id):\n user = User.query.get_or_404(id) #如果提供的id不对则返回404错误,flask-sqlalchemy提供的函数\n form = EditProfileAdminForm(user=user)\n if form.validate_on_submit():\n user.email = form.email.data\n user.username = form.username.data\n user.confirmed = form.confirmed.data\n user.role = Role.query.get(form.role.data)\n user.name = form.name.data\n user.location = form.location.data\n user.about_me = form.about_me.data\n db.session.add(user)\n flash('the profile has been updated.')\n return redirect(url_for('.user',username=user.username))\n form.email.data = user.email\n form.username.data = user.username\n form.confirmed.data = user.confirmed\n form.role.data = user.role_id\n form.name.data = user.name\n form.location.data = user.location\n form.about_me.data = user.about_me\n return render_template('edit_profile_admin.html',form=form)\n\n'''博客文章'''\n@main.route('/',methods=['GET','POST'])\ndef index():\n form = PostForm()\n if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():\n post = Post(body=form.body.data,author=current_user._get_current_object())\n #变量current_user由flask-login提供,和所有上下文变量一样,也是通过线程内的代理对象实现\n #这个对象的表现类似用户对象,但实际上是一个轻度包装,包含真正的用户对象,数据库需要真正的用户对象\n #因此需要_get_current_object()\n db.session.add(post)\n return redirect(url_for('.index'))\n page = request.args.get('page',1,type=int)\n #...\n show_followed = False\n if current_user.is_authenticated:\n show_followed = bool(request.cookies.get('show_followed',''))\n if show_followed:\n query = current_user.followed_posts\n else:\n query = Post.query\n pagination = query.order_by(Post.timestamp.desc()).paginate(page,\\\n per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)\n #posts = Post.query.order_by(Post.timestamp.desc()).all() #按时间逆序\n posts = pagination.items\n return render_template('index.html',form=form,posts=posts,show_followed=show_followed,pagination=pagination)\n\n'''文章的固定链接,添加评论'''\n@main.route('/post/',methods=['GET','POST'])\ndef post(id):\n post = Post.query.get_or_404(id)\n form = CommentForm()\n if form.validate_on_submit():\n comment = Comment(body=form.body.data,post=post,author=current_user._get_current_object())\n db.session.add(comment)\n flash('your comment has been published.')\n return redirect(url_for('.post',id=post.id,page=-1))\n page = request.args.get('page',1,type=int)\n if page == -1:\n page = (post.comments.count()-1)/current_app.config['FLASKY_POSTS_PER_PAGE']+1\n pagination = post.comments.order_by(Comment.timestamp.asc()).paginate(page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n return render_template('post.html',posts=[post],form=form,pagination=pagination,comments=comments)\n\n'''编辑博客文章'''\n@main.route('/edit/',methods=['GET','POST'])\n@login_required\ndef edit(id):\n post = Post.query.get_or_404(id)\n if current_user != post.author and not current_user.can(Permission.ADMINISTER):\n abort(403)\n form = PostForm()\n if form.validate_on_submit():\n post.body = form.body.data\n db.session.add(post)\n flash('The post has been updated')\n return redirect(url_for('.post',id=post.id))\n form.body.data = post.body\n return render_template('edit_post.html',form=form)\n\n'''关注用户'''\n@main.route('/follow/')\n@login_required\ndef follow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('Invalid user.')\n return redirect(url_for('.index'))\n if current_user.is_following(user):\n flash('you are already followed this user')\n return redirect(url_for('.user',username=username))\n current_user.follow(user)\n flash('you are now following %s'%username)\n return redirect(url_for('.user',username=username))\n\n'''取关用户'''\n@main.route('/unfollow/')\n@login_required\ndef unfollow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('Invalid user')\n return redirect(url_for('.index'))\n if not current_user.is_following(user):\n flash('you are already unfollowed this user')\n return redirect(url_for('.user',username=username))\n current_user.unfollow(user)\n flash('you are now unfollowing %s'% username)\n return redirect(url_for('.user',username=username))\n\n'''查看某人的粉丝'''\n@main.route('/followers/')\ndef followers(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('Invalid user')\n return redirect(url_for('.index'))\n page = request.args.get('page',1,type=int)\n pagination = user.followers.paginate(page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)\n follows = [{'user':item.follower,'timestamp':item.timestamp} for item in pagination.items]\n return render_template('followers.html',user=user,title=\"Followers of\",endpoint='.followers',pagination=pagination,follows=follows)\n\n'''查看某人关注的用户'''\n@main.route('/followed_by/')\ndef followed_by(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('Invalid user')\n return redirect(url_for('.index'))\n page = request.args.get('page',1,type=int)\n pagination = user.followed.paginate(page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False)\n follows = [{'user':item.followed,'timestamp':item.timestamp} for item in pagination.items]\n return render_template('followers.html',user=user,title=\"Followed by\",endpoint='.followers',pagination=pagination,follows=follows)\n\n'''显示所有文章'''\n@main.route('/all')\n@login_required\ndef show_all():\n resp = make_response(redirect(url_for('.index')))\n resp.set_cookie('show_followed','',max_age=30*24*60*60)\n return resp\n\n'''显示关注者的文章'''\n@main.route('/show_followed')\n@login_required\ndef show_followed():\n resp = make_response(redirect(url_for('.index')))\n resp.set_cookie('show_followed','1',max_age=30*24*60*60)\n return resp\n\n'''管理评论'''\n@main.route('/moderate')\n@login_required\ndef moderate():\n page = request.args.get('page',1,type=int)\n pagination = Comment.query.order_by(Comment.timestamp.asc()).paginate(page,per_page=current_app.config['FLASKY_POSTS_PER_PAGE'],\n error_out=False)\n comments = pagination.items\n return render_template('moderate.html',comments=comments,pagination=pagination,page=page)\n\n'''开启禁用评论'''\n@main.route('/moderate/enable/')\n@login_required\ndef moderate_enable(id):\n comment = Comment.query.get_or_404(id)\n comment.disabled = False\n db.session.add(comment)\n return redirect(url_for('.moderate',page=request.args.get('page',1,type=int)))\n\n'''禁用评论'''\n@main.route('/moderate/disable/')\n@login_required\ndef moderate_disable(id):\n comment = Comment.query.get_or_404(id)\n comment.disabled = True\n db.session.add(comment)\n return redirect(url_for('.moderate',page=request.args.get('page',1,type=int)))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"420546175","text":"import requests\nfrom mock import patch\nfrom nose.tools import eq_, ok_\nfrom requests.exceptions import RequestException\n\nfrom flicks.base.tests import TestCase\nfrom flicks.videos import vidly\nfrom flicks.videos.vidly import Success\n\n\nRESPONSE_XML = \"\"\"\n\n %(message)s\n %(code)s\n 0001\n \n \n %(source)s\n %(shortlink)s\n \n \n\n\"\"\"\n\n\nclass FakePostResponse(object):\n \"\"\"Fakes a requests response object.\"\"\"\n def __init__(self, status_code, xml):\n self.status_code = status_code\n self.content = xml\n\n\nclass RequestTests(TestCase):\n def _request(self, xml_params={}, status_code=200, side_effect=None,\n **kwargs):\n \"\"\"Make a request to vid.ly.\"\"\"\n action = 'AddMedia'\n params = {'Source': {'SourceFile': 'http://test.com/source.mov',\n 'Output': 'webm'}}\n\n response_params = {'message': 'Test message', 'code': '2.1',\n 'source': 'http://test.com', 'shortlink': 'asdf'}\n response_params.update(xml_params)\n response_xml = RESPONSE_XML % response_params\n\n with patch.object(requests, 'post') as post:\n post.return_value = FakePostResponse(status_code, response_xml)\n post.side_effect = side_effect\n result = vidly.request(action, params, 'http://test.com', **kwargs)\n\n return result\n\n def test_no_user_info(self):\n \"\"\"If a user id or password isn't provided, return None.\"\"\"\n eq_(self._request(user_id=None, user_key=None), None)\n\n def test_connection_error(self):\n \"\"\"If there is an error connecting to vid.ly, return None.\"\"\"\n eq_(self._request(side_effect=RequestException), None)\n\n def test_non_200_response(self):\n \"\"\"Any non-200 response from vid.ly returns None.\"\"\"\n eq_(self._request(status_code=500), None)\n\n def test_basic_success(self):\n \"\"\"Test normal conditions = success.\"\"\"\n result = self._request()\n ok_(result['success'] is not None)\n eq_(result['errors'], [])\n\n\n@patch('flicks.videos.vidly.ERROR_CODES', ['1'])\nclass AddMediaTests(TestCase):\n def _addMedia(self, source_file='file/path.mov',\n notify_url='http://test.com'):\n \"\"\"Call addMedia.\"\"\"\n return vidly.addMedia(source_file, notify_url)\n\n @patch('flicks.videos.vidly.request')\n def test_connection_error(self, request):\n \"\"\"An error connecting to vidly returns None.\"\"\"\n request.return_value = None\n eq_(self._addMedia(), None)\n\n @patch('flicks.videos.vidly.ERROR_CODES', ['1'])\n @patch('flicks.videos.vidly.request')\n def test_vidly_error_code(self, request):\n \"\"\"An erroneous status code returns None.\"\"\"\n request.return_value = {'code': '1', 'errors': []}\n eq_(self._addMedia(), None)\n\n @patch('flicks.videos.vidly.ERROR_CODES', ['1'])\n @patch.object(vidly, 'request')\n def test_success_shortlink(self, request):\n \"\"\"A successful response returns the shortlink.\"\"\"\n request.return_value = {\n 'code': '2.1',\n 'msg': 'message',\n 'success': Success('asdf', 'asdf'),\n 'errors': []\n }\n\n eq_(self._addMedia(), 'asdf')\n","sub_path":"flicks/videos/tests/test_vidly.py","file_name":"test_vidly.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"434498057","text":"import pathlib\nimport json\n\nfrom django.shortcuts import render\n\nimport cobl\nfrom cobl.lexicon.defaultModels import getDefaultDict\nfrom cobl.settings import DEBUG\n\n\ndef render_template(request, template_path, extra_context={}):\n \"\"\"Wrapper around render_to_response that fills in context_instance\"\"\"\n c = {}\n c.update(getDefaultDict(request))\n c.update(extra_context)\n c['minifiedJs'] = minifiedJs\n return render(request, template_path, c)\n\n\n# When we're not in DEBUG mode, we search for the minified.js file:\ndef get_minifiedJs():\n if DEBUG:\n return None\n sdir = pathlib.Path(cobl.__file__).parent / 'static'\n with sdir.joinpath('assets.json').open() as fp:\n assets = json.load(fp)\n minjs = sdir / 'minified.js'\n if minjs.exists():\n return minjs.name\n raise ValueError('{0} not found'.format(minjs))\n\n\nminifiedJs = get_minifiedJs()\n","sub_path":"cobl/shortcuts.py","file_name":"shortcuts.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"548400804","text":"import js2py\nimport requests\nfrom bs4 import BeautifulSoup\n\n\n\ndef proxy():\n proxies = open('veyron_kolesa/parser/ip/proxies.txt').read().split('\\n')\n while True:\n for proxy in proxies:\n yield proxy\n\n\ndef useragent():\n useragents = open('veyron_kolesa/parser/ip/useragents.txt').read().split('\\n')\n while True:\n for useragent in useragents:\n yield useragent\n\n\ndef change_proxy(url, gen_proxy, gen_useragent, params={}):\n check = True\n\n while True:\n if not check:\n break\n\n _proxy = {'http': 'http://' + next(gen_proxy)}\n _useragent = {\"X-Requested-With\": \"XMLHttpRequest\", 'User-Agent': next(gen_useragent)}\n\n try:\n r = requests.get(url, params=params, headers=_useragent, proxies=_proxy, timeout=3)\n check = False\n except:\n continue\n\n return r\n\ndef get_variable(url, var):\n _proxy = {'http': 'http://' + \"134.209.36.113:3128\"}\n _useragent = {'User-Agent': \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; yie8)\"}\n response = requests.get(url, headers=_useragent, proxies=_proxy)\n soup = BeautifulSoup(response.content, \"html.parser\")\n data = soup.find_all(\"script\")\n script = 'return mydata;'\n for i in data:\n if var in i.text:\n x = i.text.split(\"};\")\n if \"var\" not in x[0]:\n x[0] = x[0].replace(var, \"var mydata\")\n else:\n x[0] = x[0].replace(var, \"mydata\")\n if \"BACKEND.\" in x[0]:\n x[0] = x[0].replace(\"BACKEND.\", \"\")\n s = \"function f() { \" + x[0] + \"};\" + script + \" } \"\n f = js2py.eval_js(s)\n obj = eval(str(f()).replace(\"\\'\", \"\\\"\"))\n return obj\n","sub_path":"veyron_kolesa/parser/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"294562401","text":"import os\nimport sys\nimport inspect\nimport colorsys\nimport onnx\nimport numpy as np\nimport tensorflow as tf\nimport keras\nfrom PIL import Image, ImageFont, ImageDraw\nfrom keras import backend as K\nfrom keras.layers import Input\nfrom keras.models import load_model\nfrom keras2onnx import convert_keras\nfrom keras2onnx import set_converter\nfrom keras2onnx.common.onnx_ops import apply_transpose, apply_identity, apply_cast\nfrom keras2onnx.proto import onnx_proto\n\nfrom os.path import dirname, abspath\nyolo3_dir = os.path.join(os.path.dirname(__file__), '../../keras-yolo3')\nif os.path.exists(yolo3_dir):\n sys.path.insert(0, yolo3_dir)\n\nimport yolo3\nfrom yolo3.model import yolo_body, tiny_yolo_body, yolo_boxes_and_scores\nfrom yolo3.utils import letterbox_image\n\n\nclass YOLOEvaluationLayer(keras.layers.Layer):\n\n def __init__(self, **kwargs):\n super(YOLOEvaluationLayer, self).__init__()\n self.anchors = np.array(kwargs.get('anchors'))\n self.num_classes = kwargs.get('num_classes')\n\n def get_config(self):\n config = {\n \"anchors\": self.anchors,\n \"num_classes\": self.num_classes,\n }\n\n return config\n\n def call(self, inputs, **kwargs):\n \"\"\"Evaluate YOLO model on given input and return filtered boxes.\"\"\"\n yolo_outputs = inputs[0:-1]\n input_image_shape = K.squeeze(inputs[-1], axis=0)\n num_layers = len(yolo_outputs)\n anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]] if num_layers == 3 else [[3, 4, 5],\n [1, 2, 3]] # default setting\n input_shape = K.shape(yolo_outputs[0])[1:3] * 32\n boxes = []\n box_scores = []\n for l in range(num_layers):\n _boxes, _box_scores = yolo_boxes_and_scores(yolo_outputs[l], self.anchors[anchor_mask[l]], self.num_classes,\n input_shape, input_image_shape)\n boxes.append(_boxes)\n box_scores.append(_box_scores)\n boxes = K.concatenate(boxes, axis=0)\n box_scores = K.concatenate(box_scores, axis=0)\n return [boxes, box_scores]\n\n def compute_output_shape(self, input_shape):\n assert isinstance(input_shape, list)\n return [(None, 4), (None, None)]\n\n\nclass YOLONMSLayer(keras.layers.Layer):\n def __init__(self, **kwargs):\n super(YOLONMSLayer, self).__init__()\n self.max_boxes = kwargs.get('max_boxes', 20)\n self.score_threshold = kwargs.get('score_threshold', .6)\n self.iou_threshold = kwargs.get('iou_threshold', .5)\n self.num_classes = kwargs.get('num_classes')\n\n def get_config(self):\n config = {\n \"max_boxes\": self.max_boxes,\n \"score_threshold\": self.score_threshold,\n \"iou_threshold\": self.iou_threshold,\n \"num_classes\": self.num_classes,\n }\n\n return config\n\n def call(self, inputs, **kwargs):\n boxes = inputs[0]\n box_scores = inputs[1]\n box_scores_transpose = tf.transpose(box_scores, perm=[1, 0])\n boxes_number = tf.shape(boxes)[0]\n box_range = tf.range(boxes_number)\n\n mask = box_scores >= self.score_threshold\n max_boxes_tensor = K.constant(self.max_boxes, dtype='int32')\n classes_ = []\n batch_indexs_ = []\n nms_indexes_ = []\n class_box_range_ = []\n for c in range(self.num_classes):\n class_boxes = tf.boolean_mask(boxes, mask[:, c])\n class_box_scores = tf.boolean_mask(box_scores[:, c], mask[:, c])\n class_box_range = tf.boolean_mask(box_range, mask[:, c])\n nms_index = tf.image.non_max_suppression(\n class_boxes, class_box_scores, max_boxes_tensor, iou_threshold=self.iou_threshold)\n class_box_scores = K.gather(class_box_scores, nms_index)\n class_box_range = K.gather(class_box_range, nms_index)\n classes = K.ones_like(class_box_scores, 'int32') * c\n batch_index = K.zeros_like(class_box_scores, 'int32')\n batch_indexs_.append(batch_index)\n classes_.append(classes)\n nms_indexes_.append(nms_index)\n class_box_range_.append(class_box_range)\n\n classes_ = K.concatenate(classes_, axis=0)\n batch_indexs_ = K.concatenate(batch_indexs_, axis=0)\n class_box_range_ = K.concatenate(class_box_range_, axis=0)\n\n boxes_1 = tf.expand_dims(boxes, 0)\n classes_1 = tf.expand_dims(classes_, 1)\n batch_indexs_ = tf.expand_dims(batch_indexs_, 1)\n class_box_range_ = tf.expand_dims(class_box_range_, 1)\n box_scores_transpose_1 = tf.expand_dims(box_scores_transpose, 0)\n nms_final_ = K.concatenate([batch_indexs_, classes_1, class_box_range_], axis=1)\n nms_final_1 = tf.expand_dims(nms_final_, 0)\n return [boxes_1, box_scores_transpose_1, nms_final_1]\n\n def compute_output_shape(self, input_shape):\n assert isinstance(input_shape, list)\n return [(None, None, 4), (None, self.num_classes, None), (None, None, 3)]\n\n\nclass YOLO(object):\n def __init__(self, model_path='model_data/yolo.h5', anchors_path='model_data/yolo_anchors.txt', yolo3_dir=None):\n self.yolo3_dir = yolo3_dir\n self.model_path = model_path\n self.anchors_path = anchors_path\n self.classes_path = 'model_data/coco_classes.txt'\n self.score = 0.3\n self.iou = 0.45\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.model_image_size = (416, 416) # fixed size or (None, None), hw\n self.session = None\n self.final_model = None\n\n # Generate colors for drawing bounding boxes.\n hsv_tuples = [(x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))]\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n np.random.seed(10101) # Fixed seed for consistent colors across runs.\n np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes.\n np.random.seed(None) # Reset seed to default.\n K.set_learning_phase(0)\n\n @staticmethod\n def _get_data_path(name, yolo3_dir):\n path = os.path.expanduser(name)\n if not os.path.isabs(path):\n if yolo3_dir is None:\n yolo3_dir = os.path.dirname(inspect.getabsfile(yolo3))\n path = os.path.join(yolo3_dir, os.path.pardir, path)\n return path\n\n def _get_class(self):\n classes_path = self._get_data_path(self.classes_path, self.yolo3_dir)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n def _get_anchors(self):\n anchors_path = self._get_data_path(self.anchors_path, self.yolo3_dir)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n\n def load_model(self, yolo_weights=None):\n model_path = self._get_data_path(self.model_path, self.yolo3_dir)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n if yolo_weights is None:\n # Load model, or construct model and load weights.\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n is_tiny_version = num_anchors == 6 # default setting\n\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = tiny_yolo_body(Input(shape=(None, None, 3)), num_anchors // 2, num_classes) \\\n if is_tiny_version else yolo_body(Input(shape=(None, None, 3)), num_anchors // 3, num_classes)\n self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors / len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n else:\n self.yolo_model = yolo_weights\n\n input_image_shape = keras.Input(shape=(2,), name='image_shape')\n image_input = keras.Input((None, None, 3), dtype='float32', name='input_1')\n y = list(self.yolo_model(image_input))\n y.append(input_image_shape)\n\n boxes, box_scores = \\\n YOLOEvaluationLayer(anchors=self.anchors, num_classes=len(self.class_names))(inputs=y)\n\n out_boxes, out_scores, out_indices = \\\n YOLONMSLayer(anchors=self.anchors, num_classes=len(self.class_names))(\n inputs=[boxes, box_scores])\n self.final_model = keras.Model(inputs=[image_input, input_image_shape],\n outputs=[out_boxes, out_scores, out_indices])\n\n self.final_model.save('final_model.h5')\n print('{} model, anchors, and classes loaded.'.format(model_path))\n\n def prepare_keras_data(self, image):\n if self.model_image_size != (None, None):\n assert self.model_image_size[0] % 32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1] % 32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n image_data = np.array(boxed_image, dtype='float32')\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0) # Add batch dimension.\n return image_data\n\n def detect_with_onnx(self, image):\n self.load_model()\n image_data = self.prepare_keras_data(image)\n all_boxes_k, all_scores_k, indices_k = self.final_model.predict([image_data, np.array([image.size[1], image.size[0]], dtype='float32').reshape(1, 2)])\n\n image_data_onnx = np.transpose(image_data, [0, 3, 1, 2])\n feed_f = dict(zip(['input_1', 'image_shape'],\n (image_data_onnx, np.array([image.size[1], image.size[0]], dtype='float32').reshape(1, 2))))\n all_boxes, all_scores, indices = self.session.run(None, input_feed=feed_f)\n\n out_boxes, out_scores, out_classes = [], [], []\n for idx_ in indices[0]:\n out_classes.append(idx_[1])\n out_scores.append(all_scores[tuple(idx_)])\n idx_1 = (idx_[0], idx_[2])\n out_boxes.append(all_boxes[idx_1])\n\n font = ImageFont.truetype(font=self._get_data_path('font/FiraMono-Medium.otf', self.yolo3_dir),\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = (image.size[0] + image.size[1]) // 300\n\n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n\n label = '{} {:.2f}'.format(predicted_class, score)\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n\n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n\n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n\n for i in range(thickness):\n draw.rectangle(\n [left + i, top + i, right - i, bottom - i],\n outline=self.colors[c])\n draw.rectangle(\n [tuple(text_origin), tuple(text_origin + label_size)],\n fill=self.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n del draw\n\n return image\n\n\ndef detect_img(yolo, img_url, model_file_name):\n import onnxruntime\n image = Image.open(img_url)\n yolo.session = onnxruntime.InferenceSession(model_file_name)\n\n r_image = yolo.detect_with_onnx(image)\n n_ext = img_url.rindex('.')\n score_file = img_url[0:n_ext] + '_score' + img_url[n_ext:]\n r_image.save(score_file, \"JPEG\")\n\n\ndef convert_NMSLayer(scope, operator, container):\n # type: (keras2onnx.common.InterimContext, keras2onnx.common.Operator, keras2onnx.common.OnnxObjectContainer) -> None\n box_transpose = scope.get_unique_variable_name(operator.inputs[0].full_name + '_tx')\n score_transpose = scope.get_unique_variable_name(operator.inputs[1].full_name + '_tx')\n\n apply_identity(scope, operator.inputs[0].full_name, box_transpose, container)\n apply_transpose(scope, operator.inputs[1].full_name, score_transpose, container, perm=[1, 0])\n\n box_batch = scope.get_unique_variable_name(operator.inputs[0].full_name + '_btc')\n score_batch = scope.get_unique_variable_name(operator.inputs[1].full_name + '_btc')\n\n container.add_node(\"Unsqueeze\", box_transpose,\n box_batch, op_version=operator.target_opset, axes=[0])\n container.add_node(\"Unsqueeze\", score_transpose,\n score_batch, op_version=operator.target_opset, axes=[0])\n\n layer = operator.raw_operator # type: YOLONMSLayer\n\n max_output_size = scope.get_unique_variable_name('max_output_size')\n iou_threshold = scope.get_unique_variable_name('iou_threshold')\n score_threshold = scope.get_unique_variable_name('layer.score_threshold')\n\n container.add_initializer(max_output_size, onnx_proto.TensorProto.INT64,\n [], [layer.max_boxes])\n container.add_initializer(iou_threshold, onnx_proto.TensorProto.FLOAT,\n [], [layer.iou_threshold])\n container.add_initializer(score_threshold, onnx_proto.TensorProto.FLOAT,\n [], [layer.score_threshold])\n\n cast_name = scope.get_unique_variable_name('casted')\n nms_node = next((nd_ for nd_ in operator.nodelist if nd_.type == 'NonMaxSuppressionV3'), operator.nodelist[0])\n container.add_node(\"NonMaxSuppression\",\n [box_batch, score_batch, max_output_size, iou_threshold, score_threshold],\n cast_name,\n op_version=operator.target_opset,\n name=nms_node.name)\n\n cast_batch = scope.get_unique_variable_name(operator.output_full_names[2] + '_btc')\n container.add_node(\"Unsqueeze\", cast_name,\n cast_batch, op_version=operator.target_opset, axes=[0])\n apply_cast(scope, cast_batch, operator.output_full_names[2], container, to=onnx_proto.TensorProto.INT32)\n\n apply_identity(scope, box_batch, operator.output_full_names[0], container)\n apply_identity(scope, score_batch, operator.output_full_names[1], container)\n\n\nset_converter(YOLONMSLayer, convert_NMSLayer)\n\n\ndef convert_model(yolo, model_file_name, target_opset):\n yolo.load_model()\n onnxmodel = convert_keras(yolo.final_model, target_opset=target_opset, channel_first_inputs=['input_1'])\n onnx.save_model(onnxmodel, model_file_name)\n return onnxmodel\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print(\"Need an image file for object detection.\")\n exit(-1)\n\n target_opset = 10\n\n model_file_name = 'model_data/yolov3.onnx'\n model_path = 'model_data/yolo.h5' # model path or trained weights path\n anchors_path = 'model_data/yolo_anchors.txt'\n '''\n # For tiny yolov3 case, use:\n model_file_name = 'model_data/yolov3-tiny.onnx'\n model_path = 'model_data/yolo-tiny.h5'\n anchors_path = 'model_data/tiny_yolo_anchors.txt'\n '''\n\n if not os.path.exists(model_file_name):\n onnxmodel = convert_model(YOLO(model_path, anchors_path), model_file_name, target_opset)\n\n detect_img(YOLO(), sys.argv[1], model_file_name)\n","sub_path":"applications/yolov3/yolov3.py","file_name":"yolov3.py","file_ext":"py","file_size_in_byte":16384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"49774295","text":"\"\"\"\r\nStudent Name: CK Porter \r\nProgram Title: The Itsy Bitsy Aardvark\r\nDescription: A program that presents the user with a \"mad libs\" style of game, give them a random\r\nchoice of words read from a file, then injected into the story from another file\r\n\"\"\"\r\n\"\"\"\r\nstart program\r\nopen connection to choices in csv file\r\ncreate list for choices\r\nopen connection to story text\r\ncreate list for story text\r\ndisplay choices pulling info form choices list\r\nget user input\r\n -loop to ensure correct input is given (call function)\r\nif structure to determine which value on the list user selected\r\nrun loop over newstory list to replace placeholders with user input\r\nprint each line in new story list\r\nend program\r\n\"\"\"\r\n\r\n#tried to figure out how to loop through the cvs file to display output one at a time, couldn't\r\n#figure it out, so there is a large ugly section of code which I am certain will hurt your head\r\n#my apologizes in advance\r\n\r\n\r\nimport csv\r\n\r\n#function to check to make sure user entered valid input\r\ndef checkChoice ():\r\n while True:\r\n userChoice=input(\"Enter choice (a-e): \")\r\n if userChoice == \"a\":\r\n break\r\n if userChoice == \"b\":\r\n break\r\n if userChoice == \"c\":\r\n break\r\n if userChoice == \"d\":\r\n break\r\n if userChoice == \"e\":\r\n break\r\n return userChoice\r\n\r\ndef main(): \r\n\r\n \r\n fileName =\"Files\\\\the_story_file.txt\"\r\n accessMode= \"r\"\r\n \r\n\r\n story = open(fileName,accessMode)\r\n storyList=list(story) \r\n \r\n with open(\"Files\\\\the_choices_file.csv\",\"r\") as theChoices:\r\n\r\n #new story list, runs len of story to replace all words\r\n newStory= []\r\n\r\n print(\"The Itsy Bitsy Aardvark\")\r\n\r\n choices= csv.reader(theChoices)\r\n lines= list(choices) #this takes the return of the csv file and puts it into a list\r\n \r\n #choices from the choices csv file\r\n choice1 = print(\"\\nPlease choose \" + lines[0][0] + \r\n \"\\n a)\" +lines[0][1] +\r\n \"\\n b)\" +lines[0][2] +\r\n \"\\n c)\" + lines[0][3] +\r\n \"\\n d)\" + lines[0][4] +\r\n \"\\n e)\" + lines[0][5] + \": \")\r\n userChoice1=checkChoice() #this calls the while loop to check user input/collect/return input\r\n\r\n choice2 = print(\"\\nPlease choose \" + lines[1][0] + \r\n \"\\n a)\" +lines[1][1] +\r\n \"\\n b)\" +lines[1][2] +\r\n \"\\n c)\" + lines[1][3] +\r\n \"\\n d)\" + lines[1][4] +\r\n \"\\n e)\" + lines[1][5] + \": \")\r\n userChoice2=checkChoice()\r\n\r\n choice3 = print(\"\\nPlease choose \" + lines[2][0] + \r\n \"\\n a)\" +lines[2][1] +\r\n \"\\n b)\" +lines[2][2] +\r\n \"\\n c)\" + lines[2][3] +\r\n \"\\n d)\" + lines[2][4] +\r\n \"\\n e)\" + lines[2][5] + \": \")\r\n userChoice3=checkChoice()\r\n\r\n choice4 = print(\"\\nPlease choose \" + lines[3][0] + \r\n \"\\n a)\" +lines[3][1] +\r\n \"\\n b)\" +lines[3][2] +\r\n \"\\n c)\" + lines[3][3] +\r\n \"\\n d)\" + lines[3][4] +\r\n \"\\n e)\" + lines[3][5] + \": \")\r\n userChoice4=checkChoice()\r\n\r\n choice5 = print(\"\\nPlease choose \" + lines[4][0] + \r\n \"\\n a)\" +lines[4][1] +\r\n \"\\n b)\" +lines[4][2] +\r\n \"\\n c)\" + lines[4][3] +\r\n \"\\n d)\" + lines[4][4] +\r\n \"\\n e)\" + lines[4][5] + \": \")\r\n userChoice5=checkChoice()\r\n\r\n choice6 = print(\"\\nPlease choose \" + lines[5][0] + \r\n \"\\n a)\" +lines[5][1] +\r\n \"\\n b)\" +lines[5][2] +\r\n \"\\n c)\" + lines[5][3] +\r\n \"\\n d)\" + lines[5][4] +\r\n \"\\n e)\" + lines[5][5] + \": \")\r\n userChoice6=checkChoice()\r\n\r\n choice7 = print(\"\\nPlease choose \" + lines[6][0] + \r\n \"\\n a)\" +lines[6][1] +\r\n \"\\n b)\" +lines[6][2] +\r\n \"\\n c)\" + lines[6][3] +\r\n \"\\n d)\" + lines[6][4] +\r\n \"\\n e)\" + lines[6][5] + \": \")\r\n userChoice7=checkChoice()\r\n \r\n print(\"\\nYour Completed Story: \")\r\n print()\r\n\r\n #the if structure for determining user choice via choices list\r\n #this is a long chunk of code, would have liked a better way to do this\r\n if userChoice1 == \"a\":\r\n userChoice1= lines[0][1]\r\n elif userChoice1 == \"b\":\r\n userChoice1=lines[0][2]\r\n elif userChoice1 == \"c\":\r\n userChoice1=lines[0][3]\r\n elif userChoice1 == \"d\":\r\n userChoice1=lines[0][4]\r\n elif userChoice1 == \"e\":\r\n userChoice1=lines[0][5]\r\n\r\n if userChoice2 == \"a\":\r\n userChoice2 = lines[1][1]\r\n elif userChoice2 == \"b\":\r\n userChoice2=lines[1][2]\r\n elif userChoice2 == \"c\":\r\n userChoice2=lines[1][3]\r\n elif userChoice2 == \"d\":\r\n userChoice2=lines[1][4]\r\n elif userChoice2 == \"e\":\r\n userChoice2=lines[1][5]\r\n \r\n if userChoice3 == \"a\":\r\n userChoice3 = lines[2][1]\r\n elif userChoice3 == \"b\":\r\n userChoice3=lines[2][2]\r\n elif userChoice3 == \"c\":\r\n userChoice3=lines[2][3]\r\n elif userChoice3 == \"d\":\r\n userChoice3=lines[2][4]\r\n elif userChoice3 == \"e\":\r\n userChoice3=lines[2][5]\r\n\r\n if userChoice4 == \"a\":\r\n userChoice4 = lines[3][1]\r\n elif userChoice4 == \"b\":\r\n userChoice4=lines[3][2]\r\n elif userChoice4 == \"c\":\r\n userChoice4=lines[3][3]\r\n elif userChoice4 == \"d\":\r\n userChoice4=lines[3][4]\r\n elif userChoice4 == \"e\":\r\n userChoice4=lines[3][5]\r\n\r\n if userChoice5 == \"a\":\r\n userChoice5 = lines[4][1]\r\n elif userChoice5 == \"b\":\r\n userChoice5=lines[4][2]\r\n elif userChoice5 == \"c\":\r\n userChoice5=lines[4][3]\r\n elif userChoice5 == \"d\":\r\n userChoice5=lines[4][4]\r\n elif userChoice5 == \"e\":\r\n userChoice5=lines[4][5]\r\n\r\n if userChoice6 == \"a\":\r\n userChoice6 = lines[5][1]\r\n elif userChoice6 == \"b\":\r\n userChoice6=lines[5][2]\r\n elif userChoice6 == \"c\":\r\n userChoice6=lines[5][3]\r\n elif userChoice6 == \"d\":\r\n userChoice6=lines[5][4]\r\n elif userChoice6 == \"e\":\r\n userChoice6=lines[5][5]\r\n\r\n if userChoice7 == \"a\":\r\n userChoice7 = lines[6][1]\r\n elif userChoice7 == \"b\":\r\n userChoice7=lines[6][2]\r\n elif userChoice7 == \"c\":\r\n userChoice7=lines[6][3]\r\n elif userChoice7 == \"d\":\r\n userChoice7=lines[6][4]\r\n elif userChoice7 == \"e\":\r\n userChoice7=lines[6][5]\r\n\r\n #looping over the storyList , making replacements, writing to newStory list\r\n for word in storyList:\r\n newString= word.replace(\"_1_\", userChoice1.upper()).replace(\"_2_\", userChoice2.upper())\\\r\n .replace(\"_3_\", userChoice3.upper()).replace(\"_4_\", userChoice4.upper())\\\r\n .replace(\"_5_\", userChoice5.upper()).replace(\"_6_\", userChoice6.upper())\\\r\n .replace(\"_7_\", userChoice7.upper()) \r\n newStory.append(newString)\r\n \r\n #loops through the list, displays to screen\r\n for line in newStory:\r\n print(line, end=\"\") \r\n \r\n \r\n \r\n\r\n \r\n story.close()\r\n \r\nif __name__ == \"__main__\":\r\n main()","sub_path":"ItsyBitsyAardvark.py","file_name":"ItsyBitsyAardvark.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"371157022","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\n\nfrom odoo import fields, models, api\nfrom odoo.exceptions import ValidationError\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT\n\n\nclass PayNoticeWizard(models.TransientModel):\n _name = 'pay.notice.wizard'\n _description = u'缴费通知单向导'\n\n def _get_period_id(self):\n period_obj = self.env['finance.period']\n\n time_now = (datetime.now() + timedelta(hours=8))\n name = time_now.strftime('%Y%m')\n period = period_obj.search([('name', '=', name)], limit=1)\n if not period:\n period = period_obj.create({\n 'year': str(time_now.year),\n 'month': str(time_now.month),\n 'company_id': 1\n })\n return period.id\n\n period_id = fields.Many2one('finance.period', '期间', default=_get_period_id)\n partner_id = fields.Many2one('partner', '商户', domain=[('c_category_id', '!=', False)])\n\n @api.multi\n def do_search(self):\n money_order_obj = self.env['money.order']\n wizard_line_obj = self.env['pay.notice.wizard.line']\n money_line_obj = self.env['money.order.line']\n source_order_line_obj = self.env['source.order.line']\n period_obj = self.env['finance.period']\n\n self.ensure_one()\n\n args = [('type', '=', 'get'), ('company_id', '=', self.user.company_id.id), ('period_id', '=', self.period_id.id)]\n if self.partner_id:\n args += [('partner_id', '=', self.partner_id.id)]\n money_orders = money_order_obj.search(args)\n for money_order in money_orders:\n\n # 查询往期费用\n periods = period_obj.search([('name', '<', money_order.period_id.name)])\n\n source_order_lines = source_order_line_obj.search(\n [('money_id.type', '=', 'get'),\n ('money_id.period_id', 'in', periods.ids),\n ('money_id.company_id', '=', self.env.user.company_id.id),\n ('money_id.partner_id', '=', money_order.partner_id.id)])\n\n amount = sum([source_order_line.amount for source_order_line in source_order_lines])\n\n money_order_lines = money_line_obj.search([('money_id.type', '=', 'get'),\n ('money_id.period_id', 'in', periods.ids),\n ('money_id.company_id', '=', self.env.user.company_id.id),\n ('money_id.partner_id', '=', money_order.partner_id.id)])\n amount_paid = sum([money_order_line.amount for money_order_line in money_order_lines])\n\n wizard_line = wizard_line_obj.create({\n 'wizard_id': self.id,\n 'period_id': money_order.period_id.id,\n 'partner_id': money_order.partner_id.id,\n 'amount_before': amount - amount_paid,\n })\n\n # 查询本期费用详情\n\n\n view = self.env.ref('anxe_property.view_money_get_report_wizard_result')\n\n return {\n 'type': 'ir.actions.act_window',\n 'name': '月度收款报表',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'money.get.report.wizard',\n 'view_id': view.id,\n 'res_id': self.id,\n }\n\n\nclass PayNoticeWizardLine(models.TransientModel):\n _name = 'pay.notice.wizard.line'\n _description = u'缴费通知单'\n\n wizard_id = fields.Many2one('pay.notice.wizard')\n period_id = fields.Many2one('finance.period', '期间')\n partner_id = fields.Many2one('partner', '商户', domain=[('c_category_id', '!=', False)])\n amount_before = fields.Float('往期费用')\n\n\nclass PayNoticeWizardLineDetail(models.TransientModel):\n _name = 'pay.notice.wizard.line.detail'\n _description = u'缴费通知单明细'\n\n line_id = fields.Many2one('pay.notice.wizard.line')\n fee_id = fields.Many2one('core.value', string='费用类型', store=1)\n period_id = fields.Many2one('finance.period', '期间')\n date_from = fields.Date('开始日期')\n date_to = fields.Date('截止日期')\n amount = fields.Float('应付')\n amount_paid = fields.Float('已付')\n amount_not_pay = fields.Float('未付')","sub_path":"my_addons/anxe_money/wizard/money_get_report_wizard.py","file_name":"money_get_report_wizard.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"614098568","text":"#Advent of Code 2017\r\n#Day 2 Challenge, Part 2\r\n#http://adventofcode.com/2017/day/2\r\n#Author: Sam Clark\r\n\r\nimport sys\r\nimport csv\r\n\r\nprint(\"Advent of Code 2017\")\r\nprint(\"Day 2, Part 2 - http://adventofcode.com/2017/day/2\")\r\nprint(\"Sam Clark\")\r\n\r\ndef checksum ( spreadsheet ) :\r\n\tquotients = []\r\n\tchecked = []\r\n\tfor row in spreadsheet : \r\n\t\tfor i in row :\r\n\t\t\tfor j in checked :\r\n\t\t\t\tif j % i == 0 :\r\n\t\t\t\t\tquotients.append(j/i)\r\n\t\t\t\t\tbreak\r\n\t\t\t\tif i % j == 0 :\r\n\t\t\t\t\tquotients.append(i/j)\r\n\t\t\t\t\tbreak\r\n\t\t\tchecked.append(i)\r\n\t\tchecked.clear()\r\n\treturn sum(quotients)\r\n\r\n\r\nselection = '\\0'\r\n\r\nwhile (selection != 'Q' and selection != 'q') :\r\n\tfile_name = input(\"\\nEnter your spreadsheet filename (csv): \")\r\n\twith open(file_name, 'rU') as f :\r\n\t\treader = csv.reader(f)\r\n\t\tdata = list(list(rec) for rec in csv.reader(f, delimiter='\\t'))\r\n\r\n\tfor i in range(len(data)) :\r\n\t\tfor j in range(len(data[i])) :\r\n\t\t\tdata[i][j] = int(data[i][j])\r\n\r\n\tprint(\"Solution: \", checksum(data))\r\n\r\n\tselection = input(\"\\nPress q to quit. Any other key to continue.\")\r\n\t\r\nsys.exit()","sub_path":"aoc02p2.py","file_name":"aoc02p2.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"152023858","text":"# coding=utf-8\n\nimport importlib\nimport logging\nimport signal\nimport sys\nimport time\nimport traceback\n\nimport tornado.autoreload\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nfrom tornado.options import options\n\nfrom frontik.app import FrontikApplication\nfrom frontik.loggers import bootstrap_core_logging\n\nlog = logging.getLogger('frontik.server')\n\n\ndef parse_configs(config_files):\n \"\"\"Reads command line options / config file and bootstraps logging.\n \"\"\"\n\n tornado.options.parse_command_line(final=False)\n\n if options.config:\n configs_to_read = options.config\n else:\n configs_to_read = config_files\n\n configs_to_read = filter(\n None, [configs_to_read] if not isinstance(configs_to_read, (list, tuple)) else configs_to_read\n )\n\n for config in configs_to_read:\n tornado.options.parse_config_file(config, final=False)\n\n # override options from config with command line options\n tornado.options.parse_command_line(final=False)\n\n bootstrap_core_logging()\n\n for config in configs_to_read:\n log.debug('using config: %s', config)\n if options.autoreload:\n tornado.autoreload.watch(config)\n\n\ndef run_server(app):\n \"\"\"\n — run server on host:port\n — launch autoreload on file changes\n \"\"\"\n\n try:\n log.info('starting server on %s:%s', options.host, options.port)\n http_server = tornado.httpserver.HTTPServer(app, xheaders=options.xheaders)\n http_server.listen(options.port, options.host)\n\n io_loop = tornado.ioloop.IOLoop.current()\n\n if options.autoreload:\n tornado.autoreload.start(io_loop, 1000)\n\n def log_ioloop_block(signum, frame):\n io_loop.add_callback_from_signal(\n log.warning, 'IOLoop blocked for %f seconds in\\n%s',\n io_loop._blocking_signal_threshold, ''.join(traceback.format_stack(frame))\n )\n\n def sigterm_handler(signum, frame):\n log.info('requested shutdown')\n log.info('shutting down server on %s:%d', options.host, options.port)\n io_loop.add_callback_from_signal(server_stop)\n signal.signal(signal.SIGTERM, signal.SIG_IGN)\n\n def ioloop_is_running():\n return io_loop._running\n\n def server_stop():\n http_server.stop()\n\n if ioloop_is_running():\n log.info('going down in %s seconds', options.stop_timeout)\n\n def ioloop_stop():\n if ioloop_is_running():\n log.info('stopping IOLoop')\n io_loop.stop()\n log.info('stopped')\n\n io_loop.add_timeout(time.time() + options.stop_timeout, ioloop_stop)\n\n if options.log_blocked_ioloop_timeout > 0:\n io_loop.set_blocking_signal_threshold(options.log_blocked_ioloop_timeout, log_ioloop_block)\n\n signal.signal(signal.SIGTERM, sigterm_handler)\n except Exception:\n log.exception('failed to start Tornado application')\n\n\ndef main(config_file=None):\n # noinspection PyUnresolvedReferences\n import frontik.options\n\n parse_configs(config_files=config_file)\n\n if options.app is None:\n log.exception('no frontik application present (`app` option is not specified)')\n sys.exit(1)\n\n log.info('starting application %s', options.app)\n\n try:\n module = importlib.import_module(options.app)\n except Exception as e:\n log.exception('failed to import application module \"%s\": %s', options.app, e)\n sys.exit(1)\n\n if options.app_class is not None and not hasattr(module, options.app_class):\n log.exception('application class \"%s\" not found', options.app_class)\n sys.exit(1)\n\n application = getattr(module, options.app_class) if options.app_class is not None else FrontikApplication\n\n try:\n tornado_app = application(**options.as_dict())\n ioloop = tornado.ioloop.IOLoop.current()\n\n def _run_server_cb(future):\n if future.exception() is not None:\n log.error('failed to initialize application, init_async returned: %s', future.exception())\n sys.exit(1)\n\n run_server(tornado_app)\n\n def _async_init_cb():\n try:\n ioloop.add_future(tornado_app.init_async(), _run_server_cb)\n except Exception:\n log.exception('failed to initialize application')\n sys.exit(1)\n\n ioloop.add_callback(_async_init_cb)\n ioloop.start()\n except:\n log.exception('frontik application exited with exception')\n sys.exit(1)\n","sub_path":"frontik/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47357885","text":"# Create a function that takes 3 parameters: a path, a word and a number,\n# than it should write to a file.\n# The path parameter should be a string, that describes the location of the file. # nopep8\n# The word parameter should be a string, that will be written to the file as lines # nopep8\n# The number paramter should describe how many lines the file should have.\n# So if the word is \"apple\" and the number is 5, than it should write 5 lines\n# to the file and each line should be \"apple\"\n# The function should not raise any error if it could not write the file.\n\npath_global = input('Give me the file name: ')\nword_global = input('Give me the word: ')\nnumber_global = int(input('Give me the repeat number: '))\n\n\ndef write_into_a_file(path, word, number):\n try:\n file = open(path, \"w\")\n for i in range(1, number + 1):\n file.write(word + \" \\n\")\n except FileNotFoundError:\n return 0\n\n\nwrite_into_a_file(path_global, word_global, number_global)\n","sub_path":"week-03/day-01/write_multiple_lines.py","file_name":"write_multiple_lines.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77030347","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport math\nimport pprint\n\n\n# In[ ]:\n\n\nclass ValueIteration(object):\n def __init__(self, transitionTable, rewardTable, valueTable, terminalStates, convergenceTolerance, gamma, alpha = 0, eps = 0):\n self.transitionTable = transitionTable\n self.rewardTable = rewardTable\n self.valueTable = valueTable\n self.convergenceTolerance = convergenceTolerance\n self.gamma = gamma\n self.alpha = alpha\n self.eps = eps\n self.terminalStates = terminalStates\n \n def getQvalue(self, action, nextStatesAndRewards, valueTable, nextStatesAndProbabilities):\n return sum((reward + self.gamma*valueTable[nextState])*nextStatesAndProbabilities[action][nextState]\n for nextState, reward in nextStatesAndRewards.items())\n \n def getMaxValueAndAction(self, valueTable, state):\n nextStatesAndProbabilities = self.transitionTable[state]\n actionsAndRewards = self.rewardTable[state]\n maxQvalue = max(self.getQvalue(action,nextStatesAndRewards,valueTable,nextStatesAndProbabilities)\n for action, nextStatesAndRewards in actionsAndRewards.items())\n \n actionsProbability = {action:math.exp(self.alpha*self.getQvalue(action,nextStatesAndRewards,valueTable,nextStatesAndProbabilities)) \n for action, nextStatesAndRewards in actionsAndRewards.items()}\n \n total = sum(val for val in actionsProbability.values())\n actionsProbabilityNormalized = self.getPolicyDistribution(actionsProbability, lambda x: (x/total)) \n actionsProbabilityFinal = self.getPolicyDistribution(actionsProbabilityNormalized, lambda x: (x*(1-self.eps) + (self.eps/len(actionsProbability.keys()))))\n \n return (maxQvalue, actionsProbabilityFinal) \n \n def getPolicyDistribution(self, actionDict, func):\n return {action:func(actionDict[action]) for action in actionDict}\n \n def __call__(self):\n #######################################\n ########## YOUR CODE HERE #############\n #######################################\n policyTable = {}\n stateValues = self.valueTable\n while(True):\n delta = 0\n for state,value in stateValues.items():\n temp_val = value\n if all([state!=terminalState for terminalState in self.terminalStates]):\n stateValues[state], policyTable[state] = self.getMaxValueAndAction(stateValues, state) \n delta = max(delta, abs(temp_val - self.valueTable[state]))\n if(delta<=self.convergenceTolerance):\n break\n return([stateValues, policyTable])\n\n","sub_path":"Algorithms/DictValueIteration.py","file_name":"DictValueIteration.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567862079","text":"import os\n\nfrom xml.dom.minidom import parse\nimport xml.dom.minidom as XmlDocument\n\npathDict = \"DictTxt\"\n\ndef readTraceInfo(traces, PICSIZE, PADDINGPIC):\n tracesDict = {} # 【笔划 id-(pointsList)】id=\"2\" [1345.17, 1890.77] [1345.17, 1890.77] ...\n tracesBoxDict = {} # 统计每个trace的边界[(xMin,yMin),(xMax,yMax)]\n for trace in traces:\n traceid = trace.getAttribute(\"id\")\n path = trace.childNodes[0].data.replace(\"\\n\",\"\")\n points = path.split(\", \")\n\n xMin = yMin = PICSIZE\n xMax = yMax = 0\n tracesDict[traceid] = []\n for point in points:\n x = float(point.split(\" \")[0])\n y = float(point.split(\" \")[1])\n xMin = xMin if xMin < x else x\n yMin = yMin if yMin < y else y\n xMax = xMax if xMax > x else x\n yMax = yMax if yMax > y else y\n # p = (x,y)\n tracesDict[traceid].append(x+PADDINGPIC)\n tracesDict[traceid].append(y+PADDINGPIC)\n tracesBoxDict[traceid] = [(xMin,yMin),(xMax,yMax)]\n return (tracesDict, tracesBoxDict)\n\ndef readTraceGroupsInfo(traceGroups, tracesBoxDict, drawComponentSettingDict, PICSIZE):\n typesSet = set()\n traceGroupsDict = {} # 【笔划组 id-(traceidList)】 id=\"300\" traceRef=[1,2,...5] id\n traceGroupsBoxDict = {} # 统计每个traceGroup的边界\n traceGroupsTypeDict = {} # 统计每个group对应type\n for traceGroup in traceGroups:\n traceRef = []\n id = traceGroup.getAttribute(\"xml:id\")\n traceViews = traceGroup.getElementsByTagName(\"traceView\")\n groupType = traceGroup.getElementsByTagName(\"annotation\")[0].childNodes[0].data\n # 仅生成所需节点类型的JPEGImage和Annotations\n if not drawComponentSettingDict[groupType]:\n continue\n typesSet.add(groupType)\n\n xMin = yMin = PICSIZE\n xMax = yMax = 0\n # 绘制线,顺便计算min和max\n for traceView in traceViews:\n traceid = traceView.getAttribute(\"traceDataRef\")\n traceRef.append(traceid)\n\n xMin = tracesBoxDict[traceid][0][0] if tracesBoxDict[traceid][0][0] < xMin else xMin\n yMin = tracesBoxDict[traceid][0][1] if tracesBoxDict[traceid][0][1] < yMin else yMin\n xMax = tracesBoxDict[traceid][1][0] if tracesBoxDict[traceid][1][0] > xMax else xMax\n yMax = tracesBoxDict[traceid][1][1] if tracesBoxDict[traceid][1][1] > yMax else yMax\n \n traceGroupsBoxDict[id] = [(xMin,yMin),(xMax,yMax)]\n traceGroupsDict[id] = traceRef\n traceGroupsTypeDict[id] = groupType\n return (traceGroupsDict, traceGroupsBoxDict, traceGroupsTypeDict, typesSet)\n\n\ndef readInkmlInfo(pathInkml, drawComponentSettingDict, PICSIZE, PADDINGPIC):\n # if os.path.exists(os.path.join(pathDict,'typeStatisticDict.txt')) and os.path.exists(os.path.join(pathDict,'nameIndexDict.txt')) and os.path.exists(os.path.join(pathDict,'inkmlDict.txt')):\n # f = open(os.path.join(pathDict,'typeStatisticDict.txt'),'r')\n # fread = f.read()\n # typeStatisticDict = eval(fread)\n # f.close()\n # f = open(os.path.join(pathDict,'nameIndexDict.txt'),'r')\n # fread = f.read()\n # nameIndexDict = eval(fread)\n # f.close()\n # f = open(os.path.join(pathDict,'inkmlDict.txt'),'r')\n # fread = f.read()\n # inkmlDict = eval(fread)\n # f.close()\n # return (typeStatisticDict, nameIndexDict, inkmlDict)\n\n\n\n typeStatisticDict = {} # 用于统计生成ImageNet\n nameIndexDict = {} # 将原文件名映射到新文件名(xxx.inkml -> 000001)\n inkmlDict = {} # 读取出来的所有inkml\n\n fileNum = -1\n f_inkml = os.listdir(pathInkml)\n for f in f_inkml:\n fileNum += 1\n # if fileNum % 20 == 0:\n # print(fileNum)\n # print(fileNum,\"processing \" + f)\n fileNumName = '%06d' % fileNum\n nameIndexDict[f] = fileNumName\n nameIndexDict[fileNumName] = f\n # 读取inkml\n DOMTree = XmlDocument.parse(pathInkml + \"\\\\\" + f)\n ink = DOMTree.documentElement\n # 解析traces,统计markbox的最大最小值\n traces = ink.getElementsByTagName(\"trace\")\n (tracesDict, tracesBoxDict) = readTraceInfo(traces, PICSIZE, PADDINGPIC)\n # 解析traceGroup\n traceGroups = ink.getElementsByTagName(\"traceGroup\")[0].getElementsByTagName(\"traceGroup\")\n (traceGroupsDict, traceGroupsBoxDict, traceGroupsTypeDict, typesSet) = readTraceGroupsInfo(traceGroups, tracesBoxDict, drawComponentSettingDict, PICSIZE)\n \n typeStatisticDict[f] = typesSet\n inkmlDict[f] = {\"tracesDict\":tracesDict, \n \"tracesBoxDict\":tracesBoxDict, \n \"traceGroupsDict\":traceGroupsDict, \n \"traceGroupsBoxDict\":traceGroupsBoxDict, \n \"traceGroupsTypeDict\":traceGroupsTypeDict}\n \n\n f = open(os.path.join(pathDict,'typeStatisticDict.txt'),'w')\n f.write(str(typeStatisticDict))\n f.close()\n f = open(os.path.join(pathDict,'nameIndexDict.txt'),'w')\n f.write(str(nameIndexDict))\n f.close()\n f = open(os.path.join(pathDict,'inkmlDict.txt'),'w')\n f.write(str(inkmlDict))\n f.close()\n\n return (typeStatisticDict, nameIndexDict, inkmlDict)","sub_path":"2.1_flowchart2lg_FC_B/readInkml.py","file_name":"readInkml.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299494336","text":"# -*- coding: utf-8 -*-\n\"\"\"\n销量异常数据检查\n\n对于店品的销量数据,有很多不明确的场景,系统希望通过找出销量异常值\n来找出实际销售过程中特殊场景,方便后续业务规则调整\n\n样本数据突变值检测\n\nhttps://blog.csdn.net/Jasminexjf/article/details/88527966\n\"\"\"\nimport base as B\n\ndef sale_err_check(df, goods_list):\n err_sku_list = []\n for sku in good_list:\n item_df = df.query('goods_code=={0}'.format(sku))\n err_sku = iqr_check(item_df, sku)\n if err_sku is not None:\n err_sku_list.append('0' * (6 - len(str(err_sku))) + str(err_sku))\n return err_sku_list\n\n\n# 识别异常值函数\ndef iqr_check(data, sku):\n err_sku = None\n series = data['qty']\n max = series.max()\n min = series.min()\n if len(series) > 5:\n iqr = series.quantile(0.75) - series.quantile(0.25)\n low = series.quantile(0.25)\n up = series.quantile(0.75) + 5 * iqr\n if min * 10 < low or max > up:\n err_sku = sku\n print(\"------------\",err_sku)\n plt_draw(data)\n pause_flag=True\n return err_sku\n\n\ndef plt_draw(df):\n df=df[['day','qty']]\n df=df.sort_values(by='day',ascending=True)\n df['day']=df['day'].astype('str')#x轴 时间必须转换为字符串\n df.index=df['day']\n fig = B.plt.figure()\n ax = fig.add_subplot(111)\n df.plot(kind='line', ax=ax)\n B.plt.show()\n\n\n\nif __name__ == '__main__':\n input_file = 'sale_data.csv'\n df = B.pd.read_csv(input_file)\n good_list = df['goods_code'].drop_duplicates().values.tolist()\n # print(\"店品列表:\", good_list)\n # print(\"总共多少个店品:\", len(good_list))\n # print(df.query('goods_code==941047'))\n list = sale_err_check(df, good_list)\n print(\"异常店品=\", len(list))\n print(\"异常店品=\", list)\n\n","sub_path":"4_data_analysis/sale_forecast/err_check/sale_data_err_check.py","file_name":"sale_data_err_check.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"359430184","text":"from datetime import datetime, timedelta, date\nfrom dateutil.tz import tzlocal\nimport logging as log\nimport string\nimport sys\nimport json\n\nlogging = log.getLogger('crm_dump_to_SQL')\n\ndef log_missing_data(name_obj, obj_id, field):\n logging.debug(f'''{name_obj} {obj_id} does not have {field}''')\n\n\ndef log_does_not_exist(name_obj, obj_id, field):\n logging.debug(f'''{name_obj} {obj_id} {field} not found''')\n\n\ndef generate_bussinessline(name):\n bussiness_map = {\n 'Kids và Teens': 'Other',\n 'MOBILE': '18+',\n 'WEB': '18+',\n 'C4K': 'Kids',\n 'C4T': 'Teens',\n '18+': '18+',\n 'APP': 'Kids',\n 'TEENS': 'Teens',\n 'TEEN': 'Teens',\n 'KIDS': 'Kids',\n }\n for bussiness_patterm in bussiness_map.keys():\n if bussiness_patterm.upper() in name.upper():\n return bussiness_map[bussiness_patterm]\n return 'Other'\n\n\ndef generate_productline(name):\n productline_map = {\n 'C4K-WB': 'Web',\n 'C4K-WA': 'Web',\n 'C4K-NG': 'Other',\n 'APP CREATOR': 'App',\n 'C4K-LTST': 'Other',\n 'C4K-GB': 'Game',\n 'C4K-GA': 'Game',\n 'C4K-GI': 'Game',\n 'C4K-WI': 'Web',\n 'C4K-RB': 'Game',\n 'C4K-RA': 'Other',\n '18+C4EJ': 'C4E',\n '18+C4EP': 'C4E',\n 'SUMMER VER': 'Other',\n 'C4T-A': 'CS',\n 'C4T-AI': 'Other',\n '18+CI': 'Other',\n '18+WF': 'Web',\n '18+WFP': 'Web',\n '18+RN': 'App',\n '18+CIJava': 'Web',\n 'C4T-B': 'Web',\n 'TRẠI HÈ': 'Other',\n 'C++': 'Other',\n 'C4K-SB': 'Other',\n 'FRESHER WEB': 'Web',\n 'MOBILE APP': 'App'\n }\n\n for productline_patterm in productline_map.keys():\n if productline_patterm in name.upper():\n return productline_map[productline_patterm]\n return 'Other'\n\n\ndef de_empty(obj, default=''):\n return obj if bool(obj) else default\n\ndef epoch_time(x=datetime.now(tzlocal())):\n if type(x) == date:\n x = datetime.combine(x, datetime.min.time())\n return x.timestamp() * 1000\n\ndef milliseconds_to_seconds(time):\n if time:\n return time / 1000\n return datetime.now().timestamp()\n\ndef epoch_time_in_the_past(weeks=0, days=0, hours=0, minutes=0):\n print(\"Time to look back: {0}W:{1}D {2}h:{3}m\".format(weeks, days, hours, minutes))\n now = datetime.now(tzlocal())\n time_in_the_past = now - timedelta(weeks=weeks, days=days, hours=minutes, minutes=minutes)\n return epoch_time(time_in_the_past)\n\ndef link_contact_with_redundancy(v2_contact_obj, relation=None):\n link = {\n '_id': v2_contact_obj._id,\n 'fullName': v2_contact_obj.fullName,\n 'phoneNumber': v2_contact_obj.phoneNumber,\n 'email': v2_contact_obj.email,\n }\n if v2_contact_obj.family:\n link['family'] = v2_contact_obj.family\n if bool(relation):\n link['relation'] = relation\n return link\n\ndef to_none_if_empty(obj):\n if not bool(obj):\n return None\n return obj\n\n# vn_characters = 'ĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴAĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴAĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴAĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴAĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴAĂÂÁẮẤÀẰẦẢẲẨÃẴẪẠẶẬĐEÊÉẾÈỀẺỂẼỄẸỆIÍÌỈĨỊOÔƠÓỐỚÒỒỜỎỔỞÕỖỠỌỘỢUƯÚỨÙỪỦỬŨỮỤỰYÝỲỶỸỴboôơaâăêeuưiyrlcdóồớáấắềéụứíýnhsđòộờàầằếèúừìỳmtxgõổởãẫẵễẽũữĩỷvkpỏỗợảẩẳểẻủửỉỹ₫qọốỡạậặệẹùựịỵ'\n# ignore_characters = set(list(string.ascii_letters + string.punctuation + string.whitespace + vn_characters + '\\u202d'))\n# translate_map = {\n# ord(c): '' for c in ignore_characters\n# }\n\nten_digits_map = {\n '016': '+843',\n '0120': '+8470',\n '0121': '+8479',\n '0122': '+8477',\n '0126': '+8476',\n '0128': '+8478',\n '0123': '+8483',\n '0124': '+8484',\n '0125': '+8485',\n '0127': '+8481',\n '0129': '+8482',\n '0186': '+8456',\n '0188': '+8458',\n '0199': '+8459',\n '09': '+849',\n '16': '+843',\n '120': '+8470',\n '121': '+8479',\n '122': '+8477',\n '126': '+8476',\n '128': '+8478',\n '123': '+8483',\n '124': '+8484',\n '125': '+8485',\n '127': '+8481',\n '129': '+8482',\n '186': '+8456',\n '188': '+8458',\n '199': '+8459',\n '9': '+849',\n}\nextended_digits_map = ten_digits_map.copy()\nfor key, value in ten_digits_map.items():\n extended_digits_map['+84' + key] = value\n extended_digits_map['p:+84' + key] = value\n\ndef exec_sanitize_phone(input_phone):\n if bool(input_phone):\n input_phone = ''.join(c for c in str(input_phone) if c in string.digits)\n phone = de_empty(str(input_phone.strip())) \\\n .replace('+84', '') \\\n .replace(' ', '') \\\n .replace('+84p:', '') \\\n .replace('p:', '')\n if phone.startswith('84'):\n phone = phone[2:]\n if not bool(phone) or len(phone) == 0:\n return ''\n if len(phone) == 8:\n phone = '9' + phone\n for key, value in extended_digits_map.items():\n if phone.startswith(key):\n phone_chars = list(phone)\n phone = value + ''.join(phone_chars[len(key):])\n return phone\n try:\n phone = '+84' + str(int(phone))\n return phone\n except ValueError:\n print(list(phone))\n print(f'Can NOT correct phone {phone}')\n sys.exit()\n\ndef bind_upsert_one(collection):\n def upsert_one(query, update):\n collection.update_one(query, update, upsert=True)\n return collection.find_one(query)\n collection.upsert_one = upsert_one\n\ndef read_json(url):\n with open(url) as f:\n return json.loads(f.read())","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"387311036","text":"###############################################################################\n# Copyright 2015 William Chan .\n###############################################################################\n\n\nimport google\n\nfrom tensorflow.core.framework import token_model_pb2\n\nclass TokenModel(object):\n def __init__(self, token_model_path):\n self.proto = token_model_pb2.TokenModelProto()\n with open(token_model_path, \"r\") as proto_file:\n google.protobuf.text_format.Merge(proto_file.read(), self.proto)\n\n self.token_to_string = {}\n self.string_to_token = {}\n\n for token in self.proto.tokens:\n self.token_to_string[token.token_id] = token.token_string\n self.string_to_token[token.token_string] = token.token_id\n\n def string_to_tokens(self, string):\n return [self.proto.token_sos] + [self.token_to_string[w] for w in string]\n","sub_path":"speech4/models/token_model.py","file_name":"token_model.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"561260888","text":"import pandas as pd\nimport numpy as np\nimport nltk\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nimport difflib\nimport sys\nsys.path.append('//Data_Preprocessor.py')\nimport Data_Preprocessor\n\nclass feature_extracter:\n\n def __init__(self, train):\n self.stops = set(stopwords.words(\"english\"))\n self.tfidf = TfidfVectorizer(stop_words='english', ngram_range=(1, 1))\n self.tfidf_txt = pd.Series(\n train['question1'].tolist() + train['question2'].tolist()).astype(str)\n self.tfidf.fit_transform(self.tfidf_txt)\n\n def preprocess(train):\n question1List=[]\n question2List=[]\n for counter in range(len(train[\"question1\"])):\n question1List.append(Data_Preprocessor.cleanup(train[\"question1\"][counter]))\n question2List.append(Data_Preprocessor.cleanup(train[\"question2\"][counter]))\n series1 = pd.Series(question1List)\n series2 = pd.Series(question2List)\n train[\"question1\"]=series1\n train[\"question2\"]=series2\n return train\n\n def diff_ratios(self, st1, st2):\n seq = difflib.SequenceMatcher()\n seq.set_seqs(str(st1).lower(), str(st2).lower())\n return seq.ratio()\n\n\n def word_match_share(self, row):\n q1words = {}\n q2words = {}\n for word in str(row['question1']).lower().split():\n if word not in self.stops:\n q1words[word] = 1\n for word in str(row['question2']).lower().split():\n if word not in self.stops:\n q2words[word] = 1\n if len(q1words) == 0 or len(q2words) == 0:\n return 0\n shared_words_in_q1 = [w for w in q1words.keys() if w in q2words]\n shared_words_in_q2 = [w for w in q2words.keys() if w in q1words]\n R = (len(shared_words_in_q1) + len(shared_words_in_q2))/(len(q1words) + len(q2words))\n return R\n\n\n\n def tfidf_word_match_share(self, row):\n q1words = {}\n q2words = {}\n for word in str(row['question1']).lower().split():\n if word not in self.stops:\n q1words[word] = 1\n for word in str(row['question2']).lower().split():\n if word not in self.stops:\n q2words[word] = 1\n if len(q1words) == 0 or len(q2words) == 0:\n return 0\n q1_tfidf = self.tfidf.transform([\" \".join(q1words.keys())])\n q2_tfidf = self.tfidf.transform([\" \".join(q2words.keys())])\n inter = np.intersect1d(q1_tfidf.indices, q2_tfidf.indices)\n shared_weights = 0\n for word_index in inter:\n shared_weights += (q1_tfidf[0, word_index] + q2_tfidf[0, word_index])\n total_weights = q1_tfidf.sum() + q2_tfidf.sum()\n return np.sum(shared_weights) / np.sum(total_weights)\n\n\n\n def get_features(self, df_features):\n print('Procesing nouns...')\n df_features['question1_nouns'] = df_features.question1.map(lambda x: [w for w, t in nltk.pos_tag(nltk.word_tokenize(str(x).lower())) if t[:1] in ['N']])\n df_features['question2_nouns'] = df_features.question2.map(lambda x: [w for w, t in nltk.pos_tag(nltk.word_tokenize(str(x).lower())) if t[:1] in ['N']])\n df_features['z_noun_match'] = df_features.apply(lambda r: sum([1 for w in r.question1_nouns if w in r.question2_nouns]), axis=1)\n print('Processing lengths...')\n df_features['z_len1'] = df_features.question1.map(lambda x: len(str(x)))\n df_features['z_len2'] = df_features.question2.map(lambda x: len(str(x)))\n df_features['z_word_len1'] = df_features.question1.map(lambda x: len(str(x).split()))\n df_features['z_word_len2'] = df_features.question2.map(lambda x: len(str(x).split()))\n print('Processing difflib...')\n df_features['z_match_ratio'] = df_features.apply(lambda r: self.diff_ratios(r.question1, r.question2), axis=1) #takes long\n print('word match...')\n df_features['z_word_match'] = df_features.apply(self.word_match_share, axis=1, raw=True)\n print('Processing tfidf...')\n df_features['z_tfidf_sum1'] = df_features.question1.map(lambda x: np.sum(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_sum2'] = df_features.question2.map(lambda x: np.sum(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_mean1'] = df_features.question1.map(lambda x: np.mean(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_mean2'] = df_features.question2.map(lambda x: np.mean(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_len1'] = df_features.question1.map(lambda x: len(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_len2'] = df_features.question2.map(lambda x: len(self.tfidf.transform([str(x)]).data))\n df_features['z_tfidf_share'] = df_features.apply(self.tfidf_word_match_share, axis=1, raw=True)\n print('Processing Named Entities...')\n df_features['z_ner_match'] = df_features.apply(Data_Preprocessor.namedEntityMatch, axis=1, raw=True)\n return df_features.fillna(0.0)","sub_path":"Feature_Extracter.py","file_name":"Feature_Extracter.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"261941595","text":"#!/usr/bin/env python3\n\"\"\" Copyright (c) 2018, Juniper Networks, Inc\n All rights reserved\n This SOFTWARE is licensed under the LICENSE provided in the\n ./LICENCE file. By downloading, installing, copying, or otherwise\n using the SOFTWARE, you agree to be bound by the terms of that\n LICENSE.\n\"\"\"\n\n# stdlib\nimport argparse\nimport datetime\nimport getpass\nimport logging\nimport os\nimport re\nimport signal\nfrom socket import gethostbyname, gaierror, herror\n\n# local modules\nfrom splitcopy.put import SplitCopyPut\nfrom splitcopy.get import SplitCopyGet\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n \"\"\"body of script\"\"\"\n\n def handlesigint(sigint, stack):\n raise SystemExit\n\n signal.signal(signal.SIGINT, handlesigint)\n start_time = datetime.datetime.now()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"source\", help=\"either or user@: or :\"\n )\n parser.add_argument(\n \"target\", help=\"either or user@: or :\"\n )\n parser.add_argument(\n \"--pwd\", nargs=1, help=\"password to authenticate on remote host\"\n )\n parser.add_argument(\n \"--ssh_key\",\n nargs=1,\n help=\"path to ssh private key (only if in non-default location)\",\n )\n parser.add_argument(\n \"--scp\", action=\"store_true\", help=\"use scp to copy files instead of ftp\"\n )\n parser.add_argument(\n \"--noverify\",\n action=\"store_true\",\n help=\"skip sha hash comparison of src and dst file\",\n )\n parser.add_argument(\n \"--split_timeout\",\n nargs=1,\n help=\"time to wait for file split operation to complete, default 120\",\n )\n parser.add_argument(\n \"--ssh_port\",\n nargs=1,\n help=\"ssh port number to connect to\",\n )\n parser.add_argument(\"--log\", nargs=1, help=\"log level, eg DEBUG\")\n args = parser.parse_args()\n\n if not args.log:\n loglevel = \"WARNING\"\n else:\n loglevel = args.log[0]\n\n numeric_level = getattr(logging, loglevel.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError(f\"Invalid log level: {loglevel}\")\n logging.basicConfig(\n format=\"%(asctime)s %(name)s %(lineno)s %(funcName)s %(levelname)s:%(message)s\",\n level=numeric_level,\n )\n\n user = None\n host = None\n passwd = None\n ssh_key = None\n ssh_port = 22\n remote_dir = None\n remote_file = None\n remote_path = None\n local_dir = None\n local_path = None\n copy_proto = None\n get = False\n noverify = args.noverify\n source = args.source\n target = args.target\n\n if re.search(r\".*:\", source):\n if re.search(r\"@\", source):\n user = source.split(\"@\")[0]\n host = source.split(\"@\")[1]\n host = host.split(\":\")[0]\n else:\n user = getpass.getuser()\n host = source.split(\":\")[0]\n remote_path = source.split(\":\")[1]\n remote_file = os.path.basename(remote_path)\n remote_dir = os.path.dirname(remote_path)\n if remote_dir == \"\" or remote_dir == \".\":\n remote_dir = \"~\"\n remote_path = f\"{remote_dir}/{remote_file}\"\n if not remote_file:\n raise SystemExit(\"src path doesn't specify a file name\")\n get = True\n elif os.path.isfile(source):\n local_path = os.path.abspath(os.path.expanduser(source))\n try:\n with open(local_path, \"rb\"):\n pass\n except PermissionError:\n raise SystemExit(\n f\"source file {local_path} exists but is not readable - cannot proceed\"\n )\n local_file = os.path.basename(local_path)\n local_dir = os.path.dirname(local_path)\n else:\n raise SystemExit(\n \"specified source is not a valid path to a local \"\n \"file, or is not in the format @: \"\n \"or :\"\n )\n\n if re.search(r\".*:\", target):\n if re.search(r\"@\", target):\n user = target.split(\"@\")[0]\n host = target.split(\"@\")[1]\n host = host.split(\":\")[0]\n else:\n user = getpass.getuser()\n host = target.split(\":\")[0]\n remote_path = target.split(\":\")[1]\n if remote_path == \"\":\n remote_dir = \"~\"\n remote_file = local_file\n remote_path = f\"{remote_dir}/{remote_file}\"\n elif os.path.dirname(remote_path) == \"\":\n remote_dir = \"~\"\n remote_file = remote_path\n remote_path = f\"{remote_dir}/{remote_file}\"\n elif os.path.isdir(target):\n local_dir = os.path.abspath(os.path.expanduser(target))\n local_file = remote_file\n elif os.path.isdir(os.path.dirname(target)):\n # we've been passed in a filename, may not exist yet\n local_dir = os.path.dirname(os.path.abspath(os.path.expanduser(target)))\n if os.path.basename(target) != remote_file:\n # have to honour the change of name\n local_file = os.path.basename(target)\n else:\n local_file = remote_file\n else:\n raise SystemExit(\n \"specified target is not a valid path to a local \"\n \"file or directory, or is not in the format @: \"\n \"or :\"\n )\n\n try:\n host = gethostbyname(host)\n except (gaierror, herror):\n raise SystemExit(\"hostname resolution failed\")\n\n if args.pwd:\n passwd = args.pwd[0]\n\n if not args.scp:\n copy_proto = \"ftp\"\n else:\n copy_proto = \"scp\"\n\n if args.ssh_key is not None:\n ssh_key = os.path.abspath(args.ssh_key[0])\n if not os.path.isfile(ssh_key):\n raise SystemExit(\"specified ssh key not found\")\n\n if args.ssh_port is not None:\n try:\n ssh_port = int(args.ssh_port[0])\n except ValueError:\n raise SystemExit(\"ssh_port must be an integer\")\n\n split_timeout = 120\n if args.split_timeout is not None:\n try:\n split_timeout = int(args.split_timeout[0])\n except ValueError:\n raise SystemExit(\"split_timeout must be an integer\")\n if split_timeout < 120:\n split_timeout = 120\n print(\"split_timeout value is < default of 120. setting it to 120\")\n\n kwargs = {\n \"user\": user,\n \"host\": host,\n \"passwd\": passwd,\n \"ssh_key\": ssh_key,\n \"ssh_port\": ssh_port,\n \"remote_dir\": remote_dir,\n \"remote_file\": remote_file,\n \"remote_path\": remote_path,\n \"local_dir\": local_dir,\n \"local_file\": local_file,\n \"local_path\": local_path,\n \"copy_proto\": copy_proto,\n \"get\": get,\n \"noverify\": noverify,\n \"split_timeout\": split_timeout,\n }\n logger.info(kwargs)\n\n if get:\n splitcopyget = SplitCopyGet(**kwargs)\n loop_start, loop_end = splitcopyget.get()\n else:\n splitcopyput = SplitCopyPut(**kwargs)\n loop_start, loop_end = splitcopyput.put()\n\n # and we are done...\n end_time = datetime.datetime.now()\n time_delta = end_time - start_time\n transfer_delta = loop_end - loop_start\n print(f\"data transfer = {transfer_delta}\\ntotal runtime = {time_delta}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"splitcopy/splitcopy.py","file_name":"splitcopy.py","file_ext":"py","file_size_in_byte":7329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"519506918","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport math\n\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\n\n#link = \"http://suninjuly.github.io/find_link_text_redirect13.html\"\n#link = \"http://suninjuly.github.io/math.html\"\nlink = \"http://suninjuly.github.io/get_attribute.html\"\n\ntry:\n browser = webdriver.Chrome()\n browser.get(link)\n\n x_element = browser.find_element_by_xpath(\"//*[@id='treasure']\")\n x_element1 = x_element.get_attribute(\"valuex\")\n print(x_element1)\n #x = x_element1.text\n y = calc(x_element1)\n input = browser.find_element_by_css_selector(\"#answer\")\n input.send_keys(y)\n input1 = browser.find_element(By.XPATH, \"//*[@id='robotCheckbox']\")\n input1.click()\n input2 = browser.find_element(By.XPATH, \"//*[@id='robotsRule']\")\n input2.click()\n\n button = browser.find_element(By.XPATH, \"/html/body/div/form/div/div/button\")\n button.click()\n\nfinally:\n # закрываем браузер после всех манипуляций\n time.sleep(8)\n browser.quit()","sub_path":"stepik2.1,5,7.py","file_name":"stepik2.1,5,7.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362492606","text":"from __future__ import with_statement, print_function\nimport numpy as np\nimport random\n\nfrom tsp_solver.greedy_numpy import solve_tsp\n\ntry:\n import psyco\n\n psyco.full()\nexcept:\n pass\n\ndef random_generate(x_size,y_size):\n tmp = [[x, y] for x in range(x_size) for y in range(y_size)]\n random.shuffle(tmp)\n block = np.array([[2*x+1,2*y] for (x,y) in tmp])\n random.shuffle(tmp)\n rfid = np.array([[2*x,2*y+1] for (x,y) in tmp])\n\n return block, rfid\n\ndef generate_dist_matrix(block, rfid):\n assert len(block)==len(rfid)\n dist_matrix = np.eye(2*len(block))\n self_dist_matrix = np.sum(np.abs(block-rfid),axis=1)\n for i in range(2*len(block)) :\n for j in range(2 * len(block)):\n if i<=j:\n continue\n if i=len(block):\n dist_matrix[i][j] = np.inf\n elif i-len(block) == j:\n dist_matrix[i][j] = 0\n else:\n dist_matrix[i][j] = self_dist_matrix[i-len(block)] + np.sum(np.abs(rfid[i-len(block)]-block[j]))\n dist_matrix += dist_matrix.T - np.diag(dist_matrix.diagonal())\n return dist_matrix\n\ndef figure_plot(block, rfid, path):\n coordinate = np.concatenate([block, rfid], axis=0).T\n try:\n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n except ImportError as err:\n print(\"Can't show plot, matplotlib module not available:\", err)\n print(\"Either install matplotlib or set an -o option\")\n exit(2)\n # plt.plot(coordinate[0, path], coordinate[1, path], ':', block.T[0,:], block.T[1,:], 'bs', rfid.T[0, :], rfid.T[1, :], 'r*')\n # plt.show()\n fig = plt.figure()\n ax = fig.add_subplot(111)\n line, line2, line3, = ax.plot([], [], '-.k', block.T[0, :], block.T[1, :], 'bs', rfid.T[0, :], rfid.T[1, :], 'r*')\n ax.set_xlabel('Distance in X axis (unit cell)')\n ax.set_ylabel('Distance in Y axis (unit cell)')\n ax.set_title('Winter Camp Solution', fontsize=15)\n\n def update(data):\n line.set_xdata(data[0])\n line.set_ydata(data[1])\n return line,\n\n def data_gen():\n end = 0\n start = 0\n while end4:\n # start = end - 4\n yield coordinate[:, path[start:end]]\n end += 1\n\n ani = animation.FuncAnimation(fig, update, data_gen, interval=400)\n plt.show()\n\ndef main():\n from optparse import OptionParser\n\n parser = OptionParser( description = \"Winter Camp TSP solver\" )\n parser.add_option( \"-r\", \"--random\", dest=\"random\", default=True,\n help=\"Generate the coordination pairs of the certain rfid and block\" )\n parser.add_option( \"-x\", \"--xsize\", dest=\"x_size\", type=\"int\", default=6,\n help=\"Set the size in x\" )\n parser.add_option( \"-y\", \"--ysize\", dest=\"y_size\", type=\"int\", default=6,\n help=\"Set the size in y\" )\n parser.add_option( \"-p\", \"--plot\",\n dest=\"show_plot\", default=True,\n help=\"Whether to show the figure plot\" )\n\n\n (options, args) = parser.parse_args()\n if options.random:\n x_size = options.x_size\n y_size = options.y_size\n block, rfid = random_generate(x_size, y_size)\n\n # print(\"block\",block)\n # print(\"rfid\",rfid)\n\n dist_matrix = generate_dist_matrix(block, rfid)\n path = solve_tsp(dist_matrix,optim_steps=1000000)\n\n show_path = [i + 1 if i < len(block) else -i + len(block) - 1 for i in path]\n print(show_path)\n\n if options.show_plot:\n figure_plot(block, rfid, path)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"TSP_demo.py","file_name":"TSP_demo.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372846641","text":"import jsonpickle\nfrom Connection import Connection\nfrom Socket import Socket\nfrom Blockchain import Blockchain\nfrom Node import Node\nimport socket\nimport time\nimport threading\nimport commands\nimport random\nimport json\nimport hashlib\n\nfrom settings.terminal_set import bcolors\nfrom helpers.terminal_helper import print_colored\nfrom Message import Message\n\nimport os\n\nimport config\nos.system(\"color\")\n\n\n\n# class EventHandler1:\n# def join(self):\n\n# pass\n\n\n\n\n\n\n\nclass Network(Connection,Socket):\n\n def __init__(self,ip=\"\",port=None):\n if(ip==\"\"):\n ip=config.SELF_STATIC_IP\n if(ip==\"localhost\"):\n ip = socket.gethostbyname(socket.gethostname())\n Socket.__init__(self, ip,port)\n Connection.__init__(self,ip,port)\n self.SERVER_IP=ip\n self.blockchain = Blockchain()\n self.nodes_in_network.append({\"ip_addr\":self.GENESIS_NODE_ADDR,\"port\":self.GENESIS_NODE_PORT})\n self.counted_votes=list()\n\n\n def broadcast(self,data,isJson=False,title=\"#BROADCAST\"):\n\n if isJson==False:\n msg = self.short_json_msg(title,data)\n else:\n msg=data\n\n try:\n index = self.message_logs.index(msg[\"id\"])\n\n except:\n index=-1\n self.message_logs.append(msg[\"id\"])\n\n\n\n\n for node in self.nodes:\n\n try:\n self.send(node,msg) \n\n except:\n pass\n #print_colored(\"MESSAGE COULDN'T SEND, RECIEVER MAY BE DISCONNECTED \",\"red\")\n\n \n\n def join_network(self ,ip=None,port=None):\n \n if ip==None:\n ip=self.GENESIS_NODE_ADDR\n if port==None:\n port=self.GENESIS_NODE_PORT\n\n\n print(f\"{ip}{port}\")\n conn=self.create_connection(ip, port)\n\n random_node = self.ask_random_node(conn)\n \n node = json.loads(random_node)\n \n\n if node==None:\n self.remove_connection(conn, ip, port)\n print(\"Network is not exist...\")\n print(\"Connecting to Genesis Node\",end=\"\\n\\n\")\n self.connect_to_node(self.GENESIS_NODE_ADDR, self.GENESIS_NODE_PORT)\n \n else:\n\n self.remove_connection(conn, ip, port)\n \n self.ask_nodes(node[\"ip_addr\"], node[\"port\"])\n \n\n \n temp_node = self.nodes[0]\n \n \n\n\n\n \n\n broadcast_msg=Message(self.SERVER_IP,self.SERVER_PORT).msg(\"#JOINED_IN_NETWORK\",\"#BROADCAST\")\n\n self.broadcast(broadcast_msg,isJson=True)\n msg=Message().short_msg(commands.GIVE_NODES_IN_NETWORK,\"\")\n\n nodes = self.send(temp_node,msg,1)\n\n\n \n nodes=json.loads(nodes)\n\n nodes=nodes[\"message\"]\n\n\n\n for node in nodes:\n \n try:\n index = self.nodes_in_network.index(node)\n except:\n index = -1\n\n if index ==-1 :\n\n self.nodes_in_network.append(node)\n\n\n\n\n random_conn_id=random.randint(0,len(self.nodes)-1)\n random_conn = self.nodes[random_conn_id]\n chain = self.ask_blockchain(random_conn)\n print_colored(\"Chain Recieved\",\"green\")\n\n\n\n\n\n\n def ask_blockchain(self,conn):\n\n message=self.short_json_msg(commands.ASK_CURRENT_CHAIN,\"\")\n chain = self.send(conn,message,1)\n chain=json.loads(chain)\n \n chain:Blockchain=jsonpickle.decode(chain[\"message\"])\n print(chain.chain[-1].data[-1].__dict__)\n \n self.blockchain=chain\n\n\n\n\n def ask_nodes(self,ip,port):\n\n conn = self.create_connection(ip, port)\n\n msg_json=self.short_json_msg(commands.ASK_NODES_TO_CONNECT,\"\")\n\n msg = self.send(conn,msg_json,1)\n\n disconnect_msg=self.short_json_msg(self.DISCONNECT_MSG)\n\n self.send(conn,disconnect_msg)\n\n msg=json.loads(msg)\n\n nodes=msg[\"message\"]\n\n\n print_colored(f\"{len(nodes)} Node address recieved...\",\"cyan\")\n\n\n for node in nodes:\n self.connect_to_node(node[\"ip_addr\"], node[\"port\"])\n \n\n\n \n def ask_random_node(self,conn):\n\n \n message=self.short_json_msg(commands.ASK_RANDOM_NODE,f\"{self.SERVER_IP},{self.SERVER_PORT}\")\n \n msg = self.send(conn,message,1)\n \n \n disconnect_msg=self.short_json_msg(self.DISCONNECT_MSG)\n\n self.send(conn,disconnect_msg)\n \n return msg\n\n\n\n def connect_to_node(self,ip,port):\n \n print(f\"_______{ip}_{port}_______________________-\")\n\n self.CONN_ADDR=(ip,port)\n\n if(self.CONN_ADDR not in self.connections):\n\n connection=self.node_socket.create_connection(ip,port)\n\n x={\"ip_addr\":ip,\"port\":port}\n\n self.nodes.append(connection)\n\n self.connections.append(self.CONN_ADDR)\n\n self.connections_json.append(x)\n\n\n msg=self.short_json_msg(commands.NODE_CON_ADDR,f\"{self.SERVER_IP},{self.SERVER_PORT}\")\n \n self.send(connection,msg)\n\n\n\n print_colored(f\"Connected To->{ip}:{port}\",\"green\",2)\n return\n\n\n","sub_path":"src/ballotbox/Network.py","file_name":"Network.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"552238607","text":"\nimport subprocess\nimport tempfile\n\n\nclass AxSSH(object):\n\n def __init__(self, host, user, password):\n self.host = host\n self.user = user\n self.password = password\n\n def _ssh(self, commands):\n t = tempfile.TemporaryFile()\n ssh = subprocess.Popen(['ssh', '-o', 'StrictHostKeyChecking=no',\n \"%s@%s\" % (self.user, self.host)],\n close_fds=True,\n shell=False,\n stdin=subprocess.PIPE,\n stdout=t)\n\n ssh.stdin.writelines(commands)\n ssh.wait()\n\n t.flush()\n t.seek(0)\n lines = t.readlines()\n t.close()\n\n return lines[4:-3]\n\n def config_get(self, acos_commands, verbose=True):\n commands = ['en\\r\\n',\n '\\r\\n',\n 'terminal length 0\\r\\n']\n commands += acos_commands\n commands += ['exit\\r\\n',\n 'exit\\r\\n',\n 'y\\r\\n']\n\n if verbose:\n print(commands)\n lines = self._ssh(commands)\n if verbose:\n print(lines)\n trim = []\n for line in lines:\n x = line.strip()\n if x == '' or x[0] == '!':\n continue\n trim.append(line)\n return trim\n\n def config_gets(self, commands, verbose=True):\n return ''.join(self.config_get(commands, verbose))\n\n def erase(self):\n commands = [\n 'config\\r\\n',\n 'erase preserve-management preserve-accounts reload\\r\\n',\n 'y\\r\\n',\n '\\r\\n',\n # 'web-service server\\r\\n',\n # 'web-service port 8080\\r\\n',\n # 'web-service secure-server\\r\\n',\n # 'web-service secure-port 8443\\r\\n',\n # 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands)\n\n def enable_web(self):\n commands = [\n 'config\\r\\n',\n 'web-service server\\r\\n',\n 'web-service port 8080\\r\\n',\n 'web-service secure-server\\r\\n',\n 'web-service secure-port 8443\\r\\n',\n 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands)\n\n def license(self, sn, id):\n commands = [\n 'config\\r\\n',\n 'license-manager host 104.236.80.136 port 443 use-mgmt-port\\r\\n',\n 'license-manager host 54.213.147.205 port 443 use-mgmt-port\\r\\n',\n 'license-manager host 54.164.152.116 port 443 use-mgmt-port\\r\\n',\n \"license-manager sn %s\\r\\n\" % sn,\n 'license-manager interval 3\\r\\n',\n \"license-manager instance_name openstack-ci-%s\\r\\n\" % id,\n 'license-manager bandwidth_unrestricted\\r\\n',\n 'license-manager connect\\r\\n',\n 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands, verbose=False)\n\n def set_admin_password(self, id):\n commands = [\n 'config\\r\\n',\n \"admin admin password %s\\r\\n\" % id,\n 'end\\r\\n',\n 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands, verbose=False)\n\n def partition_list(self):\n commands = [\n 'config\\r\\n',\n 'show partition\\r\\n',\n 'end\\r\\n',\n ]\n z = self.config_get(commands)\n print(\"Z = %s\" % z)\n print(\"len = %d\" % len(z))\n print(\"split = %s\" % map(lambda x: x.split(), z))\n return map(lambda x: x.split()[0], z[7:-2])\n\n def partition_delete(self, partitions):\n commands = [\n 'config\\r\\n',\n ]\n for p in partitions:\n commands += [\n \"no partition %s\\r\\n\" % p,\n 'yes\\r\\n',\n ]\n commands += [\n 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands)\n\n def partition_show_run(self, partition):\n commands = [\n 'active-partition %s\\r\\n' % partition,\n 'show run\\r\\n'\n ]\n return self.config_gets(commands)\n\n def write_mem(self):\n commands = [\n 'config\\r\\n',\n 'write mem\\r\\n',\n 'end\\r\\n',\n ]\n self.config_gets(commands)\n\n def reboot(self):\n commands = [\n 'reboot\\r\\n',\n 'yes\\r\\n',\n 'yes\\r\\n'\n ]\n self.config_gets(commands)\n\n def show_run(self):\n return self.config_gets(['show run\\r\\n'])\n","sub_path":"ax/ax_ssh.py","file_name":"ax_ssh.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77517693","text":"import re\nfrom collections import deque\nimport json\nimport sys\nimport socket\nimport time\nimport threading\n\n\"\"\"\n Network Score Application\n\n Author: Isaac Thiessen Mar 2019\n\n Plan:\n 1. Make system functional without error handling\n 2. Add error handling/player disconnects\n \n\"\"\"\n\nTIMEOUT = 200\n\n\nclass STATES:\n HOST_GAME = 0\n IN_GAME = 1\n STARTING_GAME = 2\n\ndef get_tcp_socket(port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n\n # Setting address info\n bind_address = ('0.0.0.0', port)\n\n # Binding to address\n s.bind(bind_address)\n s.listen(5) # No more than 5 connections\n return s\n\n\nclass SockManager(threading.Thread):\n def __init__(self, server_socket, port=8979):\n super(SockManager, self).__init__()\n self.q = deque()\n self.num_clients_served = 0\n self.port = port\n self.max_q_size = 3\n self.alternate_port_modifier = 1\n self.max_players = 1\n\n self.initial_life = 20\n\n self.s = server_socket\n\n # initializing as hosting game\n self.state = STATES.HOST_GAME\n\n # players in format:\n # 'fargus': ('192.168.0.5', 20, socket_object)\n # name ip address life\n self.client_players = set()\n\n self.player_lives = {}\n\n # checking for disconnects\n self.disconnect_checking_thread = threading.Thread(target=self.check_for_disconnects)\n self.disconnect_checking_thread.start()\n\n def run_server(self):\n self.start()\n self.pre_game_handle_clients()\n\n\n def pre_game_handle_clients(self):\n while self.state == STATES.HOST_GAME:\n # First check if any active connections\n if (len(self.q)) == 0:\n # NO active connections, wait a sec and try again\n if len(self.client_players) >= self.max_players:\n print(\"Starting the game because the maximum number of players have joined\")\n self.state = STATES.STARTING_GAME\n\n # this is to stop listening for new clients self.max_players = 1\n c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n c.settimeout(TIMEOUT)\n c.connect(('localhost', self.port))\n c.send(\"DONE\".encode('utf-8'))\n # this works because this loop will stop running once the states have changed\n continue\n\n else:\n client_info = self.q.pop()\n\n ch = ClientHandler(client_info[0], client_info[1], (self.port + self.alternate_port_modifier))\n\n # incramenting alternate port modifier to ensure all secondary lines are running on different ports\n self.alternate_port_modifier += 1\n\n # initiating start_game protocol with client\n ch.host_game()\n\n # adding player to list of players\n self.client_players.add(ch)\n\n self.player_lives[ch.client_name] = self.initial_life\n\n def host_game(self):\n # getting new client and adding to queue\n client_soc, client_addr = self.s.accept()\n self.q.append((client_soc, client_addr))\n print('Got client: ', client_addr)\n\n def start_game(self):\n \"\"\"\n Protocol:\n For each client:\n 1. client listens for the START_GAME signal\n 2. client says OK\n 3. Once each client has responded with OK\n 4. Server sends initial life total\n \"\"\"\n # TODO: FIX THIS! A SINGLE CLIENT WILL STOP THE WHOLE SERVER IF SOMETHING IS WRONG\n\n for player in self.client_players:\n player.start_game()\n\n self.state = STATES.IN_GAME\n\n for player in self.client_players:\n player.start()\n\n self.life_update()\n\n def life_update(self):\n \"\"\"\n Protocol:\n 1. client listens for life update\n 2. server says LIFE_UPDATE\n 3. client says OK\n 4. send each client each players life total in JSON\n - example:\n {\n \"Isaac\": 20,\n \"Liyani\": 4,\n \"Dylan\": 99\n }\n 5. each player responds with OK\n 6. client goes to step 1.\n \"\"\"\n for player in self.client_players:\n if not player.disconnected:\n player.life_update(json.dumps(self.player_lives))\n\n def check_for_new_life(self):\n # here we check for each players updated life\n for player in self.client_players:\n\n # new_life will be none if the user has not set their life\n if player.new_life is not None:\n\n # setting the players life\n self.player_lives[player.client_name] = player.new_life\n\n # resetting the new life to be None\n player.new_life = None\n\n self.life_update()\n\n def kick_player(self, client):\n \"\"\"\n For removing disconnected clients, or just people who are jerks\n :param client: ClientHandler object\n \"\"\"\n print(\"KICKING PLAYER: \", client.client_name)\n # deleting from life totals\n self.player_lives[client.client_name] = \"DISCONNECTED\"\n\n # removing from active connections\n self.client_players.remove(client)\n\n # ending thread\n client.stop()\n\n # informing the players, they will be disappointed\n self.life_update()\n\n def check_for_disconnects(self):\n print(\"Checking for disconnects start\")\n while True:\n # removing disconnected clients\n kick = []\n for client in self.client_players:\n if client.disconnected:\n print(\"FOUND DISCONNECTED CLIENT\")\n kick.append(client)\n\n for dead_client in kick:\n self.kick_player(dead_client)\n\n time.sleep(0.3)\n\n def run(self):\n print(\"Starting server on port %s\" % self.port)\n while True:\n if self.state == STATES.HOST_GAME:\n self.host_game()\n\n elif self.state == STATES.STARTING_GAME:\n print('STARTING GAME NOW')\n print('Players connected: %s ' % len(self.client_players))\n self.start_game()\n\n elif self.state == STATES.IN_GAME:\n self.check_for_new_life()\n time.sleep(1)\n\n\nclass ClientHandler(threading.Thread):\n \"\"\"\n ClientHandler class for Network Score App\n\n Each instance of this object is for communicating with a single client\n 2 lines of communication:\n 1. For sending life updates to client including the life total of each player\n in the form of a json string\n 2. For receiving new life values from client\n\n \"\"\"\n\n def __init__(self, client_soc, client_addr, secondary_port):\n\n # TODO: BIG TODO:\n # ERROR HANDLING\n\n super(ClientHandler, self).__init__()\n self.secondary_port = secondary_port\n self.c = client_soc\n\n self.c.settimeout(TIMEOUT)\n\n self.client_addr = client_addr\n self.client_name = ''\n self.packet_len = 1024\n\n self.rec_life_soc = None\n\n self.disconnected = False\n\n self.new_life = None\n\n def run(self):\n while True:\n if self.disconnected:\n self.stop()\n self.receive_life()\n\n def establish_secondary_communication(self):\n print(\"started second line protocol\")\n \"\"\"\n Here we create a new socket for recieving life from the client so\n we dont get messages from the wrong protocol\n\n Protocol:\n 1. server connects to client\n 2. client says \"NEW_LINE\"\n 3. server says \"BOOYAH\"\n \"\"\"\n # sleeping for 1 second to give client time to set up server\n time.sleep(1)\n print(self.client_addr[0])\n # 0. creating socket\n self.rec_life_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # self.rec_life_soc.settimeout(TIMEOUT)\n\n # 1.\n print(\"connecting to secondary line on port %s\" % self.secondary_port)\n self.rec_life_soc.connect((self.client_addr[0], self.secondary_port))\n\n # 2.\n self.recv_expect_line2(\"NEW_LINE\")\n\n # 3.\n self.send_line2(\"BOOYAH\")\n print(\"Second line established with client\")\n\n def host_game(self):\n \"\"\"\n Protocol:\n 1. server listens\n 2. client connects through tcp\n 3. server says READY\n 4. clients send the name of the player ( e.g: \"Fargus\" )\n 5. server says OK\n\n The server adds the clients connection to list of connections\n\n The client then waits for the game to start\n \"\"\"\n # 3. server says READY\n print('Sending ready')\n self.send('READY')\n\n # 4. clients send the name of the player ( e.g: \"Fargus\" )\n # TODO: Error handling/ input validation\n self.client_name = self.recv()\n\n print('Client name ', self.client_name)\n\n # 5. server says OK\n self.send('OK')\n\n # When the user running the server starts the game, we will move to start game\n\n def recv(self):\n try:\n msg = self.c.recv(self.packet_len).decode('utf-8')\n # removing non alphanumeric characters because java sends 2 wierd characters at the begginging of string\n msg = re.sub(r'\\W+', '', msg)\n except socket.timeout:\n self.disconnected = True\n print(\"Disconnecting\", self.client_name, \"timeout\")\n time.sleep(10)\n return msg\n\n def start_game(self):\n \"\"\"\n Protocol:\n For each client:\n 1. client listens for the START_GAME signal\n 2. client says OK\n 3. Server sends port for secondary line of communication\n 4. secondary line of communication established\n 5. Once each client has responded with OK\n 6. Server sends initial life total\n \"\"\"\n print('Starting START_GAME protocol for client %s' % self.client_name)\n # 1.\n self.send(\"START_GAME\")\n\n # 2.\n print('Sending Ok at START_GAME/2')\n self.recv_expect(\"OK\")\n\n # 3.\n print('Sending secondary port %s at START_GAME/3' % self.secondary_port)\n self.send(str(self.secondary_port))\n\n # 4.\n print('Establishing second line of communication at START_GAME/4')\n self.establish_secondary_communication()\n\n # 5/6 handled by parent function\n\n def life_update(self, game_info):\n \"\"\"\n Protocol:\n 1. client listens for life update\n 2. server says LIFE_UPDATE\n 3. client says OK\n 4. send each client each players life total in JSON\n - example:\n {\n \"Isaac\": 20,\n \"Liyani\": 4,\n \"Dylan\": 99\n }\n 5. each player responds with OK\n 6. client goes to step 1.\n \"\"\"\n # 2.\n self.send(\"LIFE_UPDATE\")\n\n # 3.\n self.recv_expect(\"OK\")\n\n # 4.\n self.send(game_info)\n\n # 5.\n self.recv_expect(\"OK\")\n\n def receive_life(self):\n \"\"\"\n Protocol:\n 1. listen for new life from client\n 2. client says NEW_LIFE\n 3. server says READY\n 4. client sends life as a positive integer\n 5. server sends new life to each player\n \"\"\"\n\n # 2.\n self.recv_expect_line2(\"NEW_LIFE\")\n\n # 3.\n self.send_line2(\"READY\")\n\n # 4.\n new_life = self.recv_line2()\n print(\"new life from %s: %s\" % (self.client_name, new_life))\n\n # 5.\n self.send_line2(\"OK\")\n\n self.new_life = new_life\n\n def send(self, msg):\n if self.disconnected:\n # we dont send things when we are disconnected\n print(\"NOT SENDING MSG BECAUSE DISCONNECTED\")\n time.sleep(10)\n self.c.send(msg.encode('utf-8'))\n\n def recv_expect(self, expected_msg):\n try:\n response = self.c.recv(self.packet_len).decode('utf-8')\n\n # removing non alphanumeric characters because java sends 2 wierd characters at the begginging of string\n response = re.sub(r'\\W+', '', response)\n\n except socket.timeout:\n self.disconnected = True\n print(\"Disconnecting\", self.client_name, \"timeout\")\n response = \"OH NOOOO\"\n\n if response != expected_msg:\n print('Error: Invalid response from client, expecting %s got %s' % (expected_msg, response))\n self.disconnected = True\n\n def send_line2(self, msg):\n if self.disconnected:\n # we dont send things when we are disconnected\n print(\"NOT SENDING MSG BECAUSE DISCONNECTED\")\n time.sleep(10)\n self.rec_life_soc.send(msg.encode('utf-8'))\n\n def recv_expect_line2(self, expected_msg):\n response = self.rec_life_soc.recv(self.packet_len).decode('utf-8')\n # removing non alphanumeric characters because java sends 2 wierd characters at the begginging of string\n response = re.sub(r'\\W+', '', response)\n if response != expected_msg:\n print('Error: Invalid response from client, expecting %s got %s' % (expected_msg, response))\n self.disconnected = True\n\n def recv_line2(self):\n response = self.rec_life_soc.recv(self.packet_len).decode('utf-8')\n\n # removing non alphanumeric characters because java sends 2 wierd characters at the begginging of string\n response = re.sub(r'\\W+', '', response)\n\n return response\n\n def stop(self):\n self.c.close()\n exit(0)\n\n def disconnect(self):\n x = input(\"Disconnect? [y/N]: \\m\")\n if x == \"y\":\n self.disconnected = True\n\n\nif __name__ == '__main__':\n # port should be 8989 by default\n soc = get_tcp_socket(port=int(sys.argv[1]))\n try:\n man = SockManager(soc, port=int(sys.argv[1]))\n man.run_server()\n finally:\n soc.close()\n\n","sub_path":"PyClientServer/NSAServer.py","file_name":"NSAServer.py","file_ext":"py","file_size_in_byte":14379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"274802655","text":"from __future__ import absolute_import, print_function, unicode_literals\n\nfrom collections import Counter\n\nimport sys\nimport psycopg2\nfrom psycopg2.extensions import *\n\n# connect to tcount DB\nconn = psycopg2.connect(database=\"tcount\", user=\"postgres\", password=\"pass\", host=\"localhost\", port=\"5432\")\ncur = conn.cursor()\n\n# if no args provided, return all tweeted words and counts\nif len(sys.argv) == 1:\n selectStr = cur.mogrify(\"SELECT word, count FROM tweetwordcount ORDER BY count desc\")\n cur.execute(selectStr)\n result = cur.fetchall()\n\n if result is None:\n print(\"Tweetwordcount is empty.\")\n else:\n print(result)\n# else, look for word in table and return its count (or 0 if not in table)\nelif len(sys.argv) == 2:\n word = sys.argv[1]\n selectStr = cur.mogrify(\"SELECT word, count FROM tweetwordcount WHERE word=%s\", (word,))\n cur.execute(selectStr)\n result = cur.fetchone()\n count = 0 if result is None else result[1]\n\n print(\"Total number of occurences of '%s': %d\" % (word, count))\nelse:\n print(\"Please enter one word at a time.\")\n\nconn.close()\n\n \n","sub_path":"scripts/finalresults.py","file_name":"finalresults.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237434979","text":"\"\"\"\nGiven a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.\n\nNote: A leaf is a node with no children.\nExample:\nGiven the below binary tree and sum = 22,\n 5\n / \\\n 4 8\n / / \\\n 11 13 4\n / \\ \\\n7 2 1\n\nreturn true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.\n\"\"\"\n\nfrom utils.tree import TreeNode, list_create_tree_v2, delete_empty_subtree\n\n\"\"\"\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n # 52ms\n if not root:\n return False\n return self.helper(root, 0, sum)\n\n def helper(self, root, path_sum, sum):\n if root:\n if not root.left and not root.right:\n if path_sum + root.val == sum:\n return True\n else:\n return False\n return self.helper(root.left, path_sum + root.val, sum) or self.helper(root.right, path_sum + root.val, sum)\n\"\"\"\n\n\"\"\"\nclass Solution:\n # DFS with stack 52 ms\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n stack = [(root, 0)]\n while stack:\n node, path_sum = stack.pop()\n if node:\n if not node.left and not node.right and path_sum + node.val == sum:\n return True\n if node.left:\n stack.append((node.left, path_sum + node.val))\n if node.right:\n stack.append((node.right, path_sum + node.val))\n return False\n\"\"\"\n\nfrom collections import deque\n\"\"\"\nclass Solution:\n # BFS with queue 52ms\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if not root:\n return False\n q = deque([(root, 0)])\n while q:\n node, path_sum = q.popleft()\n if not node.left and not node.right and path_sum + node.val == sum:\n return True\n if node.left:\n q.append((node.left, path_sum + node.val))\n if node.right:\n q.append((node.right, path_sum + node.val))\n return False\n\"\"\"\n\nclass Solution:\n def hasPathSum(self, root: TreeNode, sum: int) -> bool:\n # 56ms from https://leetcode.com/problems/path-sum/discuss/36378/AcceptedMy-recursive-solution-in-Java\n if not root:\n return False\n if not root.left and not root.right and sum - root.val == 0:\n return True\n return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)\n\n\nif __name__ == '__main__':\n s = Solution()\n root = TreeNode(None)\n llist = [5,4,8,11,None,13,4,7,2,None,None,None,None,None,1]\n root = list_create_tree_v2(root, llist)\n delete_empty_subtree(root)\n print(s.hasPathSum(root, 22))\n\n root = TreeNode(None)\n llist = [1]\n root = list_create_tree_v2(root, llist)\n delete_empty_subtree(root)\n print(s.hasPathSum(root, 1))\n\n\n","sub_path":"python/problems/0112.PathSum.py","file_name":"0112.PathSum.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"183030005","text":"from network_manage_tool import *\n\nfrom rich.prompt import Prompt\nfrom rich import style\nfrom rich.console import Console\n\nconsole = Console()\n\ndef main():\n console.print('\\t\\t$*&*&*&*&*&*&*&*&network management tool project*&*&*&*&*&*&*&*&*&*$',style='bold #CAEF74')\n console.print('1. Assign IP address',style='bold green')\n console.print('2. Delete IP address',style='bold red')\n console.print('3. Display IP address',style='bold green')\n console.print('4. Display all interfaces',style='bold red')\n console.print('5. Configure routing',style='bold green')\n console.print('6. Turn Off interface',style='bold red')\n console.print('7. Turn on interface',style='bold green')\n console.print('8. Add ARP entry ',style='bold red')\n console.print('9. Delete ARP Entry',style='bold green')\n console.print('10.Restart Network',style='bold red')\n console.print('11.Change hostname',style='bold green')\n console.print('12.Add DNS server entry',style='bold red')\n\n\nwhile True:\n main()\n ch =int(input('Enter your choice:'))\n if ch ==1:\n assign_ip_add()\n elif ch==2:\n delete_ip_add()\n elif ch==3:\n display_ip_add()\n elif ch ==4 :\n display_all_interfaces()\n elif ch ==5:\n configure_routing()\n elif ch ==6:\n turn_off_interface()\n elif ch ==7:\n turn_on_interface()\n elif ch ==8:\n add_ARP_entry()\n elif ch ==9:\n delete_arp_entry()\n elif ch ==10:\n Restart_network()\n elif ch ==11:\n Change_hostname()\n elif ch ==12:\n add_dns_server()\n elif ch == 13:\n console.print(f'----------------------------Exit-----------------',style='bold italic red')\n break\n else:\n console.print('wrong choce! Please enter valiad number',style='bold #CAEF74')\n","sub_path":"net_manage_tool_main.py","file_name":"net_manage_tool_main.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"606778070","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom pandocfilters import toJSONFilter, Header, Para, CodeBlock, RawInline, RawBlock, stringify, get_caption\n\nis_in_block = None\n\ndef inlatex(s):\n\treturn RawInline('latex', s)\n\ndef pandocfilter(key, value, fmt, meta):\n\tglobal is_in_block\n\tif key == 'Header':\n\t\tret = list()\n\t\tif is_in_block is not None:\n\t\t\tret.append(Para([inlatex(\"\\\\end{%s}\" % is_in_block)]))\n\t\t\tis_in_block = None\n\t\t[level, classes, contents_list] = value\n\t\t[label, class_names, class_options] = classes\n\t\tif level == 3:\n\t\t\tblocktype = ''\n\t\t\tblocktitle = ''\n\t\t\tfor cname in class_names:\n\t\t\t\tif cname in ['block', 'alertblock', 'exampleblock', 'theorem', 'example', 'definition', 'proof']:\n\t\t\t\t\tblocktype = cname\n\t\t\t\t\tblocktitle = stringify(contents_list)\n\t\t\tif blocktype != '':\n\t\t\t\tis_in_block = blocktype\n\t\t\t\tlatexstr = \"\\\\begin{%s}\" % blocktype\n\t\t\t\tif blocktitle != '':\n\t\t\t\t\tlatexstr += \"[%s]\" % blocktitle\n\t\t\t\tif label != '':\n\t\t\t\t\tlatexstr += \" \\\\label{%s}\" % label\n\t\t\t\tret.append(Para([inlatex(latexstr)]))\n\t\t\telse:\n\t\t\t\tret.append(Header(3, classes, contents_list))\n\t\telse:\n\t\t\tret.append(Header(level, classes, contents_list))\n\t\treturn ret\n\telif key == 'CodeBlock':\n\t\tret = list()\n\t\tif is_in_block is not None:\n\t\t\tret.append(Para([inlatex(\"\\\\end{%s}\" % is_in_block)]))\n\t\t\tis_in_block = None\n\t\t[classes, contents_list] = value\n\t\t[label, class_names, class_options] = classes\n\t\tcaption, _, _ = get_caption(class_options)\n\t\tcaption = stringify(caption)\n\t\tif caption == '':\n\t\t\tret.append(Para([inlatex(\"\\\\begin{codeblock}\")]))\n\t\telse:\n\t\t\tret.append(Para([inlatex(\"\\\\begin{codeblock}[%s]\" % caption)]))\n\t\tret.append(CodeBlock(classes, contents_list))\n\t\tret.append(Para([inlatex(\"\\\\end{codeblock}\")]))\n\t\treturn ret\n\telif key == 'RawBlock':\n\t\t[rawtype, contents] = value\n\t\tif contents.startswith(' 1+1 = 2, 3 would be (1, 10, 11) 1+1+2 = 4\n# int has 4 bytes, or 16 or 32 bit\n# set bit is a 1\n# how convert int to binary?\n# bin()\n\n\n","sub_path":"Py/int.py","file_name":"int.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"645220872","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom bom1 import *\nimport pandas as pd\nimport numpy as np\n\ndef test_load_scripts():\n '''\n This should be able to catch most errors in all of the lecture clipping csvs.\n '''\n clips = load_clips()\n columns = clips.columns\n \n expected_columns = ['tag', 'nclip', 'name', 't1', 't2', 'rating', 'stream_title', 'link', 'duration']\n \n for expected_column in expected_columns:\n assert expected_column in columns, f'Column {expected_column} was expected but not found in dataframe returned from load_clips().' \n \n for column in columns:\n assert column in expected_columns, f'Column {column} was returned by load_clips() but was unexpected.'\n \n return\n \ndef test_metadata():\n '''\n This catches errors in the metadata csv file.\n '''\n df = pd.isna(pd.read_csv('./csv/metadata.csv'))\n assert ~np.any(df), 'metadata should be filled in. Use the fill_metadata() function!'\n assert np.all(df.columns == ['tag', 'stream_title', 'link'])\n return","sub_path":"bom1_unittest.py","file_name":"bom1_unittest.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430741181","text":"import click\nimport datetime\nimport os\nimport time\nfrom multiprocessing import cpu_count\nfrom subprocess import Popen, PIPE, check_call, call\nimport sys\n# proj_path = os.path.dirname(__file__)\n# sys.path.append(proj_path)\n# click.echo(proj_path, err=True)\n# click.echo(os.environ['PATH'], err=True)\nimport find_pairs\nimport cluster\nimport input_stream_alignments\nimport data_io\n\ncpu_range = click.IntRange(min=1, max=cpu_count())\n\ndefaults = {\n \"clip_length\": 21.,\n \"mapper\": \"bwamem\",\n \"map_script\": None,\n \"procs\": 1,\n \"dest\": None,\n \"post_fix\": \"fnfi\",\n \"search\": None,\n \"exclude\": None,\n \"include\": None,\n \"paired\": \"True\",\n \"insert_median\": 210.,\n \"insert_stdev\": 175.,\n \"read_length\": 125.,\n \"max_insertion\": 100.,\n \"min_aln\": 17.,\n \"max_overlap\": 100.,\n \"ins_cost\": 1.,\n \"ol_cost\": 3.,\n \"inter_cost\": 2.,\n \"u\": 9.,\n \"match_score\": 1.,\n \"bias\": 1.15,\n \"output\": \"-\",\n \"outsam\": \"-\",\n \"fq1\": None,\n \"fq2\": None\n }\n\nalign_args = {}\n\n\ndef pipeline(kwargs):\n t0 = time.time()\n click.echo(\"Running fnfi pipeline\", err=True)\n click.echo(kwargs, err=True)\n if kwargs[\"bam\"] is None:\n raise IOError(\"Error: Input bam is None\")\n\n if not os.path.exists(kwargs[\"bam\"] + \".bai\"):\n raise IOError(\"Input .bai index file not found.\")\n\n data_io.mk_dest(kwargs[\"dest\"])\n\n other_kwargs = find_pairs.process(kwargs)\n kwargs.update(other_kwargs)\n\n single = True if kwargs[\"procs\"] == 1 else False\n\n process, used_procs, remaining_procs = launch_external_mapper(kwargs)\n kwargs[\"procs\"] = remaining_procs\n\n if kwargs[\"mapper\"] == \"bwamem\" and kwargs[\"map_script\"] is None:\n kwargs[\"fq1\"] = None\n kwargs[\"fq2\"] = None\n else:\n kwargs[\"fq1\"] = kwargs[\"out_pfix\"] + \"1.fq\"\n kwargs[\"fq2\"] = kwargs[\"out_pfix\"] + \"2.fq\"\n\n kwargs[\"sam\"] = process.stdout\n kwargs[\"output\"] = kwargs[\"out_pfix\"] + \".sam\"\n\n input_stream_alignments.process_reads(kwargs)\n process.kill()\n sort_and_index(kwargs)\n\n # Clean up\n if kwargs[\"fq1\"] is not None:\n os.remove(kwargs[\"fq1\"])\n os.remove(kwargs[\"fq2\"])\n\n if kwargs[\"mapper\"] == \"last\":\n os.remove(kwargs[\"out_pfix\"] + \".dict\")\n\n if not single:\n kwargs[\"procs\"] = remaining_procs + used_procs\n\n kwargs[\"sv_bam\"] = kwargs[\"out_pfix\"] + \".srt.bam\"\n kwargs[\"raw_bam\"] = kwargs[\"bam\"]\n\n cluster.cluster_reads(kwargs)\n\n click.echo(\"fnfi run completed in {} h:m:s\\n\".format(str(datetime.timedelta(seconds=int(time.time() - t0)))),\n err=True)\n\n\ndef launch_external_mapper(kwargs):\n \"\"\"Run a shell script to map interleaved .fastq files to .sam format. Uses a basic bwa-mem by default.\n A custom shell script can be provided but must take positional arguments as:\n $1 reference genome\n $2 .fastq file; interleaved if paired-end, otherwise single end reads\"\"\"\n\n if kwargs[\"procs\"] > 1:\n p = int(kwargs[\"procs\"] / 2)\n other_p = kwargs[\"procs\"] - p\n else:\n p = kwargs[\"procs\"]\n other_p = 1\n\n if not kwargs[\"map_script\"] and kwargs[\"mapper\"] == \"bwamem\":\n command = \"bwa mem -c 2000 -Y -t {procs} -P -a {ref} {s}1.fq {s}2.fq\".format(procs=p,\n ref=kwargs[\"reference\"],\n s=kwargs[\"fastq\"])\n\n elif not kwargs[\"map_script\"] and kwargs[\"mapper\"] == \"last\":\n # Todo need to exract the sam header from input file, and use this as the dict argument in maf-convert\n command = \"fastq-interleave {s}1.fq {s}2.fq \\\n | lastal -k2 -l11 -Q1 -D10000 -K8 -C8 -i10M -r1 -q4 -a6 -b1 -P{procs} {ref} \\\n | last-map-probs -m 1 -s 1 | maf-convert -f {d}.dict sam\".format(procs=p,\n ref=kwargs[\"reference\"],\n d=kwargs[\"out_pfix\"],\n s=kwargs[\"fastq\"])\n\n else:\n command = \"bash {script} {ref} {s}1.fq {s}2.fq {procs}\".format(script=kwargs[\"map_script\"],\n procs=p,\n ref=kwargs[\"reference\"],\n s=kwargs[\"fastq\"])\n\n click.echo(\"Mapping command:\\n\" + command, err=True)\n proc = Popen(command, stdout=PIPE, shell=True)\n\n return proc, p, other_p\n\n\ndef sort_and_index(kwargs):\n \"\"\"Convenience function to sort and index a sam file, then remove the input sam file\"\"\"\n c = \"samtools view -uh {fix}.sam | samtools sort -@ {p} -o {fix}.srt.bam - ; samtools index -@ {p} {fix}.srt.bam\"\n c = c.format(fix=kwargs[\"out_pfix\"], p=kwargs[\"procs\"])\n click.echo(c, err=True)\n check_call(c, shell=True)\n os.remove(kwargs[\"outsam\"])\n\n\n# Interface:\n# ----------------------------------------------------------------------------------------------------------------------\ndef apply_ctx(ctx, kwargs):\n ctx.ensure_object(dict)\n if len(ctx.obj) == 0: # When run is invoked from cmd line, else run was invoked from test function\n for k, v in defaults.items() + kwargs.items():\n ctx.obj[k] = v\n return ctx\n\n\n@click.group(chain=False, invoke_without_command=False)\ndef cli():\n \"\"\"Fusion-finder calls structural variants from input .bam or .fastq files.\"\"\"\n pass\n\n\n@cli.command(\"run\")\n@click.argument('reference', required=True, type=click.Path(exists=False))\n@click.argument(\"bam\", required=True, type=click.Path(exists=True))\n@click.option('--include', help=\".bed file, limit calls to regions\", default=None, type=click.Path(exists=True))\n@click.option('--search', help=\".bed file, limit search to regions\", default=None, type=click.Path(exists=True))\n@click.option('--exclude', help=\".bed file, do not search/call SVs within regions. Overrides include/search\",\n default=None, type=click.Path(exists=True))\n@click.option('--clip-length', help=\"Minimum soft-clip length; >= threshold are kept\", default=defaults[\"clip_length\"], type=int,\n show_default=True)\n@click.option('--mapper', help=\"External mapper to use for re-alignment\", default=defaults[\"mapper\"],\n type=click.Choice(['bwamem', 'last']), show_default=True)\n@click.option('--map-script', help=\"\"\"External shell script for mappping fastq files. \\\nOverrides --mapper argument. Script must take positional arguments as: $1 reference genome; \\\n$2 read1.fastq file $3 read2.fastq if paired-end \\\n$4 threads to use\"\"\", default=None, type=click.Path(exists=True))\n@click.option(\"-p\", \"--procs\", help=\"Processors to use\", type=cpu_range, default=1, show_default=True)\n@click.option('--dest', help=\"Destination folder to use/create for saving results. Defaults to directory of input bam\",\n default=None, type=click.Path())\n@click.pass_context\ndef run_command(ctx, **kwargs):\n \"\"\"Run the fusion-finder pipeline.\"\"\"\n ctx = apply_ctx(ctx, kwargs)\n pipeline(ctx.obj)\n\n\n@cli.command(\"find-reads\")\n@click.argument('bam', required=True, type=click.Path(exists=True))\n@click.option('--post-fix', help=\"Post fix to tag temp files with. Default is to use 'fnfi'\", default='fnfi', type=str)\n@click.option('--clip-length', help=\"Minimum soft-clip length; >= threshold are kept\", default=defaults[\"clip_length\"], type=int,\n show_default=True)\n@click.option(\"-p\", \"--procs\", help=\"Processors to use\", type=cpu_range, default=defaults[\"procs\"], show_default=True)\n@click.option('--search', help=\".bed file, limit search to regions.\", default=None, type=click.Path(exists=True))\n@click.option('--exclude', help=\".bed file, do not search/call SVs within regions. Overrides include/search\",\n default=None, type=click.Path(exists=True))\n@click.option('--dest', help=\"Destination folder to use/create for saving results. Defaults to directory of input bam\",\n default=None, type=click.Path())\n@click.pass_context\ndef find_reads(ctx, **kwargs):\n \"\"\"Filters input .bam for read-pairs that are discordant or have a soft-clip of length >= '--clip-length'\"\"\"\n # insert_median, insert_stdev, read_length, out_name\n ctx = apply_ctx(ctx, kwargs)\n return find_pairs.process(ctx.obj)\n\n\n@cli.command(\"align\")\n@click.argument(\"sam\", type=click.File('r'), required=True)\n@click.argument(\"output\", required=False, type=click.Path())\n@click.option(\"--paired\", help=\"Paired end reads or single\", default=defaults[\"paired\"],\n type=click.Choice([\"True\", \"False\"]), show_default=True)\n@click.option(\"--insert-median\", help=\"Template insert size\", default=defaults[\"insert_median\"], type=float, show_default=True)\n@click.option(\"--insert-stdev\", help=\"Template standard-deviation\", default=defaults[\"insert_stdev\"], type=float, show_default=True)\n@click.option(\"--read-length\", help=\"Length of a read in base-pairs\", default=defaults[\"read_length\"], type=float, show_default=True)\n@click.option(\"--fq1\", help=\"Fastq reads 1, used to add soft-clips to all hard-clipped read 1 alignments\",\n default=defaults[\"fq1\"], type=click.Path())\n@click.option(\"--fq2\", help=\"Fastq reads 2, used to add soft-clips to all hard-clipped read 2 alignments\",\n default=defaults[\"fq2\"], type=click.Path())\n@click.option(\"--max_insertion\", help=\"Maximum insertion within read\", default=defaults[\"max_insertion\"], type=float, show_default=True)\n@click.option(\"--min-aln\", help=\"Minimum alignment length\", default=defaults[\"min_aln\"], type=float, show_default=True)\n@click.option(\"--max-overlap\", help=\"Maximum overlap between successive alignments\", default=defaults[\"max_overlap\"], type=float, show_default=True)\n@click.option(\"--ins-cost\", help=\"Insertion cost\", default=defaults[\"ins_cost\"], type=float, show_default=True)\n@click.option(\"--ol-cost\", help=\"Overlapping alignment cost\", default=defaults[\"ol_cost\"], type=float)\n@click.option(\"--inter-cost\", help=\"Cost of inter-chromosomal jump\", default=defaults[\"inter_cost\"], type=float, show_default=True)\n@click.option(\"--u\", help=\"Pairing heuristic cost\", default=defaults[\"u\"], type=float, show_default=True)\n@click.option(\"--match-score\", help=\"Matched base score used for input sam reads\", default=defaults[\"match_score\"], type=float, show_default=True)\n@click.option(\"-p\", \"--procs\", help=\"Processors to use\", type=cpu_range, default=1, show_default=True)\n@click.option('--include', help=\".bed file, elevate alignment scores in these regions. Determined by '--bias'\",\n default=None, type=click.Path(exists=True))\n@click.option(\"--bias\", help=\"\"\"Multiply match score by bias if alignment falls within regions .bed file.\nUnused if .bed not provided.\"\"\", default=defaults[\"bias\"], type=float)\n@click.pass_context\ndef fnfi_aligner(ctx, **kwargs):\n \"\"\"Choose an optimal set of alignments from from a collection of candidate alignments.\n If reads are paired, alignments must be sorted by read-name while the bit flag\n designates read 1 vs read 2.\"\"\"\n ctx = apply_ctx(ctx, kwargs)\n input_stream_alignments.process_reads(ctx.obj)\n\n\n@cli.command(\"call-events\")\n@click.argument('raw-bam', required=True, type=click.Path(exists=True))\n@click.argument('sv-bam', required=True, type=click.Path(exists=True))\n@click.argument(\"output\", required=False, type=click.Path())\n@click.option('--clip-length', help=\"Minimum soft-clip length; >= threshold are kept.\", default=defaults[\"clip_length\"], type=int,\n show_default=True)\n@click.option(\"--insert-median\", help=\"Template insert size\", default=defaults[\"insert_median\"], type=float)\n@click.option(\"--insert-stdev\", help=\"Template standard-deviation\", default=defaults[\"insert_stdev\"], type=float)\n@click.option(\"--read-length\", help=\"Length of a read in base-pairs\", default=defaults[\"read_length\"], type=float)\n@click.option('--verbose', type=click.Choice([\"True\", \"False\"]), default=\"True\", help=\"If set to 'True' output is directed to a folder with the same name as the input file. Otherwise a .vcf file is generated.\")\n@click.option(\"-p\", \"--procs\", help=\"Processors to use\", type=cpu_range, default=defaults[\"procs\"], show_default=True)\n@click.option('--include', help=\".bed file, limit calls to regions.\", default=None, type=click.Path(exists=True))\n@click.option('--dest', help=\"Folder to use/create for saving results. Defaults to directory of input bam directory\",\n default=None, type=click.Path())\n@click.pass_context\ndef call_events(ctx, **kwargs):\n \"\"\"Clusters reads into SV-events. Takes as input the original .bam file, and a .bam file with only sv-like reads.\"\"\"\n # Create dest in not done so already\n ctx = apply_ctx(ctx, kwargs)\n cluster.cluster_reads(ctx.obj)\n\n\n@cli.command(\"run-tests\", context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))\n@click.option('--dest', required=True, help=\"Folder to use/create for saving results.\",\n default=None, type=click.Path())\n@click.option('--reference', required=True, type=click.Path(), help=\"Path to reference for mapper to use\")\n@click.pass_context\ndef test_run_command(ctx, **kwargs):\n \"\"\"Runs fnfi commands on test data using default options.\n fnfi defaults for the run command can be modified by adding the respective option, e.g. add --procs 4\"\"\"\n\n def update_ctx(kwargs, ctx):\n for k, v in defaults.items() + kwargs.items() + {ctx.args[i][2:]: ctx.args[i + 1] for i in\n xrange(0, len(ctx.args), 2)}.items():\n if isinstance(v, str):\n if v.isdigit():\n if int(v) == float(v):\n v = int(v)\n else:\n v = float(v)\n ctx.obj[k] = v\n\n ctx.ensure_object(dict)\n\n data_io.mk_dest(kwargs[\"dest\"])\n tests_path = os.path.dirname(__file__) + \"/tests\"\n click.echo(\"Input data for tests: {}\".format(tests_path), err=True)\n\n # Test aligner using single reads\n f1 = \"{}/long_contigs.fa\".format(tests_path)\n success = False\n try:\n com = \"lastal -D1000 -K3 -C3 -r1 -q4 -a6 -b1 -P1 {ref} {f} \\\n | maf-convert -f {tp}/hg38.dict sam > {dest}/long_contigs.last.sam\".format(tp=tests_path, f=f1,\n ref=kwargs[\"reference\"],\n dest=kwargs[\"dest\"],\n )\n call(com, shell=True)\n success = True\n\n except OSError as e:\n click.echo(\"Skipping align test using longer contigs\", err=True)\n if e.errno == os.errno.ENOENT:\n click.echo(\"No such file or directory\", err=True)\n else:\n raise SystemError(\"Something went wrong\")\n if success:\n sam = \"{dest}/long_contigs.last.sam\".format(dest=kwargs[\"dest\"])\n output = \"{dest}/long_contigs.fnfi.sam\".format(dest=kwargs[\"dest\"])\n\n update_ctx(kwargs, ctx)\n\n call(\"fnfi align --paired False {sam} > {o}\".format(sam=sam, o=output), shell=True)\n\n\n quit()\n\n # Test run command using paired-end data\n b1 = \"{}/bwa.0.5.srt.bam\".format(tests_path)\n\n click.echo(b1)\n inc = \"{}/include_tels.bed\".format(tests_path)\n\n kwargs[\"bam\"] = b1\n kwargs[\"include\"] = inc\n\n update_ctx(kwargs, ctx)\n click.echo(ctx.obj)\n ctx.invoke(run_command)\n\n\nif __name__ == \"__main__\":\n print(\"Done\")\n pass\n","sub_path":"fnfi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"1233747","text":"import pytest\nimport os\nimport jsonschema\nimport collections\nfrom pyidmatcher.config import Config\n\nColumn = collections.namedtuple('Column', ['master', 'source', 'weight', 'function'])\n\n\ndef test_read_config_file(make_config_file):\n # path to file should be absolute\n expected_master_connection = {\n \"file\": os.path.join(make_config_file, \"products.txt\"),\n \"encoding\": \"latin_1\"\n }\n\n expected_source_connection = {\n \"file\": os.path.join(make_config_file, \"listings.txt\"),\n \"encoding\": \"utf-8\"\n }\n\n expected_master_id = \"product_name\"\n\n expected_matcher_columns = [\n Column(source=\"title\", master=\"product_name\", weight=1, function=None),\n Column(source=\"manufacturer\", master=\"manufacturer\", weight=1, function=None)\n ]\n\n expected_output_connection = {\n \"file\": os.path.join(make_config_file, \"matched.txt\"),\n \"encoding\": \"utf-8\"\n }\n\n expected_keep_orphans = True\n\n expected_schema_tabular = [\n (\"product_name\", \"master\"),\n (\"title\", \"source\"),\n (\"currency\", \"source\")\n ]\n\n expected_schema_grouped = {\n \"master_columns\": [\"product_name\"],\n \"source_label\": \"listings\",\n \"source_columns\": [\"title\", \"manufacturer\", \"currency\", \"price\"]\n }\n\n valid_tabular_output_path = os.path.join(make_config_file, 'config_tabular_output.txt')\n valid_grouped_output_path = os.path.join(make_config_file, 'config_grouped_output.txt')\n\n actual_tabular = Config(valid_tabular_output_path)\n assert expected_master_connection == actual_tabular.connections[\"master\"]\n assert expected_source_connection == actual_tabular.connections[\"source\"]\n assert expected_master_id == actual_tabular.master_id\n assert expected_matcher_columns == actual_tabular.matcher_columns\n assert expected_keep_orphans == actual_tabular.keep_orphans\n assert expected_output_connection == actual_tabular.connections[\"output\"]\n assert expected_schema_tabular == actual_tabular.schema_tabular\n\n actual_grouped = Config(valid_grouped_output_path)\n assert expected_schema_grouped == actual_grouped.schema_grouped\n\n config_invalid_nocolumn_path = os.path.join(make_config_file, 'config_invalid_nocolumn.txt')\n with pytest.raises(jsonschema.ValidationError):\n Config(config_invalid_nocolumn_path)\n\n config_invalid_encoding_path = os.path.join(make_config_file, 'config_invalid_encoding.txt')\n with pytest.raises(jsonschema.ValidationError):\n Config(config_invalid_encoding_path)\n\n config_invalid_weight_path = os.path.join(make_config_file, 'config_invalid_weight.txt')\n with pytest.raises(jsonschema.ValidationError):\n Config(config_invalid_weight_path)\n","sub_path":"tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"214087616","text":"from selenium import webdriver\n\noptions = webdriver.ChromeOptions()\noptions.headless = True\nbrowser = webdriver.Chrome(executable_path=\"path/chromedriver\",\n chrome_options=options, \n service_log_path=\"/tmp/selenium_browser.log\")\n\nbrowser.close()\n\n# =========================================\n# BROWSER\n\nbrowser.name\nbrowser.title\nbrowser.current_url\nbrowser.current_window_handle\nhandles_list=browser.window_handles # list of open windows\nbrowser.page_source\n\nbrowser.maximize_window()\nbrowser.minimize_window()\nbrowser.back()\nbrowser.forward()\nbrowser.refresh()\n\nbrowser.switch_to.active_element\nbrowser.switch_to.window(\"window_name\")\nbrowser.switch_to.frame(1) #You can switch to frame using Name, ID, Index & WebElement\n\n# It’s possible to access subframes by separating the path with a dot, and you can specify the frame by its index too. That is:\nbrowser.switch_to_frame(\"frameName.0.child\")\nbrowser.switch_to.parent_frame()\n# Once we are done with working on frames, we will have to come back to the parent frame which can be done using:\nbrowser.switch_to.default_content()\n\n# Execute JavaScript (scroll to the bottom of a page)\nbrowser.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n# Screenshot of the current window\nbrowser.save_screenshot('screenshot.png')\n\n\n# =========================================\n# COOKIES\n\ncookies_list = browser.get_cookies()\ncookie_value = browser.get_cookie(\"my_cookie\")\nbrowser.delete_cookie(\"my_cookie\")\nbrowser.delete_all_cookies()\nbrowser.add_cookie({\"name:value\"})\n\n\n# =========================================\n# ELEMENTS\n\n# Locating element(s)\n# http://selenium-python.readthedocs.org/locating-elements.html\nelement = browser.find_element_by_id(\"txt_1\")\nelements_list = browser.find_elements_by_id(\"txt_1\")\nbrowser.find_elements_by_xpath(\"//input\")\nbrowser.find_elements_by_link_text(\"Products\")\nbrowser.find_elements_by_partial_link_text('Sign')\nbrowser.find_elements_by_name('foo')\nbrowser.find_elements_by_tag_name('Input')\nbrowser.find_elements_by_class_name('breadcrumb')\nbrowser.find_elements_by_css_selector('input[name=\"txt\"]')\n\n# Elements\nelement.clear() # clear any text with input field\nelement.send_keys(\"pycon\") # Simulates typing into the element.\nelement.send_keys(Keys.RETURN)\nelement.send_keys(\" and some\", Keys.ARROW_DOWN)\n\nelement.get_attribute('innerHTML')\ntext_length = element.get_property(\"text_length\")\nelement.text\nelement.source\nelement.location\nelement.location_once_scrolled_into_view # USE WITH CAUTION\nelement.rect\nelement.size\nelement.tag_name\n\nelement.is_displayed() # Whether the element is visible to a user.\nelement.is_enabled() # Returns whether the element is enabled.\nelement.is_selected() # Returns whether the element (e.g. checkbox/radio button) is selected.\nelement.screenshot(filename) # Saves a screenshot of the current element to a PNG image file. Returns False if there\n # is any IOError, else returns True. Use full paths in your filename.\n\n\n# =========================================\n# USER INTERACTIONS\n# ActionChains are a way to automate low level interactions such as mouse movements, mouse button actions,\n# key press, and context menu interactions. This is useful for doing more complex actions like hover over and\n# drag and drop.\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nmenu = browser.find_element_by_css_selector(\".nav\")\nhidden_submenu = browser.find_element_by_css_selector(\".nav #submenu1\")\n\nactions = ActionChains(browser)\nactions.move_to_element(menu)\nactions.click(hidden_submenu)\nactions.perform()\nactions.click(on_element=None) # Clicks an element (or current mouse position if on_element=None).\nactions.click_and_hold(on_element=None) # Holds down the left mouse button on an element.\nactions.context_click(on_element=None) # Performs a context-click (right click) on an element.\nactions.double_click(on_element=None)\nactions.drag_and_drop(source, target) # Holds down the left mouse button on the source element,\n # then moves to the target element and releases the mouse button.\nactions.drag_and_drop_by_offset(source, xoffset, yoffset) # Holds down the left mouse button on the source element,\n # then moves to the target offset and releases the mouse button.\nactions.key_down(value, element=None) # Sends a key press only, without releasing it. Should only be used with modifier keys (Control, Alt and Shift).\nactions.key_up(value, element=None) # Releases a modifier key.\n# E.g. ActionChains(browser).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()\nactions.move_by_offset(xoffset, yoffset) # Moving the mouse to an offset from current mouse position.\nactions.move_to_element(to_element) # Moving the mouse to the middle of an element.\nactions.move_to_element_with_offset(to_element, xoffset, yoffset) # Move the mouse by an offset of the specified\n # element (relative to the top-left corner of the\n # element)\nactions.pause(seconds) # Pause all inputs for the specified duration in seconds\nactions.release(on_element=None) # Releasing a held mouse button on an element.\nactions.reset_actions() # Clears actions that are already stored on the remote end.\nactions.send_keys(*keys_to_send) # Sends keys to current focused element.\nactions.send_keys_to_element(element, *keys_to_send)\nactions.submit() # Submits a form. (alternatively find...().click()); works on any element within a form\nactions.perform() # Performs all stored actions.\n\n\n# =========================================\n# ALERTS\nfrom selenium.webdriver.common.alert import Alert\n\nbrowser.switch_to.alert() # Access alert after you’ve triggered action that would open a popup\n\nalert = Alert(browser)\nalert.accept() # Confirm an alert dialog\nalert.send_keys(\"Hello\")\nalert.text\nalert.dismiss()\n\n\n# =========================================\n# TOUCH ACTIONS\nfrom selenium.webdriver.common.touch_actions import TouchActions\n\ntouch_actions = TouchActions(browser)\n\ntouch_actions.double_tap(on_element) # Double taps on a given element.\ntouch_actions.flick(xspeed, yspeed) # Flicks, starting anywhere on the screen. (The X/Y speed in pixels per second)\ntouch_actions.flick_element(on_element, xoffset, yoffset, speed) # Flick starting at on_element, and moving by the x\n # offset and yoffset with specified speed.\ntouch_actions.long_press(on_element)\ntouch_actions.move(xcoord, ycoord)\ntouch_actions.perform() # Performs all stored actions.\ntouch_actions.release(xcoord, ycoord) # Release previously issued tap ‘and hold’ command at specified location.\ntouch_actions.scroll(xoffset, yoffset) # Touch and scroll, moving by xoffset and yoffset.\ntouch_actions.scroll_from_element(on_element, xoffset, yoffset) # Touch and scroll starting at on_element, moving by xoffset and yoffset.\ntouch_actions.tap(on_element) # Taps on a given element.\ntouch_actions.tap_and_hold(xcoord, ycoord)\n\n\n# =========================================\n# WAITS\nfrom selenium.webdriver.support.wait import WebDriverWait\n###########################\n# explicit wait\n############################\nfrom selenium.webdriver.support import expected_conditions as EC\n\nwait = WebDriverWait(browser, timeout=10)\nwait.until(expected_conditions, message='') # Calls the method provided with the browser as an argument until the return value is not False.\nwait.until_not(expected_conditions, message='') # Calls the method provided with the browser as an argument until the return value is False.\n\n# E.g.\nelement = wait.until(EC.presence_of_element_located((By.ID, 'someid')))\n\n# Expected Conditions\nEC.title_is\nEC.title_contains\nEC.presence_of_element_located\nEC.visibility_of_element_located\nEC.visibility_of\nEC.presence_of_all_elements_located\nEC.text_to_be_present_in_element\nEC.text_to_be_present_in_element_value\nEC.frame_to_be_available_and_switch_to_it\nEC.invisibility_of_element_located\nEC.element_to_be_clickable\nEC.staleness_of\nEC.element_to_be_selected\nEC.element_located_to_be_selected\nEC.element_selection_state_to_be\nEC.element_located_selection_state_to_be\nEC.alert_is_present\n# create a custom EC: http://selenium-python.readthedocs.io/waits.html#explicit-waits\n\n############################\n# implicit wait\n##########################\nfrom selenium import webdriver\n\nbrowser = webdriver.Firefox()\nbrowser.implicitly_wait(10) # seconds\nbrowser.get(\"http://somedomain/url_that_delays_loading\")\nmyDynamicElement = browser.find_element_by_id(\"myDynamicElement\")\n\n\n# =========================================\n# KEYS CODES\nfrom selenium.webdriver.common.keys import Keys\n\nADD = u'\\ue025'\nALT = u'\\ue00a'\nARROW_DOWN = u'\\ue015'\nARROW_LEFT = u'\\ue012'\nARROW_RIGHT = u'\\ue014'\nARROW_UP = u'\\ue013'\nBACKSPACE = u'\\ue003'\nBACK_SPACE = u'\\ue003'\nCANCEL = u'\\ue001'\nCLEAR = u'\\ue005'\nCOMMAND = u'\\ue03d'\nCONTROL = u'\\ue009'\nDECIMAL = u'\\ue028'\nDELETE = u'\\ue017'\nDIVIDE = u'\\ue029'\nDOWN = u'\\ue015'\nEND = u'\\ue010'\nENTER = u'\\ue007'\nEQUALS = u'\\ue019'\nESCAPE = u'\\ue00c'\nF1 = u'\\ue031'\nF10 = u'\\ue03a'\nF11 = u'\\ue03b'\nF12 = u'\\ue03c'\nF2 = u'\\ue032'\nF3 = u'\\ue033'\nF4 = u'\\ue034'\nF5 = u'\\ue035'\nF6 = u'\\ue036'\nF7 = u'\\ue037'\nF8 = u'\\ue038'\nF9 = u'\\ue039'\nHELP = u'\\ue002'\nHOME = u'\\ue011'\nINSERT = u'\\ue016'\nLEFT = u'\\ue012'\nLEFT_ALT = u'\\ue00a'\nLEFT_CONTROL = u'\\ue009'\nLEFT_SHIFT = u'\\ue008'\nMETA = u'\\ue03d'\nMULTIPLY = u'\\ue024'\nNULL = u'\\ue000'\nNUMPAD0 = u'\\ue01a'\nNUMPAD1 = u'\\ue01b'\nNUMPAD2 = u'\\ue01c'\nNUMPAD3 = u'\\ue01d'\nNUMPAD4 = u'\\ue01e'\nNUMPAD5 = u'\\ue01f'\nNUMPAD6 = u'\\ue020'\nNUMPAD7 = u'\\ue021'\nNUMPAD8 = u'\\ue022'\nNUMPAD9 = u'\\ue023'\nPAGE_DOWN = u'\\ue00f'\nPAGE_UP = u'\\ue00e'\nPAUSE = u'\\ue00b'\nRETURN = u'\\ue006'\nRIGHT = u'\\ue014'\nSEMICOLON = u'\\ue018'\nSEPARATOR = u'\\ue026'\nSHIFT = u'\\ue008'\nSPACE = u'\\ue00d'\nSUBTRACT = u'\\ue027'\nTAB = u'\\ue004'\nUP = u'\\ue013'\n","sub_path":"web/selenium.py","file_name":"selenium.py","file_ext":"py","file_size_in_byte":10284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"647711654","text":"import discord\nfrom discord.ext import commands\nimport random\n\nclass server():\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(pass_context=True)\n async def server(self, ctx, option=\"\"):\n \"\"\"\"\"\"\n server = ctx.message.server\n if option == \"\":\n await self.bot.say(\"```\\n\"\n \"!server [option]\\n\"\n \"\\n\"\n \"Commands:\\n\"\n \"name name of your server\\n\"\n \"id id of your server\\n\"\n \"region region of your server\\n\"\n \"info all your server info\\n```\")\n if option == \"name\":\n await self.bot.say(server.name)\n if option == \"id\":\n await self.bot.say(server.id)\n if option == \"region\":\n await self.bot.say(server.region)\n if option == \"info\":\n em = discord.Embed(color=0x000000)\n em.set_author(name='Serverinfo')\n em.add_field(name=\"Name\", value=(server.name))\n em.add_field(name=\"ID\", value=(server.id))\n em.add_field(name=\"Owner\", value=(server.owner.mention))\n em.add_field(name=\"Region\", value=(server.region))\n em.add_field(name=\"Member Count\", value=(server.member_count))\n try:\n em.add_field(name=\"Description\", value=(server.default_channel.topic))\n except:\n em.add_field(name=\"Description\", value=(\"none\"))\n em.add_field(name=\"ICON DOWNLOAD\", value=(\"[here]({})\".format(server.icon_url)))\n em.set_thumbnail(url=server.icon_url)\n await self.bot.say(embed=em)\n\ndef setup(bot):\n bot.add_cog(server(bot))\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279174310","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n## - api is an example of Hypermedia API support and access control\n#########################################################################\n\ndef index():\n \"\"\"\n example action using the internationalization operator T and flash\n rendered by views/default/index.html or views/generic.html\n\n if you need a simple wiki simply replace the two lines below with:\n return auth.wiki()\n \"\"\"\n features = {'book1':{'id':'1', 'name': 'Batman: Arkham Asylum','publisher': 'DC Comics',\n 'price': '9.00', 'format': 'Paperback', 'writer':'Grant Morrison',\n 'pages':'216', 'description':'Written by Grant Morrison. Art and cover by Dave McKean In celebration of the ...'},\n 'book2':{'id': '2', 'name': 'Superman: Earth One', 'publisher':'DC Comics',\n 'price': '£7.00', 'format':'Paperback', 'writer': 'Mikey',\n 'pages':'136', 'description': 'J. Michael Straczynski, the creator of Babylon 5, joins forces with rising star artist Shane Davis (Superman/Batman: The Search for Kryptonite) to create this original graphic novel that gives new insight into Clark Kents transformation into Superman and his first year as The Man of Steel. This is the first in a new wave of original DC Universe graphic novels, featuring top writers and illustrators unique takes on DC characters.'\n }}\n \n response.flash = T(\"Welcome to web2py!\")\n return dict(features=db(db.products.id == db.features.product_id).select())\n\ndef search():\n form=FORM('Search:', INPUT(_name='search', requires=IS_NOT_EMPTY()), INPUT(_type='submit'))\n\n query_result = \"\"\n\n if form.accepts(request, session):\n response.flash = 'Search Completed'\n query_result = db(db.products.name.like ('%' +request.vars.search + '%')).select()\n\n\n\n elif form.errors:\n response.flash = 'Please fill in the search box'\n\n\n else:\n response.flash = 'Please Enter a Keyword'\n\n\n\n\n\n return dict(form=form, features = query_result)\n\ndef addproduct():\n\n form=FORM('New Record:', BR(), BR(), DIV( SPAN(LABEL( 'Name: ', _for='name' ), _class='formLabel'), INPUT(_name='name', requires=IS_NOT_EMPTY()), _class='formField')\n , DIV(SPAN(LABEL( 'Price: ', _for='price' ), _class='formLabel'), INPUT( _name='price', requires=IS_NOT_EMPTY()), _class='formField')\n , DIV(SPAN(LABEL( 'Publisher: ', _for='publisher' ), _class='formLabel'), INPUT( _name='publisher', requires=IS_NOT_EMPTY()), _class='formField')\n , DIV(SPAN(LABEL( 'Type: ', _for='type' ), _class='formLabel') ,SELECT('Blu-ray','Book',_name=\"type\", requires=IS_NOT_EMPTY()), _class='formField')\n , DIV(SPAN(LABEL( 'Description: ', _for='description' ), _class='formLabel'), TEXTAREA(_name='description', requires=IS_NOT_EMPTY()), _class='formField')\n ,DIV(INPUT(_type='submit'), _class='submitButtonContainer'), _class='addRecordForm')\n\n if form.accepts(request, session):\n db.products.insert(name=request.vars.name, type=request.vars.type,\n description=request.vars.description, publisher=request.vars.publisher,\n price=request.vars.price);\n response.flash = 'Record Entered'\n\n elif form.errors:\n response.flash = 'Form filled out incorrectly'\n\n else:\n response.flash = \"\"\n\n\n\n\n return dict(form=form);\n\ndef updateProduct():\n\n db.products.description.widget = SQLFORM.widgets.text.widget\n\n db.products.type.widget = SQLFORM.widgets.options.widget\n\n db.products.type.requires = [IS_IN_SET(['Book', 'Blu-ray'], zero= None)]\n\n addform = SQLFORM(db.products)\n\n\n\n if addform.process().accepted:\n response.flash = 'Form Accepted'\n\n elif addform.errors:\n response.flash = 'Form has errors'\n\n else:\n response.flash = 'Please Fill Out the Form'\n\n return dict(form=addform)\n\n\n\ndef form_processing(form):\n if form.vars.search is None:\n form.errors.search = 'Search Box is empty'\n\n\n\n\ndef user():\n \"\"\"\n exposes:\n http://..../[app]/default/user/login\n http://..../[app]/default/user/logout\n http://..../[app]/default/user/register\n http://..../[app]/default/user/profile\n http://..../[app]/default/user/retrieve_password\n http://..../[app]/default/user/change_password\n http://..../[app]/default/user/manage_users (requires membership in\n use @auth.requires_login()\n @auth.requires_membership('group name')\n @auth.requires_permission('read','table name',record_id)\n to decorate functions that need access control\n \"\"\"\n return dict(form=auth())\n\n\n@cache.action()\ndef download():\n \"\"\"\n allows downloading of uploaded files\n http://..../[app]/default/download/[filename]\n \"\"\"\n return response.download(request, db)\n\n\ndef call():\n \"\"\"\n exposes services. for example:\n http://..../[app]/default/call/jsonrpc\n decorate with @services.jsonrpc the functions to expose\n supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv\n \"\"\"\n return service()\n\n\n@auth.requires_login() \ndef api():\n \"\"\"\n this is example of API with access control\n WEB2PY provides Hypermedia API (Collection+JSON) Experimental\n \"\"\"\n from gluon.contrib.hypermedia import Collection\n rules = {\n '': {'GET':{},'POST':{},'PUT':{},'DELETE':{}},\n }\n return Collection(db).process(request,response,rules)\n","sub_path":"Practical4/controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":6108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"640454958","text":"import random\nimport re\nimport textwrap\n\n\ndef get_file_text(filename):\n with open(filename, 'r') as f:\n text = f.read()\n f.close()\n return text\n\n\ndef text_to_list(text):\n formatted_text = re.sub(r\"[\\r\\n]\", ' ', text)\n string_list = formatted_text.split(\" \")\n for index, word in enumerate(string_list):\n string_list[index] = re.sub(r\"[^\\w,\\-!.?']|[+--]\", \"\", word)\n string_list = [x for x in string_list if x]\n return string_list\n\n\ndef list_to_trigram(input_list):\n trigram = {}\n while len(input_list) >= 3:\n key1 = input_list[-3]\n key2 = input_list[-2]\n value = input_list.pop(-1)\n trigram.setdefault((key1, key2), []).append(value)\n return trigram\n\n\ndef get_random(trigram):\n return random.choice(list(trigram.keys()))\n\n\ndef generate_text(trigram, num_words):\n word_list = list(get_random(trigram))\n while len(word_list) < num_words:\n if (word_list[-2], word_list[-1]) in trigram:\n potential_words = trigram[(word_list[-2], word_list[-1])]\n word_list.append(potential_words[\n random.randint(0, len(potential_words) - 1)])\n else:\n rand_key = get_random(trigram)\n word_list.append(rand_key[0])\n word_list.append(rand_key[1])\n word_list = word_list[:num_words]\n return ' '.join(word_list)\n\n\ndef write_text(text_file, output):\n output_filename = text_file.replace('.txt', '_trigrams.txt')\n with open(output_filename, 'w') as outfile:\n outfile.write(textwrap.fill(output, 80))\n\n\nif __name__ == \"__main__\":\n # get_filename = input(\"Enter the name of a text file to generate text from trigrams: \")\n # get_number = input(\"Enter the number of words to generate: \")\n get_filename = 'sherlock.txt'\n get_number = 500\n file_text = get_file_text(get_filename)\n str_list = text_to_list(file_text)\n trigram = list_to_trigram(str_list)\n cleanup = generate_text(trigram, int(get_number))\n print(write_text('sherlock.txt', cleanup))\n","sub_path":"students/JonathanMauk/lesson04/trigram.py","file_name":"trigram.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"612813149","text":"from __future__ import absolute_import, print_function, with_statement\nimport os\n\ndef getFiles(rootFolderPath):\n def walkFolders(rootFolderPath):\n for root, dirs, files in os.walk(rootFolderPath,topdown=True):\n for eachFolder in dirs:\n yield os.path.join(rootFolderPath,eachFolder)\n for subFolder in walkFolders(rootFolderPath):\n try:\n for eachFile in os.listdir(subFolder):\n yield os.path.join(subFolder,eachFile)\n except OSError:\n print(\"Empty Folder [{0}]\".format(subFolder))\n\ndef readLog(filename):\n with open(filename) as fp:\n for line in fp.xreadlines():\n if '\\x00' not in line and\\\n '------' not in line and\\\n 'ON-AIR' not in line:\n date = line[0:10].strip()\n time = line[10:21].strip()\n episode = line[22:57].strip()\n description = line[58:90].strip()\n duration = line[91:102].strip()\n status = line[103:110].strip()\n server = line[111:118].strip()\n details = line[134::].strip()\n yield (date, time, episode, description, duration, status, server, details)","sub_path":"utils/log_search.py","file_name":"log_search.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"135585364","text":"# coding: utf-8\n\nfrom app import db\nfrom app.models import PaginatedAPIMixin\nfrom materialized_view_factory import create_mat_view, MaterializedView\n\n\nclass VariantQuestion(db.Model):\n __tablename__ = 'variant_questions'\n __table_args__ = {\"schema\": \"qt\"}\n\n variant_name = db.Column(db.String(255), primary_key=True)\n student = db.Column(db.String(255), primary_key=True)\n registration_date = db.Column(db.DateTime)\n is_target = db.Column(db.Boolean)\n date_start = db.Column(db.DateTime)\n date_finish = db.Column(db.DateTime)\n organization = db.Column(db.String(255))\n speciality = db.Column(db.String(255))\n package = db.Column(db.String(255))\n audit_test_no = db.Column(db.String(10))\n ex_code = db.Column(db.String(50))\n discipline = db.Column(db.String(255))\n wf_code = db.Column(db.String(10))\n wf_name = db.Column(db.String(400))\n question_number = db.Column(db.Integer, primary_key=True)\n destructor_number = db.Column(db.Integer)\n is_true = db.Column(db.Boolean)\n\n\nclass Variant(MaterializedView):\n __table_args__ = {'schema': 'qt'}\n __table__ = create_mat_view('variant_mv',\n db.select(\n [\n VariantQuestion.variant_name,\n VariantQuestion.student,\n VariantQuestion.registration_date,\n VariantQuestion.is_target,\n VariantQuestion.date_start,\n VariantQuestion.date_finish,\n VariantQuestion.organization,\n VariantQuestion.speciality,\n VariantQuestion.package,\n VariantQuestion.audit_test_no,\n db.func.sum(db.case([(VariantQuestion.is_true, 1)], else_=0)).label(\n 'correct_question'),\n db.func.count(VariantQuestion.student).label('total_question'),\n ]\n ).select_from(VariantQuestion).group_by(VariantQuestion.variant_name,\n VariantQuestion.student,\n VariantQuestion.registration_date,\n VariantQuestion.is_target,\n VariantQuestion.date_start,\n VariantQuestion.date_finish,\n VariantQuestion.organization,\n VariantQuestion.speciality,\n VariantQuestion.package,\n VariantQuestion.audit_test_no),\n schema='qt')\n\n\nclass Counts(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'counts_mv',\n db.select(\n [\n db.literal('Организаций').label('name'),\n db.func.count(db.distinct(Variant.organization)).label('num'),\n db.literal('fas fa-hospital').label('icon'),\n db.literal(1).label('order')\n ]\n ).select_from(Variant).union(\n db.select(\n [\n db.literal('Пользователей'),\n db.func.count(db.distinct(Variant.student)),\n db.literal('fas fa-user'),\n db.literal(2).label('order')\n ]\n ).select_from(Variant).union(\n db.select(\n [\n db.literal('Целевых'),\n db.func.count(db.distinct(\n db.case([(Variant.is_target, Variant.student)]))).label('target_student_num'),\n db.literal('fas fa-user-md'),\n db.literal(3).label('order')\n ]\n ).select_from(Variant).union(\n db.select(\n [\n db.literal('Тестирований'),\n db.func.count(Variant.variant_name).label('attempt_num'),\n db.literal('far fa-check-square'),\n db.literal(4).label('order')\n ]\n ).select_from(Variant).union(\n db.select(\n [\n db.literal('Целевых'),\n db.func.count(db.case([(Variant.is_target, Variant.is_target)])).label(\n 'target_attempt_num'),\n db.literal('fas fa-check-double'),\n db.literal(5).label('order')\n ]\n ).select_from(Variant)\n )\n )\n )\n ),\n schema='qt')\n\n def to_dict(self):\n return {\n 'title': self.name,\n 'data': self.num,\n 'icon': self.icon\n }\n\n\nclass Speciality(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'speciality_mv',\n db.select(\n [\n Variant.speciality.label('name')\n ]\n ).distinct().select_from(Variant),\n schema='qt')\n\n def to_dict(self):\n return {\n 'name': self.name,\n }\n\n\nclass Organization(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'organization_mv',\n db.select(\n [\n Variant.organization.label('name')\n ]\n ).distinct().select_from(Variant),\n schema='qt')\n\n def to_dict(self):\n return {\n 'name': self.name,\n }\n\n\nclass Package(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'package_mv',\n db.select(\n [\n Variant.package.label('name')\n ]\n ).distinct().select_from(Variant),\n schema='qt')\n\n def to_dict(self):\n return {\n 'name': self.name,\n }\n\n\nclass Discipline(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'discipline_mv',\n db.select(\n [\n VariantQuestion.discipline.label('name')\n ]\n ).distinct().select_from(VariantQuestion).where(VariantQuestion.discipline != None),\n schema='qt')\n\n def to_dict(self):\n return {\n 'name': self.name,\n }\n\n\nclass WF(PaginatedAPIMixin, MaterializedView):\n __table_args__ = {'schema': 'qt'}\n\n __table__ = create_mat_view(\n 'wf_mv',\n db.select(\n [\n VariantQuestion.speciality,\n VariantQuestion.wf_code.label('code'),\n VariantQuestion.wf_name.label('name'),\n ]\n ).distinct().select_from(VariantQuestion).where(VariantQuestion.wf_code != None),\n schema='qt')\n\n def to_dict(self):\n return {\n 'name': self.name,\n 'code': self.code,\n }\n","sub_path":"app/selftest/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"479736197","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nimport matplotlib; matplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\nimport cv2\nimport math\n\n\n# Creating postion vectors for house vertices\np1 = np.array([0,0,0,1])[np.newaxis]\np2 = np.array([10,0,0,1])[np.newaxis]\np3 = np.array([10,10,0,1])[np.newaxis]\np4 = np.array([0,10,0,1])[np.newaxis]\np5 = np.array([0,0,10,1])[np.newaxis]\np6 = np.array([10,0,10,1])[np.newaxis]\np7 = np.array([10,10,10,1])[np.newaxis]\np8 = np.array([0,10, 10,1])[np.newaxis]\np9 = np.array([5, 10, 15,1])[np.newaxis]\np10 = np.array([5, 0, 15,1])[np.newaxis]\n\n# Order to plot the house\np = [p1,p2,p3,p4,p1,p5,p6,p2,p6,p7,\n\tp3,p7,p8,p4,p8,p5,p10,p6,p10,p9,p7,p9,p8]\n\n# Intial Tranformation matrix\n# Rotation & translation matrix\nT0 = np.array([\n\t[1, 0, 0, 6],\n\t[0, 0, 1, 6],\n\t[0, 1, 0, 6]])\n\n#Translation vector\nt = np.array([6,6,6])[np.newaxis].T\n\n# Perpective Project + Scale & Shift\nK = np.array([\n\t[10, 0, 0],\n\t[ -0, 10, 0],\n\t[ 0, 0, 1]])\n\n\n\ndef pressC(eventC):\n if eventC.key==\"c\":\n plt.close(eventC.canvas.figure)\n\ndef pressN(eventN):\n\tif eventN.key == \"n\":\n\t\tplt.close(eventN.canvas.figure)\n\ndef drawMyObject(cor):\n\n\t# Plotting the house!\n\tfig =plt.figure()\n\tplt.plot(cor[:,0],cor[:,1])\n\tfig = plt.gcf()\n\tcid = fig.canvas.mpl_connect('key_press_event', pressC)\n\tplt.show()\n\ndef getCoordinates(RT, K):\n\tcor = np.array([[0, 0]])\n\tfor x in range(0,len(p)):\n\n\t\t# Matrix multiplication of Camera Matrix by point\n\t\tpIM = np.matmul(RT,p[x].T)\n\t\tpIM = np.matmul(K,pIM)\n\n\t\t#Division by z component\n\t\tz = pIM[2]\n\t\t# We have image coordinates\n\t\tpIM = pIM/z\n\t\tpIM = np.delete(pIM, 2)\n\t\tcor = np.concatenate((cor,[pIM]))\n\n\treturn np.delete(cor,0,0)\t# Removing first zero points\n\n# Angles are accepted in Degrees\ndef getT(angZ, angY, angX):\n\n\tangZ = math.radians(angZ);\n\tangY = math.radians(angY);\n\tangX = math.radians(angX);\n\n\tZ = np.array([\n\t\t[math.cos(angZ), -math.sin(angZ), 0],\n\t\t[math.sin(angZ),\tmath.cos(angZ), 0],\n\t\t[\t\t\t 0,\t\t\t\t 0, 1]\n\t\t]);\n\n\tY = np.array([\n\t\t[ math.cos(angY), 0, \tmath.sin(angY)],\n\t\t[\t\t\t 0, 1,\t\t\t\t 0],\n\t\t[-math.sin(angY), 0,\tmath.cos(angY)]\n\t\t]);\n\n\tX = np.array([\n\t\t[1,\t\t\t\t 0, \t\t\t 0],\n\t\t[0,\tmath.cos(angX), -math.sin(angX)],\n\t\t[0,\tmath.sin(angX), math.cos(angX)]\n\t\t]);\n\n\tR = np.matmul(np.matmul(Z,Y), X)\n\tRt = np.concatenate((R,t),axis = 1)\n\treturn Rt\n\n\ndef main():\n\tprint('start')\n\n\t# Part one: Wire frame of house\n\tcor = getCoordinates(T0,K);\n\tdrawMyObject(cor);\n\n\t# Part two: will do 6 rotations of the house\n\t# about the z axis only\n\trotations = 8\n\tfor x in range(1, rotations+1):\n\t\taZ = 360/rotations * x;\n\t\tT = getT(aZ,0,0);\n\t\tcor = getCoordinates(T,K);\n\t\tfig =plt.figure()\n\t\tplt.plot(cor[:,0],cor[:,1])\n\t\tfig = plt.gcf()\n\t\tcid = fig.canvas.mpl_connect('key_press_event', pressN)\n\t\tplt.show()\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Homework/Hw3/Hw3.py","file_name":"Hw3.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"494929671","text":"from hexa_to_deci import hexa_to_deci\ndef interfaz_hexa_to_deci(num):\n dicto= {'a':10,'b':11,'c':12,'d':13,'e':14,'f':15}\n if not num:\n return 'Por favor, ingrese un numero'\n try:\n if int(num)<0:\n return 'Ingresar un numero hexadecimal positivo'\n else: \n return hexa_to_deci(num)\n except:\n for i in num:\n if not i in dicto:\n try:\n int(i)\n except:\n return 'Debe ingresar un numero hexadecimal positivo'\n return hexa_to_deci(num)","sub_path":"58021-RODRIGUEZ-Martin/hexa_a_deci/interfaz_hexa_to_deci.py","file_name":"interfaz_hexa_to_deci.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"478243778","text":"from pandas_datareader import data\r\n#name the company and source\r\nsymbol= 'RBC'\r\ndata_source= 'yahoo'\r\nstart_date= '2019-01-01'\r\nend_date= '2019-01-04'\r\n\r\ndf= data.DataReader(symbol, data_source, start_date, end_date)\r\n#print(df.head())\r\ndf.to_csv('RBC_stocks.csv')\r\n","sub_path":"google_finance.py","file_name":"google_finance.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"421982956","text":"# -*- coding: utf-8 -*-\r\nfrom telegram import InlineKeyboardButton, KeyboardButton\r\n\r\nstart_key = [['Русский 🇷🇺', \"O'zbek tili 🇺🇿\"]]\r\n\r\n#Админ раскладка\r\nadmin_key = [[InlineKeyboardButton('Добавить смузи', callback_data='add_smooth'),\r\n InlineKeyboardButton('Добавить эклер', callback_data='add_eclair')],\r\n [InlineKeyboardButton('Добавить локацию', callback_data='add_location')]]\r\n\r\naccept_smooth_info_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_info_smooth')]]\r\naccept_smooth_cost_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_cost_smooth')]]\r\naccept_smooth_pic_key = [[InlineKeyboardButton('Подтвердить', callback_data='pic_smooth')]]\r\n\r\naccept_eclair_info_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_info_eclair')]]\r\naccept_eclair_cost_mini_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_cost_mini_eclair')]]\r\naccept_eclair_cost_normal_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_cost_normal_eclair')]]\r\naccept_eclair_pic_key = [[InlineKeyboardButton('Подтвердить', callback_data='pic_smooth')]] #можео без смуз\r\n\r\naccept_location_info_key = [[InlineKeyboardButton('Подтвердить', callback_data='accept_info_location')]]\r\n\r\n\r\n#Русская раскладка\r\nmenu_key = [['🍹 Смузи', '🍰 Эклеры'], ['🗑 Корзина', '📞 Контакты']]\r\n\r\ncontacts_key = [['🔖 Общая информация', '📑 Список филиалов'], ['📖 Главное меню']]\r\n\r\nbasket_key = [['💵 Подсчет заказа', '❌ Очистить'], ['⚙️ Изменить покупку', '🛎 Оформить заказ'], ['📖 Главное меню']]\r\n\r\nget_order_key = [['🚶 Самовывоз', '🚗 Доставка'], ['⛔ Отменить заявку']]\r\n\r\nsend_contact_key = [[KeyboardButton('✅ Отправить контакт', request_contact=True)], ['⛔ Отменить заявку']]\r\n\r\nsend_location_key = [[KeyboardButton('✅ Отправить локацию', request_location=True)], ['⛔ Отменить заявку']]\r\n\r\nconfirm_order_key = [[InlineKeyboardButton('Заказать', callback_data='confirm_order'),\r\n InlineKeyboardButton('Отменить', callback_data='decline_order')]]\r\n\r\nwriting_self_text = [[InlineKeyboardButton('Подтвердить', callback_data='self_writing_accept')],\r\n [InlineKeyboardButton('Пропустить', callback_data='skip_writing')]]\r\n\r\nnumber_of_product_key = [[InlineKeyboardButton('1️⃣', callback_data='1'), InlineKeyboardButton('2️⃣', callback_data='2'), InlineKeyboardButton('3️⃣', callback_data='3')],\r\n [InlineKeyboardButton('4️⃣', callback_data='4'), InlineKeyboardButton('5️⃣', callback_data='5'), InlineKeyboardButton('6️⃣', callback_data='6')],\r\n [InlineKeyboardButton('7️⃣', callback_data='7'), InlineKeyboardButton('8️⃣', callback_data='8'), InlineKeyboardButton('9️⃣', callback_data='9')],\r\n [InlineKeyboardButton('✅ Подтвердить', callback_data='accept')]]\r\n\r\nchoose_size_eclair_key = [[InlineKeyboardButton('Обычный', callback_data='normal_size'),\r\n InlineKeyboardButton('Мини', callback_data='mini_size')]]\r\n\r\nchange_size_eclair_key = [[InlineKeyboardButton('Обычный', callback_data='change_normal_size'),\r\n InlineKeyboardButton('Мини', callback_data='change_mini_size')]]\r\n#Узбекская раскладка\r\nmenu_key_uzb = [['🍹', '🍰'], ['🗑', '🛎'], ['📖']]\r\n\r\ncontacts_key_uzb = [['🔖'], ['📑']]\r\n\r\nbasket_key_uzb = [['💵', '❌'], ['⚙', '🛎'], ['📖']]\r\n\r\nget_order_key_uzb = [['🚶', '🚗'], ['⛔']]\r\n\r\nsend_contact_key_uzb = [[KeyboardButton('✅ Отправить контакт', request_contact=True)], ['⛔ Отменить заявку']]\r\n\r\nsmooth_key_inline_uzb = [[InlineKeyboardButton('', callback_data='smooth_1')],\r\n [InlineKeyboardButton(' ➡️', callback_data='smooth_next_1')]]\r\n\r\nsmooth_next_key_uzb = [[InlineKeyboardButton('', callback_data='smooth_2')],\r\n [InlineKeyboardButton('⬅ ', callback_data='smooth_back_2'),\r\n InlineKeyboardButton(' ➡', callback_data='smooth_next_2')]]\r\n\r\nnumber_of_product_key_uzb = [[InlineKeyboardButton('1', callback_data='1'), InlineKeyboardButton('2', callback_data='2'), InlineKeyboardButton('3', callback_data='3')],\r\n [InlineKeyboardButton('4', callback_data='4'), InlineKeyboardButton('5', callback_data='5'), InlineKeyboardButton('6', callback_data='6')],\r\n [InlineKeyboardButton('7', callback_data='7'), InlineKeyboardButton('8', callback_data='8'), InlineKeyboardButton('9', callback_data='9')]\r\n ]\r\n\r\nchoose_size_eclair_key_uzb = [[InlineKeyboardButton('Обычный', callback_data='normal_size'),\r\n InlineKeyboardButton('Мини', callback_data='mini_size')]]\r\n\r\nchange_size_eclair_key_uzb = [[InlineKeyboardButton('Обычный', callback_data='change_normal_size'),\r\n InlineKeyboardButton('Мини', callback_data='change_mini_size')]]\r\n\r\nwriting_self_text_uzb = [[InlineKeyboardButton('Подтвердить', callback_data='self_writing_accept')],\r\n [InlineKeyboardButton('Пропустить', callback_data='skip_writing')]]\r\n\r\nconfirm_order_key_uzb = [[InlineKeyboardButton('Заказать', callback_data='confirm_order'),\r\n InlineKeyboardButton('Отменить', callback_data='decline_order')]]","sub_path":"keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"129361657","text":"\"\"\"\nA simple module for sending/receiving data via serial (USB) to the board.\n\"\"\"\n\nimport pdb\nimport time\nimport json\n\n## Note:\n# The following article can be referenced to help JSON serialize a custom class:\n# https://medium.com/python-pandemonium/json-the-python-way-91aac95d4041\n\ndef char_sum(s):\n return sum(bytes(s, 'utf-8'))\n\n\ndef safe_json(data):\n \"\"\"\n Checks if the input data is serializable via JSON\n \"\"\"\n if data is None:\n return True\n elif isinstance(data, (str, bool, int, float)):\n return True\n elif isinstance(data, (tuple, list)):\n return all(safe_json(x) for x in data)\n elif isinstance(data, dict):\n return all(isinstance(k, str) and safe_json(v) for k, v in data.items())\n return False\n\n\ndef send(board, data):\n \"\"\"\n Sends data over serial to the board (HITL)\n \"\"\"\n if not safe_json(data):\n raise ValueError(\"FAIL: sending data that is unserializable via JSON.\")\n\n board.reset_output_buffer() # clear the current buffer in case previously sent data was not recieved\n msg = json.dumps(data)\n to_send = json.dumps((msg, char_sum(msg))) + '\\r\\n'\n board.write(to_send.encode())\n\n while board.in_waiting == 0:\n pass\n\n board.read_until() # here because for some reason the sent sensors are echoed back\n\n\ndef receive(board, timeout=1.0):\n \"\"\"\n Receives data over serial sent by the board (HITL)\n\n note that the function will wait for 1 seconds max\n \"\"\"\n start = time.time()\n while board.in_waiting == 0:\n if (time.time() - start) > timeout:\n return None\n\n while board.in_waiting > 0: # keep trying until buffer is empty\n try:\n encoded = board.read_until()\n msg = json.loads(encoded)\n assert char_sum(msg[0]) == msg[1], \"checksum failed\"\n return json.loads(msg[0])\n\n except (json.decoder.JSONDecodeError, AssertionError):\n if encoded == b\"Traceback (most recent call last):\\r\\n\":\n # the board code has errored out\n print(\"ERROR: board code has errored out:\\n\")\n time.sleep(.1)\n while board.in_waiting > 0:\n print(board.read_until())\n quit()\n\n return False\n\n\ndef board_communicate(board, sensors, max_attempts=6):\n \"\"\"\n Publishes the latest sensor measurements, then polls the board for the\n latest commanded dipole.\n \"\"\"\n send(board, sensors)\n\n fails = 0\n while fails < max_attempts:\n data = receive(board)\n\n if data == False:\n # the board sent something unreadable\n send(board, \"DATA_RECEIVE_ERROR\")\n fails += 1\n # print(\"data was false\") # for debugging\n \n elif data == None:\n # the board did not send anything - is likely stuck on input()\n send(board, sensors)\n fails += 1\n # print(\"data was none\") # for debugging\n\n elif data == \"DATA_RECEIVE_ERROR\":\n # the board did not understand what was last sent\n send(board, sensors)\n fails += 1\n # print(\"board didn't understand\") # for debugging\n\n elif type(data) == list and data[0] == \"PASSTHROUGH_MESSAGE\":\n # simply allow the message to pass through and continue\n print(data)\n\n else:\n return data\n\n time.sleep(.1) # add a slight delay -- ONLY if some of the three errors above occurred\n\n raise RuntimeError(\"could not communicate with board in {} attempts.\".format(max_attempts))","sub_path":"computer-side/board_comms.py","file_name":"board_comms.py","file_ext":"py","file_size_in_byte":3597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336559252","text":"import os, shutil\r\nimport os.path as path\r\nfrom glob import glob\r\nfrom PIL import Image\r\nfrom subprocess import check_call\r\nimport time\r\nimport re\r\nimport psycopg2 # Only used for convert county scans function\r\n\r\nfrom const import *\r\n\r\n\r\ndef convert_images():\r\n\r\n # Turn of warnings about oversize image files\r\n Image.warnings.simplefilter('ignore', Image.DecompressionBombWarning)\r\n Image.MAX_IMAGE_PIXELS = None # This is to prevent a DecompressionBombError.\r\n # Starting in Pillow v5.0.0 warnings get auto-upgraded to\r\n # Errors if the size is twice the warning pixel threshold.\r\n\r\n nfiles = 0\r\n nframes = 0\r\n\r\n def sort_key(s):\r\n return re.sub('.*(\\d{3})(\\D{2})(\\d{3}).*', '\\\\2\\\\1\\\\3', s)\r\n\r\n for imagefile in sorted(glob(path.join(SOURCE_DIR, '*.tif')), key=sort_key):\r\n print(imagefile)\r\n\r\n map_name, book, maptype = re.match('^((\\d+)(\\D+)\\d+)', path.basename(imagefile.lower())).groups()\r\n # print(\"Hello\")\r\n print(map_name, book, maptype)\r\n\r\n scan_dir = path.join(SCAN_DIR, maptype, book)\r\n os.makedirs(scan_dir, exist_ok=True)\r\n\r\n map_dir = path.join(MAP_DIR, maptype, book)\r\n os.makedirs(map_dir, exist_ok=True)\r\n\r\n print('\\n' + imagefile.split('\\\\')[-1].lower())\r\n\r\n with Image.open(imagefile) as img:\r\n\r\n # Process one frame at at time\r\n frame_number = 0\r\n last_frame = False\r\n while not last_frame:\r\n\r\n frame = img.copy()\r\n try:\r\n frame_number += 1\r\n img.seek(frame_number)\r\n\r\n except EOFError:\r\n last_frame = True\r\n\r\n print('Frame %d' % (frame_number))\r\n print('Mode: %s' % ({\r\n '1': '1-bit black and white',\r\n 'L': '8-bit greyscale',\r\n 'P': '8-bit color map',\r\n 'RGB': 'RGB color',\r\n 'RGBA': 'RGBa color'\r\n }[frame.mode]))\r\n\r\n # Calculate the map image size\r\n scan_dpi = tuple(int(round(d)) for d in frame.info['dpi'])\r\n if scan_dpi == (96, 96):\r\n scan_dpi = (200, 200)\r\n print('Scan dpi not set, using %s dpi' % (str(scan_dpi)))\r\n map_dpi = tuple(min(MAP_DPI, sdpi) for sdpi in scan_dpi)\r\n map_size = tuple(int(round(d * mdpi / sdpi)) for d, mdpi, sdpi in zip(frame.size, map_dpi, scan_dpi))\r\n\r\n print('Map size: %s @ %d dpi => %s @ %d dpi' % (str(frame.size), scan_dpi[0], str(map_size), map_dpi[0]))\r\n\r\n basename = '%s-%03d' % (map_name, frame_number)\r\n\r\n print(\"######################\")\r\n print(frame.mode)\r\n print(\"######################\")\r\n\r\n # Convert 8-bit color map to RGB\r\n if frame.mode == 'P':\r\n print('Converting to RGB...')\r\n frame = frame.convert('RGB')\r\n elif frame.mode == 'RGBA':\r\n print('Converting from RGBA to RGB...')\r\n frame = frame.convert('RGB')\r\n\r\n # Save the tiff scan\r\n frame.save(path.join(scan_dir, basename + '.tif'),\r\n resolution=float(scan_dpi[0]), resolution_unit='inch')\r\n\r\n # Convert 1-bit black and white to 8-bit greyscale\r\n if frame.mode == '1':\r\n print('Converting to 8-bit greyscale...')\r\n frame = frame.convert('L')\r\n\r\n # Convert 8-bit color map to RGB\r\n elif frame.mode == 'P':\r\n print('Converting to RGB...')\r\n frame = frame.convert('RGB')\r\n\r\n\r\n # Resize and save the map image\r\n frame = frame.resize(map_size, resample=Image.BICUBIC)\r\n frame.save(path.join(map_dir, basename + '.jpg'), dpi=map_dpi, quality=MAP_QUALITY)\r\n\r\n nfiles += 1\r\n nframes += frame_number\r\n\r\n print('\\n%d frames from %d files' % (nframes, nfiles))\r\n\r\n\r\ndef convert_couty_scans() :\r\n\r\n with psycopg2.connect(PG_DSN) as con, con.cursor() as cur:\r\n\r\n for maptype in ('PM', 'RM', 'RS'):\r\n n = 0\r\n for srcdir in glob(path.join(SOURCE_DIR, maptype, '*')):\r\n book = re.match('.*(\\d{3})$', srcdir).group(1)\r\n\r\n scandir = path.join(SCAN_DIR, maptype.lower(), book)\r\n os.makedirs(scandir, exist_ok=True)\r\n\r\n mapdir = path.join(MAP_DIR, maptype.lower(), book)\r\n os.makedirs(mapdir, exist_ok=True)\r\n\r\n # Get a list of maps and page count\r\n cur.execute(\"\"\"\r\n SELECT {func_map_name}(m.id) AS map, m.page, m.npages\r\n FROM {table_map} m\r\n JOIN {table_maptype} t ON m.maptype_id = t.id\r\n WHERE t.abbrev = '{maptype}' AND m.book = {book}\r\n ;\r\n \"\"\".format(\r\n table_map=TABLE_MAP,\r\n table_maptype=TABLE_MAPTYPE,\r\n func_map_name=FUNC_MAP_NAME,\r\n maptype=maptype, book=book\r\n ))\r\n con.commit()\r\n\r\n for map_name, page, npages in cur:\r\n for i in range(npages):\r\n n += 1\r\n\r\n src = '%s%s_%04d.TIF' % (book, maptype, page + i)\r\n src = re.sub('RM', 'SM', src)\r\n src = path.join(srcdir, src)\r\n print(src)\r\n\r\n dst = '%s%s%03d-%03d.tif' % (book, maptype.lower(), page, i + 1)\r\n dst = path.join(scandir, dst)\r\n shutil.copy(src, dst)\r\n # print('%s => %s' % (src, dst))\r\n\r\n dst = '%s%s%03d-%03d.jpg' % (book, maptype.lower(), page, i + 1)\r\n dst = path.join(mapdir, dst)\r\n # if path.isfile(dst):\r\n # continue\r\n\r\n with Image.open(src) as img:\r\n\r\n print('Mode: %s' % ({\r\n '1': '1-bit black and white',\r\n 'L': '8-bit greyscale',\r\n 'P': '8-bit color map',\r\n 'RGB': 'RGB color',\r\n 'RGBA': 'RGBa color',\r\n 'YCbCr': 'JPEG color video format'\r\n }[img.mode]))\r\n\r\n # Calculate the map image size\r\n scan_dpi = tuple(int(round(d)) for d in img.info['dpi'])\r\n if scan_dpi == (96, 96):\r\n scan_dpi = (200, 200)\r\n print('Scan dpi not set, using %s dpi' % (str(scan_dpi)))\r\n map_dpi = tuple(min(MAP_DPI, sdpi) for sdpi in scan_dpi)\r\n map_size = tuple(\r\n int(round(d * mdpi / sdpi)) for d, mdpi, sdpi in zip(img.size, map_dpi, scan_dpi))\r\n\r\n print('Map size: %s @ %d dpi => %s @ %d dpi' % (\r\n str(img.size), scan_dpi[0], str(map_size), map_dpi[0]))\r\n\r\n # Convert 1-bit black and white to 8-bit greyscale\r\n if img.mode == '1':\r\n print('Converting to 8-bit greyscale...')\r\n img = img.convert('L')\r\n\r\n # Convert 8-bit color map or color video format to RGB\r\n elif img.mode == 'P' or img.mode == 'YCbCr':\r\n print('Converting to RGB...')\r\n img = img.convert('RGB')\r\n\r\n # Resize and save the map image\r\n img = img.resize(map_size, resample=Image.BICUBIC)\r\n img.save(dst, dpi=map_dpi, quality=MAP_QUALITY)\r\n # print('%s => %s' % (src, dst))\r\n\r\n print('%s: %d maps' % (maptype, n))\r\n\r\n\r\ndef do_check():\r\n files = 0\r\n errors = 0\r\n for dst in glob(path.join(TMP_DIR, '*')):\r\n files += 1\r\n src, book, type = re.match('.*((\\d{3})([A-Z]{2})_\\d{4}.*)', dst).groups()\r\n type = re.sub('sm', 'rm', type.lower())\r\n src = path.join(SOURCE_DIR, type, book, src)\r\n\r\n src_size = os.stat(src).st_size\r\n dst_size = os.stat(dst).st_size\r\n if src_size != dst_size:\r\n print('%s (%d) => %s (%d)' % (src, src_size, dst, dst_size))\r\n errors += 1\r\n else:\r\n print('OK: %s' % dst)\r\n\r\n print('%d files, %d errors' % (files, errors))\r\n\r\nif __name__ == '__main__':\r\n\r\n print('\\nUpdating map images ... ')\r\n startTime = time.time()\r\n\r\n # do_check()\r\n # convert_couty_scans()\r\n convert_images()\r\n\r\n endTime = time.time()\r\n print('{0:.3f} sec'.format(endTime - startTime))","sub_path":"convert_images.py","file_name":"convert_images.py","file_ext":"py","file_size_in_byte":9238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"465765190","text":"from puzzle import Image\nfrom puzzle import side\nfrom utils import flatten_with_any_depth\nimport math\nimport numpy as np\nimport cv2\n\n\nclass Pieces(Image):\n def __init__(self, img_relpass, piece_num, points):\n # 今のところデータが取れないからinit_pointsはそのまま受け流してる\n super().__init__(img_relpass)\n self.sides = self.create_side(points, self.init_side_len(points), self.proc_angles(points))\n self.piece_num = piece_num\n\n def init_side_len(self, points):\n lengths = []\n for i, p in enumerate(points):\n if i == len(points) - 1:\n s_len = self.get_distance(p, points[0])\n else:\n s_len = self.get_distance(p, points[i+1])\n lengths.append(s_len)\n return lengths\n\n def create_side(self, points, side_len, angles):\n sides = []\n for i, s in enumerate(side_len):\n #配列の最後の場合\n if i == len(side_len) - 1:\n sandwitch_angle = [ angles[i], angles[0] ]\n sandwitch_point = [points[i], points[0]]\n else:\n sandwitch_angle = [ angles[i], angles[i+1] ]\n sandwitch_point = [points[i], points[i+1]]\n sides.append(side.Side(s, sandwitch_angle, sandwitch_point))\n return sides\n\n def proc_angles(self, points):\n angles = []\n for i, p in enumerate(points):\n if i == 0:\n angles.append(self.get_angle(points[len(points) - 1], p , points[1]))\n continue\n if i == len(points) - 1:\n angles.append(self.get_angle(points[i-1], p, points[0]))\n else:\n angles.append(self.get_angle(points[i-1], p , points[i+1]))\n return angles\n\n def get_distance(self, p0, p1):\n return math.sqrt((p1.x- p0.x) * (p1.x - p0.x) + (p1.y - p0.y) * (p1.y - p0.y))\n\n def get_angle(self, p0, p1, p2):\n # p0 = a, p1 = b, p2 = cとなっている\n np.seterr(divide='ignore', invalid='ignore')\n \n ba = np.array((p0.x - p1.x, p0.y - p1.y))\n bc = np.array((p2.x - p1.x, p2.y - p1.y))\n cos_theta = \\\n float('%03.7f' % np.dot(ba, bc)) / \\\n float('%03.7f' % (math.sqrt( ba[0]**2 + ba[1]**2 ) * math.sqrt( bc[0]**2 + bc[1]**2 )))\n\n theta = math.acos(cos_theta)\n deg = math.degrees(theta)\n\n near_p1_point = self.create_near_deg_point(p0, p1, p2)\n near_p1_point_obj = side.Point(near_p1_point[0], near_p1_point[1])\n\n if self.is_out_piece(near_p1_point_obj, self.img):\n deg = 360 - deg\n return deg\n \n def is_out_piece(self, point, img):\n img_gray = cv2.cvtColor(img ,cv2.COLOR_BGR2GRAY)\n ret,thresh = cv2.threshold(img_gray ,130,255,cv2.THRESH_BINARY)\n hierarchy, contours, dummy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n cnt = contours[0]\n dist = cv2.pointPolygonTest(cnt,(point.x, point.y), False)\n if dist == 1:\n return False\n return True\n\n def create_near_deg_point(self, p1, p2, p3):\n p1_p3_middle_x = (p1.x + p3.x) / 2\n p1_p3_middle_y = (p1.y + p3.y) / 2\n return self.near_p2(p1_p3_middle_x, p1_p3_middle_y, p2)\n\n def near_p2(self, x, y, p2):\n harf_x = (x + p2.x) / 2\n harf_y = (y + p2.y) / 2\n if (p2.x - 10 < harf_x < p2.x + 10) or (p2.y - 10 < harf_y < p2.y + 10): \n return harf_x, harf_y\n return self.near_p2(harf_x, harf_y, p2)\n\n def get_link_piece_num(self):\n piece_nums = []\n for s in self.sides:\n for f in s.fit_objs:\n pieces_num.append(f.fit_pieces)\n pieces_num = flatten_with_any_depth(pieces_num)\n return pieces_nums\n","sub_path":"puzzle/pieces.py","file_name":"pieces.py","file_ext":"py","file_size_in_byte":3807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"454237222","text":"#importing the libraries\r\nimport numpy as np\r\nimport cv2\r\n\r\n#importing the cascade xml file for face detection\r\nface_cascade=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n\r\n#loading the input image \r\nframe= cv2.imread(\"people.jpg\")\r\n\r\n#converting the colored image into gray-scale\r\ngray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n\r\n#detecting faces\r\nfaces= face_cascade.detectMultiScale(gray)\r\n\r\n#drawing rectangles on detected faces\r\nif len(faces)==0:\r\n print(\"No faces found\")\r\nelse:\r\n print(\"Number of faces detected : \" + str(faces.shape[0]) )\r\n \r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)\r\n \r\n cv2.rectangle(frame,(0,frame.shape[0] - 190),(1425,frame.shape[0]),(255,255,255),-1)\r\n font=cv2.FONT_HERSHEY_SIMPLEX\r\n \r\n cv2.putText(frame,\"Total strength:30 \" + \"Present: \" + str(faces.shape[0]),(0,frame.shape[0]-70),font,3,(0,0,0),2,cv2.LINE_AA )\r\n \r\n cv2.imshow(\"Attendance\",frame)\r\n cv2.imwrite(\"output4.jpg\",frame)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n ","sub_path":"attendance_detector.py","file_name":"attendance_detector.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"579220501","text":"import math\nimport unittest\nimport numpy as num\n\nfrom pyrocko import gf, util\n\nr2d = 180. / math.pi\nd2r = 1.0 / r2d\nkm = 1000.\n\n\ndef numeq(a, b, eps):\n return (num.all(num.asarray(a).shape == num.asarray(b).shape and\n num.abs(num.asarray(a) - num.asarray(b)) < eps))\n\n\nclass GFSTFTestCase(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n\n def test_stf_triangular(self, plot=False):\n from matplotlib import pyplot as plt\n\n tref = 10.\n for duration in [0., 3.]:\n for peak_ratio in num.linspace(0., 1., 11):\n stf = gf.TriangularSTF(\n duration=duration, peak_ratio=peak_ratio, anchor=0.)\n t, a = stf.discretize_t(deltat=0.1, tref=tref)\n assert numeq(stf.centroid_time(tref), tref, 1e-5)\n if plot:\n plt.plot(t, a)\n plt.plot(t, a, 'o')\n\n if plot:\n plt.show()\n\n def test_stf_boxcar(self, plot=False):\n from matplotlib import pyplot as plt\n\n for duration in [0., 1., 2., 3.]:\n tref = 10.02\n stf = gf.BoxcarSTF(duration=duration, anchor=0.)\n t, a = stf.discretize_t(deltat=0.1, tref=tref)\n assert numeq(stf.centroid_time(tref), tref, 1e-5)\n if plot:\n plt.plot(t, a)\n plt.plot(t, a, 'o')\n\n if plot:\n plt.show()\n\n def test_stf_half_sinusoid(self, plot=False):\n from matplotlib import pyplot as plt\n\n for duration in [0., 1., 2., 3.]:\n tref = 10.02\n stf = gf.HalfSinusoidSTF(duration=duration, anchor=0.)\n t, a = stf.discretize_t(deltat=0.1, tref=tref)\n assert numeq(stf.centroid_time(tref), tref, 1e-5)\n if plot:\n plt.plot(t, a)\n plt.plot(t, a, 'o')\n\n if plot:\n plt.show()\n\n def test_effective_durations(self):\n deltat = 1e-4\n for stf in [\n gf.HalfSinusoidSTF(duration=2.0),\n gf.TriangularSTF(duration=2.0, peak_ratio=0.),\n gf.TriangularSTF(duration=2.0, peak_ratio=1.),\n gf.TriangularSTF(duration=2.0, peak_ratio=0.5),\n gf.BoxcarSTF(duration=2.0)]:\n\n t, a = stf.discretize_t(deltat, 0.0)\n t0 = stf.centroid_time(0.0)\n\n edur = num.sqrt(num.sum((t-t0)**2 * a)) * 2. * num.sqrt(3.)\n assert abs(edur - stf.effective_duration) < 1e-3\n\n def test_objects(self):\n for stf_class in gf.seismosizer.stf_classes:\n if stf_class is gf.STF:\n continue\n\n d1 = 2.0\n stf = stf_class(effective_duration=d1)\n d2 = stf.effective_duration\n assert abs(d2 - d1) < 1e-4\n\n\nif __name__ == '__main__':\n util.setup_logging('test_gf_stf', 'warning')\n unittest.main()\n","sub_path":"test/test_gf_stf.py","file_name":"test_gf_stf.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"128275204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 6 08:19:16 2019\n\n@author: nbarl\n\"\"\"\nfrom math import sqrt\nfrom BinImage2 import BinImage\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom copy import deepcopy\n\nclass Evolution :\n \"\"\"class representing the evolution of a binary image\"\"\"\n \n def __init__(self, image) :\n self.firstImage = deepcopy(image)\n self.currentImage = image\n self.actions = []\n for x in self.actions :\n self.currentImage.movePixel(x)\n \n def addAction(self, i, j, direction) :\n self.actions.append((i,j,direction))\n self.currentImage.movePixel((i,j,direction))\n \n def popAction(self) :\n if len(self.actions) > 0 :\n act = self.actions.pop()\n self.currentImage.movePixel(act)\n \n def createGif(self, name = 'dynamic_images.gif', speed = 500) :\n image = deepcopy(self.firstImage)\n M=image.image \n \n def update(i):\n image.movePixel(self.actions[i-1])\n matrice.set_array(image.image)\n \n fig, ax = plt.subplots()\n matrice = ax.matshow(M, cmap=plt.cm.gray_r)\n \n ani = animation.FuncAnimation(fig, update, frames=len(self.actions)+1, interval=speed)\n ani.save(name)\n \n def dist(p1, p2) :\n return sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)\n \n def simplify(self) :\n if len(self.actions)==0 :\n return\n newList = []\n i = 0\n while i 34 and days <= 125:\n season = 1\n elif days > 125 and days <= 219:\n season = 2\n elif days > 219 and days <= 311:\n season = 3\n else:\n season = 4\n return season\n\n\ndef switch_week(days):\n return math.ceil(days/7)\n\n\ndef phenomenon_to_list(phenomenon):\n phenomenon = phenomenon[1:-1].split(',')\n result = [0] * 11\n for i in phenomenon:\n result[int(i)] = 1\n return result\n\n\ndef standardization():\n path = 'datasets/air_weather.csv'\n # path = 'datasets/weather.csv'\n # item_list = ['pressure', 'wind_speed', 'temperature', 'humidity', 'rain20', 'rain08', 'cloud', 'visibility']\n item_list = ['pressure', 'wind_speed', 'temperature', 'humidity', 'rain20', 'rain08', 'cloud', 'visibility',\n 'day', 'week', 'month', 'quarter', 'AQI']\n csvfile = pd.read_csv(path)\n # csvfile = pd.read_csv(path, converters={'visibility': np.float64})\n\n # 将无效的值置为缺省\n csvfile1 = csvfile[item_list]\n csvfile1[csvfile1 == 999999] = np.NaN\n csvfile1[csvfile1 == 999990] = np.NaN\n # 标准化\n temp = StandardScaler().fit_transform(csvfile1)\n # 缺省置为中位数\n imputer = Imputer(strategy='median')\n temp = imputer.fit_transform(temp)\n\n csvfile[item_list] = pd.DataFrame(temp, columns=item_list)\n # csvfile = csvfile.drop(['station', 'city'], axis=1)\n\n # print(csvfile.describe())\n # corr_metrics = table.corr()\n # print(corr_metrics['temperature'].sort_values(ascending=False))\n\n csvfile.to_csv('datasets/air_weather_standardization.csv', index=False)\n # csvfile.to_csv('datasets/weather_standardization.csv', index=False)\n\n\ndef normalization():\n path = 'datasets/air_weather.csv'\n # path = 'datasets/weather.csv'\n # item_list = ['pressure', 'wind_speed', 'temperature', 'humidity', 'rain20', 'rain08', 'cloud', 'visibility']\n item_list = ['pressure', 'wind_speed', 'temperature', 'humidity', 'rain20', 'rain08', 'cloud', 'visibility',\n 'day', 'week', 'month', 'quarter', 'AQI']\n csvfile = pd.read_csv(path)\n # csvfile = pd.read_csv(path, converters={'visibility': np.float64})\n\n # 将无效的值置为缺省\n csvfile1 = csvfile[item_list]\n csvfile1[csvfile1 == 999999] = np.NaN\n csvfile1[csvfile1 == 999990] = np.NaN\n\n # 标准化\n temp = MinMaxScaler().fit_transform(csvfile1)\n # 缺省置为中位数\n imputer = Imputer(strategy='median')\n temp = imputer.fit_transform(temp)\n\n csvfile[item_list] = pd.DataFrame(temp, columns=item_list)\n # csvfile = csvfile.drop(['station', 'city'], axis=1)\n\n # print(csvfile.describe())\n # corr_metrics = table.corr()\n # print(corr_metrics['temperature'].sort_values(ascending=False))\n\n csvfile.to_csv('datasets/air_weather_normalization.csv', index=False)\n # csvfile.to_csv('datasets/weather_normalization.csv', index=False)\n\n\ndef read_csv(path):\n x = []\n y = []\n total = []\n\n with open(path) as csvfile:\n csv_reader = csv.reader(csvfile)\n for row in csv_reader:\n total.append(row)\n\n random.shuffle(total)\n for item in total:\n x.append(item[:-1])\n y.append(item[-1])\n return np.array(x), to_categorical(np.array(y), 11)\n\n\ndef shuffle_both(a, b):\n randnum = random.randint(0, 100)\n random.seed(randnum)\n random.shuffle(a)\n random.seed(randnum)\n random.shuffle(b)\n return a, b\n\n\ndef generate_data1(path, length=10):\n # 从已经划分好的训练\\验证\\测试集中读取\n x = []\n y = []\n\n sub_city = [[] for i in range(57)]\n with open(path) as csvfile:\n csv_reader = csv.reader(csvfile)\n next(csv_reader)\n for row in csv_reader:\n sub_city[int(row[1])-1].append(row)\n for item in sub_city:\n item.sort()\n\n for item in sub_city:\n # 这里item指代同一个县级城市包含的所有数据\n for i in range(len(item)):\n # 删除不需要的列\n # del item[i][1]\n # del item[i][0]\n # item[i] = item[i][2:]\n item[i] = item[i][2:-11]\n item = np.float64(item)\n for i in range(len(item)-length-1):\n x.append(np.array(item[i:i+length]))\n # y.append(np.array(item[i+length][-11:]))\n y.append(np.array(item[i+length][2]))\n\n x, y = shuffle_both(x, y)\n\n return np.array(x), np.array(y)\n\n\ndef generate_data2(path, length=10):\n # 读取的数据中未划分训练/验证/测试集\n # 预测11分类的phenomenon\n x = []\n y = []\n\n x_train = []\n y_train = []\n x_val = []\n y_val = []\n x_test = []\n y_test = []\n\n sub_city = [[] for i in range(57)]\n with open(path) as csvfile:\n csv_reader = csv.reader(csvfile)\n next(csv_reader)\n for row in csv_reader:\n sub_city[int(row[1])-1].append(row)\n for item in sub_city:\n item.sort()\n\n for item in sub_city:\n # 这里item指代同一个县级城市包含的所有数据\n for i in range(len(item)):\n # 删除不需要的列\n # del item[i][1]\n # del item[i][0]\n item[i] = item[i][2:]\n item = np.float64(item)\n for i in range(len(item)-length-1):\n x.append(np.array(item[i:i+length]))\n y.append(np.array(item[i+length][-11:]))\n\n for i in range(len(x)):\n if i % 12 == 3:\n x_val.append(x[i])\n y_val.append(y[i])\n elif i % 12 == 7 or i % 12 == 11:\n x_test.append(x[i])\n y_test.append(y[i])\n else:\n x_train.append(x[i])\n y_train.append(y[i])\n\n x_train, y_train = shuffle_both(x_train, y_train)\n x_val, y_val = shuffle_both(x_val, y_val)\n x_test, y_test = shuffle_both(x_test, y_test)\n\n return np.array(x_train), np.array(y_train), np.array(x_val), np.array(y_val), np.array(x_test), np.array(y_test)\n\n\ndef generate_data3(path, length=10, attribute='temperature'):\n # 读取的数据中未划分训练/验证/测试集\n # 预测某一特定的项,目前选择temperature\n # 输入不包含phenomenon部分\n x = []\n y = []\n\n x_train = []\n y_train = []\n x_val = []\n y_val = []\n x_test = []\n y_test = []\n\n sub_city = [[] for i in range(57)]\n with open(path) as csvfile:\n csv_reader = csv.reader(csvfile)\n csv_header = next(csv_reader)\n attribute = csv_header.index(attribute)-2\n\n for row in csv_reader:\n sub_city[int(row[1])-1].append(row)\n for item in sub_city:\n item.sort()\n\n for item in sub_city:\n # 这里item指代同一个县级城市包含的所有数据\n for i in range(len(item)):\n # 删除不需要的列\n # del item[i][1]\n # del item[i][0]\n item[i] = item[i][2:-11]\n item = np.float64(item)\n for i in range(len(item)-length-1):\n x.append(np.array(item[i:i+length]))\n y.append(np.array(item[i+length][attribute]))\n\n for i in range(len(x)):\n if i % 12 == 3:\n x_val.append(x[i])\n y_val.append(y[i])\n elif i % 12 == 7 or i % 12 == 11:\n x_test.append(x[i])\n y_test.append(y[i])\n else:\n x_train.append(x[i])\n y_train.append(y[i])\n\n x_train, y_train = shuffle_both(x_train, y_train)\n x_val, y_val = shuffle_both(x_val, y_val)\n x_test, y_test = shuffle_both(x_test, y_test)\n\n return np.array(x_train), np.array(y_train), np.array(x_val), np.array(y_val), np.array(x_test), np.array(y_test)\n\n\n\ndef generate_data4(path, length=10):\n # 从air_weather_standardization/normalization.csv生成划分数据集\n x = []\n y = []\n\n x_train = []\n y_train = []\n x_val = []\n y_val = []\n x_test = []\n y_test = []\n\n sub_city = [[] for i in range(3)]\n with open(path) as csvfile:\n csv_reader = csv.reader(csvfile)\n next(csv_reader)\n for row in csv_reader:\n index = int(row[1]) - 1\n del row[1]\n sub_city[index].append(row)\n\n for item in sub_city:\n for i in range(len(item)-length-1):\n x.append(np.array(item[i:i+length]))\n y.append(np.array(item[i+length][0]))\n\n for i in range(len(x)):\n if i % 12 == 3:\n x_val.append(x[i])\n y_val.append(y[i])\n elif i % 12 == 7 or i % 12 == 11:\n x_test.append(x[i])\n y_test.append(y[i])\n else:\n x_train.append(x[i])\n y_train.append(y[i])\n\n x_train, y_train = shuffle_both(x_train, y_train)\n x_val, y_val = shuffle_both(x_val, y_val)\n x_test, y_test = shuffle_both(x_test, y_test)\n\n return np.array(x_train), np.array(y_train), np.array(x_val), np.array(y_val), np.array(x_test), np.array(y_test)\n\n\ndef evaluate_metrics(y_test,y_pred):\n y_test = y_test.reshape(y_test.shape[0], -1).astype(float)\n print(y_test[:3])\n print(y_pred[:3])\n # exit()\n mse = mean_squared_error(y_test,y_pred)\n mae = mean_absolute_error(y_test,y_pred)\n rmse = np.sqrt(mse)\n r2 = r2_score(y_test,y_pred)\n print(\"mse: \",mse)\n print(\"mae: \",mae)\n print('rmse: ',rmse)\n print(\"r2_score:\",r2)\n\n\ndef test_classify(model,model_path, x_test,y_test,classes):\n model.load_weights(model_path)\n y_pred = model.predict(x_test)\n rocauc = metrics.roc_auc_score(y_test,y_pred)\n prauc = metrics.average_precision_score(y_test,y_pred,average='macro')\n print(f'ROC-AUC score={rocauc:.6f}')\n print(f'Prauc score={prauc:.6f}')\n y_prod = (y_pred > 0.5).astype(np.float32)\n acc = metrics.accuracy_score(y_test,y_prod)\n f1 = metrics.f1_score(y_test,y_prod,average='samples')\n print(f'acc score={acc:.6f}')\n print(f'f1 score={f1:.6f}')\n # 计算每个类的准确率\n for i,cls in enumerate(classes):\n cls_rocauc = metrics.roc_auc_score(y_test[:,i],y_pred[:,i])\n cls_prauc = metrics.average_precision_score(y_test[:,i],y_pred[:,i])\n cls_acc = metrics.accuracy_score(y_test[:,i],y_prod[:,i])\n cls_f1 = metrics.f1_score(y_test[:,i],y_prod[:,i])\n print(f'[{i:2} {cls:30}] rocauc={cls_rocauc:.4f} prauc={cls_prauc:.4f} acc={cls_acc:4f} f1={cls_f1:.4f}')\n return y_pred,y_test\n\n\nif __name__ == \"__main__\":\n # test = 'date\tcounty\tpressure\twind_speed\ttemperature\thumidity\train20\train08\n # cloud\tvisibility\tdays\tweek\tmonth\tseason\tChongqing\tBeijing\tShanghai\tsunny\n # cloudy\train\tfog\thaze\tdust\tthunder\tlightning\tsnow\thail\twind'.split('\t')\n\n # print(test[2:-11])\n # normalization()\n\n # sour_path = 'datasets/air_weather.csv'\n # dest_path = 'datasets/new_air_weather.csv'\n #\n # with open(sour_path) as csvfile:\n # csv_reader = csv.reader(csvfile)\n # csv_header = next(csv_reader)\n # del csv_header[0]\n # for item in ['Beijing', 'Shanghai', 'Chongqing']:\n # csv_header.append(item)\n # csv_write(dest_path, csv_header)\n # for row in csv_reader:\n # # days = switch_date(row[0])\n # # week = switch_week(days)\n # # month = row[0].split('/')[1]\n # # season = switch_season(days)\n # city_onehot = switch_onehot(row[2], ['北京市', '上海市', '重庆市'])\n #\n # row[2] = switch_index(row[2], ['北京市', '上海市', '重庆市'])\n # del row[0]\n #\n # for item in city_onehot:\n # row.append(item)\n #\n # csv_write(dest_path, row)\n\n standardization()\n normalization()\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":17980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"175272288","text":"#!/usr/bin/python3\n\nfrom graph.core import *\n\nfrom graph.load_xml import load_graph_types_and_instances\nfrom graph.save_xml import save_graph\nimport sys\nimport os\nimport math\nimport random\n\nurand=random.random\n\nimport os\nappBase=os.path.dirname(os.path.realpath(__file__))\n\nsrc=appBase+\"/snn_always_spike_graph_type.xml\"\n(graphTypes,graphInstances)=load_graph_types_and_instances(src,src)\n\n'''\nif len(sys.argv)>1:\n Ne=int(sys.argv[1])\nif len(sys.argv)>2:\n Ni=int(sys.argv[2])\nif len(sys.argv)>3:\n K=int(sys.argv[3])\n\nN=Ne+Ni\nK=min(N,K)\n'''\nN = 2 #two neurons for now\n\ngraphType=graphTypes[\"snn_always_spike\"]\nneuronType=graphType.device_types[\"neuron\"]\nclockType=graphType.device_types[\"clock\"]\n\ninstName=\"snn_always_spike_twonode\"\n\nproperties={}\nres=GraphInstance(instName, graphType, properties)\n\nclock=DeviceInstance(res, \"clock\", clockType, {\"neuronCount\":N})\nres.add_device_instance(clock)\n\ndt = 0.125\n\nnodes=[None]*N\nfor i in range(N):\n if i==0:\n I = 2\n tau = 10\n thr = 1 \n rst = 0\n else:\n I = 0\n tau = 100\n thr = 1 \n rst = 0\n props={\n \"I\":I, \"tau\":tau, \"thr\":thr, \"rst\":rst, \"dt\":dt\n }\n nodes[i]=DeviceInstance(res, \"n_{}\".format(i), neuronType, props)\n res.add_device_instance(nodes[i])\n\n res.add_edge_instance(EdgeInstance(res,nodes[i],\"tick\",clock,\"tick\",None))\n res.add_edge_instance(EdgeInstance(res,clock,\"tock\",nodes[i],\"tock\",None))\n\n #single synapse between neuron 0 and 1 with weight v+=0.2 \nei=EdgeInstance(res, nodes[1], \"input\", nodes[0], \"fire\", {\"weight\":0.2} )\nres.add_edge_instance(ei)\n'''\nfor dst in range(N):\n free=list(range(N))\n random.shuffle(free)\n for i in range(K):\n src=free[i]\n \n if src[0-9]+)/modifica/$', views.change_document, name='change_document'),\n url(r'^documento/(?P[0-9]+)/elimina/$', views.delete_document, name='delete_document'),\n url(r'^documento/(?P[0-9]+)/visualizza/$', views.view_document, name='view_document'),\n url(r'^documento/(?P[0-9]+)/(?P[0-9]+)/$', views.document_at_page, name='document_at_page'),\n url(r'^documento/(?P[0-9]+)/(?P[0-9]+)/visualizza/$', views.view_page, name='view_page'),\n url(r'^documento/(?P[0-9]+)/$', views.document_detail, name='document_detail'),\n url(r'^azienda/(?P\\w+)/$', views.company_detail, name='company_detail'),\n url(r'^$', views.catalog, name='catalog'),\n]\n","sub_path":"catalogo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"140371101","text":"import pygame\nimport sys\nfrom pygame.locals import *\nfrom functions import *\n\nclass spritesheet:\n #Loads image upon creation\n def __init__(self, image):\n self.sheet = pygame.image.load(image).convert_alpha()\n\n #Gets an image at (x, y) of the sprite sheet of width, width, and height, height\n #Colorkey is used to determine which color in the image is transparent\n #If colorkey is -1 then the color that is made transparent is the color in the top left pixel of the image\n def image_at(self, x, y, width, height, colorkey=None):\n image = pygame.Surface((width, height))\n image.blit(self.sheet, (0, 0), (x, y, width, height))\n if colorkey is not None:\n if colorkey is -1:\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey, pygame.RLEACCEL)\n return image\n\n #Loads a list of images which can be used for an animation\n def load_strip(self, x, y, width, height, image_count, colorkey=None):\n return [self.image_at(x + (a*width), y, width, height, colorkey) for a in range(image_count)]\n\ndef make_sprite_dict(frames, speed=1.0, loops=True, paused=False, active=False, angle=0, center=(0,0), deactivate=False):\n return {\n 'frames': frames,\n 'speed': speed,\n 'loops': loops,\n 'paused': paused,\n 'active': active,\n 'angle': angle,\n 'center': center,\n 'deactivate': deactivate\n }","sub_path":"sprite.py","file_name":"sprite.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287848298","text":"import sqlite3\n\nDB = None\nCONN = None\n\ndef get_student_by_github(github):\n query = \"\"\"SELECT first_name, last_name, github FROM Students WHERE github = ?\"\"\"\n DB.execute(query, (github,))\n row = DB.fetchone()\n return row\n\ndef make_new_student(first_name, last_name, github):\n query = \"\"\"INSERT into Students values (?, ?, ?)\"\"\"\n DB.execute(query, (first_name, last_name, github))\n CONN.commit()\n return \"Successfully added student: %s %s\" % (first_name, last_name)\n\ndef get_project_by_title(project):\n query = \"\"\"SELECT title, description, max_grade from Projects WHERE title = ?\"\"\"\n DB.execute(query, (project,))\n row = DB.fetchone()\n return \"\"\"\\\nProject: %s\nDescription: %s\nMax Grade: %d\"\"\" % (row[0],row[1],row[2])\n\ndef make_new_project(title, description, max_grade):\n query = \"\"\"INSERT into Projects values (?, ?, ?)\"\"\"\n desc = \" \".join(description)\n\n DB.execute(query, (title, desc, max_grade))\n CONN.commit()\n return \"Successfully added Project: %s\" % title\n\ndef get_student_grade_on_project(first_name, last_name, title):\n query = \"\"\"SELECT first_name, last_name, title, grade from ReportCardView WHERE first_name = ? AND last_name = ? AND title = ?\"\"\"\n DB.execute(query, (first_name, last_name, title))\n row = DB.fetchone()\n return \"\"\"\\\nStudent: %s %s\nProject: %s\nGrade: %d\"\"\" % (row[0],row[1],row[2],row[3])\n\ndef grade(first_name, last_name, title, grade):\n query = \"\"\"SELECT github from Students where first_name = ? and last_name = ?\"\"\"\n DB.execute(query, (first_name, last_name))\n row = DB.fetchone()\n #use the data we just fetched to then insert into Grades\n if row:\n query = \"\"\"INSERT into Grades VALUES (?, ?, ?)\"\"\"\n DB.execute(query, (row[0], title, grade))\n CONN.commit()\n return \"Successfully added grade for %s %s\" % (first_name, last_name)\n else:\n return \"Did not find student by that name.\"\n\ndef get_student_grades(first_name, last_name):\n query = \"\"\"SELECT title, grade FROM ReportCardView WHERE first_name = ? AND last_name = ?\"\"\"\n DB.execute(query, (first_name, last_name))\n rows = DB.fetchall()\n # return rows\n for thing in rows:\n return thing[0], thing[1]\n\ndef connect_to_db():\n global DB, CONN\n CONN = sqlite3.connect(\"hackbright.db\")\n DB = CONN.cursor()\n\ndef main():\n connect_to_db()\n command = None\n while command != \"quit\":\n input_string = raw_input(\"HBA Database> \")\n tokens = input_string.split()\n command = tokens[0]\n args = tokens[1:]\n\n if command == \"student\":\n get_student_by_github(*args) \n elif command == \"new_student\":\n make_new_student(*args)\n elif command == \"project\":\n get_project_by_title(*args)\n elif command == \"new_project\":\n make_new_project(args[0], args[1:-1], args[-1])\n elif command == \"student_grade_on_project\":\n get_student_grade_on_project(*args)\n elif command == \"grade\":\n grade(*args)\n elif command == \"student_grades\":\n get_student_grades(*args)\n\n CONN.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"sql_lesson/hackbright_app.py","file_name":"hackbright_app.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541084512","text":"# Imports\nfrom os.path import exists, expanduser, isdir, isfile, join\nfrom os import mkdir, listdir, startfile\nfrom PySimpleGUI import Window, Input, change_look_and_feel, Text\nfrom fuzzywuzzy import fuzz\nfrom toml import load, dump\n\n\n# Configuration files and folders\ndef check_configs():\n print(\"Creating configurations if don't exist\")\n if not exists(expanduser(\"~\\\\.hmenu.toml\")):\n filenew = open(expanduser(\"~\\\\.hmenu.toml\"), \"a\")\n new_config_dict = {\"read_user_start_items\": True, \"read_system_start_items\": True, \"read_user_custom_commands\":True, \"commands\":{\"command\": \"\\\\path\\\\to\\\\binary\"}}\n dump(new_config_dict, filenew)\n filenew.close()\n\n# Reading from configuration\ndef read_config():\n try:\n global read_user_start_items\n global read_system_start_items\n global read_user_custom_commands\n print(\"Reading from configuration\")\n loaded_data = load(expanduser(\"~\\\\.hmenu.toml\"))\n read_user_start_items = loaded_data[\"read_user_start_items\"]\n read_system_start_items = loaded_data[\"read_system_start_items\"]\n read_user_custom_commands = loaded_data[\"read_user_custom_commands\"]\n cmddict = loaded_data[\"commands\"]\n if read_user_custom_commands:\n return cmddict\n else:\n return {}\n except:\n \"Some error occured in configuration parsing\"\n exit()\n\n\n\n# Functions to parse start menu\ndef merge_dict(dict1, dict2):\n res = {**dict1, **dict2}\n return res\n\ndef get_items(dirName): \n listOfFile = listdir(dirName)\n allFiles = list()\n # Iterate over all the entries\n for entry in listOfFile:\n # Create full path\n fullPath = join(dirName, entry)\n # If entry is a directory then get the list of files in this directory \n if isdir(fullPath):\n allFiles = allFiles + get_items(fullPath)\n else:\n allFiles.append(fullPath)\n return allFiles\n\ndef filter_shortcut_files(arr):\n return list(filter(lambda x: x.endswith(\".lnk\"), arr))\n\ndef create_dict_of_commands(arr):\n newdict = {}\n for item in arr:\n newdict[str(item.split(\"\\\\\")[-1]).replace(\".lnk\", \"\")] = item\n return newdict\n\ndef parse_start_menu(dir):\n try:\n return create_dict_of_commands(filter_shortcut_files(get_items(dir)))\n except:\n print(\"Some error occured in parsing start menu items\")\n exit()\n\n\n\n# Fuzzy searching\ndef return_fuzzy(command, iter):\n tempdict = {}\n for i in iter:\n tempdict[i] = fuzz.ratio(command, i)\n max_key = max(tempdict, key=tempdict.get)\n return max_key\n\n\n\ncheck_configs()\ncmddict = read_config()\nif read_user_start_items:\n cmddict = merge_dict(cmddict, parse_start_menu(expanduser(\"~\\\\AppData\\\\Roaming\\\\Microsoft\\\\Windows\\\\Start Menu\\\\\")))\nif read_system_start_items:\n cmddict = merge_dict(cmddict, parse_start_menu(\"C:\\\\ProgramData\\\\Microsoft\\\\Windows\\\\Start Menu\"))\nprint(cmddict)\n# GUI\nprint(\"Creating GUI\")\ntry:\n change_look_and_feel(\"Dark Green 7\")\nexcept:\n print(\"Some error occured in configuring PySimpleGUI theme\")\n exit()\nroot = Window(\"Hmenu\", layout=[[Input(size=(40, 35)), Text(\"\", key=\"meratext\", size=(200, 35))]], no_titlebar=True, size=(1500, 40), keep_on_top=True, location=(0,0), return_keyboard_events=True)\ntemp_cmd = \"dummy_hmenu_command\"\nwhile True:\n try:\n event, val = root.read()\n except:\n print(\"Some error occured while initialising GUI\")\n exit()\n if event == \"None\" or event == \"Exit\":\n break\n print(\"Event: {}, vals: {}\".format(event, val))\n if event == \"Escape:27\":\n print(\"Killing program due to Escape Key pressed\")\n break\n if event == \"F1:112\":\n print(\"Executing command '{}' due to F1 key being pressed\".format(temp_cmd))\n startfile(cmddict[temp_cmd])\n break\n print(\"Updating Text field according to search\")\n temp_cmd = (return_fuzzy(val[0], cmddict.keys()))\n print(\"Match: {}\".format(temp_cmd))\n root[\"meratext\"].update(value=temp_cmd)\nroot.close()","sub_path":"hmenu.pyw","file_name":"hmenu.pyw","file_ext":"pyw","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"5573225","text":"from django.contrib import admin\nfrom django.urls import path\nfrom Books import views\n\napp_name = 'Books'\n\nurlpatterns = [\n path('',views.index, name='index'),\n path('data/',views.add,name='add'),\n path('delete',views.delete,name='delete'),\n path('button1',views.button,name='button'),\n path('button',views.result,name='result'),\n # path('/',views.detail, name='detail'),\n]","sub_path":"Books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"353278864","text":"import csv\nimport os\nimport sqlite3\nfrom typing import Union\n\n\nclass DBController:\n\n connect = None\n cursor = None\n\n def __init__(self, path=os.path.abspath(os.curdir) + '/database/database.db') -> None:\n self.connect = sqlite3.connect(path)\n self.cursor = self.connect.cursor()\n\n def create(self, db_table_name: str, recording_data: str) -> int:\n self.cursor.executescript(f\"INSERT INTO {db_table_name} VALUES ({recording_data})\")\n self.connect.commit()\n self.cursor.execute(\"SELECT last_insert_rowid();\")\n return self.cursor.fetchone()[0]\n\n def read(self, db_table_name: str, record_id: int) -> Union[str, None]:\n self.cursor.execute(f\"SELECT * FROM {db_table_name} WHERE id={record_id}\")\n return self.cursor.fetchone()\n\n def delete(self, db_table_name: str, record_id: int) -> bool:\n if self.read(db_table_name, record_id) is not None:\n self.cursor.executescript(f\"DELETE FROM {db_table_name} WHERE id={record_id}\")\n self.connect.commit()\n return True\n else:\n return False\n\n def get_url_list(self, db_table_name):\n self.cursor.execute(f\"SELECT realty.url FROM realty, {db_table_name} WHERE realty.id={db_table_name}.id_realty\")\n return list(map(lambda x: x[0], self.cursor.fetchall()))\n\n def database_to_csv(self):\n for db_table in ['room', 'cottages', 'apartment', 'land', 'garages', 'commercial_property']:\n with open(f\"{os.path.abspath(os.curdir)}/database/csv/{db_table}.csv\", \"w\", newline='') as write_file:\n self.cursor.execute(f\"SELECT * FROM realty, {db_table} WHERE realty.id={db_table}.id_realty\")\n\n writer = csv.writer(write_file, delimiter=',')\n writer.writerow(list(map(lambda x: x[0], self.cursor.description)))\n\n for row in self.cursor.fetchall():\n writer.writerow((list(row)))\n\n self.connect.commit()\n\n def __del__(self) -> None:\n self.connect.close()\n","sub_path":"DBController.py","file_name":"DBController.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"53498744","text":"from xlrd import open_workbook\nfrom xlwt import Workbook\nfrom xlutils.copy import copy\nimport geocoder\n\nrb = open_workbook('list.xls', formatting_info=True)\nsheet_num = 5\nadd_col = 3\nlat_col = 25\nr_sheet = rb.sheet_by_index(sheet_num)\nwb = copy(rb)\nw_sheet = wb.get_sheet(sheet_num)\narray = []\n#print first.col_values(5)\n#indexing from 0\nfor i in r_sheet.col_values(add_col):\n\tg = geocoder.google(i)\n\t#print (g.latlng)\n\tarray.append(g.latlng)\n#print array\n#for i in array:\n#\tif(len(i)>0):\n#\t\tprint i[0], i[1]\n#\telse:\n#\t\tprint '\\n'\nfor i in range(len(array)):\n\tif(len(array[i])>0):\n\t\tw_sheet.write(i,lat_col,array[i][0])\n\t\tw_sheet.write(i,lat_col+1,array[i][1])\nwb.save('list.xls')\n","sub_path":"xl_geocode.py","file_name":"xl_geocode.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"607700993","text":"# -*- coding: utf-8 -*-\n# lesson5-1, normal\n\nimport dir_commands as dc\n\n\ndef menu():\n print('Выберете действие (1-4):')\n print('1. Перейти в папку')\n print('2. Просмотреть содержимое текущей папки')\n print('3. Удалить папку')\n print('4. Создать папку')\n print('Для выхода введите \"q\"')\n action = input()\n return action\n\n\ndef handler(action):\n if action == 'q':\n print('Выход из программы...')\n print('Успешно')\n return\n action_item = {\n '1': dc.change_dir,\n '2': dc.dir_list,\n '3': dc.del_dir,\n '4': dc.make_dir\n }\n item = None\n try:\n item = int(action)\n if item in range(1, 5):\n for item, key in action_item.items():\n if item == action:\n key()\n else:\n print('\"{}\" - некорректная команда!'.format(action))\n\n except ValueError:\n print('\"{}\" - некорректная команда!'.format(action))\n\n answer = input('Продолжить работу с программой?\\n\"y\" - Да: ')\n\n handler(menu()) if answer == 'y' else handler('q')\n\n\nhandler(menu())\n","sub_path":"lesson5/les5_normal/les5-1_normal.py","file_name":"les5-1_normal.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"494283747","text":"import requests, random\r\nfrom time import sleep\r\nimport urllib.request\r\nimport colorama\r\n\"\"\"\r\nKod ile yapacağınız herhangi bir işlemden ben sorumlu değilim. Bu riski göz önüne alarak kullanın.\r\nThis application is for private or educational purposes only.\r\nDo not use it on other people without their permission. \r\nI do not accept responsibility for caused by the use of this code.\r\nBy using the this code,you automatically accept that you yourself are criminally responsible for yourself and you are aware that it violates the guidelines.\r\n\"\"\"\r\n\r\ncolors=['\\033[1;31m','\\033[1;32m','\\033[1;33m','\\033[1;34m','\\033[1;35m','\\033[1;36m']\r\n\r\n_phone = input('Hedef Telefon Numarasını Şununla Girin (+):')\r\n_name = ''\r\n\r\nfor x in range(12):\r\n\t_name = _name + random.choice(list('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789'))\r\n\tpassword = _name + random.choice(list('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789'))\r\n\tusername = _name + random.choice(list('qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789'))\r\n\r\n_phone9 = _phone[1:]\r\n\r\nnum = _phone\r\nnumplus = '+' + num\r\nprint(random.choice(colors))\r\nwhile True:\r\n#1\r\n try:\r\n print(requests.post('https://account.my.games/signup_send_sms/', data={'phone': _phone}))\r\n except:\r\n print(\"Başarısız oldu.\")\r\n print(random.choice(colors))","sub_path":"Basit Örnekler/sms_bomb.py","file_name":"sms_bomb.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"588491403","text":"\"\"\"Tests for property exercises\"\"\"\nimport math\nimport unittest\n\nfrom properties import Circle, Vector, Person\n\n\nclass CircleTests(unittest.TestCase):\n\n \"\"\"Tests for Circle.\"\"\"\n\n def test_radius(self):\n circle = Circle(5)\n self.assertEqual(circle.radius, 5)\n\n def test_default_radius(self):\n circle = Circle()\n self.assertEqual(circle.radius, 1)\n\n def test_diameter_changes(self):\n circle = Circle(2)\n self.assertEqual(circle.diameter, 4)\n circle.radius = 3\n self.assertEqual(circle.diameter, 6)\n\n def test_set_diameter(self):\n circle = Circle(2)\n self.assertEqual(circle.diameter, 4)\n circle.diameter = 3\n self.assertEqual(circle.radius, 1.5)\n\n def test_area(self):\n circle = Circle(2)\n self.assertEqual(circle.area, math.pi * 4)\n\n @unittest.skip(\"Log Radius Changes\")\n def test_radius_changes_logged(self):\n circle = Circle(2)\n self.assertEqual(circle.radius_changes, [2])\n circle.radius = 3\n self.assertEqual(circle.radius_changes, [2, 3])\n circle.diameter = 3\n self.assertEqual(circle.radius_changes, [2, 3, 1.5])\n\n @unittest.skip(\"Set Radius Error\")\n def test_no_negative_radius(self):\n circle = Circle(2)\n with self.assertRaises(ValueError) as context:\n circle.radius = -10\n self.assertEqual(str(context.exception), \"Radius cannot be negative!\")\n\n\nclass VectorTests(unittest.TestCase):\n\n \"\"\"Tests for Vector.\"\"\"\n\n def test_attributes(self):\n v = Vector(1, 2, 3)\n self.assertEqual((v.x, v.y, v.z), (1, 2, 3))\n\n def test_magnitude_property(self):\n v = Vector(2, 3, 6)\n self.assertEqual(v.magnitude, 7.0)\n try:\n v.y = 9\n except AttributeError:\n v = Vector(2, 9, 6)\n self.assertEqual(v.magnitude, 11.0)\n\n def test_no_weird_extras(self):\n v1 = Vector(1, 2, 3)\n v2 = Vector(4, 5, 6)\n with self.assertRaises(TypeError):\n len(v1)\n with self.assertRaises(TypeError):\n v1 < v2\n with self.assertRaises(TypeError):\n v1 > v2\n with self.assertRaises(TypeError):\n v1 <= v2\n with self.assertRaises(TypeError):\n v1 >= v2\n with self.assertRaises(TypeError):\n v1 + (1, 2, 3)\n with self.assertRaises(TypeError):\n (1, 2, 3) + v1\n with self.assertRaises(TypeError):\n v1 - (1, 2, 3)\n with self.assertRaises(TypeError):\n v1 * 'a'\n with self.assertRaises(TypeError):\n v1 / v2\n\n @unittest.skip(\"Vector Equality\")\n def test_equality_and_inequality(self):\n self.assertNotEqual(Vector(1, 2, 3), Vector(1, 2, 4))\n self.assertEqual(Vector(1, 2, 3), Vector(1, 2, 3))\n self.assertFalse(Vector(1, 2, 3) != Vector(1, 2, 3))\n v1 = Vector(1, 2, 3)\n v2 = Vector(1, 2, 4)\n v3 = Vector(1, 2, 3)\n self.assertNotEqual(v1, v2)\n self.assertEqual(v1, v3)\n\n @unittest.skip(\"Vector Adding\")\n def test_shifting(self):\n v1 = Vector(1, 2, 3)\n v2 = Vector(4, 5, 6)\n v3 = v2 + v1\n v4 = v3 - v1\n self.assertEqual((v3.x, v3.y, v3.z), (5, 7, 9))\n self.assertEqual((v4.x, v4.y, v4.z), (v2.x, v2.y, v2.z))\n\n @unittest.skip(\"Vector Multiplying\")\n def test_scaling(self):\n v1 = Vector(1, 2, 3)\n v2 = Vector(4, 5, 6)\n v3 = v1 * 4\n v4 = 2 * v2\n self.assertEqual((v3.x, v3.y, v3.z), (4, 8, 12))\n self.assertEqual((v4.x, v4.y, v4.z), (8, 10, 12))\n\n @unittest.skip(\"Vector Iterability\")\n def test_multiple_assignment(self):\n x, y, z = Vector(x=1, y=2, z=3)\n self.assertEqual((x, y, z), (1, 2, 3))\n\n @unittest.skip(\"Vector Immutability\")\n def test_immutability(self):\n v1 = Vector(1, 2, 3)\n with self.assertRaises(Exception):\n v1.x = 4\n self.assertEqual(v1.x, 1)\n\n\nclass PersonTests(unittest.TestCase):\n\n \"\"\"Tests for Person.\"\"\"\n\n def test_construct(self):\n Person(\"Trey\", \"Hunner\")\n\n def test_first_and_last_name_attributes(self):\n trey = Person(\"Trey\", \"Hunner\")\n self.assertEqual(trey.first_name, \"Trey\")\n self.assertEqual(trey.last_name, \"Hunner\")\n\n def test_name_attribute(self):\n trey = Person(\"Trey\", \"Hunner\")\n self.assertEqual(trey.name, \"Trey Hunner\")\n\n def test_change_names(self):\n trey = Person(\"Trey\", \"Hunner\")\n trey.last_name = \"Smith\"\n self.assertEqual(trey.name, \"Trey Smith\")\n trey.first_name = \"John\"\n self.assertEqual(trey.name, \"John Smith\")\n\n\nif __name__ == \"__main__\":\n from helpers import error_message\n error_message()\n","sub_path":"exercises/properties_test.py","file_name":"properties_test.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425130072","text":"import numpy as np\nfrom DFLS_function import *\nfrom collections import OrderedDict\n\nclass TwoLayerNet:\n def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):\n self.params = {}\n self.params['W1'] = weight_init_std*np.random.randn(input_size,hidden_size)\n self.params['b1'] = np.zeros(hidden_size)\n self.params['W2'] = weight_init_std*np.random.randn(hidden_size,output_size)\n self.params['b2'] = np.zeros(output_size)\n\n self.layers = OrderedDict()\n self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])\n self.layers['Relu1'] = ReLu()\n self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])\n self.lastLayer = SoftmaxWithLoss()\n\n def predict(self,x):\n for layer in self.layers.values():\n x = layer.forward(x)\n return x\n\n def loss(self,x,t):\n y = self.predict(x)\n return self.lastLayer.forward(y,t)\n\n def accuracy(self,x,t):\n y = self.predict(x)\n y = np.argmax(y, axis =1)\n if t.ndim!=1 : t = np.argmax(t,axis=1)\n accuracy = np.sum(y==t) /float(x.shape[0])\n return accuracy\n\n def gradient(self, x,t):\n\n self.loss(x,t)\n # print(self.loss(x,t))\n\n dout = 1\n dout = self.lastLayer.backward(dout)\n\n layers = list(self.layers.values())\n layers.reverse()\n for layer in layers:\n dout = layer.backward(dout)\n \n grads = {}\n grads['W1'] = self.layers['Affine1'].dW\n grads['b1'] = self.layers['Affine1'].db\n grads['W2'] = self.layers['Affine2'].dW\n grads['b2'] = self.layers['Affine2'].db\n return grads\n\n\nif __name__ == '__main__':\n a = TwoLayerNet(4,10,4)\n x = np.array([[1,2,3,4],[4,3,2,1]])\n t = np.array([[0,0,0,1],[1,0,0,0]])\n g = a.gradient(x,t)\n print(g)\n\n","sub_path":"lib/twoLayerNet.py","file_name":"twoLayerNet.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"314035034","text":"liste=[1,2,3,4,5]\n\nliste1=[i* 2 for i in liste] #Ilk Listedeki elemanlari dolasip verdigimiz deger ile carparak LIste1'e yaziyor!!!!!!\n\nprint(liste1)\n\n\nprint(\"\"\"\n\n\n*********************************************************************\n\n\"\"\")\n\ndef ikiylecarp(x): #Klasik Fonksiyon tanimlama\n return x*2\nprint(ikiylecarp(3))\n\nprint(\"\"\"\nLambda ifadesi ile \"def\" ile fonksiyon yazmadan bir satir ile yazabiliyoruz.\n\"\"\")\n\n\nuclecarp=lambda x:x*3\n\nprint(uclecarp(3))\n\nprint(\"\"\"\n\n\n*****************************************************************************\n\n\n\"\"\")\n\ndef toplama(x,y,z):\n return x+y+z\nprint(toplama(2,4,5))\n\nprint(\"\"\"\nLambda ile yazimi\n\"\"\")\n\n\ntoplam=lambda x,y,z:x+y+z\nprint(toplam(5,6,7))\n\n\n\nprint(\"\"\"\n\n***************** String Cevirme *****************\n\n\"\"\")\n\ndef terscevirme(s):\n return s[::-1]#!!!!!!!!!Ters cevirme komutu!!!!!!!!!!\nprint(terscevirme(\"Python Programlama\"))\n\nprint(\"\"\"\n\nLambda Ile Yazimi\n\n\"\"\")\n\nters=lambda s:s[::-1]\nprint(ters(\"Sarp\"))\n\nprint(\"\"\"\n\n*************************************\n\n\"\"\")\n\ndef cifttek(sayi):\n return sayi%2==0\nprint(cifttek(14))\n\nprint(cifttek(15))\n\nprint(\"\"\"\nLambda Ile yazilmis hali\n\"\"\")\n\nciftmitekmi=lambda sayi:sayi%2==0\n\nprint(ciftmitekmi(12))\n\nprint(ciftmitekmi(17))\n\n\n\"\"\"\nNot: Lambda ifadeleri buyuk uzun fonksiyonlarda kullnilmiyor. Kisa ve tek isimli fonksiyonalar icin.\n\"\"\"\n","sub_path":"Fonksiyionlar - Lambda Ifadeleri.py","file_name":"Fonksiyionlar - Lambda Ifadeleri.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"58323711","text":"# -*- coding: utf-8 -*-\r\n\r\n#########################################################################\r\n## This scaffolding model makes your app work on Google App Engine too\r\n## File is released under public domain and you can use without limitations\r\n#########################################################################\r\n\r\n## if SSL/HTTPS is properly configured and you want all HTTP requests to\r\n## be redirected to HTTPS, uncomment the line below:\r\n# request.requires_https()\r\n\r\n## app configuration made easy. Look inside private/appconfig.ini\r\nfrom gluon.contrib.appconfig import AppConfig\r\n## once in production, remove reload=True to gain full speed\r\nmyconf = AppConfig(reload=True)\r\n\r\n\r\nif not request.env.web2py_runtime_gae:\r\n ## if NOT running on Google App Engine use SQLite or other DB\r\n db = DAL(myconf.take('db.uri'), pool_size=myconf.take('db.pool_size', cast=int), check_reserved=['all'])\r\n # from gluon.contrib.redis_session import RedisSession\r\n # sessiondb = RedisSession('61.28.202.23:6379',db=0, session_expiry=False)\r\n # sessiondb = RedisSession('localhost:6379',db=0, session_expiry=False)\r\n # session.connect(request, response, db = sessiondb)\r\nelse:\r\n ## connect to Google BigTable (optional 'google:datastore://namespace')\r\n db = DAL('google:datastore+ndb')\r\n ## store sessions and tickets there\r\n session.connect(request, response, db=db)\r\n ## or store session in Memcache, Redis, etc.\r\n ## from gluon.contrib.memdb import MEMDB\r\n ## from google.appengine.api.memcache import Client\r\n ## session.connect(request, response, db = MEMDB(Client()))\r\n\r\n\r\n## by default give a view/generic.extension to all actions from localhost\r\n## none otherwise. a pattern can be 'controller/function.extension'\r\nresponse.generic_patterns = ['*'] if request.is_local else []\r\n## choose a style for forms\r\nresponse.formstyle = myconf.take('forms.formstyle') # or 'bootstrap3_stacked' or 'bootstrap2' or other\r\nresponse.form_label_separator = myconf.take('forms.separator')\r\n\r\n\r\n## (optional) optimize handling of static files\r\n# response.optimize_css = 'concat,minify,inline'\r\n# response.optimize_js = 'concat,minify,inline'\r\n## (optional) static assets folder versioning\r\n# response.static_version = '0.0.0'\r\n#########################################################################\r\n## Here is sample code if you need for\r\n## - email capabilities\r\n## - authentication (registration, login, logout, ... )\r\n## - authorization (role based authorization)\r\n## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss)\r\n## - old style crud actions\r\n## (more options discussed in gluon/tools.py)\r\n#########################################################################\r\n\r\nfrom gluon.tools import Auth, Service, PluginManager\r\n\r\nauth = Auth(db)\r\nservice = Service()\r\nplugins = PluginManager()\r\n\r\n## create all tables needed by auth if not custom tables\r\nauth.define_tables(username=False, signature=True, enable_tokens=True)\r\n\r\n## configure email\r\nmail = auth.settings.mailer\r\nmail.settings.server = 'secure.emailsrvr.com:465' #'logging' if request.is_local else 'secure.emailsrvr.com:465'\r\nmail.settings.sender = 'iris.notification@cynopsis-solutions.com'\r\nmail.settings.login = 'iris.notification@cynopsis-solutions.com:3ynop5i3'\r\nmail.settings.ssl = True\r\n\r\n## configure auth policy\r\n#auth.settings.create_user_groups = False\r\nauth.settings.registration_requires_verification = False\r\nauth.settings.registration_requires_approval = False\r\nauth.settings.reset_password_requires_verification = True\r\n#auth.settings.actions_disabled.append('register')\r\nauth.settings.email_case_sensitive = False\r\n\r\n\r\ndb.define_table('permission_list',\r\n Field('name','string',requires=IS_NOT_EMPTY()))\r\n\r\n\r\ndb.auth_group.id.readable=False\r\ndb.auth_user.id.readable=True\r\n#db.auth_user.password.requires = IS_STRONG(min=8, lower=1, error_message='Requires alphanumeric with minimum 8 charaters')\r\ndb.auth_permission.id.readable=False\r\ndb.auth_membership.id.readable=False\r\ndb.auth_permission.table_name.default=''\r\ndb.auth_permission.name.requires = IS_IN_DB(db(db.permission_list),'permission_list.name')\r\n\r\n\r\n#########################################################################\r\n## Define your tables below (or better in another model file) for example\r\n##\r\n## >>> db.define_table('mytable',Field('myfield','string'))\r\n##\r\n## Fields can be 'string','text','password','integer','double','boolean'\r\n## 'date','time','datetime','blob','upload', 'reference TABLENAME'\r\n## There is an implicit 'id integer autoincrement' field\r\n## Consult manual for more options, validators, etc.\r\n##\r\n## More API examples for controllers:\r\n##\r\n## >>> db.mytable.insert(myfield='value')\r\n## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL)\r\n## >>> for row in rows: print row.id, row.myfield\r\n#########################################################################\r\n\r\n## after defining tables, uncomment below to enable auditing\r\n# auth.enable_record_versioning(db)\r\n","sub_path":"models/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"115714846","text":"# library and dataset\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nf = open(\"/home/nvlacho/eclipse-workspace/databaseMYE030/hashTable.txt\", \"r\")\n\ntable = dict()\nexportCase = \"\"\nkey1 = \"\"\nkey2 = \"\"\n\nlines = f.readlines()\n\nexportCase = lines[0].strip()\n\nlineCount = 1\n\nx = 1\n\nwhile(True):\n\n \n\n #lineCount += 1\n\n data1 = lines[x].strip()\n x += 1\n data3 = \"\"\n\n tableWithCounries = dict()\n \n\n if data1 != \"\" :\n key1 = data1\n \n\n while(True):\n tableWithYears = dict()\n if data3 == \"\" :\n data2 = lines[x].strip()\n x += 1\n #lineCount += 1\n if not(data2 == \"\\n\") and not(data2 == \"\") :\n key2 = data2\n\n text = lines[x].strip()\n x += 1\n #lineCount += 1\n strArray = text.split(\",\")\n for i in range(0 , len(strArray), 2):\n if (i+1) < len(strArray):\n tableWithYears[strArray[i]] = strArray[i+1]\n \n else:\n break\n\n tableWithCounries[key2] = tableWithYears\n \n if len(lines) > x:\n data3 = lines[x]\n x += 1\n #lineCount += 1\n\n if data3 == \"\\n\" or not(len(lines)>x):\n break\n\n if data3 != \"\\n\" :\n key2 = data3.strip()\n continue\n if data3 == \"\":\n break\n \n table[key1] = tableWithCounries\n\n if not(len(lines) > x):\n break\n\n if data3 == \"\\n\" and len(lines) > x:\n continue\n\n if data3 == \"\":\n break\n\n\ndef convertToInt(x):\n array = []\n for i in list(x):\n array.append(int(i))\n return array\n\ndef convertToDouble(x):\n array = []\n for i in list(x):\n try:\n array.append(float(i)) \n except:\n print(\"Please insert a valid number. Currencies cannot contain commas, spaces, or characters.\")\n\n return array\n\n\nproblems = list(table.keys())\n\npairs=list(table.values())\ncountries=list(pairs[0].keys())\nprint(countries)\n\nfor j in countries: \n data=[]\n for i in problems:\n d=table.get(i).get(j)\n years =d.keys()\n data1=[]\n x = np.array(convertToInt(years))\n for k in years:\n data1.append(d.get(k))\n y=np.array(convertToDouble(data1))\n \n data.append(y)\n \n \n data=np.array(data) \n print(data)\n m=np.random.choice(['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd'],size=1)[0]\n rgb = np.random.rand(3,)\n plt.scatter(data[0], data[1], marker=m, s=50, color=rgb,label=j)\n \n \n\nplt.xlabel(problems[0]) \nplt.ylabel(problems[1])\nplt.legend(loc=\"upper center\", bbox_to_anchor=(0.9, 1.15), ncol=2)\n \nplt.show() \n \n \n","sub_path":"exportToScatterPlot.py","file_name":"exportToScatterPlot.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"201380281","text":"'''\n454. 4Sum II\n\nGiven four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.\n\nTo make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.\n\nExample:\n\nInput:\nA = [ 1, 2]\nB = [-2,-1]\nC = [-1, 2]\nD = [ 0, 2]\n\nOutput:\n2\n\nExplanation:\nThe two tuples are:\n1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0\n'''\nimport collections\nclass Solution(object):\n def fourSumCount(self, A, B, C, D):\n \"\"\"\n :type A: List[int]\n :type B: List[int]\n :type C: List[int]\n :type D: List[int]\n :rtype: int\n \"\"\"\n# reduce time to O(n^2) with hashtables\n memo = collections.defaultdict(int)\n for a in A:\n for b in B:\n memo[(a + b)] += 1\n print(a + b)\n res = 0\n for c in C:\n for d in D:\n print(-(c + d))\n if -(c + d) in memo:\n res += memo[-(c + d)]\n return res\n\n def fourSumCount_revise(self, A, B, C, D):\n cnt = collections.Count([a + b for a in A for b in B])\n return sum(memo[-(c + d)] for c in C for d in D)\n\n\nif __name__ == \"__main__\":\n A = [ 1, 2]\n B = [-2,-1]\n C = [-1, 2]\n D = [ 0, 2]\n res = Solution().fourSumCount(A, B, C, D)\n print(res)\n","sub_path":"454_fourSumCount.py","file_name":"454_fourSumCount.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"22770527","text":"#!/usr/bin/env python\nimport sys\nimport pandas as pd\nimport tempfile\n\nsys.path.insert(0, '../src/')\nfrom src.Ptype import Ptype\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n sys.stderr.flush()\n\n# Change to 'temp_file.csv' if running on console\nOUTPUT_DATA_PATH = tempfile._get_default_tempdir() + \"/temp_file.csv\"\n\ndef main():\n\n ptype = Ptype()\n\n while True:\n inputs = sys.stdin.readline() # clean=/app/input.csv,messy=/app/input.csv\n cmd = sys.stdin.readline() # completions | data\n query = sys.stdin.readline() # e.g. geo=EU28\n\n # Load data\n x = inputs.strip().split(',')[0].split(\"=\")[-1]\n out_data = pd.read_csv(x)\n header = out_data.columns.values\n\n # Get list of queries\n query_list = query.strip().split('/')\n\n ptype.run_inference(_data_frame=out_data)\n\n if cmd == \"completions\\n\":\n for h in header:\n temp_column_name = str(h).replace(' ', '')\n print(h + \" is \" + ptype.predicted_types[temp_column_name] + \"\\n\" + query.strip() + \"/\" + h + \"=\" + ptype.predicted_types[temp_column_name])\n # print(h + \" is \" + predicted_types[temp_column_name] + \"\\n\" + query.strip() + \"/\" + h + \"=\" + predicted_types[temp_column_name])\n print(\"\")\n sys.stdout.flush()\n else:\n\n # Rename header\n out_data.columns = out_data.columns.map(lambda x: x+ '(' + ptype.predicted_types[str(x).replace(' ', '')] + ')')\n\n out_data.to_csv(OUTPUT_DATA_PATH, index=False)\n print(OUTPUT_DATA_PATH)\n sys.stdout.flush()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"aiassistants/assistants/ptype/ptype_runner.py","file_name":"ptype_runner.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"361056941","text":"# search & replace, dictionnary, specific to the game\r\n\r\ndef athanor_var(variable_name):\r\n return 'go_' + variable_name\r\n\r\n\r\ndef athanor_sprite(sprite_name):\r\n return 'spr_' + sprite_name\r\n\r\n\r\ndef untag_digit(_str):\r\n return '\"' + _str.replace('#', 'pal_') + '\"'\r\n # return (int(_str.replace('#', '')))\r\n\r\n\r\ndef vue_index_to_game_part(idx):\r\n return \"iceland\"\r\n\r\n\r\ndef replace_athanor_semantic(_str):\r\n _str = _str.replace(\"cnosos\", \"cnossos\")\r\n _str = _str.replace(\"bateau\", \"boat\")\r\n if _str.find(\"rapa\") > -1 and _str.find(\"rapanui\") == -1:\r\n _str = _str.replace(\"rapa\", \"rapanui\")\r\n return _str\r\n\r\n\r\nworld_dict = [\"blank\", \"iceland\"]\r\nchapter_dict = [\"blank\", \"iceland\"]\r\n\r\ngame_native_text_dict = {\r\n \"%%%\": \"%s\",\r\n \"disquette 1\": \"disquette\",\r\n \"Insert Disk 1\": \"Insert Disk\",\r\n \"Appuyer Espace\": \"Appuyez sur le bouton de la souris\",\r\n \"Press Space\": \"Press Mouse Button\"\r\n}\r\n\r\n# Patch !!!\r\nathanor_missing_vars = [\r\n]\r\n\r\nathanor_con_dict = {\r\n \"ClicZone\": {\"name\": \"click_zone\", \"type\": \"variable\", \"input\": \"game_object\"},\r\n \"ClicPerso\": {\"name\": \"click_spr\", \"type\": \"variable\", \"input\": \"game_object\"},\r\n \"Mode\": {\"name\": \"game_is_current_action\", \"type\": \"function\", \"input\": \"game_action\"},\r\n \"SacADos\": {\"name\": \"game_is_object_in_inventory\", \"type\": \"function\", \"input\": \"game_object\"},\r\n \"ObjetEnMain\": {\"name\": \"game_is_object_in_hand\", \"type\": \"function\", \"input\": \"game_object\"},\r\n \"LastVue\": {\"name\": \"previous_vue\", \"type\": \"variable\", \"input\": \"integer\"},\r\n \"ArriveeVue\": {\"name\": \"previous_vue\", \"type\": \"variable\", \"input\": \"integer\"},\r\n\r\n \"Timer1\": {\"name\": \"Timer1\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": False, \"save\": False},\r\n \"Timer2\": {\"name\": \"Timer2\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": False, \"save\": False},\r\n\r\n \"Flag001\": {\"name\": \"Flag001\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag002\": {\"name\": \"Flag002\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag003\": {\"name\": \"Flag003\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag004\": {\"name\": \"Flag004\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag005\": {\"name\": \"Flag005\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag006\": {\"name\": \"Flag006\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag007\": {\"name\": \"Flag007\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag009\": {\"name\": \"Flag009\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True, \"default_value\":1},\r\n\r\n \"Flag011\": {\"name\": \"Flag011\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag012\": {\"name\": \"Flag012\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag014\": {\"name\": \"Flag014\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag015\": {\"name\": \"Flag015\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag017\": {\"name\": \"Flag017\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag018\": {\"name\": \"Flag018\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag019\": {\"name\": \"Flag019\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag020\": {\"name\": \"Flag020\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag021\": {\"name\": \"Flag021\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag022\": {\"name\": \"Flag022\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag023\": {\"name\": \"Flag023\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag024\": {\"name\": \"Flag024\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag028\": {\"name\": \"Flag028\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag029\": {\"name\": \"Flag029\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag030\": {\"name\": \"Flag030\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag031\": {\"name\": \"Flag031\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag032\": {\"name\": \"Flag032\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag034\": {\"name\": \"Flag034\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag036\": {\"name\": \"Flag036\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag037\": {\"name\": \"Flag037\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag038\": {\"name\": \"Flag038\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag039\": {\"name\": \"Flag039\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag040\": {\"name\": \"Flag040\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag041\": {\"name\": \"Flag041\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n \"Flag042\": {\"name\": \"Flag042\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True},\r\n\r\n \"Flag068\": {\"name\": \"Flag068\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True, \"default_value\":1},\r\n \"Flag069\": {\"name\": \"Flag069\", \"type\": \"variable\", \"input\": \"integer\", \"explicit_declaration\": True, \"save\": True}\r\n}\r\n\r\nathanor_set_preprocessor_dict = {\r\n \"Dial\": {\"name\": \"game_display_dialog_sequence\", \"type\": \"function\"},\r\n \"PlaySPL\": {}\r\n}\r\n\r\nathanor_set_dict = {\r\n \"Special\": {\"name\": \"start_game_special\", \"type\": \"function\", \"varargs\": False},\r\n \"Dial\": {\"name\": \"game_display_dialog\", \"type\": \"function\", \"varargs\": True},\r\n \"game_display_dialog_sequence\": {\"name\": \"game_display_dialog_sequence\", \"type\": \"function\", \"varargs\": True, \"nominal_op_count\": 2},\r\n \"game_display_dialog_sequence_ex\": {\"name\": \"game_display_dialog_sequence_ex\", \"type\": \"function\", \"varargs\": True, \"nominal_op_count\": 3},\r\n \"CurrentVue\": {\"name\": \"worldSetCurrentRoomByVue\", \"type\": \"function\", \"varargs\": False},\r\n \"Vue\": {\"name\": \"worldSetCurrentRoomByVue\", \"type\": \"function\", \"varargs\": False},\r\n \"ChangeZne\": {\"name\": \"worldSetCurrentZone\", \"type\": \"function\", \"param\": \"click_zone\", \"varargs\": False},\r\n \"Chapter\": {\"name\": \"worldSetCurrentChapter\", \"type\": \"function\", \"varargs\": False},\r\n \"ObjetEnMain\": {\"name\": \"game_set_object_to_hand\", \"type\": \"function\", \"input\": \"game_object\", \"varargs\": False, \"returns\": False},\r\n \"SacADos\": {\"name\": \"game_set_object_auto_inventory\", \"type\": \"function\", \"input\": \"game_object\", \"varargs\": False},\r\n \"HideSPR\": {\"name\": \"game_hide_sprite\", \"type\": \"function\", \"input\": \"sprite\", \"variable_translator\": athanor_var, \"varargs\": False},\r\n \"ShowSPR\": {\"name\": \"game_show_sprite\", \"type\": \"function\", \"input\": \"sprite\", \"variable_translator\": athanor_var, \"varargs\": False},\r\n \"PlaySPL\": {\"name\": \"game_play_sample\", \"type\": \"function\", \"varargs\": True},\r\n \"World\": {\"name\": \"world_set_current_index\", \"type\": \"function\", \"varargs\": False},\r\n \"CloseNord\": {\"name\": \"worldCloseExitNorth\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 1},\r\n \"CloseEst\": {\"name\": \"worldCloseExitEast\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 1},\r\n \"CloseSud\": {\"name\": \"worldCloseExitSouth\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 1},\r\n \"CloseOuest\": {\"name\": \"worldCloseExitWest\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 1},\r\n \"OpenNord\": {\"name\": \"worldOpenExitNorth\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 2},\r\n \"OpenEst\": {\"name\": \"worldOpenExitEast\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 2},\r\n \"OpenSud\": {\"name\": \"worldOpenExitSouth\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 2},\r\n \"OpenOuest\": {\"name\": \"worldOpenExitWest\", \"type\": \"function\", \"varargs\": False, \"nominal_op_count\": 2},\r\n \"AbortDepart\": {\"name\": \"game_abort_leaving_room\", \"type\": \"function\", \"varargs\": False},\r\n \"Tempo\": {\"name\": \"game_wait_ticks\", \"type\": \"function\", \"varargs\": False},\r\n \"FadeOUTPalette\": {\"name\": \"game_fade_out\", \"type\": \"function\", \"varargs\": False},\r\n \"FadeINPalette\": {\"name\": \"game_fade_in\", \"type\": \"function\", \"varargs\": False},\r\n \"GameOver\": {\"name\": \"game_over\", \"type\": \"function\", \"varargs\": False},\r\n \"PlayZik\": {\"name\": \"game_load_music\", \"type\": \"function\", \"varargs\": False, \"collect_to_table\": \"music_symbols\", \"collect_prefix\": \"mus_\"},\r\n \"StopZik\": {\"name\": \"game_stop_music\", \"type\": \"function\", \"varargs\": False },\r\n # \"PlayZik\": {\"name\": \"game_play_music\", \"type\": \"function\", \"varargs\": False},\r\n \"SetTimer1\": {\"name\": \"game_enable_timer1\", \"type\": \"function\", \"varargs\": False},\r\n \"SetTimer2\": {\"name\": \"game_enable_timer2\", \"type\": \"function\", \"varargs\": False},\r\n \"SetPalette\": {\"name\": \"game_fadeto_palette\", \"type\": \"function\", \"varargs\": False, \"variable_translator\": untag_digit},\r\n}\r\n\r\n# enum game_action { act_take_drop, act_look, act_use, act_talk, act_save, act_load };\r\n\r\ngame_action_dict = {\r\n \"TAKE\": \"act_take_drop\",\r\n \"LOOK\": \"act_look\",\r\n \"USE\": \"act_use\",\r\n \"TALK\": \"act_talk\"\r\n}\r\n\r\ngame_cardinal_order = [\"north\", \"south\", \"east\", \"west\"]\r\n\r\nvue_short_names = [\r\n \"empty\", #0\r\n \"rapa_beach\", #1\r\n \"rapa_boat_wreck\",\r\n \"rapa_boat_wreck_front\",\r\n \"rapa_boat_wreck_stairs\",\r\n \"rapa_fisherman\", #5\r\n \"rapa_moai_far\",\r\n \"rapa_moai_close\",\r\n \"rapa_valley\",\r\n \"rapa_cliff_top\",\r\n \"rapa_stone_mask\", #10\r\n \"rapa_cliff_shore\",\r\n \"rapa_cliff_shore_statue\",\r\n \"rapa_XXX\",\r\n \"rapa_YYY\",\r\n \"rapa_cavern_entrance\", #15\r\n \"rapa_giant_squid\",\r\n \"rapa_atlantis_ship\",\r\n \"rapa_atlantis_ship_flying\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"cnossos_boat\", #25\r\n \"cnossos_mosque\",\r\n \"cnossos_fishermen\",\r\n \"cnossos_drying_fish\",\r\n \"cnossos_street_0\",\r\n \"cnossos_street_1\", #30\r\n \"cnossos_wine_shop\",\r\n \"cnossos_square_statue\",\r\n \"cnossos_square_tree\",\r\n \"cnossos_inn_entrance\",\r\n \"cnossos_inn\", #35\r\n \"cnossos_street_2\",\r\n \"cnossos_guarded_door\",\r\n \"cnossos_altos_house_0\",\r\n \"cnossos_altos_house_1\",\r\n \"cnossos_pedestal_room\", #40\r\n \"cnossos_end_of_village\",\r\n \"cnossos_lilla_bedroom\",\r\n \"\",\r\n \"\",\r\n \"indus_boat\", #45\r\n \"indus_path_0\",\r\n \"indus_tent\",\r\n \"indus_path_1\",\r\n \"indus_village_0\",\r\n \"indus_house_0\", #50\r\n \"indus_potter\",\r\n \"indus_river_valley\",\r\n \"indus_village_1\",\r\n \"indus_temple_outside\",\r\n \"indus_temple_entrance\", #55\r\n \"indus_temple_hermite\",\r\n \"indus_path_2\",\r\n \"indus_village_2\",\r\n \"indus_village_race_game\",\r\n \"indus_village_cows\", #60\r\n \"indus_temple_inside\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\", #65\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\",\r\n \"\", #70\r\n \"boat_bridge\",\r\n \"boat_steering_wheel\",\r\n \"boat_cabin\",\r\n \"boat_storage\"\r\n]","sub_path":"toolchain-scenario/game_dictionnary.py","file_name":"game_dictionnary.py","file_ext":"py","file_size_in_byte":11781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227294591","text":"\"\"\"Custom component for reading values from knx group address\"\"\"\n\nimport logging\nimport voluptuous as vol\nfrom homeassistant.components.knx import DATA_KNX\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\nDOMAIN = 'knx_reader'\n\nSERVICE_KNX_READ = \"read\"\nSERVICE_KNX_ATTR_ADDRESS = \"address\"\n\nSERVICE_KNX_READ_SCHEMA = vol.Schema({\n vol.Required(SERVICE_KNX_ATTR_ADDRESS): cv.string,\n})\n\nasync def async_setup(hass, config):\n \"\"\"Ensure KNX is there.\"\"\"\n\n if DATA_KNX not in hass.data:\n _LOGGER.warning(\"Setup failed, knx_reader (custom component) cannot find DATA_KNX in hass.data\")\n hass.components.persistent_notification.async_create(\n \"Setup failed, knx_reader (custom component) cannot find DATA_KNX in hass.data\",\n title=\"KNX-READER\")\n return False\n\n def service_read_from_knx_bus(call):\n \"\"\"Issue read request to the bus.\"\"\"\n from xknx.core import ValueReader\n from xknx.knx import Address\n attr_address = call.data.get(SERVICE_KNX_ATTR_ADDRESS)\n knx_address = Address(attr_address)\n\n value_reader = ValueReader(hass.data[DATA_KNX].xknx, knx_address)\n _LOGGER.warning(\"Shoul read from KNX bus now\")\n yield from value_reader.send_group_read()\n _LOGGER.warning(\"Not sure if I got a value from KNX bus...\")\n\n hass.services.async_register(\n DOMAIN, SERVICE_KNX_READ,\n service_read_from_knx_bus,\n schema=SERVICE_KNX_READ_SCHEMA)\n\n return True\n","sub_path":"custom_components/knx_reader/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"35091444","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom scribus import *\nmargins = (36, 36, 0, 0)\n\n# Dictionary of logos' height/width aspect ratios. It is used to position the school logo\n# There's no way to programatically adjust frame to image.\n# The Python Scribus uses doesn't have any image utilities like PIL so I could not\n# figure out a way to determine the image's aspect ratio programatically. :|\n# There is a program I wrote called Logo_aspect_ratio.py that takes all the images files\n# in a directory and generates a CSV file of their width and height. The program is located in \n# the Women directory. After you run that program, you can run this one.\n\nschool_logos_dict = {}\nwith open(\"./School_Logos/filesizes_gif.csv\") as f:\n for line in f:\n current_line_list = line.split(\",\")\n school_logos_dict[current_line_list[0]] = float(current_line_list[2]) / float (current_line_list[1])\n\nconf_logos_dict = {}\nwith open(\"./Conference_Logos/filesizes_png.csv\") as f:\n for line in f:\n current_line_list = line.split(\",\")\n conf_logos_dict[current_line_list[0]] = float(current_line_list[2]) / float (current_line_list[1])\n \nplayers_list = []\nplayers_names_list = []\nwith open(\"NCAA_DI_action.csv\") as f:\n next(f) # skip headers row\n for line in f:\n current_line_list = line.split(\",\")\n full_name = current_line_list[0].split()\n first_name = full_name[0]\n first_last_name = full_name[1]\n if (full_name[1] == \"de\" or full_name[1] == \"La\"):\n player_name = full_name[0] + \" \" + full_name[1] + \" \" + full_name[2]\n if (player_name in players_names_list): \n player_name_count = sum([1 for plyr in players_names_list if plyr == player_name])\n image_filename = \"./NCAA_DI_action/\" + first_name + \"_\" + full_name[1] + \"_\" + full_name[2] + \"_\" + str(player_name_count + 1) + \".jpg\"\n else:\n image_filename = \"./NCAA_DI_action/\" + first_name + \"_\" + full_name[1] + \"_\" + full_name[2] + \".jpg\"\n else:\n player_name = first_name + \" \" + first_last_name\n if (player_name in players_names_list): \n player_name_count = sum([1 for plyr in players_names_list if plyr == player_name])\n image_filename = \"./NCAA_DI_action/\" + first_name + \"_\" + first_last_name + \"_\" + str(player_name_count + 1) + \".jpg\"\n else:\n image_filename = \"./NCAA_DI_action/\" + first_name + \"_\" + first_last_name + \".jpg\"\n \n santana_feliciano = \"Kariely Santana & Melanie Feliciano\"\n if (current_line_list[0] == santana_feliciano):\n player_name = santana_feliciano\n image_filename = \"./NCAA_DI_action/\" + santana_feliciano.replace(\" \", \"_\") + \".jpg\"\n \n \n player_school = current_line_list[1]\n school_state = current_line_list[2]\n school_division = current_line_list[3]\n photo_credit = current_line_list[4]\n \n single_player_list = [player_name, image_filename, player_school, school_state, school_division, photo_credit]\n players_list.append(single_player_list)\n players_names_list.append(player_name)\n\n\nif newDocument(PAPER_LETTER, margins, PORTRAIT, 1, UNIT_POINTS, NOFACINGPAGES, FIRSTPAGERIGHT, 1):\n\n defineColor(\"NJCAA Blue\", 217, 168, 55, 94)\n defineColor(\"NJCAA Gray\", 0, 0, 0, 40)\n defineColor(\"NJCAA Gray 2\", 0, 0, 0, 153)\n defineColor(\"NJCAA Blue 2\", 221, 168, 15, 30)\n defineColor(\"Darker Gray\", 0, 0, 0, 64)\n defineColor(\"NCAA Blue\", 230, 163, 0, 0)\n \n # top_right_rect = createRect(306, 36, 306, 180)\n # setFillColor(\"NJCAA Gray\", top_right_rect); setLineColor(\"NJCAA Gray\", top_right_rect)\n # second_rect = createRect(0, 216, 306, 180)\n # setFillColor(\"NJCAA Gray\", second_rect); setLineColor(\"NJCAA Gray\", second_rect)\n # third_rect = createRect(306, 396, 306, 180)\n # setFillColor(\"NJCAA Gray\", third_rect); setLineColor(\"NJCAA Gray\", third_rect)\n # top_left_rect = createRect(0, 576, 306, 180)\n # setFillColor(\"NJCAA Gray\", top_left_rect); setLineColor(\"NJCAA Gray\", top_left_rect)\n \n num_players = len(players_list)\n if (num_players % 8) == 0: \n num_pages = (num_players / 8) \n else: \n num_pages = (num_players / 8) + 1\n player_count = 0\n for page in range(num_pages):\n top_rect = createRect(0, 0, 612, 36)\n setFillColor(\"NCAA Blue\", top_rect); setLineColor(\"NCAA Blue\", top_rect)\n bottom_rect = createRect(0, 756, 612, 36)\n setFillColor(\"NCAA Blue\", bottom_rect); setLineColor(\"NCAA Blue\", bottom_rect)\n center_rect = createRect(0, 36, 612, 720)\n setFillColor(\"White\", center_rect); setLineColor(\"White\", center_rect)\n \n page_header = createText(36, 9, 540, 36)\n setText(\"NCAA Division I Action\", page_header)\n setTextColor(\"White\", page_header)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", page_header); setFontSize(24, page_header)\n setTextAlignment(ALIGN_CENTERED, page_header)\n \n years1 = createText(0, 6.7, 36, 36); setText(\"2019\" + \"\\n\" + \"-\" + \"\\n\" + \"2020\", years1)\n years2 = createText(576, 6.7, 36, 36); setText(\"2019\" + \"\\n\" + \"-\" + \"\\n\" + \"2020\", years2)\n setTextColor(\"White\", years1); setTextColor(\"White\", years2)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", years1); setFontSize(11, years1); setTextAlignment(ALIGN_CENTERED, years1)\n setFont(\"OLD SPORT 02 ATHLETIC NCV Regular\", years2); setFontSize(11, years2); setTextAlignment(ALIGN_CENTERED, years2)\n setLineSpacing(7, years1); setLineSpacing(7, years2) \n \n for row in range(4):\n for col in range(2):\n current_player = players_list[player_count]\n photo_width = 270; photo_height = 177\n photo_x = 38 + col * (photo_width)\n # photo_y = 36 + 20 + row * (250 + 100)\n photo_y = 36 + row * (photo_height + 4)\n player_photo = createImage(photo_x, photo_y, photo_width, photo_height)\n loadImage(current_player[1], player_photo); setScaleImageToFrame(1, 1, player_photo)\n \n division_x = photo_x + 15\n if (current_player[4].replace(\"\\n\",\"\") in [\"NCAA DI\", \"NCAA DII\", \"NCAA DIII\", \"NJCAA DI\", \"NJCAA DII\"]):\n division_y = photo_y + 15\n player_division = createImage(division_x, division_y, 25, 25)\n else:\n division_y = photo_y + 15\n player_division = createImage(division_x, division_y, 25, 12)\n loadImage(\"./Division_logos/\" + current_player[4].replace(\" \", \"_\").replace(\"\\n\",\"\") + \"_logo.png\", player_division); setScaleImageToFrame(1, 1, player_division)\n \n banner_width = 180; banner_height = 30\n banner_x = photo_x + (photo_width - banner_width) / 2.0\n if (current_player[0] in [santana_feliciano]):\n banner_width = 265.54; banner_x = photo_x\n banner_y = photo_y + (photo_height - banner_height)\n player_banner = createRect(banner_x, banner_y, banner_width, banner_height)\n setFillColor(\"White\", player_banner); setLineColor(\"None\", player_banner)\n \n \n logo_name = current_player[2].replace(\" \", \"_\")\n if (school_logos_dict[logo_name] < 0.7):\n logo_width = 33.0\n logo_height = min(logo_width * school_logos_dict[logo_name], 28)\n else:\n logo_height = 28.0\n logo_width = min(logo_height / school_logos_dict[logo_name], 33)\n logo_ypos = (banner_y + (banner_height - logo_height) / 2.0)\n school_logo = createImage(banner_x + 1, logo_ypos, logo_width, logo_height)\n loadImage(\"./School_Logos/\" + logo_name + \".gif\", school_logo); setScaleImageToFrame(1, 1, school_logo)\n \n # vocales_acentos = [\"Á\", \"É\", \"Í\", \"Ó\", \"Ú\", \"Ñ\"]\n # if any(x in unicode(current_player[0]).upper() for x in vocales_acentos): player_name_ypos = banner_y + 3\n # else: player_name_ypos = banner_y + 5\n # max_logo_width = 35.0\n if (current_player[0] in [santana_feliciano]):\n player_name = createText(banner_x + logo_width + 1, banner_y + 3, banner_width - 2 * logo_width, banner_height)\n else:\n player_name = createText(banner_x + logo_width + 1, banner_y + 3, banner_width - logo_width, banner_height)\n insertText(unicode(current_player[0]) + \"\\n\", -1, player_name)\n setFont(\"Playball Regular\", player_name);\n if (current_player[0] in [santana_feliciano]): setFontSize(13, player_name)\n else: setFontSize(15, player_name)\n name_length = getTextLength(player_name)\n player_school_and_state = current_player[2] + \" | \" + current_player[3]\n if (current_player[0] in [santana_feliciano]):\n player_school_and_state = \"Tennessee State University | University of Evansville (Indiana)\"\n school_and_state_length = len(player_school_and_state)\n insertText(unicode(player_school_and_state) + \"\\n\", -1, player_name)\n selectText(name_length, school_and_state_length, player_name)\n setFont(\"Asimov Print C\", player_name)\n selectText(name_length, len(player_school_and_state), player_name); setFontSize(6.7, player_name)\n setTextColor(\"NJCAA Blue\", player_name)\n setLineSpacing(11, player_name)\n setTextAlignment(ALIGN_CENTERED, player_name)\n \n if (current_player[0] in [santana_feliciano]):\n logo_name_2 = \"University_of_Evansville\"\n if (school_logos_dict[logo_name_2] < 0.7):\n logo_width = 33.0\n logo_height = min(logo_width * school_logos_dict[logo_name_2], 28)\n else:\n logo_height = 28.0\n logo_width = min(logo_height / school_logos_dict[logo_name_2], 33)\n logo_ypos = (banner_y + (banner_height - logo_height) / 2.0)\n school_logo = createImage(banner_x + banner_width - logo_width - 1, logo_ypos, logo_width, logo_height)\n loadImage(\"./School_Logos/\" + logo_name_2 + \".gif\", school_logo); setScaleImageToFrame(1, 1, school_logo)\n \n photo_credit = \"Photo: \" + current_player[5].replace(\"\\n\", \"\")\n photo_credit_length = len(photo_credit)\n photo_credit_width = 4.0 * photo_credit_length + 6.0\n photo_credit_banner = createRect(photo_x + 265.54 - photo_credit_width, photo_y, photo_credit_width, 10)\n setFillColor(\"NJCAA Blue\", photo_credit_banner); setLineColor(\"None\", photo_credit_banner); setFillTransparency(0.70, photo_credit_banner)\n \n \n photo_credit_text = createText(photo_x + 265.54 - photo_credit_width, photo_y + 1.5, photo_credit_width, 12)\n setText(photo_credit, photo_credit_text)\n setTextColor(\"White\", photo_credit_text); setFont(\"Asimov Print C\", photo_credit_text); setFontSize(8, photo_credit_text)\n setTextAlignment(ALIGN_CENTERED, photo_credit_text)\n \n player_count += 1\n if player_count == num_players: break\n if player_count == num_players: break\n if player_count == num_players: break\n # if page == 0: break\n \n \n \n # right_rect = createRect(576, 36, 36, 720)\n # setFillColor(\"NJCAA Gray\", right_rect); setLineColor(\"NJCAA Gray\", right_rect)\n # left_rect = createRect(0, 36, 36, 720)\n # setFillColor(\"NJCAA Gray\", left_rect); setLineColor(\"NJCAA Gray\", left_rect)\n newPage(-1)\n ","sub_path":"Women/NCAA_DI_action_shots.py","file_name":"NCAA_DI_action_shots.py","file_ext":"py","file_size_in_byte":11114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337280201","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.feature_selection import SelectKBest, f_regression, RFE\nfrom sklearn.linear_model import LinearRegression\nfrom scipy import stats\n\ndef select_kbest(X, y, k):\n '''\n Takes in predictors, target, and number of features to select and returns that number of best features based on SelectKBest function\n '''\n kbest = SelectKBest(f_regression, k=k)\n kbest.fit(X, y)\n return X.columns[kbest.get_support()].tolist()\n\ndef rfe(X, y, n):\n '''\n Takes in predictors, target, and number of features to select and returns that number of best features based on RFE function\n '''\n rfe = RFE(estimator=LinearRegression(), n_features_to_select=n)\n rfe.fit(X, y)\n return X.columns[rfe.get_support()].tolist()\n\ndef show_rfe_feature_ranking(X, y):\n '''\n Takes in predictors and target and returns feature ranking based on RFE function\n '''\n rfe = RFE(estimator=LinearRegression(), n_features_to_select=1)\n rfe.fit(X, y)\n rankings = pd.Series(rfe.ranking_, index=X.columns)\n return rankings.sort_values()\n \ndef group_stats(df, target_col, group_by_col):\n '''\n Returns 1-sample t test for groups and pop mean of target_col grouped by group_by_col\n '''\n for group, _ in df.groupby(group_by_col):\n t, p = stats.ttest_1samp(df[target_col][df[group_by_col] == group], df[target_col].mean())\n print(f'----------------\\n{group}\\n----------------\\nT-Statistic: {t:.2f}\\nP-value: {p:.3f}')\n if p < 0.01:\n print(f'We REJECT the null hypothesis, the mean {target_col} for the {group} subset is different than the overall population mean.\\n')\n else:\n print(f'We FAIL TO REJECT the null hypothesis, the mean {target_col} for the {group} subset is not different than the overall population mean.\\n')","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"183616335","text":"import random\nimport os\nimport logging\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport pandas as pd\n\nfrom utils import utils\nimport globals\nfrom games.connect4 import configuration\n\nglobals.init_config(configuration)\n\nfrom games.connect4.configuration import Config\nimport data_storage\nfrom games.connect4 import connect4, evaluation\nimport mcts\n\n\n# The logger\nutils.init_logger(logging.DEBUG, file_name=\"log/connect4.log\")\nlogger = logging.getLogger('evaluation')\n\nnp.set_printoptions(suppress=True, precision=6)\n\n\n# set the random seed\nrandom.seed(a=None, version=2)\nnp.random.seed(seed=None)\n\ntest_set_path = \"data_sets/test_set.csv\"\nnetwork_dir = \"../../training_data/connect4/networks/\" # directory in which the networks are saved\n\nprint(\"pytorch version: \", torch.__version__)\n\n\n# load the network\npath_list = os.listdir(network_dir)\npath_list.sort(key=utils.natural_keys)\n\n\n# load the test set with the solved positions\ntest_set = pd.read_csv(test_set_path, sep=\",\")\n\n\n# test the best network to quickly get a result\nnet_path = network_dir + path_list[-1]\nnet = data_storage.load_net(net_path, evaluation.torch_device)\npolicy_error, value_error = evaluation.net_prediction_error(net, test_set)\nlogger.debug(\"prediction-error: {}, value-error: {}, network: {}\".format(policy_error, value_error, net_path))\n\n\n# calculate the prediction error of the networks\ngeneration = []\nnet_prediciton_error = []\nnet_value_error = []\nmcts_prediciton_error = []\npath_list = os.listdir(network_dir)\npath_list.sort(key=utils.natural_keys)\n\n\n# empty board test\nboard = connect4.Connect4Board()\nbatch, _ = board.white_perspective()\nbatch = torch.Tensor(batch).unsqueeze(0).to(evaluation.torch_device)\npolicy, value = net(batch)\nlogger.debug(\"empty board policy: {}\".format(policy.detach().cpu().squeeze().numpy()))\nnet = data_storage.load_net(net_path, Config.evaluation_device)\npolicy = mcts.mcts_policy(board, 800, net, 1, 0)\nlogger.debug(\"empty board mcts-policy: {}\".format(policy))\n\n\n# get the prediction error of all networks\nfor i in range(len(path_list)):\n generation.append(i)\n net_path = network_dir + path_list[i]\n net = data_storage.load_net(net_path, evaluation.torch_device)\n\n policy_error, value_error = evaluation.net_prediction_error(net, test_set)\n net_prediciton_error.append(policy_error)\n net_value_error.append(value_error)\n logger.debug(\"prediction-error: {}, value-error: {}, network: {}\".format(policy_error, value_error, net_path))\n\n\n\n# get the mcts prediction error of all networks\ntemp = 1\nalpha_dirich = 0\n# path_list = [path_list[0], path_list[-1]]\npath_list = [path_list[-1]]\nfor i in range(len(path_list)):\n net_path = network_dir + path_list[i]\n net = data_storage.load_net(net_path, Config.evaluation_device)\n\n prediction_error = evaluation.mcts_prediction_error(net, test_set, 800, alpha_dirich, temp)\n mcts_prediciton_error.append(prediction_error)\n logger.debug(\"mcts-prediction-error: {}, network: {}\".format(prediction_error, net_path))\n\n\n\n# plot the network prediction error\nfig1 = plt.figure(1)\nplt.plot(generation, net_prediciton_error)\naxes = plt.gca()\naxes.set_ylim([0, 80])\nplt.title(\"Network Optimal Move Prediction Error\")\nplt.xlabel(\"Generation\")\nplt.ylabel(\"Prediction Error\")\nfig1.show()\n\n\n# plot the network value error\nfig2 = plt.figure(2)\nplt.plot(generation, net_value_error)\naxes = plt.gca()\naxes.set_ylim([0, 1.5])\nplt.title(\"Network Value Error\")\nplt.xlabel(\"Generation\")\nplt.ylabel(\"MSE Value\")\nfig2.show()\n\n\n\n# # plot the mcts prediction error\n# fig3 = plt.figure(3)\n# plt.plot(generation, mcts_prediciton_error)\n# axes = plt.gca()\n# axes.set_ylim([0, 80])\n# plt.title(\"MCTS Optimal Move Prediction Error\")\n# plt.xlabel(\"Generation\")\n# plt.ylabel(\"Prediction Error\")\n# fig3.show()\n\n\nplt.show()\n","sub_path":"games/connect4/MainPredictionError.py","file_name":"MainPredictionError.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"586872283","text":"import os\nimport sys\nimport datetime\nimport collections\nfrom math import ceil\n\nfrom flask import Flask, render_template, url_for, abort, request\nfrom flask.ext.frozen import Freezer\n\nfrom werkzeug import cached_property\nfrom werkzeug.contrib.atom import AtomFeed\n\nimport markdown\nimport yaml\n\nPOST_SKELETON = \"\"\"title: {title}\ndate: {date}\npublished: false\n\nCreate your content here...\n\"\"\"\n\n\nclass SortedDict(collections.MutableMapping):\n\n def __init__(self, items=None, key=None, reverse=False):\n self._items = {}\n self._keys = []\n if key:\n self._key_fn = lambda k: key(self._items[k])\n else:\n self._key_fn = lambda k: self._items[k]\n self._reverse = reverse\n\n if items is not None:\n self.update(items)\n\n def __getitem__(self, key):\n return self._items[key]\n\n def __setitem__(self, key, value):\n self._items[key] = value\n if key not in self._keys:\n self._keys.append(key)\n self._keys.sort(key=self._key_fn, reverse=self._reverse)\n\n def __delitem__(self, key):\n self._keys.pop(key)\n self._keys.remove(key)\n\n def __len__(self):\n return len(self._keys)\n\n def __iter__(self):\n for key in self._keys:\n yield key\n\n def __repr__(self):\n return '%s(%s)' % (self.__class__.__name__, self._items)\n\n\nclass Pagination(object):\n\n \"\"\"Class for pagination\"\"\"\n\n def __init__(self, page, per_page, total_count):\n self.page = page\n self.per_page = per_page\n self.total_count = total_count\n\n @property\n def pages(self):\n return int(ceil(self.total_count / float(self.per_page)))\n\n @property\n def has_prev(self):\n return self.page > 1\n\n @property\n def has_next(self):\n return self.page < self.pages\n\n def iter_pages(self, left_edge=2, left_current=2,\n right_current=5, right_edge=2):\n last = 0\n for num in range(1, self.pages + 1):\n if num <= left_edge or \\\n (num > self.page - left_current - 1 and\n num < self.page + right_current) or \\\n num > self.pages - right_edge:\n if last + 1 != num:\n yield None\n yield num\n last = num\n\n\nclass Blog(object):\n\n \"\"\"Class for Blog\"\"\"\n\n def __init__(self, app, root_dir='', file_ext=None):\n self.root_dir = root_dir\n self.file_ext = file_ext if file_ext is not None else \\\n app.config['POST_FILE_EXTENSION']\n self._app = app\n self._cache = SortedDict(key=lambda p: p.date, reverse=True)\n self._initialize_cache()\n\n @property\n def posts(self):\n if self._app.debug:\n return list(self._cache.values())\n else:\n return [post for post in\n list(self._cache.values()) if post.published]\n\n def get_post_or_404(self, path):\n \"\"\"Returns the post object for the given path or raises a NotFound\n exception.\n \"\"\"\n try:\n return self._cache[path]\n except KeyError:\n abort(404)\n\n def _initialize_cache(self):\n \"\"\"Walks the root directory and add all post to the cache.\"\"\"\n for (root, dirpaths, filepaths) in os.walk(self.root_dir):\n for filepath in filepaths:\n filename, ext = os.path.splitext(filepath)\n if ext == self.file_ext:\n path = os.path.join(root, filepath).replace(self.root_dir,\n '')\n post = Post(path, root_dir=self.root_dir)\n self._cache[post.urlpath] = post\n\n\nclass Post(object):\n\n \"\"\"Class for blog Posts.\"\"\"\n\n def __init__(self, path, root_dir=''):\n self.urlpath = os.path.splitext(path.strip('/'))[0]\n self.filepath = os.path.join(root_dir, path.strip('/'))\n self.published = False\n self._initialize_metadata()\n\n @cached_property\n def html(self):\n with open(self.filepath, 'r') as file_input:\n content = file_input.read().split('\\n\\n', 1)[1].strip()\n return markdown.markdown(content, extensions=['codehilite'])\n\n def url(self, _external=False):\n return url_for('post', path=self.urlpath, _external=_external)\n\n def _initialize_metadata(self):\n content = ''\n with open(self.filepath, 'r') as file_input:\n for line in file_input:\n if not line.strip():\n break\n content += line\n\n self.__dict__.update(yaml.load(content))\n\nimport settings\napp = Flask(__name__)\napp.config.from_object(settings)\nblog = Blog(app, root_dir='posts')\nfreezer = Freezer(app)\n\n\ndef generate_post_file_name(title):\n \"\"\"Return the file name a post should use based on its title and date\"\"\"\n return ''.join(char for char in title.lower() if (\n char.isalnum() or char == ' ')).replace(' ', '-')\n\n\ndef create_post(title, root_dir=''):\n \"\"\"Create an empty post with the appropriate metadata\"\"\"\n post_date = datetime.datetime.strftime(\n datetime.datetime.now(), '%Y-%m-%d')\n\n # The name must to be unique\n post_file_name = '{}-{}.md'.format(\n post_date,\n generate_post_file_name(title))\n\n post_file_path = os.path.join(root_dir, post_file_name)\n\n if os.path.exists(post_file_path):\n raise EnvironmentError('[{post}] already exists.'.format(\n post=post_file_path))\n\n with open(post_file_path, 'w') as post_file:\n post_file.write(POST_SKELETON.format(date=post_date, title=title))\n\n\ndef url_for_other_page(page):\n args = request.view_args.copy()\n args['blog/page'] = page\n return url_for(request.endpoint)\n\napp.jinja_env.globals['url_for_other_page'] = url_for_other_page\n\n\ndef get_posts_for_page(page, per_page, count):\n if page == 1:\n start = 0\n else:\n start = ((page * per_page) - (per_page - 1)) - 1\n end = page * per_page\n posts = blog.posts[start:end]\n return posts\n\n\n@app.template_filter('date')\ndef format_date(value, format='%d/%m/%Y'):\n return value.strftime(format)\n\n\n@app.route('/')\ndef index():\n count = len(blog.posts)\n posts = get_posts_for_page(1, app.config['PER_PAGE'], count)\n pagination = Pagination(1, app.config['PER_PAGE'], count)\n return render_template('index.html',\n pagination=pagination,\n posts=posts,\n page=1)\n\n\n@app.route('/blog/page//')\ndef show_blogs(page):\n count = len(blog.posts)\n posts = get_posts_for_page(page, app.config['PER_PAGE'], count)\n pagination = Pagination(page, app.config['PER_PAGE'], count)\n\n if not blog.posts and page != 1:\n abort(404)\n\n return render_template('index.html',\n pagination=pagination,\n posts=posts,\n page=page)\n\n\n@app.route('/about/')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/blog//')\ndef post(path):\n post = blog.get_post_or_404(path)\n return render_template('post.html', post=post)\n\n\n@app.route('/feed.atom')\ndef feed():\n feed = AtomFeed('Artículos recientes',\n feed_url=request.url,\n url=request.url_root)\n posts = blog.posts[:10]\n for post in posts:\n feed.add(post.title,\n content_type='html',\n author=app.config['NAME'],\n url=post.url(_external=True),\n updated=post.date,\n published=post.date)\n return feed.get_response()\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'build':\n freezer.freeze()\n elif len(sys.argv) > 1 and sys.argv[1] == 'create_post' and \\\n sys.argv[2] is not '':\n create_post(title=sys.argv[2], root_dir='posts')\n else:\n posts_files = [post.filepath for post in blog.posts]\n app.run(port=8000, debug=True, extra_files=posts_files)\n","sub_path":"plog/plog.py","file_name":"plog.py","file_ext":"py","file_size_in_byte":8103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"12020041","text":"#!/usr/bin/env python\n'''This script takes a VCF file and counts the numbers of heterozygous and missing genotypes per site. Written by Verena Kutschera, January 2017.\n\nUsage:\npython countHeterozygousGenotypes.py myData.vcf.gz het_missing_sites.out'''\n\nimport sys\nimport gzip\nimport re\n\nvcfRead = gzip.open(sys.argv[1], 'r') #open the gzipped VCF file.\noutput_file = open(sys.argv[2], 'w') #write to outputfile (unzipped).\noutput_file.write('scaffold\\tposition\\tno_het_genotypes\\tprop_het_genotypes\\tno_missing_genotypes\\n')\n\nlines = vcfRead.readlines()\n\nfor site in lines: #loop through sites in vcf file. For each site count the number of missing and heterozygous sites.\n if not site.startswith('#'):\n col = site.strip().split()\n scaffold = str(col[0])\n position = int(col[1])\n het = []\n missing = []\n for j in col:\n geno = j.split(':')[0]\n if geno == './.':\n missing.append(1)\n if re.match(\"0/[1-9]\", geno, flags=0):\n het.append(1)\n if re.match(\"[1-9]/0\", geno, flags=0):\n het.append(1)\n if re.match(\"1/[2-9]\", geno, flags=0):\n het.append(1)\n if re.match(\"2/[3-9]\", geno, flags=0):\n het.append(1)\n if re.match(\"3/[4-9]\", geno, flags=0):\n het.append(1)\n if re.match(\"4/[5-9]\", geno, flags=0):\n het.append(1)\n if re.match(\"5/[6-9]'\", geno, flags=0):\n het.append(1)\n if re.match(\"6/[7-9]'\", geno, flags=0):\n het.append(1)\n n_het = sum(het)\n n_missing = sum(missing)\n length = len(col)\n n_inds = float(length) - 9.0 - float(n_missing)\n prop_het = float(n_het) / float(n_inds)\n output_file.write('%s\\t%i\\t%i\\t%f\\t%i\\n' % (scaffold, position, n_het, prop_het, n_missing))\n \nvcfRead.close()\noutput_file.close()\n","sub_path":"countHeterozygousGenotypes.py","file_name":"countHeterozygousGenotypes.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139273204","text":"import json\nimport petname\nfrom random import randrange\n\nhead_list = ['snake', 'bull', 'lion', 'raven', 'bunny']\n\ndata = {}\ndata['animals'] = []\nfor i in range(20):\n a = randrange(2, 11, 2)\n l = randrange(3, 13, 3)\n data['animals'].append( {'head': head_list[randrange(1,5,1)], 'body': petname.name()+'-'+petname.name(), 'arms': a, 'legs': l, 'tail' : a+l} )\n\nwith open('animals.json', 'w') as out:\n json.dump(data, out, indent=2)\n","sub_path":"homework01/generate_animals.py","file_name":"generate_animals.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"570801618","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas\nimport csv\nimport webcolors\nimport os\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.neighbors import kneighbors_graph\nfrom CompiledAlgorithms.ENVI_Files import Envi\nfrom collections import Counter\nfrom datetime import datetime\nfrom CompiledAlgorithms.elbowMethod import Elbow\nimport time\nimport sys\n\n\n# Return how much time has passed since given time, rounded to 2 decimals as a string\ndef time_difference(last_time):\n return str(round(time.time() - last_time))\n\n\nclass Log:\n # RESULT_FOLDER = None # The folder where general results are stored (top-level)\n RESULT_PATH = None # The path to where results for this run are stored\n NO_RESULTS = None\n\n def __init__(self, no_results_output, result_log_path):\n # self.RESULT_FOLDER = log_path\n self.orgstdout = sys.stdout\n self.NO_RESULTS = no_results_output\n self.RESULT_PATH = result_log_path\n\n def flush(self):\n self.orgstdout.flush()\n\n # Called by sys.stdout.write, or print()\n # Used to write the console output to log files\n def write(self, msg):\n # Print calls write twice, once with the message, and once with an empty new line, which messes up the log,\n # so this ignores any newline only messages. This is a messy solution\n if msg == \"\\n\":\n return\n\n self.orgstdout.write(msg) # Print the output to the console, as we have overridden this functionality\n now = datetime.now()\n time_string = now.strftime(\"%H-%M-%S\") # Get the current time in 24hr format as string\n # Disabled latest-log\n # if os.path.isdir(self.RESULT_FOLDER): # Ensure folder for latest-log.txt exists\n # # mode 'a' will create thee file if it does not exist\n # with open(self.RESULT_FOLDER + \"latest-log.txt\", mode='a') as log:\n # log.write(time_string + \": \" + str(msg)) # Write the current time and append the message\n if not self.NO_RESULTS and os.path.isdir(self.RESULT_PATH): # Ensure we are storing results, and the dir exists\n with open(self.RESULT_PATH + \"\\\\log.txt\", mode='a') as log:\n log.write(time_string + \": \" + str(msg))\n\n\n# Runs this clustering algorithm from the command line with prompts/user input\ndef run_cml():\n text = input(\"Enter Image Path (Start with * to enter custom directory), \"\n \"\\ncluster override: -c#, n_neighbors override: -n#, \"\n \"\\nDecimate Factor: -d#, No Results: -nr: \").split()\n if text[0].startswith(\"*\"):\n image = text[1:]\n else:\n image = \"ENVI_Files\\\\Images\\\\\" + text[0]\n\n clusters = 0\n n_neighbors = 0\n decimate = 1\n no_results = False\n\n for index in range(len(text) - 1):\n if text[index + 1].startswith(\"-c\"):\n clusters = int(text[index + 1][2:])\n elif text[index + 1] == \"-nr\":\n no_results = True\n elif text[index + 1].startswith(\"-n\"):\n n_neighbors = int(text[index + 1][2:])\n elif text[index + 1].startswith(\"-d\"):\n decimate = int(text[index + 1][2:])\n\n hca = HierarchicalClusterAlgorithm(image, clusters, n_neighbors, decimate, no_results)\n\n\nclass HierarchicalClusterAlgorithm:\n CLUSTERS = None\n IMAGE = None\n LABELS = None\n WAVELENGTHS = None\n CENTROIDS = None\n PATH_TO_ENVI = None\n ENVI_NAME = None\n RESULT_PATH = None # The path to where results for this run are stored\n nNEIGHBORS = None\n is_cluster_override = False\n is_n_neighbors_override = False\n NO_RESULTS = False\n DECIMATE = 1\n\n # Takes in the image path, and cluster/n_neighbors overrides > 0\n def __init__(self, image_file, image_name, result_folder, cluster_override=0, n_neighbors_override=0, decimate_factor=1,\n no_results_output=False):\n\n try:\n self.RESULT_PATH = result_folder\n # Make the Results folder if it does not exist.\n # Necessary for the latest-log file to be created.\n # if not os.path.isdir(self.RESULT_PATH):\n # try:\n # os.makedirs(self.RESULT_PATH)\n # except OSError:\n # print(\"COULD NOT MAKE RESULTS FOLDER, NO DATA WILL BE SAVED\")\n\n self.IMAGE = image_file\n self.origImage = image_file\n self.PATH_TO_ENVI = image_file\n\n # name = str(self.PATH_TO_ENVI).split(\"\\\\\")\n # name = str(name[len(name) - 1])\n self.ENVI_NAME = image_name\n\n # Not using latest-log, commenting out all occurrences\n # Clear the latest-log file if it exists\n # if os.path.isfile(self.RESULT_FOLDER + \"latest-log.txt\"):\n # open(self.RESULT_FOLDER + \"latest-log.txt\", mode='w')\n\n if no_results_output:\n mkdir_result = \"Not saving results\"\n self.NO_RESULTS = True\n else:\n # mkdir_result = self.make_result_dir()\n # Not making a new results directory if it already exists, as the GUI should create it now\n if os.path.isdir(self.RESULT_PATH):\n mkdir_result = \"Saving results to: \" + self.RESULT_PATH\n else:\n # GUI did not make result directory, terminating\n return\n # mkdir_result = self.make_result_dir() # In case the GUI fails to make the directory\n\n sys.stdout = Log(self.NO_RESULTS, self.RESULT_PATH)\n\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%m-%d-%Y %H-%M-%S\")\n self.log(\"Starting at: \" + dt_string + \"\\nLogging is Hr/Min/Sec (24hrs)\\n\")\n self.log(mkdir_result)\n\n if cluster_override > 0:\n self.is_cluster_override = True\n self.CLUSTERS = cluster_override\n self.log(\"Clusters count overridden to be: \" + str(cluster_override))\n\n if n_neighbors_override > 0:\n self.is_n_neighbors_override = True\n self.nNEIGHBORS = n_neighbors_override\n self.log(\"n_neighbors count overridden to be: \" + str(n_neighbors_override))\n\n if decimate_factor > 1:\n self.DECIMATE = int(decimate_factor)\n self.log(\"Set Decimate Factor to be: \" + str(decimate_factor))\n\n total_time = time.time()\n self.cluster()\n if not self.NO_RESULTS:\n self.make_csv()\n self.log(\"Clustering complete, took: \" + time_difference(total_time) + \"s\")\n self.plot()\n\n except Exception as e:\n sys.stdout.write(\"A fatal exception occurred, Error:\\n%s\" % e)\n\n def log(self, message):\n sys.stdout.write(message + \"\\n\")\n\n # def make_result_dir(self):\n # now = datetime.now()\n # # dd/mm/YY H:M:S\n # dt_string = now.strftime(\"%m-%d-%Y %H-%M-%S\")\n #\n # temp_path = self.RESULT_FOLDER + self.ENVI_NAME + \" \" + dt_string\n # if os.path.isdir(temp_path):\n # name_index = 1\n # while os.path.isdir(temp_path + str(name_index)):\n # try:\n # os.makedirs(temp_path + str(name_index))\n # except OSError:\n # return \"Failed to create duplicate directory for files\"\n # else:\n # temp_path += name_index\n # self.RESULT_PATH = temp_path\n # return \"Duplicate directory created for files: \" + self.RESULT_PATH\n # else:\n # try:\n # os.makedirs(temp_path)\n # except OSError:\n # return \"Failed to create directory for files\"\n # else:\n # self.RESULT_PATH = temp_path\n # return \"Directory created for files: \" + self.RESULT_PATH\n\n def cluster(self):\n \"\"\"\n #read jpg, png or jfif image using cv2\n img = cv2.imread(self.IMAGE)\n #convert from BGR to RGB numpy arrays\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n \"\"\"\n\n ei = Envi.EnviImage()\n ei.Read(self.IMAGE, True, False, False)\n\n fig = plt.figure(frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n plt.imshow(ei.Pixels[:, :, 2])\n\n if not self.NO_RESULTS:\n plt.savefig(self.RESULT_PATH + self.ENVI_NAME + \"_OriginalImage.png\", bbox_inches=\"tight\", pad_inches=0)\n\n if self.DECIMATE > 1:\n NL = np.array(ei.wavelength, copy=False).shape[-1]\n if self.DECIMATE <= NL // 2:\n self.log(\"Decimating... Length before: \" + str(len(ei.wavelength)))\n decimate_result = ei.DecimateSpectrum(self.DECIMATE)\n self.log(\"Decimating complete, Length now: \" + str(len(ei.wavelength)))\n if not decimate_result:\n self.log(\"An error occurred while decimating\")\n else:\n plt.figure()\n plt.imshow(ei.Pixels[:, :, 2])\n plt.title(\"Decimated Image\")\n if not self.NO_RESULTS:\n plt.savefig(self.RESULT_PATH + self.ENVI_NAME + \"_DecimatedImage.png\")\n else:\n self.log(\"The decimate factor is too large, must be equal to or less than: \" + str(NL // 2))\n\n self.origImage = ei.Pixels\n self.WAVELENGTHS = ei.wavelength\n\n img = []\n\n # reshapes image into 2D array shape (x*y, z)\n # Hierarchical only takes in 2D arrays\n for y in range(ei.Pixels.shape[1]):\n for x in range(ei.Pixels.shape[0]):\n img.append(ei.Pixels[x, y, :])\n img = np.array(img)\n\n # img = img.reshape((ei.Pixels.shape[0] * ei.Pixels.shape[1], ei.Pixels.shape[2]))\n self.IMAGE = img\n\n # Hierarchical clustering\n\n # get cluster amount with kmeans\n if self.is_cluster_override:\n self.log(\"Clusters overridden, skipping elbow method and using: \" + str(self.CLUSTERS) + \" clusters\")\n else:\n st = time.time()\n self.log(\"Starting Elbow Method...\")\n self.CLUSTERS = Elbow().elbowMethod(self.IMAGE)\n self.log(\"Elbow Method complete, took: \" + str(round(time.time() - st, 2)) + \"s\")\n self.log(\"Final cluster size: \" + str(self.CLUSTERS))\n\n # sets the connectivity, too resource intensive without\n st = time.time()\n self.log(\"Creating kneighbors_graph...\")\n\n if self.is_n_neighbors_override:\n self.log(\"n_neighbors overridden, using: \" + str(self.nNEIGHBORS))\n n_neighbors = self.nNEIGHBORS\n else:\n # Source for n_neighbors = clusters squared\n # I recommend searching for a better way to do this, or at least make it configurable by the user\n # https://bioinformatics.stackexchange.com/questions/4248/how-to-decide-number-of-neighbors-and-resolution-for-louvain-clustering\n n_neighbors = pow(self.CLUSTERS, 2)\n\n knn_graph = kneighbors_graph(img, n_neighbors, include_self=False)\n self.log(\"kneighbors_graph created, n_neighbors: \" + str(n_neighbors) + \", took: \" + time_difference(st) + \"s\")\n\n self.log(\"Starting Hierarchical Clustering (This may take a while)...\")\n\n # set up the clustering with its parameters\n st = time.time()\n hierarchical = AgglomerativeClustering(n_clusters=self.CLUSTERS, linkage='ward', connectivity=knn_graph)\n hierarchical.fit(img) # do the clustering\n self.log(\"Hierarchical Clustering complete, took: \" + time_difference(st) + \"s\")\n\n self.LABELS = hierarchical.labels_\n self.make_avg_labels()\n\n def closest_colour(self, requested_colour):\n min_colours = {}\n for key, name in webcolors.css3_hex_to_names.items():\n r_c, g_c, b_c = webcolors.hex_to_rgb(key)\n rd = (r_c - requested_colour[0]) ** 2\n gd = (g_c - requested_colour[1]) ** 2\n bd = (b_c - requested_colour[2]) ** 2\n min_colours[(rd + gd + bd)] = name\n return min_colours[min(min_colours.keys())]\n\n def plot(self):\n self.log(\"Plotting...\")\n points = self.origImage\n k = self.CLUSTERS\n labels = self.LABELS\n color_key = []\n color_choices = [[0, 1, 0], [1, 0, 0], [0, .5, 1], [0, .5, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1], [0, 0, 1],\n [.5, .5, .5], [.5, .5, 1]]\n for center in range(k):\n # randColor = [rand.randint(0, 255), rand.randint(0, 255), rand.randint(0, 255)]\n rand_color = color_choices[center]\n color_key.append(rand_color)\n c = 0\n new_img = np.zeros((points.shape[0], points.shape[1], 3))\n for y in range(new_img.shape[1]):\n for x in range(new_img.shape[0]):\n new_img[x, y] = color_key[labels[c]]\n c += 1\n\n # Plots the 3D graph using R G B list collected from above and use colors from the clusters list\n fig = plt.figure(frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n plt.imshow(new_img)\n\n if not self.NO_RESULTS:\n plt.savefig(self.RESULT_PATH + self.ENVI_NAME + \"_ClusteredImage.png\", bbox_inches=\"tight\", pad_inches=0)\n\n plt.figure()\n plt.ylabel('Absorption')\n plt.xlabel('Wavenumbers')\n plt.title(\"Wavenumbers vs Absorption For Each Center(Hierarchical)\")\n for x in range(k):\n temp_color = [rgb * 255 for rgb in color_choices[x]]\n self.log(self.closest_colour(temp_color) + \": \" + str(self.CENTROIDS[x]))\n plt.plot(self.WAVELENGTHS, self.CENTROIDS[x], color=color_choices[x], marker=\"o\",\n label=\"Center \" + str(x + 1))\n plt.legend()\n\n if not self.NO_RESULTS:\n plt.savefig(self.RESULT_PATH + \"\\\\\" + self.ENVI_NAME + \"_ClusteredAbsorptionGraph.png\")\n\n #plt.show()\n\n # Return a 2D list of the average wavelengths for each cluster\n def make_avg_labels(self):\n\n st = time.time()\n self.log(\"Calculating cluster averages...\")\n\n # Get amount of wavelengths per pixel\n wavelengths = len(self.IMAGE[0])\n\n # Create list to store the avg values for each cluster, for each wavelength\n avg_labels = np.zeros((self.CLUSTERS, wavelengths))\n\n index = 0 # Store current position in image pixels\n # Loop through the label list\n for label in self.LABELS:\n for x in range(wavelengths):\n # Add the corresponding IMAGE pixel values to the sum\n avg_labels[label][x] += self.IMAGE[index][x]\n index += 1\n\n # Count the occurrences of each label, and store them in a list\n x = Counter(sorted(self.LABELS))\n values = np.array(list(x.values()))\n\n # Divide each sum by its label total\n for label in range(self.CLUSTERS):\n avg_labels[label] /= values[label]\n\n # Round to 2 decimals\n avg_labels = avg_labels.round(2)\n self.CENTROIDS = avg_labels\n self.log(\"Cluster averages calculated, took: \" + time_difference(st) + \"s\")\n\n def make_csv(self):\n csv_file_path = self.RESULT_PATH + self.ENVI_NAME + \".csv\"\n\n with open(csv_file_path, mode='w+', newline='') as csvFile:\n fieldnames = [\"Wavenumber\"]\n centers = self.CENTROIDS\n for x in range(len(centers)):\n fieldnames.append(\"Cluster \" + str(x + 1))\n writer = csv.DictWriter(csvFile, fieldnames=fieldnames)\n writer.writeheader()\n for wl in self.WAVELENGTHS:\n temp_dict = {\"Wavenumber\": wl}\n for x in range(len(centers)):\n temp_dict[\"Cluster \" + str(x + 1)] = centers[x][self.WAVELENGTHS.index(wl)]\n writer.writerow(temp_dict)\n df = pandas.read_csv(csv_file_path)\n self.log(\"\\n\" + str(df))\n","sub_path":"CompiledAlgorithms/HierarchicalAlgorithm.py","file_name":"HierarchicalAlgorithm.py","file_ext":"py","file_size_in_byte":16177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"267579537","text":"import csv\r\nimport math\r\nimport copy\r\n\r\n\r\ndef Entropy(volume_once_property, data): # энтропия выборочного поля\r\n ent = 0\r\n for i in data:\r\n if float(i) > 0:\r\n ent += -(float(i) / float(volume_once_property)) * math.log((float(i) / float(volume_once_property)), 2)\r\n return ent\r\n\r\n\r\ndef Entropy_base_property(data): # энтропия базового поля\r\n ent = 0\r\n dict_base_property = dict() # подсчет общих свойств {'Sunny': 5, 'Overcast': 4, 'Rain': 5}\r\n\r\n for i in data:\r\n dict_base_property[i] = 0\r\n\r\n for i in data:\r\n dict_base_property[i] += 1\r\n\r\n for i in dict_base_property.values():\r\n ent += -i / len(data) * math.log((i / len(data)), 2)\r\n\r\n return ent\r\n\r\n\r\ndef Gain(sample_property, base_property):\r\n ent = Entropy_base_property(base_property)\r\n\r\n dict_sample_property = dict() # подсчет общих свойств {'Sunny': 5, 'Overcast': 4, 'Rain': 5}\r\n\r\n for i in sample_property:\r\n dict_sample_property[i] = 0\r\n\r\n for i in sample_property:\r\n dict_sample_property[i] += 1\r\n\r\n dict_simple_of_base_property = dict() # подсчет свойств относительного базового свойства\r\n # {'SunnyNo': 3, 'SunnyYes': 2, 'OvercastNo': 0, 'OvercastYes': 4, 'RainNo': 2, 'RainYes': 3}\r\n\r\n for i in sample_property:\r\n for j in base_property:\r\n dict_simple_of_base_property[i + j] = 0\r\n\r\n for i in range(len(sample_property)):\r\n dict_simple_of_base_property[sample_property[i] + base_property[i]] += 1\r\n\r\n dict_entropy_sample_property = dict() # энтропия по значениям dict_simple_of_base_property\r\n\r\n for i in dict_sample_property:\r\n interim_set = []\r\n for j in dict_simple_of_base_property:\r\n if i in j:\r\n interim_set.append(dict_simple_of_base_property[j])\r\n dict_entropy_sample_property[i] = Entropy(dict_sample_property[i], interim_set)\r\n\r\n for i in dict_entropy_sample_property:\r\n a = dict_sample_property[i] / len(sample_property)\r\n b = dict_entropy_sample_property[i]\r\n ent -= a * b\r\n\r\n return ent\r\n\r\n\r\ndef definition_sign(data):\r\n ent = []\r\n base_property = []\r\n data_copy = copy.deepcopy(data)\r\n\r\n for i in range(len(data[0]) - 1, len(data[0])): # отделение последнего столбца\r\n for j in range(len(data)):\r\n base_property.append(data[j][i])\r\n del data_copy[j][i]\r\n\r\n for i in range(len(data_copy[0])): # len(data1[0]) определение прироста информации столбцов\r\n column_sample_property = []\r\n for j in range(len(data_copy)):\r\n column_sample_property.append(data_copy[j][i])\r\n ent.append(Gain(column_sample_property, base_property))\r\n\r\n return ent\r\n\r\n\r\ndef check(data):\r\n set_check = set()\r\n\r\n for i in range(len(data[0]) - 1, len(data[0])):\r\n for j in range(len(data)):\r\n set_check.add(data[j][i])\r\n\r\n if (len(set_check) != 1):\r\n return True\r\n else:\r\n return False\r\n\r\ndef solve(data):\r\n set_check = set()\r\n\r\n for i in range(len(data[0]) - 1, len(data[0])):\r\n for j in range(len(data)):\r\n set_check.add(data[j][i])\r\n\r\n return set_check.pop()\r\n\r\n\r\ndef id3(data):\r\n\r\n if check(data):\r\n entropy_data = definition_sign(data)\r\n partition_property = set() # уникальные занчения по разбиваемому свойству\r\n data_update = [] # новые данные после разбиения\r\n node = []\r\n\r\n for i in range(len(data)): # определение уникальных значений\r\n partition_property.add(data[i][entropy_data.index(max(entropy_data))])\r\n\r\n for i in partition_property: # разбиение данных\r\n table = []\r\n for j in data:\r\n if i == j[entropy_data.index(max(entropy_data))]:\r\n del j[entropy_data.index(max(entropy_data))]\r\n table.append(j)\r\n node.append({i : table})\r\n data_update.append(table)\r\n\r\n for i in node:\r\n for j in i:\r\n i[j] = id3(i[j])\r\n\r\n return node\r\n else:\r\n return solve(data)\r\n\r\n\r\ndef run(test, tree):\r\n answer = ''\r\n if test:\r\n for i in tree:\r\n for j in i:\r\n if test[0] == j:\r\n test.pop(0)\r\n run(test, i[j])\r\n break\r\n test.pop(0)\r\n run(test, tree)\r\n return answer\r\n else:\r\n answer = tree\r\n return answer\r\n\r\n\r\ndef main():\r\n data = []\r\n\r\n with open('data.csv', 'r') as file:\r\n reader = csv.reader(file, delimiter=';')\r\n for row in reader:\r\n data.append(row)\r\n\r\n tree = id3(data)\r\n\r\n test = ['Sunny', 'Hot', 'High', 'Week']\r\n\r\n # print(tree)\r\n\r\n print(run(test, tree))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Generic tree.py","file_name":"Generic tree.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"143199006","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 6 19:38:30 2017\n\n@author: diegodrc\nessa solucao nao foi criada pelo autor\n\"\"\"\n\ndef printMove(fr, to):\n print('move from ' + str(fr) + ' to ' + str(to))\n\ndef Towers(n, fr, to, spare):\n if n == 1:\n printMove(fr, to)\n else:\n Towers(n-1, fr, spare, to)\n Towers(1, fr, to, spare)\n Towers(n-1, spare, to, fr)\n\nprint(Towers(4,'P1','P2','P3'))","sub_path":"Week 2/4/hanoi.py","file_name":"hanoi.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496393498","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/yarlp/external/baselines/baselines/acktr/running_stat.py\n# Compiled at: 2018-04-01 14:21:44\n# Size of source mod 2**32: 1320 bytes\nimport numpy as np\n\nclass RunningStat(object):\n\n def __init__(self, shape):\n self._n = 0\n self._M = np.zeros(shape)\n self._S = np.zeros(shape)\n\n def push(self, x):\n x = np.asarray(x)\n assert x.shape == self._M.shape\n self._n += 1\n if self._n == 1:\n self._M[...] = x\n else:\n oldM = self._M.copy()\n self._M[...] = oldM + (x - oldM) / self._n\n self._S[...] = self._S + (x - oldM) * (x - self._M)\n\n @property\n def n(self):\n return self._n\n\n @property\n def mean(self):\n return self._M\n\n @property\n def var(self):\n if self._n > 1:\n return self._S / (self._n - 1)\n return np.square(self._M)\n\n @property\n def std(self):\n return np.sqrt(self.var)\n\n @property\n def shape(self):\n return self._M.shape\n\n\ndef test_running_stat():\n for shp in ((), (3, ), (3, 4)):\n li = []\n rs = RunningStat(shp)\n for _ in range(5):\n val = np.random.randn(*shp)\n rs.push(val)\n li.append(val)\n m = np.mean(li, axis=0)\n assert np.allclose(rs.mean, m)\n v = np.square(m) if len(li) == 1 else np.var(li, ddof=1, axis=0)\n if not np.allclose(rs.var, v):\n raise AssertionError","sub_path":"pycfiles/yarlp-0.1.0-py3.5/running_stat.cpython-35.py","file_name":"running_stat.cpython-35.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"161861406","text":"\"\"\"Django authentication backends.\n\nFor more information visit https://docs.djangoproject.com/en/dev/topics/auth/customizing/.\n\"\"\"\nimport json\n\nfrom django.conf import settings\nimport django.dispatch\nfrom social.backends.open_id import OpenIdConnectAuth\n\n\n# pylint: disable=abstract-method\nclass EdXOpenIdConnect(OpenIdConnectAuth):\n name = 'edx-oidc'\n\n ACCESS_TOKEN_METHOD = 'POST'\n REDIRECT_STATE = False\n ID_KEY = 'preferred_username'\n\n DEFAULT_SCOPE = ['openid', 'profile', 'email'] + getattr(settings, 'EXTRA_SCOPE', [])\n ID_TOKEN_ISSUER = getattr(settings, 'SOCIAL_AUTH_EDX_OIDC_URL_ROOT', None)\n AUTHORIZATION_URL = '{0}/authorize/'.format(ID_TOKEN_ISSUER)\n ACCESS_TOKEN_URL = '{0}/access_token/'.format(ID_TOKEN_ISSUER)\n USER_INFO_URL = '{0}/user_info/'.format(ID_TOKEN_ISSUER)\n\n PROFILE_TO_DETAILS_KEY_MAP = {\n 'preferred_username': u'username',\n 'email': u'email',\n 'name': u'full_name',\n 'given_name': u'first_name',\n 'family_name': u'last_name',\n 'locale': u'language',\n }\n\n auth_complete_signal = django.dispatch.Signal(providing_args=[\"user\", \"id_token\"])\n\n def user_data(self, _access_token, *_args, **_kwargs):\n # Include decoded id_token fields in user data.\n return self.id_token\n\n def auth_complete_params(self, state=None):\n params = super(EdXOpenIdConnect, self).auth_complete_params(state)\n\n # TODO: Due a limitation in the OIDC provider in the LMS, the list of all course permissions\n # is computed during the authentication process. As an optimization, we explicitly request\n # the list here, avoiding further roundtrips. This is no longer necessary once the limitation\n # is resolved and instead the course permissions can be requested on a need to have basis,\n # reducing overhead significantly.\n claim_names = getattr(settings, 'COURSE_PERMISSIONS_CLAIMS', [])\n courses_claims_request = {name: {'essential': True} for name in claim_names}\n params['claims'] = json.dumps({'id_token': courses_claims_request})\n\n return params\n\n def auth_complete(self, *args, **kwargs):\n # WARNING: During testing, the user model class is `social.tests.models` and not the one\n # specified for the application.\n user = super(EdXOpenIdConnect, self).auth_complete(*args, **kwargs)\n self.auth_complete_signal.send(sender=self.__class__, user=user, id_token=self.id_token)\n return user\n\n def get_user_claims(self, access_token, claims=None):\n \"\"\"Returns a dictionary with the values for each claim requested.\"\"\"\n data = self.get_json(\n self.USER_INFO_URL,\n headers={'Authorization': 'Bearer {0}'.format(access_token)}\n )\n\n if claims:\n claims_names = set(claims)\n data = {k: v for (k, v) in data.iteritems() if k in claims_names}\n\n return data\n\n def get_user_details(self, response):\n details = self._map_user_details(response)\n\n # Limits the scope of languages we can use\n locale = response.get('locale')\n if locale:\n details[u'language'] = _to_language(response['locale'])\n\n # Set superuser bit if the provider determines the user is an administrator\n details[u'is_superuser'] = details[u'is_staff'] = response.get('administrator', False)\n\n return details\n\n def _map_user_details(self, response):\n \"\"\"Maps key/values from the response to key/values in the user model.\n\n Does not transfer any key/value that is empty or not present in the reponse.\n \"\"\"\n dest = {}\n for source_key, dest_key in self.PROFILE_TO_DETAILS_KEY_MAP.items():\n value = response.get(source_key)\n if value is not None:\n dest[dest_key] = value\n\n return dest\n\n\ndef _to_language(locale):\n \"\"\"Convert locale name to language code if necessary.\n\n OpenID Connect locale needs to be converted to Django's language\n code. In general however, the differences between the locale names\n and language code are not very clear among different systems.\n\n For more information, refer to:\n http://openid.net/specs/openid-connect-basic-1_0.html#StandardClaims\n https://docs.djangoproject.com/en/1.6/topics/i18n/#term-translation-string\n \"\"\"\n return locale.replace('_', '-').lower()\n","sub_path":"app/insights/venvs/insights/lib/python2.7/site-packages/auth_backends/backends.py","file_name":"backends.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364685976","text":"__author__ = 'changyunglin'\nfrom Tkinter import *\n\nclass CalcGUI(Frame):\n def __init__(self, parent=None):\n Frame.__init__(self, parent)\n self.pack(expand=YES, fill=BOTH)\n self.master.title('Python Calculator')\n self.master.iconname('calc')\n self.text_box = Entry(self, justify=RIGHT)\n self.text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)\n self.text_box.insert(0, \"0\")\n # self.text = StringVar()\n self.createWidget()\n # self.total = 0\n # self.current = \"\"\n # self.new_num = True\n # self.op_pending = False\n # self.op = \"\"\n # self.eq_flag = False\n\n def btn_cmd(self, num):\n self[\"command\"] = lambda: self.num_press(num)\n\n def frame(self, side=TOP):\n widget = self\n widget.pack(side=side, expand=YES, fill=BOTH)\n return widget\n\n def button(self, side, text, command):\n b = Button(self, text=text, command=command)\n b.pack(side=side, expand=YES, fill=BOTH)\n return b\n\n\n\n def createWidget(self):\n rows = [\"789\", \"456\", \"123\"]\n text = StringVar()\n for row in rows:\n for char in row:\n self.button(side=LEFT, text=char, command=lambda char=char: text.set(text.get() + char))\n\n self.bttn_0 = Button(self, text = \"0\")\n self.bttn_0[\"command\"] = lambda: self.num_press(0)\n self.bttn_0.grid(row = 4, column = 1, pady = 5)\n\n self.bttn_div = Button(self, text = chr(247))\n self.bttn_div[\"command\"] = lambda: self.operation(\"divide\")\n self.bttn_div.grid(row = 1, column = 3, pady = 5)\n\n self.bttn_mult = Button(self, text = \"x\")\n self.bttn_mult[\"command\"] = lambda: self.operation(\"times\")\n self.bttn_mult.grid(row = 2, column = 3, pady = 5)\n\n self.minus = Button(self, text = \"-\")\n self.minus[\"command\"] = lambda: self.operation(\"minus\")\n self.minus.grid(row = 3, column = 3, pady = 5)\n\n self.point = Button(self, text = \".\")\n self.point[\"command\"] = lambda: self.num_press(\".\")\n self.point.grid(row = 4, column = 0, pady = 5)\n\n self.add = Button(self, text = \"+\")\n self.add[\"command\"] = lambda: self.operation(\"add\")\n self.add.grid(row = 4, column = 3, pady = 5)\n\n self.neg= Button(self, text = \"+/-\")\n self.neg[\"command\"] = self.sign\n self.neg.grid(row = 5, column = 0, pady = 5)\n\n self.clear = Button(self, text = \"C\")\n self.clear[\"command\"] = self.cancel\n self.clear.grid(row = 5, column = 1, pady = 5)\n\n self.all_clear = Button(self, text = \"AC\")\n self.all_clear[\"command\"] = self.all_cancel\n self.all_clear.grid(row = 5, column = 2, pady = 5)\n\n self.equals = Button(self, text = \"=\")\n self.equals[\"command\"] = self.calc_total\n self.equals.grid(row = 5, column = 3, pady = 5)\n\n def num_press(self, num):\n temp = self.text_box.get()\n self.eq_flag = False\n temp2 = str(num)\n if self.new_num == True:\n self.current = temp2\n self.new_num = False\n else:\n if temp2 == '.':\n if temp2 in temp:\n return\n self.current = temp + temp2\n self.text_box.delete(0, END)\n self.text_box.insert(0, self.current)\n\n def calc_total(self):\n if self.op_pending == True:\n self.do_sum()\n self.op_pending = False\n\n def do_sum(self):\n self.current = float(self.current)\n if self.op == \"add\":\n self.total += self.current\n if self.op == \"minus\":\n self.total -= self.current\n if self.op == \"times\":\n self.total *= self.current\n if self.op == \"divide\":\n self.total /= self.current\n self.text_box.delete(0, END)\n self.text_box.insert(0, self.total)\n self.new_num = True\n\n def operation(self, op):\n if self.op_pending == True:\n self.do_sum()\n self.op = op\n else:\n self.op_pending = True\n if self.eq_flag == False:\n self.total = float(self.text_box.get())\n else:\n self.total = self.current\n self.new_num = True\n self.op = op\n self.eq_flag = False\n\n def cancel(self):\n self.text_box.delete(0, END)\n self.text_box.insert(0, \"0\")\n self.new_num = True\n\n def all_cancel(self):\n self.cancel()\n self.total = 0\n\n def sign(self):\n self.current = -(float(self.text_box.get()))\n self.text_box.delete(0, END)\n self.text_box.insert(0, self.current)\n\nroot = Tk()\napp = CalcGUI(root)\nroot.mainloop()\n# sum1 = CalcGUI()\n# root = Tk()\n# text_box = Entry(calc, justify=RIGHT)\n# text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)\n# text_box.insert(0, \"0\")\n#\n# # make the buttons\n# numbers = \"789456123\"\n# i = 0\n# bttn = []\n# for j in range(1,4):\n# for k in range(3):\n# bttn.append(My_Btn(calc, text = numbers[i]))\n# bttn[i].grid(row = j, column = k, pady = 5)\n# bttn[i].btn_cmd(numbers[i])\n# i += 1\n#\n#\n# root.mainloop()\n","sub_path":"GUI/demo_gui_cal.py","file_name":"demo_gui_cal.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"411198630","text":"import math\n\n\ndef findNum(high, low):\n while high >= low:\n mid = (low + high) / 2\n print(\"if found=1 / if less=2 /if greater=3\")\n print(\"Your num is ?\", mid)\n ch = int(input())\n if ch == 1:\n print(mid)\n break\n else:\n if ch == 2:\n high = mid - 1\n print(\"Your num is ?\", mid)\n else:\n low = mid + 1\n print(\"Your num is ?\", mid)\n\n\nnum = int(input(\"Enter a num 0 -5\"))\nele = int(math.pow(2, num))\nlow = 0\nhigh = ele\nprint(\"low\", low, \"high\", high)\nfindNum(high, low)\n","sub_path":"new/week1/Alogrith/FindNum.py","file_name":"FindNum.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"356988904","text":"# author : forestkeep21@naver.com\n\nfrom datetime import timedelta\nimport os\n\nbase_dir = os.path.abspath(os.path.dirname(__file__))\n\nWTF_CSRF_ENABLED = True\nSECRET_KEY = os.urandom(24)\nPERMANENT_SESSION_LIFETIME = timedelta(minutes=30)\n\n# db setting\nSQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(os.path.join(base_dir, 'app.db'))\nSQLALCHEMY_MIGRATE_REPO = os.path.join(base_dir, 'db_repository')\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"23717479","text":"from project import get_project_data, save_project_data\nfrom settings import update_run_status\nimport uuid\nimport subprocess\nimport config\nimport os\nfrom logger import logger\nimport sys\n\n\navailable_inputs = []\n\ndef get_network_data(project_settings):\n\tnetwork_data = {}\n\tproject_data = get_project_data(project_settings)\n\tfirst_node_names = [f[\"name\"] for f in get_first_nodes(project_settings)]\n\t#print(first_nodes)\n\tnodes = []\n\tedges = []\n\tif \"nodes\" in project_data:\n\t\tfor node in project_data[\"nodes\"]:\n\t\t\tnodes.append(to_network_node(project_settings, first_node_names, node))\n\tif \"edges\" in project_data:\n\t\tfor edge in project_data[\"edges\"]:\n\t\t\tedges.append(to_network_edge(project_settings, edge))\n\tnetwork_data[\"nodes\"] = nodes\n\tnetwork_data[\"edges\"] = edges\n\treturn network_data\n \n\ndef get_settings_file(project_settings, filename):\n\n\tfor file in project_settings[\"files\"]:\n\t\tif file[\"name\"] == filename:\n\t\t\treturn file\n\treturn None\n\n\ndef set_node_values(settings_file, node):\n\t\n\tif not \"assigned_to\" in node[\"data\"] or node[\"data\"][\"assigned_to\"] == \"\":\n\t\tnode[\"data\"][\"assigned_to\"] = \"not assigned\"\n\n\tif not \"task_status\" in node[\"data\"] or node[\"data\"][\"task_status\"] == \"\":\n\t\tnode[\"data\"][\"task_status\"] = \"not started\" \n\n\tif node[\"data\"][\"name\"].endswith(\".R\"):\n\t\tbgImage = \"R_not_started.png\"\n\telif node[\"data\"][\"name\"].endswith(\".csv\"):\n\t\tbgImage = \"csv_not_started.png\"\n\telse:\n\t\tbgImage = \"plot_not_started.png\"\n\n\tif settings_file:\n\t\t\n\t\tif node[\"data\"][\"name\"].endswith(\".R\"):\n\t\t\tif \"run_status\" in settings_file and settings_file[\"run_status\"] == \"failure\":\n\t\t\t\tbgImage = \"R_failed.png\"\n\t\t\telif node[\"data\"][\"task_status\"] == \"completed\":\n\t\t\t\tbgImage = \"R_completed.png\"\n\t\t\telif node[\"data\"][\"task_status\"] in [\"in progress\", \"validating\"]:\n\t\t\t\tbgImage = \"R_in_progress.png\"\n\n\t\telif node[\"data\"][\"name\"].endswith(\".csv\"):\n\t\t\tif \"run_status\" in node[\"data\"] and node[\"data\"][\"run_status\"] == \"success\":\n\t\t\t\tbgImage = \"csv_completed.png\"\n\n\t\telse:\n\t\t\tif \"run_status\" in node[\"data\"] and node[\"data\"][\"run_status\"] == \"success\":\n\t\t\t\tbgImage = \"plot_completed.png\"\n\n\tnode[\"data\"][\"bgImage\"] = \"static/images/\" + bgImage\n\n\treturn node\n\t\n\ndef to_network_node(project_settings, first_node_names, project_node):\n\n\tnode = {\n\t\t\"data\": project_node\n\t}\n\t\n\tnode[\"data\"][\"id\"] = node[\"data\"][\"name\"]\n\n\tsettings_file = get_settings_file(project_settings, node[\"data\"][\"name\"])\n\n\tif project_node[\"name\"].endswith(\".R\"):\n\t\tnode[\"data\"][\"shape\"] = \"ellipse\"\n\telse:\n\t\tnode[\"data\"][\"shape\"] = \"barrel\"\n\n\tnode[\"data\"][\"first_node\"] = \"true\" if node[\"data\"][\"name\"] in first_node_names else \"false\"\n\n\tnode[\"data\"][\"color\"] = \"#fff\"\n\tnode[\"data\"][\"bgColor\"] = \"#fff\"\n\n\tnode = set_node_values(settings_file, node)\n\t\n\treturn node\n\n\ndef to_network_edge(project_settings, project_edge):\n edge = {}\n edge[\"data\"] = project_edge\n edge[\"data\"][\"id\"] = str(uuid.uuid4())\n edge[\"data\"][\"bgColor\"] = \"#333333\"\n edge[\"data\"][\"color\"] = \"#333333\"\n return edge\n\n\ndef run_node(project_settings, node_name):\n\n\tlogger.info(\"running node \" + node_name)\n\n\tsuccess = False\n\n\toutputs = [] \n\n\tif node_name.endswith(\".R\"):\n\n\t\tupdate_run_status(project_settings, node_name, run_status=\"running\", stdout=\"\", stderr=\"\")\n\n\t\tpath = project_settings[\"dir\"] + \"/\" + node_name\n\n\t\tprint(\"running\", path)\n\n\t\trscript = \"Rscript\"\n\n\t\tif config.R_HOME and os.path.isdir(config.R_HOME):\n\n\t\t\trscript = config.R_HOME + \"/Rscript\"\n\n\t\tif sys.platform == \"win32\":\n\t\t\tproc = subprocess.Popen([rscript, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)\n\t\telse:\n\t\t\tproc = subprocess.Popen([rscript, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n\n\t\tstdout, stderr = proc.communicate()\n\t\treturncode = proc.returncode\n\t\t\n\t\tprint(returncode)\n\t\tprint(stdout)\n\t\tprint(stderr)\n\n\t\trun_status = \"success\"\n\n\t\tif returncode == 0:\n\t\t\tsuccess = True\n\t\t\toutputs = get_next_nodes(project_settings, node_name)\n\n\t\telse:\n\t\t\trun_status = \"failure\"\n\t\t\tlogger.error('failed ' + node_name)\n\n\t\tupdate_run_status(project_settings, node_name, run_status=run_status, returncode=returncode, stdout=stdout, stderr=stderr)\t\n\n\treturn success, outputs\n\n\ndef get_first_nodes(project_settings):\n\n\tfirst_nodes = []\n\n\tdata = get_project_data(project_settings)\n\n\tfor node in data[\"nodes\"]:\n\n\t\tif len([e for e in data[\"edges\"] if e[\"target\"] == node[\"name\"]]) == 0:\n\n\t\t\tfirst_nodes.append(node)\n\n\treturn first_nodes\n\n\ndef get_prev_nodes(project_settings, node_name):\n\n\tprev_nodes = []\n\n\tdata = get_project_data(project_settings)\n\n\tfor edge in [e for e in data[\"edges\"] if e[\"target\"] == node_name]:\n\n\t\tprev_nodes.append(get_node_from_name(project_settings, edge[\"source\"]))\n\n\treturn prev_nodes\n\n\ndef get_next_nodes(project_settings, node_name):\n\n\tnext_nodes = []\n\n\tdata = get_project_data(project_settings)\n\n\tfor edge in [e for e in data[\"edges\"] if e[\"source\"] == node_name]:\n\n\t\tnext_nodes.append(get_node_from_name(project_settings, edge[\"target\"]))\n\n\treturn next_nodes\n\n\ndef get_node_from_name(project_settings, node_name):\n\n\tdata = get_project_data(project_settings)\n\n\tfor node in data[\"nodes\"]:\n\n\t\tif node[\"name\"] == node_name:\n\n\t\t\treturn node\n\n\treturn None \n\n\ndef get_first_script_nodes(project_settings):\n\n\tscript_nodes = []\n\n\tfor node in get_first_nodes(project_settings):\n\n\t\tfor next_node in get_next_nodes(project_settings, node[\"name\"]):\n\n\t\t\tif next_node[\"name\"].endswith(\".R\"):\n\n\t\t\t\tscript_nodes.append(next_node)\n\n\treturn script_nodes\n\n\ndef is_input_available(project_settings, node):\n\n\tprev_nodes = get_prev_nodes(project_settings, node['name'])\n\n\tglobal available_inputs\n\n\tfor prev_node in prev_nodes:\n\t\tif prev_node['name'] not in [n['name'] for n in available_inputs]:\n\t\t\treturn False\n\n\treturn True\n\n\ndef get_next_script_nodes(project_settings, node_name):\n\n\tscript_nodes = []\n\n\tfor node in get_next_nodes(project_settings, node_name):\n\n\t\tfor next_node in get_next_nodes(project_settings, node[\"name\"]):\n\n\t\t\tif next_node[\"name\"].endswith(\".R\") and is_input_available(project_settings, next_node):\n\n\t\t\t\tscript_nodes.append(next_node)\n\n\treturn script_nodes\n\n\ndef run_network(project_settings):\n\n\tfirst_script_nodes = get_first_script_nodes(project_settings)\n\n\tprint(first_script_nodes)\n\n\tglobal available_inputs\n\n\tfor node in first_script_nodes:\n\n\t\tsuccess, outputs = run_node(project_settings, node[\"name\"])\n\n\t\tif success:\n\n\t\t\tavailable_inputs.extend(outputs)\n\n\t\t\trun_next_nodes(project_settings, node[\"name\"])\n\n\tavailable_inputs = []\n\n\ndef run_next_nodes(project_settings, node_name):\n\n\tnext_nodes = get_next_script_nodes(project_settings, node_name)\n\n\tglobal available_inputs\n\n\tfor node in next_nodes:\n\n\t\tsuccess, outputs = run_node(project_settings, node[\"name\"])\n\n\t\tif success:\n\n\t\t\tavailable_inputs.extend(outputs)\n\n\t\t\trun_next_nodes(project_settings, node[\"name\"])\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":6789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"277326570","text":"def remove_overlap(ranges):\n\t\"\"\"\n\t\n\tMerges overlapping ranges. Rnages are given in a format: [form, to, id]\n\t:param ranges: ranges to be merged\n\t:return: merged ranges\n\t\"\"\"\n\t\n\tresult = []\n\tcurrent_start = -float(\"inf\")\n\tcurrent_stop = -float(\"inf\")\n\n\tfor start, stop, Type in sorted(ranges, key=lambda i:i[:2]):\n\t\tType = [Type, start, stop]\n\t\t\t\t\n\t\tif start > current_stop:\n\t\t\t# this segment starts after the last segment stops\n\t\t\t# just add a new segment\n\t\t\tresult.append( (start, stop, [Type]) )\n\t\t\tcurrent_start, current_stop = start, stop\n\t\telse:\n\t\t\t# segments overlap, replace\n\t\t\toldType = result[-1][2]\n\n\t\t\t#result[-1] = (current_start, stop, list(set(oldType+[Type])))\n\t\t\t#print oldType\n\t\t\t#print Type\n\t\t\tresult[-1] = (current_start, stop, oldType+[Type])\n\t\t\t# current_start already guaranteed to be lower\n\t\t\tcurrent_stop = max(current_stop, stop)\n\n\treturn result\n \ndef calc_sov(true, pred, label='I', calc_sigma=True):\n\t\"\"\"\n\t:param true: true assignment\n\t:param pred: predicted assignment\n\t:param label: label for which SOV is calculated\n\t:param calc_sigma: determines whether sigma factor is calculated\n\t:return: SOV value for protein\n\t\"\"\"\n\n\tassert len(true) == len(pred)\n\tif true.count(label) > 0:\n\t\tNcc = 0\n\t\ttrue_segments = []\n\t\tc = 0\n\t\tfor match in re.finditer(r\"([%s]+)\" % label, true):\n\t\t\ttrue_segments.append([])\n\t\t\tfor i in range(match.start(), match.end()):\n\t\t\t\ttrue_segments[c].append(i)\n\t\t\tc += 1\n\t\tc = 0\n\t\tpred_segments = []\n\t\tfor match in re.finditer(r\"([%s]+)\" % label, pred):\n\t\t\tpred_segments.append([])\n\t\t\tfor i in range(match.start(), match.end()):\n\t\t\t\tpred_segments[c].append(i)\n\t\t\tc += 1\n\t\tsumm = 0\n\t\tfor segment in true_segments:\n\t\t\tmatching_segment = False\n\t\t\tfor segment2 in pred_segments:\n\t\t\t\tminov = len((set(segment) & set(segment2)))\n\t\t\t\tmaxov = len((set(segment) | set(segment2)))\n\t\t\t\tif minov > 0:\n\t\t\t\t\tNcc += len(segment)\n\t\t\t\t\tmatching_segment = True\n\t\t\t\t\tlen_s1_adj = int(0.5 * len(segment))\n\t\t\t\t\tlen_s2_adj = int(0.5 * len(segment2))\n\t\t\t\t\tsigma = min(maxov - minov, minov, len_s1_adj, len_s2_adj)\n\t\t\t\t\tif not calc_sigma:\n\t\t\t\t\t\tsigma = 0\n\t\t\t\t\tsumm += float(len(segment) * (minov + sigma) / maxov)\n\t\t\tif not matching_segment:\n\t\t\t\tNcc += len(segment)\n\t\treturn (float(summ / Ncc))","sub_path":"lbs/utils/benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"314712150","text":"import random\nimport discord\nimport os\nfrom discord.ext import commands\nimport gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\n\n\n# ___________________________________________________Static Variables___________________________________________________\n# discord and gspread private key\ndiscord_bot_private_key = os.environ[\"discord_priv_key\"]\nsecret_dict = {\n \"type\": os.environ[\"type\"],\n \"project_id\": os.environ[\"project_id\"],\n \"private_key_id\": os.environ[\"private_key_id\"],\n \"private_key\": os.environ[\"private_key\"],\n \"client_email\": os.environ[\"client_email\"],\n \"client_id\": os.environ[\"client_id\"],\n \"auth_uri\": os.environ[\"auth_uri\"],\n \"token_uri\": os.environ[\"token_uri\"],\n \"auth_provider_x509_cert_url\": os.environ[\"auth_provider_x509_cert_url\"],\n \"client_x509_cert_url\": os.environ[\"client_x509_cert_url\"]\n}\n\n\n# these channels have permission to ask for resetting the signed up teams\nchannel_id_with_all_permissions = 627498228354514944\n\nchannel_ids_with_permission_to_use_sign_up = [channel_id_with_all_permissions]\nchannel_ids_with_permission_to_ask_for_results = [619293120521043968, channel_id_with_all_permissions]\nunsign_log_channel_id = 627498228354514944\n\n\n# static variables for results\nsign_out_channel_id = 627498420277477376\n\n# these are the channels and messages that have to be edited every time someone uses (un)sign\nsign_up_channel_id = 629021326304083968\nsign_up_message_id = 629021355089854464\n\n# variables used for results\nscore_dic = {}\ninvalid_input_list = [\"No input\"]\n\n# variables for point system\nposition_points = {1: 350,\n 2: 275,\n 3: 250,\n 4: 200,\n 5: 190,\n 6: 180,\n 7: 170,\n 8: 160,\n 9: 150,\n 10: 140,\n 11: 130,\n 12: 120,\n 13: 110,\n 14: 100,\n 15: 90,\n 16: 80,\n 17: 70,\n 18: 60,\n 19: 50,\n 20: 40,\n 21: 30,\n 22: 20,\n 23: 10,\n 24: 5,\n 25: 1,\n 0: 0}\npoint_per_kill = 50\nbonus_point = 200\n\n# medals in unicode\nfirst_place_medal = \"\\U0001F947\"\nsecond_place_medal = \"\\U0001F948\"\nthird_place_medal = \"\\U0001F949\"\n\n# variable used to create result message\narrow = \"-->\"\n\n# ___________________________________________________Google Spreadsheet Set Up__________________________________________\n'''\nThree spreadsheets are being used in this program:\n-\"DB_duo_sign_up\" is used to see which teams have signed up for the duo tournament.\n-\"DB_squad_sign_up\" is used to see which teams have signed up for the squad tournament.\n-\"DB_changeable_variables_sheet\" is used to delete the signed up teams or delete the sign out messages.\n'''\n\nscope = ['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive']\ncreds = ServiceAccountCredentials.from_json_keyfile_dict(secret_dict, scope)\nclient_gspread = gspread.authorize(creds)\nsign_up_sheet = client_gspread.open(\"DB_duo_sign_up\").sheet1\nDB_changeable_variables_sheet = client_gspread.open(\"DB_changeable_variables\").sheet1\n\n\ndef refresh_google_tokens():\n \"\"\"\n This function refreshes the permission to read or write data on a sheet.\n Use this function everytime the program has to read or write data on a sheet.\n \"\"\"\n if creds.access_token_expired:\n print(\"tokens expired\")\n print(\"Refreshing credentials ...\")\n client_gspread.login()\n print(\"Refreshed credentials.\")\n\n\n# _____________________________________________results function_______________________________________________________\n'''\nThis feature gives results in a discord channel. It uses messages from players as input.\nThe must have following form: \"TeamName position1 position2 position3 AmountOfKills AmountOfBonus\".\n'''\n\n\ndef is_convertible_to_int(string):\n \"\"\"\n Checks if string (Type: String) can be converted to an Integer.\n \"\"\"\n try:\n int(string)\n return True\n except ValueError:\n return False\n\n\ndef is_key_for_dict(key, dictionary):\n \"\"\"\n Checks if key is a key of dictionary (Type: Dictionary).\n \"\"\"\n if key in dictionary:\n return True\n else:\n return False\n\n\ndef is_valid_score_input(text_message):\n \"\"\"\n Checks if text_message (Type: String) is of the form \"TeamName PlacementOne PlacementTwo PlacementThree\n AmountOfKills AmountOfBonus\".\n TeamName should be one word.\n PlacementOne, PlacementTwo. PlacementThree and AmountOfKills should all be able to get converted to a string.\n If text_message is of that form, the function returns True (Type: Boolean), otherwise False (Type: Boolean).\n \"\"\"\n text_split = text_message.split()\n\n if len(text_split) != 7:\n return False\n\n else:\n position_one = text_split[1]\n position_two = text_split[2]\n position_three = text_split[3]\n position_four = text_split[4]\n kills = text_split[5]\n amount_of_bonus = text_split[6]\n\n # Boolean Expressions\n position_one_is_not_convertible_to_int = not is_convertible_to_int(position_one)\n position_two_is_not_convertible_to_int = not is_convertible_to_int(position_two)\n position_three_is_not_convertible_to_int = not is_convertible_to_int(position_three)\n position_four_is_not_convertible_to_int = not is_convertible_to_int(position_four)\n kills_is_not_convertible_to_int = not is_convertible_to_int(kills)\n amount_of_bonus_is_not_convertible_to_int = not is_convertible_to_int(amount_of_bonus)\n integer_inputs_are_not_all_convertible_to_integers = (position_one_is_not_convertible_to_int\n or position_two_is_not_convertible_to_int\n or position_three_is_not_convertible_to_int\n or position_four_is_not_convertible_to_int\n or kills_is_not_convertible_to_int\n or amount_of_bonus_is_not_convertible_to_int)\n\n if integer_inputs_are_not_all_convertible_to_integers:\n return False\n\n else:\n # Boolean Expressions\n position_one_is_not_key_for_dict = not is_key_for_dict(int(position_one), position_points)\n position_two_is_not_key_for_dict = not is_key_for_dict(int(position_two), position_points)\n position_three_is_not_key_for_dict = not is_key_for_dict(int(position_three), position_points)\n position_four_is_not_key_for_dict = not is_key_for_dict(int(position_four), position_points)\n a_position_is_not_key_from_dict = (position_one_is_not_key_for_dict\n or position_two_is_not_key_for_dict\n or position_three_is_not_key_for_dict\n or position_four_is_not_key_for_dict)\n\n if a_position_is_not_key_from_dict:\n return False\n\n else:\n return True\n\n\ndef calculate_score_for_team(text_message):\n \"\"\"\n Calculates the points with text_message (Type: String) as input. text_message is of the form \"TeamName PlacementOne\n PlacementTwo PlacementThree AmountOfKills\".\n TeamName is be one word.\n PlacementOne, PlacementTwo. PlacementThree and AmountOfKills are all able to get converted to a string.\n The points get calculated with the global variable ? (Type: Dictionary).\n The function returns a list with two elements.\n The first one is the team_name (Type: String) and the second one is the total_score (Type: Integer) for that team.\n \"\"\"\n text_split = text_message.split()\n team_name = text_split[0]\n position_one = int(text_split[1])\n position_two = int(text_split[2])\n position_three = int(text_split[3])\n position_four = int(text_split[4])\n kills = int(text_split[5])\n amount_of_bonus = int(text_split[6])\n # calculate scores\n score_one = position_points[position_one]\n score_two = position_points[position_two]\n score_three = position_points[position_three]\n score_four = position_points[position_four]\n score_kills = kills * point_per_kill\n score_bonus = amount_of_bonus * bonus_point\n total_score = score_one + score_two + score_three + score_four + score_kills + score_bonus\n\n return [team_name, total_score]\n\n\ndef add_team_and_score_to_score_dic(text_message):\n \"\"\"\n Uses text_message (Type: String) as input. text_message is of the form \"TeamName PlacementOne PlacementTwo\n PlacementThree AmountOfKills AmountOfBonus\".\n TeamName is be one word.\n PlacementOne, PlacementTwo. PlacementThree, AmountOfKills and AmountOfBonus\n should all be able to get converted to a string.\n It then adds the team_name (Type: String) as key and team_score (Type: Integer) as value to the global variable\n score_dic (Type: Dictionary).\n If the text_message isn't a valid input, then that text_message gets appended to\n invalid_input_list (Type: List)\n \"\"\"\n global score_dic\n\n if is_valid_score_input(text_message):\n team_results = calculate_score_for_team(text_message)\n team_name = team_results[0]\n team_score = team_results[1]\n score_dic[team_name] = team_score\n\n else:\n invalid_input_list.append(text_message)\n\n\ndef create_invalid_message():\n \"\"\"\n This functions creates an invalid_message (Type: string).\n This message contains all the messages that weren't a valid score input.\n Returns invalid_message.\n \"\"\"\n counter = 0\n invalid_message = \"__Wasn't able to interpret these messages:__\\n\"\n for message in invalid_input_list:\n invalid_message += \"**Message {}:** {}\\n\\n\".format(counter + 1, message)\n counter += 1\n return invalid_message\n\n\ndef order_score_into_list(score_dict):\n \"\"\"\n The input of this function is score_dict (Type: Dictionary). score_dict has team_name (Type: String)\n as key and team_score (Type: Integer) as value.\n It then creates ordered_score_list (Type: List) a list of lists.\n The sub-list has two elements team_name and team_score.\n The sub-lists have been ordered in ascending order of team_score.\n The function returns ordered_score_list.\n \"\"\"\n score_list = []\n\n for key in score_dict:\n score_list.append([key, score_dict[key]])\n\n ordered_score_list = []\n\n while len(score_list) != 0:\n biggest_index = 0\n current_index = 0\n biggest_score = score_list[biggest_index][1]\n\n for element in score_list:\n current_score = element[1]\n\n if current_score > biggest_score:\n biggest_score = current_score\n biggest_index = current_index\n\n current_index += 1\n\n ordered_score_list.append(score_list[biggest_index])\n score_list.pop(biggest_index)\n\n return ordered_score_list\n\n\ndef create_placement_list(ordered_list):\n \"\"\"\n The input of this function is ordered_score_list (Type: List) a list of lists.\n The sub-list has two elements team_name (Type: String) and team_score (Type: Integer).\n It then creates placement_list (Type: List) a list of lists of lists.\n If two teams have the same team_score they will be placed in the same sub-list.\n The sub-sub-list has two elements team_name and team_score.\n The sub-lists have been ordered in ascending order of team_score.\n The function returns ordered_score_list.\n \"\"\"\n placement_list = []\n\n while len(ordered_list) != 0:\n\n current_score = ordered_list[0][1]\n counter = 0\n\n for element in ordered_list:\n if element[1] == current_score:\n counter += 1\n\n sub_list = []\n\n for x in range(counter):\n sub_list.append(ordered_list[0])\n ordered_list.pop(0)\n\n placement_list.append(sub_list)\n\n return placement_list\n\n\ndef create_result_message(final_ordered_list):\n result_message = \"__results:__\\n\"\n placement_counter = 1\n\n result_message += \"```\"\n\n for placement in final_ordered_list:\n tie = 0\n result_message += \"{:<6}\".format(\"#\" + str(placement_counter))\n\n for team in placement:\n if tie == 0:\n result_message += \"{:<20} {} {:<}\\n\".format(team[0], arrow, team[1])\n tie = 1\n else:\n result_message += \"{:<6}{:<20} {} {:<}\\n\".format(\"\", team[0], arrow, team[1])\n\n placement_counter += 1\n result_message += \"```\"\n result_message += \"\\nWasn't able to interpret {} messages\".format(len(invalid_input_list))\n return result_message\n\n\nasync def result_main(channel_id):\n global score_dic\n global invalid_input_list\n score_dic = {}\n invalid_input_list = []\n channel_to_read = client.get_channel(channel_id)\n\n async for old_message in channel_to_read.history(limit=200):\n add_team_and_score_to_score_dic(old_message.content)\n\n ordered_list = order_score_into_list(score_dic)\n placement_list = create_placement_list(ordered_list)\n result_message = create_result_message(placement_list)\n\n return result_message\n\n\ndef create_current_result_message(final_ordered_list):\n result_message = \"__Current standings:__\\n\"\n placement_counter = 1\n\n result_message += \"```\"\n\n for placement in final_ordered_list:\n tie = 0\n result_message += \"{:<6}\".format(\"#\" + str(placement_counter))\n\n for team in placement:\n if tie == 0:\n result_message += \"{:<20} {} {:<}\\n\".format(team[0], arrow, team[1])\n tie = 1\n else:\n result_message += \"{:<6}{:<20} {} {:<}\\n\".format(\"\", team[0], arrow, team[1])\n\n placement_counter += 1\n result_message += \"```\"\n\n return result_message\n\n\nasync def current_result_main(channel_id):\n global score_dic\n global invalid_input_list\n score_dic = {}\n invalid_input_list = []\n channel_to_read = client.get_channel(channel_id)\n\n async for old_message in channel_to_read.history(limit=200):\n add_team_and_score_to_score_dic(old_message.content)\n\n ordered_list = order_score_into_list(score_dic)\n placement_list = create_placement_list(ordered_list)\n result_message = create_current_result_message(placement_list)\n\n return result_message\n\n\ndef get_first_place_team(final_ordered_list):\n if len(final_ordered_list) >= 1:\n first_place_list = final_ordered_list[0]\n first_teams = []\n for teams in first_place_list:\n first_teams.append(teams[0])\n return first_teams\n else:\n return ['No team']\n\n\ndef get_second_place_team(final_ordered_list):\n if len(final_ordered_list) >= 2:\n second_place_list = final_ordered_list[1]\n second_teams = []\n for teams in second_place_list:\n second_teams.append(teams[0])\n return second_teams\n else:\n return ['No team']\n\n\ndef get_third_place_team(final_ordered_list):\n if len(final_ordered_list) >= 3:\n third_place_list = final_ordered_list[2]\n third_teams = []\n for teams in third_place_list:\n third_teams.append(teams[0])\n return third_teams\n else:\n return ['No team']\n\n\ndef get_team_names(team_list):\n index = 0\n team_string = \"\"\n while index < len(team_list):\n if index + 1 == len(team_list):\n team_string += team_list[index]\n else:\n team_string += \"{} and \".format(team_list[index])\n index += 1\n\n return team_string\n\n\ndef create_full_result_message(final_ordered_list):\n prize = \"${}\".format(get_prize())\n\n result_message = \"These are the results of the Tournament.\\n\\n\"\n first_place = get_first_place_team(final_ordered_list)\n print(first_place)\n first_place_string = get_team_names(first_place)\n second_place = get_second_place_team(final_ordered_list)\n second_place_string = get_team_names(second_place)\n print(second_place)\n third_place = get_third_place_team(final_ordered_list)\n third_place_string = get_team_names(third_place)\n print(third_place)\n # first place\n result_message += \"{} {}\\n\\n\".format(first_place_medal, first_place_string)\n # second place\n result_message += \"{} {}\\n\\n\".format(second_place_medal, second_place_string)\n # third place\n result_message += \"{} {}\\n\\n\".format(third_place_medal, third_place_string)\n # congratulations message\n result_message += \"Congratulations {} with the victory and winning {}!\\n\\n\".format(first_place_string, prize)\n # thanking everyone and providing info for next event.\n result_message += \"Thank you everyone for participating! Hope to see you next time! GG's @everyone!\\n\" \\\n \"For future events head over to <#577574312186216448>.\\n\\n\"\n\n result_message += \"```\"\n placement_counter = 1\n for placement in final_ordered_list:\n tie = 0\n result_message += \"{:<6}\".format(\"#\" + str(placement_counter))\n\n for team in placement:\n if tie == 0:\n result_message += \"{:<20} {} {:<}\\n\".format(team[0], arrow, team[1])\n tie = 1\n else:\n result_message += \"{:<6}{:<20} {} {:<}\\n\".format(\"\", team[0], arrow, team[1])\n\n placement_counter += 1\n result_message += \"```\"\n return result_message\n\n\nasync def full_result_main(channel_id):\n global score_dic\n global invalid_input_list\n score_dic = {}\n invalid_input_list = []\n channel_to_read = client.get_channel(channel_id)\n\n async for old_message in channel_to_read.history(limit=200):\n print(old_message.content)\n add_team_and_score_to_score_dic(old_message.content)\n\n ordered_list = order_score_into_list(score_dic)\n placement_list = create_placement_list(ordered_list)\n result_message = create_full_result_message(placement_list)\n\n return result_message\n\n\n# ________________________________________________Sign Up feature_______________________________________________________\n'''\nThis feature lets players sign up for tournaments.\n'''\n\n\ndef get_nb_rows(spreadsheet):\n \"\"\"\n Return the number of filled in rows (Type: Integer).\n Uses the first column values to get the amount of rows.\n \"\"\"\n return len(spreadsheet.col_values(1))\n\n\ndef delete_column(spreadsheet, column):\n \"\"\"\n Uses spreadsheet (Type: A spreadsheet for gpsread) and column (Type: Integer) as input.\n It deletes all the values in a column of spreadsheet.\n It deletes a cell by updating the value for that cell too \"\" (an empty string).\n \"\"\"\n nb_rows = get_nb_rows(spreadsheet)\n for row in range(1, nb_rows + 1):\n spreadsheet.update_cell(row, column, \"\")\n\n\ndef get_signed_teams_list(duo_or_squad_sheet):\n \"\"\"\n Uses duo_or_squad_sheet (Type: A spreadsheet for gpsread) as input.\n It returns a list of team_names (Type: String) in the first column of duo_or_squad_sheet.\n \"\"\"\n return duo_or_squad_sheet.col_values(1)\n\n\ndef get_row_with_team_name(duo_or_squad_sheet, team_name):\n \"\"\"\n Uses duo_or_squad_sheet (Type: A spreadsheet for gpsread) and team_name (Type: String) as input.\n It returns the row number (Type: Integer) where the team_name is found in duo_or_squad_sheet.\n If The team_name isn't found in duo_or_squad_sheet it returns None.\n \"\"\"\n signed_team_list = get_signed_teams_list(duo_or_squad_sheet)\n len_signed_team_list = len(signed_team_list)\n for counter in range(len(signed_team_list)):\n if team_name == signed_team_list[len_signed_team_list - (counter + 1)]:\n return len_signed_team_list - counter\n return None\n\n\ndef check_if_still_places_available():\n \"\"\"\n Checks how many teams are in duo_or_squad_sheet (Type: A spreadsheet for gpsread) already.\n If there are 100 or more than 100 teams it returns False (Type: Boolean).\n Otherwise it returns True (Type: Boolean).\n \"\"\"\n sheet = sign_up_sheet\n sign_up_limit = get_sign_up_limit()\n\n signed_up_teams = get_nb_rows(sheet)\n\n if signed_up_teams >= sign_up_limit:\n return False\n else:\n return True\n\n\ndef add_team_to_signed_teams(duo_or_squad_sheet, team_name):\n \"\"\"\n Adds team_name (Type: String) to duo_or_squad_sheet (Type: A spreadsheet for gpsread) already.\n The team_name gets filled in in the first non-empty row in the first column of duo_or_squad_sheet.\n \"\"\"\n nb_rows = get_nb_rows(duo_or_squad_sheet)\n duo_or_squad_sheet.update_cell(nb_rows + 1, 1, team_name)\n\n\ndef is_valid_sign_or_unsign_message(text_message):\n \"\"\"\n Checks if text_message (Type: String) is valid to used for sign up.\n \"\"\"\n if len(text_message) > 55:\n return False\n else:\n return True\n\n\ndef sign_main(text_message):\n \"\"\"\n Has text_message (Type: String) and duo_or_squad_sheet (Type: A spreadsheet for gpsread) as input.\n Adds the team_name (Type: String) to duo_or_squad_sheet if text_message is valid and if there is still place.\n It returns a string whether the team_name got added or not.\n \"\"\"\n if is_valid_sign_or_unsign_message(text_message):\n sheet = sign_up_sheet\n\n team_name = \" \".join(text_message.split()[1:])\n if check_if_still_places_available():\n add_team_to_signed_teams(sheet, team_name)\n return \"{} has been signed up!\".format(team_name)\n else:\n return \"Sorry, there's no more space to sign up.\"\n else:\n return \"No valid info for **?sign** command. Make sure you use **?sign TeamName** \" \\\n \"(**TeamName** max 45 characters long).\"\n\n\ndef unsign_main(text_message):\n \"\"\"\n Has text_message (Type: String) and duo_or_squad_sheet (Type: A spreadsheet for gpsread) as input.\n Adds the team_name (Type: String) to duo_or_squad_sheet if text_message is valid and if there is still place.\n It returns a string whether the team_name got added or not.\n \"\"\"\n if is_valid_sign_or_unsign_message(text_message):\n sheet = sign_up_sheet\n\n team_name = \" \".join(text_message.split()[1:])\n row_to_delete = get_row_with_team_name(sheet, team_name)\n\n if row_to_delete is None:\n return \"The team you're trying to cancel hasn't been found. \" \\\n \"Make sure to use the exact same name as you used to sign up.\"\n\n else:\n sheet.delete_row(row_to_delete)\n return \"Your team sign up has been cancelled.\"\n else:\n return \"No valid command info for **?unsign**. Make sure you use **?unsign TeamName** \" \\\n \"(*TeamName* max 20 characters long).\"\n\n\ndef create_sign_up_string(team_list):\n \"\"\"\n Creates sign_up_string (Type: String) using team_list (Type: List).\n duo_or_squads (Type: String) is either \"duo\" or \"squad\".\n \"\"\"\n team_list_len = len(team_list)\n sign_up_string = \"__REGISTERED TEAMS:__\\n\\n\"\n\n sign_up_limit = get_sign_up_limit()\n sign_up_string += \"```\"\n\n for counter in range(1, sign_up_limit + 1):\n if counter - 1 < team_list_len:\n team_name = team_list[counter - 1]\n sign_up_string += \"{:<3} {:<}\\n\".format(str(counter) + \".\", team_name)\n else:\n sign_up_string += \"{}.\\n\".format(counter)\n\n sign_up_string += \"```\"\n return sign_up_string\n\n\nasync def edit_signed_team_message():\n \"\"\"\n Edits the message on discord.\n duo_or_squads (Type: String) is either \"duo\" or \"squad\".\n \"\"\"\n channel_to_edit_id = sign_up_channel_id\n message_to_edit_id = sign_up_message_id\n sheet = sign_up_sheet\n team_list = get_signed_teams_list(sheet)\n sign_up_string = create_sign_up_string(team_list)\n\n channel_to_edit_eu = client.get_channel(channel_to_edit_id)\n message_to_edit_eu = await channel_to_edit_eu.fetch_message(message_to_edit_id)\n await message_to_edit_eu.edit(content=sign_up_string)\n\n\n\"\"\"\nFunctions to reset the signed up teams\n\"\"\"\nreset_indicator_column = 1\n\n\ndef get_reset_indicator():\n \"\"\"\n Gets the reset_indicator (Type: String) from DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n reset_indicator is \"0\" if no reset is asked.\n reset_indicator is \"1\" if a reset is asked for duo sign up.\n reset_indicator is \"2\" if a reset is asked for squad sign up.\n \"\"\"\n return DB_changeable_variables_sheet.cell(2, reset_indicator_column).value\n\n\ndef set_reset_indicator(value):\n \"\"\"\n Sets the reset_indicator (Type: String) in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n reset_indicator is \"0\" if no reset is asked.\n reset_indicator is \"1\" if a reset is asked for duo sign up.\n reset_indicator is \"2\" if a reset is asked for squad sign up.\n \"\"\"\n DB_changeable_variables_sheet.update_cell(2, reset_indicator_column, value)\n\n\ndef initiate_reset_for_sign_up():\n \"\"\"\n Sets the reset_indicator (Type: String) in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread) to \"1\".\n \"\"\"\n set_reset_indicator(1)\n\n\n'''\nFunctions to set the sign up limit and the prizes for duo and squad.\n'''\n\nduo_prize_column = 4\nsquad_prize_column = 5\n\nduo_sign_up_limit_column = 2\nsquad_sign_up_limit_column = 3\n\n\ndef get_prize():\n \"\"\"\n Gets the duo_prize_indicator (Type: String) from DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n \"\"\"\n return DB_changeable_variables_sheet.cell(2, duo_prize_column).value\n\n\ndef set_prize(value):\n \"\"\"\n Sets the duo_prize_indicator (Type: String) in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n \"\"\"\n DB_changeable_variables_sheet.update_cell(2, duo_prize_column, value)\n\n\ndef get_sign_up_limit():\n \"\"\"\n Gets the duo_sign_up_limit (Type: String) from DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n It returns duo_sign_up_limit as an Integer.\n \"\"\"\n return int(DB_changeable_variables_sheet.cell(2, duo_sign_up_limit_column).value)\n\n\ndef set_sign_up_limit(new_amount):\n \"\"\"\n Sets the duo_sign_up_limit (Type: String) in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n duo_sign_up_limit should be an Integer.\n \"\"\"\n DB_changeable_variables_sheet.update_cell(2, duo_sign_up_limit_column, new_amount)\n\n\ndef is_right_amount_of_parameters_for_set_limit_or_set_prize(text_message):\n \"\"\"\n Checks if text_message (Type: String) is of the form \"$set_duo_limit amount\" or \"$set_duo_limit amount\".\n It checks if it only has one parameter amount.\n If thats the case it returns True (Type: Boolean) otherwise False (Type: Boolean).\n \"\"\"\n text_message_split = text_message.split()\n if len(text_message_split) != 2:\n return False\n else:\n return True\n\n\ndef is_new_amount_less_than_already_signed_up_teams(new_amount):\n \"\"\"\n Checks if the amount given in the text_message (Type: String) of the form \"$set_duo_limit amount\" or\n \"$set_duo_limit amount\" is more than the already signed up teams.\n If that's the case it returns True (Type: Boolean) otherwise False (Type: Boolean).\n \"\"\"\n already_signed_up_teams = get_nb_rows(sign_up_sheet)\n\n if new_amount < already_signed_up_teams:\n return False\n else:\n return True\n\n\ndef set_limit_main(text_message):\n \"\"\"\n Sets the duo_sign_up_limit or squad_sign_up_limit (Type: String) depending on duo_or_squads (Type: String)\n in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n duo_or_squads is either \"duo\" or \"squad\".\n \"\"\"\n if is_right_amount_of_parameters_for_set_limit_or_set_prize(text_message):\n text_message_split = text_message.split()\n new_amount = text_message_split[1]\n\n if is_convertible_to_int(new_amount):\n new_amount = int(new_amount)\n\n if is_new_amount_less_than_already_signed_up_teams(new_amount):\n\n if new_amount <= 400:\n\n set_sign_up_limit(new_amount)\n\n return \"The new limit for the sign up has been set to {}.\".format(new_amount)\n\n else:\n return \"The new limit has to be smaller than or equal to 400.\"\n\n else:\n\n already_signed_up_teams = get_nb_rows(sign_up_sheet)\n\n return \"Can't set the sign up limit to {} because there are already more teams signed up \" \\\n \"({} teams).\".format(new_amount, already_signed_up_teams)\n\n else:\n return \"Make sure that the **number** in **?set_limit number** is an integer.\"\n else:\n return \"Not the right amount of parameters for **?set_limit number**.\"\n\n\ndef set_prize_main(text_message):\n \"\"\"\n Sets the duo_prize or squad_prize (Type: String) depending on duo_or_squads (Type: String)\n in DB_changeable_variables_sheet (Type: A spreadsheet for gpsread).\n duo_or_squads is either \"duo\" or \"squad\".\n \"\"\"\n if is_right_amount_of_parameters_for_set_limit_or_set_prize(text_message):\n text_message_split = text_message.split()\n new_amount = text_message_split[1]\n\n if is_convertible_to_int(new_amount):\n new_amount = int(new_amount)\n set_prize(new_amount)\n\n return \"The new prize has been set to {}.\".format(new_amount)\n\n else:\n return \"Make sure that the **number** in **?set_prize number** is an integer.\"\n\n else:\n return \"Not the right amount of parameters for **?set_prize number**.\"\n\n\n# ________________________________________________DISCORD Set Up & Commands_____________________________________________\n'''\nSets up discord bot.\nBelow are all the commands for the discord bot.\n'''\n# Initialise Client\nClient = discord.Client()\n# Initialise client bot\nclient = commands.Bot(command_prefix=\"?\")\n# Check which discord version it is\nprint(discord.__version__)\n\n\n@client.event\nasync def on_ready():\n print(\"Bot is online and connected to Discord\")\n\n\n'''\nAll commands for the results feature.\n'''\n@client.command()\nasync def results(ctx):\n if ctx.message.channel.id in channel_ids_with_permission_to_ask_for_results:\n result_message = await result_main(sign_out_channel_id)\n await ctx.send(result_message)\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def full_results(ctx):\n if ctx.message.channel.id in channel_ids_with_permission_to_ask_for_results:\n refresh_google_tokens()\n result_message = await full_result_main(sign_out_channel_id)\n await ctx.send(result_message)\n await ctx.message.delete()\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def current_results(ctx):\n if ctx.message.channel.id in channel_ids_with_permission_to_ask_for_results:\n result_message = await current_result_main(sign_out_channel_id)\n await ctx.send(result_message)\n await ctx.message.delete()\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def give_report(ctx):\n invalid_message = create_invalid_message()\n await ctx.send(invalid_message)\n\n\n'''\nAll commands for the sign up feature.\n'''\n@client.command()\nasync def sign(ctx):\n if ctx.message.channel.id in channel_ids_with_permission_to_use_sign_up:\n refresh_google_tokens()\n input_message = ctx.message.content\n print(\"input:\", input_message)\n answer = sign_main(input_message)\n await edit_signed_team_message()\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def unsign(ctx):\n if ctx.message.channel.id in channel_ids_with_permission_to_use_sign_up:\n refresh_google_tokens()\n unsign_log_channel = client.get_channel(unsign_log_channel_id)\n unsign_log_message = \"{} used {}\".format(ctx.message.author, ctx.message.content)\n await unsign_log_channel.send(unsign_log_message)\n input_message = ctx.message.content\n answer = unsign_main(input_message)\n await edit_signed_team_message()\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n'''\nAll commands for the setting the sign up limit or prize.\n'''\n\n\n@client.command()\nasync def change_limit(ctx):\n if ctx.message.channel.id == channel_id_with_all_permissions:\n refresh_google_tokens()\n answer = set_limit_main(ctx.message.content)\n await edit_signed_team_message()\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def change_prize(ctx):\n if ctx.message.channel.id == channel_id_with_all_permissions:\n refresh_google_tokens()\n answer = set_prize_main(ctx.message.content)\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def variable_settings(ctx):\n if ctx.message.channel.id == channel_id_with_all_permissions:\n refresh_google_tokens()\n answer = \"sign up limit: {}\\n\" \\\n \"prize: {}\\n\".format(get_sign_up_limit(), get_prize())\n else:\n answer = \"This command can't be used in this channel.\"\n await ctx.send(answer)\n\n\n'''\nAll commands for the resetting the sign ups.\n'''\n\n\n@client.command()\nasync def reset_sign_up(ctx):\n refresh_google_tokens()\n if ctx.message.channel.id == channel_id_with_all_permissions:\n initiate_reset_for_sign_up()\n answer = \"If you're sure you want to reset enter **?yes** otherwise enter **?no**.\"\n else:\n answer = \"This channel doesn't have the authority to call this command. \" \\\n \"Contact <@354603604201439233> if you think it should have.\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def yes(ctx):\n refresh_google_tokens()\n reset_indicator = get_reset_indicator()\n\n if reset_indicator == \"1\":\n answer = \"Resetting the sign ups ...\"\n await ctx.send(answer)\n delete_column(sign_up_sheet, 1)\n await edit_signed_team_message()\n answer = \"Done.\"\n set_reset_indicator(0)\n await ctx.send(answer)\n\n else:\n answer = \"Sorry the **?reset_sign_up*** command hasn't been called before\"\n await ctx.send(answer)\n\n\n@client.command()\nasync def no(ctx):\n refresh_google_tokens()\n set_reset_indicator(0)\n answer = \"Cancelled the reset.\"\n await ctx.send(answer)\n\n\n'''\nAll commands to get info about the bot.\n'''\n\n\n@client.command()\nasync def bot_info(ctx):\n answer = \"__(Un)Sign Commands:__\\n\" \\\n \"-Use **?sign TeamName** to sign up a team for the tournament.\\n\" \\\n \"-Use **?unsign TeamName** to cancel a teams sign up for the tournament.\\n\" \\\n \"\\n\" \\\n \"__Result Commands:__\\n\" \\\n \"-**?results**: Gives results from the Tournament in a simple message \" \\\n \"and shows how many messages the bot couldn't interpret.\\n\" \\\n \"-**?current_results**: Gives current results from the Tournament in a message.\\n\" \\\n \"-**?full_results**: Gives results from the Tournament in a detailed message.\\n\" \\\n \"-**?give_report**: Shows which messages the bot couldn't interpret.\\n\" \\\n \"\\n\" \\\n \"__Set Variable Commands:__\\n\" \\\n \"-Use **?change_limit Number** to set the amount of teams that can register for the tournament.\\n\" \\\n \"-Use **?change_prize Number** to set the prize used in the full result message.\\n\" \\\n \"-Use **?variable_settings** to get the current settings of all the variables.\"\n my_message = await ctx.send(answer)\n print(my_message)\n\n\n@client.command()\nasync def initiate(ctx):\n answer = \"Initiating message...\"\n my_message = await ctx.send(answer)\n print(my_message)\n\n\n@client.command()\nasync def ping(ctx):\n latency = int(client.latency * 1000)\n answer = \"pong! `{}ms`\".format(latency)\n await ctx.send(answer)\n\n\n@client.command()\nasync def version(ctx):\n answer = \"`0.0.0.3`\"\n await ctx.send(answer)\n\n\nclient.run(discord_bot_private_key)\n","sub_path":"DB_PUBGM_discord_bot.py","file_name":"DB_PUBGM_discord_bot.py","file_ext":"py","file_size_in_byte":36571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"333942352","text":"import tornado.httpserver\nimport tornado.websocket\nimport tornado.ioloop\nimport tornado.web\nimport socket\nimport json\nfrom time import sleep\n\n#All connected users\nusers = []\nuserlist = []\n\n#Check if it's a JSON Array or an other datatype\ndef is_json(myjson):\n try:\n json.loads(myjson)\n except ValueError:\n return False\n return True\n\nclass WSHandler(tornado.websocket.WebSocketHandler):\n #When a client connects.\n def open(self):\n global users\n global userlist\n users.append(self)\n print(\"connected\")\n self.write_message(json.dumps({\"username\": \"Console\", \"message\":\"Succesfully connected!\"}))\n \n #When the websocket receive's a message.\n def on_message(self, message):\n global users\n if (is_json(message)):\n if(json.loads(message)[\"type\"] == \"connected\"):\n global userlist\n userlist.append(json.loads(message)[\"value\"])\n for user in users:\n user.write_message(json.dumps(userlist))\n else:\n print(message)\n \n for user in users:\n user.write_message(message)\n else:\n print(message)\n \n #When a client disconnects\n def on_close(self):\n global userlist\n global users\n\n if(len(userlist) > 0):\n del userlist[users.index(self)]\n users.remove(self)\n\n for user in users:\n user.write_message(json.dumps(userlist))\n\n print ('connection closed')\n \n #If connection IP Is same as host, still allow it.\n def check_origin(self, origin): \n return True\n \n#Configure what the connection link has to contain.\napplication = tornado.web.Application([\n (r'/ws', WSHandler),\n])\n\n#Run and configure the websocket port.\nif __name__ == \"__main__\":\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(8888)\n myIP = socket.gethostbyname(socket.gethostname())\n tornado.ioloop.IOLoop.instance().start()\n \n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"355099786","text":"import os\nimport urllib.parse\nimport urllib.request\nimport threading\nfrom pathlib import Path\nfrom urllib.parse import urljoin\n\n\nfrom bs4 import BeautifulSoup\nfrom watson_developer_cloud import NaturalLanguageUnderstandingV1 as NLU\nfrom watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions\n\n#TODO: Implement threading on the posting_generator\n#TODO: Comment everything\n#TODO: Implement pipe to send the pages\n\nprint(\"start\")\n####################################\n#Author: Unknown\n#Author: Mike DeLeo\n#File: IndeedCrawler.py\n#Summary: Crawls Indeed.com for jobs with the specified job title and location\n####################################\n\n####################################\n#Beautiful Soup Doc Notes\n#Find_all:\n#Find:\n\ni = 1\nbase_url = \"https://www.indeed.com/jobs?\" #Website to crawl\nLIMIT = 100\n\n####################################\n#Precondition:\n#Postcondition:\n#Summary:\n####################################\ndef nextPage(soup):\n print(\"next_page\")\n next_link = soup.find(\"span\", class_=\"np\")\n \n if next_link is not None:\n next_url = next_link.find_parent(\"a\")['href']\n next_page = urljoin(base_url, next_url)\n return next_page\n \n else:\n return 0\n\n####################################\n#Precondition:\n#Postcondition:\n#Summary:\n####################################\ndef saveHTML(jobURL):\n global i\n print(\"saving\")\n print(jobURL)\n## filePath = Path(\"jobs/IndeedJob{}.html\".format(i))\n## page = urllib.request.urlopen(jobURL)\n## page_content = page.read()\n## \n## if not os.path.isdir(\"jobs\"):\n## os.makedirs(\"jobs\")\n## with open(filePath, \"wb\") as fid:\n## fid.write(page_content)\n## i += 1\n## return\n\n####################################\n#Precondition:\n#Postcondition:\n#Summary:\n####################################\ndef posting_generator(job_title, job_location):\n current_thread = os.getpid()\n print(\"posting generator\")\n print('Current Thread : ',current_thread)\n jobs = [] #Array of jobs initialized\n \n #Initialize the information for the Watson API\n searchValues = {'q':job_title,'l':job_location} #Dictionary of items for watson\n search_url = (base_url + urllib.parse.urlencode(searchValues)) #Website to crawl with search items\n\n #Select the first page\n next_page = urllib.request.urlopen(search_url, None, None)\n nlu = NLU(\n\t iam_apikey='BU11gy3frJMRMKz4XQ_sPJ_HGF3p-qEr74xUlEVTWvsY',\n\t version='2018-03-19'\n )\n\n while True:\n #TODO: find out what this does\n soup = BeautifulSoup(next_page, 'html.parser')\n\n #TODO: Find out what find_all does\n for job in soup.find_all('div'):\n if job.get('data-tn-component') is not None and job.get('data-tn-component') == 'organicJob':\n url = 'https://www.indeed.com' + job.a['href']\n response = nlu.analyze(\n url=url,\n features=Features(\n entities=EntitiesOptions(\n limit=LIMIT\n ),\n keywords=KeywordsOptions(\n limit=LIMIT\n ),\n )\n ).get_result()\n jobs.append(response)\n #jsonprinter(response)\n #yield url, response\n saveHTML(url)\n next_url = nextPage(soup)\n\n if next_url == 0:\n break\n else:\n next_page = urllib.request.urlopen(next_url, None, None)\n\n print(\"END OF PROGRAM!\")\n\n","sub_path":"webcrawling/IndeedCrawler.py","file_name":"IndeedCrawler.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"286949587","text":"import os\nimport scipy.misc as scimisc\nimport matplotlib.pyplot as plt\nfrom preprocess import load_object_data\nimport sys\nimport numpy as np\nfrom PIL import Image, ImageFilter\n\n\ndef rgb2gray(image):\n gray = image[:, :, 0] * 0.3 + image[:, :, 1] * 0.2 + image[:, :, 2] * 0.5\n image[:, :, 0] = gray\n image[:, :, 1] = gray\n image[:, :, 2] = gray\n\n return image\n\n\ndef main():\n # dir = 'datasets/train_bike_car_person'\n #\n # for subdir, dirs, files in os.walk(dir):\n # print(dirs)\n # num = 0\n # for file in files:\n # # print(os.path.join(subdir, file))\n # num += 1\n # print(num)\n #\n dir = 'datasets/train_bike_car_person/bike/bike_015.bmp'\n dir2 = 'datasets/train_bike_car_person/bike/bike_016.bmp'\n\n ori_image = Image.open(dir).resize((96, 96))\n\n image = rgb2gray(np.array(ori_image))\n\n # image3 = ori_image.filter(ImageFilter.GaussianBlur(radius=1))\n image3 = ori_image.crop(box=(0, 0, 48, 96)).resize((96, 96))\n image3 = np.array(image3)\n print(image3.shape)\n\n image2 = scimisc.imread(dir2, mode='RGB')\n image2 = scimisc.imresize(image2, (96, 96, 3), interp='cubic')\n\n plt.subplot(2, 2, 1)\n plt.imshow(image)\n plt.xlabel('Image \\n from \\n Dataset')\n plt.yticks([])\n plt.xticks([])\n\n plt.subplot(2, 2, 2)\n plt.imshow(image3)\n plt.xlabel('Image \\n from \\n Dataset')\n plt.yticks([])\n plt.xticks([])\n\n plt.subplot(2, 2, 3)\n plt.imshow(image2)\n plt.xlabel('ANOTHER Image \\n from \\n Dataset')\n plt.yticks([])\n plt.xticks([])\n\n plt.tight_layout()\n plt.show()\n\n data_label = [[0, 1, 2, 0], [3, 0, 2, 1], [9, 3, 4, 1]]\n label_list = ['a', 'b', 'c', 'd']\n\n class_res = {}\n\n for i in range(len(label_list)):\n class_res[label_list[i]] = data_label[0][i]\n\n numbers = {'first': 8, 'second': 20, 'third': 2, 'fourth': 10}\n numbers = [(k, numbers[k]) for k in sorted(numbers, key=numbers.get, reverse=True)]\n\n caption = ''\n for k, v in numbers:\n caption += k + ': %.2f%% \\n' % v\n\n print(caption)\n\n data, label_list = load_object_data(num_training=2000)\n\n print(data['x_train'].shape)\n print(data['y_train'].shape)\n print(data['x_val'].shape)\n print(data['y_val'].shape)\n print(label_list)\n\nmain()\n","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"561595726","text":"'''\nScript to process yelp reviews into a line by line text corpus\nThis file was provided by the capstone course instructors\nModified for Task 1:\n To update from Python 2 to Python 3\n To avoid review duplicates\n To increase the specified random review sample size from 100000 to 500000\n To store ids and ratings in the same processed files as the reviews\nModified for Task 2:\n To be completed\n'''\n\nimport math\nimport json\nimport pickle\nimport random\nfrom time import time\nimport argparse\nimport os\n\npath2files = \"yelp_dataset_challenge_academic_dataset/\"\npath2business = path2files + \"yelp_academic_dataset_business.json\"\npath2reviews = path2files + \"yelp_academic_dataset_review.json\"\n \ndef main(save_sample, save_categories, SAMPLE_SIZE):\n categories = set([])\n restaurant_ids = set([])\n cat2rid = {}\n rest2rate = {}\n rest2revID = {}\n r = 'Restaurants'\n with open (path2business, 'r') as f:\n for line in f.readlines():\n business_json = json.loads(line)\n bjc = business_json['categories']\n if r in bjc:\n if len(bjc) > 1:\n restaurant_ids.add(business_json['business_id'])\n categories = set(bjc).union(categories) - set([r])\n stars = business_json['stars']\n rest2rate[ business_json['business_id'] ] = stars\n for cat in bjc:\n if cat == r:\n continue\n if cat in cat2rid:\n cat2rid[cat].append(business_json['business_id'])\n else:\n cat2rid[cat] = [business_json['business_id']]\n\n print(\"Saving restaurant ratings...\")\n \n with open('restaurantIds2ratings.txt', 'w') as f:\n for key in rest2rate:\n f.write(key + \" \" + str(rest2rate[key]) + \"\\n\")\n \n # clearing from memory\n rest2rate = None\n \n with open('data_cat2rid.pickle', 'wb') as f:\n pickle.dump(cat2rid, f)\n\n with open(path2reviews, 'r') as f:\n for line in f:\n review_json = json.loads(line)\n if review_json['business_id'] in restaurant_ids:\n if review_json['business_id'] in rest2revID:\n rest2revID[review_json['business_id']].append(review_json['review_id'])\n else:\n rest2revID[review_json['business_id']] = [review_json['review_id']]\n\n with open('data_rest2revID.pickle', 'wb') as f:\n pickle.dump(rest2revID,f)\n \n nz_count = 0\n valid_cats = []\n for i, cat in enumerate(cat2rid):\n cat_total_reviews = 0\n for rid in cat2rid[cat]:\n # number of reviews for each of restaurants\n if rid in rest2revID:\n cat_total_reviews = cat_total_reviews + len(rest2revID[rid])\n\n if cat_total_reviews > 30:\n nz_count = nz_count + 1\n valid_cats.append(cat)\n \n print(\"Sampling categories...\")\n sample_rid2cat = {}\n sample_size = len(valid_cats) # This specifies how many cuisines you would like to save \n cat_sample = random.sample(valid_cats, sample_size)\n for cat in cat_sample:\n for rid in cat2rid[cat]:\n if rid in rest2revID:\n if rid not in sample_rid2cat:\n sample_rid2cat[rid] = []\n sample_rid2cat[rid].append(cat)\n \n # remove from memory\n rest2revID = None\n \n print(\"Reading from reviews file...\")\n # ensure categories is a directory\n sample_cat2reviewID = {}\n sample_reviewID2stars = {}\n sample_reviewID2review = {}\n with open(path2reviews, 'r') as f:\n for line in f:\n review_json = json.loads(line)\n rid = review_json['business_id']\n if rid in sample_rid2cat:\n for rcat in sample_rid2cat[rid]:\n if rcat in sample_cat2reviewID:\n sample_cat2reviewID[rcat].append(review_json['review_id'])\n else:\n sample_cat2reviewID[rcat] = [review_json['review_id']]\n sample_reviewID2stars[review_json['review_id']] = str(review_json['stars'])\n sample_reviewID2review[review_json['review_id']] = review_json['text'].replace(\"\\n\", \" \").replace(\"\\r\", \" \")\n \n if save_categories: # save categories\n print(\"Saving categories...\")\n for cat in sample_cat2reviewID:\n with open('categories/' + cat.replace('/', '-').replace(\" \", \"_\") + \".txt\" , 'wb') as f:\n for id in sample_cat2reviewID[cat]:\n f.write((id + \" \" + sample_reviewID2stars[id] + \" \" + sample_reviewID2review[id] + \"\\n\").encode('ascii', 'ignore'))\n\n if save_sample: # save sample for restaurant reviews\n print(\"Sampling restaurant reviews...\")\n sample_size = min(SAMPLE_SIZE, len(sample_reviewID2review))\n revIDs = list(sample_reviewID2review)\n random.shuffle(revIDs)\n with open(\"review_sample.txt\", 'wb') as f:\n count = 0\n while count < sample_size:\n id = revIDs[count]\n f.write((id + \" \" + sample_reviewID2stars[id] + \" \" + sample_reviewID2review[id] + \"\\n\").encode('ascii', 'ignore'))\n count += 1\n \nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description='This program transforms the Yelp data and saves the cuisines in the category directory. It also samples reivews from Yelp. It can also generates a cuisine similarity matrix.') \n parser.add_argument('--cuisine', action='store_true',\n help='Saves a sample (10) of the cuisines to the \"categories\" directory. For Task 2 and 3 you will experiment with individual cuisines. This option allows you to generate a folder that contains all of the cuisines in the Yelp dataset. You can run this multiple times to generate more samples or if your machine permits you can change a sample parameter in the code.')\n parser.add_argument('--sample', action='store_true',\n help='Sample a subset of reviews from the yelp dataset which could be useful for Task 1. This will samples upto 100,000 restaurant reviews from 10 cuisines and saves the output in \"review_sample_100000.txt\", it also saves their corresponding raitings in the \"review_ratings_100000.txt\" file. You can run this multiple times to get several different samples.')\n parser.add_argument('--sample_size', type = int, default = 100000,\n help='Requested review sample size')\n parser.add_argument('--matrix', action='store_true',\n help='Generates the cuisine similarity matrix which is used for Task 2. First we apply topic modeling to a sample (30) of the cuisines in the \"categories\" folder and measures the cosine similarity of two cuisines from their topic weights. This might take from half-an-hour to several hours time depending on your machine. The number of topics is 20 and the default number of features is 10000.')\n parser.add_argument('--all', action='store_true',\n help='Does all of the above.') \n args = parser.parse_args()\n \n if args.all or (args.sample and args.cuisine):\n print(\"Saving sample and cuisine...\")\n main(True, True, args.sample_size)\n elif args.sample:\n print(\"Generating sample...\")\n main(args.sample, args.cuisine, args.sample_size)\n elif args.cuisine:\n print(\"Generating cuisine...\")\n main(args.sample, args.cuisine, args.sample_size)\n\n if args.matrix or args.all:\n print(\"Generating cuisine matrix\")\n # sim_matrix()\n","sub_path":"T1 - LDA Topic Modeling and Graph Visualization/yelp_review_initial_processing.py","file_name":"yelp_review_initial_processing.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558773250","text":"\"\"\"\nfile\n\n:author: lishanZheng\n:date: 2020/01/09\n\"\"\"\nimport os\nimport time\n\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom file.constant.code import MISS_FILE\nfrom util.result_util import success, error\n\n\n@csrf_exempt\ndef upload(request):\n \"\"\"\n upload\n\n :author: lishanZheng\n :date: 2020/01/09\n \"\"\"\n file = request.FILES.get(\"file\", None) # 获取上传的文件,如果没有文件,则默认为None\n if not file:\n return error(MISS_FILE, '没有选择文件')\n time_str = str(time.time()).replace('.', '')\n file_name = 'media/{0}{1}'.format(time_str, file.name)\n path = os.path.join(os.path.join(settings.FILE_ROOT_DIR, file_name))\n # 根据路径打开指定的文件(以二进制读写方式打开)\n destination = open(path, 'wb+')\n # 分块写入文件\n for chunk in file.chunks():\n destination.write(chunk)\n destination.close()\n url = settings.FILE_HOST + '/' + file_name\n res = {\n 'url': url\n }\n return success(res)\n","sub_path":"file/views/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"464712298","text":"class CoffeeMachine:\n def __init__(self, money, water, milk, beans, cups):\n self.money = money\n self.water = water\n self.milk = milk\n self.beans = beans\n self.cups = cups\n self.action = \"\"\n self.w = 0\n self.mi = 0\n self.b = 0\n self.mo = 0\n \n def log_state(self):\n print(\"The coffee machine has:\")\n print(self.water, \"of water\")\n print(self.milk, \"of milk\")\n print(self.beans, \"of coffee beans\")\n print(self.cups, \"of disposable cups\")\n print(self.money,\"of money\")\n\n def check(self):\n if self.water < self.w:\n print(\"Sorry, not enough water!\")\n if self.milk < self.mi:\n print(\"Sorry, not enough milk!\")\n if self.beans < self.b:\n print(\"Sorry, not enough beans!\")\n if self.cups < 1:\n print(\"Sorry, not enough cups!\")\n if not (self.water < self.w or self.milk < self.mi or self.beans < self.b or self.cups < 1):\n print(\"I have enough resources, making you a coffee!\")\n self.cook()\n \n def cook(self):\n self.cups -= 1\n self.water -= self.w\n self.milk -= self.mi\n self.beans -= self.b\n self.money += self.mo\n \n def buy(self):\n self.number = input(\"What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\")\n if self.number == \"1\":\n self.w = 250\n self.mi = 0\n self.b = 16\n self.mo = 4\n self.check()\n if self.number == \"2\":\n self.w = 350\n self.mi = 75\n self.b = 20\n self.mo = 7\n self.check()\n if self.number == \"3\":\n self.w = 200\n self.mi = 100\n self.b = 12\n self.mo = 6\n self.check()\n\n \n def fill(self):\n self.water += int(input(\"Write how many ml of water do you want to add:\"))\n self.milk += int(input(\"Write how many ml of milk do you want to add:\"))\n self.beans += int(input(\"Write how many grams of coffee beans do you want to add:\"))\n self.cups += int(input(\"Write how many disposable cups of coffee do you want to add:\"))\n\n def take(self):\n print(f\"I gave you ${self.money}\")\n self.money = 0\n \n def work(self):\n while self.action != \"exit\":\n self.action = input(\"Write an action (buy, fill, take, remaining, exit):\")\n if self.action == \"buy\":\n self.buy()\n if self.action == \"fill\":\n self.fill()\n if self.action == \"take\":\n self.take()\n if self.action == \"remaining\":\n self.log_state()\n\nmasha = CoffeeMachine(550, 400, 540, 120, 9)\nmasha.work()\n","sub_path":"CoffeeMachine.py","file_name":"CoffeeMachine.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"280142858","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom multiprocessing.pool import Pool\n\nfrom PyQt5.QtCore import QThread, pyqtSignal, QMutex, QMutexLocker\n\nfrom models.dsm_API import DSMAPI\n\n\nclass BaseThread(QThread):\n out_msg = pyqtSignal(str) # 显示信息\n\n def __init__(self):\n super().__init__()\n self.mutex = QMutex()\n self.stoped = False\n\n def thread_init(self, keyword=''):\n self.stoped = False\n with QMutexLocker(self.mutex):\n self.stoped = False\n\n def stop_thread(self):\n with QMutexLocker(self.mutex):\n self.stoped = True\n\n def isStoped(self):\n with QMutexLocker(self.mutex):\n return self.stoped\n\n def run(self):\n pass\n\n\nclass DSMSearcher(BaseThread):\n put_meta = pyqtSignal(dict)\n search_finished = pyqtSignal()\n\n def __init__(self, keyword, dsm, lib):\n super().__init__()\n self.lib = lib\n self.keyword = keyword\n self.DSM = dsm\n self.count = 0\n\n def run(self):\n self.count = 0\n self.out_msg.emit('开始搜索[{}]'.format(self.keyword))\n\n if self.lib:\n finded = self.DSM.find_video(self.lib, self.keyword)\n\n\n else:\n finded = self.DSM.find_videos_all(self.keyword)\n\n for meta in finded:\n if self.stoped: break\n self.count += 1\n self.put_meta.emit(meta)\n self.out_msg.emit('搜索[{}]……找到[{}]'.format(self.keyword, self.count))\n\n self.search_finished.emit()\n self.out_msg.emit('搜索[{}]完成……共找到[{}]'.format(self.keyword, self.count))\n","sub_path":"dsm_manager.py","file_name":"dsm_manager.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"99829187","text":"import time\nimport click\n\nfrom lokialerts.servicenode.jobs.base import BaseJob\nfrom lokialerts.servicenode import util\nfrom lokialerts.servicenode.rpc import ServiceNodeRPCError\nfrom lokialerts.github import LokiGithubError\n\n\nclass ServiceNodeVersionJob(BaseJob):\n def __init__(self, mailer, rpc, db, recipient_db, github):\n super().__init__(mailer, rpc, db, recipient_db)\n self.github = github\n\n def schedule(self, scheduler):\n scheduler.every(15).seconds.do(self.run)\n\n def run(self):\n s_nodes = self.db.all()\n\n if len(s_nodes) == 0:\n click.echo(\"No service nodes to check version\")\n return\n\n try:\n latest_version_tag = self.github.get_latest_version()\n latest_version = util.parse_version_tag(latest_version_tag)\n for sn in s_nodes:\n click.echo(\"Checking version for %s\" % sn['label'])\n stats = self.rpc.get_service_node_stats(sn)\n current_version_tag = stats['service_node_version']\n current_version = util.parse_version(current_version_tag)\n if current_version != 0 and current_version < latest_version:\n click.echo(\"Service node %s is out to date\" % sn['label'])\n click.echo(\"Notifying users\")\n self.mailer.connect()\n self.mailer.send(\n \"\"\"Service node %s version is %s and the latest version is %s, \n please update node\"\"\" % (sn['label'], util.parse_version_arr(current_version_tag), latest_version_tag),\n self.recipient_db.all()\n )\n self.mailer.disconnect()\n else:\n click.echo(\n \"Version is up to date for service node %s\" % sn['label']\n )\n except LokiGithubError:\n click.secho(\n 'ServiceNodeVersionJob - Unable to get latest version from github', fg='red')\n except ServiceNodeRPCError:\n click.secho(\n 'ServiceNodeVersionJob - Unable to get service node stats for %s from rpc' % sn['label'], fg='red')\n","sub_path":"lokialerts/servicenode/jobs/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"171058344","text":"# -*- coding: utf-8 -*-\n# USER: Test\n# Time: 2019/7/16 18:34\n\nimport json\nfrom conf.settings import redis_conn, cmb_request_url, bank_login_account, notice_url, business_account_nums\nfrom tornado.httpclient import AsyncHTTPClient\nfrom tornado.gen import sleep, coroutine\nfrom tornado.ioloop import IOLoop\nfrom source.payment.cmb.xmlprotocol import query_transaction_detail_information, \\\n parse_transaction_detail_information_response_message, tree2bytes, BankNotComplete, \\\n query_new_notice, parse_new_notice_response_message, \\\n query_account_transaction_information, parse_account_transaction_information_response_message\n\n\n@coroutine\ndef timer_tasks():\n yield timer_new_notice()\n yield timer_query_transaction_detail_information()\n yield timer_bulk_payroll_back()\n IOLoop.instance().call_later(10, timer_tasks)\n\n\n@coroutine\ndef timer_query_transaction_detail_information():\n \"\"\"\n 定时查询交易详细信息\n :return: {\n \"process_instance_number\": \"流程实例号\",\n \"users_list\": [\n {\n \"account_nums\": \"账户地址\",\n \"account_name\": \"账户名\",\n \"status\": \"成功 S, 是吧 F\",\n \"amount\": \"金额\",\n \"msg\": \"错误消息\",\n \"serial_number\": \"流水号\",\n \"transaction_date\": \"交易发生的日期\",\n \"transaction_time\": \"交易发生的时间\",\n }\n ]\n }\n \"\"\"\n key = \"cmb:bulk_payroll\"\n client = AsyncHTTPClient()\n while redis_conn.llen(key):\n data = redis_conn.lpop(key)\n data = str(data, encoding='utf-8')\n business_account_number, regional_branch_code, current_date, login_name, process_instance_number, callback_url = data.split(\n '|')\n\n current_date = \"20181213\"\n tree = query_account_transaction_information(business_account_number, current_date, current_date,\n login_name=login_name, borrowing_code='D',\n bank_branch_code=regional_branch_code)\n\n response = yield client.fetch(cmb_request_url, method=\"POST\", body=tree2bytes(tree))\n account_transaction_data = parse_account_transaction_information_response_message(response.body,\n process_instance_number,\n False)\n yield sleep(5)\n tree = query_transaction_detail_information(login_name, process_instance_number)\n response = yield client.fetch(cmb_request_url, method=\"POST\", body=tree2bytes(tree))\n assert response.code == 200, response.code\n try:\n data = parse_transaction_detail_information_response_message(response.body, account_transaction_data)\n result = {\"users_list\": data}\n except BankNotComplete:\n redis_conn.rpush(\n key, f\"{business_account_number}|{regional_branch_code}|{current_date}|\"\n f\"{login_name}|{process_instance_number}|{callback_url}\")\n else:\n try:\n response = yield client.fetch(callback_url, method=\"POST\", body=json.dumps(result))\n if response.code != 200:\n print(f\"callback {callback_url} http error {response.code}\")\n except Exception as e:\n print(f\"callback {callback_url} error {e}\")\n redis_conn.rpush(\"cmb:bulk_payroll_back\", f\"{callback_url}|{json.dumps(result)}\")\n\n yield sleep(5)\n\n del client\n\n\n@coroutine\ndef timer_bulk_payroll_back():\n key = \"cmb:bulk_payroll_back\"\n client = AsyncHTTPClient()\n while redis_conn.llen(key):\n data = redis_conn.lpop(key)\n data = str(data, encoding='utf-8')\n callback_url, result = data.split('|')\n\n try:\n response = yield client.fetch(callback_url, method=\"POST\", body=json.dumps(result))\n if response.code != 200:\n print(f\"callback {callback_url} http error {response.code}\")\n except Exception as e:\n print(f\"callback {callback_url} error {e}\")\n redis_conn.rpush(key, f\"{callback_url}|{json.dumps(result)}\")\n\n yield sleep(5)\n\n del client\n\n\n@coroutine\ndef timer_new_notice():\n key = \"cmb:new_notice\"\n\n def retry_notice(data):\n try:\n print(\"new_notice: \", data)\n r = yield client.fetch(notice_url, method=\"POST\", body=json.dumps(data))\n if r.code != 200:\n print(f\"notice {notice_url} http error {r.code}\")\n except Exception as e:\n print(f\"notice {notice_url} error {e}\")\n redis_conn.rpush(key, json.dumps(data))\n\n client = AsyncHTTPClient()\n\n tree = query_new_notice(bank_login_account)\n try:\n response = yield client.fetch(cmb_request_url, method=\"POST\", body=tree2bytes(tree))\n except Exception as e:\n print(f\"request {cmb_request_url} error {e}\")\n else:\n if response.code == 200:\n result = parse_new_notice_response_message(response.body, business_account_nums=business_account_nums)\n retry_notice(result)\n else:\n print(f\"request {cmb_request_url} http error {response.code}\")\n yield sleep(5)\n\n while redis_conn.llen(key):\n _data = redis_conn.lpop(key)\n retry_notice(str(_data, encoding='utf-8'))\n yield sleep(5)\n\n del client\n","sub_path":"source/tasks/timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"467386710","text":"\nimport numpy as np\nimport tensorflow as tf\nimport os\nfrom pathlib import Path\n\nnp.random.seed(1)\ntf.set_random_seed(1)\nfrom shutil import copyfile\n\nimport shutil\n\n# Deep Q Network off-policy\nclass Network(object):\n def __init__(\n self,logno,\n n_output_grad=2,\n n_output_survival=3,\n n_length=64,\n n_volume=5,\n channel=3,\n learning_rate=0.001,\n batch_size=128,\n output_graph=False,\n use_ckpt = True,\n DTYPE=tf.float32\n\n ):\n\n\n self.n_length = n_length # width or height of input matrix\n self.n_volume= n_volume,\n self.lr = learning_rate\n self.batch_size = batch_size\n self.channel = channel # num of channel\n self.learn_step_counter = 0\n self.global_step = tf.Variable(tf.constant(1))\n self.global_counter = 1 # equal to self.global_step\n self.n_output_survival = n_output_survival\n self.n_output_grad = n_output_grad\n self._build_net()\n self.keep_prob = tf.placeholder(tf.float32)\n self.DTYPE=DTYPE\n\n # e_params = tf.get_collection('eval_net_params')\n\n # self.replace_target_op = [tf.assign(t, e) for t, e in zip(t_params, e_params)]\n # self.replace_eval_op = [tf.assign(e, t) for e, t in zip(e_params,t_params)]\n # assign e to t\n\n self.sess = tf.Session()\n self.saver = tf.train.Saver(tf.global_variables())\n # self.dir_path = '/home/hengtong/project/protein/ProteinHP_DQN/heng_model/save_weight/'\n self.dir_path = '/exports/lkeb-hpc/gkarami/Code/Log/'+str(logno)#os.path.dirname(os.path.realpath(__file__))\n os.mkdir(self.dir_path)\n os.mkdir(self.dir_path+'/code/')\n os.mkdir(self.dir_path+'/code/joint/')\n\n copyfile('./net.py', self.dir_path + '/code/joint/net.py')\n copyfile('./real_time.py', self.dir_path + '/code/joint/real_time.py')\n copyfile('./test_model.py', self.dir_path + '/code/joint/test_model.py')\n copyfile('./Utils.py', self.dir_path + '/code/joint/Utils.py')\n copyfile('./jointly.py', self.dir_path + '/code/joint/jointly.py')\n\n\n self.train_writer = tf.summary.FileWriter((self.dir_path)+'/train/' , graph=tf.get_default_graph())\n self.validation_writer = tf.summary.FileWriter((self.dir_path)+'/validation/' , graph=self.sess.graph)\n\n self.merged = tf.summary.merge_all()\n if output_graph:\n # tensorboard --logdir=logs\n self.writer = tf.summary.FileWriter(\"logs/\", self.sess.graph)\n\n if use_ckpt:\n self.restore_parameters()\n else:\n self.sess.run(tf.global_variables_initializer()) # train step\n\n self.cost_his = []\n\n def get_nb_params_shape(self, shape):\n '''\n Computes the total number of params for a given shap.\n Works for any number of shapes etc [D,F] or [W,H,C] computes D*F and W*H*C.\n '''\n nb_params = 1\n for dim in shape:\n nb_params = nb_params * int(dim)\n return nb_params\n\n def count_number_trainable_params(self):\n '''\n Counts the number of trainable variables.\n '''\n tot_nb_params = 0\n for trainable_variable in tf.trainable_variables():\n shape = trainable_variable.get_shape() # e.g [D,F] or [W,H,C]\n current_nb_params = self.get_nb_params_shape(shape)\n tot_nb_params = tot_nb_params + current_nb_params\n return tot_nb_params\n\n\n # def conv2d(self,x, W, stride,pad):\n # # stride [1, x_movement, y_movement, 1]\n # # Must have strides[0] = strides[3] = 1\n # return tf.nn.conv2d(x, W, strides = stride, padding=pad)\n #\n # def max_pool(self,x,k,stride,pad):\n # # stride [1, x_movement, y_movement, 1]\n # return tf.nn.max_pool(x, ksize=k, strides=stride, padding=pad)\n\n def BN_fc(self,x,dim):\n # x is input size,dim is batch size\n mean_value,var_value = tf.nn.moments(x,[0])\n scales = tf.Variable(tf.ones([dim]))\n betas = tf.Variable(tf.zeros([dim]))\n epsilon = 1e-3\n return tf.nn.batch_normalization(x,mean_value,var_value,scales,betas,epsilon)\n\n\n\n def _build_net(self):\n # ------------------ build grad_Net ------------------\n self.xs = tf.placeholder(tf.float32, shape=(5, self.n_length, self.n_length, self.channel), name='input') # input\n self.xs2 = tf.placeholder(tf.float32, shape=(None, 5, 64, 64, 3), name='input') # input\n\n # self.s = tf.reshape(self.xs, [-1, self.n_features, self.n_features, self.channel])\n self.keep_prob = tf.placeholder(tf.float32)\n self.labels_grad = tf.placeholder(tf.float32,[None,self.n_output_grad],name='grad_labels')\n self.labels_survival = tf.placeholder(tf.float32, [None, self.n_output_survival], name='survival_labels')\n\n self.loss_ts = tf.placeholder(tf.float32)\n\n\n with tf.variable_scope('multi-para'):\n self.p = tf.Variable(0.5, name='p')\n self.q = tf.Variable(0.5, name='q')\n tf.summary.scalar('multi-para' + 'p', self.p)\n tf.summary.scalar('multi-para' + 'q', self.q)\n tf.summary.scalar(\"loss_ts\", self.loss_ts)\n\n show_img = self.xs[:, :, :, 0, np.newaxis]\n tf.summary.image('00: input_t1', show_img, 3)\n\n show_img = self.xs[:, :, :, 1, np.newaxis]\n tf.summary.image('01: input_md', show_img, 3)\n\n show_img = self.xs[:, :, :, 2, np.newaxis]\n tf.summary.image('02: input_cbv', show_img, 3)\n\n\n with tf.variable_scope('joint_net'):\n # c_names(collections_names) are the collections to store variables\n c_names, w_initializer, b_initializer = \\\n ['grad_net_params', tf.GraphKeys.GLOBAL_VARIABLES], \\\n tf.truncated_normal_initializer(0., 0.1), tf.constant_initializer(0.1) # config of layers\n\n##################################################################################################################\n def _weight_variable(name, shape):\n return tf.get_variable(name, shape, tf.truncated_normal_initializer(stddev=0.1))\n\n def _bias_variable(name, shape):\n return tf.get_variable(name, shape, tf.constant_initializer(0.1, dtype=self.DTYPE))\n\n # first layer. collections is used later when assign to target net\n prev_layer = self.xs2\n in_filters = self.channel\n with tf.variable_scope('conv1') as scope:\n out_filters = 16\n kernel = tf.get_variable('weights', [5, 5, 5, 3, out_filters], tf.truncated_normal_initializer(stddev=0.1))\n conv = tf.nn.conv3d(prev_layer, kernel, [1, 1, 1, 1, 1], padding='SAME')\n biases = tf.get_variable('biases', [1, out_filters])\n bias = tf.nn.bias_add(conv, biases)\n conv1 = tf.nn.relu(bias, name=scope.name)\n\n input = conv1\n in_filters = out_filters\n pool1 = tf.nn.max_pool3d(input, ksize=[1, 3, 3, 3, 1], strides=[1, 2, 2, 2, 1], padding='SAME') ############## 32*32*\n norm1 = pool1 # tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta = 0.75, name='norm1')\n input = norm1\n\n with tf.variable_scope('conv2') as scope:\n out_filters = 32\n kernel2 = _weight_variable('weights2', [5, 5, 5, in_filters, out_filters])\n conv = tf.nn.conv3d(prev_layer, kernel2, [1, 1, 1, 1, 1], padding='SAME')\n biases2 = _bias_variable('biases2', [out_filters])\n bias = tf.nn.bias_add(conv, biases2)\n conv2 = tf.nn.relu(bias, name=scope.name)\n\n prev_layer = conv2\n in_filters = out_filters\n # normalize prev_layer here\n prev_layer = tf.nn.max_pool3d(prev_layer, ksize=[1, 3, 3, 3, 1], strides=[1, 2, 2, 2, 1], padding='SAME') #### 16*16*\n\n with tf.variable_scope('conv3_1') as scope:\n out_filters = 64\n kernel31 = _weight_variable('weights31', [5, 5, 5, in_filters, out_filters])\n conv = tf.nn.conv3d(prev_layer, kernel31, [1, 1, 1, 1, 1], padding='SAME')\n biases31 = _bias_variable('biases31', [out_filters])\n bias = tf.nn.bias_add(conv, biases31)\n prev_layer = tf.nn.relu(bias, name=scope.name)\n in_filters = out_filters\n\n with tf.variable_scope('conv3_2') as scope:\n out_filters = 64\n kernel32 = _weight_variable('weights32', [5, 5, 5, in_filters, out_filters])\n conv = tf.nn.conv3d(prev_layer, kernel32, [1, 1, 1, 1, 1], padding='SAME')\n biases32 = _bias_variable('biases32', [out_filters])\n bias = tf.nn.bias_add(conv, biases32)\n prev_layer = tf.nn.relu(bias, name=scope.name)\n in_filters = out_filters\n\n with tf.variable_scope('conv3_3') as scope:\n out_filters = 32\n kernel33 = _weight_variable('weights33', [5, 5, 5, in_filters, out_filters])\n conv = tf.nn.conv3d(prev_layer, kernel33, [1, 1, 1, 1, 1], padding='SAME')\n biases33 = _bias_variable('biases33', [out_filters])\n bias = tf.nn.bias_add(conv, biases33)\n prev_layer = tf.nn.relu(bias, name=scope.name)\n in_filters = out_filters\n\n # normalize prev_layer here\n prev_layer = tf.nn.max_pool3d(prev_layer, ksize=[1, 3, 3, 3, 1], strides=[1, 2, 2, 2, 1], padding='SAME') #### 8*8**\n\n # fully connected layer 1\n with tf.variable_scope('fcl1'):\n w1_fu = tf.get_variable('w1_fu',[1*8*8*32,1024],initializer=w_initializer, collections=c_names)\n b1_fu = tf.get_variable('b1_fu',[1,1024],initializer=b_initializer, collections=c_names)\n h_pool3_flat = tf.reshape(prev_layer, [-1,1*8*8*32])\n bn_in_fc1 = tf.matmul(h_pool3_flat, w1_fu) + b1_fu\n # bn_out_fc1 = self.BN_fc(bn_in_fc1,512)\n h_fc1 = tf.nn.relu(bn_in_fc1)\n h_fc1_drop = tf.nn.dropout(h_fc1, self.keep_prob)#################################\n tf.summary.histogram('fcl1' + '/weight', w1_fu)\n tf.summary.histogram('fcl1' + '/bias', b1_fu)\n\n # fully connected layer 2,grad\n with tf.variable_scope('fcl2_grad'):\n w2_fc_grad = tf.get_variable('w2_fc_grad', [1024,32], initializer=w_initializer, collections=c_names)\n b2_fc_grad = tf.get_variable('b2_fc_grad', [1,32], initializer=b_initializer, collections=c_names)\n bn_fc2_grad = tf.matmul(h_fc1_drop, w2_fc_grad) + b2_fc_grad\n # self.q_eval = self.BN_fc(bn_in_fc2, self.n_actions)\n h_fc2_grad = tf.nn.relu(bn_fc2_grad)\n h_fc2_grad_drop = tf.nn.dropout(h_fc2_grad, self.keep_prob)\n tf.summary.histogram('fcl2_grad' + '/weight', w2_fc_grad)\n tf.summary.histogram('fcl2_grad' + '/bias', b2_fc_grad)\n\n # fully connected layer 2,survival\n with tf.variable_scope('fcl2_survival'):\n w2_fc_survival = tf.get_variable('w2_fc_survival', [1024, 32], initializer=w_initializer, collections=c_names)\n b2_fc_survival = tf.get_variable('b2_fc_survival', [1, 32], initializer=b_initializer, collections=c_names)\n bn_fc2_survival = tf.matmul(h_fc1_drop, w2_fc_survival) + b2_fc_survival\n h_fc2_survival = tf.nn.relu(bn_fc2_survival)\n\n h_fc2_survival_drop = tf.nn.dropout(h_fc2_survival, self.keep_prob)\n tf.summary.histogram('fcl2_survival' + '/weight', w2_fc_survival)\n tf.summary.histogram('fcl2_survival' + '/bias', b2_fc_survival)\n\n # output layer,grad\n with tf.variable_scope('out_grad'):\n w3_fc_grad = tf.get_variable('w3_fc_grad', [32, self.n_output_grad], initializer=w_initializer, collections=c_names)\n b3_fc_grad = tf.get_variable('b3_fc_grad', [1, self.n_output_grad], initializer=b_initializer, collections=c_names)\n bn_fc3_grad = tf.matmul(h_fc2_grad_drop, w3_fc_grad) + b3_fc_grad\n # self.q_eval = self.BN_fc(bn_in_fc2, self.n_actions)\n self.out_grad = tf.multiply(self.q, tf.nn.softmax(bn_fc3_grad))\n # self.out_grad = tf.nn.softmax(bn_fc3_grad)\n tf.summary.histogram('out_grad' + '/weight', w3_fc_grad)\n tf.summary.histogram('out_grad' + '/bias', b3_fc_grad)\n\n # output layer,survival\n with tf.variable_scope('out_survival'):\n w3_fc_survival = tf.get_variable('w3_fc_survival', [32, self.n_output_survival], initializer=w_initializer, collections=c_names)\n b3_fc_survival = tf.get_variable('b3_fc_survival', [1, self.n_output_survival], initializer=b_initializer, collections=c_names)\n bn_fc3_survival = tf.matmul(h_fc2_survival_drop, w3_fc_survival) + b3_fc_survival\n self.out_survival = tf.multiply(self.p, tf.nn.softmax(bn_fc3_survival))\n # self.out_survival = tf.nn.softmax(bn_fc3_survival)\n tf.summary.histogram('out_survival' + '/weight', w3_fc_survival)\n tf.summary.histogram('out_survival' + '/bias', b3_fc_survival)\n # show_img = lrn1[:, :, :, 0, np.newaxis]\n # tf.summary.image('03: conv1', show_img, 3)\n #\n # show_img = lrn2[:, :, :, 0, np.newaxis]\n # tf.summary.image('04: conv2', show_img, 3)\n #\n # show_img = lrn3[:, :, :, 0, np.newaxis]\n # tf.summary.image('05: conv3', show_img, 3)\n #\n # show_img = lrn4[:, :, :, 0, np.newaxis]\n # tf.summary.image('06: conv4', show_img, 3)\n #\n # show_img = lrn5[:, :, :, 0, np.newaxis]\n # tf.summary.image('07: conv5', show_img, 3)\n\n with tf.variable_scope('loss'):\n # alpha=.3\n # corss entropy\n cross_entropy = -tf.reduce_mean(self.labels_grad * tf.log(self.out_grad)) \\\n - tf.reduce_mean(self.labels_survival * tf.log(self.out_survival))\n # cross_entropy = -alpha*(tf.reduce_mean(self.labels_grad*tf.log(self.out_grad)) )\\\n # -(1-alpha)*(tf.reduce_mean(self.labels_survival*tf.log(self.out_survival)))\n\n # L2 regularization for the fully connected parameters.\n # regularizers = (\n # tf.nn.l2_loss(w2_fc_survival) + tf.nn.l2_loss(b2_fc_survival) +\n # tf.nn.l2_loss(w2_fc_grad) + tf.nn.l2_loss(b2_fc_grad) +\n # tf.nn.l2_loss(w3_fc_survival) + tf.nn.l2_loss(b3_fc_survival) +\n # tf.nn.l2_loss(w3_fc_grad) + tf.nn.l2_loss(b3_fc_grad) +\n # tf.nn.l2_loss(w1_fu) + tf.nn.l2_loss(b1_fu) +\n # tf.nn.l2_loss(w5_conv) + tf.nn.l2_loss(b5_conv) +\n # tf.nn.l2_loss(w4_conv) + tf.nn.l2_loss(b4_conv) +\n # tf.nn.l2_loss(w3_conv) + tf.nn.l2_loss(b3_conv) +\n # tf.nn.l2_loss(w2_conv) + tf.nn.l2_loss(b2_conv) +\n # tf.nn.l2_loss(w1_conv) + tf.nn.l2_loss(b1_conv)\n # )\n self.loss = cross_entropy + 5e-4 #*regularizers\n tf.summary.scalar('loss', self.loss)\n\n with tf.variable_scope('train'):\n\n self.learning_rate = tf.train.exponential_decay(\n self.lr, # Base learning rate.\n #batch * self.batch_size, # Current index into the dataset.\n self.global_step,\n 5000, # Decay step.\n 0.98, # Decay rate.\n staircase=True)\n tf.summary.scalar('learning rate',self.learning_rate)\n\n self._train_op = tf.train.MomentumOptimizer(self.learning_rate, 0.9).minimize(self.loss, global_step=self.global_step)\n\n # self._train_op = tf.train.RMSPropOptimizer(self.lr).minimize(self.loss) # normal training\n # self._train_op = tf.train.MomentumOptimizer(self.lr,0.9).minimize(self.loss)\n # learning_rate = tf.train.exponential_decay(learning_rate=self.lr, global_step=self.global_step,\n # decay_steps=10000, decay_rate=0.96, staircase=True)\n # grad_norm = 8\n # tvars = tf.trainable_variables()\n # grads,_ = tf.clip_by_global_norm(tf.gradients(self.loss,tvars),grad_norm) # adding clipping\n # opt = tf.train.RMSPropOptimizer(self.lr)\n # self._train_op = opt.apply_gradients(zip(grads,tvars))\n\n def accuracy(self,predictions, labels):\n \"\"\"\n Get accuracy\n :param predictions:\n :param labels:\n :return: accuracy\n \"\"\"\n size = labels.shape[0]\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n / size)\n\n def get_accuracy_rate(self,x,y_grad,y_survival,flag=3,point=0,pre_loss=0):\n cost,pred_grad,pred_survival,rs = self.sess.run([self.loss,self.out_grad,self.out_survival,self.merged],\n feed_dict={\n self.labels_grad: y_grad,\n self.labels_survival: y_survival,\n self.xs: x,\n self.loss_ts:pre_loss,\n self.keep_prob: 0.5\n\n })\n if flag==1:\n self.train_writer.add_summary(rs, point)\n elif flag==2:\n self.validation_writer.add_summary(rs, point)\n else:\n a=1\n\n accu_rate_grad = self.accuracy(pred_grad, y_grad)\n accu_rate_survival = self.accuracy(pred_survival, y_survival)\n return cost,accu_rate_grad,accu_rate_survival\n\n def get_result(self,x):\n \"\"\"\n :param x:\n :return: predicted survival and gradder\n \"\"\"\n pred_grad, pred_survival = self.sess.run([self.out_grad, self.out_survival,],feed_dict={self.xs: x})\n grad = np.argmax(pred_grad, 1)\n survival = np.argmax(pred_survival, 1)\n print (pred_grad)\n print (pred_survival)\n return grad,survival\n\n\n def learn(self,x,y_grad,y_survival,point):\n\n # train eval network\n _, self.cost= self.sess.run([self._train_op, self.loss],\n feed_dict={\n self.labels_grad: y_grad,\n self.labels_survival: y_survival,\n self.xs: x,\n self.keep_prob:0.5\n })\n\n\n self.global_counter +=1\n if self.global_counter%10==0:\n self.cost_his.append(self.cost)\n\n def plot_cost(self):\n \"\"\"\n This function will plot cost histgram\n :return:\n \"\"\"\n import matplotlib.pyplot as plt\n\n plt.plot(np.arange(len(self.cost_his)), self.cost_his)\n plt.ylabel('Cost')\n plt.xlabel('Training Steps')\n # plt.show()\n plt.grid()\n plt.savefig('cost.png')\n\n\n def restore_parameters(self):\n \"\"\"\n This function will restore weights\n :return:\n \"\"\"\n self.saver.restore(self.sess, self.dir_path + '/weights_saved/model.ckpt') # restore model\n\n def save_parameters(self):\n \"\"\"\n This function will save weights\n :return:\n \"\"\"\n saver = tf.train.Saver()\n if not os.path.exists(self.dir_path+\"/weights_saved\"):\n os.mkdir(self.dir_path + \"/weights_saved\")\n saver_path = saver.save(self.sess, self.dir_path+'/weights_saved/model.ckpt') # save model into save/model.ckpt file\n print('Model saved in file:', saver_path)\n\n def merge_hist(self,x,y_grad,y_survival,point):\n rs = self.sess.run(self.merged, feed_dict={\n self.labels_grad: y_grad,\n self.labels_survival: y_survival,\n self.xs: x,\n self.keep_prob: 0.5,\n self.loss_ts:0})\n self.writer.add_summary(rs,point)\n self.writer.flush()\n\n\n","sub_path":"joint/net3D.py","file_name":"net3D.py","file_ext":"py","file_size_in_byte":20850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"105611250","text":"#Also, I'm not sure if I'm correctly identifying which amino acids are affected \n#by frameshift. My current thought is to first translate both ancestral and \n#derived DNA sequences into protein sequences and find the corresponding \n#position of the deletion/addition in the protein sequence. Then all the \n#downstream amino acid difference could be caused by frameshift. I use the \n#positions of these downstream amino acids to look for possible features in \n#Uniprot. \n\n#Input: Alignment, All frameshifts, annotation\nfrom .classes import Protein,Feature\nfrom .find_protein_feature import find_protein_feature,find_protein_id\n\n# Translate DNA sequence into protein sequence\n\ndef reverse(d):\n d = d.upper()\n newD = ''\n for i in range(len(d)-1,-1,-1):\n if d[i] == 'A':\n newD += 'T'\n elif d[i] == 'T':\n newD += 'A'\n elif d[i] == 'G':\n newD += 'C'\n elif d[i] == 'C':\n newD += 'G'\n assert(len(d) == len(newD))\n return newD\n\ndef dna_translation(d,strand):\n table = {'TTT': 'F', 'TTC': 'F', 'TTA': 'L', 'TTG': 'L',\n 'TCT': 'S', 'TCC': 'S', 'TCA': 'S', 'TCG': 'S',\n 'TAT': 'Y', 'TAC': 'Y', 'TGT': 'C', 'TGC': 'C',\n 'TGG': 'W', 'CTT': 'L', 'CTC': 'L', 'CTA': 'L',\n 'CTG': 'L', 'CCT': 'P', 'CCC': 'P', 'CCA': 'P',\n 'CCG': 'P', 'CAT': 'H', 'CAC': 'H', 'CAA': 'Q',\n 'CAG': 'Q', 'CGT': 'R', 'CGC': 'R', 'CGA': 'R',\n 'CGG': 'R', 'ATT': 'I', 'ATC': 'I', 'ATA': 'I',\n 'ATG': 'M', 'ACT': 'T', 'ACC': 'T', 'ACA': 'T',\n 'ACG': 'T', 'AAT': 'N', 'AAC': 'N', 'AAA': 'K',\n 'AAG': 'K', 'AGT': 'S', 'AGC': 'S', 'AGA': 'R',\n 'AGG': 'R', 'GTT': 'V', 'GTC': 'V', 'GTA': 'V',\n 'GTG': 'V', 'GCT': 'A', 'GCC': 'A', 'GCA': 'A',\n 'GCG': 'A', 'GAT': 'D', 'GAC': 'D', 'GAA': 'E',\n 'GAG': 'E', 'GGT': 'G', 'GGC': 'G', 'GGA': 'G',\n 'GGG': 'G', 'TAA': '', 'TAG' : '' , 'TGA' : ''}\n prot = ''\n d = d.upper()\n if strand == '-':\n d = reverse(d)\n j = 0\n while j < len(d) and d[j:j+3] != 'ATG':\n j += 1\n for i in range(j,len(d),3):\n if i+3 <= len(d):\n codon = d[i:i+3]\n prot += table[codon]\n return prot\n\n\n# Input: annotation, original genome sequence\ndef assemble_sequence(A,originalSeq):\n seq = ''\n for i in range(len(A.start)):\n seq += originalSeq[A.start[i]:A.end[i]]\n return seq\n\n# Find position of frameshift mutation on protein sequence\ndef find_corresponding_point(pos,A):\n nt_before = 0\n if A.strand == '+':\n for i in range(len(A.start)):\n if pos < A.start[i]:\n break\n elif pos < A.end[i]:\n nt_before += pos - A.start[i]\n elif pos >= A.end[i]:\n nt_before += A.end[i] - A.start[i]\n elif A.strand == '-':\n for i in range(len(A.start)-1,-1,-1):\n if pos > A.end[i]:\n break\n elif pos > A.start[i]:\n nt_before += A.end[i] - pos\n elif pos <= A.start[i]:\n nt_before += A.end[i] - A.start[i]\n aa_pos = nt_before // 3\n return aa_pos\n\n\ndef write_feature_results(path,pos,prot1,prot2,info,features):\n with open(path,'a') as f:\n f.write(str(pos)+'\\n')\n f.write(prot1+'\\n')\n f.write(prot2+'\\n')\n f.write('Comments:\\n')\n for c in info.comments:\n f.write(c+'\\n')\n keywords = ''\n for k in info.keywords:\n keywords += k + ' '\n f.write('Keywords: '+keywords+'\\n')\n f.write('Features:'+'\\n')\n for feature in features:\n f.write(feature.type+' ')\n f.write(feature.start+' ')\n f.write(feature.end+' ')\n f.write(feature.description)\n f.write('\\n')\n f.write('\\n')\n\n\ndef evaluate_effect(frameshifts,oriSeq1,oriSeq2,output_path):\n # Clear the text file first\n with open(output_path,'w') as f:\n f.write('')\n mapping = find_protein_id(frameshifts)\n for F in frameshifts:\n A1 = F.annotation_seq1\n A2 = F.annotation_seq2\n (prot1,prot2) = ('','')\n if A1 != None:\n seq1 = assemble_sequence(A1,oriSeq1)\n prot1 = dna_translation(seq1,A1.strand)\n if A2 != None:\n seq2 = assemble_sequence(A2,oriSeq2)\n prot2 = dna_translation(seq2,A2.strand)\n if A1 != None and A2 != None:\n # print(F.start1)\n # We assume that all amino acids after the insertion/deletion point\n # are affected.\n frameshift_pt = find_corresponding_point(F.start1,A1)\n # print(prot1[:frameshift_pt+1] + '||' + prot1[frameshift_pt+1:])\n # print(prot2)\n try:\n uniprot_id = mapping[F.gene_id]\n except:\n continue\n prot_info = find_protein_feature(uniprot_id)\n if prot_info == None:\n continue\n features = prot_info.features\n affected = []\n for i in range(len(features)):\n # We assume that if the mutated amino acid is within 2 nts of \n # the functional domain, it is likely to affect its function\n if int(features[i].end) + 2 >= frameshift_pt:\n affected.append(features[i])\n write_feature_results(output_path,F.start1,prot1,prot2,prot_info,\\\n features)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Frameshift_Analysis/evaluate_effect.py","file_name":"evaluate_effect.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338267083","text":"import sys\nimport urllib\n#from urllib import request\nimport os\nimport BeautifulSoup\n#from bs4 import BeautifulSoup\n\nclass DramaItem:\n def __init__(self, num, title, url):\n self.num = num\n self.title = title\n self.url = url\n def __str__(self):\n return self.num + ' ' + self.title\n def openDrama(self):\n os.startfile(self.url)\n\nresponse = urllib.request.urlopen('http://www.iqiyi.com/a_19rrgja8xd.html')\nhtml = response.read()\nsoup = BeautifulSoup(html)\ndramaList = soup.findAll('div', attrs={'class':'list_block1 align_c'})\ndramaItems = []\n\nif(dramaList):\n lis = dramaList[0].findAll('li')\n for li in lis:\n ps = li.findAll('p')\n description = ps[1].text if len(ps)>1 else ''\n num = ps[0].find('a').text\n url = ps[0].find('a')['href']\n di = DramaItem(num, description, url)\n dramaItems.append(di)\n\nfor di in dramaItems:\n print(di)\ndiLen = len(dramaItems)\nuserChoice = int(input('input number to watch the drama:'))\nif userChoice >= 1 and userChoice <=diLen:\n dramaItems[userChoice-1].openDrama()\n","sub_path":"20140310/aiqiyi.py","file_name":"aiqiyi.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"52735356","text":"# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\nfrom lib.batch_clone_from_gitlab import get_all_projects_from_gitlab, batch_clone_from_gitlab\nfrom lib.batch_push_to_github import batch_push_to_github\n\ngitlab_addr = 'ip:port'\ngitlab_token = 'ymsSzk' # 见gitlab官网或你的gitlab私服\ngithub_token = '5737a6' # 见你的github\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n batch_clone_from_gitlab(gitlab_addr, gitlab_token)\n\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","sub_path":"sync-gitlab-to-local.py","file_name":"sync-gitlab-to-local.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488958895","text":"#!coding=utf-8\nfrom os import path\nimport os\n\n#判断是否绝对路径\n# path.isabs(path)\n\n#判断是否为目录\n# path.isdir(path)\n\n#判断是否为文件\n# path.isfile(path)\n\n#判断指定文件是否存在\n# path.exists(path)\n\n#返回文件大小\n# path.getsize(filename)\n\n#返回绝对路径\n# path.abspath(path)\n\n#返回目录的路径\n# path.dirname(path)\n\n#返回文件的最后访问时间\n# path.getatime(filename)\n\n#返回文件的最后修改时间\n# path.getmtime(filename)\n\n#递归方式遍历目录\n# path.walk()\n\n#连接多个path\n# path.join(path,*paths)\n\n#对路径进行分割,以列表形式返回\n# path.split(path)\n\n#从路径分割文件的拓展名\n# path.splitext()\n\npath = os.getcwd()\n# print(path)\nfile_list = os.listdir(path)\nfor filename in file_list:\n if filename.endswith('py'):\n print(filename)\n\nfile_list2 = [filename for filename in os.listdir(path) if filename.endswith('py')]\nprint(file_list2)","sub_path":"教程2/os.path教程.py","file_name":"os.path教程.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"93604720","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, Http404\n\n# Create your views here.\ndef index(request):\n if 'person' in request.POST:\n if request.POST['person'] == 'ground_control' \\\n and request.POST['message'] == 'Ground Control to Major Tom':\n return HttpResponse(\n \"\"\"

This is Major Tom to Ground Control,\n I'm stepping through the door,\n And I'm floating in a most peculiar way,\n And the stars look very different today.

\"\"\")\n raise Http404(\"Huh?\")\n","sub_path":"django-multi-environment/azuredemo/demo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"166519363","text":"'''donuts'''\ndef donuts():\n '''gonna go eat some donuts'''\n price = int(input())\n dobuy = int(input())\n dofree = int(input())\n dowant = int(input())\n\n deal = dobuy + dofree\n pack = dowant // deal\n get = dowant - (pack * deal)\n if get >= dobuy:\n pack += 1\n get = 0\n askfor = (pack*deal) + get\n ask_1 = price *((pack * dobuy) + get)\n print('%d %d' %(ask_1, askfor))\ndonuts()\n","sub_path":"28_sep/donuts_alt.py","file_name":"donuts_alt.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"503368845","text":"import numpy as np\n\ndef row_swap(matrix, row1, row2):\n temp = np.copy(matrix[row1][:])\n matrix[row1][:] = matrix[row2][:]\n matrix[row2][:] = temp\n return matrix\n\ndef normalize(matrix, ind):\n matrix[ind[0]][:] = matrix[ind[0]][:] / matrix[ind[0]][ind[1]]\n return matrix\n\ndef row_eliminate(matrix, ind):\n numrow, numcol = matrix.shape\n \n for row in range(numrow):\n if row != ind[0]:\n matrix[row][:] -= matrix[ind[0]][:] * matrix[row][ind[1]]\n return matrix\n\ndef gauss_elim(matrix):\n current_loc = np.array([1, 1])\n numrow, numcol = matrix.shape\n location_matrix = np.zeros([numrow, numcol]) #matrix of all zeros, and a one at the current location\n\n while current_loc[0] <= numrow and current_loc[1] <= numcol:\n current_col_bottom = matrix[current_loc[0]-1:,current_loc[1]-1] #current_col_bottom excludes the portion of the current column above current row\n max_col_ind = np.argmax(np.absolute(current_col_bottom))\n matrix = row_swap(matrix, current_loc[0]-1, max_col_ind+current_loc[0]-1)\n current_loc_zero = current_loc - [1,1] # 0 indexed current location \n\n if matrix[current_loc_zero[0]][current_loc_zero[1]] != 0:\n matrix = normalize(matrix,current_loc_zero)\n matrix = row_eliminate(matrix,current_loc_zero)\n current_loc += np.array([1, 1])\n else:\n current_loc[1] += np.array([1])\n return matrix","sub_path":"EE16A_Homework/hw02/prob2/gauss_elim.py","file_name":"gauss_elim.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"350445198","text":"from random import choice\r\nfrom discord import Embed\r\nfrom asyncio import TimeoutError\r\nfrom Assets.AllWords import words\r\nfrom discord.errors import NotFound, Forbidden\r\n\r\nasync def anagram(message, client, color):\r\n \"\"\"Allow the user to play a anagram's game.\"\"\"\r\n try:\r\n def get_anagram(main_word):\r\n normal_words.append(main_word)\r\n main_word_scramble = sorted(list(main_word))\r\n anagram_words.append(main_word_scramble)\r\n for word in words:\r\n if not len(normal_words) >= 10:\r\n new_word = word\r\n if new_word != main_word:\r\n new_word_scramble = sorted(list(new_word))\r\n if all(letter in main_word_scramble\r\n for letter in set(new_word_scramble)):\r\n normal_words.append(new_word)\r\n else:\r\n break\r\n anagram_words, normal_words = [], []\r\n get_anagram(choice(words))\r\n\r\n normal_words = list(set(normal_words))\r\n\r\n async def show_game_message():\r\n discovered_words = []\r\n game_message = await message.channel.send(\r\n embed=Embed(title=\" \".join(str(letter).capitalize()\r\n for letter in anagram_words[0]),\r\n description=f\"Restam {len(normal_words)} palavras\",\r\n color=color)\r\n .set_footer(text=\"Você tem 60 segundos para enviar uma palavra, \"\r\n \"digite \\\"cancelar jogo\\\" para sair.\")\r\n )\r\n\r\n async def start_game():\r\n if len(normal_words) == 0:\r\n await game_message.edit(\r\n embed=Embed(title=\"Todas as palavras foram desembaralhadas!\",\r\n color=0x00FF00)\r\n .add_field(name=\"Palavras encontradas:\",\r\n value=\"\\n\".join(str(item) for item in discovered_words))\r\n )\r\n else:\r\n if len(discovered_words) > 0:\r\n await game_message.edit(\r\n embed=Embed(title=\" \".join(str(letter).capitalize()\r\n for letter in anagram_words[0]),\r\n description=\"Você tem 60 segundos para enviar uma \"\r\n \"palavra.\",\r\n color=color)\r\n .add_field(name=f\"Restam {len(normal_words)} palavras.\",\r\n value=\"\\n\".join(str(item) for item in discovered_words\r\n if len(discovered_words) > 0))\r\n .set_footer(text=\"Digite \\\"cancelar jogo\\\" para sair.\")\r\n )\r\n else:\r\n await game_message.edit(\r\n embed=Embed(title=\" \".join(str(letter).capitalize()\r\n for letter in anagram_words[0]),\r\n description=\"Você tem 60 segundos para enviar uma \"\r\n \"palavra.\",\r\n color=color)\r\n .add_field(name=f\"Restam {len(normal_words)} palavras.\",\r\n value=\"Não achou nenhuma palavra ainda.\")\r\n .set_footer(text=\"Digite \\\"cancelar jogo\\\" para sair.\")\r\n )\r\n\r\n def verify_message(msg):\r\n if msg.author.id == message.author.id: return msg\r\n user_msg = await client.wait_for(\"message\",\r\n check=verify_message,\r\n timeout=60.0)\r\n await user_msg.delete()\r\n user_msg = str(user_msg.content).lower()\r\n\r\n if user_msg in normal_words:\r\n del normal_words[normal_words.index(user_msg)]\r\n discovered_words.append(user_msg.upper())\r\n await start_game()\r\n elif user_msg == \"cancelar jogo\":\r\n await game_message.edit(\r\n embed=Embed(description=f\"Faltou {len(normal_words)} palavras.\",\r\n color=0xFFFF00)\r\n .set_author(name=\"O jogo foi cancelado\",\r\n icon_url=message.author.avatar_url)\r\n )\r\n else: await start_game()\r\n await start_game()\r\n await show_game_message()\r\n except TimeoutError:\r\n await message.channel.send(\r\n embed=Embed(title=\"Tempo esgotado.\", color=0xFFFF00))\r\n # Deleted message or missing permissions.\r\n except (NotFound, Forbidden): pass","sub_path":"Commands/Games/Anagram.py","file_name":"Anagram.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73960353","text":"import re\nimport sys\nimport time\nimport pickle\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom TransE import TransE\nfrom readTrainingData import smallDataSet\nfrom readTrainingDataBig import bigDataSet\nfrom collections import defaultdict, Counter\nimport logging\nimport torch.nn.functional as F\n\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n\nclass trainTransE:\n def __init__(self, in_dir, out_dir, pre_out_dir, preOrNot, isBig):\n \n self.isBig = isBig\n \n self.inDir = in_dir\n self.outDir = out_dir\n self.preDit = pre_out_dir\n self.preOrNot = preOrNot\n self.entityDimension = 100\n self.relationDimension = 100\n self.sizeOfBatches = 10000\n self.numOfEpochs = 100\n self.outputFreq = 5\n self.learningRate = 0.01 # 0.01\n self.weight_decay = 0.001 # 0.005 0.02\n self.margin = 1.0\n self.norm = 2\n self.top = 10\n\n self.train2id = {}\n self.nums = [0, 0, 0]\n \n self.numOfTriple = 0\n self.numOfEntity = 0\n self.numOfRelation = 0\n \n\n if torch.cuda.is_available():\n self.device = torch.device(\"cuda:0\")\n else:\n self.device = torch.device(\"cpu\")\n\n self.start()\n self.train()\n self.end()\n\n\n def start(self):\n logging.info (\"-----Training Started -----\")\n logging.info (\"input address: \" + self.inDir)\n logging.info (\"output address: \" +self.outDir)\n logging.info (\"entity dimension: \" + str(self.entityDimension))\n logging.info (\"relation dimension: \" + str(self.relationDimension))\n logging.info (\"number of epochs: \" + str(self.numOfEpochs))\n logging.info (\"output training results every \" + str(self.outputFreq) + \" epochs\")\n logging.info (\"learning rate: \" + str(self.learningRate))\n logging.info (\"weight decay: \" + str(self.weight_decay))\n logging.info (\"margin: \" + str(self.margin))\n logging.info (\"norm: \" + str(self.norm))\n logging.info (\"is a continued learning: \" + str(self.preOrNot))\n if self.preOrNot:\n logging.info (\"pre-trained result address: \" + self.preAdd)\n logging.info (\"device: \" + str(self.device))\n\n def end(self):\n logging.info (\"-----Training Finished at -----\")\n\n def train(self):\n if self.isBig == True:\n self.dataSet = bigDataSet(self.inDir)\n else:\n self.dataSet = smallDataSet(self.inDir)\n \n logging.info('Model initialize')\n transE = TransE(self.dataSet.numOfEntity, self.dataSet.numOfRelation, self.entityDimension, self.relationDimension, self.norm, self.device)\n logging.info(\"embeding matrix initialize complete\")\n if self.preOrNot:\n self.preRead(transE)\n \n criterion = nn.MarginRankingLoss(self.margin, False).to(self.device)\n optimizer = optim.SGD(transE.parameters(), lr=self.learningRate, weight_decay=self.weight_decay)\n\n dataLoader = DataLoader(dataset=self.dataSet, batch_size=self.sizeOfBatches, shuffle=True, num_workers=4, pin_memory=True)\n \n logging.info('training start')\n for epoch in range(self.numOfEpochs):\n epochLoss = 0\n count = 0\n for batch in dataLoader:\n logging.info(\"making corrupted_batch\")\n corruptedBatch = self.dataSet.generateCorruptedBatch(batch)\n optimizer.zero_grad()\n logging.info(\"forawrd calculation\")\n positiveLoss, negativeLoss = transE(batch, corruptedBatch)\n logging.info(\"seperate results\")\n logging.info(\"tmp tensor\")\n positiveLoss = positiveLoss.to(self.device)\n negativeLoss = negativeLoss.to(self.device)\n tmpTensor = torch.tensor([-1], dtype=torch.float).to(self.device)\n logging.info(\"calculate loss\")\n batchLoss = criterion(positiveLoss, negativeLoss, tmpTensor).to(self.device)\n logging.info(\"backward\")\n batchLoss.backward()\n logging.info(\"optimizer step\")\n optimizer.step()\n epochLoss += batchLoss\n count += 1\n logging.info(\"step_ended\")\n if count%100 == 0:\n logging.info (\"epoch \" + str(epoch) + + \"-\" + str(count) + \": , loss: \" + str(epochLoss))\n\n logging.info (\"epoch \" + str(epoch) + \": , loss: \" + str(epochLoss))\n\n if (epoch+1)%self.outputFreq == 0 or (epoch+1) == self.numOfEpochs:\n self.write(epoch, transE)\n print (\"\")\n\n\n def write(self, epoch, transE):\n logging.info (\"-----Writing Training Results at \" + str(epoch) + \" to \" + self.outDir + \"-----\")\n entity2vecAdd = self.outDir + \"/entity2vec\" + str(epoch) + \".pickle\"\n relation2vecAdd = self.outDir + \"/relation2vec\" + str(epoch) + \".pickle\"\n entityOutput = open(entity2vecAdd, \"wb\")\n relationOutput = open(relation2vecAdd, \"wb\")\n pickle.dump(transE.entityEmbeddings, entityOutput)\n pickle.dump(transE.relationEmbeddings, relationOutput)\n entityOutput.close()\n relationOutput.close()\n\n def preRead(self, transE):\n logging.info (\"-----Reading Pre-Trained Results from \" + self.preAdd + \"-----\")\n entityInput = open(self.preAdd + \"/entity2vec.pickle\", \"rb\")\n relationInput = open(self.preAdd + \"/relation2vec.pickle\", \"rb\")\n tmpEntityEmbedding = pickle.load(entityInput)\n tmpRelationEmbedding = pickle.load(relationInput)\n entityInput.close()\n relationInput.close()\n \n before_size = tmpEntityEmbedding.shape[0]\n dummy = transE.entity_embeddings.weight[before_size:].data\n transE.entity_embeddings.weight.data = torch.cat((tmpEntityEmbedding, dummy))\n transE.relation_embeddings.weight.data = tmpRelationEmbedding\n\n\nif __name__ == '__main__':\n IN_DIR = sys.argv[1]\n OUT_DIR = sys.argv[2]\n PRE_OUT_DIR = sys.argv[3] if sys.argv[3] != \"None\" else None\n PRE_OR_NOT = True if sys.argv[3] != \"None\" else False\n IS_BIG = True if sys.argv[4] == 'big' else False\n \n trainTransE = trainTransE(IN_DIR, OUT_DIR, PRE_OUT_DIR, PRE_OR_NOT, IS_BIG)\n\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":6417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151221205","text":"# -*- coding: cp1252 -*-\r\n# Sample Python/Pygame Programs\r\n# Simpson College Computer Science\r\n# http://cs.simpson.edu\r\n# Adaptado para projectos de MDP 2011-12\r\n\r\n#Tendo por base o código Aula1\\_pygame.py e os elementos disponíveis em\r\n#aula2.zip resolva os seguintes problemas: \r\n\r\n#\r\n# O invasor:\r\n#\r\n#1- Inicie o pygame com uma janela gráfica 400x500.\r\n#2- Junta imagem de fundo (sky.jpg).\r\n#3- Desloque no topo da janela, da esquerda para a direita,\r\n# a imagem de um OVNI (fno.png). Impondo o branco como a\r\n# cor transparente. \r\n#4- Use a metade inferior da janela para deslocar a imagem\r\n# do jogador, controlada pelo rato. Estas imagens estão\r\n# em play1.gif, play2.gif e play3.dif, devendo a imagem\r\n# escolhida depender do movimento do rato. Devendo usar\r\n# play1.gif quando o rato não está em movimento. Reservado\r\n# play2.gif e play3.gif, respectivamente, para identificar\r\n# as situações onde o rato se desloca da direita para a\r\n# esquerda e da esquerda para a direita. \r\n#5- O jogador dispara um círculo, no sentido ascendente, sempre\r\n# que se usa o botão esquerdo do rato. Atenção: os projecteis que\r\n# não estejam visíveis devem ser removidas da estrutura auxiliar. \r\n#6- Meta no ecrã um contador de pontos. Sempre que um projéctil\r\n# intersecte o OVNI, deve incrementá-lo. \r\n#7- Sempre que se dispara ou sempre que um projéctil intersecta o\r\n# OVNI devem ser emitidos sons diferentes. \r\n#\r\n \r\nimport pygame_sdl2 as pygame\r\n\r\nblack = [ 0, 0, 0]\r\nwhite = [255,255,255]\r\nblue = [ 0, 0,255]\r\ngreen = [ 0,255, 0]\r\nred = [255, 0, 0]\r\n\r\npygame.init()\r\n\r\ndef texto(pos,txt): \r\n font = pygame.font.Font(None, 25)\r\n text = font.render(txt,True,black)\r\n screen.blit(text, pos)\r\n \r\nscreen=pygame.display.set_mode([400,500]) \r\npygame.display.set_caption(\"MDP Game - OVNI -2012/13\")\r\n \r\ndone=False\r\nxfno=-50 #inicia x do OVNI\r\nyfno=50 #inicia y do OVNI\r\n\r\nxOld=0 #inicia coordenadas \r\nyOld=0\r\n\r\npontos = 0 #inicia pontos\r\n\r\nbalas=[]\r\n\r\nclock = pygame.time.Clock()\r\n\r\nbackground = pygame.image.load(\"sky.jpg\").convert()\r\nfno = pygame.image.load(\"fno.png\").convert() #imagem do OVNI\r\nfno.set_colorkey(white) # Define Cor que se assume como transparente\r\n\r\njogador=[] #incia lista de imagens do utilizador\r\njogador.append(pygame.image.load(\"play1.gif\").convert())\r\njogador.append(pygame.image.load(\"play2.gif\").convert())\r\njogador.append(pygame.image.load(\"play3.gif\").convert())\r\n\r\nbalas_sound = pygame.mixer.Sound(\"pickup.wav\") #som da bala a sair\r\nponto_sound = pygame.mixer.Sound(\"SCREECH.wav\") #som do OVNI\r\n\r\nwhile done==False:\r\n \r\n for event in pygame.event.get(): \r\n if event.type == pygame.QUIT: \r\n done=True \r\n \r\n screen.fill(blue)\r\n\r\n screen.blit(background, [0,0])\r\n\r\n # Rato \r\n pos = pygame.mouse.get_pos() #coordenadas do rato\r\n \r\n #posição do rato\r\n xR=pos[0]\r\n yR=pos[1]\r\n\r\n mousestat= pygame.mouse.get_pressed() #teclas do rato\r\n\r\n\r\n # Jogor:\r\n if yR<250: # Limita yR\r\n yR=250\r\n elif yR>450:\r\n yR=450\r\n\r\n if xR<0: # Limita xR\r\n xR=0\r\n elif xR>350:\r\n xR=350\r\n \r\n if xRxOld:\r\n screen.blit(jogador[2], [xR,yR]) #move esquerda\r\n else:\r\n screen.blit(jogador[0], [xR,yR]) #está parado ou move na vertical\r\n\r\n\r\n xOld=xR #actualiza posição\r\n yOld=yR\r\n\r\n # adiciona bala na lista balas\r\n if mousestat[0]:\r\n balas.append([xR+30,yR])\r\n balas_sound.play()\r\n\r\n if xfno>450: #chega ao fim da janela\r\n xfno=-50\r\n else:\r\n xfno=xfno+15\r\n\r\n screen.blit(fno, [xfno,yfno]) #desenha OVNI\r\n\r\n #move bala\r\n newbalas=[]\r\n #update da posição das bolas na lista balas\r\n for bala in balas:\r\n if bala[1]>0: #bola chega ao topo da janela\r\n print(newbalas)\r\n xB=bala[0] #coordenadas da bola\r\n yB=bala[1]\r\n pygame.draw.circle(screen,black,[xB,yB],5) #pinta bola\r\n if xB>xfno and xByfno and yB None:\n \"\"\"Adds labels to an existing pull request.\"\"\"\n pass\n\n\nclass AbstractChangePusher(ABC):\n \"\"\"Abstractly, the thing that pushes changes to github.\"\"\"\n\n @abstractmethod\n def push_changes(\n self, commit_count: int, branch: str, pr_title: str, synth_log: str = \"\"\n ) -> AbstractPullRequest:\n \"\"\"Creates a pull request from commits in current working directory.\n\n Arguments:\n commit_count {int} -- How many commits are in this pull request?\n branch {str} -- The name of the local branch to push.\n pr_title {str} -- The title for the pull request.\n\n Keyword Arguments:\n synth_log {str} -- The full log of the call to synth. (default: {\"\"})\n\n Returns:\n A pull request.\n \"\"\"\n pass\n\n @abstractmethod\n def check_if_pr_already_exists(self, branch) -> bool:\n pass\n\n\nclass PullRequest(AbstractPullRequest):\n def __init__(self, gh: github.GitHub, pr: typing.Dict[str, typing.Any]):\n self._gh = gh\n self._pr = pr\n\n def add_labels(self, labels: typing.Sequence[str]) -> None:\n \"\"\"Adds labels to an existing pull request.\"\"\"\n self._gh.update_pull_labels(self._pr, add=labels)\n\n\nclass ChangePusher(AbstractChangePusher):\n \"\"\"Actually pushes changes to github.\"\"\"\n\n def __init__(\n self, repository: str, gh: github.GitHub, synth_path: str, default_branch: str\n ):\n self._repository = repository\n self._gh = gh\n self._synth_path = synth_path\n # maps branch name to pr json response\n self._existing_pull_requests: typing.Dict[str, typing.Any] = {}\n self.default_branch = default_branch\n\n def push_changes(\n self, commit_count: int, branch: str, pr_title: str, synth_log: str = \"\"\n ) -> AbstractPullRequest:\n git.push_changes(branch)\n trailers = _collect_trailers(commit_count)\n\n pr = self._existing_pull_requests.get(branch)\n new_body = build_pr_body(synth_log, trailers)\n if pr:\n pr = self._gh.update_pull_request(\n self._repository, pr[\"number\"], body=new_body\n )\n else:\n pr = self._gh.create_pull_request(\n self._repository,\n branch=branch,\n title=pr_title[0:250],\n body=new_body,\n base_branch=self.default_branch,\n )\n\n # args.synth_path (and api: * labels) only exist in monorepos\n if self._synth_path:\n api_label = self._gh.get_api_label(self._repository, self._synth_path)\n\n if api_label:\n self._gh.update_pull_labels(pr, add=[api_label])\n return PullRequest(self._gh, pr)\n\n def check_if_pr_already_exists(self, branch) -> bool:\n repo = self._repository\n owner = repo.split(\"/\")[0]\n prs = self._gh.list_pull_requests(repo, state=\"open\", head=f\"{owner}:{branch}\")\n\n if prs:\n pr = prs[0]\n self._existing_pull_requests[branch] = pr\n logger.info(f'PR already exists: {pr[\"html_url\"]}')\n body: str = pr[\"body\"]\n if REGENERATE_CHECKBOX_TEXT in body:\n logger.info(\"Someone requested the PR to be regenerated.\")\n return False\n\n return bool(prs)\n\n\nclass SquashingChangePusher(AbstractChangePusher):\n \"\"\"Wraps another change pusher to squash all commits into a single commit\n\n before pushing the pull request to github.\"\"\"\n\n def __init__(self, inner_change_pusher: AbstractChangePusher):\n self.inner_change_pusher = inner_change_pusher\n\n def push_changes(\n self, commit_count: int, branch: str, pr_title: str, synth_log: str = \"\"\n ) -> AbstractPullRequest:\n if commit_count < 2:\n # Only one change, no need to squash.\n return self.inner_change_pusher.push_changes(\n commit_count, branch, pr_title, synth_log\n )\n\n executor.check_call([\"git\", \"checkout\", branch]) # Probably redundant.\n with tempfile.NamedTemporaryFile() as message_file:\n # Collect the commit messages into a temporary file.\n message_file.write(\"changes triggered by multiple versions\\n\\n\".encode())\n message_file.flush()\n executor.run(\n [\"git\", \"log\", f\"-{commit_count}\", \"--format=* %s%n%b\"],\n stdout=message_file,\n check=True,\n )\n message_file.file.close() # type: ignore\n # Do a git dance to construct a branch with the commits squashed.\n temp_branch = str(uuid.uuid4())\n executor.check_call([\"git\", \"branch\", \"-m\", temp_branch])\n executor.check_call([\"git\", \"checkout\", f\"HEAD~{commit_count}\"])\n executor.check_call([\"git\", \"checkout\", \"-b\", branch])\n executor.check_call([\"git\", \"merge\", \"--squash\", temp_branch])\n executor.check_call([\"git\", \"commit\", \"-F\", message_file.name])\n return self.inner_change_pusher.push_changes(1, branch, pr_title, synth_log)\n\n def check_if_pr_already_exists(self, branch) -> bool:\n return self.inner_change_pusher.check_if_pr_already_exists(branch)\n\n\ndef build_pr_body(synth_log: str, trailers: str = \"\"):\n \"\"\"Composes the pull request body with the synth_log.\n\n If synth_log is empty, then creates link to kokoro build log.\n \"\"\"\n build_log_text = \"\"\n kokoro_build_id = os.environ.get(\"KOKORO_BUILD_ID\")\n if synth_log:\n length_limit = 40000\n if len(synth_log) > length_limit:\n synth_log = \"[LOG TRUNCATED]\\n\" + synth_log[-length_limit:]\n build_log_text = f\"\"\"\n
Log from Synthtool\n\n```\n{synth_log}\n```\n
\"\"\"\n if kokoro_build_id:\n build_log_text += f\"\"\"\n\nFull log will be available here:\nhttps://source.cloud.google.com/results/invocations/{kokoro_build_id}/targets\"\"\"\n elif kokoro_build_id:\n build_log_text = f\"\"\"Synth log will be available here:\nhttps://source.cloud.google.com/results/invocations/{kokoro_build_id}/targets\"\"\"\n\n return f\"\"\"\\\nThis PR was generated using Autosynth. :rainbow:\n\n{build_log_text}\n\n{REGENERATE_CHECKBOX_TEXT.replace('[x]', '[ ]')} (May take up to 24 hours.)\n\n{trailers}\n\"\"\".strip()\n\n\ndef _collect_trailers(commit_count: int, git_dir: typing.Optional[str] = None) -> str:\n \"\"\"Collects the trailers from recent commits in the repo.\n\n Only collects the two trailers we're interested in.\n Arguments:\n commit_count {int} -- Number of commits to collect trailers from.\n\n Keyword Arguments:\n git_dir {typing.Optional[str]} -- directory of git repo (default: {None})\n\n Returns:\n str -- The trailer lines from the recent commits.\n \"\"\"\n text = executor.run(\n [\"git\", \"log\", f\"-{commit_count}\", \"--pretty=%b\"],\n universal_newlines=True,\n check=True,\n stdout=subprocess.PIPE,\n cwd=git_dir,\n ).stdout\n return _parse_trailers(text)\n\n\ndef _parse_trailers(text: str) -> str:\n \"\"\"Parses and returns trailers in the text.\n\n Arguments:\n text {str} -- commit body text with trailers\n\n Returns:\n str -- the trailer lines.\n \"\"\"\n lines = text.splitlines()\n trailer = re.compile(r\"\\s*(Source-Link:|PiperOrigin-RevId:).*\")\n return \"\\n\".join([line for line in lines if trailer.match(line)])\n","sub_path":"autosynth/change_pusher.py","file_name":"change_pusher.py","file_ext":"py","file_size_in_byte":8625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"108420447","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom .models import Guide, Article\nfrom destinations.models import Region, Country\n\n\ndef index(request):\n guides = Guide.objects.filter(published=True).order_by('modified')[:10]\n\n context = {'guides': guides}\n\n return render(request, 'guides/index.html', context)\n\n\ndef guide_list(request):\n regions = Region.objects.all()\n guides = Guide.objects.filter(published=True).order_by('modified')\n\n context = {'guides': guides, 'regions': regions,}\n\n return render(request, 'guides/guide_list.html', context)\n\n\ndef country_guide_list(request, slug):\n regions = Region.objects.all()\n country = get_object_or_404(Country, slug=slug)\n guides = Guide.objects.filter(countries=country)\n guides = guides.filter(published=True).order_by('modified')\n\n context = {'guides': guides, 'regions': regions,}\n\n return render(request, 'guides/guide_list.html', context)\n\n\ndef guide(request, slug):\n guide = get_object_or_404(Guide, slug=slug)\n articles = guide.article_set.filter(published=True).order_by('ordering')\n\n context = {'guide': guide, 'articles': articles}\n\n return render(request, 'guides/guide.html', context)\n\n\ndef article(request, slug):\n article = get_object_or_404(Article, slug=slug)\n guide = get_object_or_404(Guide, article=article)\n\n context = {'article': article, 'guide': guide}\n\n return render(request, 'guides/article.html', context)\n","sub_path":"guides/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377969395","text":"\"\"\"\n@author:\nTasso Luís Oliveira de Moraes\ntlom@cin.ufpe.br\n\nProjeto de Introdução a Python\nResidência Visão Computacional\nCIn - UFPE\n\"\"\"\n\nimport graficos\nfrom graficos import curva_de_crescimento_peso\n\n#CRIA PRONTUÁRIO\ndef criar_protuario(dic_protuarios, ultimo_num_paciente,lista_chaves):\n prontuario = {}\n lista_input = [\"Digite o nome da criança\",\n \"Digite o sexo da criança\",\n \"Digite o nome da mãe\",\n \"Digite o nome do pai\",\n \"Digite o peso atual\",\n \"Digite o IMC atual\",\n \"Digite a altura atual\",\n \"Digite o perímetro cefálico atual\"]\n\n chaves_input = zip(lista_chaves,lista_input)\n\n num_paciente = ultimo_num_paciente + 1 #sempre incrementa a partir do ultimo criado\n\n for chave, dado_input in chaves_input:\n if(chave == \"Peso\" or chave == \"IMC\" or chave == \"Altura\" or chave == \"Perimétro Cefálico\"):\n prontuario[chave] = [float(input(dado_input + \": \"))]\n else:\n prontuario[chave] = input(dado_input + \": \")\n\n dic_protuarios[num_paciente] = prontuario\n\n return num_paciente\n\n#MENU ATUALIZAR\ndef imprime_menu_atualizar():\n menu = \"\"\"\n ####### MENU #######\n 1 - Nome\n 2 - Sexo\n 3 - Nome da mãe \n 4 - Nome do pai\n 5 - Peso\n 6 - IMC\n 7 - Altura\n 8 - Perímetro cefálico\n 0 - Sair\n ####################\n \nQual informação você deseja atualizar: \"\"\"\n opcao = int(input(menu))\n return opcao\n\n#ATUALIZAR\ndef atualizar_prontuario_por_numero(dic_prontuarios, numero):\n\n #verifica se o prontuário existe ou não\n if (len(dic_prontuarios) < 1) or (numero not in dic_prontuarios.keys()):\n print(\"Nenhum prontuário encontrado!\")\n else:\n prontuario = dic_prontuarios[numero]\n opcao = \"\"\n #chaves recebe uma lista das chaves do dicionário\n chaves = list(prontuario.keys())\n\n busca_prontuario_por_numero(dic_prontuarios, numero)\n # pergunta qual dado atualizar\n while (opcao != \"não\"):\n indice = imprime_menu_atualizar() #recebe um inteiro\n #se o indice estiver entre 1 e a quantidade de chaves\n if(indice >= 1 and indice <= len(chaves)):\n novo_valor = input(f\"\\tDigite o novo valor de {chaves[indice-1]}: \")\n #se for um valor que compões uma lista adiciona o elemento na lista\n if(chaves[indice-1] == \"Peso\" or chaves[indice-1] == \"IMC\" or chaves[indice-1] == \"Altura\" or chaves[indice-1] == \"Perimétro Cefálico\"):\n prontuario[chaves[indice-1]].append(float(novo_valor))\n else:\n prontuario[chaves[indice-1]] = novo_valor\n\n elif(opcao != 0):\n print(\"Entrada inválida!\")\n\n opcao = input(\"\\tDeseja alterar mais alguma informação? \")\n\n\n print(\"---Contao atualizado---\")\n busca_prontuario_por_numero(dic_prontuarios,numero)\n\n#BUSCA PRONTUÁRIO\ndef busca_prontuario_por_numero(dic_prontuarios, numero):\n\n #verifica se o prontuário existe ou não\n if (len(dic_prontuarios) < 1) or (numero not in dic_prontuarios.keys()):\n print(\"Nenhum prontuário encontrado!\")\n else:\n prontuario = dic_prontuarios[numero]\n\n for chave in prontuario.keys():\n print(f\"{chave}: {prontuario[chave]}\")\n\n #GRAFICOS\n graficos.curva_de_crescimento_peso(prontuario[\"Peso\"],prontuario[\"Nome\"] )\n\n#REMOVER PRONTUARIO POR NÚMERO\ndef remove_prontuario_por_numero(dic_prontuarios, numero):\n\n #verifica se o prontuário existe ou não\n if (len(dic_prontuarios) < 1) or (numero not in dic_prontuarios.keys()):\n print(\"Nenhum prontuário encontrado!\")\n else:\n dic_prontuarios.pop(numero)\n print(\"Paciente removido!\")\n\n#REMOVER PRONTUÁRIO POR NOME\ndef remove_prontuario(dic_prontuarios, nome_paciente):\n\n lista_prontuarios = {}\n for numero, prontuario in dic_prontuarios.items():\n if nome_paciente in prontuario[\"Nome\"]:\n lista_prontuarios[numero] = prontuario\n\n if (len(lista_prontuarios) == 1):\n numero = list(lista_prontuarios.keys())[0]\n remove_prontuario_por_numero(dic_prontuarios,numero)\n else:\n listar_prontuarios(lista_prontuarios)\n opcao = int(input(\"Digite o número do prontuário a ser removido: \"))\n remove_prontuario_por_numero(dic_prontuarios,opcao)\n\n#LISTAR PRONTUÁRIOS\ndef listar_prontuarios(dic_prontuarios):\n # verifica se o prontuário existe ou não\n if (len(dic_prontuarios) < 1):\n print(\"Nenhum prontuário encontrado!\")\n else:\n print(f\"N. do prontuário - Paciente\")\n for num_prontuario in dic_prontuarios:\n nome = dic_prontuarios[num_prontuario]['Nome']\n print(f\" \\t\\t{num_prontuario}\\t\\t - \\t {nome}\")\n #busca_prontuario_por_numero(dic_prontuarios, num_prontuario)\n\n#IMRPIME MENU\ndef imprime_menu():\n menu = \"\"\"\n ####### MENU #######\n 1 - Cadastrar\n 2 - Buscar\n 3 - Remover \n 4 - Atualizar\n 5 - Listar\n 0 - Sair\n ####################\n \"\"\"\n print(menu)\n\n#SALVA ARQUIVO\ndef salva_arquivo(dic_prontuarios, ultimo_paciente, arquivo):\n\n arquivo.write(str(ultimo_paciente)+\"\\n\")\n for num_pront, dic_pront in dic_prontuarios.items():\n arquivo.write(f\"{num_pront}-\")\n\n for chave, valor in dic_pront.items():\n if(chave == \"Peso\" or chave == \"IMC\" or chave == \"Altura\" or chave == \"Perimétro Cefálico\"):\n # troca a ',' por '/' e remove os \" \"\n valor = str(valor).replace(\",\", \"/\")\n valor = valor.replace(\" \", \"\")\n if (chave == \"Perimétro Cefálico\"):\n arquivo.write(f\"{chave}:{valor}\")\n else:\n arquivo.write(f\"{chave}:{valor},\")\n else:\n arquivo.write(f\"{chave}:{valor},\")\n\n arquivo.flush()\n\n arquivo.write(\"\\n\")\n\n#LER AQUIVO\ndef ler_arquivo(dic_prontuarios, nome_arquivo):\n arquivo = open(nome_arquivo,\"r\")\n linhas = arquivo.readlines()\n\n # a primeira linha do arquivo contem o número do ultimo prontuário criado\n num_ult_prontuario = int(linhas[0].strip()) # remove o \\n e converte em inteiro\n linhas.remove(linhas[0])\n\n for linha in linhas:\n numero, dados = linha.split(\"-\") # separa a chave do primeiro dicionário (número do prontuário)\n num_prontuario = int(numero)\n\n prontuario = {}\n for item in dados.split(\",\"): # separa os itens do segundo dicionário\n chave, dado = item.split(\":\") # separa a chave do dado\n if dado[0] == \"[\":\n dado = dado.replace(\"[\",\"\") # remove [\n dado = dado.replace(\"]\",\"\") # remove ]\n dado = dado.replace(\"\\n\",\"\") # remove \\n\n dado = dado.split(\"/\") # transforma em lista separando elementos\n for i in range(len(dado)): # transforma os itens da lista em reais\n dado[i] = float(dado[i])\n prontuario[chave] = dado\n\n #prontuario[\"Perimétro Cefálico\"] = dado.strip()\n dic_prontuarios[num_prontuario] = prontuario\n\n arquivo.close()\n return num_ult_prontuario\n\nprontuarios = {}\nultimo_paciente = 0\nopcao = \"\"\nnome_do_arquivo = \"prontuarios.txt\"\nlista_dados = [\"Nome\", \"Sexo\", \"Mãe\", \"Pai\", \"Peso\", \"IMC\", \"Altura\", \"Perimétro Cefálico\"]\n\nwhile (opcao != \"0\"):\n\n imprime_menu()\n opcao = input(\"Digite uma das opções: \")\n\n if (opcao == \"1\"):\n ultimo_paciente = ler_arquivo(prontuarios,nome_do_arquivo) # recebe o valor do arquivo\n #print(f\"prontuarios antes: {prontuarios}\")\n\n print(\"\\nCadastrar novo paciente:\")\n ultimo_paciente = criar_protuario(prontuarios,ultimo_paciente,lista_dados) # atualiza o valor\n #print(f\"prontuarios depois: {prontuarios}\")\n\n arquivo = open(nome_do_arquivo, \"w\")\n salva_arquivo(prontuarios,ultimo_paciente,arquivo)\n arquivo.close()\n\n elif (opcao == \"2\"):\n ultimo_paciente = ler_arquivo(prontuarios,nome_do_arquivo) # recebe o valor do arquivo\n\n listar_prontuarios(prontuarios)\n print(\"\\nBuscar paciente:\")\n numero = int(input(\"Digite o número do paciente: \"))\n busca_prontuario_por_numero(prontuarios,numero)\n\n elif (opcao == \"3\"):\n ultimo_paciente = ler_arquivo(prontuarios,nome_do_arquivo) # recebe o valor do arquivo\n\n print(\"\\nRemover paciente:\")\n nome = input(\"Digite o nome do paciente: \")\n remove_prontuario(prontuarios, nome)\n\n arquivo = open(nome_do_arquivo, \"w\")\n salva_arquivo(prontuarios,ultimo_paciente,arquivo)\n arquivo.close()\n\n elif (opcao == \"4\"):\n ultimo_paciente = ler_arquivo(prontuarios,nome_do_arquivo) # recebe o valor do arquivo\n\n listar_prontuarios(prontuarios)\n print(\"\\nAtualizar paciente:\")\n numero = int(input(\"Digite o número do paciente: \"))\n atualizar_prontuario_por_numero(prontuarios, numero)\n\n arquivo = open(nome_do_arquivo, \"w\")\n salva_arquivo(prontuarios,ultimo_paciente,arquivo)\n arquivo.close()\n\n elif (opcao == \"5\"):\n ultimo_paciente = ler_arquivo(prontuarios,nome_do_arquivo) # recebe o valor do arquivo\n\n print(\"\\nListando prontuários:\")\n listar_prontuarios(prontuarios)\n\n #GRÁFICOS\n graficos.porcentagem_peso(prontuarios)\n\n elif (opcao != \"0\"):\n print(\"Opção invalida!\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199239990","text":"__author__ = ''\n\nimport sys, os, tokenizer\nfrom trainer import train\nfrom tester import test\n# from textNormalizer import check_token\n\n\ndef main():\n\n # setting the current working directory to project root\n os.chdir('..')\n\n classes = [\"politik\", \"sport\", \"wirtschaft\"]\n\n print(\"Start learning from training data...\")\n trainings_set, prio_prob = train(\"data\", classes)\n\n\n print(\"test data...\")\n test(\"data\", classes, trainings_set)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"content_managment_search_tech/naiveclassifier/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88093159","text":"import json\nimport copy\nimport os\n\nclass TKEYS:\n TAGKBASE = 'tag_base'\n TAGK0 = 'tag_key_0'\n TAGK1 = 'tag_key_1'\n TAGK2 = 'tag_key_2'\n TAGK3 = 'tag_key_3'\n TAGK4 = 'tag_key_4'\n TAGK5 = 'tag_key_5'\n TAGK6 = 'tag_key_6'\n TAGK7 = 'tag_key_7'\n\n KEY = 'key'\n VAL = 'val'\n VALTYPE = 'val_type'\n LIST = 'list'\n DICT = 'dict'\n SET = 'set'\n SCALAR = 'scalar'\n OBJECT = 'object'\n\n OPADD = 'add'\n OPDEL = 'del'\n OPSUB = 'sub'\n OPOVR = 'override'\n\n GROUP_TAGS = 'group_tags'\n GROUP_ROWS = 'group_rows'\n GROUP_OPS = 'group_ops'\n GROUP_SUBTREE = 'group_subtree'\n\n TAGS = 'tags'\n\n ID = 'id'\n PATH = 'path'\n PATH_LIST = 'path_list'\n SUBKEY_PATH = 'subkey_path'\n TAGGROUPOPS = 'tag_ops'\n FILENAME = 'filename'\n FULL_PAYLOAD = 'full_payload'\n VERSION = 'version'\n\n IS_MODIFIED = 'is_modified'\n IS_ACTIVE = 'is_active'\n\nclass TVALS:\n TAG_KEY_ORDER = [TKEYS.TAGK0,TKEYS.TAGK1,TKEYS.TAGK2,TKEYS.TAGK3,TKEYS.TAGK4,TKEYS.TAGK5,TKEYS.TAGK6,TKEYS.TAGK7]\n\nclass util:\n @staticmethod\n def get_edata_type(value):\n if value == None:\n return None\n if isinstance(value,list):\n return TKEYS.LIST\n if isinstance(value,dict):\n return TKEYS.DICT\n if isinstance(value,set):\n return TKEYS.SET\n return TKEYS.OBJECT\n\nclass Row:\n GID = 0\n\n def __init__(self,\n key, # key name of value, not tag_key hierarchy name\n val=None,\n subkey_path=None, # specify if modify key is dict and modify subkey\n basename='basename1',\n dict_tags={}, # tag_key associated with this key\n dict_ops={},\n isactive=True):\n self.id = Row.GID\n Row.GID += 1\n\n self.key = key\n self.val = val\n self.valtype = util.get_edata_type(val)\n self.subkey_path = subkey_path # keypath is split by delimiter / to get to correct hierarchy\n self.basename = basename\n self.dict_tags = dict_tags\n self.dict_ops = dict_ops\n self.isactive = isactive\n self.is_override = False if(len(dict_tags) == 0 or\n (len(dict_tags) == 1 and TKEYS.TAGK0 in dict_tags)) \\\n else True\n\n self.map = {\n TKEYS.ID : self.id,\n TKEYS.KEY : self.key,\n TKEYS.VAL : self.val,\n TKEYS.VALTYPE : self.valtype,\n TKEYS.SUBKEY_PATH : self.subkey_path,\n TKEYS.TAGKBASE : self.basename,\n TKEYS.GROUP_TAGS : self.dict_tags,\n TKEYS.GROUP_OPS : self.dict_ops,\n TKEYS.IS_ACTIVE : self.isactive\n }\n\n def get_row_map(self):\n return self.map\n\n def to_string(self):\n return f\"id:{self.id} key:{self.key} val:{self.val} keypath:{self.subkey_path}\"\n\n\nclass GenerateInheritedDicts:\n ID = 1\n VERSION = 1\n VERSION_FILENAME = 1\n\n def __init__(self):\n self.keypath_delimiter = '/'\n self.cur_id = self.get_next_id()\n self.tag_order_dict = TVALS.TAG_KEY_ORDER\n self.filename_suffix = '.json'\n self.tree = None\n\n def get_next_id(self):\n id = GenerateInheritedDicts.ID\n GenerateInheritedDicts.ID += 1\n return id\n\n def get_version_id(self,do_increment=False):\n id = GenerateInheritedDicts.VERSION\n if do_increment == True:\n GenerateInheritedDicts.VERSION += 1\n return id\n\n def get_next_version_filename_id(self):\n v = GenerateInheritedDicts.VERSION_FILENAME\n GenerateInheritedDicts.VERSION_FILENAME += 1\n return v\n\n def get_next_version_id(self):\n self.get_version_id(True)\n return self.get_version_id()\n\n def set_keypath_delimiter(self,delimiter):\n self.keypath_delimiter = delimiter\n\n def get_next_tag_key_from_ordered_list(self,cur_tag_key,tag_key_order_list):\n last_visited_idx = 0\n if cur_tag_key == None:\n return tag_key_order_list[0]\n sz = len(tag_key_order_list)\n for i in range(last_visited_idx,sz):\n if cur_tag_key == tag_key_order_list[i]:\n if (i+1) < sz:\n return tag_key_order_list[i+1]\n else:\n return None\n return None\n\n def get_next_tag_key_from_row(self,row,tag_key_order_list,cur_tag_key=None):\n sz = len(tag_key_order_list)\n row_tags = row.get_row_map()[TKEYS.GROUP_TAGS]\n idx = None\n\n if cur_tag_key == None:\n for i in range(sz):\n if tag_key_order_list[i] in row_tags:\n return tag_key_order_list[i]\n return None\n\n next_tag_key = cur_tag_key\n for i in range(sz):\n if next_tag_key == tag_key_order_list[i]:\n idx = i+1\n break\n\n if idx == None:\n return None\n for i in range(idx,sz):\n if tag_key_order_list[i] in row_tags:\n return tag_key_order_list[i]\n return None\n\n def generate_tree_info_structure(self,path=None,filename=None,version=None,modified=None):\n node = {\n TKEYS.PATH:path,\n TKEYS.FILENAME:filename,\n TKEYS.GROUP_SUBTREE:{},\n #TKEYS.IS_MODIFIED:None\n }\n return node\n\n def generate_tree_file_structure(self,path=None,tag_key=None,tag_val=None,version=None):\n updated_version = version if version != None else self.get_version_id(True)\n node = {\n TKEYS.ID:self.get_next_id(),\n TKEYS.GROUP_TAGS:{},\n TKEYS.PATH:path,\n TKEYS.FILENAME:None,\n TKEYS.FULL_PAYLOAD:None,\n TKEYS.TAGKBASE:tag_val,\n TKEYS.GROUP_SUBTREE:{},\n TKEYS.VERSION:updated_version,\n TKEYS.IS_MODIFIED:False\n }\n if tag_key != None and tag_val != None:\n node[TKEYS.GROUP_TAGS][tag_key] = tag_val\n return node\n\n def generate_general_tag_node_structure(self,path=None,tag_key=None,tag_val=None):\n node = {\n TKEYS.ID:self.get_next_id(),\n TKEYS.PATH:path,\n TKEYS.GROUP_TAGS:{},\n TKEYS.GROUP_ROWS:[],\n TKEYS.GROUP_SUBTREE:{}\n }\n if tag_key != None and tag_val != None:\n node[TKEYS.GROUP_TAGS][tag_key] = tag_val\n return node\n\n '''\n\n this is used as template tree. use this tree to put the rows of\n data into the correct hierarchy, where rows may be repeated.\n\n after putting rows of data into this hiearchy, create a new tree\n with inherited/modified values for each subtree node\n :param dict_tags:\n {\n TKEYS.TAGKBASE:'jsonbase1',\n TKEYS.TAGK0: [v0,v1],\n TKEYS.TAGK1: [v10,v11,v12],\n TKEYS.TAGK2: [v20,v21,v22],\n TKEYS.TAGK3: [v30,v31,v32],\n TKEYS.TAGK4: [v40,v41,v42],\n }\n :return:\n {\n 'basename1':{\n TKEYS.ID = ,\n TKEYS.PATH = 'hierarchy string value',\n // dict\n TKEYS.GROUP_TAGS:{\n TKEYS.TAGKBASE:'...'\n },\n // list\n TKEYS.GROUP_NODES:[row1,row2,...],\n TKEYS.GROUP_SUBTREE:{\n v0:{\n TKEYS.ID = ,\n TKEYS.PATH = 'hierarchy string value',\n TKEYS.GROUP_TAGS:{TKEYS.TAGK0:'...'},\n TKEYS.GROUP_NODES:[row1,row2,...],\n TKEYS.GROUP_SUBTREE:{\n v10:{\n TKEYS.ID = ,\n TKEYS.PATH = 'hierarchy string value',\n TKEYS.GROUP_TAGS:{TKEYS.TAGK1:'...'},\n TKEYS.GROUP_NODES:[row1,row2,...],\n TKEYS.GROUP_SUBTREE:{\n v20:{\n TKEYS.ID = ,\n TKEYS.PATH = 'hierarchy string value',\n TKEYS.GROUP_TAGS:{TKEYS.TAGK2:'...'},\n TKEYS.GROUP_NODES:[row1,row2,...],\n TKEYS.GROUP_SUBTREE:{\n v30:{\n ...\n },\n v31:{\n }\n }\n },\n v21:{\n ...\n }\n }\n },\n v11:{\n ...\n }\n }\n }\n }\n }\n }\n\n '''\n def generate_general_tag_tree(self,dict_tags,tag_key_order_list):\n def generate_tag_tree(dict_tags,tree,tag_key_order_list,subpath=[],idx_tag_key_order_list=0):\n try:\n sz = len(tag_key_order_list)\n if idx_tag_key_order_list >= sz:\n return\n tag_key_from_order_list = tag_key_order_list[idx_tag_key_order_list]\n if tag_key_from_order_list not in dict_tags:\n return\n for tag_val in dict_tags[tag_key_from_order_list]:\n subpath.append(tag_val)\n path = self.keypath_delimiter.join(subpath)\n tree[TKEYS.GROUP_SUBTREE][tag_val] = self.generate_general_tag_node_structure(\n path=path,tag_key=tag_key_from_order_list,tag_val=tag_val)\n generate_tag_tree(dict_tags,tree[TKEYS.GROUP_SUBTREE][tag_val],tag_key_order_list,subpath,idx_tag_key_order_list+1)\n subpath.pop()\n except Exception as e:\n raise e\n finally:\n return\n\n def generate_tag_tree_base(dict_tags,tree):\n tag_bases = dict_tags[TKEYS.TAGKBASE]\n for tag_base in tag_bases:\n tree[tag_base] = self.generate_general_tag_node_structure(tag_base,TKEYS.TAGKBASE,tag_base)\n\n tree = {}\n generate_tag_tree_base(dict_tags,tree)\n for basenames,subtree in tree.items():\n generate_tag_tree(dict_tags,subtree,tag_key_order_list)\n return tree\n\n def generate_tree_from_dict_hierarchy(self,dict_hierarchy,tag_key_order_list):\n def generate_tree(dict_hierarchy,tree,tag_key_order_list,subpath=[],idx_tag_key=0):\n for tag_key,subtree_hierarchy in dict_hierarchy.items():\n assert tag_key in tag_key_order_list\n for tag_value,subtree_tree in subtree_hierarchy.items():\n subpath.append(tag_value)\n path = self.keypath_delimiter.join(subpath)\n tree[tag_value] = self.generate_general_tag_node_structure(\n path=path,tag_key=tag_key,tag_val=tag_value)\n generate_tree(\n dict_hierarchy[tag_key][tag_value],\n tree[tag_value][TKEYS.GROUP_SUBTREE],\n tag_key_order_list,\n subpath,\n idx_tag_key+1)\n subpath.pop()\n tree = {}\n generate_tree(dict_hierarchy,tree,tag_key_order_list)\n return tree\n\n\n\n def put_row_in_tag_tree(self,\n row,\n tree,\n tag_key_order_list,\n idx_tag_key_order_list=0,\n row_tag_key_to_match=None):\n sz = len(tag_key_order_list)\n if idx_tag_key_order_list >= sz:\n return\n tag_key_from_order_list = tag_key_order_list[idx_tag_key_order_list]\n rowmap = row.get_row_map()\n rowtags_dict = rowmap[TKEYS.GROUP_TAGS]\n\n # if no tags in row, put it in top level of tree\n if idx_tag_key_order_list == 0 and len(rowtags_dict) == 0:\n tree[TKEYS.GROUP_ROWS].append(row)\n return\n\n # find the next row tag key to match with current tree view\n cur_row_tag_key_to_match = row_tag_key_to_match if row_tag_key_to_match != None else \\\n self.get_next_tag_key_from_row(row,tag_key_order_list)\n if cur_row_tag_key_to_match == None:\n return\n\n # if current tag key is not in current level, traverse to all elements in next level til match\n if(cur_row_tag_key_to_match not in tree[TKEYS.GROUP_TAGS]):\n if(len(tree[TKEYS.GROUP_SUBTREE]) == 0):\n return\n for subtree_key,subtree in tree[TKEYS.GROUP_SUBTREE].items():\n self.put_row_in_tag_tree(\n row,\n subtree,\n tag_key_order_list,\n idx_tag_key_order_list+1,\n cur_row_tag_key_to_match)\n return\n\n # if next tag key matches current level\n cur_row_tag_val_to_match = rowtags_dict[cur_row_tag_key_to_match]\n tree_tag_val = tree[TKEYS.GROUP_TAGS][cur_row_tag_key_to_match]\n if(cur_row_tag_val_to_match != tree_tag_val):\n return\n\n # put in current view only if row is last key in hierarchy\n next_row_tag_key_to_match = self.get_next_tag_key_from_row(row,tag_key_order_list,cur_row_tag_key_to_match)\n if next_row_tag_key_to_match == None:\n tree[TKEYS.GROUP_ROWS].append(row)\n return\n\n for subtree_key,subtree in tree[TKEYS.GROUP_SUBTREE].items():\n self.put_row_in_tag_tree(\n row,\n subtree,\n tag_key_order_list,\n idx_tag_key_order_list+1,\n next_row_tag_key_to_match)\n\n return\n\n def populate_rows_to_tag_tree(self,rows,tree,tag_key_order_list):\n for row in rows:\n rowmap = row.get_row_map()\n try:\n if rowmap[TKEYS.IS_ACTIVE] == False:\n continue\n rowmap = row.get_row_map()\n basename = rowmap[TKEYS.TAGKBASE]\n assert basename in tree\n self.put_row_in_tag_tree(row,tree[basename],tag_key_order_list)\n except Exception as e:\n raise e\n return\n\n def generate_tree_hierarchy_with_rows(self,rows,dict_tags,tag_key_order_list):\n try:\n tree_rows = self.generate_general_tag_tree(dict_tags,tag_key_order_list)\n self.populate_rows_to_tag_tree(rows,tree_rows,tag_key_order_list)\n return tree_rows\n except Exception as e:\n raise e\n\n def get_reference_to_map_keypath(self,input_map,keypath_string):\n '''\n returns reference to subpath of a dict payload\n\n :param input_map: the dict payload\n :param keypath_string: the keypath to the key:value of input_map, delimited by keypath_delimiter\n :return: returns subkey_name,parent of input_map[subkey_name]\n\n if input_map = {\n k1:{\n k2:{\n k3:{\n k4:{\n k5:v5\n }\n }\n }\n }\n }\n\n and keypath_string = k1/k2/k3/k4, return\n k4,the payload at input_map[k1][k2][k3], which is:\n {\n k4:{\n k5:v5\n }\n }\n '''\n if keypath_string == None:\n return None\n keypath_array = keypath_string.split(self.keypath_delimiter)\n\n parent_key = None\n subpath = input_map\n last_key = None\n for k in keypath_array:\n if k not in subpath:\n string_map_val = json.dumps(input_map)\n raise Exception('path not exist in map for keypath_array {} for input_map: {}'.format(keypath_array,string_map_val))\n parent_key = subpath\n subpath = subpath[k]\n last_key = k\n return (last_key,parent_key)\n\n def evaluate_row_default_val(self,key,row,input_value):\n rowmap = row.get_row_map()\n result = input_value\n if rowmap[TKEYS.VAL] != None:\n result = rowmap[TKEYS.VAL]\n return result\n\n\n def evaluate_row_rules_on_value_override_val(self,key,row,input_value):\n rowmap = row.get_row_map()\n if TKEYS.OPOVR not in rowmap[TKEYS.GROUP_OPS]:\n return input_value\n data_row = rowmap[TKEYS.GROUP_OPS][TKEYS.OPOVR]\n dtype_val = util.get_edata_type(input_value)\n dtype_row = util.get_edata_type(data_row)\n result = input_value\n\n if input_value == None:\n result = data_row\n else:\n if dtype_val != dtype_row:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n result = data_row\n\n return result\n\n def evaluate_row_rules_on_value_override_add(self,key,row,input_value):\n rowmap = row.get_row_map()\n if TKEYS.OPADD not in rowmap[TKEYS.GROUP_OPS]:\n return input_value\n data_row = rowmap[TKEYS.GROUP_OPS][TKEYS.OPADD]\n dtype_val = util.get_edata_type(input_value)\n dtype_row = util.get_edata_type(data_row)\n result = input_value\n\n if dtype_val == TKEYS.LIST:\n if dtype_row != dtype_val:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n result = result.copy()\n for v in data_row:\n if v not in result:\n result.append(v)\n elif dtype_val == TKEYS.SET:\n if dtype_row != dtype_val:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n result = result.copy()\n for v in data_row:\n result.add(v)\n elif dtype_val == TKEYS.DICT:\n keypath = rowmap[TKEYS.SUBKEY_PATH]\n if keypath != None:\n result = copy.deepcopy(result)\n (leaf_key,subpath) = self.get_reference_to_map_keypath(result,keypath)\n dtype_subpath = util.get_edata_type(subpath[leaf_key])\n if dtype_subpath != dtype_row:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n if dtype_row == TKEYS.LIST:\n for v in data_row:\n subpath[leaf_key].append(v)\n elif dtype_row == TKEYS.SET:\n for v in data_row:\n subpath[leaf_key].add(v)\n elif dtype_row == TKEYS.DICT:\n for k,v in data_row.items():\n subpath[leaf_key][k] = v\n else:\n subpath[leaf_key] = data_row\n elif dtype_row == TKEYS.DICT:\n result = data_row\n else:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n elif dtype_row == TKEYS.OBJECT:\n result = data_row\n return result\n\n def evaluate_row_rules_on_value_override_del(self,key,row,input_value):\n rowmap = row.get_row_map()\n if TKEYS.OPDEL not in rowmap[TKEYS.GROUP_OPS]:\n return input_value\n data_row = rowmap[TKEYS.GROUP_OPS][TKEYS.OPDEL]\n dtype_val = util.get_edata_type(input_value)\n dtype_row = util.get_edata_type(data_row)\n result = input_value\n\n if dtype_val == TKEYS.LIST:\n if dtype_row != dtype_val:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n result = result.copy()\n for v in data_row:\n if v in result:\n result.remove(v)\n elif dtype_val == TKEYS.SET:\n if dtype_row != dtype_val:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n result = result.copy()\n for v in data_row:\n if v in result:\n result.remove(v)\n elif dtype_val == TKEYS.DICT:\n keypath = rowmap[TKEYS.SUBKEY_PATH]\n if keypath != None:\n result = copy.deepcopy(result)\n (leaf_key,subpath) = self.get_reference_to_map_keypath(result,keypath)\n dtype_subpath = util.get_edata_type(subpath[leaf_key])\n if dtype_subpath != dtype_row:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n if dtype_row == TKEYS.LIST:\n for v in data_row:\n if v in subpath[leaf_key]:\n subpath[leaf_key].remove(v)\n elif dtype_row == TKEYS.SET:\n for v in data_row:\n if v in subpath[leaf_key]:\n subpath[leaf_key].remove(v)\n elif dtype_row == TKEYS.DICT:\n for k,v in data_row.items():\n if k in subpath[leaf_key]:\n subpath[leaf_key].pop(v)\n else:\n subpath[leaf_key] = data_row\n elif dtype_row == TKEYS.DICT:\n result = data_row\n else:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n elif dtype_row == TKEYS.OBJECT:\n if data_row == result:\n result = None\n\n return result\n\n def evaluate_row_rules_on_value_override_sub(self,key,row,input_value):\n rowmap = row.get_row_map()\n if TKEYS.OPSUB not in rowmap[TKEYS.GROUP_OPS]:\n return input_value\n data_row = rowmap[TKEYS.GROUP_OPS][TKEYS.OPSUB]\n dtype_val = util.get_edata_type(input_value)\n dtype_row = util.get_edata_type(data_row)\n result = input_value\n\n if dtype_row == TKEYS.SET or dtype_row == TKEYS.LIST:\n raise Exception('cannot substitute set or arrayfor rowmap:{} and value:{}'.format(row.to_string(),input_value))\n if dtype_val == TKEYS.DICT:\n keypath = rowmap[TKEYS.SUBKEY_PATH]\n if keypath != None:\n result = copy.deepcopy(result)\n (leaf_key,subpath) = self.get_reference_to_map_keypath(result,keypath)\n dtype_subpath = util.get_edata_type(subpath[leaf_key])\n if dtype_subpath != dtype_row:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n subpath[leaf_key] = data_row\n elif dtype_row == TKEYS.DICT:\n result = data_row\n else:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n elif dtype_row == TKEYS.OBJECT:\n result = data_row\n else:\n if dtype_val != None and dtype_val != TKEYS.DICT and dtype_row != dtype_val:\n raise Exception('data type mismatch for rowmap:{} and value:{}'.format(row.to_string(),input_value))\n\n return result\n\n def apply_row_rules_on_cur_value(self,key,row,parent_value):\n result = parent_value\n\n rowmap = row.get_row_map()\n try:\n flag = False\n if key == 'k3a':\n flag = True\n result = self.evaluate_row_default_val(key,row,result)\n result = self.evaluate_row_rules_on_value_override_val(key,row,result)\n result = self.evaluate_row_rules_on_value_override_add(key,row,result)\n result = self.evaluate_row_rules_on_value_override_del(key,row,result)\n result = self.evaluate_row_rules_on_value_override_sub(key,row,result)\n except Exception as e:\n raise e\n return result\n\n def write_payload_to_file(self,filename,dict_payload,dir='tmp'):\n if not os.path.exists(dir):\n os.makedirs(dir)\n filename_final = '{}/{}'.format(dir,filename)\n with open(filename_final,'w') as fw:\n json_pretty = json.dumps(dict_payload,indent=4,sort_keys=True)\n fw.write(json_pretty)\n\n def evaluate_rows_in_subtree(self,tree_rows,parent_tree_files,tree_files,tag_key_order_list):\n try:\n tree_dict_modified = {}\n parent_tree_dict = {} if(parent_tree_files == None or len(parent_tree_files)==0) else parent_tree_files[TKEYS.FULL_PAYLOAD]\n\n tree_files[TKEYS.GROUP_TAGS] = tree_rows[TKEYS.GROUP_TAGS].copy()\n tree_files[TKEYS.PATH] = tree_rows[TKEYS.PATH]\n\n if(parent_tree_files == None or len(parent_tree_files) == 0):\n parent_tree_files = tree_files\n else:\n tree_files[TKEYS.TAGKBASE] = parent_tree_files[TKEYS.TAGKBASE]\n\n for row in tree_rows[TKEYS.GROUP_ROWS]:\n try:\n rowmap = row.get_row_map()\n rowkey = rowmap[TKEYS.KEY]\n cur_value_of_key = None\n if (rowkey in tree_dict_modified):\n cur_value_of_key = tree_dict_modified[rowkey]\n elif (rowkey in parent_tree_dict):\n cur_value_of_key = parent_tree_dict[rowkey]\n evaluated_value_of_key_after_row_ops = self.apply_row_rules_on_cur_value(rowkey,row,cur_value_of_key)\n tree_dict_modified[rowkey] = evaluated_value_of_key_after_row_ops\n except Exception as e:\n raise e\n\n # if tree is modified, then copy immediate parent's payload to current subtree.\n # then in current tree view, overwrite copied parent values with subtree_override_vals\n if(len(tree_dict_modified) == 0):\n tree_files[TKEYS.FULL_PAYLOAD] = parent_tree_dict # reference only\n if(len(parent_tree_dict) != 0):\n version = parent_tree_files[TKEYS.VERSION] if(TKEYS.VERSION in parent_tree_files) else \\\n self.get_version_id(True)\n tree_files[TKEYS.FILENAME] = parent_tree_files[TKEYS.FILENAME] if parent_tree_files[TKEYS.FILENAME] != None else \\\n '{}-{}{}'.format(\n tree_files[TKEYS.TAGKBASE],\n version,\n self.filename_suffix)\n else:\n tree_files[TKEYS.FULL_PAYLOAD] = {k:v for k,v in parent_tree_dict.items()}\n for k,v in tree_dict_modified.items():\n tree_files[TKEYS.FULL_PAYLOAD][k] = v # override only modified keys\n tree_files[TKEYS.IS_MODIFIED] = True\n version = self.get_next_version_id()\n version_filename = self.get_next_version_filename_id()\n tree_files[TKEYS.VERSION] = version\n tree_files[TKEYS.FILENAME] = '{}-{}{}'.format(\n tree_files[TKEYS.TAGKBASE],\n version_filename,\n self.filename_suffix)\n\n self.write_payload_to_file(tree_files[TKEYS.FILENAME],tree_files[TKEYS.FULL_PAYLOAD])\n\n # evaluate subtrees\n for tag_value,subtree in tree_rows[TKEYS.GROUP_SUBTREE].items():\n tree_files[TKEYS.GROUP_SUBTREE][tag_value] = self.generate_tree_file_structure()\n subtree_file = tree_files[TKEYS.GROUP_SUBTREE][tag_value]\n self.evaluate_rows_in_subtree(subtree,tree_files,subtree_file,tag_key_order_list)\n\n tree_files[TKEYS.FULL_PAYLOAD] = {} # clean up memory\n except Exception as e:\n raise e\n\n return\n\n def reduce_tree_info_redundancy(self,tree_files):\n do_not_delete = {}\n do_not_delete_this_subtree = False\n for key,subtree in tree_files[TKEYS.GROUP_SUBTREE].items():\n status = self.reduce_tree_info_redundancy(subtree)\n do_not_delete[key] = status\n if(status == True):\n do_not_delete_this_subtree = True\n keys_to_delete = []\n for key,subtree in tree_files[TKEYS.GROUP_SUBTREE].items():\n if(do_not_delete[key] == True):\n continue\n if(subtree[TKEYS.IS_MODIFIED] == False):\n keys_to_delete.append(key)\n else:\n do_not_delete_this_subtree = True\n for key in keys_to_delete:\n tree_files[TKEYS.GROUP_SUBTREE].pop(key)\n return do_not_delete_this_subtree\n\n\n def write_tree_info_to_file(self,tree_files,basename,dir='tmp'):\n def write_tree_files_to_tree_info(tree_files,tree_info):\n tree_info[TKEYS.PATH] = tree_files[TKEYS.PATH]\n tree_info[TKEYS.FILENAME] = tree_files[TKEYS.FILENAME]\n #tree_info[TKEYS.IS_MODIFIED] = tree_files[TKEYS.IS_MODIFIED]\n for tag_val,tree_files_subtree in tree_files[TKEYS.GROUP_SUBTREE].items():\n tree_info[TKEYS.GROUP_SUBTREE][tag_val] = self.generate_tree_info_structure()\n write_tree_files_to_tree_info(tree_files_subtree,tree_info[TKEYS.GROUP_SUBTREE][tag_val])\n return\n if not os.path.exists(dir):\n os.makedirs(dir)\n filename_final = '{}/{}-info{}'.format(dir,basename,self.filename_suffix)\n tree_info = self.generate_tree_info_structure(tree_files[TKEYS.PATH],filename_final,tree_files[TKEYS.VERSION])\n write_tree_files_to_tree_info(tree_files,tree_info)\n\n with open(filename_final,'w') as fw:\n json_pretty = json.dumps(tree_info,indent=4,sort_keys=True)\n fw.write(json_pretty)\n return tree_info\n\n def evaluate_rows_in_tree_base(self,tree_rows,tag_key_order_list):\n tree_files = {}\n\n for basename,subtree in tree_rows.items():\n assert basename == subtree[TKEYS.PATH]\n try:\n tree_files[basename] = self.generate_tree_file_structure(path=basename,tag_key=TKEYS.TAGKBASE,tag_val=basename)\n assert tree_files[basename][TKEYS.TAGKBASE] != None\n self.evaluate_rows_in_subtree(tree_rows[basename],{},tree_files[basename],tag_key_order_list)\n self.reduce_tree_info_redundancy(tree_files[basename])\n tree_info = self.write_tree_info_to_file(tree_files[basename],basename)\n except Exception as e:\n raise e\n return tree_files\n\n def print_tree_rows(self,tree_rows):\n return\n\n def print_tree_files(self,tree_files):\n return\n\n def process_tree_hierarchy_to_files(self,tree_rows,tag_key_order_list):\n tree_files = self.evaluate_rows_in_tree_base(tree_rows,tag_key_order_list)\n return tree_files\n\n def process_rows_to_files(self,rows,dict_tags,tag_key_order_list):\n tree_rows = self.generate_tree_hierarchy_with_rows(rows,dict_tags,tag_key_order_list)\n tree_files = self.process_tree_hierarchy_to_files(tree_rows,tag_key_order_list)\n return tree_files\n\n def process_rows_to_files_with_defined_tree(self,rows,tree,tag_key_order_list):\n self.populate_rows_to_tag_tree(rows,tree,tag_key_order_list)\n tree_files = self.process_tree_hierarchy_to_files(tree,tag_key_order_list)\n return tree_files","sub_path":"src/main/generate_jsons.py","file_name":"generate_jsons.py","file_ext":"py","file_size_in_byte":32398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102410419","text":"from __future__ import print_function\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\n\nfrom tqdm import tqdm\nimport os\nimport PIL.Image as Image\n\ndevice = torch.device('cuda')\n\ndef get_data(size):\n t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11 = get_transforms(size)\n train_loader = torch.utils.data.DataLoader(\n torch.utils.data.ConcatDataset([\n datasets.ImageFolder('images/train_images', transform=t0),\n datasets.ImageFolder('images/train_images', transform=t1),\n datasets.ImageFolder('images/train_images', transform=t2),\n datasets.ImageFolder('images/train_images', transform=t3),\n datasets.ImageFolder('images/train_images', transform=t4),\n datasets.ImageFolder('images/train_images', transform=t5),\n datasets.ImageFolder('images/train_images', transform=t6),\n datasets.ImageFolder('images/train_images', transform=t7),\n datasets.ImageFolder('images/train_images', transform=t8),\n datasets.ImageFolder('images/train_images', transform=t9),\n datasets.ImageFolder('images/train_images', transform=t10),\n ]),\n batch_size=1024, shuffle=True, num_workers = 8)\n\n val_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder('images/val_images', transform=t0),\n batch_size=1024, shuffle=False, num_workers = 8)\n \n return train_loader, val_loader \n \n \n# Get all the possible transforms for a given size.\ndef get_transforms(size):\n # Keep the same\n t0 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Scale brightness between the range (1.5,3.5)\n t1 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.ColorJitter(brightness=2.5),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Scale saturation between (1,2)\n t2 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.ColorJitter(saturation=2),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Scale contrast between (1,1.5)\n t3 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.ColorJitter(contrast=1.5),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Scale hue\n t4 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.ColorJitter(hue=0.2),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Random horizontal flips\n t5 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Random shearing\n t6 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.RandomAffine(degrees=20, shear=3),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Random Translation\n t7 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.RandomAffine(degrees=10, translate=(0.2,0.2)),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Random perspective change\n t8 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.RandomPerspective(),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Random rotation\n t9 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.RandomRotation(20),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # Upscale the image to size*1.5 then make a random crop of size=size\n t10 = transforms.Compose([\n transforms.Resize((int(size*1.5), int(size*1.5))),\n transforms.RandomResizedCrop(size=size),\n transforms.ToTensor(),\n transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n ])\n\n # TenCrop, only used in TTA\n t11 = transforms.Compose([\n transforms.Resize((size, size)),\n transforms.TenCrop(size),\n transforms.Lambda(lambda crops: torch.stack([transforms.ToTensor()(crop) for crop in crops])),\n transforms.Lambda(lambda crops: torch.stack([transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))(crop) for crop in crops])),\n ])\n \n return t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":4971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"331689521","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2015 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nimport json\nimport mock\nfrom mock import patch\nimport subprocess\n\nimport netifaces\nimport unittest\n\nfrom fuelmenu.common import errors\nfrom fuelmenu.common import network\n\n\nclass TestUtils(unittest.TestCase):\n\n @mock.patch('fuelmenu.common.network.os')\n def test_is_physical_false(self, os_mock):\n iface = 'lo'\n os_mock.path.realpath.return_value = '/sys/devices/virtual/net/lo'\n self.assertFalse(network.is_physical(iface))\n os_mock.path.realpath.assert_called_once_with(\n '/sys/class/net/{0}'.format(iface))\n\n @mock.patch('fuelmenu.common.network.os')\n def test_is_physical_true(self, os_mock):\n iface = 'eth0'\n os_mock.path.realpath.return_value = \\\n '/sys/devices/pci0000:00/0000:00:03.0/net/eth0'\n self.assertTrue(network.is_physical(iface))\n os_mock.path.realpath.assert_called_once_with(\n '/sys/class/net/{0}'.format(iface))\n\n @mock.patch('netifaces.ifaddresses')\n def test_interface_has_ip_false(self, addrs_mock):\n iface = 'eth0'\n addrs_mock.return_value = {'some_key': 'some_value'}\n self.assertFalse(network.is_interface_has_ip(iface))\n addrs_mock.assert_called_once_with(iface)\n\n @mock.patch('netifaces.ifaddresses')\n def test_interface_has_ip_true(self, addrs_mock):\n iface = 'eth0'\n addrs_mock.return_value = {netifaces.AF_INET: '192.168.1.2'}\n self.assertTrue(network.is_interface_has_ip(iface))\n addrs_mock.assert_called_once_with(iface)\n\n @mock.patch('fuelmenu.common.network.netifaces')\n @mock.patch('fuelmenu.common.network.is_physical')\n def test_get_physical_ifaces(self, is_physical_mock, netifaces_mock):\n all_ifaces = ['eth0', 'lo', 'veth0']\n\n is_physical_mock.side_effect = [True, False, False]\n netifaces_mock.interfaces.return_value = all_ifaces\n data = network.get_physical_ifaces()\n netifaces_mock.interfaces.assert_called_once_with()\n self.assertEqual(['eth0'], data)\n\n @mock.patch('fuelmenu.common.network.netifaces')\n def test_list_host_ip_addresses(self, netifaces_mock):\n all_ifaces = ['eth0', 'lo', 'veth0']\n netifaces_mock.AF_INET = netifaces.AF_INET\n netifaces_mock.interfaces.return_value = all_ifaces\n netifaces_mock.ifaddresses.side_effect = [\n {netifaces.AF_INET: [{'addr': '10.20.0.2'}]},\n {netifaces.AF_INET: [{'addr': '127.0.0.1'}]},\n {netifaces.AF_INET: [{'addr': '192.168.122.1'}]},\n ]\n data = network.list_host_ip_addresses()\n netifaces_mock.interfaces.assert_called_once_with()\n self.assertEqual(['10.20.0.2', '127.0.0.1', '192.168.122.1'], data)\n\n @mock.patch('fuelmenu.common.network.netifaces')\n def test_list_host_ip_addresses_ignore_no_ip(self, netifaces_mock):\n all_ifaces = ['eth0']\n netifaces_mock.AF_INET = netifaces.AF_INET\n netifaces_mock.interfaces.return_value = all_ifaces\n netifaces_mock.ifaddresses.return_value = []\n data = network.list_host_ip_addresses()\n netifaces_mock.interfaces.assert_called_once_with()\n self.assertEqual([], data)\n\n @mock.patch('fuelmenu.common.network.netifaces')\n def test_list_host_ip_addresses_raises_for_bad_iface(self, netifaces_mock):\n all_ifaces = ['eth0']\n bad_iface = \"nonexistent\"\n netifaces_mock.AF_INET = netifaces.AF_INET\n netifaces_mock.interfaces.return_value = all_ifaces\n netifaces_mock.ifaddresses.side_effect = ValueError(\n \"You must specify a valid interface name.\")\n self.assertRaises(errors.NetworkException,\n network.list_host_ip_addresses,\n bad_iface)\n\n def make_process_mock(self, return_code=0, retval=('stdout', 'stderr')):\n process_mock = mock.Mock(\n communicate=mock.Mock(return_value=retval),\n poll=mock.Mock(return_value=return_code))\n process_mock.stdout = ['Stdout line 1', 'Stdout line 2']\n process_mock.returncode = return_code\n\n return process_mock\n\n def test_search_external_dhcp(self):\n output = '[{\"mac\": \"52:54:00:12:35:02\"}]'\n\n interface = \"abc0\"\n timeout = 1\n\n process_mock = self.make_process_mock(return_code=0,\n retval=(output, ''))\n with patch.object(subprocess, 'Popen', return_value=process_mock):\n data = network.search_external_dhcp(interface, timeout)\n process_mock.communicate.assert_called_with(input=None)\n self.assertEqual(data, json.loads(output))\n\n def test_search_external_dhcp_nodata(self):\n output = ''\n\n interface = \"abc0\"\n timeout = 1\n\n process_mock = self.make_process_mock(return_code=0,\n retval=(output, ''))\n with patch.object(subprocess, 'Popen', return_value=process_mock):\n data = network.search_external_dhcp(interface, timeout)\n process_mock.communicate.assert_called_with(input=None)\n self.assertEqual(data, [])\n\n def test_search_external_dhcp_raises_exception(self):\n interface = \"abc0\"\n timeout = 1\n\n with patch.object(subprocess, 'Popen', side_effect=OSError()):\n self.assertRaises(errors.NetworkException,\n network.search_external_dhcp,\n interface, timeout)\n","sub_path":"fuelmenu/tests/test_common_network.py","file_name":"test_common_network.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"399517641","text":"class Book(dict):\n def __init__(self, *args):\n self.doc_id = args[0]\n self.title = args[1]\n self.authors = args[2]\n self.publisher = args[3]\n self.edition = args[4]\n self.price = args[5]\n self.room = args[6]\n self.level = args[7]\n self.checked_out = args[8]\n self.bestseller = (args[9] == 1)\n self.reference_book = (args[10] == 1)\n","sub_path":"Book.py","file_name":"Book.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569825639","text":"import random\nimport json\nfrom tensorflow.keras.models import load_model\n# from keras.models import load_model \nimport numpy as np\nimport pickle\nimport nltk\nnltk.download('punkt')\nnltk.download('wordnet')\n\n\nfrom nltk.stem import WordNetLemmatizer\nlemmatizer = WordNetLemmatizer()\n\n\nTHRESHOLD = 0.25\n\n\nmodel = load_model(r\"resources/models/chatbot_model.h5\")\nintents = json.loads(open(r'resources/data/intents.json').read())\nwords = pickle.load(open(r\"resources/pickles/words.pkl\", 'rb'))\nclasses = pickle.load(open(r\"resources/pickles/classes.pkl\", 'rb'))\n\nprint('RESOURCES LOADED SUCESSFULLY!')\n\n# applying lemmmatization\n\n\ndef clean_up_sentence(sentence):\n sentence_words = nltk.word_tokenize(sentence)\n sentence_words = [lemmatizer.lemmatize(\n word.lower()) for word in sentence_words]\n return sentence_words\n\n# creating bag_of_words\n\n\ndef bag_of_words(sentence, words, show_details=True):\n sentence_words = clean_up_sentence(sentence)\n bag = [0] * len(words)\n for s in sentence_words:\n for i, w in enumerate(words):\n if w == s:\n bag[i] = 1\n if show_details:\n print(f\"found in bag: {w}\")\n return (np.array(bag))\n\n\ndef predict_class(sentence, model):\n p = bag_of_words(sentence, words, show_details=False)\n res = model.predict(np.array([p]))[0]\n results = [[i, r] for i, r in enumerate(res) if r > THRESHOLD]\n results.sort(key=lambda x: x[1], reverse=True)\n return_list = []\n for r in results:\n return_list.append(\n {\n \"intent\": classes[r[0]],\n \"probability\": str(r[1])\n }\n )\n return return_list\n\n\ndef get_responses(ints, intents_json):\n tag = ints[0]['intent']\n list_of_intents = intents_json['intents']\n\n for i in list_of_intents:\n if i['tag'] == tag:\n result = random.choice(i['responses'])\n break\n return result\n\n\ndef chatbot_response(message):\n ints = predict_class(message, model)\n res = get_responses(ints, intents)\n return res\n\n\ndef main():\n while True:\n inp = input('You:\\t')\n if inp == 'exit':\n break\n else:\n chatbot_result = chatbot_response(inp)\n print(f'bot:\\t{chatbot_result}')\n\n\nif __name__ == '__main__':\n print('TYPE \"exit\" TO QUIT!')\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"217060055","text":"from google.protobuf.json_format import MessageToDict\nfrom libs import zbase62\n\n\nclass SpaceInfo(object):\n def __init__(self, pb_space):\n self.spaceinfo = MessageToDict(pb_space, including_default_value_fields=True,\n preserving_proto_field_name=True)\n self.spaceinfo[\"space_id\"] = zbase62.encode(pb_space.space_id)\n self.spaceinfo[\"owner_id\"] = zbase62.encode(pb_space.owner_id)\n self.spaceinfo[\"create_by\"] = zbase62.encode(pb_space.create_by)\n\n\nclass Group(object):\n def __init__(self, pb_group):\n self.groupinfo = MessageToDict(pb_group, including_default_value_fields=True,\n preserving_proto_field_name=True)\n self.groupinfo[\"group_id\"] = pb_group.group_id\n self.groupinfo[\"space_id\"] = zbase62.encode(pb_group.space_id)\n\n\nclass Relation(object):\n def __init__(self, pb_group):\n self.relationinfo = MessageToDict(pb_group, including_default_value_fields=True,\n preserving_proto_field_name=True)\n","sub_path":"model/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576771508","text":"#coding: utf-8\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom helloDjango.core.models import Speaker\n\nclass SpeakerDetailTest(TestCase):\n def setUp(self):\n Speaker.objects.create(name='Fulano de Tal',\n slug='fulano-de-tal',\n url='http://meusite.net',\n description='Example for description!')\n \n url = reverse('core:speaker_detail', kwargs={'slug': 'fulano-de-tal'})\n self.resp = self.client.get(url)\n\n def test_get(self):\n 'GET should result in 200'\n self.assertEqual(200, self.resp.status_code)\n\n def test_template(self):\n self.assertTemplateUsed(self.resp, \"core/speaker_detail.html\")\n\n def test_html(self):\n 'Testing basics of HTML'\n self.assertContains(self.resp, 'Fulano de Tal')\n self.assertContains(self.resp, 'Example for description!')\n self.assertContains(self.resp, 'http://meusite.net')\n\n def test_context(self):\n 'Speaker must be in context'\n speaker = self.resp.context['speaker']\n self.assertIsInstance(speaker, Speaker)\n\nclass SpeakerNotFound(TestCase):\n def test_not_found(self):\n url = reverse('core:speaker_detail', kwargs={'slug': 'john-doe'})\n response = self.client.get(url)\n self.assertEqual(404, response.status_code)\n","sub_path":"helloDjango/core/tests/test_views_speaker_detail.py","file_name":"test_views_speaker_detail.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"101165447","text":"#!/usr/bin/env python\n\nimport gym\nimport numpy as np\nfrom atari_wrappers_deprecated import wrap_dqn, ScaledFloatFrame\nfrom models import *\n\ndef wrap_train(env):\n from atari_wrappers import (wrap_deepmind, FrameStack)\n env = wrap_deepmind(env, episode_life = False, clip_rewards=False)\n env = FrameStack(env, 4)\n return env\n\n# env = gym.make(\"PongNoFrameskip-v4\")\n# env = ScaledFloatFrame(wrap_dqn(env))\n# # env = wrap_train(env)\n# obs = env.reset()\n\n# print env.observation_space\n# print env.action_space\n\n# print len(obs), len(obs[0]), len(obs[0][0]) \n# action = env.action_space.sample()\n# print action\n\n# print len(observation)\n# for _ in range(1000):\n# # env.render()\n# action = env.action_space.sample() # your agent here (this takes random actions)\n# observation, reward, done, info = env.step(action)\n# print action\n# if done:\n# env.reset()\n\n\ndef main():\n env = gym.make(\"PongNoFrameskip-v4\")\n # Remove Scaled Float Frame wrapper, re-use if needed.\n from atari_wrappers_deprecated import wrap_dqn, ScaledFloatFrame\n env = ScaledFloatFrame(wrap_dqn(env))\n model = cnn_to_dist(\n convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)],\n hiddens=[256],\n num_atoms = 50,\n dueling=True\n )\n # act = learn(\n # env,\n # q_func=model,\n # lr=1e-4,\n # max_timesteps=2000000,\n # buffer_size=10000,\n # exploration_fraction=0.1,\n # exploration_final_eps=0.01,\n # train_freq=4,\n # learning_starts=10000,\n # target_network_update_freq=1000,\n # gamma=0.99,\n # prioritized_replay=False\n # )\n # act.save(\"pong_model.pkl\")\n # env.close()\n\n\nif __name__ == '__main__':\n main()","sub_path":"build_test.py","file_name":"build_test.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"158197965","text":"import sys\nfrom collections import deque\n\nsys.stdin = open('input.txt','r')\n\nT = int(sys.stdin.readline().rstrip())\n\ndef inRange(a,b):\n if (0<=a int:\n dp = [[0 for _ in range(len(word1)+1)] for _ in range(len(word2)+1)]\n\n for i in range(len(dp[0])):\n dp[0][i] = i \n\n for i in range(len(dp)):\n dp[i][0] = i \n \n for i in range(1, len(dp)):\n for j in range(1, len(dp[0])):\n if word2[i-1] == word1[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min( dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) + 1 \n \n return dp[-1][-1]","sub_path":"edit_distance.py","file_name":"edit_distance.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"195304531","text":"from math import sqrt\nfrom itertools import product\n\nimport torch\n\nfrom aw_nas.objective.detection_utils.base import AnchorsGenerator\n\n__all__ = [\"SSDAnchorsGenerator\"]\n\nclass SSDAnchorsGenerator(AnchorsGenerator):\n NAME = \"ssd_anchors_generator\"\n\n def __init__(self,\n min_dim=300,\n aspect_ratios=[[2], [2, 3], [2, 3], [2, 3], [2], [2]],\n feature_maps=[19, 10, 5, 3, 2, 1],\n scales=[45, 90, 135, 180, 225, 270, 315],\n steps=[16, 32, 64, 100, 150, 300],\n clip=True,\n schedule_cfg=None):\n\n super(SSDAnchorsGenerator, self).__init__(schedule_cfg)\n self.min_dim = min_dim #[height, width]\n self.feature_maps = feature_maps #[(height, width), ...]\n self.aspect_ratios = aspect_ratios\n self.num_anchors = len(aspect_ratios)\n self.clip = clip\n self.scales = [s / min_dim for s in scales]\n\n if steps:\n self.steps = [step / min_dim for step in steps]\n else:\n self.steps = [(1 / f_h, 1 / f_w) for f_h, f_w in feature_maps]\n\n self.offset = [step * 0.5 for step in self.steps]\n\n self.anchors_boxes = {}\n\n def __call__(self, image_shape):\n if image_shape in self.anchors_boxes:\n return self.anchors_boxes[image_shape]\n\n mean = []\n # l = 0\n for k, f in enumerate(self.feature_maps):\n for i, j in product(range(f), range(f)):\n cx = j * self.steps[k] + self.offset[k]\n cy = i * self.steps[k] + self.offset[k]\n s_k = self.scales[k]\n mean += [cx, cy, s_k, s_k]\n\n s_k_prime = sqrt(s_k * self.scales[k + 1])\n mean += [cx, cy, s_k_prime, s_k_prime]\n for ar in self.aspect_ratios[k]:\n if isinstance(ar, int):\n ar_sqrt = sqrt(ar)\n mean += [cx, cy, s_k * ar_sqrt, s_k / ar_sqrt]\n mean += [cx, cy, s_k / ar_sqrt, s_k * ar_sqrt]\n elif isinstance(ar, list):\n mean += [cx, cy, s_k * ar[0], s_k * ar[1]]\n output = torch.Tensor(mean).view(-1, 4)\n if self.clip:\n output.clamp_(max=1, min=0)\n self.anchors_boxes[image_shape] = output\n return output\n","sub_path":"aw_nas/objective/detection_utils/anchors_generator.py","file_name":"anchors_generator.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"334055131","text":"from flask import (Flask, render_template, request, redirect,\n jsonify, url_for, flash)\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom models.models import Base, User, Category, Book\nfrom flask import session as login_session\nimport random\nimport string\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nimport httplib2\nimport json\nfrom flask import make_response\nimport requests\n\napp = Flask(__name__)\napp.secret_key = 'super_secret_key'\n\n\nCLIENT_ID = json.loads(\n open('/var/www/html/bookshelf/client_secrets.json', 'r').read())['web']['client_id']\nAPPLICATION_NAME = \"bookshelf-glaser\"\n\n# Connect to Database and create database session\nengine = create_engine('sqlite:///bookshelfdatabase.db', connect_args={'check_same_thread': False}, echo=True)\nBase.metadata.bind = engine\n\nsession_factory = sessionmaker(bind=engine)\n# Need scoped session in order to avoid cross threading with SQLite3\nSession = scoped_session(session_factory)\nsession = Session()\n\n\n# User Helper Functions\n\n\ndef createUser(login_session):\n newUser = User(name=login_session['username'], email=login_session[\n 'email'], picture=login_session['picture'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\n# Main Page\n@app.route('/')\n@app.route('/bookshelf')\ndef showBookshelf():\n categories = session.query(Category).order_by(asc(Category.name))\n if 'username' not in login_session:\n return render_template('publicMain.html',\n categories=categories)\n else:\n return render_template('main.html', categories=categories)\n\n\n# Create a new category\n@app.route('/category/new/', methods=['GET', 'POST'])\ndef newCategory():\n if 'username' not in login_session:\n return redirect(url_for('showBookshelf'))\n user_id = login_session['user_id']\n creator = getUserInfo(user_id)\n if request.method == 'POST':\n newCategory = Category(\n name=request.form['name'], user_id=login_session['user_id'])\n # TODO: add user_id=login_session['user_id'] above\n session.add(newCategory)\n flash('New Category %s Successfully Created' % newCategory.name)\n session.commit()\n return redirect(url_for('showBookshelf'))\n else:\n return render_template('newCategory.html', creator=creator)\n\n\n# Display the contents of a category\n@app.route('/bookshelf/')\n@app.route('/bookshelf//list/')\ndef showCategory(category_id):\n category = session.query(Category).filter_by(id=category_id).one()\n creator = getUserInfo(category.user_id)\n books = session.query(Book).filter_by(\n category_id=category_id).all()\n # Checks Authorization to view\n if 'username' not in login_session or creator.id != login_session[\n 'user_id']:\n return render_template('publicBooks.html', books=books,\n category=category, creator=creator)\n else:\n return render_template('categoryBooks.html', books=books,\n category=category, creator=creator)\n\n\n# Edit a category\n@app.route('/bookshelf//edit/', methods=['GET', 'POST'])\ndef editCategory(category_id):\n editedCategory = session.query(Category).filter_by(\n id=category_id).one()\n creator = getUserInfo(editedCategory.user_id)\n # Checks whether user is logged-in\n if 'username' not in login_session:\n return redirect('/login')\n # checks whether current user is authorized to edit\n if editedCategory.user_id != login_session['user_id']:\n return \"\"\"\"\"\"\n if request.method == 'POST':\n if request.form['name']:\n editedCategory.name = request.form['name']\n flash('Category Successfully Edited %s' % editedCategory.name)\n return redirect(url_for('showCategory',\n category_id=category_id, creator=creator))\n else:\n return render_template('editCategory.html',\n category=editedCategory, creator=creator)\n\n\n@app.route('/bookshelf/delete/',\n methods=['GET', 'POST'])\ndef deleteCategory(category_id):\n categoryToDelete = session.query(Category).filter_by(\n id=category_id).one()\n creator = getUserInfo(categoryToDelete.user_id)\n # Checks whether User is logged-in\n if 'username' not in login_session:\n return redirect('/login')\n # Checks whether User is authorized to delete the category\n if categoryToDelete.user_id != login_session['user_id']:\n return \"\"\"\"\"\"\n if request.method == 'POST':\n booksToDelete = session.query(Book).filter_by(\n category_id=category_id).all()\n # Deletes all the books within the category\n for b in booksToDelete:\n session.delete(b)\n # Deletes the category\n session.delete(categoryToDelete)\n flash('%s Successfully Deleted' % categoryToDelete.name)\n session.commit()\n return redirect(url_for('showBookshelf'))\n else:\n return render_template('deleteCategory.html',\n category=categoryToDelete, creator=creator)\n\n\n# Create a new book\n@app.route('/bookshelf//book/new/',\n methods=['GET', 'POST'])\ndef newBook(category_id):\n user_id = login_session['user_id']\n creator = getUserInfo(user_id)\n category = session.query(Category).filter_by(id=category_id).one()\n # Checks whether a User is logged-in\n if 'username' not in login_session:\n return redirect('/login')\n if request.method == 'POST':\n newBook = Book(title=request.form['title'],\n description=request.form['description'],\n author=request.form['author'],\n category_id=category_id,\n user_id=category.user_id)\n session.add(newBook)\n session.commit()\n flash('New Book %s Successfully Created' % (newBook.title))\n return redirect(url_for('showCategory', category_id=category_id,\n creator=creator))\n else:\n return render_template('newBook.html', category_id=category_id,\n creator=creator)\n\n\n@app.route('/bookshelf//book//edit',\n methods=['GET', 'POST'])\ndef editBook(category_id, book_id):\n editedBook = session.query(Book).filter_by(id=book_id).one()\n creator = getUserInfo(editedBook.user_id)\n # Checks whether User is logged-in\n if 'username' not in login_session:\n return redirect('/login')\n # Checks whether User is authorized to edit the book\n if editedBook.user_id != login_session['user_id']:\n return \"\"\"\"\"\"\n if request.method == 'POST':\n if request.form['title']:\n editedBook.title = request.form['title']\n if request.form['description']:\n editedBook.description = request.form['description']\n if request.form['author']:\n editedBook.author = request.form['author']\n session.add(editedBook)\n session.commit()\n flash('Book Successfully Edited')\n return redirect(url_for('showCategory', category_id=category_id,\n creator=creator))\n else:\n return render_template('editBook.html',\n category_id=category_id,\n book_id=book_id,\n book=editedBook,\n creator=creator)\n\n\n@app.route('/bookshelf//book//delete/',\n methods=['GET', 'POST'])\ndef deleteBook(category_id, book_id):\n bookToDelete = session.query(Book).filter_by(id=book_id).one()\n creator = getUserInfo(bookToDelete.user_id)\n # Checks whether User is logged-in\n if 'username' not in login_session:\n return redirect('/login')\n # Checks whether User is authorized to delete the book\n if bookToDelete.user_id != login_session['user_id']:\n return \"\"\"\"\"\"\n if request.method == 'POST':\n session.delete(bookToDelete)\n session.commit()\n flash('Book Successfully Deleted')\n return redirect(url_for('showCategory', category_id=category_id,\n creator=creator))\n else:\n return render_template('deleteBook.html', book=bookToDelete,\n creator=creator)\n\n\n\"\"\" The Following methods relate to the log-in/log-out process, the initial\nlogin page shows an option to log-in through either Google or Facebook,\ndepending on which one the User chooses, the User gets routed to the\ncorresponding function below. Those functions then check to see if the\ncredentials which were entered match the credentials at either Facebook or\nGoogle. If they match, the User is either newly created, or allowed to log-in.\nIf they do not match, then the User is not allowed to log-in\"\"\"\n\n\n@app.route('/bookshelf/login')\ndef showLogin():\n state = ''.join(random.choice(\n string.ascii_uppercase + string.digits)for x in range(32))\n login_session['state'] = state\n return render_template('/login.html', STATE=state)\n\n\n@app.route('/disconnect')\ndef disconnect():\n # Determines which provider the user used to log-in and redirects\n if 'provider' in login_session:\n if login_session['provider'] == 'google':\n gdisconnect()\n if login_session['provider'] == 'facebook':\n fbdisconnect()\n del login_session['facebook_id']\n\n # Clears login_session\n login_session.clear() ## can also .pop() each indiv attribute\n\n flash(\"You have successfully been logged out.\")\n return redirect(url_for('showBookshelf'))\n else:\n flash(\"You were not logged in to begin with!\")\n redirect(url_for('showBookshelf'))\n\n\n@app.route('/gconnect', methods=['POST'])\ndef gconnect():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n # Obtain authorization code\n code = request.data\n\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('/var/www/html/bookshelf/client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?'\n 'access_token=%s' % access_token)\n\n h = httplib2.Http()\n str_response = h.request(url, 'GET')[1]\n result = json.loads(str_response.decode()) # JSON won't take info without decode()\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n print(\"Token's client ID does not match app's.\")\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_access_token is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps(\n 'Current user is already connected.'),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n login_session['username'] = data['name']\n login_session['picture'] = data['picture']\n login_session['email'] = data['email']\n login_session['provider'] = 'google'\n\n# see if user exits, if it doesn't make a new one\n user_id = getUserID(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n output = ''\n output += '

Welcome, '\n output += login_session['username']\n output += '!

'\n output += '/list/JSON')\ndef categoryBooksJSON(category_id):\n books = session.query(Book).filter_by(\n category_id=category_id).all()\n return jsonify(Books=[b.serialize for b in books])\n\n\n@app.route('/bookshelf//list//JSON')\ndef bookJSON(category_id, book_id):\n book = session.query(Book).filter_by(id=book_id).one()\n return jsonify(Book=book.serialize)\n\n\n@app.route('/bookshelf/JSON')\ndef bookshelfJSON():\n categories = session.query(Category).all()\n return jsonify(categories=[r.serialize for r in categories])\n\n\nif __name__ == '__main__':\n app.config['SESSION_TYPE'] = 'filesystem'\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":19718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"83721545","text":"\"\"\"\ncreates database with customer info and product info\n\"\"\"\n\nfrom threading import Thread\nimport csv\nimport queue as Queue\nfrom pymongo import MongoClient\nimport time\n\n\n\nclass MongoDBConnection():\n \"\"\"MongoDB Connection\"\"\"\n\n def __init__(self, host='127.0.0.1', port=27017):\n self.host = host\n self.port = port\n self.connection = None\n\n def __enter__(self):\n self.connection = MongoClient(self.host, self.port)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\ndef show_available_products():\n mongo = MongoDBConnection()\n\n with mongo:\n database = mongo.connection.media\n\n output_dict = list(database.products.find({'quantity_available': {'$gt':'0'}}, {\"_id\": 0}))\n\n print(output_dict)\n return(output_dict)\n\ndef show_rentals(product_id):\n mongo = MongoDBConnection()\n\n with mongo:\n database = mongo.connection.media\n\n output_list = list(database.rentals.aggregate([\n {'$match':\n {'product_id': product_id}},\n {'$lookup':\n {'from': \"customers\",\n 'localField': \"user_id\",\n 'foreignField': \"user_id\",\n 'as': \"cust\"}},\n {'$project':\n {'_id': 0,\n 'user_id': 1,\n 'name': '$cust.name',\n 'address': '$cust.address',\n 'phone_number': '$cust.phone_number',\n 'email': '$cust.email'}}\n\n ]))\n return(output_list)\n\n\ndef print_mdb_collection(collection_name):\n for doc in collection_name.find({}):\n print(doc)\n\ndef csv_list(file):\n return_list = []\n with open('sample_csv_files/' + file, encoding='utf-8-sig') as csv_file:\n file_input = csv.DictReader(csv_file)\n for row in file_input:\n return_list.append(row)\n return return_list\n\ndef drop_database_data(collection):\n mongo = MongoDBConnection()\n\n with mongo:\n database = mongo.connection.media\n database[collection].drop()\n return True\n #add something here if it cant be found\n\n\nclass database_thread(Thread):\n\n def __init__(self, q, collection_name, csv_file):\n self.queue = q\n self.collection_name = collection_name\n self.csv_file = csv_file\n super().__init__()\n\n def run(self):\n mongo = MongoDBConnection()\n with mongo:\n database = mongo.connection.media\n\n database_collection = database[self.collection_name]\n starting_count = database_collection.count()\n database_list = csv_list(self.csv_file)\n database_list_errors = 0\n for item in database_list:\n try:\n database_collection.insert_one(item)\n except:\n database_list_errors += 1\n output_list = (self.collection_name, database_collection.count() - starting_count, database_list_errors)\n self.queue.put(output_list)\n self.queue.task_done()\n return None\n\ndef format_output(output_raw):\n data_entered = [0, 0, 0]\n errors = [0, 0, 0]\n for row in output_raw:\n collection_name = row[0]\n if collection_name == 'products':\n data_entered[0] = row[1]\n errors[0] = row[2]\n if collection_name == 'customers':\n data_entered[1] = row[1]\n errors[0] = row[2]\n if collection_name == 'rental':\n data_entered[2] = row[1]\n errors[0] = row[2]\n print(data_entered)\n print(errors)\n return [data_entered, errors]\n\n\ndef import_data(dir_name, product_csv, customer_csv, rental_csv):\n\n\n data_entry_queue = Queue.Queue()\n\n product_thread = database_thread(data_entry_queue, 'products', product_csv)\n customer_thread = database_thread(data_entry_queue, 'customers', customer_csv)\n rental_thread = database_thread(data_entry_queue, 'rental', rental_csv)\n\n threads = []\n threads.append(product_thread)\n threads.append(customer_thread)\n threads.append(rental_thread)\n\n for thread in threads:\n thread.start()\n\n data_entry_queue.join()\n\n output_raw = []\n for item in range(len(threads)):\n output_raw.append(data_entry_queue.get())\n\n print(output_raw)\n output = format_output(output_raw)\n return output\n\n\ndef import_data_old(dir_name, product_csv, customer_csv, rental_csv):\n\n mongo = MongoDBConnection()\n\n with mongo:\n database = mongo.connection.media\n\n #Refactor at some point - reduce repetition\n product_collection = database['products']\n product_list = csv_list(product_csv)\n product_list_count = len(product_list)\n product_list_errors = 0\n for item in product_list:\n try:\n product_collection.insert_one(item)\n except:\n #add log here for which record failed\n product_list_errors += 1\n\n customer_collection = database['customers']\n customer_list = csv_list(customer_csv)\n customer_list_count = len(customer_list)\n customer_list_errors = 0\n for item in customer_list:\n try:\n customer_collection.insert_one(item)\n except:\n customer_list_errors += 1\n\n rental_collection = database['rentals']\n rental_list = csv_list(rental_csv)\n rental_list_count = len(rental_list)\n rental_list_errors = 0\n for item in rental_list:\n try:\n rental_collection.insert_one(item)\n except:\n rental_list_errors += 1\n\n import_data_added = (product_list_count - product_list_errors,\n customer_list_count - customer_list_errors,\n rental_list_count - rental_list_errors)\n import_data_errors = (product_list_errors,\n customer_list_errors,\n rental_list_errors)\n\n return import_data_added, import_data_errors\n\n\nif __name__ == '__main__':\n new_start = time.clock()\n import_data('main_mongo', 'products.csv', 'customers.csv', 'rentals.csv')\n new_end = time.clock()\n # drop_data_response = input(\"Drop data?\")\n # if drop_data_response.upper() == 'Y':\n # drop_database_data('products')\n # drop_database_data('customers')\n # drop_database_data('rentals')\n # print(\"Data Dropped\")\n # old_start = time.clock()\n # import_data_old('main_mongo', 'products.csv', 'customers.csv', 'rentals.csv')\n # old_end = time.clock()\n # drop_data_response = input(\"Drop data?\")\n # if drop_data_response.upper() == 'Y':\n # drop_database_data('products')\n # drop_database_data('customers')\n # drop_database_data('rentals')\n # print(\"Data Dropped\")\n # print('New Time %s' % (new_end - new_start))\n # print('Old Time %s' % (old_end - old_start))\n\n #show_available_products()\n #show_rentals('prd002')\n","sub_path":"students/ZackConnaughton/lessons/lesson07/assignment/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"29746286","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n OSMtools\n A QGIS plugin\n falk\n -------------------\n begin : 2017-02-01\n git sha : $Format:%H$\n copyright : (C) 2017 by Nils Nolde\n email : nils.nolde@gmail.com\n ***************************************************************************/\n\n This plugin provides access to the various APIs from OpenRouteService\n (https://openrouteservice.org), developed and\n maintained by GIScience team at University of Heidelberg, Germany. By using\n this plugin you agree to the ORS terms of service\n (https://openrouteservice.org/terms-of-service/).\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\nadmin_levels = {'country': 'COUNTRY',\n 'region': 'STATE',\n 'locality': 'CITY',\n 'postalcode': 'POSTALCODE',\n 'street': 'STREET',\n 'housenumber': 'NUMBER',\n 'name': 'NAME',\n }\n\n\ndef reverse_geocode(client, point_in):\n params = dict()\n params['point.lat'] = point_in.y()\n params['point.lon'] = point_in.x()\n \n try:\n response = client.request('/geocode/reverse', params)['features'][0]\n except:\n raise ValueError(\"Your input coordinates are invalid for geocoding.\")\n \n response_dict = dict()\n \n x, y = response['geometry'].get('coordinates', None)\n response_dict['Lon'] = x\n response_dict['Lat'] = y\n\n # Get all properties\n for admin in admin_levels:\n if admin in response['properties']:\n response_dict[admin_levels[admin]] = response['properties'][admin]\n \n return response_dict\n","sub_path":"OSMtools/core/geocode.py","file_name":"geocode.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239741476","text":"\"\"\"\nCreated on Tue Jan 19 13:42:41 2016\n\n@author: iceberg\n\nthis is going to model continuous opacities of stars, someday\n\"\"\"\n\n#import stuff\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.ion() #did i use this?\ndata = np.loadtxt(\"temp_pelog.dat\")\ncorrect=np.loadtxt(\"correct.dat\")\nimport msvcrt as m #see next comment\ndef wait(): #dont think i ever used this, was trying to get a plot to work inside of a function, but i think plotting from inside a function hangs the program somehow\n m.getch()\n#define constants\nsigma=5.67051e-5 #ergs s-1 cm-2 K-4, stefan-boltz\nplanck=6.6260755E-27 #erg seconds\nboltz=1.380658E-16 #erg K-1\nspeed_light=2.99792458E10 #cm/sec\npmass=1.67262158E-24 #grams\ne =2.718281828459 #eulers i\nchi =2.179E-11 #hydrogen ionization in ergs\nm_H =1.6735575E-24 #mass of hydrogen in grams\nsigma_t =6.655E-25 #cm^2\nB =0.1 #n_He/n_H\nA =10**4 #n_H/n_m\n\n#define basic star stats, later will feed list -----> UPDATE THESE ARE TEMP VALUES NOW FOR TESTING DONT USE\n\n#T =5730.9728 #star temp in kelvin\n#LogPe =1.2594 #log_10 electron pressure in dynes cm-2\n#theta =5040.0/T\n\nwavelength=5000.0 #angstroms\n\n #calcultes ratio of ionized to neutroal hydrogen\ndef logsaha_h(T,LogPe): #ie n+/n0, THESE SAY LOG BUT WILL ACTUALLY UNLOG THEM\n theta =5040.0/T \n logratio=-LogPe-13.595*theta+2.5*np.log10(T)-0.4772\n ratio=10**(logratio)\n return ratio\n\n #calculates ratio of ionized to neutral metal\ndef logsaha_m(T,LogPe): #ie m+/m0\n theta =5040.0/T \n logratio=-LogPe-7.9*theta+2.5*np.log10(T)-0.0971\n ratio=10**(logratio) \n return ratio\n \ndef X(T,LogPe): #fraction H ionized\n ratio=logsaha_h(T,LogPe)\n x=ratio/(1+ratio)\n return x\n #fraction metal ionized\ndef Y(T,LogPe):\n ratio=logsaha_m(T,LogPe)\n y=ratio/(1+ratio)\n return y\n \ndef gff(wavelength_angstroms,th):\n x=(1/wavelength_angstroms)*(1/1E-4) #x is inverse wavelength in microns\n g=1.084+0.0188/th+(0.00161+0.02661/th)/x-(0.0192-0.03889/th+0.02833/th**2-0.007828/th**3+0.0007304/th**4)/x**2\n return g\n\ndef abc_m_index(m): #this might have been the dumbest solution to this, oh well\n if m == 1:\n return [0.9916,0.09068,-0.2524]\n elif m == 2:\n return [1.105,-0.7922,0.4536]\n elif m == 3:\n return [1.101,-0.329,0.1152]\n elif m == 4:\n return [0.9736,0.0,0.0]\n elif m == 5:\n return [1.03,0.0,0.0]\n elif m == 6:\n return [1.097,0.0,0.0]\n elif m == 7:\n return [1.098,0.0,0.0]\n elif m > 7:\n return [1.0,0.0,0.0]\n \n\ndef gfb(wavelength_angstroms,m):\n x=(1.0/wavelength_angstroms)*(1.0/1.0E-4) #x is inverse wavelength in microns\n a_m,b_m,c_m=abc_m_index(m)\n g=a_m+b_m/x+c_m/x**2\n return g\n \n \ndef u_m(T,m):\n u=(chi/(boltz*T))/m**2\n return u\n \n \n#print X(),Y()\n \ndef alpha_lambda_H(T,LogPe):\n theta =5040.0/T\n nu=speed_light/(wavelength*1.0E-8)\n x=(1.0/wavelength)*(1.0/1E-4)\n pt1= (2.0898E-14*e**(-u_m(T,1)))*(1-e**(-planck*nu/(boltz*T)))/((x**3.0)*2.0)\n pt2=0.0\n m0=1.0\n while u_m(T,m0) > planck*nu/(boltz*T):\n m0=m0+1.0 \n \n for mm in np.arange(m0,11,1):\n pt2=pt2+gfb(wavelength,mm)*e**(u_m(T,mm))/(mm**3.0)\n pt3=(1/(2*u_m(T,1)))*(e**(u_m(T,10))-1+gff(wavelength,theta))\n alpha=pt1*(pt2+pt3)\n return alpha\n\ndef kappa_lambda_H(T,LogPe):\n k=alpha_lambda_H(T,LogPe)*(1-X(T,LogPe))/((1+4*B)*m_H)\n return k\n \ndef alpha_lambda_H_ion(T,LogPe): #man does this section look like a mess\n theta =5040.0/T\n bigL=wavelength/1000.0\n nu=speed_light/(wavelength*1.0E-8)\n k_star=0.00680133 + 0.178708*bigL+0.164790*bigL**2 - 0.024842*bigL**3 + 5.95244E-4*bigL**4\n alphabf = 10**-26*(10**LogPe)*0.4158*theta**(5/2)*e**(1.726*theta)*(1-e**(-planck*nu/(boltz*T)))*k_star \n alphaff = 10**-26 * 10**LogPe * (0.0053666 - 0.011493*theta + 0.027029*theta**2-(3.2062-11.924*theta+5.939*theta**2)*(wavelength/10**6)-(0.40192-7.0355*theta+0.34592*theta**2)*(wavelength**2/10**9)) \n alpha = alphabf+alphaff\n #print alphaff\n return alpha \n \n \ndef kappa_lambda_H_ion(T,LogPe):\n k=alpha_lambda_H_ion(T,LogPe)*((1-X(T,LogPe))/((1+4*B)*m_H))\n return k\n\ndef sigma_r():\n r=5.799E-13/wavelength**4+1.422E-6/wavelength**6+2.784/wavelength**8\n return r\n\ndef sigma_R(T,LogPe):\n R=sigma_r()*(1-X(T,LogPe))/((1+4*B)*m_H)\n return R\n\ndef sigma_T(Temp,LogPe):\n T=sigma_t*(X(Temp,LogPe)+Y(Temp,LogPe)/A)/((1+4*B)*m_H) \n return T\n\ndef sigma_lambda(T,LogPe):\n sig=sigma_R(T,LogPe)+sigma_T(T,LogPe) # you add the simgas together\n return sig \n \n\n \n \ndef main():\n #k=kappa_lambda_H_ion()+kappa_lambda_H()\n data_out=[]\n for i in np.arange(0,len(data[:,0]),1):\n T=data[i,0]\n LogPe=data[i,1]\n LogH=np.log10(kappa_lambda_H(T,LogPe))\n LogHion=np.log10(kappa_lambda_H_ion(T,LogPe))\n LogSigma=np.log10(sigma_lambda(T,LogPe))\n data_out.append([T,LogPe,LogH,LogHion,LogSigma]) #CREATES A LINE WITH ALL THE CALCULATED VALUES AND ATTACHES IT TO THE END OF OUR DATA\n np.savetxt(\"data_out.dat\",data_out,fmt='%1.3f')\n #print data_out\n diff= data_out-correct # THIS CALCULATES THE DIFFERENCES BETWEEN MY DATA OUTPUT AND THE DATA OUTPUT ANA GAVE US, tells us how wrong we might be\n np.savetxt(\"diffs.dat\",diff,fmt='%1.3f')\n #plotallthisshit(data_out)\n return data_out\n #print \"Sum of kappas is \"+ str(k)\n #print \"Kappas before logs:\"+str(kappa_lambda_H_ion())+\" and \"+str(kappa_lambda_H())\n #print \"after logs:\"+ str(np.log10(kappa_lambda_H_ion()))+\" and \" + str(np.log10(kappa_lambda_H()))\n\n\n\n \n#kappa_lambda_H_ion()\n \n# THIS SECTIONS RUNS THE CODE AND SPITS OUT SOME PLOTS, DIS IS DA END YO \nmain()\ndata_out=np.array(main()) # UNFORTUNATELY YOU GOTTA TURN THIS THING BACK INTO A NUMPY ARRAY TO MAKE YOUR LIFE EASY\ntotal=np.log10(10**data_out[:,2]+10**data_out[:,3]+10**data_out[:,4])\nplt.plot(data_out[:,0],data_out[:,2],label=\"H\",c='r',ls='-')\nplt.plot(data_out[:,0],data_out[:,3],label=\"H-\",c='b',ls='-')\nplt.plot(data_out[:,0],data_out[:,4],label=\"sigma\",c='g',ls='-')\nplt.plot(data_out[:,0],total,label=\"total\",c=\"cyan\",ls='-')\nplt.legend(bbox_to_anchor=(1, .41))\nplt.ylabel(\"log opacity values (Kappa/gram)\") # LABELS ARE IMPORTANT\nplt.xlabel(\"Temperature (K)\")\nplt.ion()\nplt.show() \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"205487737","text":"def removeInvalidParentheses(s):\n # define when a combination of parenthesis is still valid\n def valid(candidate):\n counter = 0\n for char in candidate:\n if char == \"(\": \n counter += 1\n elif char == \")\": \n counter -= 1\n if counter < 0: \n return False\n # balanced?\n return counter == 0\n\n res, frontier = set() , set([s])\n while not res:\n _next = set()\n for candidate in frontier:\n if valid(candidate): \n res.add(candidate) \n continue\n # generate more candidates based on this candidate\n for i, letter in enumerate(candidate):\n # skip trash\n if letter not in \"()\": \n continue\n _next.add(candidate[:i] + candidate[i+1:])\n frontier = _next\n return res\n \nif __name__ == '__main__':\n # time: O(2^n)\n # space: O(n)\n print(removeInvalidParentheses(\"(a)())()\"))\n # (a)())()\n \n # a)())()\n # (a())()\n # (a)))()\n # (a)()()\n # (a)()))\n # (a)())(\n","sub_path":"stacks/valid_paren_combos.py","file_name":"valid_paren_combos.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516394639","text":"from typing import List, Dict, Union, Optional\n\nimport pytest\nfrom httpx import AsyncClient\nfrom fastapi import FastAPI, status\nfrom databases import Database\n\nfrom app.db.repositories.cleanings import CleaningsRepository\nfrom app.models.cleaning import CleaningCreate, CleaningInDB, CleaningPublic\nfrom app.models.user import UserInDB\n\n\npytestmark = pytest.mark.asyncio\n\n\n@pytest.fixture\ndef new_cleaning():\n return CleaningCreate(\n name=\"test cleaning\", description=\"test description\", price=10.00, cleaning_type=\"spot_clean\",\n )\n\n\n@pytest.fixture\nasync def test_cleanings_list(db: Database, test_user2: UserInDB) -> List[CleaningInDB]:\n cleaning_repo = CleaningsRepository(db)\n return [\n await cleaning_repo.create_cleaning(\n new_cleaning=CleaningCreate(\n name=f\"test cleaning {i}\", description=\"test description\", price=20.00, cleaning_type=\"full_clean\"\n ),\n requesting_user=test_user2,\n )\n for i in range(5)\n ]\n\n\nclass TestCleaningsRoutes:\n \"\"\"\n Check each cleaning route to ensure none return 404s\n \"\"\"\n\n async def test_routes_exist(self, app: FastAPI, client: AsyncClient) -> None:\n res = await client.post(app.url_path_for(\"cleanings:create-cleaning\"), json={})\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.get(app.url_path_for(\"cleanings:get-cleaning-by-id\", cleaning_id=1))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.get(app.url_path_for(\"cleanings:list-all-user-cleanings\"))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.put(app.url_path_for(\"cleanings:update-cleaning-by-id\", cleaning_id=1))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n res = await client.delete(app.url_path_for(\"cleanings:delete-cleaning-by-id\", cleaning_id=0))\n assert res.status_code != status.HTTP_404_NOT_FOUND\n\n\nclass TestCreateCleaning:\n async def test_valid_input_creates_cleaning_belonging_to_user(\n self, app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB, new_cleaning: CleaningCreate\n ) -> None:\n res = await authorized_client.post(\n app.url_path_for(\"cleanings:create-cleaning\"), json={\"new_cleaning\": new_cleaning.dict()}\n )\n assert res.status_code == status.HTTP_201_CREATED\n created_cleaning = CleaningPublic(**res.json())\n assert created_cleaning.name == new_cleaning.name\n assert created_cleaning.price == new_cleaning.price\n assert created_cleaning.cleaning_type == new_cleaning.cleaning_type\n assert created_cleaning.owner == test_user.id\n\n async def test_unauthorized_user_unable_to_create_cleaning(\n self, app: FastAPI, client: AsyncClient, new_cleaning: CleaningCreate\n ) -> None:\n res = await client.post(\n app.url_path_for(\"cleanings:create-cleaning\"), json={\"new_cleaning\": new_cleaning.dict()}\n )\n assert res.status_code == status.HTTP_401_UNAUTHORIZED\n\n @pytest.mark.parametrize(\n \"invalid_payload, status_code\",\n (\n (None, 422),\n ({}, 422),\n ({\"name\": \"test\"}, 422),\n ({\"price\": 10.00}, 422),\n ({\"name\": \"test\", \"description\": \"test\"}, 422),\n ),\n )\n async def test_invalid_input_raises_error(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n invalid_payload: Dict[str, Union[str, float]],\n test_cleaning: CleaningCreate,\n status_code: int,\n ) -> None:\n res = await authorized_client.post(\n app.url_path_for(\"cleanings:create-cleaning\"), json={\"new_cleaning\": invalid_payload}\n )\n assert res.status_code == status_code\n\n\nclass TestGetCleaning:\n async def test_get_cleaning_by_id(\n self, app: FastAPI, authorized_client: AsyncClient, test_cleaning: CleaningInDB\n ) -> None:\n res = await authorized_client.get(\n app.url_path_for(\"cleanings:get-cleaning-by-id\", cleaning_id=test_cleaning.id)\n )\n assert res.status_code == status.HTTP_200_OK\n cleaning = CleaningPublic(**res.json()).dict(exclude={\"owner\"})\n assert cleaning == test_cleaning.dict(exclude={\"owner\"})\n\n async def test_unauthorized_users_cant_access_cleanings(\n self, app: FastAPI, client: AsyncClient, test_cleaning: CleaningInDB\n ) -> None:\n res = await client.get(app.url_path_for(\"cleanings:get-cleaning-by-id\", cleaning_id=test_cleaning.id))\n assert res.status_code == status.HTTP_401_UNAUTHORIZED\n\n @pytest.mark.parametrize(\n \"id, status_code\", ((50000, 404), (-1, 422), (None, 422)),\n )\n async def test_wrong_id_returns_error(\n self, app: FastAPI, authorized_client: AsyncClient, id: int, status_code: int\n ) -> None:\n res = await authorized_client.get(app.url_path_for(\"cleanings:get-cleaning-by-id\", cleaning_id=id))\n assert res.status_code == status_code\n\n async def test_get_all_cleanings_returns_only_user_owned_cleanings(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_user: UserInDB,\n db: Database,\n test_cleaning: CleaningInDB,\n test_cleanings_list: List[CleaningInDB],\n ) -> None:\n res = await authorized_client.get(app.url_path_for(\"cleanings:list-all-user-cleanings\"))\n assert res.status_code == status.HTTP_200_OK\n assert isinstance(res.json(), list)\n assert len(res.json()) > 0\n cleanings = [CleaningInDB(**l) for l in res.json()]\n # check that a cleaning created by our user is returned\n assert test_cleaning in cleanings\n # test that all cleanings returned are owned by this user\n for cleaning in cleanings:\n assert cleaning.owner == test_user.id\n # assert all cleanings created by another user not included (redundant, but fine)\n assert all(c not in cleanings for c in test_cleanings_list)\n\n\nclass TestUpdateCleaning:\n @pytest.mark.parametrize(\n \"attrs_to_change, values\",\n (\n ([\"name\"], [\"new fake cleaning name\"]),\n ([\"description\"], [\"new fake cleaning description\"]),\n ([\"price\"], [3.14]),\n ([\"cleaning_type\"], [\"full_clean\"]),\n ([\"name\", \"description\"], [\"extra new fake cleaning name\", \"extra new fake cleaning description\"]),\n ([\"price\", \"cleaning_type\"], [42.00, \"dust_up\"]),\n ),\n )\n async def test_update_cleaning_with_valid_input(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_cleaning: CleaningInDB,\n attrs_to_change: List[str],\n values: List[str],\n ) -> None:\n cleaning_update = {\"cleaning_update\": {attrs_to_change[i]: values[i] for i in range(len(attrs_to_change))}}\n res = await authorized_client.put(\n app.url_path_for(\"cleanings:update-cleaning-by-id\", cleaning_id=test_cleaning.id), json=cleaning_update\n )\n assert res.status_code == status.HTTP_200_OK\n updated_cleaning = CleaningInDB(**res.json())\n assert updated_cleaning.id == test_cleaning.id # make sure it's the same cleaning\n # make sure that any attribute we updated has changed to the correct value\n for i in range(len(attrs_to_change)):\n assert getattr(updated_cleaning, attrs_to_change[i]) != getattr(test_cleaning, attrs_to_change[i])\n assert getattr(updated_cleaning, attrs_to_change[i]) == values[i]\n # make sure that no other attributes' values have changed\n for attr, value in updated_cleaning.dict().items():\n if attr not in attrs_to_change and attr != \"updated_at\":\n assert getattr(test_cleaning, attr) == value\n\n async def test_user_recieves_error_if_updating_other_users_cleaning(\n self, app: FastAPI, authorized_client: AsyncClient, test_cleanings_list: List[CleaningInDB],\n ) -> None:\n res = await authorized_client.put(\n app.url_path_for(\"cleanings:update-cleaning-by-id\", cleaning_id=test_cleanings_list[0].id),\n json={\"cleaning_update\": {\"price\": 99.99}},\n )\n assert res.status_code == status.HTTP_403_FORBIDDEN\n\n async def test_user_cant_change_ownership_of_cleaning(\n self,\n app: FastAPI,\n authorized_client: AsyncClient,\n test_cleaning: CleaningInDB,\n test_user: UserInDB,\n test_user2: UserInDB,\n ) -> None:\n res = await authorized_client.put(\n app.url_path_for(\"cleanings:update-cleaning-by-id\", cleaning_id=test_cleaning.id),\n json={\"cleaning_update\": {\"owner\": test_user2.id}},\n )\n assert res.status_code == status.HTTP_200_OK\n cleaning = CleaningPublic(**res.json())\n assert cleaning.owner == test_user.id\n\n @pytest.mark.parametrize(\n \"id, payload, status_code\",\n (\n (-1, {\"name\": \"test\"}, 422),\n (0, {\"name\": \"test2\"}, 422),\n (500, {\"name\": \"test3\"}, 404),\n (1, None, 422),\n (1, {\"cleaning_type\": \"invalid cleaning type\"}, 422),\n (1, {\"cleaning_type\": None}, 400),\n ),\n )\n async def test_update_cleaning_with_invalid_input_throws_error(\n self, app: FastAPI, authorized_client: AsyncClient, id: int, payload: Dict[str, Optional[str]], status_code: int\n ) -> None:\n cleaning_update = {\"cleaning_update\": payload}\n res = await authorized_client.put(\n app.url_path_for(\"cleanings:update-cleaning-by-id\", cleaning_id=id), json=cleaning_update\n )\n assert res.status_code == status_code\n\n\nclass TestDeleteCleaning:\n async def test_can_delete_cleaning_successfully(\n self, app: FastAPI, authorized_client: AsyncClient, test_cleaning: CleaningInDB\n ) -> None:\n res = await authorized_client.delete(\n app.url_path_for(\"cleanings:delete-cleaning-by-id\", cleaning_id=test_cleaning.id)\n )\n assert res.status_code == status.HTTP_200_OK\n\n async def test_user_cant_delete_other_users_cleaning(\n self, app: FastAPI, authorized_client: AsyncClient, test_cleanings_list: List[CleaningInDB],\n ) -> None:\n res = await authorized_client.delete(\n app.url_path_for(\"cleanings:delete-cleaning-by-id\", cleaning_id=test_cleanings_list[0].id)\n )\n assert res.status_code == status.HTTP_403_FORBIDDEN\n\n @pytest.mark.parametrize(\n \"id, status_code\", ((5000000, 404), (0, 422), (-1, 422), (None, 422)),\n )\n async def test_wrong_id_throws_error(\n self, app: FastAPI, authorized_client: AsyncClient, test_cleaning: CleaningInDB, id: int, status_code: int\n ) -> None:\n res = await authorized_client.delete(app.url_path_for(\"cleanings:delete-cleaning-by-id\", cleaning_id=id))\n assert res.status_code == status_code\n","sub_path":"backend/tests/test_cleanings.py","file_name":"test_cleanings.py","file_ext":"py","file_size_in_byte":10952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"322806802","text":"#coding=utf-8\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\nfrom app.models import *\nfrom .controller import *\nfrom .settings import DATA_NOEXIST,UER_NOLOGIN\nfrom utils.download import *\nimport json\n\nANDROID_PROFILE = 1;\nANDROID_FRIEND = 2;\nANDROID_NEARBY = 3;\nANDROID_STATUS = 4;\n\nHEADPIC = 1;\nSIGNPIC =2;\nSTATUSPIC = 3;\nUSERPHOTO = 4;\nME = 5;\n\nheadpic_path = media_path+\"android/headimg/\"\nsignpic_path = media_path+\"android/sign/\"\nstatupic_path = media_path+\"android/content_img/\"\nuserphoto_path = media_path+\"android/userphoto/\"\n\ndef android_get_service(request,name, what):\n \n if not request.user.is_authenticated():\n return HttpResponse(UER_NOLOGIN,content_type=\"application/json\")\n \n json_data =None;\n if int(what)==ANDROID_PROFILE:\n json_data = get_userprofile(name);\n elif int(what)==ANDROID_FRIEND:\n json_data = get_userfriend(name);\n elif int(what)==ANDROID_NEARBY:\n json_data = get_nearby(name);\n elif int(what)==ANDROID_STATUS:\n json_data = get_userstatus(name);\n elif int(what)==ME:\n json_data = get_me(name);\n \n if json_data==None:\n return HttpResponse(DATA_NOEXIST,content_type=\"application/json\")\n\n return HttpResponse(json_data,content_type=\"application/json\")\n \ndef android_get_without_login(request,name, what):\n \n json_data =None;\n if int(what)==ANDROID_PROFILE:\n json_data = get_userprofile(name);\n elif int(what)==ANDROID_FRIEND:\n json_data = get_userfriend(name);\n elif int(what)==ANDROID_NEARBY:\n json_data = get_nearby(name);\n elif int(what)==ANDROID_STATUS:\n json_data = get_userstatus(name);\n elif int(what)==ME:\n json_data = get_me(name);\n \n if json_data==None:\n return HttpResponse(DATA_NOEXIST,content_type=\"application/json\")\n\n return HttpResponse(json_data,content_type=\"application/json\")\n \ndef android_download(request,name, what):\n \n if not request.user.is_authenticated():\n return HttpResponse(UER_NOLOGIN,content_type=\"application/json\") \n \n userinfo = (User.objects.filter(username=name));\n if (len(userinfo)==0):\n return HttpResponse(USER_NOEXIST,content_type=\"application/json\")\n \n profile = userinfo[0].userprofile;\n filepath = \"\";\n if int(what)==HEADPIC:\n filepath = headpic_path+profile.headimg.url.split(\"/\")[-1];\n return image_download(request,filepath,name);\n elif int(what)==SIGNPIC:\n filepath = signpic_path+profile.getSignature().sign_pic.url.split(\"/\")[-1];\n elif int(what)==STATUSPIC:\n filepath = signpic_path+profile.getSignature().sign_pic.url.split(\"/\")[-1];\n elif int(what)==ANDROID_STATUS:\n filepath = signpic_path+profile.getSignature().sign_pic.url.split(\"/\")[-1];\n \n if filepath==\"\":\n return HttpResponse(PIC_DOWNLOAD_ERROR,content_type=\"application/json\")\n\n return fast_download(request,filepath,name);\n \ndef android_update_useraddr(request):\n ip = request.META['REMOTE_ADDR'];\n port = request.META['REMOTE_ADDR'];\n return HttpResponse(json.dumps(request),content_type=\"application/json\");\n ","sub_path":"weixinofneolocal/weixinofneolocal/android/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278394752","text":"import socket\nimport fitz\nimport nltk\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom collections import Counter\nfrom _collections import OrderedDict\nfrom nltk.corpus import stopwords\nnltk.download('punkt')\n\n\n\n\n\n\nHOST = \"localhost\"\nPORT = 3035\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nprint('Socket created')\ns.bind((HOST, PORT))\ns.listen()\nprint(\"Socket Listening\")\nconn, addr = s.accept()\n\n\nconn.send(bytes(\"Message\"+\"\\r\\n\",'UTF-8'))\nprint(\"Message sent\")\ndata = conn.recv(1024)\nurlcadena=data.decode(encoding='UTF-8')\n\n\n\ndef sube(nombrearchivo):\n\t\n\tdoc=fitz.open(nombrearchivo)\n\tsalida=open(nombrearchivo+\".txt\",\"wb\")\n\tfor pagina in doc:\n\t\ttexto=pagina.getText().encode(\"utf8\")\n\t\tsalida.write(texto.lower())\n\t\tsalida.write(b\"\\n-----\\n\")\n\tsalida.close()\n\n\twith open(nombrearchivo+'.txt','r',encoding='UTF8') as archivo:\n\t\ttexto = archivo.read();\n\t\n\n\t\n\n\n\t\n\n\tstop_words = set(stopwords.words(fileids=('english', 'spanish')))\n\n\tword_tokens=word_tokenize(texto)\n\n\n \n\tword_tokens=list(filter(lambda token: token not in string.punctuation,word_tokens))\n\n#areglo=[]\n\t#word_tokens.append(\"--\")\n\tfiltro=[]\n\n\tfor palabra in word_tokens:\n\t\tif palabra not in stop_words:\n\t\t\tfiltro.append(palabra)\n\n\n\t\n\tc=Counter(filtro)\n\n\ty=OrderedDict(c.most_common())\n\twith open(nombrearchivo+'KEYWORDS.txt','w',encoding='UTF8') as far:\n\t\tfor k,v in y.items():\n\t\t\tfar.write(f\"{k} {v}\\n\")\n\n\n\n\n#sube(\"C:\\\\TESIS REMIGIO FINAL\\\\wildfly-20.0.0.Final\\\\wildfly-20.0.0.Final\\\\standalone\\\\deployments\\\\SistemaWebSociedadLector.war/resources/docs/3 4G tecnologias.pdf\");\nsube(urlcadena);\nconn.close() ","sub_path":"nltk_pdf.py","file_name":"nltk_pdf.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"337115071","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# Date : 2018/5/16 14:51\r\n# Author : lixingyun\r\n# Description :\r\nfrom .common import REDIS_INST, Common\r\n\r\n\r\nclass Gift():\r\n @staticmethod\r\n def del_lj(uid, gift, cid):\r\n key = f'hm_add_new_gift_num_{uid}_{gift}_{cid}'\r\n REDIS_INST.delete(key)\r\n","sub_path":"huomao/gift.py","file_name":"gift.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"90168713","text":"# 说明:填充数据提取批次的信息···\nimport OperateCooperationCompany as OCC\nimport OperateDataExtractBatch as ODEB\nimport GlobalVariable as GV\nimport copy\n\ndef FillDataExtractBatch(MysqlObject,CommpanyName,BatchDate):\n CompanyInfoDict=copy.deepcopy(OCC.GetExistCooperationCompanyInfoDict(MysqlObject))\n BatchInfoDict=copy.deepcopy(ODEB.GetExistBatchInfoDict(MysqlObject))\n\n CompanyMap=CompanyInfoDict[CommpanyName]\n BatchInfo=[CompanyMap,BatchDate]\n for BatchMap in BatchInfoDict:\n if BatchInfo==BatchInfoDict[BatchMap]:\n GV.FinalResultRegisterDict['CompanyName']=CommpanyName\n GV.FinalResultRegisterDict['BatchDate'] = BatchDate\n GV.FinalResultRegisterDict['BatchMap'] = BatchMap\n\n\n","sub_path":"zhangzhuo (发布版)本地测试/UserPortrayal_ChangeDatabase/FillDataExtractBatch.py","file_name":"FillDataExtractBatch.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"622942937","text":"import pandas as pd\nimport pickle\nfrom pprint import pprint as pp\nimport c19all\nimport constants\n\n\n\"\"\" Creates two dictionaries of structured US data and pickle files for each dataframe\n df_us()\n Contains all US data by date with location type parsed into columns for each type\n df_region_and_state()\n Contains all US data by date, aggregated by state, with columns for us 2019 census region, sub_region, and population\n\"\"\"\n\nKNOWN_LOCATIONS = constants.US_LOCATIONS_IN_SOURCE\nPOPULATION = constants.US_POPULATION\nSTABBREVS = constants.US_STATE_ABBREVS\n\n_output_columns = [\n 'date',\n 'day',\n 'state',\n 'county',\n 'territory',\n 'other',\n 'unknown_type',\n 'sub_region', # only state-level records\n 'region', # only state-level records\n 'is_state',\n 'lat',\n 'long',\n 'population', # only state-level records\n 'cases',\n]\n\n\ndef _parse_location(row):\n location = row._location\n if location not in KNOWN_LOCATIONS:\n row.unknown_type = location\n print(f'Location {location} assigend as unknown_type. Update constants.US_LOCATIONS_IN_SOURCE')\n return row\n if KNOWN_LOCATIONS[location] == 'state':\n row.is_state = True\n row.state = location\n row.sub_region = POPULATION[location]['sub_region']\n row.region = POPULATION[location]['region']\n row.population = int(round(POPULATION[location]['population']))\n return row\n row.is_state = False\n if KNOWN_LOCATIONS[location] == 'county':\n # TODO: Error trapping here\n county_and_abbrev = location.split(', ')\n row.county = county_and_abbrev[0].replace(' ', '')\n row.state = STABBREVS[county_and_abbrev[1].replace(' ', '')]\n return row\n if KNOWN_LOCATIONS[location] == 'territory':\n row.territory = location\n return row\n if KNOWN_LOCATIONS[location] == 'other':\n row.other = location\n return row\n print(f'Failed to parse {location} as known or unknown_type')\n raise ValueError('A very specific bad thing happened.')\n\n\ndef _handle_special_cases(df):\n \"\"\" Special case renaming of locations \"\"\"\n # Merge names for the District of Columbia\n df.other = df.other.apply(lambda other: (\n other, 'District of Columbia')[other == 'Washington, D.C.'])\n # Remove U.S. from the Virgin Islands\n df.territory = df.territory.apply(lambda territory: (\n territory, 'Virgin Islands')[territory == 'Virgin Islands, U.S.'])\n return df\n\n\ndef _us_data(df):\n \"\"\" Produce output dataframe from raw JH data filtered on US records \"\"\"\n df = df.rename(columns={'province_state': '_location'})\n df['state'] = None\n df['county'] = None\n df['territory'] = None\n df['other'] = None\n df['unknown_type'] = None\n df['is_state'] = None\n df['region'] = None\n df['sub_region'] = None\n df['population'] = None\n df = df.apply(lambda row: _parse_location(row), axis=1)\n df = _handle_special_cases(df)\n df = df.reset_index(drop=True)\n df.set_index(['date', 'day', 'state', 'county', 'territory',\n 'other', 'unknown_type', 'sub_region', 'region', 'is_state'])\n return df.filter(items=_output_columns)\n\n\ndf_us = {\n 'cases': _us_data(c19all.for_country(c19all.df_all['cases'], 'US')),\n 'deaths': _us_data(c19all.for_country(c19all.df_all['deaths'], 'US')),\n 'recovered': _us_data(c19all.for_country(c19all.df_all['recovered'], 'US'))\n}\n\n\ndef _by_region_and_state(df):\n df = df[['date', 'region', 'sub_region', 'state', 'population', 'cases']]\n return df.groupby(['date', 'region', 'sub_region', 'state'], as_index=False).sum()\n\n\ndf_us_region_and_state = {\n 'cases': _by_region_and_state(df_us['cases']),\n 'deaths': _by_region_and_state(df_us['deaths']),\n 'recovered': _by_region_and_state(df_us['recovered']),\n}\n\n# Optional pickle files\npickle_file = open('output/pickles/df_us.p', 'wb')\npickle.dump(df_us, pickle_file)\nprint('Updated pickle file df_us.p')\npickle_file = open('output/pickles/df_us_region_and_state.p', 'wb')\npickle.dump(df_us, pickle_file)\nprint('Updated pickle file df_us_region_and_state.p')\n","sub_path":"lib/c19us.py","file_name":"c19us.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"543357657","text":"\nimport psutil\nimport subprocess\nimport time\n\ndef get_freq_bounds():\n bounds = [0, 0]\n freq_file = open(\"/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq\", 'r')\n bounds[1] = int(freq_file.read())\n freq_file.close()\n freq_file = open(\"/sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq\", 'r')\n bounds[0] = int(freq_file.read())\n freq_file.close()\n return bounds\n\ndef set_gov_userspace():\n # Add check for intel_cpufreq\n driver_file = open(\"/sys/devices/system/cpu/cpu0/cpufreq/scaling_driver\")\n driver = driver_file.read()\n driver_file.close()\n\n if \"cpufreq\" in driver:\n for i in range(psutil.cpu_count()):\n gov_file = \"/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor\" % i\n gfd = open(gov_file, 'w')\n gfd.write(\"userspace\")\n gfd.close()\n else:\n print(\"Unspported Driver: please enable intel/acpi_cpufreq from kerenl cmdline\")\n\ndef read_freq(cpu=0):\n f_file = \"/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq\" % cpu\n freq_file = open(f_file)\n ret_val = freq_file.read()\n freq_file.close()\n return ret_val\n\ndef write_freq(val, cpu=0):\n bounds = get_freq_bounds()\n if val <= bounds[1] and val >= bounds[0]:\n# print(\"Changing Freq to \", str(val))\n f_file = \"/sys/devices/system/cpu/cpu%d/cpufreq/scaling_setspeed\" % cpu\n freq_file = open(f_file, 'w')\n freq_file.write(str(val))\n freq_file.close()\n return\n\ndef power_at_freq(in_freq):\n # freq is represented as 8 = 800MHz; 42 = 4200MHz\n bounds = get_freq_bounds()\n if in_freq <= bounds[1] and in_freq >= bounds[0]:\n freq = in_freq/100000\n elif in_freq < bounds[0]:\n freq = 8\n elif in_freq > bounds[1]:\n freq = 42\n return (0.0211*(freq**2) - 0.4697*freq + 7.7535)*1000\n\ndef freq_at_power(power):\n return int(-0.0773*((power/1000)**2)+ 3.7436*(power/1000) - 4.6404)*100000\n \ndef change_freq(target_power, increase=False):\n \"\"\" Update frequency based on target power and power model \"\"\"\n # power differential to freq reduction factor\n new_freq = freq_at_power(target_power)\n old_freq = int(read_freq())\n # print(new_freq, old_freq, target_power)\n\n if abs(old_freq - new_freq) <= 1000:\n return\n\n new_power = power_at_freq(new_freq)\n\n if increase:\n while new_power < target_power:\n old_power = power_at_freq(new_freq)\n new_freq = new_freq + 100000\n new_power = power_at_freq(new_freq)\n if new_power == old_power:\n new_freq = new_freq - 100000\n break\n # print(new_freq, old_freq, new_power, target_power)\n else:\n while new_power > target_power:\n old_power = power_at_freq(new_freq)\n new_freq = new_freq - 100000\n new_power = power_at_freq(new_freq)\n # print(new_freq, old_freq, new_power)\n if new_power == old_power:\n new_freq = new_freq + 100000\n break\n\n # WARN: Hardecoded cpu numbers below\n for i in range(psutil.cpu_count()):\n write_freq(new_freq, i)\n\n return\n\ndef change_freq_std(target_pwr, current_pwr, increase=False):\n \"\"\" Update frequency based on target power and actulal power value \"\"\"\n # power differential to freq reduction factor\n new_freq = int(read_freq())\n\n power_diff = abs(current_pwr - target_pwr)\n step = 100000\n\n # Select the right step size\n if power_diff < 900:\n # to close better settle than oscillate\n return\n elif power_diff > 3000 and power_diff < 10000:\n step = 200000\n elif power_diff > 10000:\n step = 500000\n\n if increase:\n new_freq = new_freq + step\n else:\n new_freq = new_freq - step\n\n # WARN: Hardecoded cpu numbers below\n for i in range(psutil.cpu_count()):\n write_freq(new_freq, i)\n\n return\n\ndef keep_limit(curr_power, limit=20000, first_limit=True):\n \"\"\" Follow the power limit \"\"\"\n new_limit = limit\n\n if not first_limit:\n if curr_power - limit > 0 and new_limit > 5000:\n new_limit = new_limit - abs(curr_power - new_limit)/2\n #new_limit = new_limit - 1000\n elif curr_power - limit < 0 and new_limit > 5000:\n new_limit = new_limit + abs(curr_power - new_limit)/4\n# #new_limit = new_limit + 1000\n\n # print(\"In keep_limit \", limit)\n if curr_power > limit:\n # reduce frequency\n change_freq_std(new_limit, curr_power)\n elif curr_power < limit:\n # print(\"Increase\")\n change_freq_std(new_limit, curr_power, increase=True)\n else:\n # First Step\n if curr_power > limit:\n # reduce frequency\n change_freq(new_limit)\n elif curr_power < limit:\n # print(\"Increase\")\n change_freq(new_limit, increase=True)\n return\n\n","sub_path":"frequency.py","file_name":"frequency.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"133553946","text":"import os\nfrom flask import make_response, jsonify\n\nfrom google.cloud import iot_v1\n\n\nproject_id = os.getenv(\"PROJECT_ID\")\nregistry_id = os.getenv(\"REGISTRY_ID\")\ndevice_id = os.getenv(\"DEVICE_ID\")\ncloud_region = os.getenv(\"CLOUD_REGION\")\n\nclient = iot_v1.DeviceManagerClient()\ndevice_path = client.device_path(project_id, cloud_region, registry_id, device_id)\n\n\ndef send_command_to_device(request):\n request_json_data = request.get_json(silent=True, force=True)\n print(\"Sending command to device\")\n command = request_json_data.get(\"data\")\n data = command.encode(\"utf-8\")\n client.send_command_to_device(\n request={\"name\": device_path, \"binary_data\": data}\n )\n return make_response(jsonify({'message': \"Command sent to device successfully\"}), 200)\n\n\ndef list_state_to_iotcore():\n\n device = client.get_device(request={\"name\": device_path})\n print(\"Last state: {}\".format(device.state))\n\n print(\"State history\")\n states = client.list_device_states(request={\"name\": device_path}).device_states\n for state in states:\n print(\"State: {}\".format(state))\n\n return states\n\n\ndef update_device_config():\n # project_id = 'YOUR_PROJECT_ID'\n # cloud_region = 'us-central1'\n # registry_id = 'your-registry-id'\n # device_id = 'your-device-id'\n version = 0\n config = 'your-config-data1'\n print(\"Set device configuration\")\n client = iot_v1.DeviceManagerClient()\n device_path = client.device_path(project_id, cloud_region, registry_id, device_id)\n\n data = config.encode(\"utf-8\")\n\n return client.modify_cloud_to_device_config(\n request={\"name\": device_path, \"binary_data\": data, \"version_to_update\": version}\n )\n\n\nif __name__ == '__main__':\n list_state_to_iotcore()","sub_path":"IoTcore/iotcore_cloud_functions.py","file_name":"iotcore_cloud_functions.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377117878","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nfrom scrapy.exceptions import DropItem\n\nimport logging\nimport os\nimport time\n\nfrom scrapy.http import Request\nfrom scrapy.item import BaseItem\nfrom scrapy.utils.request import request_fingerprint\nfrom scrapy.utils.project import data_path\nfrom scrapy.utils.python import to_bytes\nfrom scrapy.exceptions import NotConfigured\nfrom scrapy import signals\n\nlogger = logging.getLogger(__name__)\n\nclass CoDeltaFetch(object):\n \"\"\"\n This is a spider middleware to ignore requests to pages containing items\n seen in previous crawls of the same spider, thus producing a \"delta crawl\"\n containing only new items.\n\n This also speeds up the crawl, by reducing the number of requests that need\n to be crawled, and processed (typically, item requests are the most cpu\n intensive).\n \"\"\"\n\n def __init__(self, dir, reset=False, stats=None):\n dbmodule = None\n try:\n dbmodule = __import__('bsddb3').db\n except ImportError:\n raise NotConfigured('bsddb3 is required')\n self.dbmodule = dbmodule\n self.dir = dir\n self.reset = reset\n self.stats = stats\n\n @classmethod\n def from_crawler(cls, crawler):\n s = crawler.settings\n if not s.getbool('CODELTAFETCH_ENABLED'):\n raise NotConfigured\n dir = data_path(s.get('CODELTAFETCH_DIR', 'codeltafetch'))\n reset = s.getbool('CODELTAFETCH_RESET')\n o = cls(dir, reset, crawler.stats)\n crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)\n crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)\n return o\n\n def spider_opened(self, spider):\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n dbpath = os.path.join(self.dir, 'company_info.db' )\n reset = self.reset or getattr(spider, 'codeltafetch_reset', False)\n flag = self.dbmodule.DB_TRUNCATE if reset else self.dbmodule.DB_CREATE\n try:\n self.db = self.dbmodule.DB()\n self.db.open(filename=dbpath,\n dbtype=self.dbmodule.DB_HASH,\n flags=flag)\n except Exception:\n logger.warning(\"Failed to open CoDeltaFetch database at %s, \"\n \"trying to recreate it\" % dbpath)\n if os.path.exists(dbpath):\n os.remove(dbpath)\n self.db = self.dbmodule.DB()\n self.db.open(filename=dbpath,\n dbtype=self.dbmodule.DB_HASH,\n flags=self.dbmodule.DB_CREATE)\n\n def spider_closed(self, spider):\n self.db.close()\n\n def process_item(self, item, spider):\n r = item\n if isinstance(r, (BaseItem, dict)):\n key = self._get_key(r)\n if key in self.db:\n logger.info(\"Ignoring already crawl: %s\" % r)\n if self.stats:\n self.stats.inc_value('codeltafetch/skipped', spider=spider)\n else:\n self.db[key] = str(time.time())\n if self.stats:\n self.stats.inc_value('codeltafetch/stored', spider=spider)\n return r\n\n def _get_key(self, item):\n try:\n key = item['companyFullName']\n key = to_bytes(key)\n except:\n key = item['companyFullName'][0]\n print(type(key))\n key = to_bytes(key)\n # request_fingerprint() returns `hashlib.sha1().hexdigest()`, is a string\n return key\n\n\nclass CleanPipeline(object):\n\n def process_item(self, item, spider):\n try:\n if item['companyFullName']:\n item[\"description\"] = str(item[\"description\"]).replace('

', '').replace('\\r', '').replace('\\t','').\\\n replace('\\n', '').replace('

', '').replace(' ', '').replace('
', '').replace('
','').replace('

','').replace('\"', '').replace(' ', '')\n return item\n else:\n raise DropItem(\"This Page Does Not Exist, nigga!\\n\")\n except:\n raise DropItem(\"This Page Does Not Exist\")","sub_path":"theproduct/qinzhihao/search/spider_lagou_search/lagou_search/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"168989049","text":"#https://www.codewars.com/kata/product-of-consecutive-fib-numbers/train/python\n\n#The Fibonacci numbers are the numbers in the following integer sequence (Fn):\n\n# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...\n\n#such as\n\n# F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.\n\n#Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying\n\n# F(n) * F(n+1) = prod.\n\n#Your function productFib takes an integer (prod) and returns an array:\n\n#[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)\n\n#depending on the language if F(n) * F(n+1) = prod.\n\n#If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prodyou will return\n\n#[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)\n\n#F(m) being the smallest one such as F(m) * F(m+1) > prod.\n#Examples\n\n#productFib(714) # should return [21, 34, true], \n# # since F(8) = 21, F(9) = 34 and 714 = 21 * 34\n\n#productFib(800) # should return [34, 55, false], \n# # since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55\n\n#Notes: Not useful here but we can tell how to choose the number n up to which to go: we can use the \"golden ratio\" phi which is (1 + sqrt(5))/2 knowing that F(n) is asymptotic to: phi^n / sqrt(5). That gives a possible upper bound to n.\n\n#You can see examples in \"Example test\".\n\n\nimport math\n\ndef fib(n):\n a = 1\n b = 1\n\n for i in range(3, n+2):\n a,b = b, a+b\n return a,b\n\ndef productFib(chislo):\n \n phi = (1+math.sqrt(5))/2\n m = math.sqrt(chislo)\n n = int(math.log(m*math.sqrt(5), phi))\n \n a,b = fib(n)\n\n if (a*b-chislo>=0) and ((a*b-chislo)<(b*(a+b)-chislo)):\n if a*b == chislo:\n return [a,b,True]\n else:\n return [a,b,False]\n else:\n if b*(a+b) == chislo:\n return [b,a+b,True]\n else:\n return [b,a+b,False]","sub_path":"python/5kyu/Product_of_consecutive_Fib_numbers.py","file_name":"Product_of_consecutive_Fib_numbers.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375049153","text":"\"\"\"\nDepreciation Rate Calibration (depreciation_calibration.py):\n-------------------------------------------------------------------------------\nLast updated: 6/26/2015.\n\nThis module calibrates the firm economic and tax depreciation parameters.\n\"\"\"\n'''\nThis py-file calls the following file(s):\n Raw input files:\n data\\**sbfltfile\\****sb1.csv\n data\\**sbfltfile\\****sb3.csv\n data\\SOI_Partner\\pa01.csv\n data\\SOI_Partner\\pa03.csv\n data\\SOI_Partner\\pa05.csv\n \n Formatted input files:\n data\\****_NAICS_Codes.csv\n data\\SOI_Partner\\pa01_Crosswalk.csv\n data\\SOI_Partner\\pa03_Crosswalk.csv\n data\\SOI_Partner\\pa05_Crosswalk.csv\n'''\n# Packages:\nimport os.path\nimport sys\nimport numpy as np\nimport pandas as pd\n# Relevant directories:\n_CUR_DIR = os.path.dirname(__file__)\n_DATA_DIR = os.path.abspath(_CUR_DIR + \"\\\\data\")\n_PROC_DIR = os.path.abspath(_CUR_DIR + \"\\\\processing\")\n_OUT_DIR = os.path.abspath(_CUR_DIR + \"\\\\output\")\n# Importing standard custom modules:\nimport naics_processing as naics\nimport constants as cst\nimport soi_processing as read_soi\n# Importing depreciation helper custom modules:\nsys.path.append(_PROC_DIR)\nimport calc_asset_types as calc_assets\nimport calc_rates as calc_rates\nimport read_bea as read_bea\nimport read_inventories as read_inv\nimport read_land as read_land\n# Dataframe names:\n_CODE_DF_NM = cst.CODE_DF_NM\n\n\ndef init_depr_rates(data_tree=naics.generate_tree(), get_econ=False, \n get_tax_est=False, get_tax_150=False,\n get_tax_200=False, get_tax_sl=False,\n get_tax_ads=False, soi_from_out=False,\n output_data=False):\n # Reading in the SOI Tax Stats-Corporation data:\n soi_tree = naics.generate_tree()\n soi_tree = read_soi.load_corporate(soi_tree=soi_tree, \n from_out=soi_from_out,\n output_data=(not soi_from_out))\n # Reading in the SOI Tax Stats-Partnership data:\n soi_tree = read_soi.load_partner(soi_tree=soi_tree, \n from_out=soi_from_out,\n output_data=(not soi_from_out))\n # Reading in the SOI Tax Stats-Proprietorship data:\n soi_tree = read_soi.load_soi_proprietorship(soi_tree=soi_tree, \n from_out=soi_from_out,\n output_data=(not soi_from_out))\n '''\n Many industries are not listed in the SOI datasets. The data for these missing\n industries are interpolated.\n '''\n # Get a list of the names of all the pd dfs besides the list of codes:\n #cur_names = soi_tree.enum_inds[0].data.dfs.keys()\n #cur_names.remove(_CODE_DF_NM)\n # Populate missing industry data backwards throught the tree:\n #naics.pop_back(data_tree, cur_names)\n # Populate the missing total corporate data forwards through the tree:\n #naics.pop_forward(data_tree, [\"tot_corps\"])\n # Populate other missing data using tot_corps as a \"blueprint\":\n #cur_names = [\"c_corps\", \"s_corps\", \"PA_inc_loss\", \"PA_assets\", \"soi_prop\"]\n #naics.pop_forward(data_tree, cur_names, \"tot_corps\")\n # Calculate c_corps data:\n #read_soi.calc_c_corp(data_tree)\n #naics.pop_back(data_tree,[\"c_corps\"])\n #naics.pop_forward(data_tree, [\"c_corps\"], \"tot_corps\")\n # Populate pa05 using pa01:\n #naics.pop_forward(data_tree, [\"PA_types\"], \"PA_inc_loss\")\n #\n #naics.pop_back(data_tree, [\"farm_prop\"])\n #naics.pop_forward(data_tree, [\"farm_prop\"], \"tot_corps\")\n \n #Create an output tree containing only the final data on FA, INV, and LAND.\n output_tree = calc_assets.summary_tree(data_tree, _DATA_DIR)\n # Create a tree with all the FA's broken down by type of asset:\n asset_tree = read_bea.read_bea(output_tree, _DATA_DIR)\n naics.pop_back(asset_tree, [\"All\", \"Corp\", \"Non-Corp\"])\n #\n corp_types = [\"C Corporations\",\n \"Corporate general partners\", \n \"Corporate limited partners\"]\n non_corp_types = [\"S Corporations\",\n \"Individual general partners\",\n \"Individual limited partners\",\n \"Partnership general partners\",\n \"Partnership limited partners\",\n \"Tax-exempt organization general partners\",\n \"Tax-exempt organization limited partners\",\n \"Nominee and other general partners\", \n \"Nominee and other limited partners\",\n \"Sole Proprietors\"]\n naics.pop_forward(asset_tree, [\"All\"], \"FA\", output_tree)\n naics.pop_forward(asset_tree, [\"Corp\"], \"FA\", output_tree, corp_types)\n naics.pop_forward(asset_tree, [\"Non-Corp\"], \"FA\", output_tree, non_corp_types)\n #\n inv_tree = read_inv.read_inventories(output_tree, _DATA_DIR)\n naics.pop_back(inv_tree, [\"Inventories\"])\n naics.pop_forward(inv_tree, [\"Inventories\"])\n #\n land_tree = read_land.read_land(output_tree, _DATA_DIR)\n naics.pop_back(land_tree, [\"Land\"])\n naics.pop_forward(land_tree, [\"Land\"], \"LAND\", output_tree)\n #\n econ_depr_tree = calc_rates.calc_depr_rates(asset_tree, inv_tree, land_tree, _DATA_DIR)\n tax_depr_tree = calc_rates.calc_tax_depr_rates(asset_tree, inv_tree, land_tree, _DATA_DIR)\n naics.pop_rates(tax_depr_tree)\n return {\"Econ\": econ_depr_tree, \"Tax\": tax_depr_tree}\n \n\n#\n#naics.print_tree_dfs(econ_depr_tree, _OUT_DIR)\n#naics.print_tree_dfs(tax_depr_tree, _OUT_DIR)\n\n\n\n\n\n","sub_path":"Data/Calibration/Firm_Calibration_Python/parameters/depreciation/depreciation_calibration.py","file_name":"depreciation_calibration.py","file_ext":"py","file_size_in_byte":5629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"509276042","text":"\"\"\"creating orders and orders product table\n\nRevision ID: c6386f7a616f\nRevises: bdf29d02ce62\nCreate Date: 2021-10-11 21:56:59.054261\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c6386f7a616f'\ndown_revision = 'bdf29d02ce62'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('orders',\n sa.Column('order_id', sa.Integer(), nullable=False),\n sa.Column('status', sa.String(), nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('adress_id', sa.Integer(), nullable=True),\n sa.Column('shipping_company_id', sa.Integer(), nullable=True),\n sa.Column('payment_method_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['adress_id'], ['orders_adresses.order_adress_id'], ),\n sa.ForeignKeyConstraint(['payment_method_id'], ['payment_methods.payment_method_id'], ),\n sa.ForeignKeyConstraint(['shipping_company_id'], ['shipping_companies.shipping_company_id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.user_id'], ),\n sa.PrimaryKeyConstraint('order_id')\n )\n op.create_table('orders_product',\n sa.Column('orders_product_id', sa.Integer(), nullable=False),\n sa.Column('order_id', sa.Integer(), nullable=True),\n sa.Column('product_id', sa.Integer(), nullable=True),\n sa.Column('quantity', sa.Integer(), nullable=True),\n sa.Column('total_value', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['order_id'], ['orders.order_id'], ),\n sa.ForeignKeyConstraint(['product_id'], ['products.product_id'], ),\n sa.PrimaryKeyConstraint('orders_product_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('orders_product')\n op.drop_table('orders')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/c6386f7a616f_creating_orders_and_orders_product_table.py","file_name":"c6386f7a616f_creating_orders_and_orders_product_table.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"623158157","text":"# Method1: Using user defined function.\n\n# function to check if small string is\n# there in big string\ndef check(string, sub_str):\n if (string.find(sub_str) == -1):\n print(\"NO\")\n else:\n print(\"YES\")\n\n\n# driver code\nstring = \"geeks for geeks\"\nsub_str = \"geek\"\ncheck(string, sub_str)\n\n# method-2\n\n\ndef check(s2, s1):\n if (s2.count(s1) > 0):\n print(\"YES\")\n else:\n print(\"NO\")\n\n\ns2 = \"A geek in need is a geek indeed\"\ns1 = \"geek\"\ncheck(s2, s1)\n\n\n# method-3\n\n# When you have imported the re module, you can start using regular expressions.\nimport re\n\n# Take input from users\nMyString1 = \"A geek in need is a geek indeed\"\nMyString2 =\"geek\"\n\n# re.search() returns a Match object if there is a match anywhere in the string\nif re.search( MyString2, MyString1 ):\n\tprint(\"YES,string '{0}' is present in string '{1}' \" .format(MyString2,MyString1))\nelse:\n\tprint(\"NO,string '{0}' is not present in string {1} \" .format(MyString2, MyString1) )\n","sub_path":"42_CheckSubstringInString&LengthOfString.py","file_name":"42_CheckSubstringInString&LengthOfString.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626772278","text":"\n\n#calss header\nclass _TORTILLA():\n\tdef __init__(self,): \n\t\tself.name = \"TORTILLA\"\n\t\tself.definitions = [u'a type of thin, round Mexican bread made from maize or wheat flour', u'a thick Spanish omelette (= a flat, round food made by frying eggs that have been mixed together) with potato and sometimes onion in it']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tortilla.py","file_name":"_tortilla.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"409293251","text":"from typing import List\n\nfrom db.base.handler import QueryHandler\nfrom db.schema.dbo.tipo_cuerno.mapper import TipoCuernoMapper, TipoCuernoDataClass\nfrom db.schema.dbo.tipo_cuerno.query import TipoCuernoQueryBuilder\nfrom dominio.producto import Cuerno\n\n\nclass TipoCuernoHandler(QueryHandler):\n _o: TipoCuernoDataClass\n _mapper = TipoCuernoMapper()\n _qb = TipoCuernoQueryBuilder()\n results: List[TipoCuernoDataClass]\n\n def create(self, o: Cuerno):\n raise Exception(\"Protected table\")\n\n def with_id(self):\n self._wheres += 1\n self._qb.with_id(self._o.id)\n\n def with_descripcion(self):\n self._wheres += 1\n self._qb.with_descripcion(self._o.descripcion)\n","sub_path":"db/schema/dbo/tipo_cuerno/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151999988","text":"# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl = \"http://news.baidu.com\"\ndata = requests.get(url)\ns = BeautifulSoup(data.text.encode(data.encoding), \"lxml\")\ntitle = s.select(\"#pane-news > div > ul > li.hdline0\")\nprint(title)\n\n\n","sub_path":"Python/Hello.py","file_name":"Hello.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233058994","text":"from __future__ import print_function\n\nfrom tqdm import tqdm\nfrom math import log10\n\nimport torch\nimport torch.backends.cudnn as cudnn\n\nfrom SRCNN.model import Net\n\n\nclass SRCNNTrainer(object):\n def __init__(self, args, train_loader, test_loader):\n super(SRCNNTrainer, self).__init__()\n self.CUDA = torch.cuda.is_available()\n self.device = torch.device('cuda' if self.CUDA else 'cpu')\n self.lr = args.lr\n self.epochs = args.epochs\n self.seed = args.seed\n self.upscale_factor = args.upscale_factor\n self.train_loader = train_loader\n self.test_loader = test_loader\n\n def build_model(self):\n self.model = Net(num_channels=3, \n base_filter=64, \n upscale_factor=self.upscale_factor).to(self.device)\n self.model.weight_init(mean=0.0, std=0.01)\n self.criterion = torch.nn.MSELoss()\n torch.manual_seed(self.seed)\n print(self.model)\n print('===========================================================')\n \n if self.CUDA:\n torch.cuda.manual_seed(self.seed)\n cudnn.benchmark = True\n self.criterion.cuda()\n\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)\n self.scheduler = torch.optim.lr_scheduler.MultiStepLR(self.optimizer, milestones=[50, 75, 100], gamma=0.5)\n\n def save_model(self):\n model_out_path = \"model_srcnn.pth\"\n torch.save(self.model, model_out_path)\n print(\"Checkpoint saved to {}\".format(model_out_path))\n\n def train(self):\n self.model.train()\n train_loss = 0\n for batch_num, (data, target) in tqdm(enumerate(self.train_loader)):\n data, target = data.to(self.device), target.to(self.device)\n self.optimizer.zero_grad()\n loss = self.criterion(self.model(data), target)\n train_loss += loss.item()\n loss.backward()\n self.optimizer.step()\n\n print(\" Average Loss: {:.4f}\".format(train_loss / len(self.train_loader)))\n\n def test(self):\n self.model.eval()\n avg_psnr = 0\n\n with torch.no_grad():\n for batch_num, (data, target) in enumerate(self.test_loader):\n data, target = data.to(self.device), target.to(self.device)\n mse = self.criterion(self.model(data), target)\n psnr = 10 * log10(1 / mse.item())\n avg_psnr += psnr\n\n print(\" Average PSNR: {:.4f} dB\".format(avg_psnr / len(self.test_loader)))\n\n def run(self):\n self.build_model()\n for epoch in range(1, self.epochs + 1):\n print(\"\\n===> Epoch {} starts:\".format(epoch))\n self.train()\n self.test()\n self.scheduler.step(epoch)\n if epoch == self.epochs:\n self.save_model()\n","sub_path":"SRCNN/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"287926994","text":"from time import sleep\r\n\r\nfrom pages.report.report_page import ReportPage\r\n\r\n\r\nclass ReportDataBlockPage(ReportPage):\r\n\r\n # 进入框架\r\n REPORT_FRAME = 'i,J_iframe'\r\n # 定位数据块\r\n DATA_BLOCK = 'x,.//*[@id=\\'_easyui_tree_3\\']/span[3]'\r\n # 定位操作区\r\n OPERATING_SPACE = 'x,.//*[@id=\\'layout_1\\']'\r\n # 定位数据块标题\r\n BLOCK_TITLE = 'x,.//*[@id=\\'layout_1\\']/div[1]/div[1]/div[1]/h5'\r\n # 定位输入标题名称\r\n BLOCK_NAME = 'x,.//*[@id=\\'Jlayout\\']/div[27]/div[2]/div[4]/input'\r\n # 定位输入标题确定\r\n BLOCK_SUBMIT = 'x,.//*[@id=\\'Jlayout\\']/div[27]/div[3]/a[1]/span/span'\r\n # 定位设置组件\r\n BLOCK_SETTING = 'x,.//*[@id=\\'layout_table\\']/tbody/tr/td/div[1]/div[1]/div[2]/button[2]'\r\n # 定位设置组件的数据\r\n BLOCK_DATA = 'x,.//*[@id=\\'box_menu\\']/div[2]'\r\n # 定位页面数据按钮\r\n DATA_BUTTON = 'x,.//*[@id=\\'mb4\\']/span/span[3]'\r\n # 定位选择立方体\r\n CHOOSE_CUBE = 'x,//*[@id=\"selectinfo\"]/div[2]/div'\r\n # 定位选择立方体模型\r\n CHOOSE_MODEL = 'x,.//*[@id=\\'datagrid-row-r1-2-3\\']/td[1]/div/input'\r\n # 定位确定按钮\r\n CUBE_SUBMIT = 'x,//*[@id=\"Jlayout\"]/div[25]/div[3]/a[1]/span/span[1]'\r\n # 定位立方体度量\r\n CUBE_METRIC = 'x,//*[@id=\"datasettree\"]/li/ul/li[2]/ul/li[4]/div'\r\n # 定位绑定度量区域\r\n METRIC_AREA = 'x,//*[@id=\"boxData\"]/div'\r\n # 定位设置组件的筛选\r\n BLOCK_SCREEN = 'x,.//*[@id=\\'box_menu\\']/div[3]'\r\n # 定位新增筛选条件按钮\r\n ADD_SCREEN = 'x,.//*[@id=\\'pdailog\\']/div/button'\r\n # 筛选字段\r\n FILTER_FIELD1 = 'x,.//*[@id=\\'filtercolumn\\']'\r\n FILTER_FIELD2 = 'x,//*[@id=\"filtercolumn\"]/option[10]'\r\n # 判断条件\r\n JUDGE_CONDITION1 = \"x,.//*[@id='filtertype']\"\r\n JUDGE_CONDITION2 = 'x,//*[@id=\"filtertype\"]/option[3]'\r\n # 筛选值\r\n SCREENING_VALUE = 'x,//*[@id=\"filtervalue\"]'\r\n # 筛选值类型\r\n VALUE_TYPE1 = 'x,//*[@id=\"valuetype\"]'\r\n VALUE_TYPE2 = 'x,//*[@id=\"valuetype\"]/option[2]'\r\n # 定位添加筛选条件的确定按钮\r\n SCREEN_SUBMIT = 'x,//*[@id=\"Jlayout\"]/div[29]/div[3]/a[1]/span/span[1]'\r\n # 定位筛选条件的确定按钮\r\n SCR_SUB = 'x,//*[@id=\"Jlayout\"]/div[26]/div[3]/a[1]/span/span[1]'\r\n # 定位设置组件的属性\r\n BLOCK_ATTRIBUTE = 'x,.//*[@id=\\'box_menu\\']/div[4]'\r\n # 定位属性的标题\r\n ATTRIBUTE_TITLE = 'x,//*[@id=\"datagrid-row-r2-2-0\"]/td[2]/div'\r\n # 定位属性的单位\r\n BLOCK_UNIT = \"x,.//*[@id='datagrid-row-r4-2-1']/td[2]\"\r\n # 定位属性的格式化\r\n BLOCK_FORMATTING = \"x,.//*[@id='datagrid-row-r4-2-2']/td[2]\"\r\n BLOCK_INPUT = \"x,.//*[@id='datagrid-row-r4-2-2']/td[2]/div/table/tbody/tr/td/span/input[1]\"\r\n # 定位属性的度量比例\r\n BLOCK_RATIO = \"x,.//*[@id='datagrid-row-r4-2-3']/td[2]\"\r\n BLOCK_ENTER = \"x,.//*[@id='datagrid-row-r4-2-3']/td[2]/div/table/tbody/tr/td/span/input[1]\"\r\n\r\n\r\n '''拖动新增数据块'''\r\n def add_data_block(self):\r\n '''\r\n 点击和拖动新增数据块组件到操作区\r\n :return: \r\n '''\r\n d = self.base_driver\r\n # 点击数据报表\r\n self.enter_report()\r\n sleep(2)\r\n # 进入框架和点击新建报表\r\n self.creat_report()\r\n sleep(2)\r\n # 点击和拖动数据块组件到目的地\r\n d.drag(self.BLOCK_DATA,self.OPERATING_SPACE)\r\n d.switch_to_default()\r\n sleep(2)\r\n\r\n '''双击标题更改名称'''\r\n def block_title(self):\r\n '''\r\n 双击更改数据块组件名称\r\n :return: \r\n '''\r\n d = self.base_driver\r\n d.switch_to_frame(self.REPORT_FRAME)\r\n # 双击数据块标题\r\n d.double_click(self.BLOCK_TITLE)\r\n sleep(2)\r\n # 输入新标题名称\r\n d.type(self.BLOCK_NAME,'点名')\r\n d.click(self.BLOCK_SUBMIT)\r\n d.switch_to_default()\r\n sleep(2)\r\n\r\n '''点击设置组件和设置数据'''\r\n def block_setting(self):\r\n d = self.base_driver\r\n d.switch_to_frame(self.IFRAME1)\r\n # 点击设置组件\r\n d.click(self.BLOCK_SETTING)\r\n # 点击数据\r\n d.click(self.BLOCK_DATA)\r\n sleep(2)\r\n # 点击页面数据按钮\r\n d.click(self.DATA_BUTTON)\r\n # 点击选择立方体\r\n d.click(self.CHOOSE_CUBE)\r\n sleep(1)\r\n # 点击选择立方体模型\r\n d.click(self.CHOOSE_MODEL)\r\n d.click(self.CUBE_SUBMIT)\r\n sleep(2)\r\n # 点击和拖动度量到目的地\r\n d.drap_and_drop(self.CUBE_METRIC,self.METRIC_AREA)\r\n d.switch_to_default()\r\n sleep(2)\r\n\r\n '''点击设置组件的筛选'''\r\n def block_screen(self):\r\n d = self.base_driver\r\n d.switch_to_frame(self.IFRAME1)\r\n # 点击设置组件\r\n d.click(self.BLOCK_SETTING)\r\n # 点击设置组件的筛选\r\n d.click(self.BLOCK_SCREEN)\r\n sleep(1)\r\n # 点击新增筛选条件按钮\r\n d.click(self.ADD_SCREEN)\r\n sleep(2)\r\n # 筛选字段\r\n d.click(self.FILTER_FIELD1)\r\n d.click(self.FILTER_FIELD2)\r\n # 判断条件\r\n d.click(self.JUDGE_CONDITION1)\r\n d.click(self.JUDGE_CONDITION2)\r\n # 筛选值\r\n d.type(self.SCREENING_VALUE,'85')\r\n # 筛选值类型\r\n d.click(self.VALUE_TYPE1)\r\n d.click(self.VALUE_TYPE2)\r\n # 添加筛选条件的确定按钮\r\n d.click(self.SCREEN_SUBMIT)\r\n # 筛选条件列表的确定按钮\r\n d.click(self.SCR_SUB)\r\n sleep(3)\r\n\r\n '''点击设置组件的属性'''\r\n def block_attribute(self):\r\n d = self.base_driver\r\n d.switch_to_frame(self.IFRAME1)\r\n # 点击设置组件\r\n d.click(self.BLOCK_SETTING)\r\n # 点击设置组件的属性\r\n d.click(self.BLOCK_ATTRIBUTE)\r\n sleep(2)\r\n # 标题\r\n d.type(self.ATTRIBUTE_TITLE,'上课')\r\n # 单位\r\n d.type(self.BLOCK_UNIT,'个')\r\n # 格式化\r\n d.click(self.BLOCK_FORMATTING)\r\n d.enter(self.BLOCK_INPUT,'整数')\r\n # 度量比例\r\n d.click(self.BLOCK_RATIO)\r\n d.enter(self.BLOCK_ENTER,'1')\r\n","sub_path":"02_RSBI/src/rsbi_auto/pages/report/report_date_block_page.py","file_name":"report_date_block_page.py","file_ext":"py","file_size_in_byte":6248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"399714400","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 12 15:35:26 2018\n\n@author: enizm\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndata = pd.read_csv('50_startups.csv')\n\nX = data.iloc[:, :-1].values\ny = data.iloc[:, -1].values\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelEncoderX = LabelEncoder()\nX[:, -1] = labelEncoderX.fit_transform(X[:, -1])\noneHotEncoderX = OneHotEncoder(categorical_features = [3])\nX = oneHotEncoderX.fit_transform(X).toarray()\nX = X[:, 1:];\n\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state = 0)\n\n\nfrom sklearn.linear_model import LinearRegression\n\nreg = LinearRegression()\nreg.fit(X_train, y_train)\n\ny_pred = reg.predict(X_test)\n\n# backward elimination \n\nX = np.append(arr = np.ones((X.shape[0],1)), values = X, axis = 1)\n\nimport statsmodels.formula.api as sm\nslvl = 0.05;\nX_hi = X\nregOLS = sm.OLS(endog = y, exog = X_hi).fit()\nregOLS.summary()\n\nX_hi = X[:, [0, 1, 3, 4, 5]]\nregOLS = sm.OLS(endog = y, exog = X_hi).fit()\nregOLS.summary()\n\nX_hi = X[:, [0, 3, 4, 5]]\nregOLS = sm.OLS(endog = y, exog = X_hi).fit()\nregOLS.summary()\n\nX_hi = X[:, [0, 3, 5]]\nregOLS = sm.OLS(endog = y, exog = X_hi).fit()\nregOLS.summary()\n\nX_hi = X[:, [0, 3]]\nregOLS = sm.OLS(endog = y, exog = X_hi).fit()\nregOLS.summary()\n\nX_train, X_test, y_train, y_test = train_test_split(X_hi,y, test_size = 0.2, random_state = 0)\nreg.fit(X_train, y_train)\n\ny_pred2 = reg.predict(X_test)\n\nplt.plot(y_test, c = 'blue')\nplt.plot(y_pred2, c = 'red')\nplt.plot(y_pred, c= 'green')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Machine Learning A-Z/Part 2 - Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression.py","file_name":"multiple_linear_regression.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541245555","text":"from __future__ import print_function\nfrom past.builtins import unicode\n# catalog parser must contain these functions and variables\nHEADERLEN = 1\nCOLSTART = 0\nVENDOR = 'western'\nVENDOR_PRINT_NAME = 'Western'\nHEADER_KEY = (2, 'U.P.C.')\n\n\ndef index_sheets(sheets, fileinfo):\n return [0]\n\n\ndef find_header(workbook):\n \"\"\"\n :param workbook: \n :return: \n \"\"\"\n # print workbook\n headerfound = False\n startrow = 1\n for idx, row in enumerate(workbook):\n if unicode(row[0]).lower() == 'item #':\n startrow = idx + 1\n return startrow\n\n\ndef file_info(filename):\n \"\"\"\n Western Beverages Filenames\n 'Western April 2018 Off Premise.xlsx'\n\n :param filename: \n :return: dict\n \"\"\"\n\n year = ''\n monthnum = ''\n month = ''\n catalog = ''\n catalogid = ''\n vendor = ''\n\n output = dict(\n year=year,\n monthnum=monthnum,\n month=month,\n catalog=catalog,\n catalogid=catalogid,\n vendor=VENDOR,\n vendor_print_name=VENDOR_PRINT_NAME\n )\n return output\n\n\ndef reformat(catalog_data):\n \"\"\"\n return a list containing the formatted rows for your worksheet including headers\n :param catalog_data: \n :return: \n \"\"\"\n\n formatted = []\n return formatted\n\n\nclass Meta(object):\n def __init__(self, parent=None):\n self.year = ''\n self.month = ''\n","sub_path":"catalogboss/catalogs/western.py","file_name":"western.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"226566553","text":"\n\nfrom xai.brain.wordbase.verbs._maltreat import _MALTREAT\n\n#calss header\nclass _MALTREATING(_MALTREAT, ):\n\tdef __init__(self,): \n\t\t_MALTREAT.__init__(self)\n\t\tself.name = \"MALTREATING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"maltreat\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_maltreating.py","file_name":"_maltreating.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"23705193","text":"\"\"\"ARFCN Correlator.\"\"\"\n\nimport alert_manager\nimport os\nimport sqlite3\nfrom utility import Utility\n\n\nclass ArfcnCorrelator(object):\n \"\"\"The ArfcnCorrelator compares ARFCN metadata against feeds and threshold.\n\n The feed data is put in place by the FeedManager class, prior to\n instantiating the ArfcnCorrelator.\n \"\"\"\n\n def __init__(self, feed_dir, whitelist, power_threshold, device_id):\n \"\"\"Initializing the ArfcnCorrelator.\n\n Args:\n arfcn_db (str): Full path to the ARFCN database.\n whitelist (list): This is a list of ARFCNs that should be\n considered trustworthy enough to skip feed comparison.\n This does not override comparison against threshold.\n power_threshold (str): No matter the type, it will be coerced,\n if possible, to float. This is the value that Kalibrate-\n reported channel power will be compared against to make a\n determination on whether or not to fire an alarm.\n \"\"\"\n self.alerts = alert_manager.AlertManager(device_id)\n self.geo_state = {\"type\": \"Point\", \"coordinates\": [0, 0]}\n self.feed_dir = feed_dir\n self.arfcn_db = os.path.join(feed_dir, \"arfcn.db\")\n self.power_threshold = float(power_threshold)\n self.observed_arfcn = whitelist\n self.arfcn_threshold = []\n self.arfcn_range = []\n return\n\n def correlate(self, scan_bolus):\n \"\"\"Entrypoint for correlation, wraps individual checks.\n\n Args:\n scan_bolus (tuple): Position 0 contains a string defining scan\n type. If it's type 'gps', the geo_state instance variable\n will be updated with Position 1's contents. If the scan type\n is 'kal_channel', we perform feed and threshold comparison.\n any other scan type will be compared against the feed only.\n\n Returns:\n list: Returns a list of alerts. If no alerts are generated, an\n empty list is returned.\n \"\"\"\n retval = []\n scan_type = scan_bolus[0]\n scan = scan_bolus[1]\n if scan_type == \"gps\":\n self.geo_state = scan[\"location\"]\n arfcn = ArfcnCorrelator.arfcn_from_scan(scan_type, scan)\n if scan_type == \"kal_channel\":\n scan_bolus[1][\"location\"] = self.geo_state\n retval.append(scan_bolus)\n if self.arfcn_over_threshold(scan[\"power\"]):\n message = \"ARFCN %s over threshold at %s / %s. Observed: %s\" % ( # NOQA\n scan[\"channel\"],\n scan[\"site_name\"],\n scan[\"sensor_name\"],\n scan[\"power\"])\n alert = self.alerts.build_alert(200, message, self.geo_state)\n alert[1][\"site_name\"] = scan[\"site_name\"]\n alert[1][\"sensor_name\"] = scan[\"sensor_name\"]\n alert[1][\"sensor_id\"] = scan[\"sensor_id\"]\n retval.append(alert)\n self.manage_arfcn_lists(\"in\", arfcn, \"threshold\")\n else:\n self.manage_arfcn_lists(\"out\", arfcn, \"threshold\")\n feed_alerts = self.compare_arfcn_to_feed(arfcn, scan[\"site_name\"],\n scan[\"sensor_name\"])\n for feed_alert in feed_alerts:\n feed_alert[1][\"site_name\"] = scan[\"site_name\"]\n feed_alert[1][\"sensor_name\"] = scan[\"sensor_name\"]\n feed_alert[1][\"sensor_id\"] = scan[\"sensor_id\"]\n retval.append(feed_alert)\n self.observed_arfcn.append(arfcn)\n return retval\n\n def manage_arfcn_lists(self, direction, arfcn, aspect):\n \"\"\"Manage the instance variable lists of ARFCNs.\n\n This is necessary to maintain an accurate state over time, and reduce\n unnecessary noise.\n\n Args:\n direction (str): Only will take action if this is \"in\" or \"out\"\n arfcn (str): This is the ARFCN that will be moved in or our of\n the list\n aspect (str): This is used to match the ARFCN with the list it\n should be moved in or out of. This should be either\n \"threshold\" or \"not_in_range\".\n\n \"\"\"\n reference = {\"threshold\": self.arfcn_threshold,\n \"not_in_range\": self.arfcn_range}\n if direction == \"in\":\n if reference[aspect].count(arfcn) > 0:\n pass\n else:\n reference[aspect].append(arfcn)\n elif direction == \"out\":\n if reference[aspect].count(arfcn) == 0:\n pass\n else:\n while arfcn in reference[aspect]:\n reference[aspect].remove(arfcn)\n return\n\n def arfcn_over_threshold(self, arfcn_power):\n \"\"\"Compare the ARFCN power against the thresholdset on instantiation.\n\n Args:\n arfcn_power (float): If this isn't a float already, it will be\n coerced to float.\n\n Returns:\n bool: True if arfcn_power is over threshold, False if not.\n \"\"\"\n if float(arfcn_power) > self.power_threshold:\n return True\n else:\n return False\n\n def compare_arfcn_to_feed(self, arfcn, site_name, sensor_name):\n \"\"\"Wrap other functions that dig into the FCC license DB.\n\n This relies on the observed_arfcn instance variable for caching, to\n skip DB comparison, that way we (probably) won't end up with a\n forever-increasing queue size.\n\n Args:\n arfcn (str): This is the text representation of the ARFCN we want\n to compare against the FCC license database.\n\n Returns:\n list: You get back a list of alerts as tuples, where position 0 is\n 'sitch_alert' and position 1 is the actual alert.\n \"\"\"\n results = []\n # If we can't compare geo, have ARFCN 0 or already been found in feed:\n if (str(arfcn) in [\"0\", None] or\n arfcn in self.observed_arfcn or\n self.geo_state[\"coordinates\"] == [0, 0]):\n return results\n else:\n msg = \"ArfcnCorrelator: Cache miss on ARFCN %s\" % str(arfcn)\n print(msg)\n results.extend(self.feed_alert_generator(arfcn, site_name,\n sensor_name))\n return results\n\n def feed_alert_generator(self, arfcn, site_name, sensor_name):\n \"\"\"Wrap the yield_arfcn_from_feed function, and generates alerts.\n\n Args:\n arfcn (str): This is the string representation of the ARFCN to be\n correlated.\n\n Returns:\n list: This returns a list of alert tuples.\n \"\"\"\n results = []\n if arfcn is None:\n return results\n if not self.match_arfcn_against_feed(arfcn, self.geo_state):\n msg = \"Unable to locate a license for ARFCN %s at %s / %s\" % (\n str(arfcn), site_name, sensor_name)\n self.manage_arfcn_lists(\"in\", arfcn, \"not_in_range\")\n alert = self.alerts.build_alert(400, msg, self.geo_state)\n results.append(alert)\n return results\n\n @classmethod\n def arfcn_from_scan(cls, scan_type, scan_doc):\n \"\"\"Pull the ARFCN from different scan types.\n\n Args:\n scan_type (str): \"kal_channel\", \"gsm_modem_channel\", or \"gps\".\n scan_doc (dict): Scan document\n\n Returns:\n str: ARFCN from scan, or None if scan is unrecognized or\n unsupported.\n \"\"\"\n if scan_type == \"kal_channel\":\n return scan_doc[\"arfcn_int\"]\n elif scan_type == \"gsm_modem_channel\":\n return scan_doc[\"arfcn\"]\n elif scan_type == \"cell\":\n return None\n elif scan_type == \"scan\":\n return None\n elif scan_type == \"gps\":\n return None\n else:\n print(\"ArfcnCorrelator: Unknown scan type: %s\" % str(scan_type))\n return None\n\n def match_arfcn_against_feed(self, arfcn, state_gps):\n \"\"\"Get a match for the ARFCN within range of the sensor.\n\n Args:\n arfcn (str): Absolute Radio Frequency Channel Number\n\n Returns:\n bool: True if there is an ARFCN in range, False if not.\n \"\"\"\n result = False\n conn = sqlite3.connect(self.arfcn_db)\n c = conn.cursor()\n clean_arfcn = str(arfcn)\n c.execute(\"SELECT arfcn, carrier, lon, lat FROM arfcn WHERE arfcn=?\", (clean_arfcn, )) # NOQA\n for result in c.fetchall():\n test_set = {\"arfcn\": result[0], \"carrier\": result[1],\n \"lon\": result[2], \"lat\": result[3]}\n if self.is_in_range(test_set, state_gps):\n result = True\n conn.close()\n break\n return result\n\n @classmethod\n def is_in_range(cls, item_gps, state_gps):\n \"\"\"Return True if items are within 40km.\"\"\"\n state_gps_lat = state_gps[\"coordinates\"][1]\n state_gps_lon = state_gps[\"coordinates\"][0]\n max_range = 40000 # 40km\n state_lon = state_gps_lon\n state_lat = state_gps_lat\n item_lon = item_gps[\"lon\"]\n item_lat = item_gps[\"lat\"]\n distance = Utility.calculate_distance(state_lon, state_lat,\n item_lon, item_lat)\n if distance > max_range:\n return False\n else:\n return True\n","sub_path":"sitch/sitchlib/arfcn_correlator.py","file_name":"arfcn_correlator.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"180180194","text":"'''\nTitle : Finding the percentage\nSubdomain : Data Types\nDomain : Python\nAuthor : Ahmedur Rahman Shovon\nCreated : 15 July 2016\nProblem : https://www.hackerrank.com/challenges/finding-the-percentage/problem\n'''\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nif __name__ == '__main__':\n n = int(input())\n student_marks = {}\n for _ in range(n):\n name, *line = input().split()\n scores = list(map(float, line))\n student_marks[name] = scores\n query_name = input()\nm=len(student_marks[query_name])\nsum1=00.00\nfor i in range(0,m):\n sum1=student_marks[query_name][i]+sum1\nprint(\"{:.2f}\".format(sum1/m));\n\n","sub_path":"BasicDataTypes/Findingthepercentage.py","file_name":"Findingthepercentage.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"254637931","text":"import pytest\n\nfrom os.path import abspath, dirname, join\nimport os\n\nfrom flask import Flask\nfrom flask_bcrypt import Bcrypt\n\nfrom places.models import db, bcrypt\nfrom places.endpoints import app as bp\nfrom places import create_app\n\n_cwd = dirname(abspath(__file__))\n\n@pytest.fixture\ndef app():\n app = create_app()\n app.config['TESTING'] = True\n app.config['SECRET_KEY'] = 'secret_key'\n app.config['JWT_SECRET_KEY'] = 'secret_key'\n app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('CLICKBUS_TEST_DB_URI', None)\n app.config['SQLALCHEMY_ECHO'] = False\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n app.config['BCRYPT_LOG_ROUNDS'] = 12\n app.config['DEBUG'] = True\n app.config['ENV'] = 'development'\n app.config['JSON_AS_ASCII'] = False\n\n app.register_blueprint(bp)\n\n with app.app_context():\n db.create_all()\n yield app\n db.session.remove()\n db.drop_all()","sub_path":"testes/backend-developer/solution/places_api/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569420475","text":"import tensorflow as tf\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.training.optimizer import Optimizer\n\nSMALL_NUMBER = 1e-15\nDEFAULT_UNPUTS_SUFFIX = \"input\"\n\n\nclass _BaseOptimizer(Optimizer):\n def __init__(self, *args, **kwargs):\n super(_BaseOptimizer, self).__init__(*args, **kwargs)\n self.inputs = None\n self.t = tf.train.get_or_create_global_step()\n\n def create_const_init_slot(self, v, name, value=0):\n initializer = tf.initializers.constant(value, dtype=v.dtype)\n\n return self._get_or_make_slot_with_initializer(\n v, initializer, v.shape, v.dtype, name, self._name)\n\n def create_normal_init_slot(self, v, name, m=0, std=1):\n initializer = tf.initializers.random_normal(mean=m, stddev=std, dtype=v.dtype)\n\n return self._get_or_make_slot_with_initializer(\n v, initializer, v.shape, v.dtype, name, self._name)\n\n\nclass _FeatureBasedOptimizer(_BaseOptimizer):\n def __init__(self,\n use_locking=False,\n name=None,\n epsilon=1.0,\n epsilon_scaled=False,\n s0=0\n ):\n super(_FeatureBasedOptimizer, self).__init__(use_locking=use_locking, name=name)\n self.epsilon = float(epsilon)\n self.epsilon_scaled = epsilon_scaled\n self.s0 = s0\n\n def setup_epsilon_slot(self, var, name):\n if not self.epsilon_scaled:\n return self.create_const_init_slot(var, name, 1.0)\n if len(var.shape) == 1:\n value = (1 / var.get_shape().as_list()[0]) ** 0.5\n return self.create_const_init_slot(var, name, value)\n else:\n initializer = tf.initializers.glorot_normal(dtype=var.dtype)\n\n return self._get_or_make_slot_with_initializer(\n var, initializer, var.shape, var.dtype, name, self._name)\n\n def _process_inputs(self, var):\n x = self.inputs[var]\n if x.shape == []:\n max_x = tf.abs(x)\n x2 = x ** 2\n else:\n x = tf.expand_dims(x, len(x.shape))\n x2 = tf.reduce_mean(x ** 2, 0)\n max_x = tf.reduce_max(tf.abs(x), 0)\n x2 = tf.broadcast_to(x2, var.get_shape())\n return x, x2, max_x\n\n def _retrieve_inputs(self, var_list):\n\n self.inputs = {}\n operations = {op.name: op for op in tf.get_default_graph().get_operations()}\n for var in var_list:\n op_name = var.op.name + \"/{}\".format(\"input\")\n inputs = operations.get(op_name, None)\n if inputs is None:\n inputs = tf.constant(1.0, name=op_name)\n # TODO does it work in more general cases?\n if isinstance(inputs, tf.Operation):\n inputs = inputs.outputs[0]\n self.inputs[var] = inputs\n\n # def compute_gradients(self, loss, var_list=None,\n # gate_gradients=Optimizer.GATE_OP,\n # aggregation_method=None,\n # colocate_gradients_with_ops=False,\n # grad_loss=None):\n #\n # # TODO perhaps retrieve lost copied code from here some day\n # if var_list is None:\n # var_list = (\n # variables.trainable_variables() +\n # ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))\n # else:\n # var_list = nest.flatten(var_list)\n #\n # # pylint: disable=protected-access\n # var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS)\n # # pylint: enable=protected-access\n # if not var_list:\n # raise ValueError(\"No variables to optimize.\")\n #\n # if self.inputs is None:\n # self._retrieve_inputs(var_list)\n # self._create_slots(var_list)\n # preapply_ops = [self._preapply_dense(var) for var in var_list]\n #\n # t_op = tf.assign_add(self.t, 1)\n # preapply_ops.append(t_op)\n #\n # with tf.control_dependencies(preapply_ops):\n # return super(_FeatureBasedOptimizer, self).compute_gradients(loss, var_list,\n # gate_gradients,\n # aggregation_method,\n # colocate_gradients_with_ops,\n # grad_loss)\n @property\n def preapply_ops(self):\n var_list = (\n variables.trainable_variables() +\n ops.get_collection(ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))\n var_list += ops.get_collection(ops.GraphKeys._STREAMING_MODEL_PORTS)\n\n if self.inputs is None:\n self._retrieve_inputs(var_list)\n self._create_slots(var_list)\n\n t_op = tf.assign_add(self.t, 1)\n with tf.control_dependencies([t_op]):\n preapply_ops = [self._preapply_dense(var) for var in var_list]\n\n return preapply_ops\n\n def apply_gradients(self, grads_and_vars, global_step=None, name=None):\n unzipped_grads_and_vars = []\n for g, v in grads_and_vars:\n unzipped_grads_and_vars += [g, v]\n with tf.control_dependencies(unzipped_grads_and_vars):\n return super(_FeatureBasedOptimizer, self).apply_gradients(grads_and_vars, global_step, name)\n\n\nclass ScinolOptimizer(_FeatureBasedOptimizer):\n \"\"\"Optimizer that implements the algorithm.\n\n See this [paper](TODO)\n \"\"\"\n\n def __init__(self,\n name=\"ScInOl\",\n beta=None,\n *args, **kwargs):\n super(ScinolOptimizer, self).__init__(name=name, *args, **kwargs)\n self.beta = beta\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self.create_const_init_slot(v, \"grads_sum\", 0)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self._get_or_make_slot(v, v, \"initial_value\", self._name)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"beta\")\n self.setup_epsilon_slot(v, \"epsilon\")\n\n def _preapply_dense(self, var):\n _, x2, max_x = self._process_inputs(var)\n\n beta = self.get_slot(var, \"beta\")\n G = self.get_slot(var, \"grads_sum\")\n S2 = self.get_slot(var, \"squared_grads_sum\")\n M = self.get_slot(var, \"max\")\n var0 = self.get_slot(var, \"initial_value\")\n epsilon = self.get_slot(var, \"epsilon\")\n t = tf.to_float(self.t)\n\n new_M = tf.assign(M, tf.maximum(M, max_x))\n if self.beta is not None:\n beta = tf.constant(float(self.beta))\n else:\n beta = tf.assign(beta, tf.minimum(beta, epsilon*(S2 + new_M ** 2) / (x2 * t)))\n\n theta = G / (S2 + new_M ** 2) ** 0.5\n new_var = (beta * tf.sign(theta)) / (2 * (S2 + new_M ** 2) ** 0.5) * (tf.exp(tf.abs(theta) / 2) - 1)\n return tf.assign(var, new_var- var0)\n\n def _apply_dense(self, grad, var):\n G = self.get_slot(var, \"grads_sum\")\n S2 = self.get_slot(var, \"squared_grads_sum\")\n\n new_G = tf.assign_add(G, -grad)\n new_S2 = tf.assign_add(S2, (grad) ** 2)\n\n return new_G, new_S2\n\n\nclass Scinol2Optimizer(_FeatureBasedOptimizer):\n \"\"\"Optimizer that implements the algorithm.\n\n See this [paper](TODO)\n \"\"\"\n\n def __init__(self,\n name=\"ScInOl2\",\n *args, **kwargs\n ):\n super(Scinol2Optimizer, self).__init__(name=name, *args, **kwargs)\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self.create_const_init_slot(v, \"grads_sum\", 0)\n self._get_or_make_slot(v, v, \"initial_value\", self._name)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"eta\")\n\n def _preapply_dense(self, var):\n x, _, max_x = self._process_inputs(var)\n eta = self.get_slot(var, \"eta\")\n G = self.get_slot(var, \"grads_sum\")\n S2 = self.get_slot(var, \"squared_grads_sum\")\n M = self.get_slot(var, \"max\")\n var0 = self.get_slot(var, \"initial_value\")\n\n new_M = tf.assign(M, tf.maximum(M, max_x))\n\n theta = G / (S2 + new_M ** 2) ** 0.5\n\n var_delta = tf.sign(theta) * tf.minimum(tf.abs(theta), 1.0) / (2 * (S2 + new_M ** 2) ** 0.5) * eta\n return tf.assign(var, var0 + var_delta)\n\n def _apply_dense(self, grad, var):\n x, _, max_x = self._process_inputs(var)\n G = self.get_slot(var, \"grads_sum\")\n S2 = self.get_slot(var, \"squared_grads_sum\")\n eta = self.get_slot(var, \"eta\")\n var0 = self.get_slot(var, \"initial_value\")\n\n new_G = tf.assign_add(G, -grad)\n new_S2 = tf.assign_add(S2, (grad) ** 2)\n new_eta = tf.assign_add(eta, -grad * (var - var0))\n\n # import sys\n # if \"weights\" in var.name:\n # n = \"W: \"\n # else:\n # n = \"B:\"\n # print_op = tf.print(\n # n, \"\\t\",\n # tf.reduce_sum(var ** 2),\n # \"g:\", tf.reduce_sum(grad),\n # \"x:\", tf.reduce_sum(x),\n # \"G:\", tf.reduce_sum(new_G),\n # \"S2:\", tf.reduce_sum(new_S2),\n # \"eta:\", tf.reduce_sum(new_eta),\n # summarize=-1, output_stream=sys.stdout)\n # with ops.control_dependencies([print_op]):\n return tf.group(new_G, new_S2, new_eta)\n\n\nclass ScinolAOptimizer(ScinolOptimizer):\n \"\"\"Inicjalizacja zgodnie z dokumentem new_alg.tex, tzn. S_0 np. rzędu 100 i potem początkowy skumulowany gradient G_i ~ N(0, S_0/d), gdzie S_0/d jest *wariancją*, a d = (n_in + n_out) / 2. Wartość początkową eta ustawiamy na 1.\n Hacky: this assumes that weights are initialized with glorot so it initializes G_i with s_0*V0 rather than ~ N(0, S_0/d) (basically the same result)\n \"\"\"\n\n def __init__(self, s0=100, name=\"ScInOlA\", *args, **kwargs):\n super(ScinolAOptimizer, self).__init__(s0=s0, name=name, *args, **kwargs)\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self._get_or_make_slot(v, (self.s0) ** 0.5 * v, \"grads_sum\", self._name)\n self.create_const_init_slot(v, \"initial_value\", 0)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"beta\")\n self.setup_epsilon_slot(v, \"epsilon\")\n\n\nclass Scinol2AOptimizer(Scinol2Optimizer):\n \"\"\"Inicjalizacja zgodnie z dokumentem new_alg.tex, tzn. S_0 np. rzędu 100 i potem początkowy skumulowany gradient G_i ~ N(0, S_0/d), gdzie S_0/d jest *wariancją*, a d = (n_in + n_out) / 2. Wartość początkową eta ustawiamy na 1.\n\n Hacky: this assumes that weights are initialized with glorot so it initializes G_i with s_0*V0 rather than ~ N(0, S_0/d) (basically the same result)\n \"\"\"\n\n def __init__(self, s0=100, name=\"ScInOl2A\", *args, **kwargs):\n super(Scinol2AOptimizer, self).__init__(s0=s0, name=name, *args, **kwargs)\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self._get_or_make_slot(v, (self.s0) ** 0.5 * v, \"grads_sum\", self._name)\n self.create_const_init_slot(v, \"initial_value\", 0)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"eta\")\n\n\nclass ScinolBOptimizer(ScinolOptimizer):\n \"\"\"Inicjalizacja podobnie jak w new_alg.tex, ale teraz S_0 = 1, G_i ~ N(0, 1),\na cała skala siedzi w zmiennej początkowej epsilon. Tzn. trzeba dobrać epsilon = sqrt(2/(n_in + n_out)).\n\n\n Hacky: this assumes that weights are initialized with glorot so it initializes eta with V0 rather than ~ N(0, 1/d) (basically the same result)\n \"\"\"\n\n def __init__(self, s0=1, name=\"ScInOlB\", *args, **kwargs):\n super(ScinolBOptimizer, self).__init__(s0=s0, epsilon_scaled=True, name=name, *args, **kwargs)\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self.create_normal_init_slot(v, \"grads_sum\")\n self.create_const_init_slot(v, \"initial_value\", 0)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"beta\")\n self.setup_epsilon_slot(v, \"epsilon\")\n\n\nclass Scinol2BOptimizer(Scinol2Optimizer):\n \"\"\"Inicjalizacja podobnie jak w new_alg.tex, ale teraz S_0 = 1, G_i ~ N(0, 1), a cała skala siedzi w zmiennej początkowej epsilon. Tzn. trzeba dobrać epsilon = sqrt(2/(n_in + n_out)).\n Hacky: this assumes that weights are initialized with glorot so it initializes eta with V0 rather than ~ N(0, 1/d) (basically the same result)\n\n \"\"\"\n\n def __init__(self, s0=1, name=\"ScInOl2B\", *args, **kwargs):\n super(Scinol2Optimizer, self).__init__(s0=s0, name=name, epsilon_scaled=True, *args, **kwargs)\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self.create_normal_init_slot(v, \"grads_sum\")\n self.create_const_init_slot(v, \"initial_value\", 0)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", SMALL_NUMBER)\n self.setup_epsilon_slot(v, \"eta\")\n\n\nclass Scinol2DLOptimizer(_BaseOptimizer):\n def __init__(self,\n epsilon=1.0,\n s0=0,\n use_locking=False,\n name=\"ScInOL2DL\",\n max_start=SMALL_NUMBER,\n epsilon_scaled=False, ):\n super(Scinol2DLOptimizer, self).__init__(use_locking=use_locking, name=name)\n self.epsilon = float(epsilon)\n self.s0 = s0\n self.max_start = max_start\n self.epsilon_scaled = epsilon_scaled\n\n def _create_slots(self, var_list):\n for v in var_list:\n with ops.colocate_with(v):\n self.create_const_init_slot(v, \"grads_sum\", 0)\n self._get_or_make_slot(v, v, \"initial_value\", self._name)\n self.create_const_init_slot(v, \"squared_grads_sum\", self.s0)\n self.create_const_init_slot(v, \"max\", self.max_start)\n\n if not self.epsilon_scaled:\n self.create_const_init_slot(v, \"eta\", self.epsilon)\n else:\n if len(v.shape) == 1:\n value = (1 / v.get_shape().as_list()[0]) ** 0.5\n self.create_const_init_slot(v, \"eta\", value)\n else:\n initializer = tf.initializers.glorot_normal(dtype=v.dtype)\n self._get_or_make_slot_with_initializer(\n v, initializer, v.shape, v.dtype, \"eta\", self._name)\n\n def _apply_dense(self, grad, var):\n eta = self.get_slot(var, \"eta\")\n G = self.get_slot(var, \"grads_sum\")\n S2 = self.get_slot(var, \"squared_grads_sum\")\n M = self.get_slot(var, \"max\")\n var0 = self.get_slot(var, \"initial_value\")\n\n M = tf.assign(M, tf.maximum(M, tf.abs(grad)))\n\n theta = G / (S2 + M ** 2) ** 0.5\n var_delta = tf.sign(theta) * tf.minimum(tf.abs(theta), 1.0) / (2 * (S2 + M ** 2) ** 0.5) * eta\n\n new_G = tf.assign_add(G, -grad)\n new_S2 = tf.assign_add(S2, (grad) ** 2)\n new_eta = tf.maximum(0.5 * eta, eta - grad * var_delta)\n new_eta = tf.assign(eta, new_eta)\n\n new_var = tf.assign(var, var0 + var_delta)\n\n return tf.group(new_G, new_S2, new_eta, new_var)\n","sub_path":"scinol/_scinol.py","file_name":"_scinol.py","file_ext":"py","file_size_in_byte":16223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"1813274","text":"import importlib\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom heads import FCNHead\n\n\nclass ModelBuilder(nn.Module):\n def __init__(self, net_config, aux_config=None):\n super(ModelBuilder, self).__init__()\n\n num_classes = net_config['num_classes']\n out_planes = int(net_config['out_planes'])\n self.use_aux = aux_config is not None\n\n if self.use_aux:\n in_planes = int(aux_config['in_planes'])\n out_planes = int(aux_config['out_planes'])\n self.aux = FCNHead(in_planes, out_planes)\n self.aux_clsf = nn.Conv2d(out_planes, num_classes)\n\n self.encoder = self._build_module(net_config, 'encoder')\n self.seg_head = self._build_module(net_config, 'seg_head')\n self.decoder = self._build_module(net_config, 'decoder')\n assert self.encoder is not None, 'There must be an encoder!'\n\n if out_planes >= 256:\n self.clsf = nn.Sequential(\n nn.Dropout2d(0.1),\n nn.Conv2d(out_planes, num_classes, 1))\n else:\n self.clsf = nn.Conv2d(out_planes, num_classes)\n\n\n def _build_module(self, net_config, key):\n cls_config = net_config.get(key, None)\n if cls_config is None:\n return None\n\n cls_type = cls_config['type']\n mod_name, cls_name = cls_type.rsplit('.', 1)\n mod = importlib.import_module(mod_name)\n cls = getattr(mod, cls_name)\n return cls(**cls_config.get('args', dict()))\n\n def forward(self, x):\n h, w = x.size()[-2:]\n xs = self.encoder(x)\n\n if self.seg_head is not None:\n xs[-1] = self.seg_head(xs[-1])\n\n if self.decoder is not None:\n x = self.decoder(xs)\n else:\n x = xs[-1]\n\n pred = self.clsf(x)\n pred = F.interpolate(pred, size=(h, w), mode='bilinear', \n align_corners=True)\n\n if not self.use_aux:\n return [pred, None]\n\n aux = self.aux(xs[-2])\n aux = self.aux_clsf(aux)\n aux = F.interpolate(aux, size=(h, w), mode='bilinear', \n align_corners=True)\n\n return [pred, aux]\n\n\nif __name__ == '__main__':\n net_config = {\n 'num_classes': 19,\n 'out_planes': 512,\n 'encoder': {\n 'type': 'resnet.resnet50',\n },\n 'seg_head': {\n 'type': 'heads.ASPP',\n 'args': {\n 'in_planes': 2048,\n }\n },\n }\n model = ModelBuilder(net_config)\n print(model)\n input = torch.Tensor(2, 3, 513, 513)\n outputs = model(input)\n for output in outputs:\n if output is not None:\n print(output.size())\n\n","sub_path":"libs/networks/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"387401602","text":"import unittest\n\nfrom nltk.grammar import (FeatStructNonterminal, FeatureGrammar)\nfrom nltk.parse.earleychart import FeatureEarleyChartParser\nfrom nltk.data import load as data_load\n\nfrom literalpainting import (num_production,\n RE_INT,\n grammar,\n preprocess\n )\n\nclass GrammarMixin:\n def parse(self, command):\n tokens = preprocess(command)\n ints = set(filter(RE_INT.match, tokens))\n lproductions = list(grammar.productions())\n # Add a production for every integer\n lproductions.extend(map(num_production, ints))\n\n # Make a local copy of the grammar with extra productions\n lgrammar = FeatureGrammar(type(self).start, lproductions)\n\n # Load grammar into a parser\n parser = FeatureEarleyChartParser(lgrammar, trace=0)\n return parser.nbest_parse(tokens)\n\nclass ShapeTestCase(unittest.TestCase, GrammarMixin):\n start = FeatStructNonterminal('NP')\n\n def test_circle_at(self):\n test = 'a circle at 200 200 with a radius of 20 pixels'\n self.assertTrue(self.parse(test))\n\n def test_and(self):\n test = 'a line from 100 100 to 200 200 and a rectangle from 100 100 to 200 200'\n self.assertTrue(self.parse(test))\n \nclass NPTestCase(unittest.TestCase, GrammarMixin):\n start = FeatStructNonterminal('NP')\n def test_location(self):\n test = '200 200'\n self.assertTrue(self.parse(test))\n\n def test_length(self):\n test = '200 pixels'\n self.assertTrue(self.parse(test))\n\n\nclass PPTestCase(unittest.TestCase, GrammarMixin):\n start = FeatStructNonterminal('PP')\n\n def test_at(self):\n test = 'at 200 200'\n self.assertTrue(self.parse(test))\n\n def test_with(self):\n test = 'with a radius of 20 pixels'\n self.assertTrue(self.parse(test))\n\n def test_of(self):\n test = 'of 20 pixels'\n self.assertTrue(self.parse(test))\n\nclass DeclSentenceTestCase(unittest.TestCase, GrammarMixin):\n start = FeatStructNonterminal('S')\n def test_want(self):\n test = 'I want a line from 1 1 to 2 2'\n self.assertTrue(self.parse(test)) \n\nclass ImpSentenceTestCase(unittest.TestCase, GrammarMixin):\n start = FeatStructNonterminal('S')\n def test_give(self):\n test = 'Give me a line from 1 1 to 2 2'\n self.assertTrue(self.parse(test)) \n\n def test_draw(self):\n test = 'Draw me a line from 1 1 to 2 2'\n self.assertTrue(self.parse(test)) \n","sub_path":"literalpainting/tests/test_grammar.py","file_name":"test_grammar.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"574705110","text":"\nfrom tkinter import *\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nfrom kensuke import *\n\nclass Application(ttk.Frame):\n def __init__(self, master=None, k=None):\n super().__init__(master)\n self.master = master\n self.kensuke = k\n self.grid()\n self[\"relief\"] = \"raised\"\n self[\"borderwidth\"] = 3\n self.create_widgets()\n self.draw_canvases()\n \n def create_viewports(self):\n # Default values\n WIDTH = 600\n HEIGHT = 400\n BG_COLOR = \"#F0F0F0\"\n RELIEF = \"sunken\"\n BW = 3\n \n \n # Canvas creation for images (styling placed upon creation)\n self.origin_view = Canvas(self, width=WIDTH, height=HEIGHT, background=BG_COLOR,\n relief=RELIEF, borderwidth=BW)\n self.origin_view.grid(row=0, column=0, columnspan=4, padx=20, pady=20, sticky=N+S+E+W)\n self.origin_view.grid_propagate(0)\n\n self.distort_view = Canvas(self, width=WIDTH, height=HEIGHT, background=BG_COLOR,\n relief=RELIEF, borderwidth=BW)\n self.distort_view.grid(row=0, column=4, columnspan=4, padx=\"0 20\", pady=20, sticky=N+S+E+W)\n self.distort_view.grid_propagate(0)\n \n def create_controls(self):\n # Default values (x position, y positon, width, and height)\n MAX_X = 100\n MAX_Y = 100\n MAX_W = 50\n MAX_H = 50\n \n MAX_P = 50 # (Padding, number of rows, number of columns)\n MAX_R = 30\n MAX_C = 30\n\n SCALE_LENGTH = 160 # Widget constants\n COMBO_WIDTH = 3\n \n # Sliders for the top left position of cell array (x, y) w/ labels\n self.x = ttk.Scale(self, orient=\"horizontal\", style=\"Horizontal.TScale\", length=SCALE_LENGTH,\n from_=0, to=MAX_X)\n self.y = ttk.Scale(self, orient=\"horizontal\", style=\"Horizontal.TScale\", length=SCALE_LENGTH,\n from_=0, to=MAX_Y)\n\n self.x_label = ttk.Label(self, text=\"X Coordinate: \")\n self.y_label = ttk.Label(self, text=\"Y Coordinate: \")\n\n self.x_label.grid(row=1, column=0, columnspan=1, padx=\"20 0\", sticky=N+S+W)\n self.x.grid(row=1, column=0, columnspan=2, padx=\"10 20\", sticky=N+S+E)\n self.y_label.grid(row=1, column=2, columnspan=1, padx=\"0 0\", sticky=N+S+W)\n self.y.grid(row=1, column=2, columnspan=2, padx=\"10 20\", sticky=N+S+E)\n \n \n # Cell size sliders (width, height)\n self.width = ttk.Scale(self, orient=\"horizontal\", style=\"Horizontal.TScale\", length=SCALE_LENGTH,\n from_=1, to=MAX_W)\n self.height = ttk.Scale(self, orient=\"horizontal\", style=\"Horizontal.TScale\", length=SCALE_LENGTH,\n from_=1, to=MAX_H)\n \n self.w_label = ttk.Label(self, text=\"Cell Width: \")\n self.h_label = ttk.Label(self, text=\"Cell Height: \")\n\n self.w_label.grid(row=2, column=0, columnspan=1, padx=\"20 0\", pady=\"10 20\", sticky=N+S+W)\n self.width.grid(row=2, column=0, columnspan=2, padx=\"10 20\", pady=\"10 20\", sticky=N+S+E)\n self.h_label.grid(row=2, column=2, columnspan=1, padx=\"0 0\", pady=\"10 20\", sticky=N+S+W)\n self.height.grid(row=2, column=2, columnspan=2, padx=\"10 20\", pady=\"10 20\", sticky=N+S+E)\n \n \n # Padding slider (one for both x and y)\n self.padding = ttk.Scale(self, orient=\"horizontal\", style=\"Horizontal.TScale\", length=SCALE_LENGTH,\n from_=0, to=MAX_P)\n self.p_label = ttk.Label(self, text=\"Cell Padding: \")\n\n self.p_label.grid(row=1, column=4, columnspan=1, padx=\"0 0\", sticky=N+S+W)\n self.padding.grid(row=1, column=4, columnspan=2, padx=\"10 20\", sticky=N+S+E)\n \n \n # Row input box and column input box\n row_values = list(range(1, MAX_R+1))\n col_values = list(range(1, MAX_C+1))\n \n self.rows = ttk.Combobox(self, values=row_values, width=COMBO_WIDTH, justify=RIGHT)\n self.rows.current(self.kensuke.rows-1)\n self.r_label = ttk.Label(self, text=\"Rows: \")\n\n self.cols = ttk.Combobox(self, values=col_values, width=COMBO_WIDTH, justify=RIGHT)\n self.cols.current(self.kensuke.cols-1)\n self.c_label = ttk.Label(self, text=\"Columns: \")\n\n self.r_label.grid(row=2, column=4, columnspan=1, padx=\"0 0\", pady=\"10 20\", sticky=N+S+W)\n self.rows.grid(row=2, column=4, columnspan=1, padx=\"10 20\", pady=\"10 20\", sticky=N+S+E)\n self.c_label.grid(row=2, column=5, columnspan=1, padx=\"0 0\", pady=\"10 20\", sticky=N+S+W)\n self.cols.grid(row=2, column=5, columnspan=1, padx=\"10 20\", pady=\"10 20\", sticky=N+S+E)\n\n # Radio button for resizing distorted image\n\n if self.kensuke is not None:\n self.set_control_values()\n\n # Implement update function when widget's state is changed\n self.x.configure(command=self.update)\n self.y.configure(command=self.update)\n self.width.configure(command=self.update)\n self.height.configure(command=self.update)\n self.padding.configure(command=self.update)\n self.rows.configure(validatecommand=self.update)\n self.cols.configure(validatecommand=self.update)\n\n def create_styles(self):\n self.style = ttk.Style(self)\n self.style.configure(\"Horizontal.TScale\", troughcolor=\"#F0F0F0\", background=\"green\",\n sliderthickness=20, borderwidth=2)\n\n def create_widgets(self):\n self.create_styles() # Implement styles for widgets\n self.create_viewports() # Create canvases for original and distorted image\n self.create_controls() # Parameter control widgets created\n\n def draw_canvases(self):\n if self.kensuke is None:\n print(\"None\")\n return\n \n # -- Original image canvas --\n # Clear canvas\n origin_obj_ids = self.origin_view.find_all()\n if len(origin_obj_ids) > 0:\n for i in origin_obj_ids: self.origin_view.delete(i)\n\n # Canvas resize\n image_dim = self.kensuke.image.size\n if image_dim[0] > int(self.origin_view[\"width\"]):\n self.origin_view[\"width\"] = image_dim[0]\n if image_dim[1] > int(self.origin_view[\"height\"]):\n self.origin_view[\"height\"] = image_dim[1]\n\n # Original image draw\n tkimage = ImageTk.PhotoImage(self.kensuke.image)\n self.origin_view.create_image(0, 0, anchor=NW, image=tkimage)\n self.origin_view.image = tkimage\n\n self.draw_grid()\n \n\n # -- Distorted image canvas --\n # Clear canvas\n distort_obj_ids = self.distort_view.find_all()\n if len(distort_obj_ids) > 0:\n for i in distort_obj_ids: self.distort_view.delete(i)\n\n # Canvas resize\n self.distort_view[\"width\"] = self.origin_view[\"width\"]\n self.distort_view[\"height\"] = self.origin_view[\"height\"]\n\n # Distorted image draw\n tkdistort = ImageTk.PhotoImage(self.kensuke.distorted)\n self.distort_view.create_image(0, 0, anchor=NW, image=tkdistort)\n self.distort_view.image = tkdistort\n \n\n # Draws outlines for cells onto original image\n def draw_grid(self):\n for i in range(self.kensuke.rows):\n for j in range(self.kensuke.cols):\n temp = self.kensuke\n x0 = temp.x + (j * temp.w) + (j * temp.padding)\n y0 = temp.y + (i * temp.h) + (i * temp.padding)\n x1 = x0 + temp.w\n y1 = y0 + temp.h\n\n self.origin_view.create_rectangle(x0, y0, x1, y1, outline=\"cyan\")\n\n # Grabs values from Kensuke object and sets them in corresponding widgets\n def set_control_values(self):\n temp = self.kensuke\n self.x[\"value\"] = temp.x\n self.y[\"value\"] = temp.y\n self.width[\"value\"] = temp.w\n self.height[\"value\"] = temp.h\n self.padding[\"value\"] = temp.padding\n\n temp_dim = temp.image.size\n self.x[\"to\"] = temp_dim[0]\n self.y[\"to\"] = temp_dim[1]\n\n def set_kensuke(self, k=None):\n if k is None:\n return\n self.kensuke = k\n\n # Update function when widgets' (related to distortion parameters) states change\n def update(self, value):\n # Grabbing values from all scales\n self.kensuke.x = int(self.x.get())\n self.kensuke.y = int(self.y.get())\n self.kensuke.w = int(self.width.get())\n self.kensuke.h = int(self.height.get())\n self.kensuke.padding = int(self.padding.get())\n\n # Grabbing values from comboboxes\n self.kensuke.rows = int(self.rows.get()) if self.rows.get() != '' else self.kensuke.rows\n self.kensuke.cols = int(self.cols.get()) if self.cols.get() != '' else self.kensuke.cols\n\n # Create new cells and assemble them\n if self.kensuke.inside_image_dim():\n self.kensuke.create_cells()\n\n self.kensuke.assemble_cells()\n self.kensuke.resize_distorted()\n\n # Redraw viewports\n self.draw_canvases()\n \n\nroot = Tk()\nktest = Kensuke(create_image(\"sample_imgs/tree_frog.jpg\"), 10, 12, 20, 10, 10, 20, 20)\nktest.create_cells()\nktest.assemble_cells()\nktest.resize_distorted()\n\napp = Application(root, ktest)\napp.mainloop()\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":9376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"27095683","text":"from keras.applications import inception_resnet_v2\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten\nfrom keras import layers\nfrom keras.optimizers import Adam\n\ndef build_model_Inception_Resnet():\n\n inception_resnet = inception_resnet_v2.InceptionResNetV2(\n weights='imagenet',\n include_top=False,\n input_shape=(224,224,3)\n )\n\n model = Sequential()\n model.add(inception_resnet)\n model.add(layers.GlobalMaxPooling2D())\n model.add(layers.Dropout(0.5))\n \n model.add(layers.Dense(2, activation='sigmoid'))\n \n model.compile(\n loss='categorical_crossentropy',\n optimizer=Adam(lr=0.0005),\n metrics=['accuracy']\n )\n \n return model\n","sub_path":"Inception_Resnet_model.py","file_name":"Inception_Resnet_model.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611734874","text":"import datetime\n\nimport tensorflow as tf\nfrom utils import mlp\nimport numpy as np\nimport numpy.random as npr\n\n\nclass Agent2048:\n\n def __init__(self, board_size, batch_size, expname, gamma, device='/cpu:0', dropout=0.0, threads=2, **kwargs):\n self.board_size = board_size\n self.batch_size = batch_size\n self.dropout = dropout\n\n with tf.device(device):\n with tf.variable_scope('agent') as scope:\n self.state = tf.placeholder(shape=[batch_size, self.board_size ** 2], dtype=tf.int32)\n oh_state = tf.cast(tf.reshape(tf.one_hot(self.state, 11), (batch_size, -1)), tf.float32)\n\n self.estimated_rewards = self.Q(oh_state)\n scope.reuse_variables()\n self.selected_action, self.estimated_reward = self.select_best_action(oh_state)\n\n self.new_state = tf.placeholder(shape=[batch_size, board_size ** 2], dtype=tf.int32)\n self.last_action = tf.placeholder(shape=[batch_size], dtype=tf.int32)\n self.last_reward = tf.placeholder(shape=[batch_size], dtype=tf.float32)\n self.last_estimated_reward = tf.placeholder(shape=[batch_size], dtype=tf.float32)\n self.gamma = gamma\n\n oh_new_state = tf.cast(tf.reshape(tf.one_hot(self.new_state, 11), (batch_size, -1)), tf.float32)\n _, new_estimated_reward = self.select_best_action(oh_new_state)\n\n self.losses = (self.last_reward + self.gamma * self.last_estimated_reward - new_estimated_reward) ** 2\n self.loss = tf.reduce_mean(self.losses)\n\n self.optimizer = tf.train.RMSPropOptimizer(learning_rate=0.001)\n self.training = self.optimizer.minimize(self.loss)\n\n self.session = tf.Session(config=tf.ConfigProto(inter_op_parallelism_threads=threads,\n intra_op_parallelism_threads=threads,\n allow_soft_placement=True))\n self.session.run(tf.initialize_all_variables())\n\n self.summary_writer = tf.train.SummaryWriter('train_{}'.format(expname),\n graph=self.session.graph,\n flush_secs=10)\n\n def select_best_action(self, state):\n state_action_estimated_reward = self.Q(state)\n\n # select the action\n selected_action = tf.argmax(state_action_estimated_reward, 1)\n\n # and the reward\n estimated_reward = tf.reduce_max(state_action_estimated_reward, 1)\n\n return selected_action, estimated_reward\n\n def Q(self, state):\n estimated_reward = mlp(state, [512, 128, 4], ['RELU', 'RELU', 'IDENTITY'])\n return estimated_reward\n\n def play(self, env_states, epoch_id):\n if npr.random() < 0.9**epoch_id:\n estimated_rewards = self.session.run(self.estimated_rewards,\n {self.state: np.array(env_states).reshape((self.batch_size, self.board_size ** 2))})\n\n selected_action = npr.random_integers(0, 3, self.batch_size)\n\n estimated_reward = []\n for r, a in zip(estimated_rewards, selected_action):\n estimated_reward.append(r[a])\n estimated_reward = np.array(estimated_reward)\n else:\n selected_action, estimated_reward = self.session.run([self.selected_action, self.estimated_reward],\n {self.state: np.array(env_states).reshape((self.batch_size, self.board_size ** 2))})\n return selected_action, estimated_reward\n\n def learn(self, env_states, last_action, last_reward, last_estimated_reward):\n _, loss = self.session.run([self.training, self.loss],\n {self.new_state: np.array(env_states).reshape((self.batch_size, self.board_size ** 2)),\n self.last_action: last_action,\n self.last_estimated_reward: last_estimated_reward,\n self.last_reward: last_reward})\n return loss\n","sub_path":"agent_2048.py","file_name":"agent_2048.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"507213987","text":"from pwn import *\nfrom datetime import datetime\nimport os, signal, sys\nimport inspect, csv, copy\n\n# Defines\nrun_file_name = \"./signal_pp.out\"\n\n# Global variables\ntopology_list = {1: \"Ping-pong\"}\ngraph_list = {1: \"Per cores\", 2: \"Per processes\"}\nprocess_list = []\nmax_cores = 0\n\ndef run_program(iter):\n # context.log_level = 'error'\n p = process([run_file_name] + [str(iter)])\n process_list.append(p)\n p.recvuntil(\"{\")\n pids = [int(p.recvuntil(\",\")[:-1]), int(p.recvuntil(\"}\")[:-1])]\n # context.log_level = 'INFO'\n return pids\n\n# Menu\ndef init_menu():\n menu = {1: \"Signal\", 2: \"IPC\", 3: \"Lock\"}\n while True:\n mode = -1\n topology = -1\n while mode < 0 or mode > len(menu):\n\n# Select Mode\n print(\"Select a testing type\\n\")\n print(\"1. Signal\")\n print(\"2. IPC\")\n print(\"3. Lock\")\n print(\"0. exit\\n\")\n\n mode = int(input(\"type: \"))\n\n if mode == 0:\n print(\"Terminate program\")\n sys.exit(0)\n else :\n print(\"\\n* Selected Mode: {0}\".format(menu[mode]))\n# Select Topology\n while topology < 0 or topology > len(topology_list):\n print(\"Select topology\\n\")\n for key in topology_list:\n print(\"{0}: {1}\".format(key, topology_list[key]))\n print(\"0. exit\\n\")\n\n topology = int(input(\"Topology: \"))\n\n if topology == 0:\n print(\"Terminate program\")\n sys.exit(0)\n else :\n print(\"\\n* Selected Mode: {0}, Topology: {1}\\n\".format(menu[mode], topology_list[topology]))\n\n if mode == 1: # 1. Signal\n sig_test(topology)\n return 1\n elif mode == 2:\n return 2\n elif mode == 3:\n return 3\n else:\n print(\"Invalid Input ({0})\".format(mode))\n sys.exit(-1)\n\n\n\n''' Signal '''\n# Initial runution function\ndef sig_test(topology):\n print(\"#########\\n1. Signal\\n#########\\n\")\n \n test_attr = sig_test_setattr() \n result = sig_test_all_run(test_attr)\n\n # Create a file named by datetime\n now = datetime.now()\n filename = \"{0}{1}{2}{3}{4}{5}.csv\".format(now.year, now.month, now.day, now.hour, now.minute, now.second)\n with open(filename, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=' ',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n csvwriter.writerow(result.values()) \n \n print(\"\\n* Save successed (file name: {0})\".format(filename))\n \n\n# Set attribute\ndef sig_test_setattr():\n '''\n 0: Number of processes or Number of processes' pairs\n 1: Number of iterations\n 2: Number of cores\n 3: Number of tests\n 4: Graph type\n 5: Number of gap\n '''\n flag = 0\n num_of_attr = 6\n attr = []\n attr_name = {\n 0: \"Number of processes\", 1: \"Number of iterations\",\n 2: \"Number of cores\", 3: \"Number of tests\",\n 4: \"Graph type\", 5: \"Number of gap\"\n }\n while flag == 0:\n attr = [0 for i in range(num_of_attr)]\n\n while len(list(filter(lambda x: x <= 0, attr))):\n if attr[0] <= 0:\n attr[0] = int(input(\"Number of processes' pairs: \"))\n if attr[1] <= 0:\n attr[1] = int(input(\"Number of iterations: \"))\n if attr[2] <= 0:\n attr[2] = int(input(\"Number of cores (Max cores: {0}): \".format(max_cores)))\n attr[2] = -1 if attr[2] > max_cores else attr[2]\n if attr[3] <= 0:\n attr[3] = int(input(\"Number of tests: \"))\n if attr[4] <= 0:\n attr[4] = int(input(\"Variations of graphs: \"))\n if attr[4] == 2 and attr[5] <= 0:\n attr[5] = int(input(\"Gaps: \"))\n\n if attr[4] != 2:\n attr[5] = 1\n\n print(\"\\n* Test Attribute\\n\")\n for i in range(num_of_attr):\n print(\"{0}. {1}: {2}\".format(i, attr_name[i], attr[i]))\n print()\n\n flag = 1\n # while flag == 0:\n # flag = input(\"Confirm? (Y/N): \")\n # print (flag, type(flag))\n # if flag == \"Y\":\n # print (\"hello\")\n # flag = 1\n # break\n # elif flag == \"N\":\n # print(\"wtf\")\n # flag = 0\n # break\n # else:\n # print(\"???????\")\n # flag = 0\n\n\n\n return attr\n\n \ndef sig_test_init(test_attr):\n pcnt, ni, nc, nt, ng, ngap = test_attr\n\n pid_list = []\n affinity_mask = {i for i in range(0, nc)}\n\n process_list.clear()\n # context.log_level = 'error'\n for i in range(pcnt):\n pid_list.append(run_program(ni))\n\n for pid in pid_list:\n os.sched_setaffinity(pid[0], affinity_mask)\n os.sched_setaffinity(pid[1], affinity_mask)\n\n return pid_list\n\n\ndef sig_test_run(pid_list):\n for pid in pid_list:\n os.kill(pid[0], signal.SIGCONT)\n\n recv = []\n for p in process_list:\n p.recvuntil(\"{\")\n recv.append(float(p.recvuntil(\"}\")[:-1]))\n avg = sum(recv) / len(pid_list)\n # context.log_level = 'DEBUG'\n return avg\n\ndef sig_test_all_run(attr):\n result = {}\n \n # Increase number of processes' pairs from 1 \n plog = log.progress(\"Testing \", level = logging.CRITICAL)\n # context.log_level = 'ERROR'\n \n for i in range(1, attr[0] + 1, attr[5]): # attr[0]: Number of processes', attr[5] = gap\n # Number of tests\n for j in range(attr[3]):\n # context.log_level = 'INFO'\n plog.status(\"Total pairs: {0}, Current pairs: {1}, Current iterations: {2}\".format(attr[0], i, j + 1))\n # context.log_level = 'ERROR'\n # Single runution\n test_attr = copy.deepcopy(attr)\n test_attr[0] = i\n \n pid_list = sig_test_init(test_attr)\n single_result = sig_test_run(pid_list)\n \n try:\n result[i] += single_result\n except:\n result[i] = single_result\n\n # context.log_level = 'INFO'\n \n plog.success(\"Hello world!\")\n \n for key in result:\n result[key] /= attr[3]\n for key in result:\n print (\"{0}: {1}\".format(key, result[key]))\n\n return result\n\n\n# Program starts\nif __name__ == \"__main__\":\n max_cores = os.cpu_count()\n init_menu()\n ","sub_path":"signal/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":6461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"577339012","text":"import requests\nimport pickle\nimport datetime\nimport os\nfrom bokeh.io import curdoc\nfrom bokeh.plotting import figure, output_file, show\n\ntier_points = {\n \"IRON\": 0,\n \"BRONZE\": 400,\n \"SILVER\": 800,\n \"GOLD\": 1200\n}\nrank_points = {\n \"I\": 299,\n \"II\": 200,\n \"III\": 100,\n \"IV\": 0\n}\n\nranks_tags = {\n 0: \"Iron\",\n 400: \"Bronze\",\n 800: \"Silver\",\n 1200: \"Gold\"\n}\n\napi_token = \"\"\nsummoner_names: dict = {\n \"Gaziibo\": \"jnegFz8Qt2SKpXkU0UQ7uyeo04xuHIzHTozGpD4paLnhHY8\",\n \"Yosh710\": \"qrkYHRZgRqpsWgr9UZx9h8ZAQz_kzdWTiR6VMXs_vi0jLCi_\",\n \"Drizzy0415\": \"FLPg43L1a2HpfDLS9wmcAmNyCeNytuilKprYmPo-eUBmwTS3\",\n \"Hairy Pooner\": \"HvXunAyiAxdOb3aAuDdpCLq2SESgnVAOAKxTXtnkbBFwJtvqgSRvYkcvyQ\",\n \"BigDevInDaHouse\": \"99-XRTbz3l94Pvhw74QeV8DtM8ysjpU73HQMBVatDx4PPZOl\",\n \"Griffiniti\": \"cwI_NPdAAZrejdLDCgtXu9WPJGwxeT54gbFj_jtUUmXdzoUF\",\n \"TheP1ckl3r\": \"5qFSxAufMIF07G2c9UI_cPinCOdQmnaZraRGUSwXTHs8lRye\",\n \"YourDadsFist\": \"sXxXFZ1Geb97Arzcr4L6IZJmnr-Jal_TOpsixX0XKGi8ViZR\",\n \"SlootDragoon\": \"zAu5V-jMB5wFaesaPdbfkAb87Y_9c3foQNvjyedlyH4h3ufR\",\n \"somdee\": \"mvFzy02VKGYtI7RqZOQK9pAxlH_obNk9Uji9nvcZIXPOIBg\",\n \"BZuke\": \"kDX-noD02l7jTpVmuceZwQWY8RbmpqEMDVj3CEm8SHw_SmA\"\n}\n\nrequests_headers = {\n \"X-Riot-Token\": api_token\n}\n\n\ndef save_obj(obj, name):\n with open('summoner_scores/' + name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n\n\ndef load_obj(name):\n with open('summoner_scores/' + name + '.pkl', 'rb') as f:\n return pickle.load(f)\n\n\ndef get_leader_board():\n summoner_names_total_score = dict()\n for key in summoner_names:\n print(\"Getting: \" + key + \" score\")\n ranked_response = requests.get(\"https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/{id}\"\n .format(id=summoner_names[key]), headers=requests_headers)\n\n ranked_response_json = ranked_response.json()\n summoner_total_score = calculate_rank_score(ranked_response_json[0][\"leaguePoints\"],\n ranked_response_json[0][\"tier\"], ranked_response_json[0][\"rank\"])\n\n summoner_names_total_score[key] = summoner_total_score\n\n print(summoner_names_total_score)\n save_obj(summoner_names_total_score, \"summoner_names_total_score-\" + str(datetime.date.today()))\n plot_ranks()\n\ndef load_rank_and_time():\n for file_name in os.listdir(\"summoner_scores\"):\n single_dict = load_obj(file_name)\n\n\n\ndef plot_ranks():\n\n graph_name = \"The Family Ranked Leader Board - \" + str(datetime.date.today())\n summoner_names_total_score: dict = load_obj(\"summoner_names_total_score-\" + str(datetime.date.today()))\n summoner_names_total_score = dict(sorted(summoner_names_total_score.items(), key=lambda item: item[1]))\n print(type(summoner_names_total_score.keys()))\n plot = figure(x_range=list(summoner_names_total_score.keys()),\n plot_width=1200, plot_height=800, x_axis_label=\"Summoner Name\",\n y_axis_label=\"Total LP\", title=graph_name)\n curdoc().theme = 'dark_minimal'\n\n plot.circle_dot(list(summoner_names_total_score.keys()),\n list(summoner_names_total_score.values()),\n size=20, color=\"#ff9bff\", hatch_color=\"#DDA0DD\")\n show(plot)\n\n\ndef calculate_rank_score(league_points: int, tier: str, rank: str):\n total_score = 0\n total_score += league_points\n total_score += rank_points[rank]\n total_score += tier_points[tier]\n return total_score\n\n\nif __name__ == '__main__':\n get_leader_board()\n","sub_path":"leaderboard.py","file_name":"leaderboard.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230221656","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n################################################################################\n# BLE Logger for ble_gps [GPS/GNSS][GATT/VSSPP]\n#\n# Bluetooth LE拡張ボードを搭載した Spresenseが送信するビーコンを受信し、\n# Lapis独自のVSSPPプロファイルで位置情報を取得するサンプル・プログラムです。\n#\n# Copyright (c) 2019 Wataru KUNINO\n################################################################################\n\n#【インストール方法】\n# bluepy (Bluetooth LE interface for Python)をインストールしてください\n# sudo pip3 install bluepy\n#\n#【実行方法】\n# 実行するときは sudoを付与してください\n# sudo ./ble_logger_sens_gatt.py &\n#\n#【参考文献】\n# 本プログラムを作成するにあたり下記を参考にしました\n# https://ianharvey.github.io/bluepy-doc/notifications.html\n\nfrom bluepy import btle\nfrom bluepy.btle import Peripheral, DefaultDelegate\nfrom sys import argv\nimport getpass\n\naddress = 'xx:xx:xx:xx:xx:xx' # BLEデバイス(ペリフェラル側)のアドレスを記入\n\ndef payval(val,num, bytes=1, sign=False):\n a = 0\n for i in range(0, bytes):\n a += (256 ** i) * int(val[(num - 2 + i) * 2 : (num - 1 + i) * 2],16)\n if sign:\n if a >= 2 ** (bytes * 8 - 1):\n a -= 2 ** (bytes * 8)\n return a\n\nclass MyDelegate(DefaultDelegate):\n val = ''\n\n def __init__(self, params):\n DefaultDelegate.__init__(self)\n # ... initialise here\n\n def handleNotification(self, cHandle, data):\n # ... perhaps check cHandle\n # ... process 'data'\n val = data.hex()\n print(val)\n sensors = dict()\n\n # センサ値を辞書型変数sensorsへ代入\n sensors['ID'] = hex(payval(val,2,2))\n sensors['Latitude'] = payval(val,4,3,True) / 8388607 * 90\n sensors['LatLast8'] = payval(val,11,1) / 2147483647 * 90\n sensors['Longitude'] = payval(val,7,3,True) / 8388607 * 180\n sensors['LonLast8'] = payval(val,12,1) / 2147483647 * 180\n sensors['SEQ'] = payval(val,10)\n sensors['RSSI'] = dev.rssi\n\n # 画面へ表示\n print(' ID =',sensors['ID'])\n print(' SEQ =',sensors['SEQ'])\n print(' GPS Latitude =',round(sensors['Latitude'],5),'°')\n print(' (32bit) =',round(sensors['Latitude']+sensors['LatLast8'],8),'°')\n print(' GPS Longitude =',round(sensors['Longitude'],5),'°')\n print(' (32bit) =',round(sensors['Longitude']+sensors['LonLast8'],7),'°')\n print(' RSSI =',sensors['RSSI'],'dB')\n\nif address[0] == 'x':\n scanner = btle.Scanner()\n # BLE受信処理\n try:\n devices = scanner.scan(5)\n except Exception as e:\n print(\"ERROR\",e)\n if getpass.getuser() != 'root':\n print('使用方法: sudo', argv[0])\n exit()\n # 受信データについてBLEデバイス毎の処理\n for dev in devices:\n for (adtype, desc, val) in dev.getScanData():\n if adtype == 8 and val[0:10] == 'LapisDev':\n print(\"\\nDevice %s (%s), RSSI=%d dB, Connectable=%s\" % (dev.addr, dev.addrType, dev.rssi, dev.connectable))\n print(\" %3d %s = %s\" % (adtype, desc, val))\n address = dev.addr\nif address[0] == 'x':\n print(\"no LapisDev found\")\n exit()\n\np = Peripheral(address, addrType='random')\t# Failed to connect to peripheral\np.setDelegate(MyDelegate(DefaultDelegate))\n\n# Setup to turn notifications on\nsvc = p.getServiceByUUID('0179bbd0-5351-48b5-bf6d-2167639bc867')\nch = svc.getCharacteristics('0179bbd1-5351-48b5-bf6d-2167639bc867')[0]\nch.handle += 2\n#ch.write(b'\\x01')\nprint('uuid =',ch.uuid, 'handle =',hex(ch.handle))\np.writeCharacteristic(ch.handle, b'\\x01')\n\n# Main\nprint('Waiting...')\np.waitForNotifications(20)\n\n'''\n(bluepyのダウンロードとインストール)\npi@raspberrypi:~ $ sudo apt-get update\npi@raspberrypi:~ $ sudo pip3 install bluepy\n\n(プログラムのダウンロード)\npi@raspberrypi:~\n$ git clone http://github.com/bokunimowakaru/rohm_iot_for_spresense\n\n(プログラムの実行)\npi@raspberrypi:~ $ cd rohm_iot_for_spresense\npi@raspberrypi:~/rohm_iot_for_spresense \n$ sudo ./ble_logger_gps_gatt.py\nDevice xx:xx:xx:xx:xx:xx (random), RSSI=-83 dB, Connectable=True\n 8 Short Local Name = LapisDev\nuuid = 0179bbd1-5351-48b5-bf6d-2167639bc867 handle = 0x404\nWaiting...\n0100a35631825960414fa5\n ID = 0x1\n SEQ = 65\n GPS Latitude = 34.xx108 °\n (32bit) = 34.xx10873 °\n GPS Longitude = 135.xx17 °\n (32bit) = 135.xx171108 °\n RSSI = -81 dB\n'''\n","sub_path":"ble_logger_gps_gatt.py","file_name":"ble_logger_gps_gatt.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410084635","text":"#!/usr/bin/python2\n\n# \n# Copyright (C) 2012 Aaron Lewis \n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n\nimport atexit\nimport gobject\nimport glib\nimport sys\nimport os\nimport pyinotify\n\ntry:\n\tfrom dockmanager.dockmanager import DockManagerItem, DockManagerSink, DOCKITEM_IFACE\n\tfrom signal import signal, SIGTERM\n\tfrom xml.dom import minidom\n\tfrom sys import exit\nexcept:\n\texit()\n\nclass VBOXItem(DockManagerItem):\n\tdef __init__(self, sink, path):\n\t\tDockManagerItem.__init__(self, sink, path)\n\t\t\n\t\tself.clear_menu_buttons()\n\t\tself.readvms()\n\n\tdef readvms(self):\n\t\ttry:\n\t\t\tdom = minidom.parse(os.path.expanduser(\"~/.VirtualBox/VirtualBox.xml\"))\n\t\t\t\t\t\t\n\t\t\tfor node in dom.getElementsByTagName('MachineEntry'):\n\t\t\t\turi = node.getAttribute('src')\n\t\t\t\tself.add_vm(uri)\n\t\t\t\n\t\texcept:\n\t\t\tprint(\"Exception while parsing vbox xml file\")\n\n\tdef add_vm(self , uri):\n\t\t\n\t\ttry:\n\t\t\tdom = minidom.parse(uri)\n\n\t\t\tfor node in dom.getElementsByTagName('Machine'):\n\t\t\t\tname = node.getAttribute('name')\n\t\t\t\ticon = \"/secure/Common/Pictures/vboxicons/os_%s.png\" % node.getAttribute('OSType').lower()\n\t\t\t\t\t\n\t\t\t\tself.add_menu_item (name, icon, \"Virtual Machines\")\n\t\t\t\n\t\texcept:\n\t\t\tprint (\"Exception: %s\" % uri)\n\n\tdef clear_menu_buttons(self):\n\t\tfor k in self.id_map.keys():\n\t\t\tself.remove_menu_item(k)\n\n\tdef menu_pressed(self, menu_id):\n\t\ttry:\t\t\n\t\t\tuuid = self.id_map[menu_id]\n\t\t\tos.system (\"VBoxManage startvm '%s' &>/dev/null\" % uuid)\n\t\texcept:\n\t\t\tpass\n\n\nclass GTGSink(DockManagerSink):\n\tdef item_path_found(self, pathtoitem, item):\n\t\tif item.Get(DOCKITEM_IFACE, \"DesktopFile\", dbus_interface=\"org.freedesktop.DBus.Properties\").endswith (\"virtualbox.desktop\"):\n\t\t\tself.items[pathtoitem] = VBOXItem(self, pathtoitem)\n\n\ngtgsink = GTGSink()\n\ndef cleanup ():\n\tgtgsink.dispose ()\n\nif __name__ == \"__main__\":\n\tmainloop = gobject.MainLoop(is_running=True)\n\n\tatexit.register (cleanup)\n\tsignal(SIGTERM, lambda signum, stack_frame: exit(1))\n\n\tmainloop.run()\n","sub_path":"scripts/virtualbox.py","file_name":"virtualbox.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"175857060","text":"import csv\nimport logging\nfrom pathlib import Path\nimport tarfile\nfrom typing import Dict\n\nimport pandas as pd\n\nfrom guesslangtools.common import (\n absolute, File, cached, download_file, load_csv)\n\n\nLOGGER = logging.getLogger(__name__)\n\n# Open source projects dataset: https://zenodo.org/record/1196312\nDATASET_FILENAME = 'repositories-1.2.0-2018-03-12.csv'\nDATASET_URL = (\n 'https://zenodo.org/record/1196312/files/'\n 'Libraries.io-open-data-1.2.0.tar.gz')\n\nCSV_FIELD_LIMIT = 10 * 1024 * 1024 # 1O MiB\n\nPKG_ROOT = Path(__file__).parent.parent\nSQL_DATASET_PATH = PKG_ROOT.joinpath('data', 'sql_dataset.csv')\n\n\n@cached(File.COMPRESSED_DATASET)\ndef download() -> None:\n LOGGER.info('Retrieving repositories dataset (8GB)')\n LOGGER.info('This operation might take a lot of time...')\n\n destination = absolute(File.COMPRESSED_DATASET)\n download_file(DATASET_URL, destination)\n\n\n@cached(File.DATASET)\ndef extract() -> None:\n LOGGER.info('Extracting repositories list file')\n LOGGER.info('This operation might take few minutes...')\n\n compressed_filename = absolute(File.COMPRESSED_DATASET)\n with tarfile.open(compressed_filename) as tar:\n tar.extract(DATASET_FILENAME, path=absolute('.'))\n\n extracted_file = absolute(DATASET_FILENAME)\n extracted_file.rename(absolute(File.DATASET))\n\n\n@cached(File.SHRUNK_DATASET)\ndef shrink() -> None:\n LOGGER.info('Shrink repositories list file')\n LOGGER.info('This operation might take few minutes...')\n\n input_path = absolute(File.DATASET)\n output_path = absolute(File.SHRUNK_DATASET)\n\n # The input dataset is too huge to be fully loaded into memory\n csv.field_size_limit(CSV_FIELD_LIMIT)\n with input_path.open() as input_file, output_path.open('w') as output_file:\n reader = csv.DictReader(input_file)\n fieldnames = ['repository_name', 'repository_language']\n writer = csv.DictWriter(output_file, fieldnames=fieldnames)\n writer.writeheader()\n\n for item in reader:\n if _ignore(item):\n continue\n\n smaller_item = {\n 'repository_name': item['Name with Owner'],\n 'repository_language': item['Language'],\n }\n writer.writerow(smaller_item)\n\n\ndef _ignore(item: Dict[str, str]) -> bool:\n return (\n item['Fork'] == 'true'\n or item['Host Type'] != 'GitHub'\n or not item['Name with Owner']\n )\n\n\n@cached(File.ALTERED_DATASET)\ndef alter() -> None:\n LOGGER.info('Alter repositories list file')\n LOGGER.info('This operation might take few minutes...')\n\n output_path = absolute(File.ALTERED_DATASET)\n\n df = load_csv(File.SHRUNK_DATASET)\n\n # Set repositories with no language as Markdown repositories.\n # Because most of Github repositories have a Readme.md file.\n mask = df['repository_language'].isnull()\n df.loc[mask, 'repository_language'] = 'Markdown'\n\n # There are too few repositories tagged as SQL repositories.\n # To mitigate this problem, a list of known repositories are flagged as\n # SQL repositories.\n sql_df = pd.read_csv(SQL_DATASET_PATH)\n mask = df['repository_name'].isin(sql_df['repository_name'])\n df.loc[mask, 'repository_language'] = 'SQL'\n\n df.to_csv(output_path, index=False)\n","sub_path":"guesslangtools/workflow/repositories_dataset.py","file_name":"repositories_dataset.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"340573177","text":"import sys\nimport time\nimport urllib.request\nfrom urllib.parse import urlencode\nimport json\nfrom corry import *\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import QPixmap\nfrom country import country_list\n\nclass MyForm(QDialog):\n def __init__(self, parent=None):\n QWidget.__init__(self, parent)\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n self.get_all()\n countries = country_list.get_country()\n completer = QCompleter(countries)\n self.ui.country.setCompleter(completer)\n self.ui.country.editingFinished.connect(self.search)\n \n def get_all(self):\n url = \"https://corona.lmao.ninja/v2/all\"\n\n headers = {}\n headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'\n\n request = urllib.request.Request(url, headers=headers)\n resp = urllib.request.urlopen(request)\n data = json.loads(resp.read().decode(\"utf-8\"))\n time_stamp = data['updated']\n time_stamp_ft = time.strftime('%d-%B-%Y %H:%M:%S', time.localtime(time_stamp/1000))\n\n # Update GUI\n self.ui.activeCount.setText(str(data['active']))\n self.ui.recoveredCount.setText(str(data['recovered']))\n self.ui.confirmedCount.setText(str(data['cases']))\n self.ui.deathsCount.setText(str(data['deaths']))\n self.ui.criticalCount.setText(str(data['critical']))\n self.ui.lastUpdated.setText(\"Last updated: \" + time_stamp_ft) \n\n def search(self):\n # url = \"https://corona.lmao.ninja/v2/countries/\" + self.ui.country.text()\n \n country = urllib.parse.quote(self.ui.country.text())\n url = f\"https://corona.lmao.ninja/v2/countries/{country}\"\n\n headers = {}\n headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17'\n\n request = urllib.request.Request(url, headers=headers)\n resp = urllib.request.urlopen(request)\n data = json.loads(resp.read().decode(\"utf-8\"))\n flag_url = data['countryInfo']['flag']\n request = urllib.request.Request(flag_url, headers=headers)\n flag = urllib.request.urlopen(request).read()\n pixmap = QPixmap()\n pixmap.loadFromData(flag)\n time_stamp = data['updated']\n time_stamp_ft = time.strftime('%d-%B-%Y %H:%M:%S', time.localtime(time_stamp/1000))\n\n # Update GUI\n self.ui.countryFlag.setPixmap(pixmap)\n self.ui.activeCount.setText(str(data['active']))\n self.ui.recoveredCount.setText(str(data['recovered']))\n self.ui.confirmedCount.setText(str(data['cases']))\n self.ui.deathsCount.setText(str(data['deaths']))\n self.ui.criticalCount.setText(str(data['critical']))\n self.ui.lastUpdated.setText(\"Last updated: \" + time_stamp_ft)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myapp = MyForm()\n myapp.show()\n sys.exit(app.exec_())","sub_path":"corry.pyw","file_name":"corry.pyw","file_ext":"pyw","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199501307","text":"from typing import List\nfrom collections import Counter\n\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool: \n if arr.count(0) > 1:\n return True\n\n print(Counter(arr))\n\n map= {}\n for i in range(len(arr)):\n if arr[i] not in map:\n map[arr[i]]= i\n\n for i in range(len(arr)):\n d= arr[i] * 2\n if d in map and map[d]!= i:\n return True\n\n return False\n\n\ndef main():\n inputs= [[10,2,5,3], [7,1,14,11], [3,1,7,11], [0, 1, 0]]\n\n sol= Solution()\n for nums in inputs:\n print(nums)\n res= sol.checkIfExist(nums)\n print(res)\n \nmain()","sub_path":"leetcode/old_session/1346. Check If N and Its Double Exist.py","file_name":"1346. Check If N and Its Double Exist.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"483589447","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Dani/Documents/Projects/Golismero_2.0/src_github/golismero/api/net/cache.py\n# Compiled at: 2014-01-14 18:58:51\n\"\"\"\nNetwork cache API.\n\"\"\"\n__license__ = '\\nGoLismero 2.0 - The web knife - Copyright (C) 2011-2013\\n\\nAuthors:\\n Daniel Garcia Garcia a.k.a cr0hn | cr0hn<@>cr0hn.com\\n Mario Vilas | mvilas<@>gmail.com\\n\\nGolismero project site: https://github.com/golismero\\nGolismero project mail: golismero.project<@>gmail.com\\n\\nThis program is free software; you can redistribute it and/or\\nmodify it under the terms of the GNU General Public License\\nas published by the Free Software Foundation; either version 2\\nof the License, or (at your option) any later version.\\n\\nThis program is distributed in the hope that it will be useful,\\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\nGNU General Public License for more details.\\n\\nYou should have received a copy of the GNU General Public License\\nalong with this program; if not, write to the Free Software\\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\\n'\n__all__ = [\n 'NetworkCache']\nfrom ..config import Config\nfrom ...common import Singleton\nfrom ...messaging.codes import MessageCode\nfrom collections import defaultdict\nfrom functools import partial\n\nclass _NetworkCache(Singleton):\n \"\"\"\n Cache for network resources, separated by protocol.\n \"\"\"\n\n def __init__(self):\n self._clear_local_cache()\n\n def _clear_local_cache(self):\n \"\"\"\n .. warning: Do not call!\n \"\"\"\n self.__cache = defaultdict(partial(defaultdict, dict))\n\n def get(self, key, protocol):\n \"\"\"\n Get a network resource from the cache.\n\n :param key: Key to reference the network resource.\n :type key: str\n\n :param protocol: Network protocol.\n :type protocol: str\n\n :returns: Resource from the cache, None if not found.\n :rtype: object | None\n \"\"\"\n data = self.__cache[Config.audit_name][protocol].get(key, None)\n if data is None:\n data = Config._context.remote_call(MessageCode.MSG_RPC_CACHE_GET, key, protocol)\n if data is not None:\n self.__cache[Config.audit_name][protocol][key] = data\n return data\n\n def set(self, key, data, protocol, timestamp=None, lifespan=None):\n \"\"\"\n Store a network resource in the cache.\n\n :param key: Key to reference the network resource.\n :type key: str\n\n :param data: Data to store in the cache.\n :type data: object\n\n :param protocol: Network protocol.\n :type protocol: str\n\n :param timestamp: Timestamp for this network resource.\n :type timestamp: int\n\n :param lifespan: Time to live in the cache.\n :type lifespan: int\n \"\"\"\n self.__cache[Config.audit_name][protocol][key] = data\n Config._context.async_remote_call(MessageCode.MSG_RPC_CACHE_SET, key, protocol, data)\n\n def remove(self, key, protocol):\n \"\"\"\n Remove a network resource from the cache.\n\n :param key: Key to reference the network resource.\n :type key: str\n\n :param protocol: Network protocol.\n :type protocol: str\n \"\"\"\n try:\n del self.__cache[Config.audit_name][protocol][key]\n except KeyError:\n pass\n\n Config._context.async_remote_call(MessageCode.MSG_RPC_CACHE_REMOVE, key, protocol)\n\n def exists(self, key, protocol):\n \"\"\"\n Verify if the given key exists in the cache.\n\n :param key: Key to reference the network resource.\n :type key: str\n\n :returns: True if the resource is in the cache, False otherwise.\n :rtype: bool\n \"\"\"\n found = key in self.__cache[Config.audit_name][protocol]\n if not found:\n found = Config._context.remote_call(MessageCode.MSG_RPC_CACHE_CHECK, key, protocol)\n found = bool(found)\n return found\n\n\nNetworkCache = _NetworkCache()","sub_path":"pycfiles/golismero-2.0.3-1.tar/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"445881614","text":"from dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport json\n\n\ndef initialize(app, data, fl):\n\n # finish line client side data api\n fl.register_data('output-form-n-clicks', { 'n_clicks': 0 })\n\n # plugin api to register visualization\n fl.register_vis(\n 'InputForm',\n html.Div([\n dcc.Input(id='input-1-state', type='text', value=data['state']),\n dcc.Input(id='input-2-state', type='text', value=data['country']),\n html.Button(id='submit-button', n_clicks=0, children='Submit')\n ])\n )\n\n \ndef finalize(app, data, fl):\n\n # example callback that updates client side data\n @app.callback(Output('output-form-n-clicks', 'children'),\n [Input('submit-button', 'n_clicks')])\n def callback(n_clicks):\n return json.dumps({ 'n_clicks': n_clicks })\n","sub_path":"example/plugins/InputForm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482165006","text":"import random\r\nlist1=[]\r\nfor i in range(20):\r\n list1.append(random.randint(1,10))\r\ntuple1=tuple(list1)\r\nprint(\"元组:\",tuple1)\r\ndict1={}\r\nfor i in tuple1:\r\n if i in dict1.keys():\r\n dict1[i]+=1\r\n else:\r\n dict1[i]=1\r\nfor i in dict1:\r\n print(\"数字%d出现的次数:%d\"%(i,dict1.get(i)))\r\n\r\n \r\n","sub_path":"4.5.py","file_name":"4.5.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"282029170","text":"from decimal import Decimal\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .models import Event, Invoice, InvoiceItem, TicketPriceIncrease, TicketType, DeliveryMethod\n\n\nclass TicketTypeForm(forms.ModelForm):\n available_tickets_number = forms.IntegerField(\n min_value=0, label=_('Available tickets number')\n )\n\n def __init__(self, *args, **kwargs):\n super(TicketTypeForm, self).__init__(*args, **kwargs)\n available = self.instance.available_tickets_number\n self.fields['available_tickets_number'].initial = available\n\n def save(self, commit=True):\n available_tckts_no = self.cleaned_data.get('available_tickets_number', 0)\n self.instance.available_tickets_number = available_tckts_no\n return super(TicketTypeForm, self).save(commit=commit)\n\n class Meta:\n model = TicketType\n fields = ['event', 'name', 'base_price', 'price_currency',\n 'people_per_ticket', 'available_tickets_number',\n 'ticket_deadline']\n\n\nclass EventForm(forms.ModelForm):\n def clean_max_people_allowed(self):\n value = self.cleaned_data['max_people_allowed']\n if value is None:\n return None\n if value < self.instance.people_allowed_in:\n raise ValidationError(_('Maximum number of people allowed in must '\n 'be greater than people already allowed '\n 'in.'))\n return value\n\n class Meta:\n model = Event\n fields = '__all__'\n\n\nclass TicketPriceIncreaseForm(forms.ModelForm):\n class Meta:\n model = TicketPriceIncrease\n fields = '__all__'\n\n def clean_end_datetime(self):\n end = self.cleaned_data.get('end_datetime', None)\n start = self.cleaned_data.get('start_datetime', None)\n\n if start and end and start >= end:\n raise ValidationError(_('End time has to be after start time.'))\n return end\n\n def clean(self):\n cleaned_data = super(TicketPriceIncreaseForm, self).clean()\n start = self.cleaned_data.get('start_datetime')\n end = self.cleaned_data.get('end_datetime', None)\n date_error_msg = _('There are currently price increases set in this '\n 'period.')\n if start:\n queryset = type(self.instance).objects.exclude(pk=self.instance.pk)\n if end is None:\n if queryset.filter(start_datetime__lte=start,\n end_datetime__gte=start).count():\n raise ValidationError(date_error_msg)\n else:\n if queryset.filter(\n Q(\n start_datetime__range=(start, end),\n end_datetime__range=(start, end)\n ) |\n Q(\n start_datetime__range=(start, end),\n end_datetime__isnull=True\n )\n ).count():\n raise ValidationError(date_error_msg)\n\n\nclass InvoiceItemForm(forms.ModelForm):\n class Meta:\n model = InvoiceItem\n fields = '__all__'\n\n def get_invoice_status(self):\n return self.instance.invoice.status\n\n def clean_quantity(self):\n quantity = self.cleaned_data.get('quantity', 0)\n invoice_status = self.get_invoice_status()\n if (quantity - self.instance.old_quantity) > self.instance.maximum_item_quantity and \\\n self.instance.old_quantity < quantity:\n raise ValidationError(_('Not enough tickets in stock to do that.'))\n return quantity\n\n def clean(self):\n super(InvoiceItemForm, self).clean()\n # if not self.instance.invoice.is_not_ordered:\n # raise ValidationError(_('You cannot edit invoice item with this '\n # 'status'))\n\n\nclass AbstractPaymentForm(forms.Form):\n def __init__(self, invoice, *args, **kwargs):\n super(AbstractPaymentForm, self).__init__(*args, **kwargs)\n self.invoice = invoice\n self.payment_method = self.invoice.payment_method.real_instance\n\n def pay(self, **kwargs):\n price = self.invoice.total_in_vat\n currency = 'gbp'\n description = \"Invoice #%(invoice_id)d\" % {\n 'invoice_id': self.invoice.pk\n }\n self.payment = self.payment_method.real_instance.pay(price, currency,\n description, **kwargs)\n\n if self.payment.get('status', None).lower() != 'success':\n raise ValidationError(self.payment.get('message', _('Internal problems. Try again.')))\n\n self.invoice.charge_id = self.payment.get('charge_id', None)\n self.invoice.save()\n self.invoice.update_payment_status()\n\n def clean(self, *args, **kwargs):\n if not self.invoice.is_ordered:\n raise ValidationError(_('Invoice status does not allow to do '\n 'payment.'))\n\n super(AbstractPaymentForm, self).clean(*args, **kwargs)\n self.pay()\n\n\nclass ManualPaymentForm(AbstractPaymentForm):\n pass\n\n\nclass StripePaymentForm(AbstractPaymentForm):\n card_number = forms.CharField(label=_('card number'))\n exp_month = forms.CharField(label=_('expiry month'))\n exp_year = forms.CharField(label=_('expiry year'))\n cvc = forms.CharField(label=_('security code (CVC)'),\n help_text=_('last three digits on the back of your '\n 'card'))\n\n def pay(self, **kwargs):\n card_number = self.cleaned_data.get('card_number', None)\n exp_month = self.cleaned_data.get('exp_month', None)\n exp_year = self.cleaned_data.get('exp_year', None)\n cvc = self.cleaned_data.get('cvc', None)\n return super(StripePaymentForm, self).pay(card_number=card_number,\n exp_month=exp_month,\n exp_year=exp_year, cvc=cvc)\n\n\nclass PayPalPaymentForm(AbstractPaymentForm):\n pass\n\n\nclass InvoiceDeliveryMethodForm(forms.Form):\n delivery_method = forms.ChoiceField(label=_('Delivery method'))\n\n def __init__(self, invoice, *args, **kwargs):\n super(InvoiceDeliveryMethodForm, self).__init__(*args, **kwargs)\n self.invoice = invoice\n self.fields['delivery_method'].choices = self.get_delivery_methods()\n if self.invoice.delivery_method:\n self.fields['delivery_method'].initial = self.invoice.delivery_method.item.pk\n\n def get_delivery_methods(self):\n delivery_methods = []\n\n for row in DeliveryMethod.objects.all():\n name = _('%(name)s (£%(price)s) - %(days)d days') % {\n 'name': row.name,\n 'price': row.price,\n 'days': row.delivery_time.days\n }\n delivery_methods.append((row.pk, name))\n\n return delivery_methods\n\n def get_delivery_method(self, pk):\n return DeliveryMethod.objects.get(pk=pk)\n\n def save(self, *args, **kwargs):\n if self.invoice.delivery_method:\n self.invoice.delivery_method.delete()\n\n dm_pk = self.cleaned_data.get('delivery_method', None)\n self.delivery_method = self.get_delivery_method(dm_pk)\n\n if not self.delivery_method.require_delivery_address:\n self.invoice.delivery_address_name = None\n self.invoice.delivery_address_address_line_1 = None\n self.invoice.delivery_address_address_line_2 = None\n self.invoice.delivery_address_address_city = None\n self.invoice.delivery_address_address_postal_code = None\n self.invoice.delivery_address_address_country = None\n self.invoice.save()\n\n invoice_item = InvoiceItem(\n invoice=self.invoice,\n name=_('Delivery'),\n variant=self.delivery_method,\n price=self.delivery_method.price,\n item=self.delivery_method\n )\n invoice_item.save()\n\nclass InvoiceBillingAddressForm(forms.ModelForm):\n use_as_delivery_address = forms.BooleanField(\n label=_('use as delivery address'),\n initial=True,\n required=False\n )\n\n def __init__(self, *args, **kwargs):\n super(InvoiceBillingAddressForm, self).__init__(*args, **kwargs)\n for k, v in self.fields.items():\n # Hide delivery method field if the delivery address is not required\n if k == 'use_as_delivery_address' and \\\n (not self.instance.delivery_method or \\\n not self.instance.delivery_method.item.require_delivery_address):\n del self.fields[k]\n\n if k != 'billing_address_address_line_2' and \\\n k != 'use_as_delivery_address':\n v.required = True\n if self.fields.get('use_as_delivery_address', False):\n if self.instance.is_billing_address_same_as_delivery_address:\n self.fields['use_as_delivery_address'].initial = True\n else:\n self.fields['use_as_delivery_address'].initial = False\n\n\n class Meta:\n model = Invoice\n fields = [\n 'billing_address_name', 'billing_address_address_line_1',\n 'billing_address_address_line_2', 'billing_address_address_city',\n 'billing_address_address_postal_code',\n 'billing_address_address_country'\n ]\n\n def save(self, commit=True):\n instance = super(InvoiceBillingAddressForm, self).save(commit=False)\n\n if self.cleaned_data.get('use_as_delivery_address', False):\n instance.delivery_address_name = self.cleaned_data['billing_address_name']\n instance.delivery_address_address_line_1 = self.cleaned_data['billing_address_address_line_1']\n instance.delivery_address_address_line_2 = self.cleaned_data['billing_address_address_line_2']\n instance.delivery_address_address_city = self.cleaned_data['billing_address_address_city']\n instance.delivery_address_address_postal_code = self.cleaned_data['billing_address_address_postal_code']\n instance.delivery_address_address_country = self.cleaned_data['billing_address_address_country']\n\n if commit:\n instance.save()\n return instance\n\n\nclass InvoiceDeliveryAddressForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(InvoiceDeliveryAddressForm, self).__init__(*args, **kwargs)\n for k, v in self.fields.items():\n if k != 'delivery_address_address_line_2':\n v.required = True\n\n class Meta:\n model = Invoice\n fields = [\n 'delivery_address_name', 'delivery_address_address_line_1',\n 'delivery_address_address_line_2', 'delivery_address_address_city',\n 'delivery_address_address_postal_code',\n 'delivery_address_address_country'\n ]\n","sub_path":"events_booking_system/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":11192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"563844928","text":"class Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\nclass BinaryTreeNode(object):\n def __init__(self, val=None, left=None,right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution(object):\n def preorder(self, root: Node):\n \"\"\"\n 589. N叉树的前序遍历 循环法\n 给定一个 N 叉树,返回其节点值的前序遍历。\n \"\"\"\n if not root:\n return []\n result,root = [],root and [root]\n while root:\n node = root.pop()\n result.append(node.val)\n if node.children: # 2020-04-22 晚加,前一晚还没问题?\n root += [child for child in node.children[::-1] if child]\n return result\n\n\n def preorder1(self, root: Node):\n if not root:\n return []\n result,root = [],root and [root]\n while root:\n node = root.pop()\n result.append(node.val)\n if node.children: # 2020-04-22 晚加,前一晚还没问题?\n root.extend(node.children[::-1])\n return result\n\n \n def preorder2(self, root: Node):\n \"\"\"\n N叉树的前序遍历 递归法\n \"\"\"\n if not root:\n return []\n result = []\n result.append(root.val)\n if root.children: # 2020-04-22 晚加,前一晚还没问题?\n for node in root.children: \n result += self.preorder2(node)\n return result\n\n def postorder(self, root: Node):\n \"\"\"N叉树的后序遍历 迭代法:先前序遍历,再反转结果\"\"\"\n if not root:\n return [] \n stack, result = [root, ], []\n while stack:\n node = stack.pop()\n result.append(node.val)\n if node.children:\n for child in node.children:\n stack.append(child) \n return result[::-1]\n\n \n def postorder1(self, root: Node):\n \"\"\"N叉树的后序遍历 递归法\"\"\"\n if not root:\n return [] \n result = []\n if root.children:\n for node in root.children:\n result.extend(self.postorder1(node))\n result.append(root.val) \n return result\n\n\n def levelOrder(self, root:Node):\n \"\"\"N叉树的层序遍历\"\"\"\n if not root:\n return []\n result = []\n temp = [root]\n while temp:\n node = temp.pop(0)\n tmp = []\n if node.children:\n for item in node.children:\n tmp.append(item.val)\n temp.extend([item])\n result.append(tmp)\n return result\n\n\n def levelOrder1(self, root:Node):\n \"\"\"N叉树的层序遍历,BFS\"\"\"\n if not root:\n return []\n result = []\n temp = [root]\n while temp:\n tmp = []\n for _ in range(len(temp)):\n item = temp.pop(0)\n tmp.append(item.val)\n if item.children:\n temp.extend(item.children)\n result.append(tmp)\n return result\n\n \n def levelOrder2(self, root: 'Node'):\n \"\"\"N叉树的层序遍历\"\"\"\n import collections\n if root is None:\n return []\n result = []\n queue = collections.deque([root])\n # queue.append(root)\n # visited = set(root)\n while queue:\n level = []\n for _ in range(len(queue)):\n node = queue.popleft()\n level.append(node.val)\n if node.children:\n queue.extend(node.children)\n result.append(level)\n return result\n\n def levelOrderBinaryTree(self, root: BinaryTreeNode):\n \"\"\"二叉树的层序遍历\"\"\"\n import collections\n if root is None:\n return []\n result = []\n queue = collections.deque([root])\n while queue:\n current_level = []\n for _ in range(len(queue)):\n node = queue.popleft()\n current_level.append(node.val)\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n result.append(current_level)\n return result\n\n def levelOrderBinaryTree2(self, root: BinaryTreeNode):\n \"\"\"二叉树的层序遍历\"\"\"\n if not root:return [] \n self.result = []\n self._dfs(root,0)\n return self.result\n\n def _dfs(self,node,level):\n if not node :return\n if len(self.result) < level + 1:\n self.result.append([])\n self.result[level].append(node.val)\n self._dfs(node.left,level+1)\n self._dfs(node.right,level+1)\n \n def preorderBinaryTree(self, root: BinaryTreeNode):\n \"\"\"\n 二叉树的前序遍历。迭代法\n \"\"\"\n if not root:\n return []\n result,root = [],root and [root]\n while root:\n node = root.pop()\n result.append(node.val)\n if node.right:\n root.extend([node.right])\n if node.left:\n root.extend([node.left])\n return result\n\n\n def preorderBinaryTree2(self, root: BinaryTreeNode):\n \"\"\"\n 二叉树的前序遍历。递归法\n \"\"\"\n if not root:\n return []\n result = [root.val]\n result.extend(self.preorderBinaryTree2(root.left))\n result.extend(self.preorderBinaryTree2(root.right))\n return result\n\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n \"\"\"\n 二叉树的中序遍历 递归法\n \"\"\"\n if not root:\n return []\n result = []\n result.extend(self.inorderTraversal(root.left))\n result.append(root.val)\n result.extend(self.inorderTraversal(root.right))\n return result\n \n def inorderTraversal1(self, root: TreeNode) -> List[int]:\n \"\"\"\n 二叉树的中序遍历 迭代法\n 0、根节点入栈\n 1、循环遍历左节点依次入栈直到叶子节点,cur指针指向栈顶节点\n 2、栈顶节点出栈,并记录节点value值,cur指向栈顶节点的右节点,重复第1步\n 3、输出最终的结果\n \"\"\"\n if not root:\n return []\n result = []\n tmp = []\n cur = root\n while cur or len(tmp)>0:\n while cur:\n tmp.append(cur)\n cur = cur.left\n cur = tmp.pop()\n result.append(cur.val)\n cur = cur.right\n return result\n\n def postorderTraversal(self, root: TreeNode) -> List[int]:\n \"\"\"\n 二叉树的后序遍历 递归法\n \"\"\"\n if not root:\n return []\n result = []\n result.extend(self.postorderTraversal(root.left))\n result.extend(self.postorderTraversal(root.right))\n result.append(root.val)\n return result\n\n def postorderTraversal1(self, root: TreeNode) -> List[int]:\n \"\"\"\n 二叉树的后序遍历 迭代法\n \"\"\"\n if not root:\n return [] \n stack, result = [root, ], []\n while stack:\n node = stack.pop()\n result.append(node.val)\n if node.left:\n stack.extend([node.left])\n if node.right:\n stack.extend([node.right]) \n return result[::-1]\n\n def postorderTraversal(self, root):\n \"\"\"\n flag标记已访问的节点\n \"\"\"\n result, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop()\n if node:\n if visited:\n # add to result if visited\n result.append(node.val)\n else:\n # post-order\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\n return result\n\n def lowestCommonAncestor(self,root,p,q):\n \"\"\"\n 最近公共祖先\n \"\"\"\n if root==None or root==p or root==q:\n return root\n left = self.lowestCommonAncestor(root.left,p,q)\n right = self.lowestCommonAncestor(root.right,p,q)\n if left == None:\n return right\n if right == None:\n return left\n return root\n\n def lowestCommonAncestor2(self,root,p,q):\n \"\"\"最近公共祖先: 针对二叉搜索树\"\"\"\n if root.val > p.val and root.val > q.val:\n return self.lowestCommonAncestor(root.left,p,q)\n if p.val > root.val and q.val > root.val:\n return self.lowestCommonAncestor(root.right,p,q)\n return root\n\n def lowestCommonAncestor22(self,root,p,q):\n \"\"\"最近公共祖先: 针对二叉搜索树\"\"\"\n while root:\n if root.val > p.val and root.val > q.val:\n root = root.left\n elif p.val > root.val and q.val > root.val:\n root = root.right\n else:\n return root\n \n def lowestCommonAncestor222(self,root,p,q):\n stack = [root]\n parent = {root: None}\n while p not in parent or q not in parent:\n node = stack.pop()\n if node.left:\n parent[node.left] = node\n stack.append(node.left)\n if node.right:\n parent[node.right] = node\n stack.append(node.right)\n ancestors = set()\n while p:\n ancestors.add(p)\n p = parent[p]\n while q not in ancestors:\n q = parent[q]\n return q\n\n def maxDepth(self,root:BinaryTreeNode):\n if not root: return 0\n return 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))\n\n def minDepth(self,root:BinaryTreeNode):\n if not root :return 0\n if not root.left:\n return self.minDepth(root.right)+1\n if not root.right:\n return self.minDepth(root.left)+1\n \n leftMinDepth = self.minDepth(root.left)\n rightMinDepth =self.minDepth(root.right)\n\n return 1 + min(leftMinDepth,rightMinDepth)\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n root = Node(1)\n root.children = [Node(3),Node(2),Node(4)]\n root.children[0].children = [Node(5),Node(6)]\n root.children[1].children = [Node(7),Node(8)]\n\n print(solution.levelOrder1(root))\n print(solution.postorder1(root))\n\n\n # # Driver code to test above \n # arr = [ 12, 11, 13, 5, 6, 7] \n # solution.heapSort(arr) \n # n = len(arr) \n # print (\"Sorted array is\") \n # for i in range(n): \n # print (\"%d\" % arr[i]), \n # # This code is contributed by Mohit Kumra ","sub_path":"Week_02/Tree.py","file_name":"Tree.py","file_ext":"py","file_size_in_byte":11003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425298043","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.ListView.as_view(), name='list'),\n url(r'^report/$', views.ReportView.as_view(), name='report'),\n url(r'^create/$', views.CreateView.as_view(), name='create'),\n url(r'^delete/(?P.*)/$', views.DeleteView.as_view(), name='delete'),\n url(r'^up/(?P.*)/$', views.SortView.as_view(adjustment=-1), name='up'),\n url(r'^down/(?P.*)/$', views.SortView.as_view(adjustment=+1), name='down'),\n url(r'^(?P.*)/$', views.UpdateView.as_view(), name='update'),\n]\n","sub_path":"ddm/criteria/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"456998173","text":"from django.db import models\nfrom django.utils import timezone\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=128)\n order = models.PositiveIntegerField(default=5)\n\n def __str__(self):\n return self.name\n\n class Meta:\n ordering = ['order', 'name']\n verbose_name = 'FAQ Category'\n verbose_name_plural = 'FAQ Categories'\n\n\nclass FAQ(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n category = models.ForeignKey(\n Category, related_name='faqs', blank=True,\n null=True, on_delete=models.SET_NULL)\n question = models.CharField(max_length=128)\n answer = models.TextField()\n order = models.PositiveIntegerField(default=5)\n\n def save(self, *args, **kwargs):\n if not self.id:\n self.created_at = timezone.now()\n self.updated_at = timezone.now()\n return super().save(*args, **kwargs)\n\n def __str__(self):\n return self.question\n\n class Meta:\n ordering = ['category', 'order']\n verbose_name = 'FAQ'\n verbose_name_plural = 'FAQs'\n","sub_path":"faq/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"483390461","text":"#ALL URLS\nhome_url = 'https://www.jiosaavn.com/api.php?__call=content.getHomepageData&format=json'\nsearch_url = 'https://www.jiosaavn.com/api.php?__call=search.getResults&_format=json&q={}'\nalbum_url = 'https://www.jiosaavn.com/api.php?__call=content.getAlbumDetails&albumid={}&_format=json&p={}'\nartist_url = 'https://www.jiosaavn.com/api.php?_marker=0&_format=json&__call=artist.getArtistPageDetails&n_album=1&artistId={}&page={}'\nlyric_url = 'https://www.jiosaavn.com/api.php?__call=lyrics.getLyrics&ctx=web6dot0&_format=json&lyrics_id={}'\nplaylist_url = 'https://www.jiosaavn.com/api.php?listid={}&_format=json&__call=playlist.getDetails'\nfeature_playlist_url = 'https://www.jiosaavn.com/api.php?__call=playlist.getFeaturedPlaylists&_marker=false&language={}&offset=1&size=100&_format=json'\nauto_comp_url = 'https://www.jiosaavn.com/api.php?_format=json&query={}&__call=autocomplete.get'\nmsgs = 'QWR1bHRzIG9ubHkuIFRoaXMgYXJlYSBjb250YWlucyBhZHVsdCBjb250ZW50IGludGVuZGVkIGZvciBpbmRpdmlkdWFscyAxOCB5ZWFycyBvZiBhZ2Ugb3Igb2xkZXIuIElmIHlvdSBhcmUgbm90IHlldCAxOCsgcGxlYXNlIGdvIGJhY2su'\ngaana_url = 'https://liteapp.gaana.com/'\n#ALL FUNCTIONS\ndef clean(strs):\n try:\n strs = str(strs).split(\"-->\")[1].replace(\"\\\\n\",\"\")\n return strs\n except:\n return strs\ndef url_convert(url):\n try:\n url = str(url).replace('preview', 'h')\n url= url.replace('_96_p.mp4', '_96.mp4')\n url= url.replace('h.saavncdn.com', 'jiosaavn.cdn.jio.com')\n return url\n except:\n return url\ndef get_duration(dur):\n dur = int(int(dur)*1.6)\n min = int(round(dur/100,0))\n sec = dur % 100\n if sec > 60:\n sec = sec - 60\n final_dur = \"{:02d}:{:02d}\".format(min,sec)\n return final_dur\n\ndef get_country(ip):\n import requests\n import json\n url = 'https://ipinfo.io/'.format(ip)\n url_other = 'https://geolocation-db.com/json/8f12b5f0-2bc2-11eb-9444-076679b7aeb0/{}'.format(ip)\n try:\n data = requests.get(url)\n data =json.loads(data.text)\n country = data['country']\n city = data['city']\n return country,city\n except:\n data = requests.get(url_other)\n data = json.loads(data.text)\n country = data['country_code']\n city = data['city']\n return country, city\n\ndef clean_str(txt):\n import re\n txt = re.sub('[^A-Za-z0-9]+', ' ', txt)\n return txt\n\ndef resize(url):\n data = url.replace(\"50x50\",\"150x150\")\n return data\n\ndef get_movie(id):\n if id == '1':\n return \"https://4movierulz.vin/genre/hindi/\"\n elif id == '2':\n return \"https://4movierulz.vin/genre/english/\"\n elif id == '3':\n return \"https://4movierulz.vin/genre/download-tv-shows-english-web-series/\"\n elif id == '4':\n return \"https://4movierulz.vin/genre/hindi-web-series-download/\"\n else:\n return \"https://4movierulz.vin/?h=150\"\ndef fb_dw(url):\n if \"?v=\" in url:\n url = url.split(\"?v=\")[1]\n url = \"https://m.facebook.com/\"+str(url)\n import youtube_dl\n with youtube_dl.YoutubeDL() as ydl:\n try:\n lists = []\n info_dict = ydl.extract_info(url, download=False)\n for links in info_dict['formats']:\n lists.append(links['url'])\n sz = len(lists)\n if sz>4:\n audio = lists[0]\n vid1 = lists[-1]\n vid2 = lists[-2]\n vid3 = lists[-3]\n else:\n audio = lists[0]\n vid1 = lists[-1]\n vid2 = lists[-1]\n vid3 = lists[-1]\n ttl = info_dict['title'].replace('\"',\" \")\n res_list = '{\"title\" : \"'+ttl+'\", \"audio\" : \"'+audio+'\", \"high\" : \"'+vid1+'\", \"medium\" : \"'+vid2+'\", \"low\" : \"'+vid3+'\"}'\n return res_list\n except Exception as e:\n lists = []\n info_dict = ydl.extract_info(url, download=False)\n js = info_dict['entries'][0]\n for links in js['formats']:\n lists.append(links['url'])\n sz =len(lists)-1\n if sz < 4:\n audio = lists[0]\n vid1 = lists[-1]\n vid2 = lists[-1]\n vid3 = lists[-1]\n else:\n audio = lists[0]\n vid1 = lists[-1]\n vid2 = lists[-2]\n vid3 = lists[-3]\n ttl = info_dict['entries'][0]['title'].replace('\"', \" \")\n res_list = '{\"title\" : \"' + ttl + '\", \"audio\" : \"' + audio + '\", \"high\" : \"' + vid1 + '\", \"medium\" : \"' + vid2 + '\", \"low\" : \"' + vid3 + '\"}'\n return res_list\n\ndef insta(link):\n try:\n import requests\n from urllib.parse import unquote\n from bs4 import BeautifulSoup\n url = \"https://ucmate.info\"\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n resp = {'input': link}\n print(resp)\n request_image = requests.get(url, data = resp)\n src = request_image.content.decode('utf-8')\n return str(src)\n # soup = BeautifulSoup(src)\n # url = soup.find(\"meta\", property=\"og:video\")\n # ttl = soup.find(\"meta\", property=\"og:title\")['content'].replace(\"\\n\",\" \").replace('\"',\" \")\n # video_url = unquote(url['content'])\n # res_list = '{\"title\" : \"'+ttl+'\", \"video\" : \"'+video_url+'\"}'\n # return res_list\n except Exception as e:\n return str(e)","sub_path":"jiosaavn/baseurl.py","file_name":"baseurl.py","file_ext":"py","file_size_in_byte":5518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"361052284","text":"#!/usr/bin/env python3\n\"\"\"\n`compdecomp` testing\n\n@authors: Roman Yasinovskyy\n@version: 2021.10\n\"\"\"\n\n\nimport importlib\nimport json\nimport pathlib\nimport sys\nfrom collections import Counter\nfrom typing import Generator\n\nimport pytest\nimport toml\n\ntry:\n importlib.util.find_spec(\".\".join(pathlib.Path(__file__).parts[-3:-1]), \"src\")\nexcept ModuleNotFoundError:\n sys.path.append(f\"{pathlib.Path(__file__).parents[3]}/\")\nfinally:\n from src.projects.compdecomp import (\n Node,\n build_tree,\n compress,\n decompress,\n follow_tree,\n load_codes,\n mark_tree,\n traverse_tree,\n )\n\nDATA_DIR = pathlib.Path(\"data/projects/compdecomp/\")\nTIME_LIMIT = 1\n\n\ndef get_cases(category: str, *attribs: str) -> Generator:\n \"\"\"Get test cases from the TOML file\"\"\"\n with open(pathlib.Path(__file__).with_suffix(\".toml\"), encoding=\"utf-8\") as file:\n all_cases = toml.load(file)\n for case in all_cases[category]:\n yield tuple(case.get(a) for a in attribs)\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"text, total_weight\",\n get_cases(\"test_case\", \"text\", \"total_weight\"),\n)\ndef test_build_tree(text: str, total_weight: int):\n \"\"\"Test the tree building\"\"\"\n weights = Counter(text)\n root = build_tree(weights)\n assert root.weight == total_weight\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"text, tree\",\n get_cases(\"test_case\", \"text\", \"tree\"),\n)\ndef test_traverse_tree(text: str, tree: Node):\n \"\"\"Testing the tree traversal\"\"\"\n weights = Counter(text)\n root = build_tree(weights)\n assert traverse_tree(root) == tree\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"text, code2char\",\n get_cases(\"test_case\", \"text\", \"code2char\"),\n)\ndef test_follow_tree_to_leaf(text: str, code2char: str):\n \"\"\"Testing the tree following with a valid result\"\"\"\n weights = Counter(text)\n root = build_tree(weights)\n codes = json.loads(code2char)\n for code in codes:\n assert follow_tree(root, code) == codes[code]\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"text, code2char\",\n get_cases(\"test_case\", \"text\", \"code2char\"),\n)\ndef test_follow_tree_to_none(text: str, code2char: str):\n \"\"\"Testing the tree following with no result\"\"\"\n weights = Counter(text)\n root = build_tree(weights)\n codes = json.loads(code2char)\n if \"0\" not in codes:\n assert follow_tree(root, \"0\") is None\n if \"1\" not in codes:\n assert follow_tree(root, \"1\") is None\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"text, char2code, code2char\",\n get_cases(\"test_case\", \"text\", \"char2code\", \"code2char\"),\n)\ndef test_mark_tree(text: str, char2code: str, code2char: str):\n \"\"\"Testing the tree marking\"\"\"\n weights = Counter(text)\n root = build_tree(weights)\n dict_1: dict = {}\n dict_2: dict = {}\n mark_tree(dict_1, dict_2, root, \"\")\n assert dict_1 == json.loads(char2code)\n assert dict_2 == json.loads(code2char)\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"filename, tree\",\n get_cases(\"test_case\", \"filename\", \"tree\"),\n)\ndef test_load_codes(filename: str, tree: Node):\n \"\"\"Testing the codes loading\"\"\"\n with open(\n DATA_DIR / pathlib.Path(f\"{filename}.json\"), encoding=\"utf-8\"\n ) as code_file:\n metadata = json.load(code_file)\n root = load_codes(metadata)\n assert traverse_tree(root) == tree\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"filename, padding\",\n get_cases(\"test_case\", \"filename\", \"padding\"),\n)\ndef test_compression(filename: str, padding: int):\n \"\"\"Testing the compression\"\"\"\n with open(\n DATA_DIR / pathlib.Path(f\"{filename}.txt\"), encoding=\"utf-8\"\n ) as text_file:\n text = text_file.read().strip()\n weights = Counter(text)\n root = build_tree(weights)\n char_to_code, _ = mark_tree({}, {}, root, \"\")\n with open(DATA_DIR / pathlib.Path(f\"{filename}.bin\"), \"rb\") as compressed:\n assert compress(text, char_to_code) == (compressed.read(), padding)\n\n\n@pytest.mark.timeout(TIME_LIMIT)\n@pytest.mark.parametrize(\n \"filename, text\",\n get_cases(\"test_case\", \"filename\", \"text\"),\n)\ndef test_decompression(filename: str, text: str):\n \"\"\"Testing the decompression\"\"\"\n with open(\n DATA_DIR / pathlib.Path(f\"{filename}.json\"), encoding=\"utf-8\"\n ) as code_file:\n metadata = json.load(code_file)\n root = load_codes(metadata)\n padding_length = metadata.get(\"padding\", 0)\n with open(DATA_DIR / pathlib.Path(f\"{filename}.bin\"), \"rb\") as compressed:\n assert decompress(compressed.read(), padding_length, root) == text\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-v\", __file__])\n","sub_path":"tests/projects/compdecomp/test_compdecomp.py","file_name":"test_compdecomp.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"581312394","text":"import re as regex\n\nimport RedisConstants as Constants\n\nkeyPattern = '\"([_a-zA-Z]+)\"'\n\n\ndef save_file(file_path):\n \"\"\"Save all from a file in redis database\"\"\"\n count = 0\n with open(file_path, 'r') as a_file:\n for line in a_file:\n # Convert line to Map/Dictionary\n dict_from_line = get_dictionary_from_string(line)\n # SAVE IN REDIS\n save(dict_from_line)\n count += 1\n return count\n\n\ndef save(key_value):\n \"\"\"Saves a dictionary into the database\"\"\"\n\n # get key-values\n identifier = key_value['_id']\n state = key_value['state']\n city = key_value['city']\n\n # create key\n key = identifier + ':' + state + ':' + city\n\n # Add Values\n Constants.CONNECTION.set(key + '#pop', key_value['pop'])\n Constants.CONNECTION.set(key + '#loc', key_value['loc'])\n\n if Constants.VERBOSE:\n print(str(key_value))\n\n\ndef get_dictionary_from_string(string):\n \"\"\"Returns a Map/Dictionary from a String with KEY VALUE pairs\"\"\"\n result = {}\n # Look for \"\" : \"\"\n for match in regex.findall(keyPattern + ' : \"([\\- 0-9a-zA-Z]+)\"', string):\n result[match[0]] = match[1]\n # Look for \"\" : \n for match in regex.findall(keyPattern + ' : ([.\\-0-9]+)', string):\n result[match[0]] = float(match[1])\n # Look for \"\" : []\n for match in regex.findall(keyPattern + ' : \\[([.,\\- 0-9]+)\\]', string):\n result[match[0]] = [float(i) for i in (match[1].split(','))]\n return result\n\n\ndef delete_all():\n \"\"\"Clears the database\"\"\"\n Constants.CONNECTION.flushall()\n print('Database cleared!')\n","sub_path":"_04_key_value_db/src/RedisSaver.py","file_name":"RedisSaver.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"579445262","text":"from flask import Flask, render_template, request, redirect, send_from_directory\nfrom flask_csp.csp import csp_header\nfrom werkzeug.middleware import proxy_fix\nimport requests\nimport urllib\n\napp = Flask(__name__)\napp.wsgi_app = proxy_fix.ProxyFix(app.wsgi_app)\n\n# csp one (data uri) use cookie 54E0DA086734D3985318F11970AE03BD\n\n@app.after_request\ndef apply_csp(response):\n response.headers[\"Content-Security-Policy\"] = \"default-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src-elem 'self'; connect-src *\"\n return response\n\n@app.route('/')\n@app.route('/csp-one')\ndef cspOne():\n\treturn render_template('csp-one.html')\n\n@app.route('/csp-one-result', methods = ['POST','GET'])\ndef cspOneResult():\n\tpayload = \"None\"\n\tif request.method == 'POST':\n\t\tpayload = request.form['payload']\n\t\trequests.post('http://127.0.0.1:3000/submit', data={'url': request.base_url + \"?payload=\" + urllib.quote(payload)})\n\tif request.method == 'GET' and 'admin' in request.cookies and request.cookies.get(\"admin\") == u\"54E0DA086734D3985318F11970AE03BD\":\n\t\tpayload = request.args.get('payload')\n\telif request.method == 'GET':\n\t app.logger.warning('GET request without valid admin cookie.')\n\treturn render_template('csp-one-result.html', payload = payload)\n\n@app.route('/csp-one-flag', methods = ['GET'])\ndef cspOneFlag():\n\tif 'admin' in request.cookies and request.cookies.get(\"admin\") == u\"54E0DA086734D3985318F11970AE03BD\":\n\t\treturn \"CTF{Can_Send_Payloads}\"\n\telse:\n\t\treturn \"Ah ah ah, you didn't say the magic word\"\n\napp.run(host='0.0.0.0', port=8000)\n","sub_path":"csp-1/challenge/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458675737","text":"# -*- coding: utf-8 -*-\n\nfrom backpack.collections import Collection\nfrom ..exceptions import CleoException\n\n\nclass Question(object):\n \"\"\"\n Represents a Question\n \"\"\"\n\n def __init__(self, question, default=None):\n \"\"\"\n Constructor.\n\n :param question: The question to ask the user\n :type question: str\n\n :param default: The default answer to return if the user enters nothing\n :type default: mixed\n \"\"\"\n self.question = question\n self.default = default\n\n self._attempts = None\n self._hidden = False\n self.hidden_fallback = True\n self._autocompleter_values = None\n self.validator = None\n self.normalizer = None\n\n @property\n def hidden(self):\n return self._hidden\n\n @hidden.setter\n def hidden(self, value):\n if self.autocompleter_values:\n raise CleoException('A hidden question cannot use the autocompleter.')\n\n self._hidden = value\n\n @property\n def autocompleter_values(self):\n return self._autocompleter_values\n\n @autocompleter_values.setter\n def autocompleter_values(self, values):\n \"\"\"\n Sets values for the autocompleter.\n\n :param values: The autocomplete values\n :type values: list or None\n \"\"\"\n if values is not None and not isinstance(values, (list, Collection)):\n raise CleoException('Autocompleter values can be either a list or None.')\n\n if self.hidden:\n raise CleoException('A hidden question cannot use the autocompleter.')\n\n self._autocompleter_values = values\n\n @property\n def max_attempts(self):\n return self._attempts\n\n @max_attempts.setter\n def max_attempts(self, attempts):\n if attempts is not None and attempts < 1:\n raise CleoException('Maximum number of attempts must be a positive value.')\n\n self._attempts = attempts\n\n\n","sub_path":"cleo/questions/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"478747056","text":"# ==================================================================================================\n# Copyright 2011 Twitter, Inc.\n# --------------------------------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==================================================================================================\n\nimport os\nimport errno\nimport hashlib\nimport getpass\n\nfrom twitter.common.dirutil import safe_mkdir, safe_open\nfrom twitter.common.python.eggparser import EggParser\n\nclass EggCache(object):\n DEFAULT_PATH = \"/var/tmp/%(user)s\"\n PATH_FORMAT = \"%(name)s.%(crc)s\"\n\n def __init__(self, pexfile, basepath=None):\n self._pex = pexfile\n self._name = os.path.basename(self._pex.path())\n if self._pex.is_condensed():\n self._cache_path = basepath if basepath is not None else EggCache.DEFAULT_PATH\n self._cache_path = os.path.join(self._cache_path, EggCache.PATH_FORMAT) % {\n 'user': getpass.getuser(),\n 'name': self._name,\n 'crc': hashlib.md5(open(self._pex.path(), 'rb').read()).hexdigest()\n }\n else:\n self._cache_path = self._pex.path()\n self._eggparser = EggParser()\n self._registry = set()\n self._populate_registry()\n\n def _populate_registry(self):\n def extract_usable_egg(filename):\n if not filename.startswith('.deps/'):\n return None\n spath = filename.split('/')\n if len(spath) >= 2:\n if self._eggparser.is_compatible(spath[1]):\n return '/'.join(spath[0:2])\n return None\n\n for name in self._pex.listdir():\n extracted = extract_usable_egg(name)\n if extracted:\n self._registry.add(extracted)\n\n def paths(self):\n \"\"\"\n Return valid sys.path components for this egg, dumping them to a local\n cache if necessary.\n \"\"\"\n def same(filename, contents):\n if not os.path.exists(filename):\n return False\n # Hmm...for directories we should probably recursively verify\n if not os.path.isfile(filename):\n return True\n with open(filename, 'rb') as fp:\n file_contents = fp.read()\n return hashlib.md5(file_contents).digest() == hashlib.md5(contents).digest()\n\n def populate_cache():\n safe_mkdir(self._cache_path)\n\n for fn in self._pex.listdir():\n egg_prefix = '/'.join(fn.split('/')[0:2])\n if egg_prefix in self._registry:\n fn_contents = self._pex.read(fn)\n dest = os.path.join(self._cache_path, fn)\n if same(dest, fn_contents):\n continue\n with safe_open(dest, 'wb') as fn_out:\n fn_out.write(fn_contents)\n\n if self._pex.is_condensed():\n populate_cache()\n\n path_adjuncts = []\n for egg in self._registry:\n path_adjuncts.append(os.path.join(self._cache_path, egg))\n\n return path_adjuncts\n","sub_path":"src/python/twitter/common/python/eggcache.py","file_name":"eggcache.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"454533412","text":"import torch\nfrom pytorch_pretrained_bert.modeling import PreTrainedBertModel, BertModel, BertPreTrainingHeads\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass BertForMTPostTraining(PreTrainedBertModel):\n def __init__(self, config):\n super(BertForMTPostTraining, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertPreTrainingHeads(config, self.bert.embeddings.word_embeddings.weight)\n self.qa_outputs = torch.nn.Linear(config.hidden_size, 2)\n self.apply(self.init_bert_weights)\n\n def forward(self, mode, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None, next_sentence_label=None, start_positions=None, end_positions=None):\n \n sequence_output, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n \n if mode==\"review\":\n prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)\n if masked_lm_labels is not None and next_sentence_label is not None:\n loss_fct = torch.nn.CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1)) \n next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))\n total_loss = masked_lm_loss + next_sentence_loss\n \n return total_loss\n else:\n return prediction_scores, seq_relationship_score\n\n elif mode==\"squad\":\n logits = self.qa_outputs(sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1)\n end_logits = end_logits.squeeze(-1)\n\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions.clamp_(0, ignored_index)\n end_positions.clamp_(0, ignored_index)\n\n loss_fct = torch.nn.CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n qa_loss = (start_loss + end_loss) / 2\n return qa_loss\n else:\n return start_logits, end_logits\n else:\n raise Exception(\"unknown mode.\")\n\n\nclass BertForSequenceLabeling(PreTrainedBertModel):\n def __init__(self, config, num_labels=3):\n super(BertForSequenceLabeling, self).__init__(config)\n self.num_labels = num_labels\n self.bert = BertModel(config)\n self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)\n self.classifier = torch.nn.Linear(config.hidden_size, num_labels)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n\n if labels is not None:\n loss_fct = torch.nn.CrossEntropyLoss(ignore_index=-1)\n loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))\n return loss\n else:\n return logits\n\n","sub_path":"src/absa_models.py","file_name":"absa_models.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422493561","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 ('matches', '0007_eventtype_has_commentary'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='eventtype',\n name='glyph_colour',\n field=models.CharField(max_length=50, blank=True, null=True),\n ),\n migrations.AddField(\n model_name='eventtype',\n name='glyph_name',\n field=models.CharField(max_length=50, blank=True, null=True),\n ),\n ]\n","sub_path":"matches/migrations/0008_auto_20150804_1434.py","file_name":"0008_auto_20150804_1434.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"654087757","text":"from stock_prediction import create_model, load_data, np\nfrom parameters import *\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\nimport pandas as pd\n\nTEST_TICKER = \"FB\"#\"TSLA\" #\"FSLY\" #\"SQ\" #\"QS\" #\"FSLY\" #\"FB\" \"NET\" \"XPEV\" \"NIO\" \"SPWR\" \"SOLO\"\nTEST_FROM_DAYS_AG0 = 200\nTEST_VALIDATION_DAYS = 5\n\ndef plot_graph(model, data):\n y_test = data[\"y_test\"]\n X_test = data[\"X_test\"]\n y_pred = model.predict(X_test)\n ##y_test = np.squeeze(data[\"column_scaler\"][PREDICT_FIELD].inverse_transform(np.expand_dims(y_test, axis=0)))\n ##y_pred = np.squeeze(data[\"column_scaler\"][PREDICT_FIELD].inverse_transform(y_pred))\n plt.plot(y_test[-200:], c='g', linestyle=\"\", marker=\"o\")\n plt.plot(y_pred[-200:], c='r', linestyle=\"\", marker=\"o\")\n plt.xlabel(\"Days\")\n plt.ylabel(\"Value\")\n plt.legend([\"Actual \", \"Predicted \"])\n\n #my#\n # 0 1 advance/decline logRegression\n prediction_matches = []\n #realv = data[\"df\"][-len(data[\"y_test\"]):]\n #realv = list(realv[PREDICT_FIELD])\n #predictedv = y_pred #y_test#data[\"y_test\"]\n # p = [x for x in zip(predictedv, realv)]\n # for pr in p: #todo rule? if prev2,3*0 ->then 0=1 (swap direction for each subsequent 0 in series (until 1 observed->resetAdvisor))\n # if pr[0] > 0.5 and pr[1] == 1: #todo remove? 0.5\n # prediction_matches.append(1)\n # elif pr[0] > 0.5 and pr[1] == 0:\n # prediction_matches.append(0)\n # elif pr[0] < 0.5 and pr[1] == 0:\n # prediction_matches.append(1)\n # elif pr[0] < 0.5 and pr[1] == 1:\n # prediction_matches.append(0)\n #good = len([x for x in prediction_matches if x==1 ])\n #print(\"%s matches from total %s %s\" % (good, len(prediction_matches), good/len(prediction_matches)))\n #print(prediction_matches) #to do np.where>0.5\n #print(y_test)\n #print(y_pred)\n\n #my#\n\n plt.show()\n\n\ndef get_accuracy(model, data):\n y_test = data[\"y_test\"]\n X_test = data[\"X_test\"]\n y_pred = model.predict(X_test)\n y_test_before_inverse = y_test\n y_pred_before_inverse = y_pred\n y_test = np.squeeze(data[\"column_scaler\"][PREDICT_FIELD].inverse_transform(np.expand_dims(y_test, axis=0)))\n y_pred = np.squeeze(data[\"column_scaler\"][PREDICT_FIELD].inverse_transform(y_pred))\n y_pred = list(map(lambda current, future: int(float(future) > float(current)), y_test[:-LOOKUP_STEP], y_pred[LOOKUP_STEP:]))\n y_test = list(map(lambda current, future: int(float(future) > float(current)), y_test[:-LOOKUP_STEP], y_test[LOOKUP_STEP:]))\n\n #my\n df_train_len = len(data[\"X_train\"])\n df_test_len = len(y_test)\n print('Before inverse data[\"y_test\"]', data[\"y_test\"])\n print(len(y_test), \" tested___ \", y_test)\n print(len(y_pred), \" predicted \", y_pred)\n df_test_dates = data[\"df\"].index[df_train_len+LOOKUP_STEP: df_train_len + LOOKUP_STEP + df_test_len] # axes[0].values() # DatetimeIndex\n print(\"Predict for next {} date: \".format(LOOKUP_STEP) + pd.Series(df_test_dates.format()))\n periods = 15\n print(\"Last {}d\\nActual :{}\\nPredicted:{}\".format(periods, y_test[-periods:], y_pred[-periods:]))\n\n #remove added dummy dates todo param\n # remove_days = -92\n # print(\"Predict for next {} date: \".format(LOOKUP_STEP) + pd.Series(df_test_dates.format())[:remove_days])\n # y_pred = y_pred[:remove_days]\n # y_test = y_test[:remove_days]\n #\n return accuracy_score(y_test, y_pred)\n\n\ndef predict(model, data):\n # retrieve the last sequence from data\n last_sequence = data[\"last_sequence\"][-N_STEPS:]\n # retrieve the column scalers\n column_scaler = data[\"column_scaler\"]\n # reshape the last sequence\n last_sequence = last_sequence.reshape((last_sequence.shape[1], last_sequence.shape[0]))\n # expand dimension\n last_sequence = np.expand_dims(last_sequence, axis=0)\n # get the prediction (scaled from 0 to 1)\n prediction = model.predict(last_sequence)\n # get the price (by inverting the scaling)\n predicted_price = column_scaler[PREDICT_FIELD].inverse_transform(prediction)[0][0]\n return predicted_price\n\n\n# load the data\ndata = load_data(TEST_TICKER, N_STEPS, lookup_step=LOOKUP_STEP, test_size=TEST_SIZE,\n feature_columns=FEATURE_COLUMNS, shuffle=False)\n\n# construct the model\nmodel = create_model(N_STEPS, loss=LOSS, units=UNITS, cell=CELL, n_layers=N_LAYERS,\n dropout=DROPOUT, optimizer=OPTIMIZER, bidirectional=BIDIRECTIONAL)\n\nmodel_path = os.path.join(\"results\", model_name) + \".h5\"\nmodel.load_weights(model_path)\n\n# evaluate the model\nmse, mae = model.evaluate(data[\"X_test\"], data[\"y_test\"], verbose=0)\n# calculate the mean absolute error (inverse scaling)\nmean_absolute_error = data[\"column_scaler\"][PREDICT_FIELD].inverse_transform([[mae]])[0][0]\nprint(\"### Ticker: \" + TEST_TICKER)\nprint(\"Mean Absolute Error:\", mean_absolute_error)\n# predict the future price\nfuture_price = predict(model, data)\n##print(f\"Future price after {LOOKUP_STEP} days is {future_price:.2f}$\")\nprint(\"Future price after {} days is {}$\".format(LOOKUP_STEP, future_price))\nprint(\"Accuracy Score (%s data points) :\" % len(data), get_accuracy(model, data))\nplot_graph(model, data)\n\n\nTEST_TICKERS = [\"TSLA\", \"SQ\", \"FB\", \"KODK\"] #crypto, fx\nTEST_MODEL = \"TODO\"\nTEST_MODEL_BATCH_PERIOD = 3 #20 #3-5 20-60 # sequence/batch learning model\nTEST_START_PERIOD_DAYS_BACK = 60\nTEST_VALIDATION_SIZE_FORWARD = 7\nTEST_PREDICT_PERIOD_DAYS_FORWARD = 1 #2-5-7\n\n#for tkr in TEST_TICKERS:\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"83335948","text":"\"\"\"init tables\n\nRevision ID: 2dbf653aa7b7\nRevises:\nCreate Date: 2021-06-26 00:26:27.028714\n\n\"\"\"\nimport sqlalchemy as sa\n\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"2dbf653aa7b7\"\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"users\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"username\", sa.String(length=20), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"username\"),\n )\n\n op.create_table(\n \"songs\",\n sa.Column(\"id\", sa.Integer(), autoincrement=True, nullable=False),\n sa.Column(\"user_id\", sa.Integer(), nullable=True),\n sa.Column(\"title\", sa.String(length=100), nullable=False),\n sa.Column(\"chords\", sa.String(), nullable=True),\n sa.Column(\"strumming\", sa.String(), nullable=True),\n sa.Column(\"lyrics\", sa.String(), nullable=True),\n sa.ForeignKeyConstraint(\n [\"user_id\"],\n [\"users.id\"],\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"title\"),\n )\n\n\ndef downgrade():\n op.drop_table(\"songs\")\n op.drop_table(\"users\")\n","sub_path":"alembic/versions/2dbf653aa7b7_init_tables.py","file_name":"2dbf653aa7b7_init_tables.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"323208600","text":"# import packages\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader, TensorDataset\nimport torchvision.transforms as transforms\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#%matplotlib inline\n\nfrom json import JSONDecoder, JSONDecodeError # for reading the JSON data files\nimport re # for regular expressions\nimport os # for os related operations\n\n\n# I delaborately list all hyperparameters to remind myself of the architecture and arguments for each layer.\n\n# Hyperparameters\nnum_classes = 1\nnum_features = 14 # number of 'color' channels for the input 1D 'image'\ntime_steps = 60 # number of pixels for the input 1D 'image'\n\n# all features\nfeature_names = ['TOTUSJH', 'TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'ABSNJZH', 'SAVNCPP', 'USFLUX', 'TOTFZ', 'MEANPOT', 'EPSZ',\n 'MEANSHR', 'SHRGT45', 'MEANGAM', 'MEANGBT', 'MEANGBZ', 'MEANGBH', 'MEANJZH', 'TOTFY', 'MEANJZD',\n 'MEANALP', 'TOTFX', 'EPSY', 'EPSX', 'R_VALUE', 'XR_MAX']\n# relevent features by Fischer ranking score and manually looking at the histograms in positive and negative classes.\n# I choose those features with reletively high Fischer ranking score & those whose histograms look different in\n# positive and negative classes.\n# I further drop features according to their physical definitions. When some features' definitions are related to each\n# other, I first double check their correlation by looking at their scatter plot. If their correlation is confirmed visually,\n# I drop n number features from the correlated features if there are n confirmed correlations.\nrelevant_features_0 = ['TOTUSJH','TOTBSQ','TOTPOT','TOTUSJZ','ABSNJZH','SAVNCPP','USFLUX','TOTFZ',\n 'EPSZ','MEANSHR','SHRGT45','MEANGAM','MEANGBT','MEANGBZ','MEANGBH','MEANJZD','R_VALUE']\n\n# By observing the histograms of relevant features, their histograms can be grouped into four categories.\n# right skewed with extreme outliers, right skewed without extreme outliers, left skewed with extreme outliers, non skewed\nright_skewed_features = ['TOTUSJH', 'TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'ABSNJZH', 'SAVNCPP', 'USFLUX', 'EPSZ', 'MEANSHR', 'MEANGAM', 'MEANGBH', 'MEANJZD']\nright_skewed_features_with_ol = ['TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'SAVNCPP', 'USFLUX', 'MEANSHR', 'MEANGAM', 'MEANGBH', 'MEANJZD']\nright_skewed_features_without_ol = ['TOTUSJH', 'ABSNJZH', 'EPSZ']\nleft_skewed_features_with_ol = ['TOTFZ']\nnon_skewed_features = ['MEANGBT', 'R_VALUE']\n\n# I further decide that TOTFZ is correlated with EPSZ and TOTBSQ. Furthermore, TOTFZ cannot be well scaled yet, I\n# decide to drop it for now. Note that TOTFZ is the only feature in the list `left_skewed_with_ol`. In the end, I select\n# 14 features for fitting the data, their names are stored in the list called `selected_features`.\nselected_features = right_skewed_features + non_skewed_features\nprint('{} are selected for training.'.format(len(selected_features)))\nprint('selected features include \\n',selected_features)\n\n# get the indice for features\nindice_right_skewed_with_ol = []\nindice_right_skewed_without_ol = []\nindice_non_skewed = []\nfor i in range(0,len(selected_features)):\n if selected_features[i] in right_skewed_features_with_ol:\n indice_right_skewed_with_ol.append(i)\n elif selected_features[i] in right_skewed_features_without_ol:\n indice_right_skewed_without_ol.append(i)\n elif selected_features[i] in non_skewed_features:\n indice_non_skewed.append(i)\n\n\nscale_params_right_skewed = pd.read_csv('scale_params_right_skewed.csv')\nscale_params_right_skewed.set_index('Unnamed: 0', inplace=True)\n\nscale_params_non_skewed = pd.read_csv('scale_params_non_skewed.csv')\nscale_params_non_skewed.set_index('Unnamed: 0', inplace=True)\n\n\n# all features\nfeature_names = ['TOTUSJH', 'TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'ABSNJZH', 'SAVNCPP', 'USFLUX', 'TOTFZ', 'MEANPOT', 'EPSZ',\n 'MEANSHR', 'SHRGT45', 'MEANGAM', 'MEANGBT', 'MEANGBZ', 'MEANGBH', 'MEANJZH', 'TOTFY', 'MEANJZD',\n 'MEANALP', 'TOTFX', 'EPSY', 'EPSX', 'R_VALUE', 'XR_MAX']\n# relevent features by Fischer ranking score and manually looking at the histograms in positive and negative classes.\n# I choose those features with reletively high Fischer ranking score & those whose histograms look different in\n# positive and negative classes.\n# I further drop features according to their physical definitions. When some features' definitions are related to each\n# other, I first double check their correlation by looking at their scatter plot. If their correlation is confirmed visually,\n# I drop n number features from the correlated features if there are n confirmed correlations.\nrelevant_features_0 = ['TOTUSJH','TOTBSQ','TOTPOT','TOTUSJZ','ABSNJZH','SAVNCPP','USFLUX','TOTFZ',\n 'EPSZ','MEANSHR','SHRGT45','MEANGAM','MEANGBT','MEANGBZ','MEANGBH','MEANJZD','R_VALUE']\n\n# By observing the histograms of relevant features, their histograms can be grouped into four categories.\n# right skewed with extreme outliers, right skewed without extreme outliers, left skewed with extreme outliers, non skewed\nright_skewed_features = ['TOTUSJH', 'TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'ABSNJZH', 'SAVNCPP', 'USFLUX', 'EPSZ', 'MEANSHR', 'MEANGAM', 'MEANGBH', 'MEANJZD']\nright_skewed_features_with_ol = ['TOTBSQ', 'TOTPOT', 'TOTUSJZ', 'SAVNCPP', 'USFLUX', 'MEANSHR', 'MEANGAM', 'MEANGBH', 'MEANJZD']\nright_skewed_features_without_ol = ['TOTUSJH', 'ABSNJZH', 'EPSZ']\nleft_skewed_features_with_ol = ['TOTFZ']\nnon_skewed_features = ['MEANGBT', 'R_VALUE']\n\n# I further decide that TOTFZ is correlated with EPSZ and TOTBSQ. Furthermore, TOTFZ cannot be well scaled yet, I\n# decide to drop it for now. Note that TOTFZ is the only feature in the list `left_skewed_with_ol`. In the end, I select\n# 14 features for fitting the data, their names are stored in the list called `selected_features`.\nselected_features = right_skewed_features + non_skewed_features\nprint('{} are selected for training.'.format(len(selected_features)))\nprint('selected features include \\n',selected_features)\n\n# get the indice for features\nindice_right_skewed_with_ol = []\nindice_right_skewed_without_ol = []\nindice_non_skewed = []\nfor i in range(0,len(selected_features)):\n if selected_features[i] in right_skewed_features_with_ol:\n indice_right_skewed_with_ol.append(i)\n elif selected_features[i] in right_skewed_features_without_ol:\n indice_right_skewed_without_ol.append(i)\n elif selected_features[i] in non_skewed_features:\n indice_non_skewed.append(i)\n\n\nscale_params_right_skewed = pd.read_csv('scale_params_right_skewed.csv')\nscale_params_right_skewed.set_index('Unnamed: 0', inplace=True)\n\nscale_params_non_skewed = pd.read_csv('scale_params_non_skewed.csv')\nscale_params_non_skewed.set_index('Unnamed: 0', inplace=True)\n\n# define read-in functions\ndef decode_obj(line, pos=0, decoder=JSONDecoder()):\n no_white_space_regex = re.compile(r'[^\\s]')\n while True:\n match = no_white_space_regex.search(line, pos)\n # line is a long string with data type `str`\n if not match:\n # if the line is full of white space, get out of this func\n return\n # pos will be the position for the first non-white-space character in the `line`.\n pos = match.start()\n try:\n # JSONDecoder().raw_decode(line,pos) would return a tuple (obj, pos)\n # obj is a dict, and pos is an int\n # not sure how the pos is counted in this case, but it is not used anyway.\n obj, pos = decoder.raw_decode(line, pos)\n # obj = {'id': 1, 'classNum': 1, 'values',feature_dic}\n # here feature_dic is a dict with all features.\n # its key is feature name as a str\n # its value is a dict {\"0\": float, ..., \"59\": float}\n except JSONDecodeError as err:\n print('Oops! something went wrong. Error: {}'.format(err))\n # read about difference between yield and return\n # with `yield`, obj won't be assigned until it is used\n # Once it is used, it is forgotten.\n yield obj\n\ndef get_obj_with_last_n_val(line, n):\n # since decode_obj(line) is a generator\n # next(generator) would execute this generator and returns its content\n obj = next(decode_obj(line)) # type:dict\n id = obj['id']\n class_label = obj['classNum']\n\n data = pd.DataFrame.from_dict(obj['values']) # type:pd.DataFrame\n data.set_index(data.index.astype(int), inplace=True)\n last_n_indices = np.arange(0, 60)[-n:]\n data = data.loc[last_n_indices]\n\n return {'id': id, 'classType': class_label, 'values': data}\n\ndef convert_json_data_to_nparray(data_dir: str, file_name: str, features):\n \"\"\"\n Generates a dataframe by concatenating the last values of each\n multi-variate time series. This method is designed as an example\n to show how a json object can be converted into a csv file.\n :param data_dir: the path to the data directory.\n :param file_name: name of the file to be read, with the extension.\n :return: the generated dataframe.\n \"\"\"\n fname = os.path.join(data_dir, file_name)\n\n all_df, labels, ids = [], [], []\n with open(fname, 'r') as infile: # Open the file for reading\n for line in infile: # Each 'line' is one MVTS with its single label (0 or 1).\n obj = get_obj_with_last_n_val(line, 60) # obj is a dictionary\n\n # if the classType in the sample is NaN, we do not read in this sample\n if np.isnan(obj['classType']):\n pass\n else:\n # a pd.DataFrame with shape = time_steps x number of features\n # here time_steps = 60, and # of features are the length of the list `features`.\n df_selected_features = obj['values'][features]\n\n # a list of np.array, each has shape=time_steps x number of features\n # I use DataFrame here so that the feature name is contained, which we need later for\n # scaling features.\n all_df.append(np.array(df_selected_features))\n\n labels.append(obj['classType']) # list of integers, each integer is either 1 or 0\n ids.append(obj['id']) # list of integers\n\n# df = pd.concat(all_df).reset_index(drop=True)\n# df = df.assign(LABEL=pd.Series(labels))\n# df = df.assign(ID=pd.Series(ids))\n# df.set_index([pd.Index(ids)])\n # Uncomment if you want to save this as CSV\n #df.to_csv(file_name + '_last_vals.csv', index=False)\n return all_df, labels, ids\n\n\nprint('Files contained in the ../input directiory include:')\nprint(os.listdir(\"../input\"))\n\npath_to_data = \"../input\"\nfile_name = \"fold3Training.json\"\nfname = os.path.join(path_to_data,file_name)\n\n# Read in all data in a single file\nall_input, labels, ids = convert_json_data_to_nparray(path_to_data, file_name, selected_features)\n\n# Change X and y to numpy.array in the correct shape.\nX = np.array(all_input)\ny = np.array([labels]).T\nprint(\"The shape of X is (sample_size x time_steps x feature_num) = {}.\".format(X.shape))\nprint(\"the shape of y is (sample_size x 1) = {}, because it is a binary classification.\".format(y.shape))\n\n# Scale and fillin NaN\ndef scale_features(X, selected_features, nan_to=0.0):\n X_copy = X.copy() # make a copy of X, must use np.array.copy(), otherwise if use X_copy = X, X_copy would point to the same memory, and once X or X_copy gets changed, both will change.\n for i in range(0,len(selected_features)):\n feature = selected_features[i] # str, feature name\n # right skewed with extreme outliers\n if feature in right_skewed_features_with_ol:\n x_min, y_median, y_IQR = scale_params_right_skewed.loc[['x_min','y_median','y_IQR'],feature]\n x = X[:,:,i] # n_sample x time_steps x 1\n# x = np.nan_to_num(x, nan=nan_to)\n y = np.log(x - x_min + 1.0)\n z = (y - y_median)/y_IQR\n X_copy[:,:,i] = np.nan_to_num(z,nan=nan_to) #,posinf=inf_to,neginf=-inf_to)\n # right skewed without extreme outliers\n elif feature in right_skewed_features_without_ol:\n x_min, y_mean, y_std = scale_params_right_skewed.loc[['x_min','y_mean','y_std'],feature]\n x = X[:,:,i]\n# x = np.nan_to_num(x, nan=nan_to)\n y = np.log(x-x_min+1.0)\n z = (y - y_mean)/y_std\n X_copy[:,:,i] = np.nan_to_num(z,nan=nan_to) #,posinf=inf_to,neginf=-inf_to)\n # non_skewed features, they do not have extreme outliers\n elif feature in non_skewed_features:\n x_mean, x_std = scale_params_non_skewed.loc[['x_mean','x_std'],feature]\n x = X[:,:,i]\n# x = np.nan_to_num(x,nan=nan_to)\n X_copy[:,:,i] = np.nan_to_num((x - x_mean)/x_std,nan=nan_to) #,posinf=inf_to,neginf=-inf_to)\n else:\n print(feature+' is not found, and thus not scaled.')\n\n return X_copy\n\n# Scale X\nX_scaled = scale_features(X, selected_features)\n\n# Save X_scaled and y\n# np.save('../input/X_scaled.npy', X_scaled)\n# np.save('../input/y.npy',y)\n\n# Split train and validation\nval_fraction = 0.33\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, y_train, y_val = train_test_split(X_scaled, y, test_size=val_fraction, random_state=0)\n","sub_path":"Feature_Scaling_Snippet.py","file_name":"Feature_Scaling_Snippet.py","file_ext":"py","file_size_in_byte":13353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"98737552","text":"\n# This script was written in Python 3.3.5.\nfrom bibtexparser import loads\nfrom os import walk\nfrom os.path import expanduser, join, splitext\nfrom re import search\nfrom textwrap import TextWrapper\n\nverbose = True\n\ndestpath = '~/Dropbox/School/references'\n\ndestpath = expanduser(destpath)\nbasepath = '{}/lib'.format(destpath)\nbibfn = 'bibliography.bib'\norgfn = 'references.org'\n\ndef write_headline(f, n, s):\n f.write('*' * n)\n f.write(' {}'.format(s))\n f.write('\\n')\n\nn = len(basepath)\n\nbibfile = join(destpath, bibfn)\nf = open(bibfile, 'w')\nf.write('\\n')\n\norgfile = join(destpath, orgfn)\ng = open(orgfile, 'w')\ng.write('#+title: References\\n\\n')\n\n\n\nexclude_dirs = ['.git', 'tmp']\nfor (dirpath, dirnames, filenames) in walk(basepath):\n if len(filenames) == 0 and len(dirnames) == 0:\n if verbose:\n print(\"Skipping empty directory {}\".format(dirpath))\n pass\n\n dirnames[:] = [d for d in dirnames if d not in exclude_dirs]\n\n ## org-mode headings\n if len(dirpath) > n and dirpath[:n] == basepath:\n dirs = dirpath[n:]\n categories = dirs.split('/')[1:]\n category = categories[-1]\n depth = len(categories)\n\n\n bibs = [fn for fn in filenames if search('\\.bib', fn) is not None]\n pdfs = [fn for fn in filenames if search('\\.pdf', fn) is not None]\n notes = [fn for fn in filenames\n if search('\\.md', fn) is not None\n or search('\\.org', fn) is not None]\n\n # Directories containing a paper:\n if len(bibs) == 1 and len(pdfs) == 1:\n bib = bibs[0]\n pdf = pdfs[0]\n if len(notes) > 0:\n note = notes[0]\n else:\n note = '{}.org'.format(splitext(pdf)[0])\n\n with open(join(dirpath, bib)) as h:\n bib_txt = h.read()\n bib_db = loads(bib_txt)\n\n if len(bib_db.entries) > 1:\n print('Too many entries in')\n print('{}...'.format(join(dirpath, bib)[n:]))\n print('Using first entry.')\n\n entry = bib_db.entries[0]\n title = entry['title'].replace('``', '\"').replace(\"''\", '\"')\n\n write_headline(g, depth, entry['ID'])\n\n wrapper = TextWrapper(initial_indent = '{} * '.format(' ' * depth),\n subsequent_indent = ' ' * (depth+3))\n g.write(wrapper.fill('{0}. ({1}).'.format(title, entry['year'])))\n g.write('\\n')\n g.write(wrapper.fill(entry['author']))\n g.write('\\n')\n g.write('\\n')\n\n\n # Links to the files\n options1 = '* [[file:{}][PDF]]'\n options2 = '* [[file:{}][.bib]]'\n options3 = '* [[file:{}][Notes]]'\n\n g.write(' ' * (depth+1))\n g.write(options1.format(join(dirpath, pdf)))\n g.write('\\n')\n g.write(' ' * (depth+1))\n g.write(options2.format(join(dirpath, bib)))\n g.write('\\n')\n g.write(' ' * (depth+1))\n g.write(options3.format(join(dirpath, note)))\n g.write('\\n')\n\n # Add the contents of the .bib to the master .bib file\n f.write(bib_txt)\n elif len(pdfs) == 1:\n pdf = pdfs[0]\n if len(notes) > 0:\n note = notes[0]\n else:\n note = '{}.org'.format(splitext(pdf)[0])\n\n write_headline(g, depth, pdf)\n\n options1 = '* [[file:{}][PDF]]'\n options3 = '* [[file:{}][Notes]]'\n\n g.write(' ' * (depth+1))\n g.write(options1.format(join(dirpath, pdf)))\n g.write('\\n')\n g.write(' ' * (depth+1))\n g.write(options3.format(join(dirpath, note)))\n g.write('\\n')\n elif len(bibs) == 1:\n bib = bibs[0]\n if len(notes) > 0:\n note = notes[0]\n else:\n note = '{}.org'.format(splitext(bib)[0])\n\n with open(join(dirpath, bib)) as h:\n bib_txt = h.read()\n bib_db = loads(bib_txt)\n\n if len(bib_db.entries) > 1:\n print('Too many entries in')\n print('{}...'.format(join(dirpath, bib)[n:]))\n print('Using first entry.')\n\n entry = bib_db.entries[0]\n title = entry['title'].replace('``', '\"').replace(\"''\", '\"')\n\n write_headline(g, depth, entry['ID'])\n\n wrapper = TextWrapper(initial_indent = '{} * '.format(' ' * depth),\n subsequent_indent = ' ' * (depth+3))\n g.write(wrapper.fill('{0}. ({1}).'.format(title, entry['year'])))\n g.write('\\n')\n g.write(wrapper.fill(entry['author']))\n g.write('\\n')\n g.write('\\n')\n\n\n # Links to the files\n options2 = '* [[file:{}][.bib]]'\n options3 = '* [[file:{}][Notes]]'\n\n g.write(' ' * (depth+1))\n g.write(options2.format(join(dirpath, bib)))\n g.write('\\n')\n g.write(' ' * (depth+1))\n g.write(options3.format(join(dirpath, note)))\n g.write('\\n')\n\n # Add the contents of the .bib to the master .bib file\n f.write(bib_txt)\n elif (len(bibs) > 1 or len(pdfs) > 1) and not dirpath == basepath:\n if verbose:\n print(\"Bossman, something weird goin' on in directory {}\".format(dirpath))\n print(\"Too many files!\")\n else:\n write_headline(g, depth, category)\n\ng.close()\nf.close()\n\n","sub_path":"build-bib.py","file_name":"build-bib.py","file_ext":"py","file_size_in_byte":5590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"28525816","text":"# Opus/UrbanSim urban simulation software.\r\n# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington\r\n# See opus_core/LICENSE \r\n\r\nimport os\r\n\r\nfrom opus_core.database_management.configurations.estimation_database_configuration import EstimationDatabaseConfiguration\r\nfrom opus_core.configurations.dataset_pool_configuration import DatasetPoolConfiguration\r\n\r\n\r\nmy_configuration = {\r\n 'cache_directory' : 'C:/urbansim_cache/psrc/estimation', # change or leave out\r\n 'estimation_database_configuration': EstimationDatabaseConfiguration(\r\n database_name = 'GSPSRC_2000_baseyear_change_20070102',\r\n ),\r\n 'dataset_pool_configuration': DatasetPoolConfiguration(\r\n package_order=['psrc', 'urbansim', 'opus_core'],\r\n ),\r\n 'datasets_to_cache_after_each_model':[],\r\n 'low_memory_mode':False,\r\n 'base_year': 2000,\r\n 'years': (2000,2000), \r\n }","sub_path":"psrc/estimation/my_estimation_config.py","file_name":"my_estimation_config.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"559004366","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.base, name='base'),\n\turl(r'^recreational$', views.viewRecreational, name='viewRecreational'),\n\turl(r'^small$', views.viewSmall, name='viewSmall'),\n\turl(r'^free$', views.viewFree, name='viewFree'),\n]\n","sub_path":"uavcas/courseinfo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"10550052","text":"R,C = map(int,input().split())\nmatrix = [list(map(int,input().split())) for row in range(R)]\nK = int(input())\nrow,col=-1,-1\nfor i in range(R):\n for j in range(C):\n if i==0 or i==R-1 or j==0 or j==C-1:\n if matrix[i][j] == K and row == -1 and col == -1:\n row = i\n col = j \nif row == -1 and col == -1 :\n print(-1)\n exit()\n\nsize = (R*2) + ((C-2)*2) \nborder,ind= [],-1\ni1,j1=0,0\n\nfor i in range(0,size):\n if i1==row and j1==col:\n ind = i \n border.append(matrix[i1][j1])\n if i1==0 and j1==0:\n j1+=1 \n elif i1 ==0 and j1 == C-1:\n i1+=1\n elif i1==R-1 and j1==C-1:\n j1-=1\n elif i1==R-1 and j1==0:\n i1-=1\n elif i1==0:\n j1+=1\n elif j1==C-1:\n i1+=1\n elif i1==R-1:\n j1-=1\n elif j1==0:\n i1-=1\n\nleft,right,l=ind,ind,size \nwhile size>0:\n ind1 = left%l\n ind2 = right%l \n if ind1 == ind2:\n print(border[ind1],end=\" \")\n size-=1 \n else:\n print(border[ind1],end=\" \")\n print(border[ind2],end=\" \")\n size-=2\n if left==0:\n left=l \n left-=1\n right+=1\n\n\n\n\n\n\n'''\n5 5\n74 21 77 95 58\n97 21 35 98 73\n94 23 39 38 14\n64 47 17 58 54\n38 61 22 72 25\n54\n\n'''\n\n\n","sub_path":"11-6-2021.py","file_name":"11-6-2021.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362340363","text":"#!/home/labinm_robotica/.virtualenvs/cv/bin/python\nimport pickle\nimport cv2\n#from Sampling_app import Sample,colorize\nimport libseedlingdb as seedb\nfrom libseedlingdb import Sample\nimport os\nimport time\nimport numpy as np\nimport pyrealsense2 as rs\nfrom sklearn.cluster import KMeans\n\n_distance=0.46 #ground distance or max distance\n_seedlingheight=0.28 #minimum distance\n\n#set depth camera parameters\ndistance=0.359\ndepth_scale=9.999999747378752e-05\nintrinsics=rs.intrinsics()\nintrinsics.width=1280\nintrinsics.height=720\nintrinsics.ppx=639.399\nintrinsics.ppy=350.551\nintrinsics.fx=906.286\nintrinsics.fy=905.369\nintrinsics.model=rs.distortion.inverse_brown_conrady\nintrinsics.coeffs=[0.0,0.0,0.0,0.0,0.0]\n\ndef colorize(depth_image):\n d_image=depth_image.astype(np.float)\n _min=_seedlingheight #_distance-_seedlingheight\n _max=_distance\n normalized=255.0*(d_image-_min)/(_max-_min)\n normalized=np.clip(normalized,0,255).astype(np.uint8)\n colorized=cv2.applyColorMap(normalized,cv2.COLORMAP_JET)\n return colorized\n\n#It's possible to click on the depth image in order to know the spatial position of a pixel.\ndef click_depth_rgb(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n d_image = depth.astype(np.float)\n point = rs.rs2_deproject_pixel_to_point(intrinsics, [y, x], d_image[y, x])\n #print(\"X= {x}, Y={y}, Z={z}\".format(x=100 * point[0], y=100 * point[1], z=100 * point[2]))\n print(\"X= {x}, Y={y}, Z={z}, H={h}, S={s}\".format(x=y, y=x, z=point[2],h=cimage_hsv[y-pinit[0],x-pinit[1],0],s=cimage_hsv[y-pinit[0],x-pinit[1],1]))\n return\n\n\n\n\n#Set the dataset folder\nfolder=\"/home/amaranth/Desktop/Robot_UPAO/seedling_dataset_11_01_20/\"\n\n#GUI and mouse\ncv2.namedWindow(\"depthimage\")\ncv2.setMouseCallback(\"depthimage\", click_depth_rgb)\n\n#Set the sample number\nsample_num=57\n\n#Open the sample\nDB=seedb.seedling_dataset(folder)\nsample=DB.read_sample(sample_num)\ndepth=sample.depth\ndepth_rgb=sample.toprgb\ncolorized=colorize(depth)\n\n#Segment rgb image using depth information\n\"\"\"\nbinarized_coords=zip(*np.where((depth<0.41)&(depth>0.28)))# pixels between 3cm and 33 cm\nbinarized_coords=list(binarized_coords)\n\ninvalid_coords=zip(*np.where(depth<0.28))\ninvalid_coords=list(invalid_coords)\n\nout_coords=zip(*np.where(depth>0.41))\nout_coords=list(out_coords)\n\nbinarized_rgb=np.zeros(depth_rgb.shape,dtype=np.uint8)\nmask=np.zeros(depth.shape,dtype=np.uint8)\n\nfor coord in binarized_coords:\n binarized_rgb[coord[0],coord[1]]= depth_rgb[coord[0],coord[1]]\n #mask[coord[0],coord[1]]=255\n\nfor coord in invalid_coords:\n binarized_rgb[coord[0],coord[1]]= [0,0,255]\n\nfor coord in out_coords:\n binarized_rgb[coord[0],coord[1]]= [255,0,0]\n\"\"\"\n\npinit=[450,410]\n#\"\"\"\n#CREATING THE TRAINING MATRIX\ncropped_rgb=depth_rgb[450:,410:1070]\ncimage_hsv=cv2.cvtColor(cropped_rgb,cv2.COLOR_BGR2HSV)\nprint(cimage_hsv.shape)\n\nX=[]\nfor i in range(cropped_rgb.shape[0]):\n for j in range(cropped_rgb.shape[1]):\n X.append([cimage_hsv[i,j,0],cimage_hsv[i,j,1],depth[i+pinit[0],j+pinit[1]]])\n\nX=np.array(X)\nprint(X.shape)\nnp.save(\"cropped_data.npy\",X)\n#\"\"\"\n\n#\"\"\"\n#TRAINING THE MODEL\ninits=np.array([[15,31,577-pinit[0],498-pinit[1],0.0],[13,46,533-pinit[0],535-pinit[1],0.574],[36,153,568-pinit[0],540-pinit[1],0.358],[53,43,578-pinit[0],758-pinit[1],0.3923],[38,119,571-pinit[0],953-pinit[1],0.3753]])\nX=np.load(\"cropped_data.npy\")\nkmeans=KMeans(6,random_state=0).fit(X)\nseg_img=np.resize(kmeans.labels_,(270,660,1))\n#\"\"\"\n\"\"\"\nseg_img=np.resize(kmeans.labels_,(270,660,1))\nimage=np.zeros((270,660,3),dtype=np.uint8)\nfor i in X:\n region=kmeans.predict([i])\n if region[0]==0:\n image[int(i[2]),int(i[3]),:]=[30,40,15]\n elif region[0]==1:\n image[int(i[2]),int(i[3]),:]=[80,50,45]\n elif region[0]==2:\n image[int(i[2]),int(i[3]),:]=[10,140,150]\n elif region[0]==3:\n image[int(i[2]),int(i[3]),:]=[90,180,54]\n elif region[0]==4:\n image[int(i[2]),int(i[3]),:]=[63,87,190]\n\"\"\"\n\n#\"\"\"\nB= np.where(seg_img==0,30,seg_img)\nB= np.where(B==1,30,B)\nB= np.where(B==2,100,B)\nB= np.where(B==3,100,B)\nB= np.where(B==4,150,B)\nB= np.where(B==5,150,B)\nprint(B.shape)\n\nR= np.where(seg_img==0,30,seg_img)\nR= np.where(R==1,80,R)\nR= np.where(R==2,100,R)\nR= np.where(R==3,150,R)\nR= np.where(R==4,200,R)\nR= np.where(R==5,220,R)\nprint(R.shape)\n\nG= np.where(seg_img==0,120,seg_img)\nG= np.where(G==1,90,G)\nG= np.where(G==2,60,G)\nG= np.where(G==3,30,G)\nG= np.where(G==4,0,G)\nG= np.where(G==5,190,G)\nprint(G.shape)\n#\"\"\"\n\nimage=cv2.merge((B,G,R))\nimage=image.astype(np.uint8)\nprint(image.dtype)\n\n\n#Show the results\n#binarized_rgb=cv2.bitwise_or(depth_rgb,depth_rgb,mask=mask)\ncv2.imshow(\"original\",depth_rgb)\ncv2.imshow(\"depthimage\",image)\n#cv2.imshow(\"mask\",mask)\n#cv2.imwrite(\"segmented_images/mask{}.jpg\".format(sample_num),mask)\n#cv2.imwrite(\"segmented_images/seedlingimg{}.jpg\".format(sample_num),depth_rgb)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","sub_path":"segmentation/kmeans_segmentation.py","file_name":"kmeans_segmentation.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"622454007","text":"\"\"\"\nMDB.\n\nhttps://github.com/GII/MDB\n\"\"\"\n\n# Python 2 compatibility imports\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom future import standard_library\n\nstandard_library.install_aliases()\nfrom builtins import * # noqa pylint: disable=unused-wildcard-import,wildcard-import\n\n# Standard imports\nimport math\n\n# Library imports\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import patches\n\n\n# Para el primer ejemplo debo cambiar cosas o tener en cuenta que, por ejemplo, en el vector de sensorizacion solo\n# debo considerar la distancia del baxter a la pelota y de la pelota a la caja\n\n\nclass Sim(object):\n \"\"\"\n Class that implements a Simulator.\n\n This simulator makes possible to make/test different experiments in a virtual scenario.\n It contains the two arms of the Baxter robot, the Robobo! robot, some boxes and a\n ball.\n\n The implemented methods allow the user to move both robots throw the scenario (with\n and without the ball), get distances and relative angles between the different objects\n and get/set the position of all of them.\n \"\"\"\n\n def __init__(self):\n \"\"\"Create the different objects present in the Simulator and place them in it\"\"\"\n self.ball = plt.Circle((1800, 300), 30, fc=\"r\", label=\"ball\")\n self.box1 = plt.Rectangle((1800, 450), 67, 67, fc=\"y\", linewidth=3.5, label=\"box1\")\n self.box2 = plt.Rectangle((2000, 900), 67, 67, fc=\"grey\", linewidth=3.5, label=\"box2\")\n self.robobo = patches.Rectangle((700, 300), 75, 60, angle=0.0, fc=\"cyan\", label=\"robobo\")\n self.robobo_act = patches.Rectangle((775, 300), 20, 60, angle=0.0, fc=\"blue\", label=\"robobo_actuator\")\n self.baxter_rarm = patches.Rectangle((2000, 50), 75, 60, angle=0.0, fc=(0.8, 0, 0.2), label=\"baxter_rarm\")\n self.baxter_rarm_act = patches.Rectangle((2075, 50), 20, 60, angle=0.0, fc=\"black\", label=\"baxter_rarm_act\")\n self.baxter_larm = patches.Rectangle((1600, 50), 75, 60, angle=0.0, fc=(0.8, 0, 0.2), label=\"baxter_larm\")\n self.baxter_larm_act = patches.Rectangle((1675, 50), 20, 60, angle=0.0, fc=\"black\", label=\"baxter_larm_act\")\n\n self.baxter_figure = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 1))\n self.baxter_figure_1 = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 0.8))\n self.baxter_figure_2 = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 0.6))\n self.baxter_figure_3 = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 0.4))\n self.baxter_figure_4 = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 0.2))\n self.baxter_figure_5 = patches.Circle((2700, 264), 12, fc=(0.8, 0, 0, 0.0))\n\n self.fig = plt.figure()\n self.fig.canvas.set_window_title(\"Simulator\")\n self.ax = plt.axes(xlim=(0, 3500), ylim=(0, 1000))\n self.ax.axes.get_xaxis().set_visible(False)\n self.ax.axes.get_yaxis().set_visible(False)\n\n # Movement boundaries\n plt.axvline(x=1250) # draw a default vline at x=1 that spans the yrange\n plt.axhline(y=800, xmin=0.357, xmax=0.686, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=50, xmin=0.0286, xmax=0.686, linestyle=\"--\", color=\"grey\")\n # plt.axhline(y=950, xmin=0.0286, xmax=0.357, linestyle='--', color='grey')\n plt.axhline(y=800, xmin=0.0286, xmax=0.357, linestyle=\"--\", color=\"grey\")\n # plt.axvline(x=100, ymin=0.05, ymax=0.95, linestyle='--', color='grey')\n plt.axvline(x=100, ymin=0.05, ymax=0.80, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=2400, ymin=0.05, ymax=0.80, linestyle=\"--\", color=\"grey\")\n self.ball_position = None # Indicates where is the ball: robobo, baxter_larm, bater_rarm, box1, box2 or None\n\n # Show figure and patches\n self.fig.show()\n self.ax.add_patch(self.box1)\n self.ax.add_patch(self.box2)\n self.ax.add_patch(self.robobo)\n self.ax.add_patch(self.robobo_act)\n # self.ax.add_patch(self.baxter_rarm)\n # self.ax.add_patch(self.baxter_rarm_act)\n self.ax.add_patch(self.baxter_larm)\n self.ax.add_patch(self.baxter_larm_act)\n self.ax.add_patch(self.ball)\n\n # plt.text(2700, 970, 'State Space')\n\n # Prueba espacio estados\n plt.axhline(y=950, xmin=0.771, xmax=0.967, linestyle=\"-\", color=\"black\", linewidth=1.3)\n plt.axhline(y=264, xmin=0.771, xmax=0.967, linestyle=\"-\", color=\"black\", linewidth=1.3)\n plt.axhline(y=364, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=464, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=564, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=664, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=764, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axhline(y=864, xmin=0.771, xmax=0.967, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=2700, ymin=0.264, ymax=0.950, linestyle=\"-\", color=\"black\", linewidth=1.3)\n plt.axvline(x=3386, ymin=0.264, ymax=0.950, linestyle=\"-\", color=\"black\", linewidth=1.3)\n plt.axvline(x=2800, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=2900, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=3000, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=3100, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=3200, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=3300, ymin=0.264, ymax=0.950, linestyle=\"--\", color=\"grey\")\n plt.axvline(x=2500)\n self.ax.add_patch(self.baxter_figure)\n self.ax.add_patch(self.baxter_figure_1)\n self.ax.add_patch(self.baxter_figure_2)\n self.ax.add_patch(self.baxter_figure_3)\n self.ax.add_patch(self.baxter_figure_4)\n self.ax.add_patch(self.baxter_figure_5)\n\n def ball_set_pos(self, pos):\n \"\"\"Set the ball center position\"\"\"\n (x, y) = pos\n self.ball.center = (x, y)\n # self.fig.canvas.draw()\n\n def box1_set_pos(self, pos):\n \"\"\"Set the box1 center position\"\"\"\n (x, y) = pos\n self.box1.xy = (x - self.box1.get_width() / 2, y - self.box1.get_height() / 2)\n # self.fig.canvas.draw()\n\n def box2_set_pos(self, pos):\n \"\"\"Set the box2 center position\"\"\"\n (x, y) = pos\n self.box2.xy = (x - self.box2.get_width() / 2, y - self.box2.get_height() / 2)\n # self.fig.canvas.draw()\n\n def robobo_set_pos(self, pos):\n \"\"\"Set the Robobo! center position (and its actuator) checking if it is inside its movement limits\"\"\"\n (x, y) = pos\n w = self.robobo.get_width()\n h = self.robobo.get_height()\n # New x, y position\n new_x = (\n x\n - w / 2 * math.cos(self.robobo._angle * math.pi / 180)\n + h / 2 * math.sin(self.robobo._angle * math.pi / 180)\n )\n new_y = (\n y\n - w / 2 * math.sin(self.robobo._angle * math.pi / 180)\n - h / 2 * math.cos(self.robobo._angle * math.pi / 180)\n )\n\n # Check if the new robobo position is inside its movement limits\n if self.check_limits((x, y), \"robobo\"):\n self.robobo.xy = (new_x, new_y)\n self.robobo_act.xy = (\n new_x + w * math.cos(self.robobo_act._angle * math.pi / 180),\n new_y + w * math.sin(self.robobo_act._angle * math.pi / 180),\n )\n # self.fig.canvas.draw()\n\n def robobo_set_angle(self, angle):\n \"\"\"Set the Robobo! angle (and its actuator angle and adjust its position)\"\"\"\n centre = self.robobo_get_pos()\n self.robobo._angle = angle\n self.robobo_act._angle = angle\n self.robobo_set_pos(centre)\n w = self.robobo.get_width()\n self.robobo_act.xy = (\n self.robobo.get_x() + w * math.cos(self.robobo_act._angle * math.pi / 180),\n self.robobo.get_y() + w * math.sin(self.robobo_act._angle * math.pi / 180),\n )\n if self.ball_position == \"robobo\":\n self.ball_set_pos(self.robobo_act_get_pos())\n # self.fig.canvas.draw()\n\n # def baxter_rarm_set_pos(self, (x, y)):\n # \"\"\"Set the Baxter's right arm center position (and its actuator) checking if it is inside its movement limits\"\"\"\n # w = self.baxter_rarm.get_width()\n # h = self.baxter_rarm.get_height()\n # # New x, y position\n # new_x = x - w / 2 * math.cos(self.baxter_rarm._angle * math.pi / 180) + h / 2 * math.sin(\n # self.baxter_rarm._angle * math.pi / 180)\n # new_y = y - w / 2 * math.sin(self.baxter_rarm._angle * math.pi / 180) - h / 2 * math.cos(\n # self.baxter_rarm._angle * math.pi / 180)\n #\n # # Check if the new baxter right arm position is inside its movement limits\n # if self.check_limits((x, y), 'baxter'):\n # self.baxter_rarm.xy = (new_x, new_y)\n # self.baxter_rarm_act.xy = (new_x + w * math.cos(self.baxter_rarm_act._angle * math.pi / 180),\n # new_y + w * math.sin(self.baxter_rarm_act._angle * math.pi / 180))\n # self.fig.canvas.draw()\n #\n # def baxter_rarm_set_angle(self, angle):\n # \"\"\"Set the Baxter's right arm angle (and its actuator angle and adjust its position)\"\"\"\n # centre = self.baxter_rarm_get_pos()\n # self.baxter_rarm._angle = angle\n # self.baxter_rarm_act._angle = angle\n # self.baxter_rarm_set_pos(centre)\n # w = self.baxter_rarm.get_width()\n # self.baxter_rarm_act.xy = (self.baxter_rarm.get_x() + w * math.cos(self.baxter_rarm_act._angle * math.pi / 180),\n # self.baxter_rarm.get_y() + w * math.sin(self.baxter_rarm_act._angle * math.pi / 180))\n # if self.ball_position == 'baxter_rarm':\n # self.ball_set_pos(self.baxter_rarm_act_get_pos())\n # self.fig.canvas.draw()\n\n ## def baxter_rarm_set_height(self, h):\n ## self.baxter_rarm._angle = angle\n ## self.fig.canvas.draw()\n\n def baxter_larm_set_pos(self, pos):\n \"\"\"Set the Baxter's left arm center position (and its actuator) checking if it is inside its movement limits\"\"\"\n (x, y) = pos\n w = self.baxter_larm.get_width()\n h = self.baxter_larm.get_height()\n # New x, y position\n new_x = (\n x\n - w / 2 * math.cos(self.baxter_larm._angle * math.pi / 180)\n + h / 2 * math.sin(self.baxter_larm._angle * math.pi / 180)\n )\n new_y = (\n y\n - w / 2 * math.sin(self.baxter_larm._angle * math.pi / 180)\n - h / 2 * math.cos(self.baxter_larm._angle * math.pi / 180)\n )\n\n # Check if the new baxter left arm position is inside its movement limits\n if self.check_limits((x, y), \"baxter\"):\n self.baxter_larm.xy = (new_x, new_y)\n self.baxter_larm_act.xy = (\n new_x + w * math.cos(self.baxter_larm_act._angle * math.pi / 180),\n new_y + w * math.sin(self.baxter_larm_act._angle * math.pi / 180),\n )\n # self.fig.canvas.draw()\n\n def baxter_larm_set_angle(self, angle):\n \"\"\"Set the Baxter's left arm angle (and its actuator angle and adjust its position)\"\"\"\n centre = self.baxter_larm_get_pos()\n self.baxter_larm._angle = angle\n self.baxter_larm_act._angle = angle\n self.baxter_larm_set_pos(centre)\n w = self.baxter_larm.get_width()\n self.baxter_larm_act.xy = (\n self.baxter_larm.get_x() + w * math.cos(self.baxter_larm_act._angle * math.pi / 180),\n self.baxter_larm.get_y() + w * math.sin(self.baxter_larm_act._angle * math.pi / 180),\n )\n if self.ball_position == \"baxter_larm\":\n self.ball_set_pos(self.baxter_larm_act_get_pos())\n # self.fig.canvas.draw()\n\n def ball_get_pos(self):\n \"\"\"Return the position of the center of the ball\"\"\"\n return self.ball.center\n\n def box1_get_pos(self):\n \"\"\"Return the position of the center of the box1\"\"\"\n return tuple(map(sum, list(zip(self.box1.xy, (self.box1.get_width() / 2, self.box1.get_height() / 2)))))\n\n def box2_get_pos(self):\n \"\"\"Return the position of the center of the box2\"\"\"\n return tuple(map(sum, list(zip(self.box2.xy, (self.box2.get_width() / 2, self.box2.get_height() / 2)))))\n\n def robobo_get_pos(self):\n \"\"\"Return the position of the center of the Robobo!\"\"\"\n w = self.robobo.get_width()\n h = self.robobo.get_height()\n x, y = self.robobo.xy\n x_c = (\n x\n + w / 2 * math.cos(self.robobo._angle * math.pi / 180)\n - h / 2 * math.sin(self.robobo._angle * math.pi / 180)\n )\n y_c = (\n y\n + w / 2 * math.sin(self.robobo._angle * math.pi / 180)\n + h / 2 * math.cos(self.robobo._angle * math.pi / 180)\n )\n return x_c, y_c\n\n def robobo_act_get_pos(self):\n \"\"\"Return the position of the center of the Robobo! actuator\"\"\"\n w = self.robobo_act.get_width()\n h = self.robobo_act.get_height()\n x, y = self.robobo_act.xy\n x_c = (\n x\n + w / 2 * math.cos(self.robobo_act._angle * math.pi / 180)\n - h / 2 * math.sin(self.robobo_act._angle * math.pi / 180)\n )\n y_c = (\n y\n + w / 2 * math.sin(self.robobo_act._angle * math.pi / 180)\n + h / 2 * math.cos(self.robobo_act._angle * math.pi / 180)\n )\n return x_c, y_c\n\n def robobo_get_angle(self):\n \"\"\"Return the angle of the Robobo!\"\"\"\n return self.robobo._angle\n\n #\n # def baxter_rarm_get_pos(self):\n # \"\"\"Return the position of the center of the Baxter's right arm\"\"\"\n # w = self.baxter_rarm.get_width()\n # h = self.baxter_rarm.get_height()\n # x, y = self.baxter_rarm.xy\n # x_c = x + w / 2 * math.cos(self.baxter_rarm._angle * math.pi / 180) - h / 2 * math.sin(\n # self.baxter_rarm._angle * math.pi / 180)\n # y_c = y + w / 2 * math.sin(self.baxter_rarm._angle * math.pi / 180) + h / 2 * math.cos(\n # self.baxter_rarm._angle * math.pi / 180)\n # return x_c, y_c\n #\n # def baxter_rarm_act_get_pos(self):\n # \"\"\"Return the position of the center of the Baxter's right arm actuator\"\"\"\n # w = self.baxter_rarm_act.get_width()\n # h = self.baxter_rarm_act.get_height()\n # x, y = self.baxter_rarm_act.xy\n # x_c = x + w / 2 * math.cos(self.baxter_rarm_act._angle * math.pi / 180) - h / 2 * math.sin(\n # self.baxter_rarm_act._angle * math.pi / 180)\n # y_c = y + w / 2 * math.sin(self.baxter_rarm_act._angle * math.pi / 180) + h / 2 * math.cos(\n # self.baxter_rarm_act._angle * math.pi / 180)\n # return x_c, y_c\n\n def baxter_larm_get_pos(self):\n \"\"\"Return the position of the center of the Baxter's left arm\"\"\"\n w = self.baxter_larm.get_width()\n h = self.baxter_larm.get_height()\n x, y = self.baxter_larm.xy\n x_c = (\n x\n + w / 2 * math.cos(self.baxter_larm._angle * math.pi / 180)\n - h / 2 * math.sin(self.baxter_larm._angle * math.pi / 180)\n )\n y_c = (\n y\n + w / 2 * math.sin(self.baxter_larm._angle * math.pi / 180)\n + h / 2 * math.cos(self.baxter_larm._angle * math.pi / 180)\n )\n return x_c, y_c\n\n def baxter_larm_act_get_pos(self):\n \"\"\"Return the position of the center of the Baxter's left arm actuator\"\"\"\n w = self.baxter_larm_act.get_width()\n h = self.baxter_larm_act.get_height()\n x, y = self.baxter_larm_act.xy\n x_c = (\n x\n + w / 2 * math.cos(self.baxter_larm_act._angle * math.pi / 180)\n - h / 2 * math.sin(self.baxter_larm_act._angle * math.pi / 180)\n )\n y_c = (\n y\n + w / 2 * math.sin(self.baxter_larm_act._angle * math.pi / 180)\n + h / 2 * math.cos(self.baxter_larm_act._angle * math.pi / 180)\n )\n return x_c, y_c\n\n # def baxter_rarm_get_angle(self):\n # \"\"\"Return the angle of the right arm of the Baxter robot\"\"\"\n # return self.baxter_rarm._angle\n\n def baxter_larm_get_angle(self):\n \"\"\"Return the angle of the left arm of the Baxter robot\"\"\"\n return self.baxter_larm._angle\n\n def get_distance(self, p1, p2):\n \"\"\"Return the distance between two points\"\"\"\n (x1, y1) = p1\n (x2, y2) = p2\n return math.sqrt(pow(x2 - x1, 2) + (pow(y2 - y1, 2)))\n\n def get_relative_angle(self, p1, p2):\n \"\"\"Return the relative angle betwen two points\"\"\"\n (x1, y1) = p1\n (x2, y2) = p2\n return math.atan2(y2 - y1, x2 - x1) * 180 / math.pi\n\n # def move_baxter_rarm(self, vel=10):\n # \"\"\"Move Baxter's right arm wih a specific velocity (default 10)\"\"\"\n # x, y = self.baxter_rarm_get_pos()\n # self.baxter_rarm_set_pos((x + vel * math.cos(self.baxter_rarm._angle * math.pi / 180),\n # y + vel * math.sin(self.baxter_rarm._angle * math.pi / 180)))\n # if self.ball_position == 'baxter_rarm':\n # self.ball_set_pos(self.baxter_rarm_act_get_pos())\n\n def move_baxter_larm(self, vel=20):\n \"\"\"Move Baxter's left arm wih a specific velocity (default 20)\"\"\"\n x, y = self.baxter_larm_get_pos()\n self.baxter_larm_set_pos(\n (\n x + vel * math.cos(self.baxter_larm._angle * math.pi / 180),\n y + vel * math.sin(self.baxter_larm._angle * math.pi / 180),\n )\n )\n if self.ball_position == \"baxter_larm\":\n self.ball_set_pos(self.baxter_larm_act_get_pos())\n\n def baxter_larm_action(self, relative_angle, vel=20):\n \"\"\"Move baxter left arm with a specific angle and velocity (default 20)\"\"\"\n angle = self.baxter_larm._angle + relative_angle\n self.baxter_larm_set_angle(angle)\n self.move_baxter_larm(vel)\n self.world_rules()\n # self.baxter_state_space()\n\n def move_robobo(self, vel=20):\n \"\"\"Move Robobo! wih a specific velocity (default 20)\"\"\"\n x, y = self.robobo_get_pos()\n self.robobo_set_pos(\n (\n x + vel * math.cos(self.robobo._angle * math.pi / 180),\n y + vel * math.sin(self.robobo._angle * math.pi / 180),\n )\n )\n if self.ball_position == \"robobo\":\n self.ball_set_pos(self.robobo_act_get_pos())\n\n def robobo_action(self, relative_angle, vel=20):\n \"\"\"Move robobo with a specific angle and velocity (default 20)\"\"\"\n angle = self.robobo._angle + relative_angle\n self.robobo_set_angle(angle)\n self.move_robobo(vel)\n self.world_rules()\n # self.baxter_state_space()\n\n def apply_action(self, relative_angles, vel_rob=25, vel_baxt=25):\n \"\"\"Move robobo and baxter left arm with a specific angle and velocity (default 20)\"\"\"\n self.robobo_action(relative_angles[0], vel_rob)\n self.baxter_larm_action(relative_angles[1], vel_baxt)\n\n # def move_baxter_rarm_ball(self, vel=10):\n # x, y = self.baxter_rarm_get_pos()\n # self.baxter_rarm_set_pos((x + vel * math.cos(self.baxter_rarm._angle * math.pi / 180),\n # y + vel * math.sin(self.baxter_rarm._angle * math.pi / 180)))\n # self.ball_set_pos(self.baxter_rarm_act_get_pos())\n #\n # def move_baxter_larm_ball(self, vel=10):\n # x, y = self.baxter_larm_get_pos()\n # self.baxter_larm_set_pos((x + vel * math.cos(self.baxter_larm._angle * math.pi / 180),\n # y + vel * math.sin(self.baxter_larm._angle * math.pi / 180)))\n # self.ball_set_pos(self.baxter_larm_act_get_pos())\n #\n # def move_robobo_ball(self, vel=10):\n # x, y = self.robobo_get_pos()\n # self.robobo_set_pos((x + vel * math.cos(self.robobo._angle * math.pi / 180),\n # y + vel * math.sin(self.robobo._angle * math.pi / 180)))\n # self.ball_set_pos(self.robobo_act_get_pos())\n\n def get_reward(self):\n \"\"\"Return the reward checking if the ball is inside one of the boxes\"\"\"\n if self.ball_position == \"box1\": # or self.ball_position == 'box2':\n reward = 1\n else:\n reward = 0\n\n return reward\n\n def get_sensorization(self):\n \"\"\"Return a sensorization vector with the distances between the ball and the robots' actuators and the reward\"\"\"\n dist_rob_ball = self.get_distance(self.robobo_act_get_pos(), self.ball_get_pos())\n dist_baxt_larm_ball = self.get_distance(self.baxter_larm_act_get_pos(), self.ball_get_pos())\n # dist_baxt_rarm_ball = self.get_distance(self.baxter_rarm_act_get_pos(), self.ball_get_pos())\n dist_ball_box1 = self.get_distance(self.ball_get_pos(), self.box1_get_pos())\n # dist_ball_box2 = self.get_distance(self.ball_get_pos(), self.box2_get_pos())\n # reward = self.get_reward()\n\n return dist_rob_ball, dist_baxt_larm_ball, dist_ball_box1 # ,reward\n\n def world_rules(self):\n \"\"\"Establish the ball position in the scenario\"\"\"\n # Set minimum distances for the ball to be inside the box or grasped by a robot\n min_dist_box = 50\n min_dist_robot = 50\n # Ball position: Check where the ball has to be (check distances)\n sens = self.get_sensorization()\n if sens[2] < min_dist_box and self.ball_position == \"baxter_larm\": # distance ball-box1\n # if self.ball_position == 'baxter_larm':\n # self.baxter_larm_set_pos(self.box1_get_pos())\n self.ball_position = \"box1\"\n # self.ball_set_pos(self.box1_get_pos())\n elif sens[1] < min_dist_robot: # distance ball-baxter_larm\n self.ball_position = \"baxter_larm\"\n self.ball_set_pos(self.baxter_larm_act_get_pos())\n elif sens[0] < min_dist_robot: # distance ball-robobo\n self.ball_position = \"robobo\"\n self.ball_set_pos(self.robobo_act_get_pos())\n else:\n self.ball_position = None\n\n def check_limits(self, pos, robot_type):\n \"\"\"Check if the next position of one of the robots is inside its movement limits\"\"\"\n (x, y) = pos\n # Set limits for robots movements\n lim_robobo_x = (100, 2400) # (100, 1250) # (x_min,x_max)\n lim_robobo_y = (50, 800) # (50, 950)\n lim_baxter_x = (1250, 2400)\n lim_baxter_y = (50, 800)\n # Movement boundaries\n result = 1\n if robot_type == \"robobo\":\n if x < lim_robobo_x[0] or x > lim_robobo_x[1] or y < lim_robobo_y[0] or y > lim_robobo_y[1]:\n result = 0 # Do not move: it may crash\n elif robot_type == \"baxter\":\n if x < lim_baxter_x[0] or x > lim_baxter_x[1] or y < lim_baxter_y[0] or y > lim_baxter_y[1]:\n result = 0 # Do not move: exceed movement boundaries\n\n return result\n\n def restart_scenario(self):\n self.ball_set_pos((np.random.randint(100, 2400), np.random.randint(50, 800)))\n # self.box1_set_pos((np.random.randint(1750, 2400), np.random.randint(50, 800)))\n # self.box1_set_pos((np.random.randint(1250, 2400), np.random.randint(50, 800)))\n\n # def baxter_state_space(self):\n\n # x5, y5 = self.baxter_figure_4.center\n # x4, y4 = self.baxter_figure_3.center\n # x3, y3 = self.baxter_figure_2.center\n # x2, y2 = self.baxter_figure_1.center\n # x1, y1 = self.baxter_figure.center\n #\n # x, y = 2700 + self.get_sensorization()[0] / 2, 264 + self.get_sensorization()[1] / 2\n #\n # self.baxter_figure.center = (x, y)\n # self.baxter_figure_1.center = (x1, y1)\n # self.baxter_figure_2.center = (x2, y2)\n # self.baxter_figure_3.center = (x3, y3)\n # self.baxter_figure_4.center = (x4, y4)\n # self.baxter_figure_5.center = (x5, y5)\n # self.fig.canvas.draw()\n\n\nif __name__ == \"__main__\":\n a = Sim()\n","sub_path":"mdb_motiven/src/mdb_motiven/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":24211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173650004","text":"import pandas as pd\n\n\ndef convert_to_panda(data_table, columns):\n \"\"\"\n :param data_table: row based table represented as a list of lists\n :param columns: map definining column definitions of the form:\n {'key': {'index': 0, 'Name': 'columnB', 'dtype': 'float'},\n 'two': ...}\n :return: this mapped to a panda data structure\n \"\"\"\n # reuse the columns datastructure to keep the column names\n frame = columns.copy()\n for key, value in frame.items():\n frame[key] = []\n\n # Transpose as panda works by column not by row\n for row in data_table:\n for key, value in frame.items():\n index = columns[key]['index']\n frame[key].append(row[index])\n\n #convert each column to a panda series with the correct datatype\n for key, value in frame.items():\n col_info = columns[key]\n type = col_info['dtype']\n\n #convert any ''->'0' for numeric columns\n if type in ['float32', 'float64', 'int32', 'int64']:\n for index, item in enumerate(value):\n if item == '':\n value[index] = '0'\n\n frame[key] = pd.Series(value, dtype=type)\n\n return pd.DataFrame(frame)","sub_path":"fabfile/charts/panda_parser.py","file_name":"panda_parser.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"161106119","text":"# protos/__init__.py\n\nimport sys\nimport os\n\n\ndef init_protobuf_path():\n current_folder = os.path.dirname(os.path.abspath(__file__))\n print(f'protobuf folder = {current_folder}')\n sub_folders = [f.name for f in os.scandir(current_folder) if f.is_dir()]\n for dir_name in list(sub_folders):\n if not dir_name.startswith('__'):\n path_to_append = os.path.join(current_folder, dir_name)\n print(f'path to append = {path_to_append}')\n sys.path.append(path_to_append)\n print(f'Python PATH={sys.path}')\n\n\ninit_protobuf_path()","sub_path":"proto/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"58854880","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\nget_ipython().magic(u'sql connect')\n\n\n# # DB2 Jupyter Notebook Extensions\n# \n# This code is imported as a Jupyter notebook extension in any notebooks you create with DB2 code in it. Place the following line of code in any notebook that you want to use these commands with:\n#
\n# %run db2.ipynb\n# 
\n# \n# This code defines a Jupyter/Python magic command called %sql which allows you to execute DB2 specific calls to \n# the database. There are other packages available for manipulating databases, but this one has been specifically\n# designed for demonstrating a number of the SQL features available in DB2.\n# \n# There are two ways of executing the %sql command. A single line SQL statement would use the\n# line format of the magic command:\n#
\n# %sql SELECT * FROM EMPLOYEE\n# 
\n# If you have a large block of sql then you would place the %%sql command at the beginning of the block and then\n# place the SQL statements into the remainder of the block. Using this form of the %%sql statement means that the\n# notebook cell can only contain SQL and no other statements.\n#
\n# %%sql\n# SELECT * FROM EMPLOYEE\n# ORDER BY LASTNAME\n# 
\n# You can have multiple lines in the SQL block (%%sql). The default SQL delimiter is the semi-column (;).\n# If you have scripts (triggers, procedures, functions) that use the semi-colon as part of the script, you \n# will need to use the -d option to change the delimiter to an at \"@\" sign. \n#
\n# %%sql -d\n# SELECT * FROM EMPLOYEE\n# @\n# CREATE PROCEDURE ...\n# @\n# 
\n# \n# The %sql command allows most DB2 commands to execute and has a special version of the CONNECT statement. \n# A CONNECT by itself will attempt to reconnect to the database using previously used settings. If it cannot \n# connect, it will prompt the user for additional information. \n# \n# The CONNECT command has the following format:\n#
\n# %sql CONNECT TO <database> USER <userid> USING <password | ?> HOST <ip address> PORT <port number>\n# 
\n# If you use a \"?\" for the password field, the system will prompt you for a password. This avoids typing the \n# password as clear text on the screen. If a connection is not successful, the system will print the error\n# message associated with the connect request.\n# \n# If the connection is successful, the parameters are saved on your system and will be used the next time you\n# run a SQL statement, or when you issue the %sql CONNECT command with no parameters.\n# \n# In addition to the -d option, there are a number different options that you can specify at the beginning of \n# the SQL:\n# \n# - -d - Delimiter: Change SQL delimiter to \"@\" from \";\"\n# - -q - Quiet: Quiet results - no answer set or messages returned from the function\n# - -n - No result set: Execute all of the SQL as commands rather than select statements (no answer sets) \n# - -s - SQL: Execute everything as SELECT statements. By default, SELECT, VALUES, and WITH are considered part of an answer set, but it is possible that you have an SQL statement that does not start with any of these keywords but returns an answer set.\n# - -r - Return the result set as an array of values instead of a dataframe\n# - -t - Time: Time the following SQL statement and return the number of times it executes in 1 second\n# - -j - JSON: Create a pretty JSON representation. Only the first column is formatted\n# - -a - All: Return all rows in answer set and do not limit display\n# - -pb - Plot Bar: Plot the results as a bar chart\n# - -pl - Plot Line: Plot the results as a line chart\n# - -pp - Plot Pie: Plot the results as a pie chart\n# - -sampledata - Create and load the EMPLOYEE and DEPARTMENT tables\n# \n# One final note. You can pass python variables to the %sql command by using the \\{\\} braces with the name of the\n# variable inbetween. Note that you will need to place proper punctuation around the variable in the event the\n# SQL command requires it. For instance, the following example will find employee '000010' in the EMPLOYEE table.\n#
\n# empno = '000010'\n# %sql SELECT LASTNAME FROM EMPLOYEE WHERE EMPNO='{empno}'\n\n# ### Install Db2 Python Driver\n# In the event that you do not have ibm_db installed on your system, this command will attempt to load it for you. If the %sql command does not work, it may be that this library is failing. To review the error messages, remove the %%capture clause.\n\n# In[1]:\n\n\nget_ipython().run_cell_magic(u'capture', u'', u'!pip install ibm_db\\n!pip install --user --upgrade pixiedust')\n\n\n# ### Install Db2 Extensions\n\n# In[2]:\n\n\n#\n# Set up Jupyter MAGIC commands \"sql\". \n# %sql will return results from a DB2 select statement or execute a DB2 command\n#\n# IBM 2017: George Baklarz\n# Version 2017-11-15\n#\n\nimport ibm_db\nimport pandas\nimport ibm_db_dbi\nimport json\nimport matplotlib.pyplot as plt\nimport getpass\nimport os\nimport pickle\nimport time\nimport sys\nimport re\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n# Override the name of display, HTML, and Image in the event you plan to use the pixiedust library for\n# rendering graphics.\n\nfrom IPython.display import HTML as pHTML, Image as pImage, display as pDisplay\nfrom __future__ import print_function\nfrom IPython.core.magic import (Magics, magics_class, line_magic,\n                                cell_magic, line_cell_magic)\nfrom pixiedust.display import *\nfrom pixiedust.utils.shellAccess import ShellAccess\n\n# Python Hack for Input between 2 and 3\n\ntry: \n    input = raw_input \nexcept NameError: \n    pass \n\nplt.style.use('ggplot')\n\nsettings = {\n     \"maxrows\"  : 10,    \n     \"database\" : \"\",\n     \"hostname\" : \"localhost\",\n     \"port\"     : \"50000\",\n     \"protocol\" : \"TCPIP\",    \n     \"uid\"      : \"DB2INST1\",\n     \"pwd\"      : \"password\"\n}\n\n# Connection settings for statements \n\nconnected = False\nhdbc = None\nhstmt = None\nruntime = 1\n\ndef sqlhelp():\n    \n    sd = ''\n    ed = ''\n    sh = ''\n    eh = ''\n    sr = ''\n    er = ''\n    \n    helpSQL = \"\"\"\n       

SQL Options

\n

The following options are available as part of a SQL statement. The options are always preceded with a\n minus sign (i.e. -q).\n \n {sr}\n {sh}Option{eh}\n {sh}Description{eh}\n {er}\n {sr}\n {sd}d{ed}\n {sd}Change SQL delimiter to \"@\" from \";\"{ed}\n {er}\n {sr}\n {sd}q{ed}\n {sd}Quiet results - no answer set or messages returned from the function{ed}\n {er}\n {sr}\n {sd}n{ed}\n {sd}Execute all of the SQL as commands rather than select statements (no answer sets){ed}\n {er}\n {sr}\n {sd}s{ed}\n {sd}Execute everything as SELECT statements. By default, SELECT, VALUES, and WITH are considered part of an answer set, but it is possible that you have an SQL statement that does not start with any of these keywords but returns an answer set.\n {ed} \n {er}\n {sr} \n {sd}r{ed}\n {sd}Return the result set as an array of values{ed}\n {er}\n {sr}\n {sd}t{ed}\n {sd}Time the following SQL statement and return the number of times it executes in 1 second{ed}\n {er}\n {sr}\n {sd}j{ed}\n {sd}Create a pretty JSON representation. Only the first column is formatted{ed}\n {er}\n {sr}\n {sd}a{ed}\n {sd}Return all rows in answer set and do not limit display{ed}\n {er}\n {sr}\n {sd}i{ed}\n {sd}Return the data in a pixiedust display to view the data and optionally plot it.{ed}\n {er}\n {sr}\n {sd}pb{ed}\n {sd}Plot the results as a bar chart{ed}\n {er}\n {sr}\n {sd}pl{ed}\n {sd}Plot the results as a line chart{ed}\n {er}\n {sr}\n {sd}pp{ed}\n {sd}Plot Pie: Plot the results as a pie chart{ed}\n {er}\n {sr}\n {sd}sampledata{ed}\n {sd}Create and load the EMPLOYEE and DEPARTMENT tables{ed}\n {er}\n
\n \"\"\"\n \n helpSQL = helpSQL.format(**locals())\n \n pDisplay(pHTML(helpSQL))\n \ndef connected_help():\n \n sd = ''\n ed = ''\n sh = ''\n eh = ''\n sr = ''\n er = ''\n \n helpConnect = \"\"\"\n

Connecting to DB2

\n

The CONNECT command has the following format:\n

\n       %sql CONNECT TO <database> USER <userid> USING <password|?> HOST <ip address> PORT <port number>\n       
\n If you use a \"?\" for the password field, the system will prompt you for a password. This avoids typing the \n password as clear text on the screen. If a connection is not successful, the system will print the error\n message associated with the connect request.\n

\n Note: When prompted for input, you can use the format ip:port or #x:port where #x represents \n the last digits of the containers IP address. For instance, if the Db2 server is found on 172.17.0.2 then\n you would use the value #2 to represent 172.17.0.2:50000. \n

\n If the connection is successful, the parameters are saved on your system and will be used the next time you\n run an SQL statement, or when you issue the %sql CONNECT command with no parameters.\n

If you issue CONNECT RESET, all of the current values will be deleted and you will need to \n issue a new CONNECT statement. \n

CONNECT without any parameters will cause the program to prompt you for\n the values. To use the default values, just hit return for each input line. The default values are: \n \n {sr}\n {sh}Setting{eh}\n {sh}Description{eh}\n {er}\n {sr}\n {sd}DB2 Driver{ed}\n {sd}IBM DB2 ODBC Driver (this requires a manual change){ed}\n {er}\n {sr}\n {sd}Database{ed}{sd}SAMPLE{ed}\n {er}\n {sr}\n {sd}Hostname{ed}\n {sd}localhost (enter an IP address if you need to connect to a remote server){ed}\n {er}\n {sr}\n {sd}PORT{ed}\n {sd}50000 (this is the default but it could be different){ed}\n {er}\n {sr} \n {sd}PROTOCOL{ed}\n {sd}TCPIP (You could have a local connection in Windows){ed}\n {er}\n {sr} \n {sd}Userid{ed}\n {sd}DB2INST1{ed} \n {er}\n {sr} \n {sd}Password{ed}\n {sd}No password is provided so you have to enter a value{ed}\n {er}\n {sr} \n {sd}Maximum Rows{ed}\n {sd}10 lines of output are displayed when a result set is returned{ed}\n {er}\n
\n \"\"\"\n \n helpConnect = helpConnect.format(**locals())\n \n pDisplay(pHTML(helpConnect)) \n \ndef split_ipport(in_port):\n\n # Split input into an IP address and Port number\n\n checkports = in_port.split(':')\n ip = checkports[0]\n if (len(checkports) > 1):\n port = checkports[1]\n else:\n port = None\n\n if (ip[:1] == '#'):\n ip = \"172.17.0.\" + ip[1:]\n\n return ip, port \n\n\ndef load_settings():\n\n # This routine will load the settings from the previous session if they exist\n \n global settings\n \n fname = \"db2connect.pickle\"\n\n try:\n with open(fname,'rb') as f: \n settings = pickle.load(f) \n \n except: \n pass\n \n return\n\ndef save_settings():\n\n # This routine will save the current settings if they exist\n \n global settings\n \n fname = \"db2connect.pickle\"\n \n try:\n with open(fname,'wb') as f:\n pickle.dump(settings,f)\n \n except:\n errormsg(\"Failed trying to write DB2 Configuration Information.\")\n \n return \n\n# DB2 Connection information Help\n\ndef db2_create_sample():\n \n create_department = \"\"\"\n BEGIN\n DECLARE FOUND INTEGER; \n SET FOUND = (SELECT COUNT(*) FROM SYSIBM.SYSTABLES WHERE NAME='DEPARTMENT' AND CREATOR=CURRENT USER); \n IF FOUND = 0 THEN \n EXECUTE IMMEDIATE('CREATE TABLE DEPARTMENT(DEPTNO CHAR(3) NOT NULL, DEPTNAME VARCHAR(36) NOT NULL, \n MGRNO CHAR(6),ADMRDEPT CHAR(3) NOT NULL)'); \n EXECUTE IMMEDIATE('INSERT INTO DEPARTMENT VALUES \n (''A00'',''SPIFFY COMPUTER SERVICE DIV.'',''000010'',''A00''), \n (''B01'',''PLANNING'',''000020'',''A00''), \n (''C01'',''INFORMATION CENTER'',''000030'',''A00''), \n (''D01'',''DEVELOPMENT CENTER'',NULL,''A00''), \n (''D11'',''MANUFACTURING SYSTEMS'',''000060'',''D01''), \n (''D21'',''ADMINISTRATION SYSTEMS'',''000070'',''D01''), \n (''E01'',''SUPPORT SERVICES'',''000050'',''A00''), \n (''E11'',''OPERATIONS'',''000090'',''E01''), \n (''E21'',''SOFTWARE SUPPORT'',''000100'',''E01''), \n (''F22'',''BRANCH OFFICE F2'',NULL,''E01''), \n (''G22'',''BRANCH OFFICE G2'',NULL,''E01''), \n (''H22'',''BRANCH OFFICE H2'',NULL,''E01''), \n (''I22'',''BRANCH OFFICE I2'',NULL,''E01''), \n (''J22'',''BRANCH OFFICE J2'',NULL,''E01'')'); \n END IF;\n END\"\"\"\n \n get_ipython().magic(u'sql -d -q {create_department}')\n \n create_employee = \"\"\"\n BEGIN\n DECLARE FOUND INTEGER; \n SET FOUND = (SELECT COUNT(*) FROM SYSIBM.SYSTABLES WHERE NAME='EMPLOYEE' AND CREATOR=CURRENT USER); \n IF FOUND = 0 THEN \n EXECUTE IMMEDIATE('CREATE TABLE EMPLOYEE(\n EMPNO CHAR(6) NOT NULL,\n FIRSTNME VARCHAR(12) NOT NULL,\n MIDINIT CHAR(1),\n LASTNAME VARCHAR(15) NOT NULL,\n WORKDEPT CHAR(3),\n PHONENO CHAR(4),\n HIREDATE DATE,\n JOB CHAR(8),\n EDLEVEL SMALLINT NOT NULL,\n SEX CHAR(1),\n BIRTHDATE DATE,\n SALARY DECIMAL(9,2),\n BONUS DECIMAL(9,2),\n COMM DECIMAL(9,2)\n )');\n EXECUTE IMMEDIATE('INSERT INTO EMPLOYEE VALUES\n (''000010'',''CHRISTINE'',''I'',''HAAS'' ,''A00'',''3978'',''1995-01-01'',''PRES '',18,''F'',''1963-08-24'',152750.00,1000.00,4220.00),\n (''000020'',''MICHAEL'' ,''L'',''THOMPSON'' ,''B01'',''3476'',''2003-10-10'',''MANAGER '',18,''M'',''1978-02-02'',94250.00,800.00,3300.00),\n (''000030'',''SALLY'' ,''A'',''KWAN'' ,''C01'',''4738'',''2005-04-05'',''MANAGER '',20,''F'',''1971-05-11'',98250.00,800.00,3060.00),\n (''000050'',''JOHN'' ,''B'',''GEYER'' ,''E01'',''6789'',''1979-08-17'',''MANAGER '',16,''M'',''1955-09-15'',80175.00,800.00,3214.00),\n (''000060'',''IRVING'' ,''F'',''STERN'' ,''D11'',''6423'',''2003-09-14'',''MANAGER '',16,''M'',''1975-07-07'',72250.00,500.00,2580.00),\n (''000070'',''EVA'' ,''D'',''PULASKI'' ,''D21'',''7831'',''2005-09-30'',''MANAGER '',16,''F'',''2003-05-26'',96170.00,700.00,2893.00),\n (''000090'',''EILEEN'' ,''W'',''HENDERSON'' ,''E11'',''5498'',''2000-08-15'',''MANAGER '',16,''F'',''1971-05-15'',89750.00,600.00,2380.00),\n (''000100'',''THEODORE'' ,''Q'',''SPENSER'' ,''E21'',''0972'',''2000-06-19'',''MANAGER '',14,''M'',''1980-12-18'',86150.00,500.00,2092.00),\n (''000110'',''VINCENZO'' ,''G'',''LUCCHESSI'' ,''A00'',''3490'',''1988-05-16'',''SALESREP'',19,''M'',''1959-11-05'',66500.00,900.00,3720.00),\n (''000120'',''SEAN'' ,'' '',''O`CONNELL'' ,''A00'',''2167'',''1993-12-05'',''CLERK '',14,''M'',''1972-10-18'',49250.00,600.00,2340.00),\n (''000130'',''DELORES'' ,''M'',''QUINTANA'' ,''C01'',''4578'',''2001-07-28'',''ANALYST '',16,''F'',''1955-09-15'',73800.00,500.00,1904.00),\n (''000140'',''HEATHER'' ,''A'',''NICHOLLS'' ,''C01'',''1793'',''2006-12-15'',''ANALYST '',18,''F'',''1976-01-19'',68420.00,600.00,2274.00),\n (''000150'',''BRUCE'' ,'' '',''ADAMSON'' ,''D11'',''4510'',''2002-02-12'',''DESIGNER'',16,''M'',''1977-05-17'',55280.00,500.00,2022.00),\n (''000160'',''ELIZABETH'',''R'',''PIANKA'' ,''D11'',''3782'',''2006-10-11'',''DESIGNER'',17,''F'',''1980-04-12'',62250.00,400.00,1780.00),\n (''000170'',''MASATOSHI'',''J'',''YOSHIMURA'' ,''D11'',''2890'',''1999-09-15'',''DESIGNER'',16,''M'',''1981-01-05'',44680.00,500.00,1974.00),\n (''000180'',''MARILYN'' ,''S'',''SCOUTTEN'' ,''D11'',''1682'',''2003-07-07'',''DESIGNER'',17,''F'',''1979-02-21'',51340.00,500.00,1707.00),\n (''000190'',''JAMES'' ,''H'',''WALKER'' ,''D11'',''2986'',''2004-07-26'',''DESIGNER'',16,''M'',''1982-06-25'',50450.00,400.00,1636.00),\n (''000200'',''DAVID'' ,'' '',''BROWN'' ,''D11'',''4501'',''2002-03-03'',''DESIGNER'',16,''M'',''1971-05-29'',57740.00,600.00,2217.00),\n (''000210'',''WILLIAM'' ,''T'',''JONES'' ,''D11'',''0942'',''1998-04-11'',''DESIGNER'',17,''M'',''2003-02-23'',68270.00,400.00,1462.00),\n (''000220'',''JENNIFER'' ,''K'',''LUTZ'' ,''D11'',''0672'',''1998-08-29'',''DESIGNER'',18,''F'',''1978-03-19'',49840.00,600.00,2387.00),\n (''000230'',''JAMES'' ,''J'',''JEFFERSON'' ,''D21'',''2094'',''1996-11-21'',''CLERK '',14,''M'',''1980-05-30'',42180.00,400.00,1774.00),\n (''000240'',''SALVATORE'',''M'',''MARINO'' ,''D21'',''3780'',''2004-12-05'',''CLERK '',17,''M'',''2002-03-31'',48760.00,600.00,2301.00),\n (''000250'',''DANIEL'' ,''S'',''SMITH'' ,''D21'',''0961'',''1999-10-30'',''CLERK '',15,''M'',''1969-11-12'',49180.00,400.00,1534.00),\n (''000260'',''SYBIL'' ,''P'',''JOHNSON'' ,''D21'',''8953'',''2005-09-11'',''CLERK '',16,''F'',''1976-10-05'',47250.00,300.00,1380.00),\n (''000270'',''MARIA'' ,''L'',''PEREZ'' ,''D21'',''9001'',''2006-09-30'',''CLERK '',15,''F'',''2003-05-26'',37380.00,500.00,2190.00),\n (''000280'',''ETHEL'' ,''R'',''SCHNEIDER'' ,''E11'',''8997'',''1997-03-24'',''OPERATOR'',17,''F'',''1976-03-28'',36250.00,500.00,2100.00),\n (''000290'',''JOHN'' ,''R'',''PARKER'' ,''E11'',''4502'',''2006-05-30'',''OPERATOR'',12,''M'',''1985-07-09'',35340.00,300.00,1227.00),\n (''000300'',''PHILIP'' ,''X'',''SMITH'' ,''E11'',''2095'',''2002-06-19'',''OPERATOR'',14,''M'',''1976-10-27'',37750.00,400.00,1420.00),\n (''000310'',''MAUDE'' ,''F'',''SETRIGHT'' ,''E11'',''3332'',''1994-09-12'',''OPERATOR'',12,''F'',''1961-04-21'',35900.00,300.00,1272.00),\n (''000320'',''RAMLAL'' ,''V'',''MEHTA'' ,''E21'',''9990'',''1995-07-07'',''FIELDREP'',16,''M'',''1962-08-11'',39950.00,400.00,1596.00),\n (''000330'',''WING'' ,'' '',''LEE'' ,''E21'',''2103'',''2006-02-23'',''FIELDREP'',14,''M'',''1971-07-18'',45370.00,500.00,2030.00),\n (''000340'',''JASON'' ,''R'',''GOUNOT'' ,''E21'',''5698'',''1977-05-05'',''FIELDREP'',16,''M'',''1956-05-17'',43840.00,500.00,1907.00),\n (''200010'',''DIAN'' ,''J'',''HEMMINGER'' ,''A00'',''3978'',''1995-01-01'',''SALESREP'',18,''F'',''1973-08-14'',46500.00,1000.00,4220.00),\n (''200120'',''GREG'' ,'' '',''ORLANDO'' ,''A00'',''2167'',''2002-05-05'',''CLERK '',14,''M'',''1972-10-18'',39250.00,600.00,2340.00),\n (''200140'',''KIM'' ,''N'',''NATZ'' ,''C01'',''1793'',''2006-12-15'',''ANALYST '',18,''F'',''1976-01-19'',68420.00,600.00,2274.00),\n (''200170'',''KIYOSHI'' ,'' '',''YAMAMOTO'' ,''D11'',''2890'',''2005-09-15'',''DESIGNER'',16,''M'',''1981-01-05'',64680.00,500.00,1974.00),\n (''200220'',''REBA'' ,''K'',''JOHN'' ,''D11'',''0672'',''2005-08-29'',''DESIGNER'',18,''F'',''1978-03-19'',69840.00,600.00,2387.00),\n (''200240'',''ROBERT'' ,''M'',''MONTEVERDE'',''D21'',''3780'',''2004-12-05'',''CLERK '',17,''M'',''1984-03-31'',37760.00,600.00,2301.00),\n (''200280'',''EILEEN'' ,''R'',''SCHWARTZ'' ,''E11'',''8997'',''1997-03-24'',''OPERATOR'',17,''F'',''1966-03-28'',46250.00,500.00,2100.00),\n (''200310'',''MICHELLE'' ,''F'',''SPRINGER'' ,''E11'',''3332'',''1994-09-12'',''OPERATOR'',12,''F'',''1961-04-21'',35900.00,300.00,1272.00),\n (''200330'',''HELENA'' ,'' '',''WONG'' ,''E21'',''2103'',''2006-02-23'',''FIELDREP'',14,''F'',''1971-07-18'',35370.00,500.00,2030.00),\n (''200340'',''ROY'' ,''R'',''ALONZO'' ,''E21'',''5698'',''1997-07-05'',''FIELDREP'',16,''M'',''1956-05-17'',31840.00,500.00,1907.00)'); \n END IF;\n END\"\"\"\n \n get_ipython().magic(u'sql -d -q {create_employee}')\n \n success(\"Sample tables [EMPLOYEE, DEPARTMENT] created.\")\n \ndef connected_prompt():\n \n global settings\n\n \n settings[\"database\"] = input(\"Enter the database name [SAMPLE]: \") or \"SAMPLE\";\n hostport = input(\"Enter the HOST IP address and PORT in the form ip:port or #x:port [localhost:50000].\") or \"localhost:50000\";\n ip, port = split_ipport(hostport)\n if (port == None): port = \"50000\"\n settings[\"hostname\"] = ip\n settings[\"port\"] = port\n settings[\"uid\"] = input(\"Enter Userid on the DB2 system [DB2INST1]: \").upper() or \"DB2INST1\";\n settings[\"pwd\"] = getpass.getpass(\"Password [password]: \") or \"password\";\n settings[\"maxrows\"] = input(\"Maximum rows displayed [10]: \") or \"10\";\n settings[\"maxrows\"] = int(settings[\"maxrows\"])\n\n# Connect to DB2 and prompt if you haven't set any of the values yet\n\ndef db2_doConnect():\n \n global hdbc, hstmt, connected, runtime\n global settings \n\n if connected == False: \n \n if len(settings[\"database\"]) == 0:\n connected_help()\n connected_prompt()\n \n dsn = (\n \"DRIVER={{IBM DB2 ODBC DRIVER}};\"\n \"DATABASE={0};\"\n \"HOSTNAME={1};\"\n \"PORT={2};\"\n \"PROTOCOL=TCPIP;\"\n \"UID={3};\"\n \"PWD={4};\").format(settings[\"database\"], settings[\"hostname\"], settings[\"port\"], settings[\"uid\"], settings[\"pwd\"])\n\n # Get a database handle (hdbc) and a statement handle (hstmt) for subsequent access to DB2\n\n try:\n hdbc = ibm_db.connect(dsn, \"\", \"\")\n except Exception as err:\n errormsg(str(err))\n connected = False\n settings[\"database\"] = ''\n return\n \n try:\n hstmt = ibm_db_dbi.Connection(hdbc)\n except Exception as err:\n errormsg(str(err))\n connected = False\n settings[\"database\"] = ''\n return \n \n connected = True\n \n # Save the values for future use\n \n save_settings()\n \n success(\"Connection successful.\")\n \n# Parse the CONNECT statement and execute if possible \n\ndef parseConnect(inSQL):\n \n global settings, connected\n\n connected = False\n \n cParms = inSQL.split()\n cnt = 0\n \n while cnt < len(cParms):\n if cParms[cnt].upper() == 'TO':\n if cnt+1 < len(cParms):\n settings[\"database\"] = cParms[cnt+1].upper()\n cnt = cnt + 1\n else:\n errormsg(\"No database specified in the CONNECT statement\")\n return\n elif cParms[cnt].upper() == 'USER':\n if cnt+1 < len(cParms):\n settings[\"uid\"] = cParms[cnt+1].upper()\n cnt = cnt + 1\n else:\n errormsg(\"No userid specified in the CONNECT statement\")\n return\n elif cParms[cnt].upper() == 'USING':\n if cnt+1 < len(cParms):\n settings[\"pwd\"] = cParms[cnt+1] \n if (settings[\"pwd\"] == '?'):\n settings[\"pwd\"] = getpass.getpass(\"Password [password]: \") or \"password\"\n cnt = cnt + 1\n else:\n errormsg(\"No password specified in the CONNECT statement\")\n return\n elif cParms[cnt].upper() == 'HOST':\n if cnt+1 < len(cParms):\n settings[\"hostname\"] = cParms[cnt+1].upper()\n cnt = cnt + 1\n else:\n errormsg(\"No hostname specified in the CONNECT statement\")\n return\n elif cParms[cnt].upper() == 'PORT': \n if cnt+1 < len(cParms):\n settings[\"port\"] = cParms[cnt+1].upper()\n cnt = cnt + 1\n else:\n errormsg(\"No port specified in the CONNECT statement\")\n return\n elif cParms[cnt].upper() == 'RESET': \n settings[\"database\"] = ''\n success(\"Connection reset.\")\n return\n else:\n cnt = cnt + 1\n \n db2_doConnect()\n\n# Find a keyword in a SQL string\n\ndef findKeyword(keywords,keyword):\n \n if len(keywords) == 0: return False\n if len(keyword) == 0: return False\n \n uKeywords = keywords.upper()\n uKeyword = keyword.upper()\n \n if uKeywords.find(uKeyword.strip()) >= 0:\n return True\n else:\n return False\n \n# Run a command for one second to see how many times we execute it and return the count\n\ndef sqlTimer(flag_cmd, inSQL):\n \n global hdbc, hstmt, runtime\n\n db2Block = 2\n count = 0\n t_end = time.time() + runtime\n while time.time() < t_end:\n if (flag_cmd == db2Block):\n try:\n stmt = ibm_db.exec_immediate(hdbc,inSQL)\n except Exception as err:\n db2_error(False)\n return(-1)\n else:\n try:\n stmt = ibm_db.exec_immediate(hdbc,inSQL)\n while( ibm_db.fetch_row(stmt) ): pass\n except Exception as err:\n db2_error(False)\n return(-1)\n \n count = count + 1\n \n return(count)\n\n# Print out the DB2 error generated by the last executed statement\n\ndef db2_error(quiet):\n \n if quiet == True: return\n\n html = '

'\n\n errmsg = ibm_db.stmt_errormsg().replace('\\r',' ')\n errmsg = errmsg[errmsg.rfind(\"]\")+1:].strip()\n pDisplay(pHTML(html+errmsg+\"

\"))\n \n# Print out an error message\n\ndef errormsg(message):\n \n html = '

'\n pDisplay(pHTML(html + message + \"

\")) \n \ndef success(message):\n \n print(message)\n#\n# Optional Code to print green border around success statements\n#\n# html = '

'\n# \n# if message != \"\":\n# pDisplay(pHTML(html + message + \"

\"))\n \n return \n \n@magics_class\nclass DB2(Magics):\n \n import pixiedust \n \n @line_cell_magic\n def sql(self, line, cell=None):\n \n # Before we event get started, check to see if you have connected yet. Without a connection we \n # can't do anything. You may have a connection request in the code, so if that is true, we run those,\n # otherwise we connect immediately\n \n # If your statement is not a connect, and you haven't connected, we need to do it for you\n \n global settings \n global hdbc, hstmt, connected\n \n select = [\"SELECT\", \"WITH\", \"VALUES\"] \n noBlock = 0\n sqlBlock = 1\n db2Block = 2\n \n # If you use %sql (line) we just run the SQL. If you use %%SQL the entire cell is run.\n \n flag_delim = \";\"\n flag_results = True\n flag_sqlType = noBlock\n flag_quiet = False\n flag_json = False\n flag_timer = False\n flag_plot = 0\n flag_cell = False\n flag_output = False\n flag_resultset = False\n flag_dataframe = False\n \n # The parameters must be in the line, not in the cell i.e. %sql -c \n \n Parms = line.strip()\n \n if len(Parms) == 0:\n if cell == None: \n sqlhelp()\n return\n if len(cell.strip()) == 0: \n sqlhelp()\n return\n \n # Check of you just want help\n \n if Parms == \"?\":\n sqlhelp()\n return\n \n if Parms.upper() == \"? CONNECT\":\n connected_help()\n return\n \n # If you issue a CONNECT statement in %sql then we run this first before auto-connecting\n if findKeyword(Parms,\"CONNECT\") == True: \n parseConnect(Parms)\n return\n \n # We need to check to see if we are connected before running any SQL\n if connected == False:\n db2_doConnect()\n if connected == False: return\n \n # Default result set size\n if settings[\"maxrows\"] == -1:\n pandas.reset_option('max_rows')\n else:\n pandas.options.display.max_rows = settings[\"maxrows\"]\n \n # Display rows as JSON structure\n if Parms.find(\"-j\") >= 0:\n flag_json = True\n Parms = Parms.replace(\"-j\",\" \")\n \n # Load sample tables for scripts\n if Parms.find('-sampledata') >= 0:\n db2_create_sample()\n return\n \n # Execute the SQL so that it behaves like a SELECT statement\n if Parms.find(\"-s\") >= 0:\n flag_sqlType = sqlBlock\n Parms = Parms.replace(\"-s\",\" \")\n \n # Execute the SQL but return the results in an array (basically a two-dimensional array)\n if Parms.find(\"-r\") >= 0:\n flag_resultset = True\n Parms = Parms.replace(\"-r\", \" \")\n \n # Execute the SQL so that it behaves like an INSERT, DELETE, UPDATE or no result set\n if Parms.find(\"-n\") >= 0:\n flag_sqlType = db2Block\n Parms = Parms.replace(\"-n\",\" \")\n \n # Quiet execution (no errors or completed messages)\n if Parms.find(\"-q\") >= 0:\n flag_quiet = True\n Parms = Parms.replace(\"-q\",\" \")\n\n # Retrieve all rows (do not use the default limit)\n if Parms.find(\"-a\") >= 0:\n pandas.reset_option('max_rows')\n Parms = Parms.replace(\"-a\",\" \")\n \n # Set the delimiter to @ instead of a semi-colon for procedures, triggers, and functions\n if Parms.find(\"-d\") >= 0:\n flag_delim = \"@\"\n Parms = Parms.replace(\"-d\",\" \") \n \n # Timer function (not that useful, but worth a try)\n if Parms.find(\"-t\") >= 0:\n flag_timer = True\n Parms = Parms.replace(\"-t\",\" \")\n \n # Plot functions -pb = bar, -pp = pie, -pl = line\n if Parms.find(\"-pb\") >= 0:\n flag_plot = 1\n Parms = Parms.replace(\"-pb\",\" \")\n \n if Parms.find(\"-pp\") >= 0:\n flag_plot = 2\n Parms = Parms.replace(\"-pp\",\" \")\n \n if Parms.find(\"-pl\") >= 0:\n flag_plot = 3\n Parms = Parms.replace(\"-pl\",\" \") \n \n if Parms.find(\"-i\") >= 0:\n flag_plot = 4\n Parms = Parms.replace(\"-i\",\" \") \n \n remainder = Parms.strip()\n \n # Split the line according to your delimiter\n \n if cell is None:\n sqlLines = [remainder]\n flag_cell = False\n else:\n cell = re.sub('.*?--.*$',\"\",cell,flags=re.M)\n remainder = cell.replace(\"\\n\",\" \")\n sqlLines = remainder.split(flag_delim)\n flag_cell = True\n \n # For each line figure out if you run it as a command (db2) or select (sql)\n \n for sql in sqlLines:\n\n # Split the line so we know what the first keyword is. We only look at the first one. There may\n # be SQL that returns output that we may not know about\n \n keywords = sql.split()\n if len(keywords) == 0: continue\n \n sqlcmd = keywords[0].upper()\n \n if (flag_timer == True):\n \n count = sqlTimer(flag_sqlType, sql)\n \n if flag_quiet == False and count != -1:\n print(\"Total iterations in %s second(s): %s\" % (runtime,count))\n \n return(count)\n \n elif (flag_plot != 0):\n \n try:\n df = pandas.read_sql(sql,hstmt)\n except Exception as err:\n db2_error(False)\n return\n \n if flag_plot == 4:\n \n ShellAccess.pdf = df\n display(pdf)\n\n return\n \n plt.style.use('ggplot')\n plt.figure()\n col_count = len(df.columns)\n \n if flag_plot == 1:\n\n # Bar Chart\n if (col_count >= 2):\n xlabel = df.columns.values[0]\n ylabel = df.columns.values[1]\n _ = df.plot(kind='bar',x=xlabel,y=ylabel);\n else:\n _ = df.plot(kind='bar');\n \n \n elif flag_plot == 2:\n \n # Pie \n if (col_count >= 2):\n xlabel = df.columns.values[0]\n xname = df[xlabel].tolist()\n yname = df.columns.values[1]\n _ = df.plot(kind='pie',y=yname,labels=xname);\n else:\n yname = df.columns.values[0]\n _ = df.plot(kind='pie',y=yname);\n \n elif flag_plot == 3:\n \n # Line Chart\n if (col_count >= 2): \n xlabel = df.columns.values[0]\n ylabel = df.columns.values[1]\n _ = df.plot(kind='line',x=xlabel,y=ylabel) ; \n else:\n _ = df.plot(kind='line') ; \n \n else:\n return\n \n plt.show()\n return\n \n elif (flag_sqlType == sqlBlock) or (sqlcmd in select and flag_sqlType != db2Block):\n \n if flag_json == True:\n try: \n stmt = ibm_db.exec_immediate(hdbc,sql);\n row_count = 0\n while( ibm_db.fetch_row(stmt) ):\n row_count = row_count + 1\n jsonVal = ibm_db.result(stmt,0)\n formatted_JSON = json.dumps(json.loads(jsonVal), indent=4, separators=(',', ': '))\n \n # Print JSON Structure\n \n if row_count > 1: print()\n print(\"Row: %d\" % row_count)\n print(formatted_JSON)\n flag_output = True\n \n except Exception as err:\n db2_error(flag_quiet)\n \n else: \n if flag_resultset == True:\n row_count = 0\n resultSet = []\n try:\n stmt = ibm_db.exec_immediate(hdbc,sql)\n result = ibm_db.fetch_tuple(stmt)\n while (result):\n row = []\n for col in result:\n row.append(col)\n \n resultSet.append(row)\n result = ibm_db.fetch_tuple(stmt)\n \n return(resultSet) \n \n except Exception as err:\n db2_error(False) \n \n else:\n try:\n \n dp = pandas.read_sql(sql, hstmt)\n if flag_dataframe == True:\n return(dp)\n else:\n # pDisplay(dp)\n flag_output = True\n return(dp)\n \n except Exception as err:\n db2_error(flag_quiet)\n \n else:\n \n try: \n ibm_db.exec_immediate(hdbc,sql);\n if flag_cell == False and flag_quiet == False:\n print(\"Command completed.\")\n \n except Exception as err:\n db2_error(flag_quiet)\n \n if flag_cell == True and flag_output == False:\n print(\"Command completed.\")\n \n# Register the Magic extension in Jupyter \nip = get_ipython() \nip.register_magics(DB2)\nload_settings()\nsuccess(\"DB2 Extensions Loaded.\")\n\n\n# Set the table formatting to left align a table in a cell. By default, tables are centered in a cell. Remove this cell if you don't want to change Jupyter notebook formatting for tables.\n\n# In[3]:\n\n\nget_ipython().run_cell_magic(u'html', u'', u'')\n\n\n# #### Credits: IBM 2017, George Baklarz [baklarz@ca.ibm.com]\n","sub_path":"DB2_magic.py","file_name":"DB2_magic.py","file_ext":"py","file_size_in_byte":38507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528125841","text":"class Solution:\n \"\"\"\n @param num: a string contains only digits 0-9\n @param target: An integer\n @return: return all possibilities\n \"\"\"\n def addOperators(self, num, target):\n # write your code here\n res = []\n \n self.dfs(num, 0, 0, 0, target, \"\", res)\n return res\n \n def dfs(self, num, start, total, lastnum, target, path, res):\n if start == len(num) and total == target:\n res.append(path)\n return \n \n for i in range(start + 1, len(num) + 1):\n number_str = num[start: i]\n number = int(number_str)\n \n if start == 0:\n self.dfs(num, i, total + number, number, target, number_str, res)\n else:\n self.dfs(num, i, total + number, number, target, path + \"+\" + number_str, res)\n\n self.dfs(num, i, total - number, -number, target, path + \"-\" + number_str, res)\n\n self.dfs(num, i, total - lastnum + lastnum * number, lastnum * number, target, path + \"*\" + number_str, res)\n \n # anything that starts with 0. only 0 is valid\n if number == 0:\n break\nclass Solution2:\n def addOperators(self, num, target):\n def dfs(idx, tmp, tot, last, res):\n if idx == len(num):\n if tot == target:\n res.append(tmp)\n return\n for i in range(idx, len(num)):\n x = int(num[idx: i + 1])\n if idx == 0:\n dfs(i + 1, str(x), x, x, res)\n else:\n dfs(i + 1, tmp + \"+\" + str(x), tot + x, x, res)\n dfs(i + 1, tmp + \"-\" + str(x), tot - x, -x, res)\n dfs(i + 1, tmp + \"*\" + str(x), tot - last + last * x, last * x, res)\n if x == 0:\n break\n res = []\n dfs(0, \"\", 0, 0, res)\n return res\nprint(Solution().addOperators(\"0030\", 3))","sub_path":"653 expression and operators.py","file_name":"653 expression and operators.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"630237073","text":"\"\"\"Attempt to find except-expression candidates\n\nUsage: $ python3 find_except_expr.py filename.py [filename.py ...]\n\n$ find cpython/ -name \\*.py|xargs python3 ExceptExpr/find_except_expr.py >ExceptExpr/candidates.txt\n\"\"\"\n\nimport ast\nimport sys\n\nverbose = False\n\ncompare_key = {\n\t# Currently looking for the same target.\n\t# Since I am fairly clueless with the ast module, I'm\n\t# looking for string equality of ast.dump(), which is\n\t# hardly the best way to do things!\n\tast.Assign: lambda node: ' '.join(ast.dump(t) for t in node.targets),\n\t# Same target and same operator.\n\tast.AugAssign: lambda node: ast.dump(node.target) + ast.dump(node.op),\n\t# A return statement is always compatible with another.\n\tast.Return: lambda node: \"(easy)\",\n\t# Calling these never compatible is wrong. Calling them\n\t# always compatible will give lots of false positives.\n\tast.Expr: lambda node: \"(maybe)\",\n\t# These ones are never compatible, so return some\n\t# object that's never equal to anything.\n\tast.Import: lambda node: float(\"nan\"),\n\tast.ImportFrom: lambda node: float(\"nan\"),\n\tast.Pass: lambda node: float(\"nan\"),\n\tast.Raise: lambda node: float(\"nan\"),\n\tast.If: lambda node: float(\"nan\"),\n}\n\nexcepts = excepts_with_as = 0\nsimple_excepts = simple_excepts_with_as = 0\n\nclass walker(ast.NodeVisitor): # For \"Ghost who walks\", if you read comics\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\n\tdef visit_ExceptHandler(self, node):\n\t\t\"\"\"Keep stats on usage of 'as' in except clauses\"\"\"\n\t\tglobal excepts, excepts_with_as\n\t\texcepts += 1\n\t\tif node.name is not None: excepts_with_as += 1\n\t\tself.generic_visit(node)\n\n\tdef visit_Try(self, node):\n\t\t\"\"\"Report on 'simple' try/except statements.\n\n\t\tThe definition of simple is:\n\t\t1. No else or finally clause\n\t\t2. Only one except clause (currently)\n\t\t3. Exactly one statement in the try clause\n\t\t4. Exactly one statement in each except clause\n\t\t5. Each of those statements is the same type.\n\t\t6. That type is one that could be an expression.\n\t\t7. Those statements are all compatible.\n\n\t\tThe last two are the trickiest.\"\"\"\n\t\tself.generic_visit(node) # Recurse first for simplicity.\n\n\t\t# 1. No else or finally clause\n\t\tif node.orelse or node.finalbody: return\n\n\t\t# 2. Only one except clause (currently)\n\t\t# Note that having zero handlers shouldn't happen, as a try\n\t\t# block with no except clauses will normally have an else or\n\t\t# finally.\n\t\tif len(node.handlers) != 1: return\n\n\t\t# 3. Exactly one statement in the try clause\n\t\t# Again, I don't expect ever to see 0 here.\n\t\t# This check is quite optional (the rest of the checks don't\n\t\t# depend on it); some versions of the proposal are quite okay\n\t\t# with having more than one except clause.\n\t\tif len(node.body) != 1: return\n\n\t\t# 4. Exactly one statement in each except clause\n\t\t# These ones definitely could have zero statements, though.\n\t\tfor handler in node.handlers:\n\t\t\tif len(handler.body) != 1: return\n\n\t\t# 5. Each of those statements is the same type.\n\t\ttry_type = type(node.body[0])\n\t\tfor handler in node.handlers:\n\t\t\tif type(handler.body[0]) is not try_type: return\n\n\t\t# 6. That type is one that could be an expression.\n\t\t# 7. Those statements are all compatible.\n\t\t# These two done with a lookup table. If the type isn't in\n\t\t# the table, dump it out for debugging (once); otherwise,\n\t\t# the function should return a value which is equal for any\n\t\t# two compatible nodes.\n\t\tif try_type not in compare_key:\n\t\t\tprint(\"Unrecognized type\",try_type.__name__,file=sys.stderr)\n\t\t\tcompare_key[try_type] = lambda node: float(\"nan\")\n\t\tfunc = compare_key[try_type]\n\t\ttry_node = func(node.body[0])\n\t\tfor handler in node.handlers:\n\t\t\tif try_node != func(handler.body[0]): return\n\t\tprint(\"%s:%d: %s: %s\"%(self.filename,node.lineno,try_type.__name__,try_node))\n\t\tglobal simple_excepts, simple_excepts_with_as\n\t\tfor handler in node.handlers:\n\t\t\tsimple_excepts += 1\n\t\t\tif handler.name is not None: simple_excepts_with_as += 1\n\n\t\t# What's the easiest way to get a readable form for display?\n\ndef search(fn):\n\twith open(fn,\"rb\") as f:\n\t\tdata = f.read()\n\ttry:\n\t\ttree = ast.parse(data)\n\texcept SyntaxError as e:\n\t\t# Some files in the stdlib are deliberately broken\n\t\t# (including lib2to3 test data, which is \"broken\" from\n\t\t# the point of view of a Python 3 parser). Just log it\n\t\t# (optionally) and move on.\n\t\tif verbose:\n\t\t\tprint(\"Unable to parse\", fn, file=sys.stderr)\n\t\t\tprint(e, file=sys.stderr)\n\t\treturn\n\twalker(fn).visit(tree)\n\nif __name__ == \"__main__\":\n\tfor fn in sys.argv[1:]:\n\t\t# print(\"Searching\", fn, \"...\")\n\t\tsearch(fn)\n\tif excepts:\n\t\tprint(\"Of\",excepts,\"except clauses,\",excepts_with_as,\"use the 'as' clause:\",excepts_with_as*100/excepts,\"%\",file=sys.stderr)\n\tif simple_excepts:\n\t\tprint(\"Simple excepts:\",simple_excepts_with_as,\"/\",simple_excepts,\"=\",simple_excepts_with_as*100/simple_excepts,\"%\",file=sys.stderr)\n","sub_path":"find_except_expr.py","file_name":"find_except_expr.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237172922","text":"from PIL import Image\nimport urllib\nimport os\nfrom compressinator_utils import printlog, CompressionInfo, TIMEOUT, curl_limit_rate, image_errors\nimport re\nimport subprocess\nimport shutil\n\ndef process_image(image_url, updatedConfig, url, new_path, backup_path):\n printlog('Processing image: ' + image_url)\n MinBytes = int(updatedConfig['minbytes'])\n MinSaving = int(float(updatedConfig['minsaving']))\n SsoLink = updatedConfig['ssolink']\n PngquantCommand = updatedConfig['pngquantcommand']\n PillowQuality = int(updatedConfig['pillowquality'])\n ThumbnailPath = updatedConfig['thumbnailpath']\n RootPath = updatedConfig['rootpath']\n\n AllowExternalImages = updatedConfig['allowexternalimages']\n if AllowExternalImages == '0':\n AllowExternalImages = False\n\n CopyAllImages = updatedConfig['copyallimages']\n if CopyAllImages == '0':\n CopyAllImages = False\n\n FlattenOutputDirectory = updatedConfig['flattenoutputdirectory']\n if FlattenOutputDirectory == '0':\n FlattenOutputDirectory = False\n\n site_regex = re.escape(url)\n host_regex = r'(?:http[s]?:)\\/\\/([^\\/?#]+)'\n new_size = 0\n old_size = 0\n attempted = False\n compressed = False\n if re.search(r'(https?:|^\\/\\/)', image_url) is None:\n image_url = url + image_url\n elif re.search(site_regex, image_url) is None and not AllowExternalImages:\n return CompressionInfo(exclusion_reason='REMOTE')\n for exclusion in ThumbnailPath.split(','):\n if re.search(re.escape(exclusion), image_url) is not None:\n return CompressionInfo(exclusion_reason='THUMBNAIL')\n try:\n image = None\n try:\n image = urllib.request.urlopen(image_url, timeout=TIMEOUT)\n except Exception as error:\n image_errors[url][image_url] = repr(error)\n return CompressionInfo(exclusion_reason='ERROR')\n image_size = int(image.getheader(\"Content-Length\"))\n if image_size > MinBytes or CopyAllImages:\n image_relative_path = re.sub(site_regex, '', image_url) #Remove the https://domain.com\n printlog('flat: ' + str(FlattenOutputDirectory) + ', external: ' + str(AllowExternalImages))\n if FlattenOutputDirectory or AllowExternalImages:\n image_relative_path = re.match(host_regex, image_url).group(1) + '/' + image_relative_path\n if FlattenOutputDirectory:\n printlog(image_url)\n image_relative_path = re.match(host_regex, image_url).group(1) + re.search(r'(\\/[^\\/]+$)', image_url).group()\n printlog(image_relative_path)\n\n \n image_relative_path = re.sub(r'^\\/', '', image_relative_path) # Remove the initial / so it doesn't look like an absolute path\n image_relative_path = image_relative_path.split('/')\n filename = os.path.join(new_path,*image_relative_path)\n backup_filename = os.path.join(backup_path, *image_relative_path)\n printlog(filename)\n if not os.path.exists(os.path.dirname(filename)):\n try:\n os.makedirs(os.path.dirname(filename))\n except OSError as exc: # Guard against race condition\n printlog('OS Error')\n pass\n elif os.path.exists(filename):\n return CompressionInfo(exclusion_reason='EXISTS')\n if not os.path.exists(os.path.dirname(backup_filename)):\n try:\n os.makedirs(os.path.dirname(backup_filename))\n except OSError as exc: # Guard against race condition\n printlog('OS Error')\n pass\n with open(filename, \"w\") as file:\n #urllib.request.urlretrieve(image_url, filename)\n try:\n curl_limit_rate(image_url, filename, 500000)\n except Exception as error:\n printlog('Could not write ' + image_url + ' to ' + filename)\n return CompressionInfo(to_remove=filename, exclusion_reason='ERROR')\n if not os.path.exists(backup_filename):\n shutil.copyfile(filename, backup_filename)\n original_file_size = os.path.getsize(filename)\n if re.search(r'png$', image_url, re.IGNORECASE):\n command = PngquantCommand + ' \\\"' + filename +'\\\"'\n CREATE_NO_WINDOW = 0x08000000\n process = subprocess.Popen(command, stdout=subprocess.PIPE, creationflags=CREATE_NO_WINDOW)\n output, error = process.communicate()\n else:\n image = Image.open(filename)\n try:\n image.save(filename, optimize=True, quality=int(PillowQuality))\n except Exception as err:\n printlog(filename)\n printlog(repr(err))\n pass\n new_file_size = os.path.getsize(filename)\n attempted = True\n if not CopyAllImages and (original_file_size == 0 or (original_file_size - new_file_size) / original_file_size < (MinSaving / 100)):\n os.remove(filename)\n os.remove(backup_filename)\n else:\n old_size = original_file_size\n new_size = new_file_size\n compressed = True\n else:\n return CompressionInfo(exclusion_reason='TOO_SMALL')\n except Exception as err:\n printlog('Got an error with: ' + image_url)\n printlog(repr(err))\n return CompressionInfo(new_size=new_size, old_size=old_size, attempted=attempted, compressed=compressed)\n","sub_path":"imageprocessor.py","file_name":"imageprocessor.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"346016685","text":"import glob\nimport struct\nimport sys\nimport threading\n\nimport serial\n\nfrom src.data_producer import DataProducer\nfrom src.realtime.checksum_validator import ChecksumValidator\nfrom src.rocket_packet.rocket_packet_parser import RocketPacketParser\nfrom src.rocket_packet.rocket_packet_repository import RocketPacketRepository\n\n\nclass NoConnectedDeviceException(Exception):\n \"\"\"Raised when data acquisition is started with no device connected\"\"\"\n\n\nclass SerialDataProducer(DataProducer):\n def __init__(self, lock: threading.Lock, rocket_packet_repository: RocketPacketRepository,\n rocket_packet_parser: RocketPacketParser, checksum_validator: ChecksumValidator, baudrate=9600,\n start_character=b's', sampling_frequency=1.0):\n super().__init__(lock)\n self.rocket_packet_repository = rocket_packet_repository\n self.rocket_packet_parser = rocket_packet_parser\n self.checksum_validator = checksum_validator\n self.unsaved_data = False\n\n self.port = serial.Serial()\n self.port.baudrate = baudrate\n self.port.timeout = 1 / sampling_frequency\n self.start_character = start_character\n\n # RocketPacket data + 1 byte for checksum\n self.num_bytes_to_read = self.rocket_packet_parser.get_number_of_bytes() + 1\n\n def start(self):\n ports = self.detect_serial_ports()\n if not ports:\n raise NoConnectedDeviceException(\"Aucun récepteur connecté\")\n self.port.port = ports[0]\n self.port.open()\n\n self.is_running = True\n self.thread = threading.Thread(target=self.run)\n self.thread.start()\n\n def run(self):\n while self.is_running:\n c = self.port.read(1)\n if c == self.start_character:\n data_bytes = self.port.read(self.num_bytes_to_read)\n\n if self.checksum_validator.validate(data_bytes):\n try:\n rocket_packet = self.rocket_packet_parser.parse(data_bytes[:-1])\n self.add_rocket_packet(rocket_packet)\n self.unsaved_data = True\n except struct.error as e:\n \"\"\"\n This error can occur if we don't read enough bytes on the serial port or if the packet format is\n incorrect.\n \"\"\"\n print(\"Invalid packet: \" + str(e))\n self.port.close()\n\n def save(self, filename: str):\n self.rocket_packet_repository.save(filename, self.available_rocket_packets, self.rocket_packet_parser)\n self.unsaved_data = False\n\n def has_unsaved_data(self):\n return self.unsaved_data\n\n def clear_rocket_packets(self):\n self.lock.acquire()\n self.available_rocket_packets.clear()\n self.unsaved_data = False\n self.lock.release()\n\n @staticmethod\n def detect_serial_ports():\n \"\"\" Lists serial port names\n :raises EnvironmentError\n On unsupported or unknown platforms\n :returns:\n A list of the serial ports available on the system\n \"\"\"\n\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/tty[A-Za-z]*')\n elif sys.platform.startswith('darwin'):\n ports = glob.glob('/dev/tty.*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n","sub_path":"BaseStation/src/realtime/serial_data_producer.py","file_name":"serial_data_producer.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347075453","text":"import cv2\ndst = cv2.imread('./data/tsukuba_l.png')\ndst2 = cv2.imread('./data/tsukuba_r.png')\n\ndst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\ndst2 = cv2.cvtColor(dst2, cv2.COLOR_BGR2GRAY)\nstereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)\n\ndisparity = stereo.compute(dst, dst2, disparity=cv2.CV_32F)\nnorm_coeff = 255 / disparity.max()\ncv2.imshow(\"disparity\", disparity * norm_coeff / 255)\ncv2.waitKey(0)","sub_path":"asdasd.py","file_name":"asdasd.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275335792","text":"from functools import wraps\n\nfrom .core import Sort, Attribute\nfrom .exceptions import ArgumentError, RewritingError\n\n\nclass Strategy(Sort):\n pass\n\n\ndef set_operation(fn):\n @wraps(fn)\n def wrapper(self, terms):\n if not isinstance(terms, (set, frozenset)):\n terms = set([terms])\n\n rv = set()\n for term in terms:\n term = fn(self, term)\n if isinstance(term, (set, frozenset)):\n rv |= term\n else:\n rv.add(term)\n return rv\n\n return wrapper\n\n\ndef make_strategy(fn):\n def __call__(self, term):\n if fn(term) is None:\n print(fn)\n return fn(term)\n return type(fn.__name__, (Strategy,), {'__call__': set_operation(__call__)})()\n\n\nidentity = type('identity', (Strategy,), {'__call__': set_operation(lambda self, term: term)})()\n\n\nclass union(Strategy):\n\n left = Attribute(domain=Strategy)\n right = Attribute(domain=Strategy)\n\n def __init__(self, *operands):\n if len(operands) < 2:\n raise ArgumentError('%s requires at least 2 operands.' % self.__class__.__name__)\n elif len(operands) == 2:\n super().__init__(left=operands[0], right=operands[1])\n else:\n super().__init__(left=operands[0], right=union(*operands[1:]))\n\n def __call__(self, terms):\n if not isinstance(terms, (set, frozenset)):\n terms = set([terms])\n\n return self.left(terms) | self.right(terms)\n\n\nclass fixpoint(Strategy):\n\n f = Attribute(domain=Strategy)\n\n def __call__(self, terms):\n if not isinstance(terms, (set, frozenset)):\n terms = set([terms])\n\n rv = self.f(terms)\n while rv != terms:\n terms = rv\n rv = self.f(terms)\n return rv\n\n\nclass try_(Strategy):\n\n f = Attribute(domain=Strategy)\n\n def __call__(self, terms):\n if not isinstance(terms, (set, frozenset)):\n terms = set([terms])\n\n rv = set()\n for term in terms:\n try:\n rv |= self.f(term)\n except RewritingError:\n rv.add(term)\n return rv\n\n try:\n return self.f(terms)\n except RewritingError:\n return terms\n","sub_path":"stew/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"538017935","text":"\nimport scrapy\nfrom scrapy.http import HtmlResponse\nfrom jobparser.items import JobparserItem\n\nclass HhruSpider(scrapy.Spider):\n name = 'hhru'\n allowed_domains = ['hh.ru']\n start_urls = ['https://hh.ru/search/vacancy?fromSearchLine=true&st=searchVacancy&text=python&area=1&search_field=description&search_field=company_name&search_field=name',\n 'https://hh.ru/search/vacancy?fromSearchLine=true&st=searchVacancy&text=python&area=2&search_field=description&search_field=company_name&search_field=name']\n\n def parse(self, response: HtmlResponse):\n next_page = response.xpath(\"//a[@data-qa='pager-next']/@href\").get()\n if next_page:\n yield response.follow(next_page, callback=self.parse)\n links = response.xpath(\"//a[@data-qa='vacancy-serp__vacancy-title']/@href\").getall()\n for link in links:\n yield response.follow(link, callback=self.vacancy_parse)\n\n\n def vacancy_parse(self, response: HtmlResponse):\n name = response.xpath(\"//h1[@data-qa='vacancy-title']/text()\").get()\n salary = response.xpath(\"//span[@data-qa = 'vacancy-salary-compensation-type-net']/text()\").getall()\n link = response.xpath(\"//link[@rel = 'canonical']/@href\").get()\n item = JobparserItem(name=name, salary=salary, link=link)\n yield item","sub_path":"jobparser/spiders/hhru.py","file_name":"hhru.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"329259075","text":"# EJERCICIO 7\n#!/usr/bin/python\n\nimport random,sys,math\nimport numpy\nfrom scipy import stats\n\ndef intervalo(lista, variable):\n acc = 0\n for x in lista:\n acc += x\n prom = acc / len(lista)\n # print \"Prom: \" + str(prom)\n\n # Calculo de intervalo de confianza\n numerador = 0\n for x in lista:\n numerador += (x - prom) * (x - prom)\n\n # print \"Numerador: \" + str(numerador)\n\n desv_std = math.sqrt(numerador / (len(lista) - 1))\n\n # print \"Desviacion std: \" + str(desv_std)\n\n gl = len(lista) - 1\n\n # print \"Grados de libertad: \" + str(gl)\n\n alpha = 0.10\n\n z_val = stats.norm.ppf(1-(alpha / 2))\n\n delta = z_val * (desv_std / (math.sqrt(len(lista))))\n\n x_inf = prom - delta\n x_sup = prom + delta\n\n print( \"\\nVariabe: \" + variable)\n print( \"Existe una probabilidad \" + str((1 - alpha) * 100) + \"% que el intervalo (\" + str(x_inf) + \",\" + str(x_sup) + \") incluya el valor real\")\n\n\ndef generar_demanda_diaria():\n\n\tdist = random.random()\n\n\tif dist <= 0.05:\n\t\treturn 12\n\telif dist <= 0.2:\n\t\treturn 13\n\telif dist <= 0.45:\n\t\treturn 14\n\telif dist <= 0.8:\n\t\treturn 15\n\telif dist <= 0.95:\n\t\treturn 16\n\telse:\n\t\treturn 17\n\n\ndef generar_tiempo_entrega():\n\n\tdist = random.random()\n\n\tif dist <= 0.2:\n\t\treturn 1\n\telif dist <= 0.5:\n\t\treturn 2\n\telif dist <= 0.85:\n\t\treturn 3\n\telse:\t\n\t\treturn 4\n\n\nespera = False\nQ = 100\n\ndef modelo(r):\n\n\tglobal espera\n\n\tproductos_iniciales = 100\n\tproductos_actuales = productos_iniciales\n\tproductos_escaceados = 0\n\n\tdias_espera_pedido = -1\n\n\tcosto_total = 0\n\n\t# Ciclo por 30 dias para el intervalo de confianza\n\tfor dia in range(30):\n\n\t\tdemanda = generar_demanda_diaria()\n\n\t\t# Si tengo productos para satisfacer la demanda\n\t\tif demanda <= productos_actuales:\n\n\t\t\tproductos_actuales -= demanda\n\n\t\t# Sino, hay productos escaceando\n\t\telse:\n\n\t\t\tproductos_escaceados += (demanda - productos_actuales)\n\t\t\tcosto_total += 1*productos_escaceados\n\t\t\tproductos_actuales = 0\n\n\t\t# Si no hay productos & no estan por llegar, debo hacer un pedido por Q unidades\n\t\tif productos_actuales <= r and dias_espera_pedido == -1:\n\n\t\t\ttiempo_entrega = generar_tiempo_entrega()\n\t\t\tdias_espera_pedido = tiempo_entrega\n\t\t\tcosto_total += 10\n\n\t\t# Si me sobraron productos en el dia, aumento costo total\n\t\tif productos_actuales > 0:\n\n\t\t\tcosto_total += 0.2*productos_actuales\n\n\n\t\t# Si estaba en espera de un pedido y no ha llegado\n\t\tif dias_espera_pedido != -1:\n\n\t\t\t#aumento numero de dias en espera\n\t\t\tdias_espera_pedido -= 1\n\n\t\t\t# Si el pedido llega ese dia\n\t\t\tif dias_espera_pedido == 0:\n\n\t\t\t\tdias_espera_pedido = -1\n\t\t\t\tproductos_actuales += Q\n\n\t\t\t\t# Si todavia debo productos\n\t\t\t\tif productos_escaceados > 0:\n\n\t\t\t\t\tif productos_actuales >= productos_escaceados:\n\n\t\t\t\t\t\tproductos_actuales -= productos_escaceados\n\t\t\t\t\t\tproductos_escaceados = 0\n\n\t\t\t\t\telse:\n\n\t\t\t\t\t\tproductos_escaceados -= productos_actuales\n\t\t\t\t\t\tproductos_actuales = 0\n\n\n\treturn costo_total\n\nprint(\"\\n\\nNumero de iteraciones a simular:\")\niteraciones = input()\niteraciones = int(iteraciones)\nmejor_costo = numpy.inf\nmejor_R = 0\nlista_costos = []\n\nfor r in range(100):\n\n\tcostos = 0\n\t\n\tfor i in range(iteraciones):\n\t\tcostos += modelo(0)\n\n\tcosto_promedio = (costos/iteraciones)\n\tlista_costos.append(costo_promedio)\n\n\tif costo_promedio < mejor_costo:\n\t\tmejor_costo = costo_promedio\n\t\tmejor_R = r\n\n\tprint(\"Costo promedio con R = %s, $%s\" % (r, costo_promedio))\n\nprint(\"Mejor Costo Total Variable: R = %s de $%s\" % (mejor_R, mejor_costo))\n\n\nprint(\"\\n\\n-------- INTERVALO --------\")\nintervalo(lista_costos, \"Costos\")","sub_path":"ejercicio_7.py","file_name":"ejercicio_7.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"542039722","text":"import json\nimport requests\n\nfrom benchmarks.utils import get_class_by_reference\nfrom settings import RESULTS_FILE_PATH, METRICS_REGISTRY, REMOTE_SOURCE_API_URL, PUBLISH_RESULTS\n\n\nclass ResultsHandler(object):\n \"\"\"\n Results handler class.\n \"\"\"\n\n def store(self, results):\n results = [r for r in results if r[\"runtime\"] != \"-\"]\n self.store_results_in_local_source(results)\n if PUBLISH_RESULTS: self.store_results_in_remote_source(results)\n\n def are_results_equal(self, old, new):\n \"\"\"\n Checks whether old and new results are equal.\n\n Args:\n old (dict): old result.\n new (dict): new result.\n\n Returns:\n bool\n \"\"\"\n return old[\"siteName\"] == new[\"siteName\"] and old[\"type\"] == new[\"type\"] and old[\"name\"] == new[\"name\"]\n\n def store_results_in_local_source(self, results):\n \"\"\"\n Stores results locally on RESULTS_FILE_PATH as JSON.\n \"\"\"\n with open(RESULTS_FILE_PATH) as f:\n all_results = json.loads(f.read() or \"[]\")\n for result in results:\n all_results = [r for r in all_results if not self.are_results_equal(r, result)]\n all_results.append(result)\n with open(RESULTS_FILE_PATH, \"w+\") as f:\n f.write(json.dumps(all_results, indent=4))\n\n def store_results_in_remote_source(self, results):\n \"\"\"\n Stores results on remote source (Google Spreadsheets).\n \"\"\"\n session = requests.Session()\n data = {\"results\": results}\n headers = {\"Content-Type\": \"application/json\"}\n response = session.request(method=\"PUT\", url=REMOTE_SOURCE_API_URL, data=json.dumps(data), headers=headers)\n response.raise_for_status()\n\n def plot(self, site_names, metric):\n \"\"\"\n Plots the results for given site names and metric.\n\n Args:\n site_names (list): list of site names.\n metric (str): metric name.\n \"\"\"\n with open(RESULTS_FILE_PATH) as f:\n results = json.loads(f.read())\n metric = get_class_by_reference(METRICS_REGISTRY[metric])(results)\n metric.plot(site_names)\n","sub_path":"results/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"191773071","text":"class Solution:\n # @param candidates, a list of integers\n # @param target, integer\n # @return a list of lists of integers\n\n def combinationSum2(self, candidates, target):\n #candidates = list(set(candidates))\n candidates.sort()\n q = []\n n = len(candidates)\n ans = []\n\n for i in range(n - 1, -1, -1):\n if candidates[i] <= target:\n q.append(([(candidates[i], i)], target - candidates[i]))\n\n while len(q):\n l, t = q.pop(0)\n if t == 0:\n v = map(lambda l: l[0], l)[::-1]\n if not v in ans:\n ans.append(v)\n else:\n for i in range(l[-1][1] - 1, -1, -1):\n if candidates[i] <= t:\n lc = list(l)\n lc.append((candidates[i], i))\n q.append((lc, t - candidates[i]))\n return ans\n","sub_path":"CombinationSum2/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"510493592","text":"#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom nav_msgs.msg import Odometry\nfrom ap_msgs.msg import NavStatus\n\n\n\n\n\nclass NavMonitor(object):\n def __init__(self):\n self.goal_z=0\n self.current_z=0\n \n self.n_fails=0\n self.MAX_FAILS=100\n \n rospy.init_node('nav_monitor') \n rospy.Subscriber(\"/cmd_vel\", Twist, self.vel_callback) \n rospy.Subscriber(\"/odom\", Odometry, self.odom_callback)\n \n self.pub = rospy.Publisher('nav_status', NavStatus)\n self.pub_msg=NavStatus()\n\n\n def vel_callback(self,msg):\n self.goal_z=msg.angular.z\n if self.goal_z != 0 and self.current_z==0:\n self.n_fails=self.n_fails+1\n else:\n self.n_fails=0\n if self.n_fails>self.MAX_FAILS:\n self.pub_msg.carpet_stuck=True\n else:\n self.pub_msg.carpet_stuck=False\n self.pub.publish(self.pub_msg)\n\n \n\n\n def odom_callback(self,msg):\n self.current_z=msg.twist.twist.angular.z\n\n \n \n\n \n \n \nif __name__ == '__main__':\n\n\n NavMonitor()\n \n \n rospy.spin() \n","sub_path":"nav_monitor/scripts/nav_monitor.py","file_name":"nav_monitor.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364841061","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\n\n\n\nX = np.linspace(-3,5,100)\nY = np.linspace(-4,4,100)\n\nx,y = np.meshgrid(X,Y)\n\nx.shape == y.shape == (100,100)\n\nz_data = np.zeros(2000000).reshape(100,100,200)\n\nfor t in np.arange(200):\n T = t/200\n z_data[:,:,t] = pow(y, 2) - pow(x, 3) + x - (1 - 2*T)\n\nfig,ax = plt.subplots()\n\ndef animate(i):\n ax.clear()\n ax.contour(x,y,z_data[:,:,i], 0)\n ax.set_xlim(-3,5)\n ax.set_ylim(-4,4)\n ax.spines['left'].set_position('zero')\n ax.spines['right'].set_color('none')\n ax.spines['top'].set_color('none')\n ax.spines['bottom'].set_position('zero')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_title('%03d'%(i)) \n return ax\n\nanim = animation.FuncAnimation(fig, animate, frames=200, interval=50, repeat=False, blit=False)\n\nHTML(anim.to_html5_video())","sub_path":"Examples/myAnim.py","file_name":"myAnim.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"473461565","text":"import sys\n\nfrom django.apps import apps\nfrom django.contrib.auth.models import Permission\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.db.models import Q\nfrom django.dispatch import Signal\n\nfrom ..utils.autoupdate import Element, inform_changed_elements\n\n\n# This signal is send when the migrate command is done. That means it is sent\n# after post_migrate sending and creating all Permission objects. Don't use it\n# for other things than dealing with Permission objects.\npost_permission_creation = Signal()\n\n# This signal is sent if a permission is changed (e. g. a group gets a new\n# permission). Connected receivers may yield Collections.\npermission_change = Signal()\n\n\ndef delete_django_app_permissions(sender, **kwargs):\n \"\"\"\n Deletes the permissions, Django creates by default. Only required\n for auth, contenttypes and sessions.\n \"\"\"\n contenttypes = ContentType.objects.filter(\n Q(app_label=\"auth\") | Q(app_label=\"contenttypes\") | Q(app_label=\"sessions\")\n )\n Permission.objects.filter(content_type__in=contenttypes).delete()\n\n\ndef get_permission_change_data(sender, permissions, **kwargs):\n \"\"\"\n Yields all necessary Cachables if the respective permissions change.\n \"\"\"\n core_app = apps.get_app_config(app_label=\"core\")\n for permission in permissions:\n if permission.content_type.app_label == core_app.label:\n if permission.codename == \"can_see_projector\":\n yield core_app.get_model(\"Projector\")\n elif permission.codename == \"can_manage_projector\":\n yield core_app.get_model(\"ProjectorMessage\")\n yield core_app.get_model(\"Countdown\")\n elif permission.codename == \"can_use_chat\":\n yield core_app.get_model(\"ChatMessage\")\n\n\ndef autoupdate_for_many_to_many_relations(sender, instance, **kwargs):\n \"\"\"\n Send autoupdate for many-to-many related objects if the other side\n is deleted.\n \"\"\"\n # Hotfix for #4501: Skip autoupdate for many-to-many related objects\n # during migrations.\n if \"migrate\" in sys.argv:\n return\n\n m2m_fields = (\n field\n for field in instance._meta.get_fields(include_hidden=True)\n if field.many_to_many and field.auto_created\n )\n for field in m2m_fields:\n queryset = getattr(instance, field.get_accessor_name()).all()\n for related_instance in queryset:\n if hasattr(related_instance, \"get_root_rest_element\"):\n # The related instance is or has a root rest element.\n # So lets send it via autoupdate.\n root_rest_element = related_instance.get_root_rest_element()\n inform_changed_elements(\n [\n Element(\n collection_string=root_rest_element.get_collection_string(),\n id=root_rest_element.pk,\n full_data=None,\n reload=True,\n )\n ]\n )\n","sub_path":"openslides/core/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"451504125","text":"# -*- coding : utf-8 -*-\nfrom flickr_api.send_requests import *\nimport pymysql.cursors\nfrom datetime import datetime\nimport json,os\n\nwith open('config.json','r') as f:\n config_raw = f.read()\n CONFIG = json.loads(config_raw)\n\nclass DB_Operater:\n \"\"\"\n データベースを更新するときに発火するいろいろ\n update() -> 新しく撮影された写真を追加する\n complement -> もし取得漏れデータがあった場合に発火する。\n 取得できていない写真データを取得する。\n \"\"\"\n def __init__(self):\n self.HOST = CONFIG['DB']['HOST']\n self.USER = CONFIG['DB']['USER']\n self.PASSWORD = CONFIG['DB']['PASSWORD']\n self.DB_NAME = CONFIG['DB']['DB_NAME']\n # self.PHOTO_TABLE_NAME = 'photo_flickr_photo'\n self.PHOTO_TABLE_NAME = 'test_photo_flickr_update'\n #self.update_start_datetime = datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n self.update_start_datetime = '2015/12/31 12:00:00' # for test\n self.should_update_flickr_ids = False\n self.should_complement_flickr_ids = False\n\n def get_should_update(self):\n\n \"\"\"\n アップデートする写真があればfliclr_idを\n なければFalseを返す\n\n 1. 最新画像idを取得(1回で500枚\n 2. 新しい順にデータベース上にあるかを判別 1ページ上のすべての写真データが\n 挿入できる場合、次のページのリクエストを送るフラグを立てる\n 3. データベース上にある写真データが見つかるまで2を繰り返して見つかったら終了\n 4. 0件見つかったらFalseを、1件以上見つかったらそのidの数とid(配列?)を返すa\n \"\"\"\n\n per_page = 20\n num_page = overview(per_page=per_page)['num_page'] #総ページ数を取得\n\n #挿入可能なflickr_idを格納するリスト\n can_insert_ids = []\n\n # local databaseに接続\n connection = pymysql.connect(\n host = self.HOST,\n user = self.USER,\n passwd = self.PASSWORD,\n db = self.DB_NAME)\n\n #ページのイテレート\n should_stop_request_next_page = False\n\n for p in range(1,num_page+1):\n\n # フラグをみてリクエストを送るべきか判断する\n if should_stop_request_next_page:\n break\n\n photos = send_photo_search_requests(\n page=p,\n per_page=per_page,\n )['photos']['photo']\n ids = []\n\n # local database上に存在しなければcan_insert_idsにflickr_idをappendする\n # 写真idのイテレート\n count_can_insert_per_page = 0 #1ページにinsert可能な写真が何枚あるかを格納する ==num_pageだったらループを閉じるフラグを立てる\n for photo in photos:\n flickr_id = photo['id']\n\n with connection.cursor() as cursor:\n sql = 'SELECT flickr_id,data_taken FROM {0} WHERE flickr_id = \"{1}\"'.format(self.PHOTO_TABLE_NAME,flickr_id)\n cursor.execute(sql)\n data = cursor.fetchall()\n\n if(len(data)==0) : #local database上に存在しない場合\n can_insert_ids.append(flickr_id)\n count_can_insert_per_page +=1\n\n #次のリクエストを送るためのフラグを操作\n if(count_can_insert_per_page < per_page):\n should_stop_request_next_page = True\n\n connection.close()\n\n self.should_update_flickr_ids = can_insert_ids\n\n if can_insert_ids:\n return True\n else:\n return False\n\n def update(self):\n \"\"\"\n リモートの最新画像をとる\n 新しい写真から順番にローカルにぶちこんでいく\n すでに存在する写真データとぶつかったらプログラム終了\n \"\"\"\n\n should_update = self.get_should_update()\n should_updates = self.should_update_flickr_ids\n\n if should_update == False:\n msg = '更新可能なデータはありません。'\n print(msg)\n return False\n else:\n msg = '更新可能なデータが{0}件あります。データベースを更新します。'.format(len(should_updates))\n print(msg)\n\n\n connection = pymysql.connect(\n host = self.HOST,\n user = self.USER,\n passwd = self.PASSWORD,\n db = self.DB_NAME)\n\n with connection.cursor() as cursor:\n\n count_inserted = 0\n total = len(should_updates)\n for id in should_updates:\n\n response = send_get_info_request(id)\n flickr_id = id\n date_taken = response['photo']['dates']['taken']\n\n now = datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n sql = \"\"\"\n INSERT INTO {0} (\n flickr_id,\n data_taken,\n created,\n updated\n ) VALUE (\n '{1}',\n '{2}',\n '{3}',\n '{4}'\n );\n \"\"\".format(\n self.PHOTO_TABLE_NAME,\n flickr_id,\n date_taken,\n now,\n now\n )\n cursor.execute(sql)\n connection.commit()\n count_inserted += 1\n print('flickr_id:{0} data_taken:{1} をデータベースに挿入しました。 ({2}/{3})'.format(\n flickr_id,date_taken,count_inserted,total\n ))\n connection.close()\n\n\n\n\n def get_should_complement(self):\n \"\"\"\n 取得漏���があるかどうかを判断する\n あれば取得漏れしたflickr_idを格納したlistを返す\n なければFalseを返す。\n\n 1. リモートサーバーのflickr_idをすべて(?)取得する\n 2. ローカルサーバーとの差分を取得 一回に全部取得するとめちゃくちゃな数を計算するので\n 1ページごとに差分を計算する\n 3. 差分を返す\n \"\"\"\n\n\n # num_page = overview()['num_page']\n num_page = 2 # test\n\n connection = pymysql.connect(\n host = self.HOST,\n user = self.USER,\n passwd = self.PASSWORD,\n db = self.DB_NAME)\n\n with connection.cursor() as cursor:\n\n #取得漏れしたflickr_idを格納するlist\n should_complement_ids = []\n\n for p in range(1,num_page+1):\n response = send_photo_search_requests(page=p)\n photos = response['photos']['photo']\n\n for photo in photos:\n flickr_id = photo['id']\n\n sql = \"\"\"\n SELECT * FROM {0} WHERE flickr_id = '{1}'\n \"\"\".format(self.PHOTO_TABLE_NAME,flickr_id)\n\n cursor.execute(sql)\n data = cursor.fetchall()\n\n if data:\n pass\n else:\n should_complement_ids.append(flickr_id)\n\n msg = '{0} / {1} ページの探索が終了。取得漏れ総数:{2}件'.format(p,num_page,len(should_complement_ids))\n print(msg)\n\n connection.close()\n\n if len(should_complement_ids) != 0:\n self.should_complement_flickr_ids = should_complement_ids\n return True\n else:\n return False\n\n\n\n\n def complement(self):\n \"\"\"\n get_should_complement()関数を実行して\n 補完すべきデータを見つけたらinsertをする。\n 補完すべきデータが見つからなかった場合、get_should_complement()はFalseを返す\n 補完すべきデータはコンストラクタshould_complement_flickr_idsに格納されている\n \"\"\"\n\n # フラグチェック\n should_complement = self.get_should_complement()\n if should_complement == False:\n msg = '取得漏れが見つからなかったため、補完を実行しません。'\n print(msg)\n return False\n msg = '取得漏れが{0}件見つかりました。補完を開始します。'.format(len(self.should_complement_flickr_ids))\n print(msg)\n\n\n # local DBへのinsertを開始する\n # TODO: 挿入のコードを何箇所も書いているので関数化した方がいい。 このクラスとは別でつくるべき?\n connection = pymysql.connect(\n host = self.HOST,\n user = self.USER,\n passwd = self.PASSWORD,\n db = self.DB_NAME)\n\n with connection.cursor() as cursor:\n count_inserted = 0\n total = len(self.should_complement_flickr_ids)\n\n for id in self.should_complement_flickr_ids:\n\n response = send_get_info_request(id)\n flickr_id = id\n date_taken = response['photo']['dates']['taken']\n\n now = datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n sql = \"\"\"\n INSERT INTO {0} (\n flickr_id,\n data_taken,\n created,\n updated\n ) VALUE (\n '{1}',\n '{2}',\n '{3}',\n '{4}'\n );\n \"\"\".format(\n self.PHOTO_TABLE_NAME,\n flickr_id,\n date_taken,\n now,\n now\n )\n cursor.execute(sql)\n connection.commit()\n count_inserted += 1\n print('flickr_id:{0} data_taken:{1} をデータベースに挿入しました。 ({2}/{3})'.format(\n flickr_id,date_taken,count_inserted,total\n ))\n connection.close()\n","sub_path":"src/db_operator/updateDB.py","file_name":"updateDB.py","file_ext":"py","file_size_in_byte":10289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"521531749","text":"# !/usr/bin/env python\n# encoding: utf-8\n#\n# This file is part of ckanext-nhm\n# Created by the Natural History Museum in London, UK\n\n'''\nController for displaying an individual record\nLoads all the data and then defers render function to view objects\n'''\n\nimport json\nimport logging\n\nfrom ckan import model\nfrom ckan.plugins import toolkit\nfrom flask import Blueprint, current_app\n\nfrom ckanext.nhm.lib.helpers import resource_view_get_view\nfrom ckanext.nhm.lib.jinja_extensions import TaxonomyFormatExtension\nfrom ckanext.nhm.views import DarwinCoreView\n\nlog = logging.getLogger(__name__)\n\nblueprint = Blueprint(name='record', import_name=__name__, url_prefix='/dataset')\n\n\ndef _load_data(package_name, resource_id, record_id, version=None):\n '''Load the data for dataset, resource and record (into toolkit.c variable).\n\n :param package_name:\n :param record_id:\n :param resource_id:\n\n '''\n context = {\n 'user': toolkit.c.user or toolkit.c.author\n }\n\n # try & get the resource\n try:\n toolkit.c.resource = toolkit.get_action('resource_show')(context, {\n 'id': resource_id\n })\n toolkit.c.package = toolkit.get_action('package_show')(context, {\n 'id': package_name\n })\n # required for nav menu\n toolkit.c.pkg = context['package']\n toolkit.c.pkg_dict = toolkit.c.package\n\n record_data_dict = {\n 'resource_id': resource_id,\n 'record_id': record_id\n }\n if version is not None:\n version = int(version)\n record_data_dict['version'] = version\n toolkit.c.version = version\n record = toolkit.get_action('record_show')(context, record_data_dict)\n toolkit.c.record_dict = record['data']\n\n except toolkit.ObjectNotFound:\n toolkit.abort(404, toolkit._('Resource not found'))\n except toolkit.NotAuthorized:\n toolkit.abort(401, toolkit._(f'Unauthorized to read resource {package_name}'))\n\n field_names = {\n 'image': toolkit.c.resource.get('_image_field', None),\n 'title': toolkit.c.resource.get('_title_field', None),\n 'latitude': toolkit.c.resource.get('_latitude_field', None),\n 'longitude': toolkit.c.resource.get('_longitude_field', None),\n }\n\n # if this is a DwC dataset, add some default for image and lat/lon fields\n if toolkit.c.resource['format'].lower() == 'dwc':\n for field_name, dwc_field in [('latitude', 'decimalLatitude'),\n ('longitude', 'decimalLongitude')]:\n if dwc_field in toolkit.c.record_dict:\n field_names[field_name] = dwc_field\n\n # assign title based on the title field\n toolkit.c.record_title = toolkit.c.record_dict.get(field_names['title'],\n f'Record {toolkit.c.record_dict.get(\"_id\")}')\n\n # sanity check: image field hasn't been set to _id\n if field_names['image'] and field_names['image'] != '_id':\n default_copyright = '© The Trustees of the Natural History ' \\\n 'Museum, London'\n licence_id = toolkit.c.resource.get('_image_licence') or 'cc-by'\n short_licence_id = licence_id[:5].lower()\n # try and overwrite default licence with more specific one\n for l_id in [licence_id, short_licence_id]:\n try:\n licence = model.Package.get_license_register()[l_id]\n break\n except KeyError:\n continue\n\n licence_url = toolkit.h.link_to(licence.title, licence.url, target=\"_blank\")\n default_licence = f'Licence: {licence_url}'\n\n # pop the image field so it isn't output as part of the\n # record_dict/field_data dict (see self.view())\n image_field_value = toolkit.c.record_dict.pop(field_names['image'], None)\n\n if image_field_value:\n # init the images list on the context var\n toolkit.c.images = []\n\n if isinstance(image_field_value, list):\n for image in image_field_value:\n href = image.get('identifier', None)\n if href:\n license_link = toolkit.h.link_to(image.get('license'),\n image.get(\n 'license')) if image.get(\n 'license', None) else None\n toolkit.c.images.append({\n 'title': image.get('title', None) or toolkit.c.record_title,\n 'href': href,\n 'copyright': f'{license_link or default_licence}
'\n f'{image.get(\"rightsHolder\", None) or default_copyright}',\n 'record_id': record_id,\n 'resource_id': resource_id,\n 'link': toolkit.url_for('record.view', package_name=package_name,\n resource_id=resource_id, record_id=record_id),\n })\n else:\n # it's a string field value, use the delimiter to split up the field\n # value (if there is one!)\n delimiter = toolkit.c.resource.get('_image_delimiter', None)\n if delimiter:\n images = image_field_value.split(delimiter)\n else:\n images = [image_field_value]\n # loop through the images, adding dicts with their details to the context\n for image in images:\n if image.strip():\n toolkit.c.images.append({\n 'title': toolkit.c.record_title,\n 'href': image.strip(),\n 'copyright': f'{default_licence}
{default_copyright}'\n })\n\n if field_names['latitude'] and field_names['longitude']:\n latitude = toolkit.c.record_dict.get(field_names['latitude'])\n longitude = toolkit.c.record_dict.get(field_names['longitude'])\n\n if latitude and longitude:\n # create a piece of GeoJSON to point at the specific record location on a map\n toolkit.c.record_map = json.dumps({\n 'type': 'Point',\n 'coordinates': [float(longitude), float(latitude)]\n })\n\n\n@blueprint.before_app_first_request\ndef init_jinja_extensions():\n '''\n This hook is called before the first request is received by the app and therefore allows us to\n ensure that the taxonomy extension is loaded into jinja2 before it's used.\n '''\n # Load the taxonomy formatter\n current_app.jinja_env.add_extension(TaxonomyFormatExtension)\n\n\n@blueprint.route('//resource//record/',\n defaults={'version': None})\n@blueprint.route('//resource//record//')\ndef view(package_name, resource_id, record_id, version):\n '''View an individual record.\n\n :param package_name:\n :param record_id:\n :param resource_id:\n :param version:\n\n '''\n _load_data(package_name, resource_id, record_id, version)\n view_cls = resource_view_get_view(toolkit.c.resource)\n return view_cls.render_record(toolkit.c)\n\n\n@blueprint.route('//resource//record//dwc',\n defaults={'version': None})\n@blueprint.route('//resource//record//dwc/')\ndef dwc(package_name, resource_id, record_id, version):\n '''Explicit DwC view\n\n :param package_name:\n :param record_id:\n :param resource_id:\n :param version:\n\n '''\n _load_data(package_name, resource_id, record_id, version)\n\n # Is this a DwC view of an additional dataset?\n # In which case, provide links back to the original record view\n toolkit.c.additional_view = True\n\n return DarwinCoreView().render_record(toolkit.c)\n","sub_path":"ckanext/nhm/routes/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":8103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"277686638","text":"import numpy as np\nfrom numpy.linalg import inv\n\n\n################\n# Euler Method #\n################\n\ndef euler(x0, y0, U, V, dt):\n\n u = U(x0, y0)\n x1 = x0 + (u * dt)\n\n v = V(x0, y0)\n y1 = y0 + (v * dt)\n \n return [x1, y1]\n \n\n###########################\n# Runge-Kutta integration #\n###########################\n\ndef RK4(x0, y0, U, V, dt):\n \n uk1 = U(x0, y0)\n vk1 = V(x0, y0)\n\n uk2 = U(x0+0.5*uk1*dt, y0+0.5*vk1*dt)\n vk2 = V(x0+0.5*uk1*dt, y0+0.5*vk1*dt)\n\n uk3 = U(x0+0.5*uk2*dt, y0+0.5*vk2*dt)\n vk3 = V(x0+0.5*uk2*dt, y0+0.5*vk2*dt)\n\n uk4 = U(x0+uk3*dt, y0+vk3*dt)\n vk4 = V(x0+uk3*dt, y0+vk3*dt)\n \n u = ((uk1 + 2*uk2 + 2*uk3 + uk4) / 6)\n v = ((vk1 + 2*vk2 + 2*vk3 + vk4) / 6)\n x1 = x0 + dt * u\n y1 = y0 + dt * v\n \n return [x1, y1], [u, v]\n\n# def RK4(x0, y0, U, V, dt):\n#\n# uk1 = dt * U(x0, y0)\n# vk1 = dt * V(x0, y0)\n#\n# uk2 = dt * U(x0+0.5*uk1, y0+0.5*vk1)\n# vk2 = dt * V(x0+0.5*uk1, y0+0.5*vk1)\n#\n# uk3 = dt * U(x0+0.5*uk2, y0+0.5*vk2)\n# vk3 = dt * V(x0+0.5*uk2, y0+0.5*vk2)\n#\n# uk4 = dt * U(x0+uk3, y0+vk3)\n# vk4 = dt * V(x0+uk3, y0+vk3)\n#\n# x1 = x0 + ((uk1 + 2*uk2 + 2*uk3 + uk4) / 6)\n# y1 = y0 + ((vk1 + 2*vk2 + 2*vk3 + vk4) / 6)\n#\n# return [x1, y1]\n\n########\n# Plot #\n########\n\ndef plot(x, y, x0=None, y0=None):\n\n import matplotlib.pyplot as plt\n\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10,10))\n ax.plot(x,y)\n if x0 is not None:\n ax.scatter(x0, y0, marker='x', c='k')\n\n plt.show()\n\n###############################################################################\n# Below is an attempt at presenting trajectory problem in state-space form #\n# -- Needs to be revised using Runge-Kutta #\n###############################################################################\n\n############################\n# Randum turbulent impulse #\n############################\n\ndef impulse(i, dw):\n F = np.array([0.0,0.0])\n F[0] = np.sqrt(K) * (dw[i]/delta_t)\n return F\n \n#########################################\n# Slope function for Runge-Kutta method #\n#########################################\n\ndef F(y, i, dw):\n return inv(A).dot(impulse(i, dw) - B.dot(y))\n\n######################\n# Gaussian mean flow #\n######################\n\ndef gaus(x, r, mean, shift):\n g = mean * np.exp(-(x-r)**2 / (0.1*r**2)) + shift\n return g\n\n###############################################################################\n \n \n# =============================================================================\n# CIRCULAR - RANDOM\n# =============================================================================\n\nUmean = 0.35\nVmean = 0.35\nn = 2\ndt = 1.0\nstop = 1.0\n\ndef launch(Umean, Vmean, n=1, dt=30, stop=3):\n # RETURNS t, u, v\n\n # TIME DOMAIN\n # Time series with half-hour increments (units: seconds) for 3 days\n dt = dt*60.\n end_time = stop*24*60*60\n t = np.arange(start=0, stop=end_time+1, step=dt)\n \n # Empty objects to fill: total velocity\n u = np.zeros([len(t),n])\n v = np.zeros([len(t),n])\n\n # Gaussian sheared background flow with random turbulent velocity\n \n # SPATIAL DOMAIN (units: m)\n r = 20000.0 # should be 20 km \n x = np.arange(start=0, stop=1*r)\n y = np.arange(start=0, stop=1*r)\n \n # Rotational background flow (m/s)\n Umean = np.arange(start=-Umean, stop=Umean, step=((2*Umean)/r))\n Vmean = np.arange(start=-Vmean, stop=Vmean, step=((2*Vmean)/r))\n\n V, U = np.meshgrid(Umean[::-1], Vmean)\n\n # Initial positions for each particle\n # All particles start at x0=0, but at different points along the y-axis (between 500-3500 m -- see above) in order to capture different parts of the mean flow.\n x0 = [7500,5000]\n y0 = [1000,1000]\n #y0 = np.linspace(5000, len(Ugaus)-5000, n, dtype='int')\n \n # PARAMETERS (see Griffa 1998 and Falco 2000)\n T_L = 2.*24*60*60 # Lagrangian turbulent time scale: \n # O(2-10 days)\n sigma2 = 0.e-2 # Variance of turbulent velocity: \n # O(10^-3-10^-2 m^2/s^2) or O(10-100 cm^2/s^s)\n K = sigma2 / T_L # Diffusion coefficient\n\n dwx = np.random.random(size=len(t))\n dwy = np.random.random(size=len(t))\n #dwx = np.random.normal(loc=0, # Random increment from normal\n # scale=np.sqrt(2*dt), # distribution with mean =0 and\n # size=len(t)) # second moment (variance) =2*dt.\n #dwy = np.random.normal(loc=0, # Randomly generated for each observation\n #scale=np.sqrt(2*dt), # in time t. Corresponds to a \"push\"\n #size=len(t)) # due to turbulent velocity.\n \n # Initialize mean velocity for each particle\n Ubar, Vbar = U[y0,x0], V[y0,x0]\n\n # Initialize turbulent velocity for each particle:\n u_prime = np.random.normal(loc=0,scale=sigma2,size=n)\n v_prime = np.random.normal(loc=0,scale=sigma2,size=n)\n\n # Load total velocity matrices:\n # u = U + u' and v = V + v'\n u[0,:] = Ubar + u_prime\n v[0,:] = Vbar + v_prime\n\n # New (x,y) position\n \n #######################\n # Runge Kutta 4th Order\n kx1 = dt * u[0,:]\n ky1 = dt * v[0,:]\n xk1 = x0 + (0.5 * kx1)\n yk1 = y0 + (0.5 * ky1)\n uk1 = U[np.round(yk1).astype(int),np.round(xk1).astype(int)] + u_prime\n vk1 = V[np.round(yk1).astype(int),np.round(xk1).astype(int)] + v_prime\n \n kx2 = dt * uk1\n ky2 = dt * vk1\n xk2 = x0 + (0.5 * kx2)\n yk2 = y0 + (0.5 * ky2)\n uk2 = U[np.round(yk2).astype(int),np.round(xk2).astype(int)] + u_prime\n vk2 = V[np.round(yk2).astype(int),np.round(xk2).astype(int)] + v_prime\n \n kx3 = dt * uk2\n ky3 = dt * vk2\n xk3 = x0 + kx3\n yk3 = y0 + ky3\n uk3 = U[np.round(yk3).astype(int),np.round(xk3).astype(int)] + u_prime\n vk3 = V[np.round(yk3).astype(int),np.round(xk3).astype(int)] + v_prime\n \n kx4 = dt * uk3\n ky4 = dt * uk3\n \n x1 = np.round(x0 + dt * (kx1 + 2*kx2 + 2*kx3 + kx4)/6)\n y1 = np.round(y0 + dt * (ky1 + 2*ky2 + 2*ky3 + ky4)/6)\n #######################\n \n # Make (x,y) NaN if out of bounds\n y1[np.logical_or(y1<0, y1>len(Umean))] = np.nan\n y1[np.logical_or(x1<0, x1>len(Vmean))] = np.nan\n x1[np.logical_or(y1<0, y1>len(Umean))] = np.nan\n x1[np.logical_or(x1<0, x1>len(Vmean))] = np.nan\n\n # Calculate the rest of the velocities: u'(u'(t-1))\n for i in range(1, len(t)):\n\n # Mean flow U,V based on new position (NaN if new position is out of bounds)\n for j in range(n):\n if np.isnan(x1[j]) or np.isnan(y1[j]):\n Ubar[j] = np.nan\n else:\n Ubar[j] = U[y1[j].astype(int),x1[j].astype(int)]\n\n for j in range(n):\n if np.isnan(x1[j]) or np.isnan(y1[j]):\n Vbar[j] = np.nan\n else:\n Vbar[j] = V[y1[j].astype(int),x1[j].astype(int)]\n \n # Turbulent velocity u',v' (see Griffa 1998)\n du = -(1/T_L)*u_prime*dt + np.sqrt(K)*dwx[i]\n dv = -(1/T_L)*v_prime*dt + np.sqrt(K)*dwy[i]\n u_prime += du\n v_prime += dv\n \n # Load total velocity matrices\n u[i,:] = Ubar + u_prime\n v[i,:] = Vbar + v_prime\n\n # New (x,y) position\n \n #######################\n # Runge Kutta 4th Order\n kx1 = dt * u[i,:]\n ky1 = dt * v[i,:]\n xk1 = x0 + (0.5 * kx1)\n yk1 = y0 + (0.5 * ky1)\n uk1 = U[np.round(yk1).astype(int),np.round(xk1).astype(int)] + u_prime\n vk1 = V[np.round(yk1).astype(int),np.round(xk1).astype(int)] + v_prime\n \n kx2 = dt * uk1\n ky2 = dt * vk1\n xk2 = x0 + (0.5 * kx2)\n yk2 = y0 + (0.5 * ky2)\n uk2 = U[np.round(yk2).astype(int),np.round(xk2).astype(int)] + u_prime\n vk2 = V[np.round(yk2).astype(int),np.round(xk2).astype(int)] + v_prime\n \n kx3 = dt * uk2\n ky3 = dt * vk2\n xk3 = x0 + kx3\n yk3 = y0 + ky3\n uk3 = U[np.round(yk3).astype(int),np.round(xk3).astype(int)] + u_prime\n vk3 = V[np.round(yk3).astype(int),np.round(xk3).astype(int)] + v_prime\n \n kx4 = dt * uk3\n ky4 = dt * uk3\n \n x1 += np.round(dt * (kx1 + 2*kx2 + 2*kx3 + kx4)/6)\n y1 += np.round(dt * (ky1 + 2*ky2 + 2*ky3 + ky4)/6)\n #######################\n \n # Make (x,y) NaN if out of bounds\n y1[np.logical_or(y1<0, y1>len(Umean))] = np.nan\n y1[np.logical_or(x1<0, x1>len(Vmean))] = np.nan\n x1[np.logical_or(y1<0, y1>len(Umean))] = np.nan\n x1[np.logical_or(x1<0, x1>len(Vmean))] = np.nan\n\n return t, u, v","sub_path":"flowRK4.py","file_name":"flowRK4.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"220702969","text":"from __future__ import division, print_function\nfrom modules.query_methods import MomentumQuerying\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nfrom matplotlib import animation\nimport numpy as np\n\n\nleft, width = .5, .5\nbottom, height = .5, .5\nright = left + width\ntop = bottom + height\n\ndef taskVisualization(posterior, query, alp):\n\n x = np.arange(len(alp))\n fig = plt.figure(figsize=(8, 6))\n gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])\n # ax1\n ax1 = plt.subplot(gs[0])\n ax1.set_xticks(x)\n # Hide the right and top spines\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n # Only show ticks on the left and bottom spines\n ax1.yaxis.set_ticks_position('left')\n ax1.xaxis.set_ticks_position('bottom')\n ax1.set_xticklabels(alp)\n ax1.set_title('Posterior Probability')\n ax1.set_ylabel('Probability')\n ax1.set_xlabel('Symbols')\n plot1 = ax1.bar(x, posterior, color=[0., 0., 0.])\n # ax2\n ax2 = plt.subplot(gs[1], aspect=1)\n # Hide the right and top spines\n ax2.spines['right'].set_visible(False)\n ax2.spines['left'].set_visible(False)\n ax2.spines['top'].set_visible(False)\n ax2.spines['bottom'].set_visible(False)\n ax2.set_xticks([])\n ax2.set_yticks([])\n #ax2.axis('off')\n ax2.set_facecolor((0., 0., 0.))\n # build a rectangle in axes coords\n left, width = .25, .5\n bottom, height = .25, .5\n right = left + width\n top = bottom + height\n # placing the query in the middle fo the screen\n ax2.axis('equal')\n # show the plot\n mng = plt.get_current_fig_manager()\n figS = np.array(mng.window.maxsize())*np.array([.5, .4])\n figSize = tuple(figS.astype(int))\n mng.resize(*figSize)\n plot2 = ax2.text(0.5*(left+right), 0.5*(bottom+top), query,\n horizontalalignment='center',\n verticalalignment='center',\n fontsize=40, color='yellow',\n transform=ax2.transAxes)\n\n\n return fig, plot1, plot2\n\ndef makeMovie(posterior, query, alp):\n\n fig, plot1, plot2 = taskVisualization(np.zeros(len(alp)), '', alp)\n\n def init():\n _, plot1, plot2 = taskVisualization(np.zeros(len(alp)), '+', alp)\n return plot1, plot2\n\n def animate(i):\n\n len_query = len(query[i])\n p = posterior[i]\n max_p_val = np.sort(p)[::-1]\n max_p_val = max_p_val[0:len_query]\n\n if i == 0:\n for rect, y in zip(plot1, posterior[i][0]):\n rect.set_height(y)\n plot2.set_text('')\n else:\n for rect, y in zip(plot1, posterior[i][0]):\n rect.set_height(y)\n plot2.set_text(query[i][0])\n\n return plot1, plot2\n\n # call the animator. blit=True means only re-draw the parts that have changed.\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=50, interval=20, blit=True)\n plt.rcParams['animation.ffmpeg_path'] ='C:\\\\Users\\\\Yeganeh\\\\ffmpeg\\\\bin\\\\ffmpeg.exe'\n FFwriter = animation.FFMpegWriter(fps=30, extra_args=['-vcodec', 'libx264'])\n\n plt.show()\n anim.save('test.mp4', writer = FFwriter)\n\n\n\n\n\n\n\n\n","sub_path":"simulation/python/modules/make_animation.py","file_name":"make_animation.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"123082263","text":"import numpy as np\nimport pydicom\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport imageio\nfrom scipy import interpolate\nfrom scipy import optimize\nfrom scipy.signal import convolve\nfrom skimage.filters import gaussian\nplt.style.use(['science', 'notebook'])\nimport tomopy\nimport functions\nimport pandas as pd\n\nfrom scipy.interpolate import RectBivariateSpline\nfrom skimage.data import shepp_logan_phantom\nfrom skimage.transform import radon, iradon, rescale, rotate\nfrom skimage.measure import profile_line\n\nconv_shaper = np.array([[[-1,0,0],\n [0,1,0],\n [0,0,0]],\n [[0,-1,0],\n [0,1,0],\n [0,0,0]],\n [[0,0,-1],\n [0,1,0],\n [0,0,0]],\n [[0,0,0],\n [0,1,-1],\n [0,0,0]],\n [[0,0,0],\n [0,1,0],\n [0,0,-1]],\n [[0,0,0],\n [0,1,0],\n [0,-1,0]],\n [[0,0,0],\n [0,1,0],\n [-1,0,0]],\n [[0,0,0],\n [-1,1,0],\n [0,0,0]],\n ])\n\ndrk = np.array([np.sqrt(2),1]*4)\n\ndef dM(M):\n dM = [convolve(M, filt, 'same') for filt in conv_shaper]\n return np.array(dM)\n\ndef w(o,l,mu=0.1,nu=0.2,kap=1/3, M=500):\n dork = dM(o)\n dlrk = dM(l)\n mu = mu*M\n nu = nu*M\n kap = kap*l.max()\n return np.exp(-(dork/mu)**2) + \\\n (1-np.exp(-(dork/mu)**2))*np.exp(-(dork/nu)**2)*np.exp(-(dlrk/kap)**2)\n\ndef dwdo(o,l,mu=0.1,nu=0.2,kap=1/3, M=500):\n mu = mu*M\n nu = nu*M\n kap = kap*l.max()\n dork = dM(o)\n dlrk = dM(l)\n fac = 2/(mu**2 * nu**2)\n t1 = np.exp(-(dork/mu)**2)\n t2 = np.exp(-(dork/nu)**2)\n t3 = np.exp(-(dlrk/kap)**2)\n return fac * (mu**2 *t1*t2*t3 - mu**2 * t3*t2 + nu**2 * t1*t2*t3 - nu**2 * t1) * dork\n \ndef f(o, i, l, h, lam):\n o_2D = o.reshape(400,400).copy()\n term1 = np.sum((i-convolve(o_2D,h, 'same'))**2) \n term2 = np.sum(w(o_2D,l)/drk[:,np.newaxis,np.newaxis]*dM(o_2D)**2)\n return (term1 + lam*term2)\ndef gradf(o, i, l, h, lam):\n o_2D = o.reshape(400,400).copy()\n term1 = 2*convolve((convolve(o_2D,h, 'same')-i), h, 'same')\n term2 = 4*np.sum(w(o_2D,l)/drk[:,np.newaxis,np.newaxis]*dM(o_2D), axis=0)\n term3 = 2*np.sum(1/drk[:,np.newaxis,np.newaxis] * dwdo(o_2D,l)*dM(o_2D)**2, axis=0)\n grad = term1 + lam*(term2+term3) \n return grad.ravel()","sub_path":"Phys 541/final_proj/.ipynb_checkpoints/paper_f_old-checkpoint.py","file_name":"paper_f_old-checkpoint.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"245784509","text":"import praw\nimport os\nimport textwrap\nimport datetime\nfrom config import *\n\n\nif not os.path.isfile(\"config.py\"):\n print(\"Credentials not found, exiting...\")\n exit(1)\n\n\nUA = \"A bot for testing purposes by u/Tomassias\"\n\nr = praw.Reddit(UA)\n\nr.login(REDDIT_USERNAME, REDDIT_PASSWORD, disable_warning=True)\n\nwrapper = textwrap.TextWrapper()\n\ndef get_submissions():\n subreddit = r.get_subreddit(\"all\")\n submissions = subreddit.get_hot(limit=1)\n\n for post in submissions:\n print(\"\\nTitle: \"+post.title)\n print(\"Contents: \"+post.selftext)\n print(\"Score: \" + str(post.score))\n comments = praw.helpers.flatten_tree(post.comments)\n\n print(\"Top comment: \" + \"\\n\".join(wrapper.wrap(comments[0].body)))\n\n\n\n\n\nget_submissions()","sub_path":"RedditBot/testbot.py","file_name":"testbot.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459601737","text":" # -*- coding: utf-8 -*-\nfrom plugin_paginator import Paginator, PaginateSelector, PaginateInfo\nfrom gluon.contrib.populate import populate\n\ndef call():\n session.forget()\n return service()\n\ndef custom_button(form):\n # inputname = form.elements(_type=\"texto\")[0]\n # inputname[\"_required\"] = \"required\"\n # inputname[\"_style\"] = \"background:#FA4A81\"\n\n submit_button = form.elements(_type=\"submit\")[0]\n submit_button[\"_class\"] = \"btn btn-primary\"\n return form\n\ndef custom_form(form):\n inputemail = form.elements(_class=\"string\")[0]\n inputemail['_class'] = \"form-control\"\n\n inputpasswd = form.elements(_class=\"password\")[0]\n inputpasswd[\"_class\"] = \"form-control\"\n\n # labelcheckbox = form.elements(_label=\"checkbox\")\n # labelcheckbox[\"_class\"] = \"checkbox\"\n\n return form\n\ndef index():\n from insert_db.insert_db import InsertDB\n\n DB = InsertDB(db)\n # DB.set_data()\n\n return locals()\n\n\ndef user():\n\n forms = auth()\n # inputemail = forms.elements(_class=\"string\")[0]\n # inputemail['_class'] = \"form-control\"\n\n # inputpasswd = forms.elements(_class=\"password\")[0]\n # inputpasswd[\"_class\"] = \"form-control\"\n\n submit_button = forms.elements(_type=\"submit\")[0]\n submit_button[\"_class\"] = \"btn btn-primary btn-block\" \n\n email_label = forms.elements(\"label\")[0]\n email_label[\"_style\"] = \"display:none;\"\n\n email_label2 = forms.elements(\"label\")[1]\n email_label2[\"_style\"] = \"display:none;\"\n\n # email_label3 = forms.elements(\"label\")[2]\n # # email_label3[\"\"] = \"Remember Me\"\n # email_label3[\"_class\"] = \"checkbox\"\n\n\n # for form_style in forms.elements(\"form\"):\n # form_style[\"_class\"] = \"form-signin\"\n\n\n placemail = forms.elements(_type=\"text\")[0]\n placemail[\"_placeholder\"] = \"Email\"\n placepwd = forms.elements(_type=\"password\")[0]\n placepwd[\"_placeholder\"] = \"Password\"\n\n # register_button = forms.add_button(T('Register'), \n # URL(args='register', \n # vars={'_next': request.vars._next} \\\n # if request.vars._next else None),\n # _class='btn btn-primary')\n \n\n return dict(form=forms)\n\n\ndef login():\n\n form = auth.login()\n\n return dict(form=form)\n\n\n@auth.requires_login()\ndef perfil():\n\n result = None\n\n # form = SQLFORM.factory(Field('name', requires=IS_NOT_EMPTY()))\n form = FORM('Pesquisa:',\n INPUT(_type=\"text\", _name=\"result\", requires=IS_NOT_EMPTY(),\n _id=\"result\", _autocomplete=\"off\", \n _onkeyup=\"getData(this.value);\"),\n INPUT(_type=\"submit\"))\n if form.accepts(request):\n tokens = form.vars.result.split()\n query = reduce(lambda a,b:a&b,\n [Institution.name.contains(k) | Project.name.contains(k) \\\n for k in tokens])\n result = db(query).select(orderby=db.institution.name)\n # else:\n # result = DIV(T(\"Pesquise uma Instituição\"),\n # _class=\"alert alert-info\")\n\n submit_button = form.elements(_type=\"submit\")[0]\n submit_button[\"_class\"] = \"btn btn-primary\"\n\n inputext = form.elements(_type=\"text\")[0]\n inputext['_class'] = \"form-control\"\n\n return dict(form=form, result=result)\n\n@auth.requires_login()\ndef ajaxlivesearch():\n tokens = request.vars.tokens if request.vars else None\n query = Institution.name.like('%'+tokens+'%')\n # query = reduce(lambda a,b:a&b,\n # [Institution.name.contains(k) | Project.name.contains(k) \\\n # for k in tokens])\n results = db(query).select(orderby=Institution.name)\n items = []\n for (i,found) in enumerate(results):\n items.append(DIV(A(found.name, _id=\"res%s\"%i, _href=\"#\", \n _onclick=\"copyToBox($('#res%s').html())\"%i), \n _id=\"resultLiveSearch\"))\n\n return TAG[''](*items)\n\n\n@auth.requires_login()\ndef ocean():\n headers={'oceanography.id':'#','oceanography.dates':'Data', \n 'oceanography.times':'Hora','oceanography.depths':'Profundidade', \n 'oceanography.temperature':'Temperatura','oceanography.salt':'Salinidade',\n 'oceanography.chla':'CHLA','oceanography.feofitina':'Feofitina',\n 'oceanography.primary_prod':'Produção Primária',\n 'oceanography.bacterian_prod':'Produção Bacteriana',\n 'oceanography.bacterian_biomass':'Biomassa Bacteriana',\n 'oceanography.org_part_carbon':'Carbono Orgânico Particulado',\n 'oceanography.org_diss_carbon':'Carbono Orgânico Dissolvido',\n 'oceanography.oxigen':'Oxigênio','oceanography.fosfate':'Fosfato',\n 'oceanography.nitrate':'Nitrato','oceanography.amonium':'Amônia',\n 'oceanography.silicate':'Silicato'}\n \n args = request.args(0)\n query = Oceanography\n qry = db(query).select()\n\n datas = SQLFORM.grid(query=query, user_signature=True,\n headers=headers, formstyle='divs', create=False, deletable=False,\n editable=False)\n \n paginate_selector = PaginateSelector(anchor='main')\n paginator = Paginator(paginate=paginate_selector.paginate, \n extra_vars={'v':1}, anchor='main',\n renderstyle=True) \n paginator.records = db(query).count()\n paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records)\n \n rows = db(query).select(limitby=paginator.limitby()) \n\n\n return locals()\n\ndef projects():\n args = request.args(0)\n # query = db(Oceanography).select()\n # datas = SQLFORM.grid(query=query, user_signature=True,\n # headers=headers, formstyle='divs', create=False, deletable=False,\n # editable=False)\n\n # if request.args(0) == ''\n query = Oceanography.station_id\n \n paginate_selector = PaginateSelector(anchor='main')\n paginator = Paginator(paginate=paginate_selector.paginate, \n extra_vars={'v':1}, anchor='main',\n renderstyle=True) \n paginator.records = db(query).count()\n paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records)\n \n rows = db(query).select(limitby=paginator.limitby())\n\n return locals()\n\ndef advancedsearch():\n return locals()\n\n\ndef datainfo():\n inf = request.args(0) or redirect(URL('datas'))\n rows = Oceanography(Oceanography.id == inf)\n\n\n return locals()","sub_path":"w2p_app/peld/controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"371404035","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^nlp$', views.index, name='index'),\n url(r'^pages$', views.get_keyword_pages, name='get_keyword_pages'),\n url(r'^wordpages$', views.get_word_pages, name='get_word_pages'),\n url(r'^timeline$', views.get_keyword_timeline, name='get_keyword_timeline'),\n url(r'^pages/date$', views.get_keyword_date_pages, name='get_keyword_pages'),\n url(r'^history$', views.get_keywordsum_history, name='get_keywordsum_history'),\n url(r'^stopwords$', views.add_stopword, name='add_stopword'),\n url(r'^stopwords$', views.get_stopwords, name='get_stopwords'),\n url(r'^keywords$', views.get_keywords_today, name='get_keywords_today'),\n url(r'^updatefeeds$', views.update_feeds, name='update_feeds'),\n url(r'^pagesreport$', views.pages_report, name='pages_report'),\n url(r'^googlenews$', views.google_news, name='google_news'),\n url(r'^grouptodaynews$', views.group_today_news, name='group_today_news'),\n url(r'^buildtodaynews$', views.build_today_news, name='build_today_news'),\n url(r'^todaygroups$', views.today_groups, name='today_groups'),\n url(r'^todaybow$', views.today_topN_keywords, name='today_top_N_keywords'),\n url(r'^historygroups$', views.history_groups, name='history_groups'),\n url(r'^recpages$', views.recommend_pages, name='recommend_pages'),\n url(r'^pagecount$', views.page_count, name='page_count'),\n]","sub_path":"mindynode_nltk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"267529658","text":"\"\"\"\n.py source code generator for the vehicle interface firmware.\n\n-This is just a simple proof of concept implementation.\n-currently just creates appropriate data structures so CAN translation can be done via python\n-rather than leveraging existing python classes for json parsing and codifying their memory state after the parse,\n we are creating simple arrays of dicts to loosely match the C structs. This gives the most flexibility\n with small Python interpreters.\n\n-supports a single message set, needs fixed\n-does not implement decode or filter, commands and handlers, these are the responsibility of the consumer of the module\n\n\"\"\"\nimport os\nimport operator\nimport logging\n\nfrom openxc.utils import find_file\n\nLOG = logging.getLogger(__name__)\n\n\nclass CodeGeneratorPython(object):\n \"\"\"This class is used to build an implementation of the signals.h functions\n from one or more CAN message sets. The message sets must already be read\n into memory and parsed.\n \"\"\"\n\n MAX_SIGNAL_STATES = 12\n GENERATED_CODE_VERSION = \"1.0\"\n\n def __init__(self, search_paths):\n self.search_paths = search_paths\n self.message_sets = []\n\n def build_source(self):\n lines = []\n lines.extend(self._build_header())\n lines.extend(self._build_extra_sources())\n lines.extend(self._build_message_sets())\n lines.extend(self._build_buses())\n# lines.extend(self._build_signal_states()) #integrated into specific signal build now\n lines.extend(self._build_messages())\n #lines.extend(self._build_signals()) #done internal to build_messages now\n lines.extend(self._build_initializers())\n lines.extend(self._build_loop())\n lines.extend(self._build_commands())\n# lines.extend(self._build_decoder()) #part of footer\n# lines.extend(self._build_filters()) #part of footer\n lines.extend(self._build_footer())\n\n return '\\n'.join(lines)\n\n def _build_extra_sources(self):\n lines = []\n for i, message_set in enumerate(self.sorted_message_sets):\n for extra_source_filename in message_set.extra_sources:\n with open(find_file(extra_source_filename, self.search_paths)\n ) as extra_source_file:\n lines.append(extra_source_file.read())\n return lines\n\n def _build_header(self):\n with open(os.path.join(os.path.dirname(__file__),\n 'signals.py.header')) as header:\n return [header.read().format(self.GENERATED_CODE_VERSION)]\n\n def _build_footer(self):\n with open(os.path.join(os.path.dirname(__file__),\n 'signals.py.footer')) as header:\n return [header.read().format(self.GENERATED_CODE_VERSION)]\n\n\n @property\n def sorted_message_sets(self):\n return sorted(self.message_sets, key=operator.attrgetter('name'))\n\n def _max_command_count(self):\n if len(self.message_sets) == 0:\n return 0\n\n return max(len(list(message_set.active_commands()))\n for message_set in self.message_sets)\n\n def _max_message_count(self):\n if len(self.message_sets) == 0:\n return 0\n return max(len(list(message_set.active_messages()))\n for message_set in self.message_sets)\n\n def _max_signal_count(self):\n if len(self.message_sets) == 0:\n return 0\n\n return max(len(list(message_set.active_signals()))\n for message_set in self.message_sets)\n\n\n def _build_messages(self):\n lines = []\n lines.append(\"MAX_MESSAGE_COUNT = %d\" %\n self._max_message_count())\n lines.append(\"CAN_MESSAGES = {}\")\n\n def block(message_set):\n lines = []\n for message_index, message in enumerate(message_set.all_messages()):\n if not message.enabled:\n LOG.warning(\"Skipping disabled message %s (0x%x)\" %\n (message.name, message.id))\n continue\n LOG.info(\"Added message '%s'\" % message.name)\n lines.append(\"message = {}\")\n lines.append(\"message['bus_index']=%d\" % message_set.lookup_bus_index(message.bus_name))\n lines.append(\"message['id']='%03X'\" % message.id)\n lines.append(\"message['name']='%s'\" % message.name)\n lines.append(\"message['signals']=[]\")\n \n lines.extend(self._build_signals(message))\n \n lines.append(\"CAN_MESSAGES['%03X'] = message\" % message.id)\n lines.append(\"\")\n\n return lines\n\n lines.extend(self._message_set_lister(block))\n\n lines.append(\"\")\n return lines\n\n\n def _build_message_sets(self):\n lines = []\n lines.append(\"MESSAGE_SET_COUNT = %d\" %\n len(self.message_sets))\n lines.append(\"MESSAGE_SETS = []\")\n for i, message_set in enumerate(self.sorted_message_sets):\n message_set.index = i\n lines.append('set = {}')\n lines.append(\"set['index']=%d\" % i)\n lines.append(\"set['name']='%s'\" % message_set.name)\n lines.append(\"set['busCount']=%d\" % len(list(message_set.valid_buses())))\n lines.append(\"set['messageCount']=%d\" % len(list(message_set.active_messages())))\n lines.append(\"set['signalCount']=%d\" % len(list(message_set.active_signals())))\n lines.append(\"set['commandCount']=%d\" % len(list(message_set.active_commands())))\n lines.append(\"MESSAGE_SETS.append(set)\")\n lines.append(\"\")\n LOG.info(\"Added message set '%s'\" % message_set.name)\n return lines\n\n def _build_buses(self):\n lines = []\n lines.append(\"MAX_CAN_BUS_COUNT = 2\")\n lines.append(\"CAN_BUSES = []\")\n\n def block(message_set, **kwargs):\n lines = []\n for bus in message_set.valid_buses():\n lines.append('bus = {}')\n lines.append(\"bus['bus_speed']=%d\" % bus.speed)\n lines.append(\"bus['address']=%d\" % bus.controller)\n lines.append(\"CAN_BUSES.append(bus)\")\n lines.append(\"\")\n return lines\n\n lines.extend(self._message_set_lister(block))\n\n\n return lines\n\n\n def _build_signal_states_for_signal(self, signal):\n lines = []\n lines.append('states = []')\n for state_count, state in enumerate(signal.sorted_states):\n if state_count >= self.MAX_SIGNAL_STATES:\n LOG.warning(\"Ignoring anything beyond %d states for %s\" % (self.MAX_SIGNAL_STATES, signal.generic_name))\n break\n lines.append(\"state = {}\")\n lines.append(\"state['value']=%d\" % state.value)\n lines.append(\"state['name']='%s'\" % state.name)\n lines.append(\"signal['states'].append(state)\")\n lines.append(\"\")\n return lines\n\n\n def _message_set_lister(self, block, indent=4):\n lines = []\n whitespace = \" \" * indent\n for message_set in self.sorted_message_sets:\n lines.append(whitespace + \"#message set: %s\" % message_set.name)\n lines.extend(block(message_set))\n return lines\n\n def _message_set_switcher(self, block, indent=4):\n lines = []\n whitespace = \" \" * indent\n\n for message_set in self.sorted_message_sets:\n lines.extend(block(message_set))\n return lines\n\n\n def _build_signals(self, message):\n lines = []\n #lines.append(\"SIGNALS = []\")\n\n def block(message_set):\n lines = []\n i = 1\n for signal in message.sorted_signals():\n if not signal.enabled:\n LOG.warning(\"Skipping disabled signal '%s' (in 0x%x)\" % (\n signal.generic_name, signal.message.id))\n continue\n signal.array_index = i - 1\n lines.append(\"signal = {}\")\n lines.append(\"signal['message_set_index']=%d\" % signal.message_set.index)\n lines.append(\"signal['message_index']=%d\" % message_set.lookup_message_index(signal.message))\n lines.append(\"signal['generic_name']='%s'\" % signal.generic_name)\n lines.append(\"signal['bit_position']=%d\" % signal.bit_position)\n lines.append(\"signal['bit_size']=%d\" % signal.bit_size)\n lines.append(\"signal['factor']=%f\" % signal.factor)\n lines.append(\"signal['offset']=%f\" % signal.offset)\n lines.append(\"signal['min_value']=%f\" % signal.min_value)\n lines.append(\"signal['max_value']=%f\" % signal.max_value)\n lines.append(\"signal['frequency']=%d\" % signal.send_frequency)\n lines.append(\"signal['send_same']=%s\" % signal.send_same)\n lines.append(\"signal['handler']=%s\" % signal.handler)\n lines.append(\"signal['received']=False\")\n lines.append(\"signal['sendClock']=0\")\n lines.append(\"signal['lastValue']=0\")\n\n if (len(signal.states) > 0):\n lines.append(\"\")\n lines.append(\"signal['states'] = []\")\n lines.extend(self._build_signal_states_for_signal(signal))\n\n lines.append(\"signal['writable']=%s\" % str(signal.writable).title())\n lines.append(\"signal['write_handler']=%s\" % signal.write_handler or \"NULL\") #handlers are implemented outside of this module for now\n lines.append(\"signal['name']='%s'\" % signal.name)\n lines.append(\"message['signals'].append(signal)\")\n lines.append(\"\")\n\n LOG.info(\"Added signal '%s'\" % signal.generic_name)\n i += 1\n return lines\n\n lines.extend(self._message_set_lister(block))\n lines.append(\"\")\n\n return lines\n\n def _build_initializers(self):\n lines = []\n lines.append(\"def openxc_signals_initialize():\")\n\n def block(message_set):\n return [\" %s()\" % initializer\n for initializer in message_set.initializers]\n lines.extend(self._message_set_switcher(block))\n lines.append(\"\")\n return lines\n\n def _build_loop(self):\n lines = []\n lines.append(\"def openxc_signals_loop():\")\n def block(message_set):\n return [\" %s()\" % looper for looper in message_set.loopers]\n lines.extend(self._message_set_switcher(block))\n lines.append(\"\")\n return lines\n\n def _build_commands(self):\n lines = []\n lines.append(\"MAX_COMMAND_COUNT = %d\" %\n self._max_command_count())\n lines.append(\"COMMANDS = []\")\n def block(message_set, **kwargs):\n for command in message_set.all_commands():\n if not command.enabled:\n LOG.warning(\"Skipping disabled Command %s\" % command.name)\n continue\n lines.append(\"command = {}\")\n lines.append(\"command['name']='%s'\" % command.name)\n lines.append(\"command['handler']='%s'\" % command.handler)\n lines.append(\"COMMANDS.append(command)\")\n LOG.info(\"Added command '%s'\" % command.name)\n yield \"\" # %s\" % command\n lines.extend(self._message_set_lister(block))\n lines.append(\"\")\n\n return lines\n\n","sub_path":"openxc/generator/coder_py.py","file_name":"coder_py.py","file_ext":"py","file_size_in_byte":11538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587965030","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@rules_python//python:pip.bzl\", \"pip_install\")\nload(\":python_packages.bzl\", \"PYTHON_PACKAGES\")\n\ndef python_repositories():\n \"\"\"Load and register python toolchains from PYTHON_PACKAGES.\n\n Declare `http_archive`s, register toolchains, and define `pip_install`\n external repositories for each platform in PYTHON_PACKAGES.\n \"\"\"\n for name, platform_data in PYTHON_PACKAGES.items():\n if name not in native.existing_rules():\n py2 = platform_data.python2 if \"python2\" in dir(platform_data) else None\n py3 = platform_data.python3\n\n if py2:\n http_archive(\n name = \"python2_interpreter_%s\" % name,\n build_file_content = py2.build_file_content,\n patch_cmds = py2.patch_cmds,\n sha256 = py2.sha256,\n strip_prefix = py2.strip_prefix,\n urls = py2.urls,\n )\n\n http_archive(\n name = \"python3_interpreter_%s\" % name,\n build_file_content = py3.build_file_content,\n patch_cmds = py3.patch_cmds,\n sha256 = py3.sha256,\n strip_prefix = py3.strip_prefix,\n urls = py3.urls,\n )\n\n native.register_toolchains(\"@//:tfjs_py_toolchain_%s\" % name)\n\n # Create a central external repo, @tensorflowjs_dev_deps, that\n # contains Bazel targets for all the third-party packages specified\n # in the requirements.txt file.\n interpreter = \"@python3_interpreter_%s//:%s\" % (name, py3.python_interpreter)\n pip_install(\n name = \"tensorflowjs_dev_deps_%s\" % name,\n python_interpreter_target = interpreter,\n requirements = \"@//tfjs-converter/python:requirements-dev.txt\",\n )\n\n pip_install(\n name = \"tensorflowjs_deps_%s\" % name,\n python_interpreter_target = interpreter,\n requirements = \"@//tfjs-converter/python:requirements.txt\",\n )\n","sub_path":"python_repositories.bzl","file_name":"python_repositories.bzl","file_ext":"bzl","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239766460","text":"import argparse\nimport os\nimport re\n\nimport torch\nfrom glob import glob\nfrom tqdm import tqdm\n\nfrom dataset.transcribe import transcribe\n\nREGEX = re.compile(\"[^a-zA-Z ]\")\nPATH = os.path.join(\"LJSpeech-1.1\", \"wavs\")\nTOTAL_SAMPLES = 100\n\n\nclass Transcription:\n def __init__(self, filename, prediction, actual, score):\n self.filename = filename\n self.prediction = prediction\n self.actual = actual\n self.score = score\n\n\ndef compare(expected_text, actual_text):\n expected_text = REGEX.sub(\"\", expected_text.strip()).lower()\n actual_text = REGEX.sub(\"\", actual_text.strip()).lower()\n expected_words = expected_text.split(\" \")\n actual_words = actual_text.split(\" \")\n difference = set(expected_words) - set(actual_words)\n return 1 - (len(difference) / len(expected_words))\n\n\ndef save_results(data, path):\n with open(path, \"w\") as f:\n for item in data:\n f.write(f\"{item.filename}|{item.actual}|{item.prediction}|{item.score}\\n\")\n\n\ndef read_labels(path):\n with open(path, encoding=\"utf-8\") as f:\n data = {}\n for line in f.readlines():\n row = line.split(\"|\")\n data[row[0]] = row[1]\n return data\n\n\ndef transcribe_clips(folder, labels, output_path):\n files = os.listdir(folder)[:5]\n labels = read_labels(labels)\n data = []\n for filename in tqdm(files):\n prediction = transcribe(os.path.join(folder, filename))\n actual = labels[filename[:-4]]\n score = compare(prediction, actual)\n data.append(Transcription(filename, prediction, actual, score))\n\n save_results(data, output_path)\n\n\nif __name__ == \"__main__\":\n \"\"\" Script to transcribe a folder of audio \"\"\"\n parser = argparse.ArgumentParser(description=\"Clean & improve text for training\")\n parser.add_argument(\"-f\", \"--folder\", help=\"Audio folder\", type=str, required=True)\n parser.add_argument(\"-l\", \"--labels\", help=\"Labels path\", type=str, required=True)\n parser.add_argument(\"-o\", \"--output\", help=\"Output text file path\", type=str, required=True)\n args = parser.parse_args()\n\n transcribe_clips(args.folder, args.labels, args.output)\n","sub_path":"research/transcribe_clips.py","file_name":"transcribe_clips.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"484168721","text":"#Two functions to check if the given string follows the pattern\nclass Solution(object):\n #Time Complexity: O(n) where n is number of characters and number of words in string\n # and they are of same length\n #Space Complexity: O(n) where n is number of characters and number of words in string\n # and they are of same length\n # Does it runs on leetcode? : Yes\n # Approach: The idea is just to check if the lengths of characters in the pattern and words\n # in the string as well as the length of \n # mapping from each character of pattern to each word of string is same\n def wordPattern1(self, pattern, str):\n \"\"\"\n :type pattern: str\n :type str: str\n :rtype: bool\n \"\"\"\n s = pattern\n t = str.split()\n #print(zip(s,t))\n return len(set(zip(s,t)))==len(set(s))==len(set(t)) and len(s)==len(t)\n\n #Time Complexity: O(n) where n is number of characters and number of words in string\n # and they are of same length\n #Space Complexity: O(n) where n is number of characters and number of words in string\n # and they are of same length\n # Does it runs on leetcode? : Yes\n # Approach: Here the idea is to use each character and each word in both strings to map to their positions using a dictionary.\n # Finally we check if the sorted positions from both mappings (dictionary) lineup or not. \n def wordPattern2(self, pattern: str, str: str) -> bool:\n if len(pattern)!=len(pattern):\n return False\n s = pattern\n t = str.split()\n dict1, dict2 = {}, {}\n for i,v in enumerate(s):\n dict1[v] = dict1.get(v,[]) + [i]\n for i,v in enumerate(t):\n dict2[v] = dict2.get(v,[]) + [i]\n return sorted(dict1.values())==sorted(dict2.values())","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"377593039","text":"def main():\n N = int(input())\n A = list(map(int, input().split()))\n for a in A:\n if a == 0:\n print(0)\n return\n\n mul = 1\n for a in A:\n mul *= a\n if mul > 10 ** 18:\n print(-1)\n return\n\n print(mul)\n\nmain()\n","sub_path":"abc/169/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"476351191","text":"import sys\nsys.stdin = open('D2백만장자프로젝트.txt')\nT = int(input())\nfor tc in range(T):\n day = int(input())\n price = list(map(int, input().split()))\n maxp = 0\n sumprice = 0\n ck = 0\n for i in range(day-1,-1,-1):\n if maxp < price[i]:\n maxp = price[i]\n else:\n ck += maxp -price[i]\n if sumprice <= ck:\n sumprice = ck\n print('#{} {}'.format(tc+1,sumprice))\n\n","sub_path":"08_algorithm/sw.expert/D2백만장자프로젝트.py","file_name":"D2백만장자프로젝트.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"354648145","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 28 18:50:14 2016\r\n\r\n@author: James\r\n\"\"\"\r\n\r\nimport sys\r\nimport os\r\n\r\ndef flip_pancakes(stack, end):\r\n flipped_chain = stack[:end + 1]\r\n for i, cake in enumerate(reversed(flipped_chain)):\r\n stack[i] = cake ^ 1\r\n\r\ndef end_of_chain(stack, size):\r\n for i in range(size - 1):\r\n if stack[i + 1] != stack[i]:\r\n return i\r\n return -1\r\n\r\ndef least_flips(stack):\r\n count, size = 0, len(stack)\r\n end = end_of_chain(stack, size)\r\n while end >= 0 and end < size:\r\n flip_pancakes(stack, end)\r\n count += 1\r\n end = end_of_chain(stack, size)\r\n if stack[0] == 1:\r\n return count\r\n else:\r\n return count + 1\r\n \r\ndef pancake_string_to_list(string):\r\n def char_to_digit(char):\r\n if char == '+':\r\n return 1\r\n else:\r\n return 0\r\n return [char_to_digit(char) for char in string]\r\n\r\ndef make_answer(string):\r\n pancake_list = pancake_string_to_list(string)\r\n return least_flips(pancake_list)\r\n \r\ndef rdln(txtin):\r\n return txtin.readline().strip()\r\n\r\ndef file_io():\r\n file_names = 'problemB'\r\n with open(''.join([file_names, '.in'])) as txtin:\r\n with open(''.join([file_names, '.out']), 'w') as txtout:\r\n case_count = int(rdln(txtin))\r\n for i in range(case_count):\r\n string = rdln(txtin)\r\n answer = make_answer(string)\r\n \r\n str_out = str(answer)\r\n txtout.write(''.join(['Case #', str(i + 1), ': ']))\r\n txtout.write(str_out)\r\n txtout.write('\\n')\r\n osCommandString = ''.join(['notepad.exe ', file_names, '.out'])\r\n os.system(osCommandString)\r\n\r\ndef main():\r\n \"\"\"Main\"\"\"\r\n file_io()\r\n\r\nif __name__ == '__main__':\r\n sys.exit(main())\r\n","sub_path":"solutions_5634697451274240_0/Python/JimmyJenkins/problemB.py","file_name":"problemB.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"490053478","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Prepare Librispeech ASR datasets.\n\nDownload, unpack and create manifest files.\nManifest file is a json-format file with each line containing the\nmeta data (i.e. audio filepath, transcript and audio duration)\nof each audio file in the data set.\n\"\"\"\nimport argparse\nimport codecs\nimport io\nimport json\nimport os\nfrom multiprocessing.pool import Pool\n\nimport soundfile\n\nfrom paddlespeech.dataset.download import download\nfrom paddlespeech.dataset.download import unpack\n\nURL_ROOT = \"http://openslr.elda.org/resources/31\"\nURL_TRAIN_CLEAN = URL_ROOT + \"/train-clean-5.tar.gz\"\nURL_DEV_CLEAN = URL_ROOT + \"/dev-clean-2.tar.gz\"\n\nMD5_TRAIN_CLEAN = \"5df7d4e78065366204ca6845bb08f490\"\nMD5_DEV_CLEAN = \"6d7ab67ac6a1d2c993d050e16d61080d\"\n\nparser = argparse.ArgumentParser(description=__doc__)\nparser.add_argument(\n \"--target_dir\",\n default='~/.cache/paddle/dataset/speech/libri',\n type=str,\n help=\"Directory to save the dataset. (default: %(default)s)\")\nparser.add_argument(\n \"--manifest_prefix\",\n default=\"manifest\",\n type=str,\n help=\"Filepath prefix for output manifests. (default: %(default)s)\")\nargs = parser.parse_args()\n\n\ndef create_manifest(data_dir, manifest_path):\n \"\"\"Create a manifest json file summarizing the data set, with each line\n containing the meta data (i.e. audio filepath, transcription text, audio\n duration) of each audio file within the data set.\n \"\"\"\n print(\"Creating manifest %s ...\" % manifest_path)\n json_lines = []\n total_sec = 0.0\n total_text = 0.0\n total_num = 0\n\n for subfolder, _, filelist in sorted(os.walk(data_dir)):\n text_filelist = [\n filename for filename in filelist if filename.endswith('trans.txt')\n ]\n if len(text_filelist) > 0:\n text_filepath = os.path.join(subfolder, text_filelist[0])\n for line in io.open(text_filepath, encoding=\"utf8\"):\n segments = line.strip().split()\n text = ' '.join(segments[1:]).lower()\n audio_filepath = os.path.join(subfolder, segments[0] + '.flac')\n audio_data, samplerate = soundfile.read(audio_filepath)\n duration = float(len(audio_data)) / samplerate\n\n utt = os.path.splitext(os.path.basename(audio_filepath))[0]\n utt2spk = '-'.join(utt.split('-')[:2])\n json_lines.append(\n json.dumps({\n 'utt': utt,\n 'utt2spk': utt2spk,\n 'feat': audio_filepath,\n 'feat_shape': (duration, ), #second\n 'text': text,\n }))\n\n total_sec += duration\n total_text += len(text)\n total_num += 1\n\n with codecs.open(manifest_path, 'w', 'utf-8') as out_file:\n for line in json_lines:\n out_file.write(line + '\\n')\n\n subset = os.path.splitext(manifest_path)[1][1:]\n manifest_dir = os.path.dirname(manifest_path)\n data_dir_name = os.path.split(data_dir)[-1]\n meta_path = os.path.join(manifest_dir, data_dir_name) + '.meta'\n with open(meta_path, 'w') as f:\n print(f\"{subset}:\", file=f)\n print(f\"{total_num} utts\", file=f)\n print(f\"{total_sec / (60*60)} h\", file=f)\n print(f\"{total_text} text\", file=f)\n print(f\"{total_text / total_sec} text/sec\", file=f)\n print(f\"{total_sec / total_num} sec/utt\", file=f)\n\n\ndef prepare_dataset(url, md5sum, target_dir, manifest_path):\n \"\"\"Download, unpack and create summmary manifest file.\n \"\"\"\n if not os.path.exists(os.path.join(target_dir, \"LibriSpeech\")):\n # download\n filepath = download(url, md5sum, target_dir)\n # unpack\n unpack(filepath, target_dir)\n else:\n print(\"Skip downloading and unpacking. Data already exists in %s.\" %\n target_dir)\n # create manifest json file\n create_manifest(target_dir, manifest_path)\n\n\ndef main():\n if args.target_dir.startswith('~'):\n args.target_dir = os.path.expanduser(args.target_dir)\n\n tasks = [\n (URL_TRAIN_CLEAN, MD5_TRAIN_CLEAN,\n os.path.join(args.target_dir, \"train-clean\"),\n args.manifest_prefix + \".train-clean\"),\n (URL_DEV_CLEAN, MD5_DEV_CLEAN, os.path.join(\n args.target_dir, \"dev-clean\"), args.manifest_prefix + \".dev-clean\"),\n ]\n\n with Pool(2) as pool:\n pool.starmap(prepare_dataset, tasks)\n\n print(\"Data download and manifest prepare done!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"dataset/mini_librispeech/mini_librispeech.py","file_name":"mini_librispeech.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624571716","text":"import pandas as pd\nfrom collections import OrderedDict\nfrom well_mapper import get_well_name\n\n\ndef to_tsv(Designs):\n\n plates = Designs.coords['plates'].values.tolist()\n\n for plate in plates:\n file_name = \"%s_design.tsv\" % plate\n design = Designs.sel(plates=plate)\n df = make_tsv(design, file_name)\n return df\n\n\ndef make_tsv(design, file_name):\n\n dimension_fields = design.dims.keys()\n\n coordinate_fields = [cf for cf in design.coords.keys()\n if cf != 'plates']\n\n metadata_fields = [mf for mf in coordinate_fields\n if mf not in dimension_fields]\n\n data_variables = design.data_vars.keys()\n\n well_info = OrderedDict()\n\n plate_dims = [16, 24]\n plate_size = 384\n well_info['well'] = [get_well_name(w, plate_dims)\n for w in range(plate_size)]\n\n for field in metadata_fields:\n field_array = design[field].values.reshape(1, 384)[0]\n well_info[field] = field_array.tolist()\n\n for field in data_variables:\n field_array = design[field].values.reshape(1, 384)[0]\n well_info[field] = field_array.tolist()\n\n df = pd.DataFrame(well_info)\n df.to_csv(file_name, sep='\\t')\n return df\n","sub_path":"datarail/experimental_design/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"98930563","text":"import subprocess, os, os.path as osp\ndef du(directory):\n \"\"\"disk usage in kilobytes\"\"\"\n return int(subprocess.check_output(['du','-sk', directory]).split()[0].decode('utf-8'))\n\ndef get_projects_to_consider(current_project_key, config):\n mode = config.get('projectsMode', \"CURRENT\")\n\n if mode == \"ALL_BUT_IGNORED\":\n dip_home = os.environ[\"DIP_HOME\"]\n config_projects = osp.join(dip_home, \"config\", \"projects\")\n all_projects = set(os.listdir(config_projects))\n ignored = set([x.strip() for x in config.get(\"ignoredProjects\", \"\").split(\",\")])\n projects = list(all_projects - ignored)\n elif mode == \"INCLUDED\":\n projects = list(set([x.strip() for x in config.get(\"includedProjects\", \"\").split(\",\")]))\n elif mode == \"CURRENT\":\n projects = [current_project_key]\n else:\n raise Exception(\"Unexpected projects mode: %s\" % mode)\n\n return projects","sub_path":"disk-cleanup-macros/python-lib/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160263330","text":"#!\"usr/local/bin/python3.2\"\n\n#this program calculates a salesperson's pay at \n#Make Your Own Music\n\n#define the main function\ndef main():\n #get the salesperson's monthly sales\n #note that the function resides on the right of the operator\n sales = get_sales()\n \n #get the amount of advanced pay\n advanced_pay = get_advanced_pay()\n \n #determine the commission rate\n #it is dependant upon the sales, so the determine_commission_rate\n #takes the sales argument\n commission_rate = determine_commission_rate(sales)\n \n #get the final pay\n pay = sales * commission_rate - advanced_pay\n \n #display the final pay\n print(\"The pay is $\", format(pay, ',.2f'))\n \n #is the pay negative?\n if pay < 0:\n print(\"This employee must reimburse the company $\")\n \n#the get sales function asks the user to input the employees' monthly_sales total\n#and returns the value\ndef get_sales():\n #get the amount of monthly sales\n monthly_sales = float(input(\"Enter the employees' sales: $ \"))\n \n #return the amount entered\n return monthly_sales\n\n#the get_advanced_pay function asks the user to enter the employees'\n#advanced pay and reurns the value\ndef get_advanced_pay():\n print(\"Enter the amount of advanced pay OR\")\n print(\"if no advanced pay was given, enter 0\")\n advanced = float(input(\"Enter advanced pay: $ \"))\n \n #return the value of advanced pay\n return advanced\n\n#the commission_rate function calculates the commission rate\n#and returns its value\ndef determine_commission_rate(sales):\n if sales < 10000:\n rate = 0.10\n elif sales >= 10000 and sales <= 14999.99:\n rate = 0.12\n elif sales >= 15000 and sales <= 17999.99:\n rate = 0.14\n elif sales >=18000 and sales <= 21999.99:\n rate = 0.16\n else:\n rate = 0.18\n \n #return the values of commission rate\n return rate\n \nmain()\n\n ","sub_path":"commission_rate.py","file_name":"commission_rate.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"398428482","text":"# In[1]\n# %matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport time\nfrom multiprocessing import Pool\n\nnp.set_printoptions(threshold=np.inf)\n\nclass trace(object):\n def __init__(self,x_0,y_0,v_0,beta,time_step=0.01,time_total=100):\n self.v_x0 = 0\n self.v_y0 = v_0\n self.x_0 = x_0\n self.y_0 = y_0\n self.time_total=time_total\n self.time_step=time_step\n self.t = np.arange(0, self.time_total + time_step, time_step)\n self.x = np.arange(0, self.time_total + time_step, time_step)\n self.y = np.arange(0, self.time_total + time_step, time_step) \n self.v_x = np.arange(0, self.time_total + time_step, time_step)\n self.v_y = np.arange(0, self.time_total + time_step, time_step)\n self.v = np.arange(0, self.time_total + time_step, time_step)\n self.r = np.arange(0, self.time_total + time_step, time_step)\n self.t[0] = 0\n self.x[0] = self.x_0\n self.y[0] = self.y_0\n self.v_x[0] = self.v_x0\n self.v_y[0] = self.v_y0\n self.beta = beta\n self.r[0] = 1\n\n def calculate(self):\n for i in range(self.t.shape[0] - 1):\n\n self.v_x[i+1] = -4*math.pi**2*self.x[i]/(self.r[i]**(self.beta+1))*self.time_step + self.v_x[i]\n self.v_y[i+1] = -4*math.pi**2*self.y[i]/(self.r[i]**(self.beta+1))*self.time_step + self.v_y[i]\n self.x[i+1] = self.x[i] + self.v_x[i+1]*self.time_step\n self.y[i+1] = self.y[i] + self.v_y[i+1]*self.time_step \n self.r[i+1] = math.sqrt(self.x[i+1]**2+self.y[i+1]**2)\n def plot(self):\n fig=plt.figure(figsize=[8,8]) \n plt.plot(self.x,self.y)\n plt.scatter([0],[0],s=1000,color='yellow')\n plt.xlabel('x(AU)')\n plt.ylabel('y(AU)')\n plt.title(\"beta=\"+str(self.beta)+\",e=\"+str(self.x[0]-1))\n plt.show()\n\nstart = time.time()\na = trace(x_0=1.5,y_0=0,v_0=2*math.pi,beta=2.05)\na.calculate()\na.plot()\nend = time.time()\nend-start\n","sub_path":"Computation Physics/hw7/4.9.py","file_name":"4.9.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"549561430","text":"from datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.models import Variable\nfrom airflow.contrib.operators.emr_add_steps_operator \\\n import EmrAddStepsOperator\nfrom airflow.hooks.base_hook import BaseHook\nfrom airflow.contrib.sensors.emr_step_sensor import EmrStepSensor\n\n\nclass SqoopEmrWorkflow:\n \"\"\"\n Class specifying the EMR workflow using the steps API for the Sqoop import. Currently, we support only the full snapshot mode.\n \"\"\"\n def __init__(self, params):\n self.cluster_key = Variable.get('cluster_key', 'dummy_cluster')\n self.source_app = params.get('source_app', 'milkyway')\n self.connection_name = params.get('connection_name', 'prod_mysql_milkyway')\n self.script = params.get('script', 'mysql_import.sh')\n self.destination = params.get('destination', None)\n self.default_args = {\n 'owner': 'shubham',\n 'depends_on_past': False,\n 'start_date': datetime.now(),\n 'email': ['shubham.gupta@scripbox.com'],\n 'email_on_failure': False,\n 'email_on_retry': False\n }\n\n\n def _create_dag(self, params):\n connection = BaseHook.get_connection(self.connection_name)\n\n arguments = [\n f\"{Variable.get('sqoop_dir')}/{self.script}\",\n connection.host,\n f\"{connection.port}\",\n connection.schema,\n connection.login,\n self.destination,\n f\"{Variable.get('milkyway_sqoop_dest_dir')}/{self.destination}\"\n ]\n\n steps = [\n {\n \"Name\": f\"Sqoop {self.source_app} {self.destination} import\",\n \"HadoopJarStep\": {\n \"Args\": arguments,\n \"Jar\": \"s3://ap-south-1.elasticmapreduce/libs/script-runner/script-runner.jar\"\n },\n \"ActionOnFailure\": \"CONTINUE\"\n }\n ]\n\n dag_name = f\"{self.source_app}_sqoop_{self.destination}_import\"\n\n dag = DAG(\n dag_name,\n default_args=self.default_args,\n dagrun_timeout=timedelta(hours=2),\n schedule_interval=params['schedule_interval']\n )\n\n adder = EmrAddStepsOperator(\n task_id='add_steps',\n job_flow_id=self.cluster_key,\n aws_conn_id='aws_default',\n steps=steps,\n dag=dag\n )\n\n checker = EmrStepSensor(\n task_id='watch_step',\n job_flow_id=self.cluster_key,\n step_id=\"{{ task_instance.xcom_pull('add_steps', key='return_value')[0] }}\",\n aws_conn_id='aws_default',\n dag=dag\n )\n adder.set_downstream(checker)\n return dag\n\n @classmethod\n def create(cls, params):\n obj = cls(params)\n dag = obj._create_dag(params)\n return dag\n","sub_path":"dags/common/operators/sqoop_emr_workflow.py","file_name":"sqoop_emr_workflow.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"480918525","text":"# both python2 and python3\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport argparse, codecs, os, re, shutil, sys\n\ndef ansi_len(s):\n no_ansi_s = rx.ansi_len.sub('', s)\n return len(no_ansi_s)\n\nclass ParsedLine:\n INDENT_CHAR=' '\n def __init__(self, t, line, pos=None, line_nr=None):\n self.t = t\n self.line = line\n self.pos = pos\n self.line_nr = line_nr\n self.indent = 0\n\n def set_indent(self, max_pos, max_width):\n if self.pos and max_pos:\n self.indent = max_pos - self.pos\n # if indent makes line wrap, indent less\n line_len = ansi_len(self.line)\n line_wraps = line_len > max_width\n indent_wraps = line_len+self.indent > max_width\n if not line_wraps and indent_wraps:\n self.indent = max_width - line_len\n else:\n self.indent = 0\n\nclass rx:\n heading = re.compile('^[ \\t]*(#)')\n whitespace = re.compile('^[ \\t]*$')\n comment = re.compile('(^[ \\t]+)?(?0 and len(lines[0])>0 and ord(lines[0][0]) == 0xFEFF: # BOM_UTF16_BE\n lines[0] = lines[0][1:]\n result = []\n line_nr = 0\n for line in lines:\n line = line.strip('\\n')\n heading_match=rx.heading.search(line)\n if heading_match:\n result.append(ParsedLine('heading', line, pos=heading_match.start(1)))\n elif rx.whitespace.search(line):\n result.append(ParsedLine('whitespace', line))\n else:\n line_nr += 1\n match = rx.comment.search(line)\n pos = match.start() if match else None\n result.append(ParsedLine('code', line, line_nr=line_nr, pos=pos))\n return result\n\ndef set_indent(l, start, stop, max_pos, max_width):\n for i in range(start, stop):\n item = l[i]\n if item.t == 'code':\n item.set_indent(max_pos, max_width)\n\ndef format_lines(l, elastic_tab, nr_positions_line_nr, max_width):\n if elastic_tab == 0: return\n if elastic_tab == 1: group_reset = ['heading','whitespace']\n if elastic_tab == 2: group_reset = ['heading']\n if elastic_tab == 3: group_reset = []\n start_group = None\n for i in range(0, len(l)):\n x = l[i]\n if start_group is None and x.t not in group_reset:\n start_group = i\n max_pos = ansi_len(x.line)+1 if x.pos is None else x.pos\n if start_group is not None: # We are in a group\n if x.t == 'code':\n max_pos = max(max_pos, 0 if x.pos is None else x.pos)\n has_no_next_item = i+1>=len(l)\n if has_no_next_item or l[i+1].t in group_reset:\n max_command_width = max_width - nr_positions_line_nr - len('. ')\n # indent only at certain positions\n set_indent(l, start_group, i+1, max_pos, max_command_width)\n start_group = None #reset start code-block\n\ndef print_line(l, clr, nr_positions_line_nr, format_line):\n if l.t == 'heading':\n cprint(clr.heading, l.line)\n cprint(clr.nc, '\\n')\n elif l.t == 'whitespace':\n cprint(clr.nc, l.line+'\\n')\n elif l.t == 'code':\n if format_line:\n cprint(clr.number, '{:{}}. '.format(l.line_nr, nr_positions_line_nr))\n if l.pos is None:\n cprint(clr.command, l.line)\n else:\n cprint(clr.command, l.line[:l.pos])\n cprint(None, ParsedLine.INDENT_CHAR*l.indent)\n cprint(clr.comment, l.line[l.pos:])\n cprint(clr.nc, '\\n')\n else:\n print(l.line, file=sys.stderr)\n\ndef main():\n # customizations\n clr = ok_color()\n\n # handle arguments\n parser = argparse.ArgumentParser(description='Show the ok-file colorized (or just one line).')\n parser.add_argument('--verbose', '-v', metavar='V', type=int, default=1, help='0=quiet, 1=normal, 2=verbose. Defaults to 1. ')\n parser.add_argument('--comment_align', '-c', metavar='CA', type=int, default=2, choices= [0,1,2,3], help='Level ($e) of comment alignment. 0=no alignment, 1=align consecutive lines (Default), 2=including whitespace, 3 align all.')\n parser.add_argument('--terminal_width', '-t', metavar='TW', type=int, default=None, help='number of columns of the terminal (tput cols)')\n parser.add_argument('only_line_nr', metavar='N', type=int, nargs='?', help='the line number to show')\n args = parser.parse_args()\n\n if args.terminal_width is None:\n if sys.version_info[0] >= 3:\n args.terminal_width = shutil.get_terminal_size().columns\n else:\n # Python 2 doesn't have `get_terminal_size`\n args.terminal_width = 80\n\n if args.verbose > 1:\n print(' comment_align: %d' % args.comment_align)\n print('terminal_width: %d' % args.terminal_width)\n print('python version: '+ sys.version.replace('\\n', '\\t'))\n\n # prepare (read stdin parse, transform, and calculate stuff)\n # Unicode: best to ignore other encodings? SO doesn't seem to give good advice\n # See https://stackoverflow.com/q/2737966/56\n try:\n lines = sys.stdin.readlines()\n except UnicodeDecodeError as err:\n print('ERROR: UTF-8 (unicode) should be used as sole encoding for .ok-files', file=sys.stderr)\n if args.verbose > 1:\n print('UnicodeDecodeError exception properties (error on: %s):' % err.object[err.start:err.end], file=sys.stderr)\n print('* encoding: %s' % err.encoding, file=sys.stderr)\n print('* reason__: %s' % err.reason, file=sys.stderr)\n print('* object__: %s' % err.object, file=sys.stderr)\n print('* start___: %s' % err.start, file=sys.stderr)\n print('* end_____: %s' % err.end, file=sys.stderr)\n exit(1)\n p_lines = parse_lines(lines)\n cmd_lines = [pl.line_nr for pl in p_lines if pl.line_nr]\n nr_positions_line_nr = len(str(max(cmd_lines))) if len(cmd_lines)>0 else 0\n format_lines(p_lines, args.comment_align, nr_positions_line_nr, args.terminal_width)\n\n # execute\n if args.only_line_nr is None:\n for p_line in p_lines:\n print_line(p_line, clr, nr_positions_line_nr, True)\n if len(cmd_lines) == 0:\n sys.exit(1)\n else:\n # swap stdout and stderr (the calling shell-script needs a unformated string, and we need to print something to the display as well)\n (sys.stdout, sys.stderr) = (sys.stderr, sys.stdout)\n try:\n p_line = next(x for x in p_lines if x.t=='code' and x.line_nr==args.only_line_nr)\n except StopIteration:\n if args.verbose >= 2: print(\"ERROR: entered line number '{}' does not exist\".format(args.only_line_nr))\n sys.exit(2)\n # The formated line is printed to stdout, and the actual line from .ok is printed to stderr\n if args.verbose > 0: print_line(p_line, clr, nr_positions_line_nr, True)\n print_line(p_line, clr, nr_positions_line_nr, False)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n'''\nParsing of comments is not yet perfect. It's also quite complicated. \nSee also:\n http://www.apeth.com/nonblog/stories/textmatebundle.html\n https://github.com/stedolan/jq/wiki/Docs-for-Oniguruma-Regular-Expressions-(RE.txt)\n\nSome notes:\nIn what parts of a bash-line can a #-sign occur:\n - comment\n - interpolation:\n * $()\n * ``\n * $(()) #but how does this work?\n - variables:\n * $# \n * ${#xxx}\n - string\n * \\#\n * double quoted string: variabele/interpolation\n'''","sub_path":"ok-show.py","file_name":"ok-show.py","file_ext":"py","file_size_in_byte":8764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"183480971","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[49]:\n\n\nget_ipython().system(u'curl https://topcs.blob.core.windows.net/public/FlightData.csv -o flightdata.csv')\n\n\n# In[50]:\n\n\nimport pandas as pd\n\ndf = pd.read_csv('flightdata.csv')\ndf.head()\n\n\n# In[51]:\n\n\ndf.shape\n\n\n# In[52]:\n\n\ndf.isnull().values.any()\n\n\n# In[53]:\n\n\ndf.isnull().sum()\n\n\n# In[54]:\n\n\ndf = df.drop('Unnamed: 25', axis = 1)\ndf.isnull().sum()\n\n\n# In[55]:\n\n\nfeatures = [\"MONTH\", \"DAY_OF_MONTH\", \"DAY_OF_WEEK\", \"ORIGIN\", \"DEST\", \"CRS_DEP_TIME\", \"ARR_DEL15\"]\ndf = df[features]\ndf.isnull().sum()\n\n\n# In[56]:\n\n\ndf.columns\n\n\n# In[57]:\n\n\ndf[df.isnull().values.any(axis=1)].head()\n\n\n# In[58]:\n\n\ndf = df.fillna({'ARR_DEL15': 1})\ndf.iloc[177:185]\n\n\n# In[ ]:\n\n\n\n\n\n# In[59]:\n\n\ndf.isnull().sum()\n\n\n# In[60]:\n\n\nimport math\n\nfor index, row in df.iterrows():\n df.loc[index, 'CRS_DEP_TIME'] = math.floor(row['CRS_DEP_TIME'] / 100)\ndf.head()\n\n\n# In[61]:\n\n\ndf = pd.get_dummies(df, columns=['ORIGIN', 'DEST'])\ndf.head()\n\n\n# In[64]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain_x, test_x, train_y, test_y = train_test_split(df.drop('ARR_DEL15', axis=1), df['ARR_DEL15'], test_size=0.2, random_state=42)\ntrain_x.shape\n\n\n# In[65]:\n\n\ntest_x.shape\n\n\n# In[66]:\n\n\ntrain_y.shape\n\n\n# In[67]:\n\n\ntest_y.shape\n\n\n# In[68]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier(random_state=13)\nmodel.fit(train_x, train_y)\n\n\n# In[69]:\n\n\npredicted = model.predict(test_x)\nmodel.score(test_x, test_y)\n\n\n# In[70]:\n\n\nfrom sklearn.metrics import roc_auc_score\nprobabilities = model.predict_proba(test_x)\n\n\n# In[71]:\n\n\nroc_auc_score(test_y, probabilities[:, 1])\n\n\n# In[72]:\n\n\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(test_y, predicted)\n\n\n# In[73]:\n\n\nfrom sklearn.metrics import precision_score\n\ntrain_predictions = model.predict(train_x)\nprecision_score(train_y, train_predictions)\n\n\n# In[74]:\n\n\nfrom sklearn.metrics import recall_score\n\nrecall_score(train_y, train_predictions)\n\n\n# In[75]:\n\n\nget_ipython().magic(u'matplotlib inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set()\n\n\n# In[76]:\n\n\nfrom sklearn.metrics import roc_curve\n\nfpr, tpr, _ = roc_curve(test_y, probabilities[:, 1])\nplt.plot(fpr, tpr)\nplt.plot([0, 1], [0, 1], color='grey', lw=1, linestyle='--')\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\n\n\n# In[78]:\n\n\ndef predict_delay(departure_date_time, origin, destination):\n from datetime import datetime\n\n try:\n departure_date_time_parsed = datetime.strptime(departure_date_time, '%d/%m/%Y %H:%M:%S')\n except ValueError as e:\n return 'Error parsing date/time - {}'.format(e)\n\n month = departure_date_time_parsed.month\n day = departure_date_time_parsed.day\n day_of_week = departure_date_time_parsed.isoweekday()\n hour = departure_date_time_parsed.hour\n\n origin = origin.upper()\n destination = destination.upper()\n\n input = [{'MONTH': month,\n 'DAY': day,\n 'DAY_OF_WEEK': day_of_week,\n 'CRS_DEP_TIME': hour,\n 'ORIGIN_ATL': 1 if origin == 'ATL' else 0,\n 'ORIGIN_DTW': 1 if origin == 'DTW' else 0,\n 'ORIGIN_JFK': 1 if origin == 'JFK' else 0,\n 'ORIGIN_MSP': 1 if origin == 'MSP' else 0,\n 'ORIGIN_SEA': 1 if origin == 'SEA' else 0,\n 'DEST_ATL': 1 if destination == 'ATL' else 0,\n 'DEST_DTW': 1 if destination == 'DTW' else 0,\n 'DEST_JFK': 1 if destination == 'JFK' else 0,\n 'DEST_MSP': 1 if destination == 'MSP' else 0,\n 'DEST_SEA': 1 if destination == 'SEA' else 0 }]\n\n return model.predict_proba(pd.DataFrame(input))[0][0]\n\n\n# In[79]:\n\n\npredict_delay('1/10/2018 21:45:00', 'JFK', 'ATL')\n\n\n# In[80]:\n\n\npredict_delay('2/10/2018 21:45:00', 'JFK', 'ATL')\n\n\n# In[81]:\n\n\npredict_delay('2/10/2018 10:00:00', 'ATL', 'SEA')\n\n\n# In[82]:\n\n\nimport numpy as np\n\nlabels = ('Oct 1', 'Oct 2', 'Oct 3', 'Oct 4', 'Oct 5', 'Oct 6', 'Oct 7')\nvalues = (predict_delay('1/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('2/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('3/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('4/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('5/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('6/10/2018 21:45:00', 'JFK', 'ATL'),\n predict_delay('7/10/2018 21:45:00', 'JFK', 'ATL'))\nalabels = np.arange(len(labels))\n\nplt.bar(alabels, values, align='center', alpha=0.5)\nplt.xticks(alabels, labels)\nplt.ylabel('Probability of On-Time Arrival')\nplt.ylim((0.0, 1.0))\n\n\n# In[84]:\n\n\nimport numpy as np\n\nlabels = ('9:00am', 'Noon', '3:00pm', '6:00pm', '9:00pm')\nvalues = (predict_delay('30/01/2018 09:00:00', 'SEA', 'ATL'),\n predict_delay('30/01/2018 12:00:00', 'SEA', 'ATL'),\n predict_delay('30/01/2018 15:00:00', 'SEA', 'ATL'),\n predict_delay('30/01/2018 18:00:00', 'SEA', 'ATL'),\n predict_delay('30/01/2018 21:00:00', 'SEA', 'ATL'))\n \nalabels = np.arange(len(labels))\n\nplt.bar(alabels, values, align='center', alpha=0.5)\nplt.xticks(alabels, labels)\nplt.ylabel('Probability of On-Time Arrival')\nplt.ylim((0.0, 1.0))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"flightdelay/On-Time Flight Arrivals.py","file_name":"On-Time Flight Arrivals.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530701236","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom django.utils import timezone\nfrom django.db.models import Avg, Min, Max, Sum\nimport datetime\nfrom izvestaj.models import *\nfrom izvestaj.forms import *\n\n# Create your views here.\n\ndef home(request):\n\treturn render(request, 'home.html')\n\ndef korisnici(request):\n\tkor_total = Korisnici.objects.count()\n\tsvi_korisnici = Korisnici.objects.all()\n\tdanas = datetime.date.today()\n\tprij_danas = Korisnici.objects.filter(last_login=timezone.now().date()).count()\n\treturn render(request, 'korisnici.html', {'kor_total': kor_total, 'prij_danas': prij_danas, 'svi_korisnici': svi_korisnici})\n\ndef materijali(request):\n\tmat = Materijali.objects.all()\n\tmat_ukupno_metara = Materijali.objects.all().aggregate(Sum('preostala_duzina'))\n\tmat_prosecna_cena = Materijali.objects.all().aggregate(Avg('cena_po_metru'))\n\tnajjeftin = Materijali.objects.all().aggregate(Min('cena_po_metru'))['cena_po_metru__min']\n\tnajskup = Materijali.objects.all().aggregate(Max('cena_po_metru'))['cena_po_metru__max']\n\tnajjeftiniji_mat = Materijali.objects.filter(cena_po_metru=najjeftin).first()\n\tnajskuplji_mat = Materijali.objects.filter(cena_po_metru=najskup).first()\n\treturn render(request, 'materijali.html', {'materijali': mat,\n\t\t\t\t'mat_ukupno_metara': mat_ukupno_metara,\n\t\t\t\t'mat_prosecna_cena': mat_prosecna_cena,\n\t\t\t\t'najjeftiniji_mat': najjeftiniji_mat,\n\t\t\t\t'najskuplji_mat': najskuplji_mat})\n\ndef dugmici(request):\n\tdug = Dugmici.objects.all()\n\tdug_prosecna_cena = Dugmici.objects.all().aggregate(Avg('cena_deset_dugmica'))\n\tnajjeftin = Dugmici.objects.all().aggregate(Min('cena_deset_dugmica'))['cena_deset_dugmica__min']\n\tnajskup = Dugmici.objects.all().aggregate(Max('cena_deset_dugmica'))['cena_deset_dugmica__max']\n\tnajjeftinije_dug = Dugmici.objects.filter(cena_deset_dugmica=najjeftin).first()\n\tnajskuplje_dug = Dugmici.objects.filter(cena_deset_dugmica=najskup).first()\n\treturn render(request, 'dugmici.html', {'dugmici': dug,\n\t\t\t\t'dug_prosecna_cena': dug_prosecna_cena,\n\t\t\t\t'najjeftinije_dug': najjeftinije_dug,\n\t\t\t\t'najskuplje_dug': najskuplje_dug})\n\ndef meblovi(request):\n\tmebl = MaterijaliNamestaj.objects.all()\n\tmebl_prosecna_cena = MaterijaliNamestaj.objects.all().aggregate(Avg('cena_deset_metara'))\n\tnajjeftin = MaterijaliNamestaj.objects.all().aggregate(Min('cena_deset_metara'))['cena_deset_metara__min']\n\tnajskup = MaterijaliNamestaj.objects.all().aggregate(Max('cena_deset_metara'))['cena_deset_metara__max']\n\tnajjeftiniji_mebl = MaterijaliNamestaj.objects.filter(cena_deset_metara=najjeftin).first()\n\tnajskuplji_mebl = MaterijaliNamestaj.objects.filter(cena_deset_metara=najskup).first()\n\treturn render(request, 'meblovi.html', {'meblovi': mebl,\n\t\t\t\t'mebl_prosecna_cena': mebl_prosecna_cena,\n\t\t\t\t'najjeftiniji_mebl': najjeftiniji_mebl,\n\t\t\t\t'najskuplji_mebl': najskuplji_mebl})\n\t\ndef korisnici_komentari(request):\n\tkomentari = Komentari.objects.all()\n\tkomentari_danas = Komentari.objects.filter(postavljeno_datuma=timezone.now().date())\n\treturn render(request, 'komentari.html', {'komentari': komentari, 'komentari_danas': komentari_danas})\n\ndef korisnici_narudzbine(request):\n\tnarudzbine = Narudzbina.objects.all()\n\tnarudzbine_danas = Narudzbina.objects.filter(datum_narucivanja=timezone.now().date())\n\tisporuceno_danas = Narudzbina.objects.filter(datum_narucivanja=timezone.now().date()).filter(isporuceno=True).count()\n\tisporuceno_ukupno = Narudzbina.objects.filter(isporuceno=True).count()\n\treturn render(request, 'narudzbine.html', {'narudzbine': narudzbine, 'narudzbine_danas': narudzbine_danas, 'isporuceno_danas': isporuceno_danas, 'isporuceno_ukupno': isporuceno_ukupno})\n\t\ndef izbrisi_korisnika(request, id):\n\tkorisnik = Korisnici.objects.get(id=id)\n\tkorisnik.delete()\n\treturn redirect('korisnici')\n\ndef izbrisi_narudzbinu(request, id):\n\tnar = Narudzbina.objects.get(narudzbinaid=id)\n\tnar.delete()\n\treturn redirect('korisnici_narudzbine')\n\ndef potvrdi_narudzbinu(request, id):\n\tnar = Narudzbina.objects.get(narudzbinaid=id)\n\tnar.isporuceno = True\n\tnar.save()\n\treturn redirect('korisnici_narudzbine')\n\ndef novi_materijal(request):\n\tif request.method == 'POST':\n\t\tform = MaterijaliForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tlast_obj = Materijali.objects.last()\n\t\t\tmat = Materijali(materijalid=last_obj.materijalid+1, naziv=form.cleaned_data['naziv'], boja=form.cleaned_data['boja'], preostala_duzina=form.cleaned_data['preostala_duzina'], cena_po_metru=form.cleaned_data['cena_po_metru'])\n\t\t\tmat.save()\n\t\t\treturn redirect('materijali')\n\t\telse:\n\t\t\tform = MaterijaliForm()\n\t\t\treturn render(request, 'materijal_forma.html', {'form': form, 'error': 'Problem u dodavanju. Pokusajte ponovo.'})\n\telse:\n\t\tform = MaterijaliForm()\n\t\treturn render(request, 'materijal_forma.html', {'form': form})\n\ndef izmeni_materijal(request, id):\n\tmat = get_object_or_404(Materijali, pk=id)\n\tif request.method == 'POST':\n\t\tform = MaterijaliForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tmat.naziv = form.cleaned_data['naziv']\n\t\t\tmat.boja = form.cleaned_data['boja']\n\t\t\tmat.preostala_duzina = form.cleaned_data['preostala_duzina']\n\t\t\tmat.cena_po_metru = form.cleaned_data['cena_po_metru']\n\t\t\tmat.save()\n\t\t\treturn redirect('materijali')\n\t\telse:\n\t\t\tform = MaterijaliForm(instance=mat)\n\t\t\treturn render(request, 'materijal_forma_izmeni.html', {'form': form, 'id': id, 'error': 'Problem u izmeni. Pokusajte ponovo.'})\n\telse:\n\t\tform = MaterijaliForm(instance=mat)\n\t\treturn render(request, 'materijal_forma_izmeni.html', {'form': form, 'id': id})\n\ndef izbrisi_materijal(request, id):\n\tmat = Materijali.objects.get(materijalid=id)\n\tmat.delete()\n\treturn redirect('materijali')\n\ndef novo_dugme(request):\n\tif request.method == 'POST':\n\t\tform = DugmiciForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tlast_obj = Dugmici.objects.last()\n\t\t\tdug = Dugmici(dugmiciid=last_obj.dugmiciid+1, boja=form.cleaned_data['boja'], kolicina=form.cleaned_data['kolicina'], cena_deset_dugmica=form.cleaned_data['cena_deset_dugmica'])\n\t\t\tdug.save()\n\t\t\treturn redirect('dugmici')\n\t\telse:\n\t\t\tform = DugmiciForm()\n\t\t\treturn render(request, 'dugme_forma.html', {'form': form, 'error': 'Problem u dodavanju. Pokusajte ponovo.'})\n\telse:\n\t\tform = DugmiciForm()\n\t\treturn render(request, 'dugme_forma.html', {'form': form})\n\ndef izmeni_dugme(request, id):\n\tdug = get_object_or_404(Dugmici, pk=id)\n\tif request.method == 'POST':\n\t\tform = DugmiciForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tdug.boja = form.cleaned_data['boja']\n\t\t\tdug.kolicina = form.cleaned_data['kolicina']\n\t\t\tdug.cena_deset_dugmica = form.cleaned_data['cena_deset_dugmica']\n\t\t\tdug.save()\n\t\t\treturn redirect('dugmici')\n\t\telse:\n\t\t\tform = DugmiciForm(instance=dug)\n\t\t\treturn render(request, 'dugme_forma_izmeni.html', {'form': form, 'id': id, 'error': 'Problem u izmeni. Pokusajte ponovo.'})\n\telse:\n\t\tform = DugmiciForm(instance=dug)\n\t\treturn render(request, 'dugme_forma_izmeni.html', {'form': form, 'id': id})\n\ndef izbrisi_dugme(request, id):\n\tdug = Dugmici.objects.get(dugmiciid=id)\n\tdug.delete()\n\treturn redirect('dugmici')\n\ndef novi_mebl(request):\n\tif request.method == 'POST':\n\t\tform = MeblForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tlast_obj = MaterijaliNamestaj.objects.last()\n\t\t\tmebl = MaterijaliNamestaj(m_namestajid=last_obj.m_namestajid+1, boja=form.cleaned_data['boja'], preostala_duzina=form.cleaned_data['preostala_duzina'], cena_deset_metara=form.cleaned_data['cena_deset_metara'])\n\t\t\tmebl.save()\n\t\t\treturn redirect('meblovi')\n\t\telse:\n\t\t\tform = MeblForm()\n\t\t\treturn render(request, 'mebl_forma.html', {'form': form, 'error': 'Problem u dodavanju. Pokusajte ponovo.'})\n\telse:\n\t\tform = MeblForm()\n\t\treturn render(request, 'mebl_forma.html', {'form': form})\n\ndef izmeni_mebl(request, id):\n\tmebl = get_object_or_404(MaterijaliNamestaj, pk=id)\n\tif request.method == 'POST':\n\t\tform = MeblForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tmebl.boja = form.cleaned_data['boja']\n\t\t\tmebl.preostala_duzina = form.cleaned_data['preostala_duzina']\n\t\t\tmebl.cena_deset_metara = form.cleaned_data['cena_deset_metara']\n\t\t\tmebl.save()\n\t\t\treturn redirect('meblovi')\n\t\telse:\n\t\t\tform = MeblForm(instance=mebl)\n\t\t\treturn render(request, 'mebl_forma_izmeni.html', {'form': form, 'id': id, 'error': 'Problem u izmeni. Pokusajte ponovo.'})\n\telse:\n\t\tform = MeblForm(instance=mebl)\n\t\treturn render(request, 'mebl_forma_izmeni.html', {'form': form, 'id': id})\n\ndef izbrisi_mebl(request, id):\n\tmebl = MaterijaliNamestaj.objects.get(m_namestajid=id)\n\tmebl.delete()\n\treturn redirect('meblovi')\n\ndef statistika(request):\n\treturn render(request, 'statistika.html')\n\ndef stat_mat(request):\n\tstat_materijal = Narudzbina.objects.exclude(materijal__isnull=True).values('datum_narucivanja').annotate(uk_kolicina=Sum('kolicina')).order_by('datum_narucivanja')\n\t\n\tlabele_mat = []\n\tdata_mat = []\n\t\n\tfor mat in stat_materijal:\n\t\tlabele_mat.append(mat['datum_narucivanja'])\n\t\tdata_mat.append(mat['uk_kolicina'])\n\t\n\treturn JsonResponse(data={\n\t\t'labele_mat': labele_mat,\n\t\t'data_mat': data_mat\n\t})\n\ndef stat_dug(request):\n\tstat_dugmici = Narudzbina.objects.exclude(dugmici__isnull=True).values('datum_narucivanja').annotate(uk_kolicina=Sum('kolicina')).order_by('datum_narucivanja')\n\t\n\tlabele_dug = []\n\tdata_dug = []\n\t\n\tfor dug in stat_dugmici:\n\t\tlabele_dug.append(dug['datum_narucivanja'])\n\t\tdata_dug.append(dug['uk_kolicina'])\n\t\n\treturn JsonResponse(data={\n\t\t'labele_dug': labele_dug,\n\t\t'data_dug': data_dug\n\t})\n\ndef stat_mebl(request):\n\tstat_mebl = Narudzbina.objects.exclude(m_namestaj__isnull=True).values('datum_narucivanja').annotate(uk_kolicina=Sum('kolicina')).order_by('datum_narucivanja')\n\t\n\tlabele_mebl = []\n\tdata_mebl = []\n\t\n\tfor mebl in stat_mebl:\n\t\tlabele_mebl.append(mebl['datum_narucivanja'])\n\t\tdata_mebl.append(mebl['uk_kolicina'])\n\t\n\treturn JsonResponse(data={\n\t\t'labele_mebl': labele_mebl,\n\t\t'data_mebl': data_mebl\n\t})","sub_path":"statistika_django/izvestaj/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"596268234","text":"from __future__ import annotations\nfrom collections import namedtuple\nfrom typing import Union\nfrom mentormatch.api.pair.pair import Pair\nfrom mentormatch.utils import MinMax\n\n\nclass PairsEqual:\n pass\n\n\n# PairsEqual = sentinel.PairsEqual\npairs_equal = PairsEqual()\nBetterPair = Union[PairsEqual, Pair]\nPairAndValue = namedtuple('PairAndValue', 'pair value')\nWeightedSorter = namedtuple('WeightedSorter', 'pair_ranker weight')\n\n\ndef calc_better_pair(pair1: PairAndValue, pair2: PairAndValue, mode: MinMax) -> BetterPair:\n if pair1.value == pair2.value:\n return pairs_equal\n pairs = sorted([pair1, pair2], key=lambda _pair: _pair.value)\n if mode is MinMax.MAX:\n return pairs[1].pair\n elif mode is MinMax.MIN:\n return pairs[0].pair\n raise NotImplementedError\n","sub_path":"mentormatch/api/sorter/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"195232179","text":"from django.urls import path, re_path\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom . import views\n\n\nurlpatterns = [\n re_path(r'^test/$', views.testpage, name='test'),\n re_path(r'^$', views.home, name='home'),\n re_path(r'^home/$', views.home, name='home'),\n re_path(r'^mall/(\\d+)/(\\d+)/(\\d+)/$', views.mall, name='mall'),\n re_path(r'^mall/$', views.mall_redirect, name='mall_redirect'),\n re_path(r'^trolley/$', views.trolley, name='trolley'),\n re_path(r'^profile/$', views.profile, name='profile'),\n # 登录、注册\n re_path(r'^login/$', views.login, name='login'),\n re_path(r'^register/$', views.register, name='register'),\n # 检查用户注册id是否已存在\n re_path(r'^checkuserid/$', views.checkuserid, name='checkuserid'),\n re_path(r'^logout/$', views.logout, name='logout'),\n re_path(r'^signout/$', views.signout, name='signout'),\n # 修改购物车信息\n re_path(r'^changetrolley/(\\d+)/$', views.changetrolley, name='changetrolley'),\n # 提交订单\n re_path(r'^submitorder/$', views.submitorder, name='submitorder'),\n # 验证码\n re_path(r'^captcha/$', views.captcha, name='captcha'),\n]\n\n# 实现登录、注册或进入个人资料时展示头像\nurlpatterns += static('/login/', document_root=settings.MEDIA_ROOT)\nurlpatterns += static('/profile/', document_root=settings.MEDIA_ROOT)\nurlpatterns += static('/register/', document_root=settings.MEDIA_ROOT)\n\n\n# 测试页\nurlpatterns += static('/test/', document_root=settings.MEDIA_ROOT)\n","sub_path":"project/axf/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"28882272","text":"from flask import Blueprint, render_template, url_for, redirect\nfrom flask_login import current_user, login_required\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, TextAreaField, DateField, RadioField, FieldList, FormField\n\nfrom app import db\nfrom app.posts.forms import PostForm, FeaturePlanForm, VotingForm, VotingOptionForm, VoteRadio, VoteForm\nfrom app.posts.models import Post, PlannedFeature, Vote, Voting, VotingOption\n\nblueprint = Blueprint(\n 'posts_blueprint',\n __name__,\n url_prefix='/posts',\n template_folder='templates',\n static_folder='static'\n)\n\n\n@blueprint.route('/create_post', methods=['GET', 'POST'])\n@login_required\ndef create_post(): # todo: check if only available to admin\n form = PostForm()\n\n if form.validate_on_submit():\n\n post = Post(title=form.title.data,\n text=form.text.data,\n user_id=current_user.id\n )\n db.session.add(post)\n db.session.commit()\n return redirect(url_for('settings_blueprint.administration'))\n\n return render_template('create_post.html', form=form)\n\n\n@blueprint.route(\"//delete\", methods=['POST'])\n@login_required\ndef delete_post(post_id):\n post = Post.query.get_or_404(post_id)\n db.session.delete(post)\n db.session.commit()\n return redirect(url_for('settings_blueprint.administration'))\n\n\n@blueprint.route('/create_feature_plan', methods=['GET', 'POST'])\n@login_required\ndef create_feature_plan(): # todo: check if only available to admin\n form = FeaturePlanForm()\n\n if form.validate_on_submit():\n\n planned_feature = PlannedFeature(\n feature_name=form.feature_name.data,\n feature_comment=form.feature_comment.data,\n feature_planned_start=form.feature_planned_start.data,\n feature_planned_end=form.feature_planned_end.data,\n )\n db.session.add(planned_feature)\n db.session.commit()\n return redirect(url_for('settings_blueprint.administration'))\n\n return render_template('create_feature_plan.html', form=form)\n\n\n@blueprint.route(\"//delete\", methods=['POST'])\n@login_required\ndef delete_feature_plan(feature_id):\n planned_feature = PlannedFeature.query.get_or_404(feature_id)\n db.session.delete(planned_feature)\n db.session.commit()\n return redirect(url_for('settings_blueprint.administration'))\n\n\n@blueprint.route('/votings_list')\n@login_required\ndef votings_list():\n all_votings = Voting.query.order_by(Voting.date.desc()).all()\n return render_template('all_votings.html', all_votings=all_votings)\n\n\n@blueprint.route('/create_voting', methods=['GET', 'POST'])\n@login_required\ndef create_voting():\n form = VotingForm()\n\n if form.validate_on_submit():\n voting = Voting(\n title=form.title.data,\n description=form.description.data,\n user_id=current_user.user_id,\n )\n db.session.add(voting)\n db.session.commit()\n return redirect(url_for('posts_blueprint.votings_list'))\n\n return render_template('create_voting.html', form=form)\n\n\n@blueprint.route('votings//view', methods=['GET', 'POST'])\n@login_required\ndef view_voting(voting_id):\n new_option_form = VotingOptionForm()\n voting_name = Voting.query.filter_by(voting_id=voting_id).first()\n voting_options = VotingOption.query.filter_by(voting_id=voting_id).all()\n form_rows = []\n for vo in voting_options:\n vo_dict = {'voting_option_id': vo.voting_option_id, 'title': vo.text, 'text': vo.text}\n form_rows.append(vo_dict)\n voting_form = VoteForm(fields=form_rows)\n for i in voting_form.fields:\n print(i)\n if new_option_form.validate_on_submit():\n voting_option = VotingOption(\n title=new_option_form.title.data,\n text=new_option_form.text.data,\n user_id=current_user.user_id,\n voting_id=voting_id,\n )\n db.session.add(voting_option)\n db.session.commit()\n return redirect(url_for('posts_blueprint.view_voting', voting_id=voting_id, voting_options=voting_options,\n new_option_form=new_option_form, voting_name=voting_name, voting_form=voting_form))\n\n return render_template('view_voting.html', voting_id=voting_id, voting_options=voting_options,\n new_option_form=new_option_form, voting_name=voting_name, voting_form=voting_form)\n\n\n@blueprint.route('/edit_posts')\n@login_required\ndef edit_posts():\n posts = Post.query.order_by(Post.date.desc()).all()\n features = PlannedFeature.query.order_by(PlannedFeature.feature_planned_end.asc()).all()\n return render_template('edit_posts.html', posts=posts, features=features)\n\n\n\n","sub_path":"app/posts/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"369635041","text":"dict_of_month = { \"January\": 31,\n \"February\" : 28,\n \"March\" : 31,\n \"April\" : 30,\n \"May\" : 31,\n \"June\" : 30,\n \"July\" : 31,\n \"August\" : 31,\n \"September\" : 30,\n \"October\" : 31,\n \"November\" : 30,\n \"December\" : 31}\n\ndef Sundays():\n day = 2 # 1st jan 1901 was a tuesday that's why i initialsed days with 2\n No_of_sundays = 0\n\n for year in range(1901,2001):\n\n for m in dict_of_month:\n\n day =day+ dict_of_month[m]\n if year % 4 == 0 and m == \"February\": # Condition for leap year\n day += 1\n if day % 7 == 0: #Sunday conidtion : starting from tueday at day=2, Each sunday falls on this condition\n No_of_sundays += 1\n return No_of_sundays\nNo_of_sundays=countingSundays()\nprint( No_of_sundays)\n","sub_path":"sunday.py","file_name":"sunday.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"33017293","text":"from outils import Outils\n\n\nclass BilanMensuel(object):\n \"\"\"\n Classe pour la création du bilan mensuel\n \"\"\"\n\n @staticmethod\n def bilan(dossier_destination, subedition, subgeneraux, lignes):\n \"\"\"\n création du bilan\n :param dossier_destination: Une instance de la classe dossier.DossierDestination\n :param subedition: paramètres d'édition\n :param subgeneraux: paramètres généraux\n :param lignes: lignes de données du bilan\n \"\"\"\n\n nom = \"bilan-subsides_\" + str(subedition.annee_fin_general) + \"_\" + \\\n Outils.mois_string(subedition.mois_fin_general) + \".csv\"\n\n with dossier_destination.writer(nom) as fichier_writer:\n\n ligne = [\"année\", \"mois\", \"code client\", \"code client sap\", \"abrév. labo\", \"nom labo\", \"type client\",\n \"nature client\", \"Bonus\", \"Subsides MAt\", \"Subsides MOt\"]\n for categorie in subgeneraux.codes_d3():\n ligne.append(\"Subsides \" + categorie + \"t\")\n ligne += [\"total Subsides\"]\n fichier_writer.writerow(ligne)\n\n for ligne in lignes:\n fichier_writer.writerow(ligne)\n\n @staticmethod\n def creation_lignes(subedition, subgeneraux, consolidation):\n \"\"\"\n génération des lignes de données du bilan\n :param subedition: paramètres d'édition\n :param subgeneraux: paramètres généraux\n :param consolidation: classe de consolidation des données des bilans\n :return: lignes de données du bilan\n \"\"\"\n lignes = []\n\n for code_client, client in sorted(consolidation.clients.items()):\n ligne = [subedition.annee_fin_general, subedition.mois_fin_general, code_client, client['sap'],\n client['abrev'], client['nom'], client['type'], client['nature'], client['bonus'],\n Outils.format_2_dec(client['subs_ma']), Outils.format_2_dec(client['subs_mo'])]\n for categorie in subgeneraux.codes_d3():\n ligne.append(Outils.format_2_dec(client['subs_' + categorie + 't']))\n ligne += [Outils.format_2_dec(client['subs'])]\n lignes.append(ligne)\n return lignes\n","sub_path":"traitement/bilan_mensuel.py","file_name":"bilan_mensuel.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"7054943","text":"def max_d_char(string, n): \n count = [0] * 256\n for i in range(n): \n count[ord(string[i])] += 1\n \n max_d = 0\n for i in range(256): \n if (count[i] != 0): \n max_d += 1 \n \n return max_d \n \nif __name__ == \"__main__\": \n string=input()\n if len(string)>=1 and len(string)<=10**5:\n n = len(string) \n max_d = max_d_char(string, n) \n m= n\n \n for i in range(n): \n for j in range(n): \n s = string[i:j] \n s1 = len(s) \n s2 = max_d_char(s,s1) \n \n if(s1\n# \"este script me ha \n# salvado la vida\"\n\n# ----------------------------------------------------------------------------\n# \"CR_DEHYPHENATOR\" (Revision 1.0):\n# mridpin wrote this file. You can do whatever you want with this stuff. Including but not limited to:\n# writing a GATE plugin, using it as NLP preprocessing, etc\n# ----------------------------------------------------------------------------\n\nimport os\n\nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize.treebank import TreebankWordDetokenizer\n\n# path vars, modify accordingly\ninput_docs = str(os.getcwd()) + '/input_docs'\noutput_dir = str(os.getcwd()) + '/output_docs'\n\nprint(os.getcwd())\n\nfiles = [i for i in os.listdir(input_docs) if i.endswith(\"txt\")]\n\nfor input_file in files:\n\n input_lines = open(os.path.join(input_docs, input_file)).readlines()\n\n output_lines = ''\n hyphenated_word = ''\n\n # iterate the text looking for applicable cases. \n for line in input_lines:\n\n # check if prev line had applicable word\n if (hyphenated_word):\n line = hyphenated_word + line\n hyphenated_word = '' \n\n line = line.strip()\n if len(line) > 2:\n last_char = line[-1]\n # if last char is hyphen\n if (last_char == '-'):\n # if prev char to hyphen is alpha\n prev_char = line[-2]\n if (prev_char.isalpha()):\n # store last token to join with next line\n tokens = word_tokenize(line)\n hyphenated_word = tokens[-1].rstrip('-')\n tokens.pop()\n line = TreebankWordDetokenizer().detokenize(tokens)\n output_lines += line + \"\\n\"\n\n # write output file\n output_file = open(output_dir + '/dehyphenated_' + input_file, 'w')\n output_file.write(output_lines)\n output_file.close()\n","sub_path":"cr_dehyphenator/cr_dehyphenator_es-ES.py","file_name":"cr_dehyphenator_es-ES.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"177442122","text":"import pysal\nfrom types import ModuleType, ClassType\nfrom six import iteritems as diter\n\ndef _find_bcs():\n classes = dict()\n bcs = dict()\n ucs = dict()\n submods = dict()\n for obname in dir(pysal.spreg):\n ob = pysal.spreg.__dict__[obname]\n if isinstance(ob, ModuleType):\n if ob.__package__.startswith(\"pysal\"):\n submods.update({obname:ob})\n elif isinstance(ob, ClassType):\n classes.update({obname:ob})\n if ob.__name__.startswith('Base'):\n bcs.update({obname:ob})\n for modname, mod in diter(submods):\n basecands = dict()\n for clname in dir(mod):\n cl = mod.__dict__[clname]\n if isinstance(cl, ClassType):\n try:\n if cl.__name__.startswith('Base'):\n if cl not in bcs:\n bcs.update({cl.__name__:cl})\n else:\n classes.update({cl.__name__:cl})\n except:\n pass\n ucs.update({k:v for k,v in diter(classes) if (\n any([issubclass(v, bc) for bc in bcs.values()])\n and (k not in bcs))\n or k.endswith('Regimes')})\n return bcs, ucs\n\nbase, user = _find_bcs()\n_everything = base.copy()\n_everything.update(user)\n\nfor k,v in diter(base):\n exec('{k} = {v}'.format(k=k,v=v))\nfor k,v in diter(user):\n exec('{k} = {v}'.format(k=k,v=v))\n\n__all__ = list()\n__all__.extend(base.keys())\n__all__.extend(user.keys())\n#regimes = {cls for cls in user if 'regimes' in cls.__module__}\n\n#if we go with something like a \"base\" and \"user\" submodule setup,\n#it'd be as simple as flattening the subclasses out into those submodules. \n#for name, cl in diter(_find_bcs()[0]):\n# exec('{n} = {cls}'.format(n=name, cls=cl))\n","sub_path":"pysal/contrib/handler/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"291906066","text":"import time\nfrom gen.libs import lib\nfrom gen.libs import genlib\n\n\nlog = lib.get_seq_logger()\n\n\nclass Coronado(object):\n uut = None\n sernum = None\n uuttype = None\n area = None\n container = None\n result = None\n test = None\n\n def initial_variables(self):\n self.uut = lib.conn.UUT\n self.uut.close()\n time.sleep(1)\n\n def power_on(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.uut.open()\n log.info('it is power on')\n time.sleep(1)\n lib.set_display1('Power ON')\n time.sleep(3)\n\n def power_off(self):\n \"\"\"\n\n :return:\n \"\"\"\n log.info('it is power off')\n time.sleep(0.5)\n self.uut.close()\n\n def get_prompt(self):\n lib.set_display2('Get Pormpt')\n host = 'localhost'\n log.debug('This is get_prompt - {}'.format(host))\n time.sleep(1.2)\n self.uut.send('alias\\r', expectphrase=']$', timeout=20)\n self.uut.send('ls -lt\\r', expectphrase=']$', timeout=20)\n self.uut.send('ssh -l genius {}\\r'.format(host), expectphrase=['password:', 'yes/no'], timeout=20)\n time.sleep(0.5)\n if 'yes/no' in self.uut.buf:\n self.uut.send('yes\\r', expectphrase='password:', timeout=20)\n self.uut.send('genius\\r', expectphrase=']$', timeout=20)\n time.sleep(3)\n\n def test_rf(self):\n lib.set_display3('Test RF')\n log.debug('This is test_rf')\n self.uut.send('pwd\\r', expectphrase=']$', timeout=20)\n self.uut.send('cd\\r', expectphrase=']$', timeout=20)\n self.uut.send('ls -lt | grep anaconda-ks.cfg\\r', expectphrase=']$', timeout=20)\n self.uut.send('cd\\r', expectphrase=']$', timeout=20)\n self.uut.send('ls -lt\\r', expectphrase=']$', timeout=20)\n\n def test_gps(self):\n lib.set_display1('Test GPS')\n self.uut.send('exit\\r', expectphrase=']$', timeout=20)\n self.uut.send('ls -lt\\r', expectphrase=']$', timeout=20)\n self.uut.send('cd\\r', expectphrase=']$', timeout=20)\n self.uut.send('ls -lt\\r', expectphrase=']$', timeout=20)\n # raise lib.AbortException('User try to fail')\n\n def scan_serial_number(self):\n while True:\n ans = lib.ask_question('Please input serial number - ')\n if 'FOX' not in ans:\n continue\n break\n self.sernum = 'FOX1212121'\n log.debug('Serial Number - {}'.format(self.sernum))\n self.sernum = self.sernum.strip()\n return\n\n def scan_uuttype(self):\n ans = lib.ask_question('Please input UUTTYPE - ')\n self.uuttype = 'IR2200'\n log.debug('UUTTYPE - {}'.format(self.uuttype))\n self.uuttype = self.uuttype.strip()\n return\n\n def add_start_test_data(self):\n log.debug('Add Test Data...')\n self.area = 'PCBST'\n self.result = 'S'\n log.debug('self.sernum - [{}]'.format(self.sernum))\n genlib.add_test_data(sernum=self.sernum,\n uuttype=self.uuttype,\n area=self.area,\n result=self.result)\n\n def add_duplicated_test_data(self):\n self.area = 'PCBST'\n self.result = 'S'\n log.debug('self.sernum - [{}]'.format(self.sernum))\n genlib.add_test_data(sernum=self.sernum,\n uuttype=self.uuttype,\n area=self.area,\n result=self.result)\n time.sleep(1)\n self.area = 'PCBST'\n self.result = 'P'\n log.debug('self.sernum - [{}]'.format(self.sernum))\n genlib.add_test_data(sernum=self.sernum,\n uuttype=self.uuttype,\n area=self.area,\n result=self.result)\n\n def add_pass_test_data(self):\n log.debug('Add Test Data...')\n self.area = 'PCBST'\n self.result = 'P'\n log.debug('self.sernum - [{}]'.format(self.sernum))\n log.debug('self.uuttype - [{}]'.format(self.uuttype))\n genlib.add_test_data(sernum=self.sernum,\n uuttype=self.uuttype,\n area=self.area,\n result=self.result)\n\n def add_loop_test_data(self):\n area = ['PCBST', 'PCBP2', 'PCBFA']\n result = ['S', 'P', 'F']\n test = ['Traffic Test Fail', 'Get Prompt Fail', 'Flash Test Fail']\n for i in range(1, 99):\n self.area = area[int(i % 3)]\n self.result = result[int(i % 3)]\n if self.result == 'F':\n self.test = test[int(i % 2)]\n self.sernum = 'FOX21{:03}VI{:02}'.format(i, i)\n self.uuttype = '68-{:04}-{:02}'.format(i, i)\n\n kwargs = {\n 'test': self.test,\n }\n log.debug('sernum - {}'.format(self.sernum))\n log.debug('uuttype - {}'.format(self.uuttype))\n log.debug('area - {}'.format(self.area))\n log.debug('result - {}'.format(self.result))\n genlib.add_test_data(sernum=self.sernum,\n uuttype=self.uuttype,\n area=self.area,\n result=self.result,\n **kwargs)\n time.sleep(5)\n\n def finalization(self):\n pass\n","sub_path":"gen/te/projects/iotbu/coronado/coronado.py","file_name":"coronado.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"166363179","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\npump_enable = 26\n\nGPIO.setup(pump_enable, GPIO.OUT)\n\ndef turn_on():\n GPIO.output(pump_enable, 1)\n\ndef turn_off():\n GPIO.output(pump_enable, 0)\n\nif __name__ == '__main__':\n while True:\n status = input('On or Off? (1 or 0): ')\n if status == '1':\n try:\n turn_on()\n except:\n print('Failed to turn ON GPIO pin {}'.format(pump_enable))\n elif status == '0':\n try: \n turn_off()\n except:\n print('Failed to turn OFF GPIO pin {}'.format(pump_enable))\n\n","sub_path":"YingXao_Embedded/sensor_dev/Pump/pump.py","file_name":"pump.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247013180","text":"def random_on_space_invaders():\n import q_learning as q\n import ale_game as ag\n reload(q)\n reload(ag)\n\n ale = ag.init()\n game = ag.SpaceInvadersGame(ale)\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n return game\n\n # game.show_vectorized(game.vectorized(ale.getScreen()))\n teacher = q.Teacher(new_game, q.RandomAlgo(game.get_actions()), ag.SpaceInvadersGameCombined2Visualizer(),\n ag.Phi(skip_every=6), repeat_action=6)\n teacher.teach(1)\n\n\ndef dqn_on_space_invaders_gpu(visualize=False, theano_verbose=False, initial_weights_file=None, initial_i_frame=0):\n import q_learning as q\n import ale_game as ag\n import dqn\n import theano\n reload(q)\n reload(ag)\n reload(dqn)\n\n print(\"Using weights from file: \", initial_weights_file)\n\n if theano_verbose:\n theano.config.compute_test_value = 'warn'\n theano.config.exception_verbosity = 'high'\n theano.config.optimizer = 'fast_compile'\n\n ale = ag.init()\n game = ag.SpaceInvadersGame(ale)\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n game.lives = 4\n return game\n\n replay_memory = dqn.ReplayMemory(size=500000)\n dqn_algo = dqn.DQNAlgo(game.n_actions(), replay_memory=replay_memory, initial_weights_file=initial_weights_file)\n\n if initial_weights_file:\n dqn_algo.replay_start_size = 250000\n dqn_algo.epsilon = 0.1\n dqn_algo.final_epsilon = 0.1\n dqn_algo.initial_epsilon = 0.1\n dqn_algo.i_frames = initial_i_frame\n\n print(str(dqn_algo))\n\n visualizer = ag.SpaceInvadersGameCombined2Visualizer() if visualize else q.GameNoVisualizer()\n teacher = q.Teacher(new_game, dqn_algo, visualizer,\n ag.Phi(skip_every=4), repeat_action=4, sleep_seconds=0)\n teacher.teach(500000)\n\n\ndef dqn_on_space_invaders_cpu(visualize=False, theano_verbose=False, initial_weights_file=None, ignore_feedback=False):\n import q_learning as q\n import ale_game as ag\n import dqn\n import theano\n reload(q)\n reload(ag)\n reload(dqn)\n if theano_verbose:\n theano.config.compute_test_value = 'warn'\n theano.config.exception_verbosity = 'high'\n theano.config.optimizer = 'fast_compile'\n\n ale = ag.init()\n game = ag.SpaceInvadersGame(ale)\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n game.lives = 4\n return game\n\n replay_memory = dqn.ReplayMemory(size=100, grace=10)\n dqn_algo = dqn.DQNAlgo(game.n_actions(), replay_memory=replay_memory, initial_weights_file=initial_weights_file)\n\n dqn_algo.target_network_update_frequency = 50\n dqn_algo.replay_memory_size = 100\n dqn_algo.replay_start_size = 75\n dqn_algo.epsilon = 0.1\n dqn_algo.initial_epsilon = 0.1\n dqn_algo.final_epsilon = 0.1\n dqn_algo.log_frequency = 10\n\n dqn_algo.ignore_feedback = ignore_feedback\n # dqn_algo.ignore_feedback = True\n\n print(str(dqn_algo))\n\n visualizer = ag.SpaceInvadersGameCombined2Visualizer() if visualize else q.GameNoVisualizer()\n teacher = q.Teacher(new_game, dqn_algo, visualizer,\n ag.Phi(skip_every=4), repeat_action=4, sleep_seconds=0)\n teacher.teach(500000)\n\n\nclass Plot(object):\n\n def __init__(self):\n import matplotlib.pyplot as plt\n plt.ion()\n self.fig = plt.figure()\n plt.title('Surprise')\n plt.ylabel('Surprise (red), Expectation (blue)')\n plt.xlabel('frame')\n\n self.expectation = self.fig.add_subplot(2, 1, 1)\n self.expectations_l, = self.expectation.plot([], [], color='b', linestyle='-', lw=2)\n self.expectation.set_xlim([0, 105])\n self.expectation.set_ylim([-5, 10])\n\n self.surprise = self.fig.add_subplot(2, 1, 2)\n self.surprise_l, = self.surprise.plot([], [], color='r', linestyle='-', lw=2)\n self.surprise.set_xlim([0, 105])\n self.surprise.set_ylim([-5, 5])\n\n self.expectations_y = []\n self.surprise_y = []\n self.i = 0\n self.print_every_n = 1\n\n def show(self, info):\n self.i += 1\n\n self.expectations_y.append(info['expectations'])\n self.surprise_y.append(info['surprise'])\n if len(self.expectations_y) > 100:\n self.expectations_y = self.expectations_y[1:]\n self.surprise_y = self.surprise_y[1:]\n\n print(info)\n if self.i % self.print_every_n == 0:\n self.expectations_l.set_xdata(list(range(len(self.expectations_y))))\n self.expectations_l.set_ydata(self.expectations_y)\n self.surprise_l.set_xdata(list(range(len(self.surprise_y))))\n self.surprise_l.set_ydata(self.surprise_y)\n\n # self.mi.set_xdata([self.xlim[0]] * 2)\n # self.mi.set_ydata([-0.08, 0.08])\n # self.ma.set_xdata([self.xlim[1]] * 2)\n # self.ma.set_ydata([-0.08, 0.08])\n\n #pos = np.arange(-1.2, 0.5, 0.05)\n #vel = np.arange(-0.07, 0.07, 0.005)\n\n #self.expectation.line(expectations)\n\n self.fig.canvas.draw()\n self.fig.canvas.flush_events()\n\n #time.sleep(0.01)\n\n\n\ndef dqn_on_space_invaders_play(initial_weights_file, visualize='q', show_mood=False):\n import q_learning as q\n import ale_game as ag\n import dqn\n reload(q)\n reload(ag)\n reload(dqn)\n\n print(\"Using weights from file: \", initial_weights_file)\n\n ale = ag.init(display_screen=(visualize == 'ale'))\n game = ag.SpaceInvadersGame(ale)\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n game.lives = 4\n return game\n\n replay_memory = dqn.ReplayMemory(size=100, grace=10)\n dqn_algo = dqn.DQNAlgo(game.n_actions(), replay_memory=replay_memory, initial_weights_file=initial_weights_file)\n\n dqn_algo.epsilon = 0.1\n dqn_algo.initial_epsilon = 0.1\n dqn_algo.final_epsilon = 0.1\n dqn_algo.ignore_feedback = True\n dqn_algo.log_frequency = 0\n\n import Queue\n dqn_algo.mood_q = Queue.Queue() if show_mood else None\n\n if show_mood:\n plot = Plot()\n\n def worker():\n while True:\n item = dqn_algo.mood_q.get()\n plot.show(item)\n dqn_algo.mood_q.task_done()\n\n import threading\n t = threading.Thread(target=worker)\n t.daemon = True\n t.start()\n\n print(str(dqn_algo))\n\n visualizer = ag.SpaceInvadersGameCombined2Visualizer() if visualize == 'q' else q.GameNoVisualizer()\n teacher = q.Teacher(new_game, dqn_algo, visualizer,\n ag.Phi(skip_every=4), repeat_action=4, sleep_seconds=0)\n return teacher.teach(100)\n\n\ndef const_on_space_invaders():\n import q_learning as q\n import ale_game as ag\n import dqn\n reload(q)\n reload(ag)\n reload(dqn)\n\n ale = ag.init()\n game = ag.SpaceInvadersGame(ale)\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n return game\n\n const_algo = q.ConstAlgo([2, 2, 2, 2, 2, 0, 0, 0, 0])\n teacher = q.Teacher(new_game, const_algo, ag.SpaceInvadersGameCombined2Visualizer(),\n ag.Phi(skip_every=6), repeat_action=6)\n teacher.teach(1)\n\n\ndef sarsa_gd_on_space_invaders():\n import q_learning as q\n import numpy as np\n import ale_game as ag\n import matplotlib.pyplot as plt\n import sarsa as ss\n\n plt.ion()\n reload(ss)\n reload(q)\n reload(ag)\n ale = ag.init()\n run = '1'\n\n def state_adapter(frames):\n result = np.where(np.reshape(np.concatenate(frames), 80 * 80 * 4) > 0)\n if len(result) == 0:\n return [0]\n else:\n return result\n\n game = ag.SpaceInvadersGame(ale)\n q_algo1 = ss.SARSALambdaGradientDescent(game.n_actions(), theta_len=80 * 80 * 4, state_adapter=state_adapter)\n q_algo1.epsilon = 0.9\n q_algo1.lmbda = 0.99\n q_algo1.gamma = 0.999\n q_algo1.alpha = 0.1\n\n def new_game():\n game.ale.reset_game()\n game.finished = False\n game.cum_reward = 0\n return game\n\n\n\n result_test = []\n result_1 = []\n result_2 = []\n\n teacher = q.Teacher(new_game, q_algo1, q.GameNoVisualizer(), phi=ag.Phi(skip_every=6), repeat_action=6)\n\n q_algo1.epsilon = 1\n q_algo1.log_freq = 1\n result_test.append(teacher.teach(10))\n\n vis_teacher = q.Teacher(new_game, q_algo1, ag.SpaceInvadersGameCombined2Visualizer(), phi=ag.Phi(skip_every=6),\n repeat_action=6)\n\n # teacher.single_step(Game)\n q_algo1.epsilon = 0.1\n q_algo1.log_freq = 1\n # vis_teacher.teach(5)\n\n for i in xrange(90):\n q_algo1.log_freq = 0.03\n q_algo1.epsilon = 1 - i / 100\n result_2.append(teacher.teach(50))\n q_algo1.epsilon = 0.1\n result_test.append(teacher.teach(10))\n\n import cPickle as pickle\n with open('gradient_descent.theta' + run, 'wb') as handle:\n pickle.dump(q_algo1.theta, handle)\n\n with open('gradient_descent.gamma' + run, 'wb') as handle:\n pickle.dump(q_algo1.gamma, handle)\n\n with open('gradient_descent.lmbda' + run, 'wb') as handle:\n pickle.dump(q_algo1.lmbda, handle)\n\n with open('gradient_descent.alpha' + run, 'wb') as handle:\n pickle.dump(q_algo1.alpha, handle)\n\n r1 = [a[1] for a in result_1]\n plt.plot(np.array([x[1] - x[0] for x in zip(np.cumsum(r1), np.cumsum(r1)[200:])]) / 200)\n\n r2 = [a[1] for r in result_2 for a in r]\n plt.plot(np.array([x[1] - x[0] for x in zip(np.cumsum(r2), np.cumsum(r2)[200:])]) / 200)\n\n r_test = [a[1] for r in result_test for a in r]\n plt.plot(np.array([x[1] - x[0] for x in zip(np.cumsum(r_test), np.cumsum(r_test)[50:])]) / 50)\n\n r_4 = [a[1] for a in result_4]\n plt.plot(np.array([x[1] - x[0] for x in zip(np.cumsum(r_test), np.cumsum(r_4)[2:])]) / 2)\n\n q_algo1.epsilon = 0.1\n teacher = q.Teacher(new_game, q_algo1, q.GameNoVisualizer(), repeat_action=3)\n teacher.teach(100)\n\n\ndef random_on_mountain_car_game():\n import games as g\n import q_learning as q\n reload(q)\n reload(g)\n game = g.MountainCarGame()\n q_algo = q.RandomAlgo(game.get_actions())\n visualizer = g.MountainCarGameVisualizer()\n\n teacher = q.Teacher(game, q_algo, visualizer)\n\n teacher.teach(1)\n\n\ndef latest(dir='.'):\n import os, re\n frames = [int(re.match(r\"weights_([0-9]*).npz\", file).groups()[0])\n for file in os.listdir(dir) if file.startswith(\"weights_\")]\n\n return dir + '/weights_' + str(max(frames)) + '.npz', max(frames)\n\n#dqn_on_space_invaders(visualize=visualize, initial_weights_file=initial_weights_file)\n#dqn_on_space_invaders(visualize=True, initial_weights_file='weights_2400100.npz', ignore_feedback=True)\n\n\n#dqn_on_space_invaders_gpu(visualize=False, initial_weights_file=latest('.')[0], initial_i_frame=latest('.')[1])\n\n#results = dqn_on_space_invaders_play(visualize=None, initial_weights_file='analysis/sth_working_900000.npz', show_mood=False)\n\n\n#results = dqn_on_space_invaders_cpu(visualize=None, initial_weights_file=None)\nresults = dqn_on_space_invaders_play(visualize='ale', initial_weights_file=latest('analysis')[0], show_mood=True)\n#results = dqn_on_space_invaders_play(visualize='q', initial_weights_file=None, show_mood=True)\n#results = dqn_on_space_invaders_play(visualize='ale', initial_weights_file='analysis/weights_800100.npz', show_mood=True)\n#results = dqn_on_space_invaders_play(visualize='q', initial_weights_file='analysis/weights_1000100.npz')\n#results = dqn_on_space_invaders_play(visualize='q', initial_weights_file='analysis/weights_800100.npz')\n\n#pickle.dump(results, open(\"results_900000_new.pickled\", \"wb\"))\n","sub_path":"ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":11828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"608538808","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n# @项目名称: python\n# @File : aStart.py\n# @Time : 2020/3/27 14:01\n# @Author : big\n# @Email : shdorado@126.com\n\nimport sys\nimport random\nimport math\nimport time\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Node:\n def __init__(self, index, value, father=None):\n self.index = index\n self.value = value\n self.father = father\n self.child_left = None\n self.child_right = None\n\n\nclass MaxHeap:\n \"\"\"最大堆:父比子大\"\"\"\n heap = []\n\n @staticmethod\n def show_heap():\n print(MaxHeap.heap)\n\n # region 基本操作\n # region 插入元素\n @staticmethod\n def insert(num):\n MaxHeap.heap.append(num)\n MaxHeap.shift_up()\n\n @staticmethod\n def shift_up():\n \"\"\"把新增在最后的大数节点往上移动\"\"\"\n current_id = len(MaxHeap.heap) - 1\n parent_id = (current_id - 1) // 2\n while current_id > 0:\n if MaxHeap.heap[parent_id] >= MaxHeap.heap[current_id]:\n break\n else:\n MaxHeap.heap[parent_id], MaxHeap.heap[current_id] = MaxHeap.heap[current_id], MaxHeap.heap[parent_id]\n current_id = parent_id\n parent_id = (current_id - 1) // 2\n\n # endregion\n\n # region 删除元素\n @staticmethod\n def delate(num):\n \"\"\"删除特定数,并下沉\"\"\"\n temp = MaxHeap.heap.pop()\n if num == temp: # 是最末的最小数\n return\n if num not in MaxHeap.heap:\n print('not in heap')\n return\n ind = MaxHeap.heap.index(num)\n MaxHeap.heap[ind] = temp\n MaxHeap.shift_down(ind)\n\n @staticmethod\n def shift_down(ind):\n \"\"\"把最末的数作为根,再根据大小往下沉\"\"\"\n current_id = ind\n child_id_left = current_id * 2 + 1\n child_id_right = current_id * 2 + 2\n while current_id < len(MaxHeap.heap) - 1:\n # 如果当前节点为叶子节点,shift_down完成\n if current_id * 2 + 1 > len(MaxHeap.heap) - 1:\n break\n # 如果当前节点只有左孩子没有右孩子\n if current_id * 2 + 1 == len(MaxHeap.heap) - 1:\n if MaxHeap.heap[current_id] > MaxHeap.heap[-1]:\n break\n else:\n MaxHeap.heap[current_id], MaxHeap.heap[-1] = MaxHeap.heap[-1], MaxHeap.heap[current_id]\n break\n # 如果当前节点既有左孩子又有右孩子\n if MaxHeap.heap[current_id] > max(MaxHeap.heap[child_id_left], MaxHeap.heap[child_id_right]):\n break\n else:\n if MaxHeap.heap[child_id_right] > MaxHeap.heap[child_id_left]:\n MaxHeap.heap[child_id_right], MaxHeap.heap[current_id] = MaxHeap.heap[current_id], MaxHeap.heap[\n child_id_right]\n current_id = child_id_right\n child_id_left = current_id * 2 + 1\n child_id_right = current_id * 2 + 2\n else:\n MaxHeap.heap[child_id_left], MaxHeap.heap[current_id] = MaxHeap.heap[current_id], MaxHeap.heap[\n child_id_left]\n current_id = child_id_left\n child_id_left = current_id * 2 + 1\n child_id_right = current_id * 2 + 2\n\n # endregion\n # endregion\n\n # region 基础排序\n @staticmethod\n def extract_max():\n \"\"\"弹出最大的根,并重新构建\"\"\"\n num = MaxHeap.heap[0]\n try:\n MaxHeap.delate(num)\n return num\n except:\n return num\n\n @staticmethod\n def heap_sort(arr):\n for n in arr: # 形成大堆\n MaxHeap.insert(n)\n for i in range(len(arr)): # 大堆重新赋值给源\n arr[i] = MaxHeap.extract_max()\n\n @staticmethod\n def heapify(arr):\n \"\"\"从最后一个父节点倒推,一个个下沉,省去所有叶子的运算\"\"\"\n MaxHeap.heap = arr\n n = (len(arr) - 1) // 2\n while n >= 0:\n MaxHeap.shift_down(n)\n n -= 1\n\n @staticmethod\n def heap_sort2(arr):\n \"\"\"返回列表的绝对排序过的新列表\"\"\"\n MaxHeap.heapify(arr)\n res = []\n for i in range(len(arr)):\n res.append(MaxHeap.extract_max())\n return res\n\n @staticmethod\n def heap_sort3(arr):\n \"\"\"原地堆排序,直接在源数据上操作\"\"\"\n MaxHeap.heapify(arr)\n for i in range(len(arr) - 1, -1, -1):\n MaxHeap.heap[i], MaxHeap.heap[0] = MaxHeap.heap[0], MaxHeap.heap[i] # 将堆顶元素与堆尾元素互换\n MaxHeap.shift_down(0)\n # endregion\n\n\nclass MinHeap:\n \"\"\"最小堆:父比子小\"\"\"\n heap = []\n\n @staticmethod\n def show_heap():\n print(MinHeap.heap)\n\n # region 基本操作\n # region 插入元素\n @staticmethod\n def insert(num):\n MinHeap.heap.append(num)\n MinHeap.shift_up()\n # MinHeap.show_heap()\n\n @staticmethod\n def shift_up():\n \"\"\"把新增在最后的小数往上移动\"\"\"\n current_id = len(MinHeap.heap) - 1\n parent_id = (current_id - 1) // 2\n while current_id > 0:\n if MinHeap.heap[parent_id] <= MinHeap.heap[current_id]:\n break\n else:\n MinHeap.heap[parent_id], MinHeap.heap[current_id] = MinHeap.heap[current_id], MinHeap.heap[parent_id]\n current_id = parent_id\n parent_id = (current_id - 1) // 2\n\n # endregion\n\n # region 删除元素\n @staticmethod\n def delate(num):\n \"\"\"删除特定数,并下沉\"\"\"\n temp = MinHeap.heap.pop()\n if num == temp: # 是最末的最大数\n return\n if num not in MinHeap.heap:\n print('not in heap')\n return\n ind = MinHeap.heap.index(num)\n MinHeap.heap[ind] = temp\n MinHeap.shift_down(ind)\n\n @staticmethod\n def shift_down(ind):\n \"\"\"父节点根据大小往下沉\"\"\"\n current_id = ind\n child_left_id = current_id * 2 + 1\n child_right_id = current_id * 2 + 2\n while child_left_id <= len(MinHeap.heap) - 1:\n # 如果当前节点为叶子节点,shift_down完成\n # if child_left_id > len(MinHeap.heap) - 1:\n # break\n\n # 如果当前节点只有左孩子没有右孩子\n if child_left_id == len(MinHeap.heap) - 1:\n if MinHeap.heap[current_id] < MinHeap.heap[-1]:\n break\n else:\n MinHeap.heap[current_id], MinHeap.heap[-1] = MinHeap.heap[-1], MinHeap.heap[current_id]\n break\n # 如果当前节点既有左孩子又有右孩子\n else:\n litter_id = child_left_id \\\n if MinHeap.heap[child_left_id] <= MinHeap.heap[child_right_id] else child_right_id\n if MinHeap.heap[current_id] <= MinHeap.heap[litter_id]:\n break\n else:\n MinHeap.heap[litter_id], MinHeap.heap[current_id] \\\n = MinHeap.heap[current_id], MinHeap.heap[litter_id]\n current_id = litter_id\n child_left_id = current_id * 2 + 1\n child_right_id = current_id * 2 + 2\n\n # endregion\n # endregion\n\n # region 基础排序\n @staticmethod\n def extract_min():\n \"\"\"弹出最小的根,并重新构建\"\"\"\n num = MinHeap.heap[0]\n try:\n MinHeap.delate(num)\n return num\n except:\n return num\n\n @staticmethod\n def heap_sort(arr):\n for n in arr: # 形成大堆\n MinHeap.insert(n)\n for i in range(len(arr)): # 大堆重新赋值给源\n arr[i] = MinHeap.extract_min()\n\n @staticmethod\n def heapify(arr):\n \"\"\"从最后一个父节点倒推,一个个下沉,省去所有叶子的运算\"\"\"\n MinHeap.heap = arr\n n = (len(arr) - 1) // 2\n while n >= 0:\n MinHeap.shift_down(n)\n n -= 1\n\n @staticmethod\n def heap_sort2(arr):\n \"\"\"返回列表的绝对排序过的新列表\"\"\"\n MinHeap.heapify(arr)\n res = []\n for i in range(len(arr)):\n res.append(MinHeap.extract_min())\n return res\n\n @staticmethod\n def heap_sort3(arr):\n \"\"\"原地堆排序,直接在源数据上操作\"\"\"\n MinHeap.heapify(arr)\n for i in range(len(arr) - 1, -1, -1):\n MinHeap.heap[i], MinHeap.heap[0] = MinHeap.heap[0], MinHeap.heap[i] # 将堆顶元素与堆尾元素互换\n MinHeap.shift_down(0)\n # endregion\n\n\nclass MyBinaryTree(object):\n def __init__(self, btree):\n\n for each in btree:\n MinHeap.insert(each)\n # MinHeap.heap = btree\n self.Btree = MinHeap.heap\n\n # MaxHeap.heap = self.Btree\n # MinHeap.heap_sort3(self.Btree)\n # res = self.Heap.heap_sort2(self.Btree)\n # print(res)\n # MaxHeap.show_heap()\n\n # self.Heap.insert(11)\n MinHeap.delate(2)\n # self.Heap.show_heap()\n # print(self.Btree)\n\n self.Count = len(self.Btree)\n self.Depth = int(math.log2(self.Count)) + 1 if self.Count > 0 else 0 # 深度 n个节点的完全二叉树的深度\n self.Breadth = pow(2, self.Depth) - 1 # 广度,最底层需要的格数,即完全二叉树的节点数\n\n def draw_node(self, qp, grid_w, grid_h, index):\n depth = int(math.log2(index + 1) if index >= 0 else 0) # 所在层数\n depth_max = self.Depth - 1 # 深度\n\n grid_first = pow(2, depth_max - depth) # 左边距\n grid_mid = 2 * grid_first # 中间的间隔\n\n first_index = pow(2, depth) - 1 # 左边第一项序号\n # last_index = first_index + pow(2, depth) - 1 # pow(2, depth+1) - 2\n # # 右边序号\n\n cur_grid_x = grid_first + grid_mid * (index - first_index) + 1 # 树左移一格\n cur_grid_y = depth + 1 # 节点所在的格子\n\n x = cur_grid_x * grid_w - grid_w // 2 # 圆心的屏幕坐标\n y = cur_grid_y * grid_h - grid_h // 2\n\n ride = 25 # 圆半径\n rect = QtCore.QRect(x - ride, y - ride, 2 * ride, 2 * ride)\n\n qp.setPen(QtCore.Qt.darkBlue)\n qp.setBrush(QtGui.QColor(173, 216, 230))\n\n # 画圆\n qp.drawEllipse(rect)\n\n # 画数字\n font = QtGui.QFont('Decorative', 20)\n font.setBold(True)\n qp.setFont(font)\n qp.drawText(rect, QtCore.Qt.AlignCenter, str(self.Btree[index]))\n\n # 画连线\n pen = QtGui.QPen(QtGui.QColor(0, 150, 0), 2, QtCore.Qt.SolidLine)\n qp.setPen(pen)\n\n if index == 0:\n return\n\n X = grid_first * grid_w\n R = math.sqrt(pow(X, 2) + grid_h * grid_h)\n scale = ride / R\n dx = round(scale * X)\n dy = round(scale * grid_h)\n\n if index % 2: # 在左边\n qp.drawLine(x + dx, y - dy, x - dx + X, y + dy - grid_h)\n else: # 在右边\n qp.drawLine(x - dx, y - dy, x + dx - X, y + dy - grid_h)\n\n def draw_tree(self, qp, canvas_size):\n col = QtGui.QColor(0, 0, 0)\n col.setNamedColor('#d0d0d0')\n # pen = QPen()\n qp.setPen(col)\n\n if self.Depth == 0:\n return\n grid_w = canvas_size.width() // self.Breadth # 画布方格尺寸\n grid_h = canvas_size.height() // self.Depth # 画布方格尺寸\n\n for y in range(self.Depth):\n for x in range(self.Breadth):\n # qp.setBrush(col)\n qp.drawRect(\n round(\n grid_w * x),\n round(\n grid_h * y),\n round(grid_w),\n round(grid_h))\n\n for i in range(self.Count):\n self.draw_node(qp, grid_w, grid_h, i)\n\n\nclass ShowTree(QtWidgets.QWidget):\n def __init__(self, parent=None):\n # noinspection PyArgumentList\n super(ShowTree, self).__init__()\n self.heap = [90, 2, 85, 70, 10, 60, 80, 30, 20, 50, 40, 34, 134, 62]\n\n self.tree = MyBinaryTree(self.heap)\n\n # self.maxHeap = MaxHeap(self.heap)\n # self.initUI()\n\n def initUI(self):\n pass\n\n def clicked(self):\n pass\n\n def paintEvent(self, event):\n qp = QtGui.QPainter()\n qp.begin(self)\n self.tree.draw_tree(qp, QtCore.QSize(self.width() - 50, self.height() - 50))\n qp.end()\n\n\nclass NewAStar(object):\n \"\"\"采用二叉堆的 A星算法\"\"\"\n\n def __init__(self):\n self.map2d_w = 1\n self.map2d_h = 1\n\n self.map2d = []\n self.map2d_size = None\n\n self.start = None\n self.end = None\n\n self.impasse = None # 死路的权重\n self.value = None # 权重范围\n\n self.open_list = []\n self.close_list = []\n\n self.init_map2d(5, 54, 5, 54)\n\n def init_map2d(self, map_w=5, map_h=12, start=0, end=59):\n \"\"\"初始化地图数据\"\"\"\n # [row, col , g, h, v, father]\n # row,col-坐标 g-当前路径成本 h-估算成本 v-节点的权重 father-父节点\n self.map2d.clear()\n self.open_list.clear()\n self.close_list.clear()\n\n self.map2d_w = map_w\n self.map2d_h = map_h\n self.start = start # 初始化起点的序号\n self.end = end # 初始化终点的序号\n self.map2d_size = self.map2d_w * self.map2d_h # 地图节点数目\n\n self.open_list.append(self.start) # 起点放进列表\n\n self.impasse = 4 # 死路\n self.value = [1, 2, 3, self.impasse] # 权重\n\n for row in range(self.map2d_h):\n for col in range(self.map2d_w):\n h = (abs(self.end // self.map2d_h - row) + abs(self.end % self.map2d_w - col)) * 10 # 计算h值\n value = random.choice(self.value)\n\n # [row, col , g, h, v, father]\n # row,col-坐标 g-当前路径成本 h-估算成本 v-节点的权重 father-父节点\n self.map2d.append([row, col, 0, h, value, None])\n\n # self.map2d[self.start][4] = 2 # 起点权重\n # self.map2d[self.end][4] = 3 # 终点权重\n # print(self.map2d)\n\n def _get_f(self, node):\n assert 0 <= node < self.map2d_size\n return self.map2d[node][2] + self.map2d[node][3] # 价值\n\n # region 插入和删除 open list的项目\n def _insert(self, num):\n current_id = 0\n parent_id = 0\n\n if num in self.open_list:\n current_id = self.open_list.index(num)\n parent_id = (current_id - 1) // 2\n else:\n self.open_list.append(num)\n current_id = len(self.open_list) - 1\n parent_id = (current_id - 1) // 2\n\n \"\"\"把新增在最后的小数往上移动\"\"\"\n while current_id > 0:\n if self._get_f(self.open_list[parent_id]) <= self._get_f(self.open_list[current_id]): # f值比较\n break\n else:\n self.open_list[parent_id], self.open_list[current_id] = \\\n self.open_list[current_id], self.open_list[parent_id]\n\n current_id = parent_id\n parent_id = (current_id - 1) // 2\n\n def _delate(self, num):\n \"\"\"删除特定数,并下沉\"\"\"\n if num not in self.open_list:\n print(f'delate {num} : it is not in open list')\n return None\n\n temp = self.open_list.pop()\n if num == temp: # 是最末的最大数\n return num\n\n ind = self.open_list.index(num)\n self.open_list[ind] = temp # 用最后一项覆盖当前位置\n # print(self.open_list)\n self._shift_down(ind) # 可以不用调用吗?\n # print(self.open_list)\n return num\n\n def _shift_down(self, ind):\n \"\"\"父节点根据大小往下沉\"\"\"\n current_id = ind\n child_left_id = current_id * 2 + 1\n child_right_id = current_id * 2 + 2\n\n last_id = len(self.open_list) - 1\n\n while child_left_id <= last_id: # 叶子节点不需要处理\n # 如果当前节点只有左孩子没有右孩子\n if child_left_id == last_id:\n if self._get_f(self.open_list[current_id]) <= self._get_f(self.open_list[-1]): # f值比较\n break\n else:\n self.open_list[current_id], self.open_list[-1] = \\\n self.open_list[-1], self.open_list[current_id]\n break\n # 如果当前节点既有左孩子又有右孩子\n else:\n litter_id = child_left_id \\\n if self._get_f(self.open_list[child_left_id]) <= self._get_f(self.open_list[child_right_id]) \\\n else child_right_id\n if self._get_f(self.open_list[current_id]) <= self._get_f(self.open_list[litter_id]):\n break\n else:\n self.open_list[litter_id], self.open_list[current_id] \\\n = self.open_list[current_id], self.open_list[litter_id]\n current_id = litter_id\n child_left_id = current_id * 2 + 1\n child_right_id = current_id * 2 + 2\n\n # endregion\n\n def deal_neighbours(self, node_id):\n \"\"\"处理邻居\"\"\"\n node_row = self.map2d[node_id][0]\n node_col = self.map2d[node_id][1]\n\n for i in range(node_row - 1, node_row + 2):\n if i < 0 or i >= self.map2d_h: # 越界检测\n continue\n for j in range(node_col - 1, node_col + 2):\n if j < 0 or j >= self.map2d_w: # 越界检测\n continue\n if i == node_row and j == node_col: # 自身检测\n continue\n\n if (i + j - node_row - node_col) not in [-1, 1]: # 四个角忽略,不走对角线\n continue\n\n neighbour_id = i * self.map2d_w + j\n\n if self.map2d[neighbour_id][4] == self.impasse: # 避开障碍物\n continue\n\n if neighbour_id in self.close_list: # 已经处理过了\n continue\n\n path = abs(node_row - i) + abs(node_col - j)\n value = 10 if path == 1 else 14 # 不容许对角线通过,14则可以\n\n new_g = self.map2d[neighbour_id][4] * value + self.map2d[node_id][2] # 计算跨越的代价\n\n if neighbour_id not in self.open_list: # 新考察对象\n self.map2d[neighbour_id][5] = node_id # 更新其父亲\n if neighbour_id == self.end: # 已经找到终点了\n return 1\n self.map2d[neighbour_id][2] = new_g # 首先更新g值\n self._insert(neighbour_id) # 再根据f值大小排序插入\n else:\n if new_g < self.map2d[neighbour_id][2]: # 更小的g值\n self.map2d[neighbour_id][5] = node_id # 更新其父亲\n self.map2d[neighbour_id][2] = new_g # 必须更新g值\n # self._delate(neighbour_id) # 已经处理过了,不重复添加\n self._insert(neighbour_id) # 先删后插,以保持排序\n else:\n continue # 父亲、g值不必改变\n\n # if node_id in self.open_list:\n # self._insert(node_id)\n self._delate(node_id)\n self.close_list.append(node_id)\n\n return 0\n\n # 获得最短路径\n def searching(self):\n path = []\n if self.map2d[self.end][4] != self.impasse: # 判断寻路终点是否是障碍\n # 2.主循环逻辑\n while True:\n if not self.open_list:\n print('山重水复疑无路')\n break\n\n if self.deal_neighbours(self.open_list[0]): # 找到终点了\n son_id = self.end\n while True:\n if son_id != self.start:\n path.append(son_id)\n son_id = self.map2d[son_id][5] # 找父亲\n else:\n path.append(son_id)\n return list(reversed(path))\n else:\n print('世上只有套路,本没有路')\n\n return path\n\n # def get_min_node(self):\n # if not self.open_list:\n # return None\n #\n # node = self.open_list[0]\n # for each in self.open_list:\n # f = self._get_f(each)\n # print(f)\n # if self._get_f(node) > f: # 等于时怎么办?\n # node = each\n # print(self._get_f(node))\n # return node\n\n\nclass MyAStar(object):\n class Point:\n \"\"\"\n 表示一个点\n \"\"\"\n\n def __init__(self, row, col):\n self.row = row\n self.col = col\n\n def __eq__(self, other):\n if self.row == other.row and self.col == other.col:\n return True\n return False\n\n def __str__(self):\n return \"row:\" + str(self.row) + \", col:\" + str(self.col)\n\n class Node: # 描述AStar算法中的节点数据\n def __init__(self, point, endPoint, v=0):\n \"\"\"\n :param point: 二元组\n :param endPoint: 二元组\n :param v:\n \"\"\"\n self.point = point # 自己的坐标\n self.v = v # 节点的权重\n # 从起点移动到方格的移动代价,沿着到达该方格而生成的路径\n self.g = 0 # g值在用到的时候会重新算\n # 从指定的方格移动到终点 B 的估算成本\n self.h = (abs(endPoint.row - point.row) +\n abs(endPoint.col - point.col)) * 10 # 计算h值\n self.f = self.g + self.h\n self.father = None # 父节点\n\n def __str__(self):\n return f\"{self.point} v={self.v} g={self.g} h={self.h} father:{self.father}\"\n\n class Map2D:\n \"\"\"\n 说明:\n 1.构造方法需要两个参数,即二维数组的宽和高\n 2.成员变量w和h是二维数组的宽和高\n 3.使用:‘对象[x][y]’可以直接取到相应的值\n 4.数组的默认值都是0\n \"\"\"\n\n def __init__(self, w, h):\n self.width = w # 地图宽\n self.height = h # 地图高\n\n self.start_point = MyAStar.Point(0, 0) # 起点坐标\n self.end_point = MyAStar.Point(h - 1, w - 1) # 终点坐标\n # self.end_point = Point(random.randint(0, h-1), random.randint(0, w-1))\n\n self.impasse = 4 # 死路\n value = [1, 2, 3, self.impasse] # 权重\n self.pics = [\n r'E:\\python\\res\\images\\good.png',\n r'E:\\python\\res\\images\\tu.png',\n r'E:\\python\\res\\images\\grass.png',\n r'E:\\python\\res\\images\\water.png',\n r'E:\\python\\res\\images\\pudi.png']\n\n self.nodes = [[MyAStar.Node(MyAStar.Point(i, j), self.end_point, random.choice(\n value)) for j in range(w)] for i in range(h)]\n\n self.nodes[0][0].v = 3\n self.nodes[self.end_point.row][self.end_point.col].v = 1\n\n def getValue(self, i, j):\n return self.nodes[i][j].v - 1\n # def showMap(self):\n # for y in range(self.h):\n # for x in range(self.w):\n # print(self.data[x][y], end=' ')\n # print(\"\")\n #\n # def __getitem__(self, item):\n # return self.data[item]\n\n def __init__(self, map_w, map_h):\n # 创建一个10*10的地图\n self.map2d = MyAStar.Map2D(map_w, map_h)\n self.open_list = [self.map2d.nodes[self.map2d.start_point.row][self.map2d.start_point.col]]\n self.close_list = []\n\n self.Item_list = []\n self.Item_count = 0\n d = NewAStar(map_w, map_h)\n\n def find_neighbours(self, node):\n w = self.map2d.width\n h = self.map2d.height\n\n for i in range(node.point.row - 1, node.point.row + 2):\n if i < 0 or i >= self.map2d.height: # 越界检测\n continue\n for j in range(node.point.col - 1, node.point.col + 2):\n if j < 0 or j >= self.map2d.width: # 越界检测\n continue\n if i == node.point.row and j == node.point.col: # 自身检测\n continue\n neighbour = self.map2d.nodes[i][j]\n if neighbour.v == self.map2d.impasse: # 去掉障碍物\n continue\n if self.is_in_close_list(neighbour): # 已经处理过了\n continue\n\n path = abs(node.point.row - neighbour.point.row) + \\\n abs(node.point.col - neighbour.point.col)\n value = 10 if path == 1 else 14\n new_g = neighbour.v * value + node.g # 更新g值\n\n if not self.is_in_open_list(neighbour): # 加入下一步考察对象\n self.open_list.append(neighbour)\n neighbour.father = node # 更新其父亲\n if neighbour.point == self.map2d.end_point: # 已经找到终点了\n return 1\n else:\n if new_g < neighbour.g: # 更小的值\n neighbour.father = node\n else:\n continue\n neighbour.g = new_g\n neighbour.f = new_g + neighbour.h # 更新h值\n # print(neighbour)\n\n if self.is_in_open_list(node):\n self.open_list.remove(node)\n self.close_list.append(node)\n # print(len(self.open_list))\n return 0\n\n def get_min_node(self):\n if not self.open_list:\n return None\n\n node = self.open_list[0]\n for each in self.open_list:\n if node.f > each.f: # 等于时怎么办?\n node = each\n return node\n\n def searching(self):\n path = []\n # 判断寻路终点是否是障碍\n # if self.map2d[self.endPoint.x][self.endPoint.y] != self.passTag:\n # return None\n # 2.主循环逻辑\n while True:\n node = self.get_min_node()\n if not node:\n print('无路可走')\n break\n if self.find_neighbours(node):\n last = self.map2d.nodes[self.map2d.end_point.row][self.map2d.end_point.col]\n while True:\n if last:\n path.append(last)\n last = last.father\n else:\n return list(reversed(path))\n return path\n\n def is_in_close_list(self, node):\n for each in self.close_list:\n if node.point == each.point:\n return True\n return False\n\n def is_in_open_list(self, node):\n for each in self.open_list:\n if node.point == each.point:\n return True\n return False\n\n\nclass D2Pane(QtWidgets.QWidget):\n def __init__(self):\n super(D2Pane, self).__init__()\n self.text = \"Лев Николаевич Толстой\\nАнна Каренина\"\n self.map_w = 5\n self.map_h = 12\n self.colors = [QtGui.QColor(211, 211, 211), QtGui.QColor(155, 155, 155),\n QtGui.QColor(85, 85, 85), QtGui.QColor(20, 20, 20)]\n\n self.flag = True\n print('-----------------------------------------')\n print('开始探路1')\n start = time.perf_counter()\n self.s = NewAStar()\n # self.s = MyAStar(self.map_w, self.map_h)\n # self.s.find_neighbours(self.map2d.nodes[0][0]\n self.path = self.s.searching()\n # self.s.deal_neighbours(49)\n # print(self.s.open_list[0], ':', self.s._get_f(self.s.open_list[0]))\n # node = self.s.get_min_node()\n end = time.perf_counter()\n print(f'用时:{end - start}')\n print('-----------------------------------------')\n\n # self.flag = False\n # print('-----------------------------------------')\n # print('开始探路2')\n # start = time.perf_counter()\n # self.s2 = MyAStar(self.map_w, self.map_h)\n # # self.s = MyAStar(self.map_w, self.map_h)\n # # self.s.find_neighbours(self.map2d.nodes[0][0]\n # self.path2 = self.s2.searching()\n # # self.s.deal_neighbours(49)\n # # print(self.s.open_list[0], ':', self.s._get_f(self.s.open_list[0]))\n # # node = self.s.get_min_node()\n # end = time.perf_counter()\n # print(f'用时:{end - start}')\n # print('-----------------------------------------')\n\n self.initUI()\n\n def initUI(self):\n # self.setGeometry(2500, 130, 1000, 800)\n self.setWindowTitle('A星算法演示')\n\n # btn = QtWidgets.QPushButton('刷新', self)\n # btn.resize(btn.sizeHint())\n # btn.move(800, 0)\n\n # btn.clicked.connect(self.clicked)\n\n self.show()\n\n def clicked(self):\n if self.flag:\n self.s = NewAStar()\n else:\n self.s = MyAStar(self.map_w, self.map_h)\n self.path = self.s.searching()\n print(self.path)\n self.update()\n\n def paintEvent(self, event):\n qp = QtGui.QPainter()\n qp.begin(self)\n # self.drawText(event, qp)\n # self.drawPoints(qp)\n # self.drawRectangles(qp)\n # self.drawLines(qp)\n # self.drawBrushes(qp)\n # self.drawBezierCurve(qp)\n self.drawMap(qp)\n # print(self.s.open_list)\n # self.drawNode(qp, self.s.open_list[0])\n # for each in self.s.open_list:\n # self.drawNode(qp, each)\n for i in range(len(self.path)):\n self.drawNode1(qp, self.path[i])\n # for i in range(len(self.path2)):\n # self.drawNode2(qp, self.path2[i])\n\n qp.end()\n\n def drawNode1(self, qp, node):\n # print(node)\n ride = 10\n rt_w = self.size().width() / self.map_w\n rt_h = self.size().height() / self.map_h\n\n qp.setBrush(QtCore.Qt.green)\n qp.drawEllipse(int(self.s.map2d[node][1] * rt_w + rt_w / 2) - ride,\n int(self.s.map2d[node][0] * rt_h + rt_h / 2) - ride, 2 * ride, 2 * ride)\n\n def drawNode2(self, qp, node):\n # print(node)\n ride = 10\n rt_w = self.size().width() / self.map_w\n rt_h = self.size().height() / self.map_h\n\n qp.setBrush(QtCore.Qt.red)\n qp.drawEllipse(int(node.point.col * rt_w + rt_w / 2) - ride,\n int(node.point.row * rt_h + rt_h / 2) - ride, 2 * ride, 2 * ride)\n\n def drawMap(self, qp):\n col = QtGui.QColor(0, 0, 0)\n col.setNamedColor('#d0d0d0')\n # pen = QPen()\n qp.setPen(col)\n\n rt_w = self.size().width() / self.map_w\n rt_h = self.size().height() / self.map_h\n\n # if self.flag:\n for i in range(self.s.map2d_size):\n y = i // self.s.map2d_w\n x = i % self.s.map2d_w\n v = self.s.map2d[i][4] - 1\n # print(f'i={i} {x,y} v={self.s.map2d[i][4]}')\n qp.setBrush(self.colors[v])\n qp.drawRect(int(rt_w * x), int(rt_h * y), int(rt_w), int(rt_h))\n # size = QtCore.QSize(int(rt_w), int(rt_h))\n # img = QtGui.QImage(self.map2d.pics[v])\n # pixImg = QtGui.QPixmap.fromImage(img.scaled(size, QtCore.Qt.IgnoreAspectRatio))\n # qp.drawPixmap(int(rt_w * x), int(rt_h * y), pixImg)\n\n # 起点 与 终点\n ride = 20\n side1 = int(rt_w / 2)\n side2 = int(rt_h / 2)\n qp.setBrush(QtCore.Qt.blue)\n qp.drawEllipse(side1 - ride, side2 - ride, 2 * ride, 2 * ride)\n\n side1 = int(rt_w * self.s.map2d[self.s.end][0] + side1)\n side2 = int(rt_h * self.s.map2d[self.s.end][1] + side2)\n qp.setBrush(QtCore.Qt.red)\n qp.drawEllipse(side1 - ride, side2 - ride, 2 * ride, 2 * ride)\n\n # else:\n # for y in range(self.map_h):\n # for x in range(self.map_w):\n # v = self.s.map2d.getValue(y, x)\n # qp.setBrush(self.colors[v])\n # qp.drawRect(int(rt_w * x), int(rt_h * y), int(rt_w), int(rt_h))\n # # size = QtCore.QSize(int(rt_w), int(rt_h))\n # # img = QtGui.QImage(self.map2d.pics[v])\n # # pixImg = QtGui.QPixmap.fromImage(img.scaled(size, QtCore.Qt.IgnoreAspectRatio))\n # # qp.drawPixmap(int(rt_w * x), int(rt_h * y), pixImg)\n # # 起点 与 终点\n # ride = 20\n # side1 = int(rt_w / 2)\n # side2 = int(rt_h / 2)\n # qp.setBrush(QtCore.Qt.blue)\n # qp.drawEllipse(side1 - ride, side2 - ride, 2 * ride, 2 * ride)\n # side1 = int(rt_w * self.s.map2d.end_point.col + side1)\n # side2 = int(rt_h * self.s.map2d.end_point.row + side2)\n # qp.setBrush(QtCore.Qt.red)\n # qp.drawEllipse(side1 - ride, side2 - ride, 2 * ride, 2 * ride)\n\n def drawText(self, event, qp):\n qp.setPen(QtGui.QColor(168, 34, 3))\n qp.setFont(QtGui.QFont('Decorative', 20))\n qp.drawText(event.rect(), QtCore.Qt.AlignCenter, self.text)\n\n def drawPoints(self, qp):\n qp.setPen(QtCore.Qt.blue)\n size = self.size()\n\n for i in range(1000):\n x = random.randint(1, size.width() - 1)\n y = random.randint(1, size.height() - 1)\n qp.drawPoint(x, y)\n\n def drawRectangles(self, qp):\n col = QtGui.QColor(0, 0, 0)\n col.setNamedColor('#d400d4')\n qp.setPen(col)\n\n qp.setBrush(QtGui.QColor(200, 0, 0))\n qp.drawRect(10, 15, 90, 60)\n\n qp.setBrush(QtGui.QColor(255, 80, 0, 160))\n qp.drawRect(130, 15, 90, 60)\n\n qp.setBrush(QtGui.QColor(25, 0, 90, 200))\n qp.drawRect(250, 15, 90, 60)\n\n def drawLines(self, qp):\n pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)\n\n qp.setPen(pen)\n qp.drawLine(20, 40, 250, 40)\n\n pen.setStyle(QtCore.Qt.DashLine)\n qp.setPen(pen)\n qp.drawLine(20, 80, 250, 80)\n\n pen.setStyle(QtCore.Qt.DashDotLine)\n qp.setPen(pen)\n qp.drawLine(20, 120, 250, 120)\n\n pen.setStyle(QtCore.Qt.DotLine)\n qp.setPen(pen)\n qp.drawLine(20, 160, 250, 160)\n\n pen.setStyle(QtCore.Qt.DashDotDotLine)\n qp.setPen(pen)\n qp.drawLine(20, 200, 250, 200)\n\n pen.setStyle(QtCore.Qt.CustomDashLine)\n pen.setDashPattern([1, 4, 5, 4])\n qp.setPen(pen)\n qp.drawLine(20, 240, 250, 240)\n\n def drawBrushes(self, qp):\n brush = QtGui.QBrush(QtCore.Qt.SolidPattern)\n qp.setBrush(brush)\n qp.drawRect(10, 15, 90, 60)\n\n brush.setStyle(QtCore.Qt.Dense1Pattern)\n qp.setBrush(brush)\n qp.drawRect(130, 15, 90, 60)\n\n brush.setStyle(QtCore.Qt.Dense2Pattern)\n qp.setBrush(brush)\n qp.drawRect(250, 15, 90, 60)\n\n brush.setStyle(QtCore.Qt.DiagCrossPattern)\n qp.setBrush(brush)\n qp.drawRect(10, 105, 90, 60)\n\n brush.setStyle(QtCore.Qt.Dense5Pattern)\n qp.setBrush(brush)\n qp.drawRect(130, 105, 90, 60)\n\n brush.setStyle(QtCore.Qt.Dense6Pattern)\n qp.setBrush(brush)\n qp.drawRect(250, 105, 90, 60)\n\n brush.setStyle(QtCore.Qt.HorPattern)\n qp.setBrush(brush)\n qp.drawRect(10, 195, 90, 60)\n\n brush.setStyle(QtCore.Qt.VerPattern)\n qp.setBrush(brush)\n qp.drawRect(130, 195, 90, 60)\n\n brush.setStyle(QtCore.Qt.BDiagPattern)\n qp.setBrush(brush)\n qp.drawRect(250, 195, 90, 60)\n\n def drawBezierCurve(self, qp):\n \"\"\"贝塞尔曲线\"\"\"\n path = QtGui.QPainterPath()\n path.moveTo(30, 30)\n path.cubicTo(30, 30, 200, 350, 350, 130)\n path.cubicTo(350, 130, 260, 450, 250, 30)\n\n qp.drawPath(path)\n\n\nclass MainWindow(QtWidgets.QWidget):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.wg = D2Pane()\n self.setGeometry(200, 40, 1200, 1000)\n self.setupUI()\n\n def setupUI(self):\n vl_main = QtWidgets.QVBoxLayout()\n # self.wg = ShowTree()\n\n btn = QtWidgets.QPushButton('刷新')\n btn.clicked.connect(self.wg.clicked)\n\n vl_main.addWidget(btn)\n vl_main.addWidget(self.wg)\n self.setLayout(vl_main)\n\n # def resizeEvent(self, event):\n # palette = QtGui.QPalette()\n # pix = QtGui.QPixmap('res/background/bk4.jpg')\n # pix = pix.scaled(self.width(), self.height())\n # palette.setBrush(QtGui.QPalette.Background, QtGui.QBrush(pix))\n # self.setPalette(palette)\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n win = MainWindow()\n win.show()\n sys.exit(app.exec_())\n\n # dd = []\n # for each in dd:\n # print('dd')\n","sub_path":"aStart.py","file_name":"aStart.py","file_ext":"py","file_size_in_byte":37484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73413928","text":"from django.test import TestCase\nfrom django.test import Client\nfrom django.core import mail\nfrom django.conf import settings\nfrom django.core import mail\n\nfrom .models import Suggestion, Reply\n\n# Create your tests here.\n\nclass HomeTestCase(TestCase):\n \"\"\"This class defines a set of tests for the Home app.\"\"\"\n\n def setUp(self):\n self.client = Client()\n\n def test_post_suggestion(self):\n \"\"\" Posting a new Suggestion. \"\"\"\n response = self.client.post('/add/', \n {\n 'name': 'Bruno Mendes', \n 'email': 'brunomendes81@gmail.com',\n 'text': 'Dummy Suggestion'\n }\n )\n self.assertEqual(response.status_code, 302)\n\n def test_login_admin(self):\n \"\"\" Login to admin. \"\"\"\n response = self.client.post('/admin/', \n {\n 'username': 'admin', \n 'password': 'tonicapp',\n }\n )\n self.assertEqual(response.status_code, 302)\n\n def test_send_email(self):\n subject = \"New Suggestion\"\n email_message = \"Dummy Suggestion\"\n user_email = \"dummyemail@gmail.com\"\n mail.send_mail(\n subject, \n email_message, \n user_email, \n settings.ADMINS,\n fail_silently=False,\n )\n\n # Test that one message has been sent.\n self.assertEqual(len(mail.outbox), 1)\n\n # Test that subject is correct.\n self.assertEqual(mail.outbox[0].subject, 'subject')\n\n","sub_path":"home/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338104361","text":"import asyncio\nimport time\nfrom flask import Flask, request, redirect, url_for\nfrom flask_cors import CORS\nimport pickle\nfrom sqlalchemy import and_\n\nimport database\nfrom Bank import Bank\nfrom ClientFactory import ClientFactory\nfrom Manager import Manager\nfrom SendPaymentReminder import SendPaymentReminder\n\nfrom threading import Thread\nfrom flask import Flask, jsonify\n\n\napp = Flask(__name__)\nCORS(app)\n\nbank = Bank()\nclient_factory = ClientFactory(bank)\nthread = None\n\nsend_payment_reminder = SendPaymentReminder(bank)\nmanager: Manager = Manager.instance()\nmanager.set_command(send_payment_reminder)\n\n\n# async def threaded_task() -> None:\n# print(\"Starting bank manager command...\")\n# duration = 10\n# global manager\n# for i in range(duration):\n# print(\"Working... {}/{}\".format(i + 1, duration))\n# await manager.command.execute()\n# await asyncio.sleep(1)\n\n\n@app.route('/', methods=['POST', 'GET'])\nasync def index():\n return redirect(\"http://localhost:3000/\")\n\n\n@app.route('/manager')\nasync def manager():\n manager_l = Manager.instance()\n await database.connect_db()\n await manager_l.command.execute()\n await database.disconnect_db()\n return {\"message\": \"idk\"}\n\n\n@app.route('/register', methods=['POST', 'GET'])\nasync def register():\n if request.method == 'POST':\n name = request.form['name']\n username = request.form['username']\n password = request.form['password']\n await database.connect_db()\n client = await client_factory.create_client(name, username, password)\n bank.add_client(client)\n await database.disconnect_db()\n return redirect(\"http://localhost:3000/login\")\n if request.method == 'GET':\n return redirect(\"http://localhost:3000/register\")\n\n\n@app.route('/login', methods=['POST', 'GET'])\nasync def login():\n if request.method == 'POST':\n # TODO: login logic\n username = request.json['username']\n password = request.json['password']\n await database.connect_db()\n from models.ClientModel import ClientModel\n client = await ClientModel.query.where(and_(ClientModel.username == username,\n ClientModel.password == password)).gino.first()\n await database.disconnect_db()\n if client:\n return {'message': 'Successfully logged in!', 'logged_in': True, 'client_id': client.bank_id}\n else:\n return {'message': 'Unsuccessful log in!', 'logged_in': False, 'client_id': None}\n if request.method == 'GET':\n return redirect(\"http://localhost:3000/login\")\n\n\n@app.route('/loanform', methods=['POST'])\nasync def loan_form():\n gender = int(request.json['gender'])\n married = int(request.json['married'])\n self_employed = int(request.json['selfEmployed'])\n education = int(request.json['education'])\n credit_history = int(request.json['creditHistory'])\n property_area = int(request.json['propertyArea'])\n\n client_id = int(request.json['clientId'])\n\n await database.connect_db()\n from database import db_loan_prediction as db\n from models.ClientModel import ClientModel\n client = await ClientModel.query.where(ClientModel.bank_id == client_id).gino.first()\n from LoanFormFactory import LoanFormFactory\n\n from Predictor import Predictor\n prediction = Predictor.predict([[gender, married, self_employed, education, credit_history, property_area]])\n message = \"\"\n if prediction == 0:\n print(\"Loan rejected\")\n message = \"Loan rejected\"\n else:\n print(\"Loan approved\")\n message = \"Loan approved\"\n\n loan_term = 0 if (prediction == 0) else int(request.json['loanTerm'])\n print(loan_term)\n\n client_current = None\n for cl in bank.client_list:\n if cl.bank_id == client.bank_id:\n client_current = cl\n break\n\n await LoanFormFactory.create_loan_form(gender, married, self_employed, education, credit_history, property_area,\n int(request.json['loanAmount']), loan_term, client_current)\n await database.disconnect_db()\n return {'message': message}\n\n\n@app.route('/clientstatus', methods=['POST'])\nasync def clientstatus():\n await database.connect_db()\n from models.ClientModel import ClientModel\n from models.LoanFormModel import LoanFormModel\n from models.TransactionModel import TransactionModel\n # client = await ClientModel.query.where(ClientModel.bank_id == 3659022).gino.first()\n print(\"\\n\\n\")\n print(request.json)\n print(\"\\n\\n\")\n client = await ClientModel.query.where(ClientModel.bank_id == int(request.json['clientId'])).gino.first()\n loan_details = None\n if client:\n loan_details = await LoanFormModel.query.where(LoanFormModel.loan_id == client.loan_id).gino.first()\n client_dict = {\n 'name': client.name,\n 'bank_id': client.bank_id,\n 'loan_id': client.loan_id\n }\n else:\n print(\"No client\")\n transactions = None\n if loan_details:\n transactions = await TransactionModel.query.where(TransactionModel.client_id == client.bank_id).gino.all()\n else:\n print(\"No loan details\")\n return {'message': 'Loan not applied', 'client_data':\n {'client': client_dict, 'loan_details': None, 'transactions': None}}\n await database.disconnect_db()\n\n loan_details = {\n 'loan_amount': loan_details.loan_amount,\n 'loan_term_months': loan_details.loan_term_months,\n 'loan_amount_remaining': loan_details.loan_amount_remaining\n }\n\n if loan_details['loan_term_months'] == 0:\n return {'message': 'Loan rejected', 'client_data':\n {'client': client_dict, 'loan_details': loan_details, 'transactions': None}}\n\n transaction_json = dict()\n index = 0\n for trans in transactions:\n transaction_json[index] = {\n 'transaction_id': trans.transaction_id,\n 'client_id': trans.client_id,\n 'amount_paid': trans.amount_paid\n }\n index += 1\n\n client_data = {'client': client_dict, 'loan_details': loan_details, 'transactions': transaction_json}\n\n print(client_data)\n\n print(\"**********************\\n\\n\\n\")\n return {'message': 'Success', 'client_data': client_data}\n\n\n# TODO: Need this in a thread to run periodically\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=81)\n\n","sub_path":"Project7/LoanPrediction/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"111497936","text":"class UF:\n def __init__(self,strlist):\n n=len(strlist)\n self.parent={i:i for i in range(n)}\n self.count=n\n\n def find(self,x):\n if self.parent[x]==x:\n return x\n else:\n self.parent[x]=self.find(self.parent[x])\n return self.parent[x]\n\n def union(self,x,y):\n if self.find(x)==self.find(y):\n return\n else:\n self.parent[self.find(x)]=self.find(y)\n self.count-=1\n\nstrs = [\"tars\",\"rats\",\"arts\",\"star\"]\nn=len(strs)\nm=len(strs[0])\nuf=UF(strs)\nfor i in range(n-1):\n for j in range(i+1,n):\n count=0\n for k in range(m):\n if strs[i][k]!=strs[j][k]:\n count+=1\n if count>2:\n break\n if count==2 or count==0:\n uf.union(i,j)\nprint(uf.count)\n","sub_path":"839.py","file_name":"839.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"611046597","text":"from maintain_frontend import main\nfrom flask_testing import TestCase\nfrom unit_tests.utilities import Utilities\nfrom flask import url_for\nfrom unittest.mock import patch\nfrom maintain_frontend.constants.permissions import Permissions\nfrom maintain_frontend.dependencies.session_api.session import Session\nfrom maintain_frontend.models import LightObstructionNoticeItem\n\nTEMPLATE = 'applicant_info.html'\n\nADD_LON = 'add_lon.'\nGET_APPLICANT_INFO = ADD_LON + 'get_applicant_info'\nPOST_APPLICANT_INFO = ADD_LON + 'post_applicant_info'\nGET_DOMINANT_BUILDING = ADD_LON + 'get_dominant_building_info'\n\nNO_VALIDATION_ERRORS = []\nERROR_MESSAGE = ['some error message']\n\nINVALID_STRING = \"\"\nVALID_STRING = \"string\"\nVALID_POSTCODE = \"EX4 7AN\"\n\n\nclass TestLONApplicantInfo(TestCase):\n def create_app(self):\n main.app.testing = True\n Utilities.mock_session_cookie_flask_test(self)\n return main.app\n\n def setUp(self):\n main.app.config['Testing'] = True\n main.app.config['WTF_CSRF_ENABLED'] = False\n\n def test_applicant_info_redirects_to_new_when_state_none(self):\n self.client.set_cookie('localhost', Session.session_cookie_name,\n 'cookie_value')\n\n self.mock_session.return_value.add_lon_charge_state = None\n self.mock_session.return_value.user.permissions = [Permissions.add_lon]\n\n response = self.client.get(url_for(GET_APPLICANT_INFO))\n\n self.assert_status(response, 302)\n self.assertRedirects(response, url_for(ADD_LON + 'new'))\n\n def test_applicant_info_get(self):\n self.client.set_cookie('localhost', Session.session_cookie_name, 'cookie_value')\n\n state = LightObstructionNoticeItem()\n self.mock_session.add_lon_charge_state = state\n self.mock_session.return_value.user.permissions = [Permissions.add_lon]\n\n response = self.client.get(url_for(GET_APPLICANT_INFO))\n\n self.assert_status(response, 200)\n self.assert_template_used(TEMPLATE)\n\n def test_applicant_info_no_permission_redirects(self):\n self.client.set_cookie('localhost', Session.session_cookie_name, 'cookie_value')\n\n self.mock_session.return_value.user.permissions = []\n\n response = self.client.get(url_for(GET_APPLICANT_INFO))\n self.assertStatus(response, 302)\n self.assertRedirects(response, '/not-authorised')\n\n response = self.client.post(url_for(POST_APPLICANT_INFO))\n self.assertStatus(response, 302)\n self.assertRedirects(response, '/not-authorised')\n\n @patch('maintain_frontend.add_lon.applicant_info.AddressConverter')\n @patch('maintain_frontend.add_lon.applicant_info.ReviewRouter')\n @patch('maintain_frontend.add_lon.applicant_info.ApplicantInfoValidator')\n def test_post_with_no_validation_errors(self, mock_validator, mock_review_router, mock_address_converter):\n self.client.set_cookie('localhost', Session.session_cookie_name, 'cookie_value')\n self.mock_session.return_value.user.permissions = [Permissions.add_lon]\n mock_review_router.get_redirect_url.return_value = url_for(GET_DOMINANT_BUILDING)\n\n mock_validator.validate.return_value.errors = NO_VALIDATION_ERRORS\n\n mock_address_converter.condense_address.return_value = {'address_line_1': VALID_STRING}\n\n data = {\n 'applicant_name': VALID_STRING,\n 'postcode': VALID_POSTCODE,\n 'address_line_1': VALID_STRING,\n 'address_line_2': VALID_STRING,\n 'address_line_3': VALID_STRING,\n 'address_line_4': VALID_STRING,\n 'address_line_5': VALID_STRING,\n 'address_line_6': VALID_STRING,\n 'country': VALID_STRING\n }\n\n response = self.client.post(url_for(POST_APPLICANT_INFO), data=data)\n\n self.assert_status(response, 302)\n self.assertRedirects(response, url_for(GET_DOMINANT_BUILDING))\n\n @patch('maintain_frontend.add_lon.applicant_info.ApplicantInfoValidator')\n def test_post_with_validation_errors(self, mock_validator):\n self.client.set_cookie('localhost', Session.session_cookie_name, 'cookie_value')\n self.mock_session.return_value.user.permissions = [Permissions.add_lon]\n\n name_error = {'applicant_name': ERROR_MESSAGE}\n mock_validator.validate.return_value.errors = name_error\n\n data = {\n }\n\n response = self.client.post(url_for(POST_APPLICANT_INFO), data=data)\n\n self.assert_context('validation_errors', name_error)\n self.assert_status(response, 400)\n self.assert_template_used(TEMPLATE)\n","sub_path":"unit_tests/add_lon/test_add_lon_applicant_info.py","file_name":"test_add_lon_applicant_info.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281132157","text":"elementPrefixDict = {\n 'CACHE': 'CACHE',\n 'ANIM': 'CACHE',\n 'MODEL': 'CACHE',\n\n 'CAM': 'CAM',\n 'CAMERA': 'CAM',\n\n 'LGTR': 'LGTR',\n 'LIGHTRIG': 'LGTR',\n\n 'LOOK': 'LOOK',\n 'LOOKFILE': 'LOOKFILE',\n\n 'UTIL': 'UTIL',\n 'UTILITY': 'UTIL'\n}\n\nelementTypeList = ['CAM','CACHE','LGTR', 'LOOK', 'UTIL']\n\nmayaFileTypes = {\n 'abc': 'Alembic',\n 'ma': 'mayaAscii',\n 'mb': 'mayaBinary',\n 'fbx': 'FBX'\n}","sub_path":"pureroot/plugins/maya/api/defines.py","file_name":"defines.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"522882728","text":"from django.test import TestCase\nfrom content.models import Content\nfrom users.models import CustomUser\n\n\nclass ContentTestCase(TestCase):\n def setUp(self) -> None:\n CustomUser.objects.create(username=\"ryan\",)\n\n Content.objects.create(\n title=\"Home Page\",\n page_content=\"

Home Page

This is the home page!

\",\n author=CustomUser.objects.get(username=\"ryan\"),\n slug=\"Home\",\n )\n\n def test_string_representation(self):\n page = Content.objects.get(title=\"Home Page\")\n self.assertEqual(str(page), \"Home Page\")\n\n def test_object_properties(self):\n page = Content.objects.get(title=\"Home Page\")\n self.assertEqual(page.title, \"Home Page\")\n self.assertEqual(\n page.page_content, \"

Home Page

This is the home page!

\"\n )\n self.assertEqual(page.author.username, \"ryan\")\n self.assertEqual(page.slug, \"Home\")\n self.assertTrue(isinstance(page, Content))\n","sub_path":"content/tests/tests_models.py","file_name":"tests_models.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"630441024","text":"\"\"\"\n This endpoint is to redirect requests from Slack into our isolated Tracebacks VPC.\n\"\"\"\nfrom urllib.parse import parse_qs\nimport os\nimport traceback\n\nimport requests\n\nfrom chalice import Chalice\n\n\n\napp = Chalice(app_name='lambda-traceback-slack-proxy')\n\nAPP_SERVER_URL = os.getenv('APP_SERVER_URL')\nAPP_CALLBACK_URL = '{}/slack-callback'.format(APP_SERVER_URL)\n\n\n@app.route(\n '/slack-callback',\n methods=['POST'],\n content_types=['application/x-www-form-urlencoded'],\n cors=True\n)\ndef slack_callback():\n \"\"\" redirect post requests from slack to our app server\"\"\"\n print('starting lambda')\n\n try:\n # parse the request\n request = app.current_request\n print('received request: %s' % request)\n data = parse_qs(app.current_request.raw_body)\n print('payload: %s' % data)\n\n # forward request to tracebacks server\n r = requests.post(APP_CALLBACK_URL, data=data)\n print('response from app server: %s' % r)\n r.raise_for_status()\n return r.json()\n except Exception:\n traceback.print_exc()\n raise\n\n\n# just for debugging\n@app.route('/')\ndef index():\n return {'hello': 'world'}\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"142229240","text":"class MultiFrameDecoder:\n \"\"\"BETA class for handling transport protocol data. For each response ID, identify\n sequences of subsequent frames and combine the relevant parts of the data payloads\n into a single payload with the response ID as the ID. The original raw dataframe is\n then cleansed of the original response ID sequence frames. Instead, the new concatenated\n frames are inserted. Further, the class supports DBC decoding of the resulting modified raw data\n\n :param df_raw: dataframe of raw CAN data from the mdf_iter module\n :param res_id_list_hex: list of transport protocol 'response CAN IDs' to process\n :param SINGLE_FRAME_MASK: mask used in matching single frames\n :param FIRST_FRAME_MASK: mask used in matching first frames\n :param CONSEQ_FRAME_MASK: mask used in matching consequtive frames\n :param SINGLE_FRAME: frame type reflecting a single frame response\n :param FIRST_FRAME: frame type reflecting the first frame in a multi frame response\n :param CONSEQ_FRAME: frame type reflecting a consequtive frame in a multi frame response\n :param first_frame_payload_start: the combined payload will start at this byte in the FIRST_FRAME\n :param bam_id_hex: used in e.g. J1939, this marks the initial BAM message ID in HEX\n \"\"\"\n\n def __init__(self, df_raw, res_id_list_hex):\n self.df_raw = df_raw\n self.res_id_list_hex = res_id_list_hex\n self.res_id_list = [int(res_id, 16) for res_id in self.res_id_list_hex]\n\n return\n\n def construct_new_tp_frame(self, base_frame, payload_concatenated, can_id):\n new_frame = base_frame\n new_frame.at[\"DataBytes\"] = payload_concatenated\n new_frame.at[\"DLC\"] = 0\n new_frame.at[\"DataLength\"] = len(payload_concatenated)\n\n if can_id:\n new_frame.at[\"ID\"] = can_id\n\n return new_frame\n\n def combine_tp_frames(\n self,\n SINGLE_FRAME_MASK,\n FIRST_FRAME_MASK,\n CONSEQ_FRAME_MASK,\n SINGLE_FRAME,\n FIRST_FRAME,\n CONSEQ_FRAME,\n first_frame_payload_start,\n conseq_frame_payload_start,\n tp_type=\"\",\n bam_id_hex=\"\",\n ):\n import pandas as pd\n import sys\n\n df_raw_combined = pd.DataFrame()\n\n df_raw_excl_tp = self.df_raw[~self.df_raw[\"ID\"].isin(self.res_id_list)]\n df_raw_combined = df_raw_excl_tp\n\n for channel, df_raw_channel in self.df_raw.groupby(\"BusChannel\"):\n for res_id in self.res_id_list:\n # filter raw data for response ID and extract a 'base frame'\n if bam_id_hex == \"\":\n bam_id = 0\n else:\n bam_id = int(bam_id_hex, 16)\n\n df_raw_filter = df_raw_channel[df_raw_channel[\"ID\"].isin([res_id, bam_id])]\n\n if df_raw_filter.empty:\n continue\n\n base_frame = df_raw_filter.iloc[0]\n\n frame_list = []\n frame_timestamp_list = []\n payload_concatenated = []\n ff_length = 0xFFF\n can_id = None\n conseq_frame_prev = None\n\n # iterate through rows in filtered dataframe\n for index, row in df_raw_filter.iterrows():\n payload = row[\"DataBytes\"]\n first_byte = payload[0]\n row_id = row[\"ID\"]\n\n # if single frame, save frame directly (excl. 1st byte)\n if first_byte & SINGLE_FRAME_MASK == SINGLE_FRAME:\n new_frame = self.construct_new_tp_frame(base_frame, payload, row_id)\n frame_list.append(new_frame.values.tolist())\n frame_timestamp_list.append(index)\n\n # if first frame, save info from prior multi frame response sequence,\n # then initialize a new sequence incl. the first frame payload\n elif ((first_byte & FIRST_FRAME_MASK == FIRST_FRAME) & (bam_id_hex == \"\")) or (bam_id == row_id):\n # create a new frame using information from previous iterations\n if len(payload_concatenated) >= ff_length:\n new_frame = self.construct_new_tp_frame(base_frame, payload_concatenated, can_id)\n\n frame_list.append(new_frame.values.tolist())\n frame_timestamp_list.append(frame_timestamp)\n\n # reset and start on next frame\n payload_concatenated = []\n conseq_frame_prev = None\n frame_timestamp = index\n\n # for J1939 BAM, extract PGN and convert to 29 bit CAN ID for use in baseframe\n if bam_id_hex != \"\":\n pgn_hex = \"\".join(\"{:02x}\".format(x) for x in reversed(payload[5:8]))\n pgn = int(pgn_hex, 16)\n can_id = (6 << 26) | (pgn << 8) | 254\n\n if tp_type == \"uds\":\n ff_length = (payload[0] & 0x0F) << 8 | payload[1]\n\n for byte in payload[first_frame_payload_start:]:\n payload_concatenated.append(byte)\n\n # if consequtive frame, extend payload with payload excl. 1st byte\n elif first_byte & CONSEQ_FRAME_MASK == CONSEQ_FRAME:\n if (conseq_frame_prev == None) or ((first_byte - conseq_frame_prev) == 1):\n conseq_frame_prev = first_byte\n for byte in payload[conseq_frame_payload_start:]:\n payload_concatenated.append(byte)\n\n df_raw_tp = pd.DataFrame(frame_list, columns=base_frame.index, index=frame_timestamp_list)\n df_raw_combined = df_raw_combined.append(df_raw_tp)\n\n df_raw_combined.index.name = \"TimeStamp\"\n df_raw_combined = df_raw_combined.sort_index()\n\n return df_raw_combined\n\n def decode_tp_data(self, df_raw_combined, df_decoder):\n import pandas as pd\n\n df_phys_list = []\n\n # to process data with variable payload lengths for the same ID\n # it needs to be processed group-by-group based on the data length:\n if df_raw_combined.empty:\n return df_raw_combined\n else:\n df_grouped = df_raw_combined.groupby(\"DataLength\")\n df_phys = pd.DataFrame()\n for length, group in df_grouped:\n df_phys_group = df_decoder.decode_frame(group)\n df_phys = df_phys.append(df_phys_group)\n\n df_phys = df_phys.sort_index()\n return df_phys\n\n def combine_tp_frames_by_type(self, tp_type):\n conseq_frame_payload_start = 1\n bam_id_hex = \"\"\n\n if tp_type == \"uds\":\n SINGLE_FRAME_MASK = 0xF0\n FIRST_FRAME_MASK = 0xF0\n CONSEQ_FRAME_MASK = 0xF0\n SINGLE_FRAME = 0x00\n FIRST_FRAME = 0x10\n CONSEQ_FRAME = 0x20\n first_frame_payload_start = 2\n\n if tp_type == \"j1939\":\n SINGLE_FRAME_MASK = 0xFF\n FIRST_FRAME_MASK = 0xFF\n CONSEQ_FRAME_MASK = 0x00\n SINGLE_FRAME = 0xFF\n FIRST_FRAME = 0x20\n CONSEQ_FRAME = 0x00\n first_frame_payload_start = 8\n bam_id_hex = \"0x1CECFF00\"\n\n if tp_type == \"nmea\":\n SINGLE_FRAME_MASK = 0xFF\n FIRST_FRAME_MASK = 0x0F\n CONSEQ_FRAME_MASK = 0x00\n SINGLE_FRAME = 0xFF\n FIRST_FRAME = 0x00\n CONSEQ_FRAME = 0x00\n first_frame_payload_start = 0\n\n return self.combine_tp_frames(\n SINGLE_FRAME_MASK,\n FIRST_FRAME_MASK,\n CONSEQ_FRAME_MASK,\n SINGLE_FRAME,\n FIRST_FRAME,\n CONSEQ_FRAME,\n first_frame_payload_start,\n conseq_frame_payload_start,\n tp_type,\n bam_id_hex,\n )\n","sub_path":"examples/data-processing/utils_tp.py","file_name":"utils_tp.py","file_ext":"py","file_size_in_byte":8220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"445637526","text":"def merge_iter(lst1, lst2):\n \"\"\"Merges two sorted lists recursively.\n\n >>> merge_iter([1, 3, 5], [2, 4, 6])\n [1, 2, 3, 4, 5, 6]\n >>> merge_iter([], [2, 4, 6])\n [2, 4, 6]\n >>> merge_iter([1, 2, 3], [])\n [1, 2, 3]\n >>> merge_iter([5, 7], [2, 4, 6])\n [2, 4, 5, 6, 7]\n \"\"\"\n new = []\n while lst1 and lst2:\n if lst1[0] < lst2[0]:\n new += [lst1[0]]\n lst1 = lst1[1:]\n else:\n new += [lst2[0]]\n lst2 = lst2[1:]\n if lst1:\n return new + lst1\n else:\n return new + lst2\n\ndef merge_recur(lst1, lst2):\n \"\"\"Merges two sorted lists recursively.\n\n >>> merge_recur([1, 3, 5], [2, 4, 6])\n [1, 2, 3, 4, 5, 6]\n >>> merge_recur([], [2, 4, 6])\n [2, 4, 6]\n >>> merge_recur([1, 2, 3], [])\n [1, 2, 3]\n >>> merge_recur([5, 7], [2, 4, 6])\n [2, 4, 5, 6, 7]\n \"\"\"\n if not lst1:\n return lst2\n if not lst2:\n return lst1\n if lst1[0] > lst2[0]:\n return [lst2[0]] + merge_recur(lst1, lst2[1:])\n else:\n return [lst1[0]] + merge_recur(lst1[1:], lst2)","sub_path":"3_Data_structures/list/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"153636956","text":"from django.core.exceptions import ValidationError\nfrom rest_framework import serializers\n\nfrom talentmap_api.common.common_helpers import resolve_path_to_view, validate_filters_exist, serialize_instance\nfrom talentmap_api.bidding.serializers.serializers import UserBidStatisticsSerializer\nfrom talentmap_api.common.serializers import PrefetchedSerializer, StaticRepresentationField\nfrom talentmap_api.language.serializers import LanguageQualificationSerializer\nfrom talentmap_api.position.serializers import PositionSerializer, SkillSerializer\nfrom talentmap_api.messaging.serializers import SharableSerializer\n\nfrom django.contrib.auth.models import User\nfrom talentmap_api.user_profile.models import UserProfile, SavedSearch\n\n\nclass UserSerializer(PrefetchedSerializer):\n class Meta:\n model = User\n fields = [\"username\", \"email\", \"first_name\", \"last_name\"]\n\n\nclass UserProfileShortSerializer(PrefetchedSerializer):\n is_cdo = serializers.ReadOnlyField()\n username = serializers.CharField(source=\"user.username\")\n first_name = serializers.CharField(source=\"user.first_name\")\n last_name = serializers.CharField(source=\"user.last_name\")\n email = serializers.CharField(source=\"user.email\")\n\n class Meta:\n model = UserProfile\n fields = [\"username\", \"first_name\", \"last_name\", \"email\", \"phone_number\", \"is_cdo\"]\n\n\nclass ClientSerializer(PrefetchedSerializer):\n current_assignment = serializers.SerializerMethodField()\n grade = StaticRepresentationField(read_only=True)\n is_cdo = serializers.ReadOnlyField()\n primary_nationality = StaticRepresentationField(read_only=True)\n secondary_nationality = StaticRepresentationField(read_only=True)\n\n def get_current_assignment(self, obj):\n if obj.assignments.count() > 0:\n return str(obj.assignments.latest('start_date'))\n else:\n return None\n\n class Meta:\n model = UserProfile\n fields = [\"id\", \"current_assignment\", \"skills\", \"grade\", \"is_cdo\", \"primary_nationality\", \"secondary_nationality\", \"bid_statistics\", \"user\", \"language_qualifications\"]\n nested = {\n \"user\": {\n \"class\": UserSerializer,\n \"kwargs\": {\n \"read_only\": True\n }\n },\n \"language_qualifications\": {\n \"class\": LanguageQualificationSerializer,\n \"kwargs\": {\n \"override_fields\": [\n \"id\",\n \"representation\"\n ],\n \"many\": True,\n \"read_only\": True,\n }\n },\n \"bid_statistics\": {\n \"class\": UserBidStatisticsSerializer,\n \"kwargs\": {\n \"many\": True,\n \"read_only\": True\n }\n },\n \"skills\": {\n \"class\": SkillSerializer,\n \"kwargs\": {\n \"many\": True,\n \"read_only\": True\n }\n }\n }\n\n\nclass ClientDetailSerializer(ClientSerializer):\n\n def get_current_assignment(self, obj):\n if obj.assignments.count() > 0:\n return serialize_instance(obj.assignments.latest('start_date'), \"talentmap_api.position.serializers.AssignmentSerializer\")\n else:\n return None\n\n\nclass UserProfileSerializer(PrefetchedSerializer):\n current_assignment = serializers.SerializerMethodField()\n skills = StaticRepresentationField(read_only=True, many=True)\n grade = StaticRepresentationField(read_only=True)\n cdo = StaticRepresentationField(read_only=True)\n is_cdo = serializers.ReadOnlyField()\n primary_nationality = StaticRepresentationField(read_only=True)\n secondary_nationality = StaticRepresentationField(read_only=True)\n\n def get_current_assignment(self, obj):\n if obj.assignments.count() > 0:\n return str(obj.assignments.latest('start_date'))\n else:\n return None\n\n class Meta:\n model = UserProfile\n fields = \"__all__\"\n nested = {\n \"user\": {\n \"class\": UserSerializer,\n \"kwargs\": {\n \"read_only\": True\n }\n },\n \"cdo\": {\n \"class\": UserProfileShortSerializer,\n \"kwargs\": {\n \"read_only\": True\n }\n },\n \"language_qualifications\": {\n \"class\": LanguageQualificationSerializer,\n \"kwargs\": {\n \"override_fields\": [\n \"id\",\n \"representation\"\n ],\n \"many\": True,\n \"read_only\": True,\n }\n },\n \"favorite_positions\": {\n \"class\": PositionSerializer,\n \"kwargs\": {\n \"override_fields\": [\n \"id\",\n \"representation\"\n ],\n \"many\": True,\n \"read_only\": True\n }\n },\n \"received_shares\": {\n \"class\": SharableSerializer,\n \"kwargs\": {\n \"many\": True,\n \"read_only\": True\n }\n },\n \"skills\": {\n \"class\": SkillSerializer,\n \"kwargs\": {\n \"many\": True,\n \"read_only\": True\n }\n }\n }\n\n\nclass UserProfileWritableSerializer(PrefetchedSerializer):\n\n class Meta:\n model = UserProfile\n fields = [\"language_qualifications\", \"favorite_positions\", \"primary_nationality\", \"secondary_nationality\", \"date_of_birth\", \"phone_number\"]\n writable_fields = (\"language_qualifications\", \"favorite_positions\", \"primary_nationality\", \"secondary_nationality\", \"date_of_birth\", \"phone_number\")\n\n\nclass SavedSearchSerializer(PrefetchedSerializer):\n owner = serializers.StringRelatedField(read_only=True)\n\n def validate(self, data):\n # We'll need the endpoint to validate our filters, so determine if our\n # datasource is an instance or a fresh object (in which case we use initial data)\n datasource = self.initial_data\n if self.instance:\n datasource = self.instance.__dict__\n\n # The endpoint to test our filters against is either the one stored, or the incoming endpoint\n endpoint = data.get(\"endpoint\", datasource.get(\"endpoint\"))\n # Likewise for the filters\n filters = data.get(\"filters\", datasource.get(\"filters\"))\n\n # Get our viewset using the endpoint\n try:\n view = resolve_path_to_view(endpoint)\n except:\n view = None\n finally:\n if not view:\n # Raise a validation error if the endpoint isn't good\n raise ValidationError(f\"Endpoint {endpoint} is not a valid API path\")\n\n # Get our list of filters, and verify that the specified filters are valid\n if hasattr(view, \"filter_class\"):\n validate_filters_exist(filters, view.filter_class)\n else:\n raise ValidationError(\"Specified endpoint does not support filters\")\n\n return data\n\n class Meta:\n model = SavedSearch\n fields = \"__all__\"\n writable_fields = (\"name\", \"endpoint\", \"filters\",)\n","sub_path":"talentmap_api/user_profile/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":7486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"585956120","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\"\"\"\n File Name : 13-urllib.py\n Author: Ginakira\n Mail: ginakira@outlook.com\n Github: https://github.com/Ginakira\n Created Time: 2020/07/17 11:10:47\n\"\"\"\n\n# urllib的使用\n\nimport urllib.request\n\n# 向一个指定的URL发送请求 获取响应\nresponse = urllib.request.urlopen(\"http://www.haizeix.com\")\n\n# 获取响应内容\ncontent = response.read().decode('utf-8')\nfo = open('./haizei.html', 'w', encoding='utf-8')\nprint(content, file=fo)\nfo.close()\n\n# 响应头信息\nprint(response.headers)\n\n# 状态码\nprint(response.status)\n","sub_path":"HZOJ/Python/13-urllib.py","file_name":"13-urllib.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"17713331","text":"from modeller import *\nfrom modeller.automodel import *\n\nimport sys\n\nlog.none()\nlog.level(output=0, notes=0, warnings=0, errors=0, memory=0) \n\nprot = sys.argv[1]\nprot_file = sys.argv[2]\nenv = environ()\naln = alignment(env)\nenv.io.hetatm = True\nmdl = model(env, file=prot)\n\na = automodel(env, alnfile='all_aligne.pir',\n knowns='cut', sequence='ori',\n assess_methods=assess.GA341\n )\n \n #assess_methods=(assess.DOPE, assess.GA341))\na.starting_model = 1\na.ending_model = 1\na.final_malign3d = True\n\n\n\n\n#a.very_fast()\na.make()\n\n","sub_path":"script/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513653097","text":"\"\"\"\nsee if the file list is passed to the script\n\"\"\"\n\nimport os, argparse\nimport csv\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--file-list', help='list of files to process')\n\n#parser.add_argument('--file-folder', help='folder containing files')\n\nargs = parser.parse_args()\n\n# ----------------------------------------------------------------------------\n\n# read csv file list\ndef read_file(filename):\n file_list = []\n\n csv_temp = open(filename)\n \n csv_file = csv.reader(csv_temp, delimiter=',')\n \n for i in csv_file:\n #file_list.append(os.path.join(filename, i))\n file_list.append(i[0])\n\n return file_list\n\n# read list of files from dir\ndef read_dir(foldername):\n return os.listdir(foldername)\n\n# check if the argument passed is file or folder\nif os.path.isfile(args.file_list) == True:\n file_list = read_file(args.file_list)\nelse:\n file_list = read_dir(args.file_list)\n\ndef add_data(inputfiles):\n # Make a list of all files to be processed\n \n for obj in inputfiles:\n print(obj)\n\n# call add_data function\nadd_data(file_list)\n\n","sub_path":"argparse_file_list.py","file_name":"argparse_file_list.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"495452306","text":"#coding: utf-8\n\nimport urllib2\nimport re\nimport pymysql\nimport sys\nfrom HTMLParser import HTMLParser\nimport sqlConnect\nfrom sqlConnect import sqlConnect\nimport traceback\n\nsrcprefix = \"http://www.news.zju.edu.cn\"\nimgSrcPreFix = \"http://www.news.zju.edu.cn\"\n\nallImgUrl = []\navai = []\ntagMap = {'h1' : True, 'h2' : True, 'h3' : True, 'h4' : True, 'h5' : True, 'h6' : True, 'p' : True}\n\nclass myHTMLParser(HTMLParser) :\n\tmyStr = \"\"\n\tmyTitle = \"\"\n\tmyUrl = \"\"\n\tmyImgUrl = \"\"\n\tdef handle_data(self, data) :\n\t\tself.myStr += pymysql.escape_string(data)\n\t\tif(tagMap.has_key(self.lasttag)) :\n\t\t\tself.myStr += \"\\n\"\n\tdef handle_starttag(self, tag, attrs) :\n\t\tif(tag == 'a') :\n\t\t\tfor x in attrs :\n\t\t\t\tif(x[0] == 'title') :\n\t\t\t\t\tself.myTitle = pymysql.escape_string(x[1])\n\t\t\t\telif(x[0] == 'href') :\n\t\t\t\t\tself.myUrl = srcprefix + x[1]\n\t\telif(tag == 'img') :\n\t\t\tfor x in attrs :\n\t\t\t\tif(x[0] == 'src') :\n\t\t\t\t\tself.myImgUrl = imgSrcPreFix + x[1]\n\n\ndef getContext(c_url) :\n\tret = []\n\tfor i, url in enumerate(c_url) :\n\t\ttry :\n\t\t\tprint(\"handling %dth context from zju\" %(i + 1))\n\t\t\tlink = urllib2.urlopen(url)\n\t\t\tsrcCode = link.read()\n\t\t\tnewsPattern = '
[\\s\\S]+?
'\n\t\t\tnewsblock = re.compile(newsPattern).findall(srcCode)\n\t\t\tparser = myHTMLParser()\n\t\t\tstri = parser.unescape(newsblock[0])\n\t\t\tstri = re.sub(r'', '', stri)\n\t\t\tstri = stri.replace(\"\", '').replace(\"\", '').replace(\"\", '').replace(\"\", '').replace(\"\", '')\n\t\t\tparser.feed(stri)\n\t\t\tallImgUrl.append(parser.myImgUrl)\n\t\t\tstri = parser.myStr\n\t\t\tparser.close()\n\n\t\t\tret.append(stri)\n\t\texcept :\n\t\t\tret.append('error')\n\t\t\tprint(\"error when handling %dth context from zju\" %(i + 1))\n\t\t\tprint(traceback.print_exc())\n\n\treturn ret\n\n\ndef main():\n\n\treload(sys)\n\tsys.setdefaultencoding('utf8')\n\n\ttest = sqlConnect(\"zju\", 10)\n\n\tparser = myHTMLParser()\n\n\tlink = urllib2.urlopen('http://www.news.zju.edu.cn/773/list.htm')\n\tsrcCode = link.read()\n\n\tdatePattern = r'
.+?
'\n\tallDate = re.compile(datePattern).findall(srcCode)\n\n\tfor i in range(len(allDate)) :\n\t\tallDate[i] = allDate[i].lstrip('
').rstrip('
')\n\n\ttest.date = allDate\n\n\tallTitle = []\n\tallContextUrl = []\n\n\tnewsPattern = r'
.+?
'\n\tnewsblock = re.compile(newsPattern).findall(srcCode)\n\tfor x in newsblock :\n\t\tparser.feed(x)\n\t\tallTitle.append(parser.unescape(parser.myTitle))\n\t\tallContextUrl.append(parser.myUrl)\n\n\ttest.title = allTitle\n\ttest.contextUrl = allContextUrl\n\n\tallContext = getContext(test.contextUrl)\n\ttest.context = allContext\n\n\ttest.updateSql()\n\ttest.mysqlToJson()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"source/schools/zju.py","file_name":"zju.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"344456732","text":"from torch.utils.data.dataset import Dataset\nimport numpy as np\nimport json\nimport h5py\nimport pdb\n\nclass vqaDataset(Dataset):\n \n def __init__(self, dataset, phase):\n\n with open(dataset['data_info']) as data_file:\n data = json.load(data_file)\n self.ix_to_word = data['ix_to_word']\n self.ix_to_ans = data['ix_to_ans']\n self.dict_size = len(self.ix_to_word.keys())+1\n self.num_ans = len(self.ix_to_ans.keys())\n\n with h5py.File(dataset['questions'], 'r') as hf:\n temp = hf.get('ques_length_%s' % phase)\n self.len_ques = np.array(temp).astype(np.int64)\n\n temp = hf.get('ques_%s' % phase)\n question = np.array(temp).astype(np.int64)\n self.max_len = question.shape[1]\n # right align questions\n N = len(self.len_ques)\n self.question = np.zeros([N, self.max_len])\n for i in range(N):\n self.question[i][-self.len_ques[i]:] = question[i][:self.len_ques[i]]\n\n temp = hf.get('img_pos_%s' % phase)\n self.img_list = np.array(temp)\n\n temp = hf.get('question_id_%s' % phase)\n self.ques_ix = np.array(temp).astype(np.int64)\n\n self.ans_mask = np.zeros([N, 1000])\n\n # make the answer idx start from 0\n temp = hf.get('answers')\n self.answer = np.array(temp).astype(np.int64)-1\n\n if phase == 'train':\n self.ans_mask[np.linspace(0, N-1, N).astype(np.int64), self.answer] = 1\n\n with h5py.File(dataset['img_feat'], 'r') as hf:\n temp = hf.get('images_%s' % phase)\n self.img_feat = np.array(temp).astype(np.float64)\n\n # normalize image feature\n self.img_dim = self.img_feat.shape[1]\n temp = np.sqrt(np.sum(np.multiply(self.img_feat, self.img_feat), axis=1))\n self.img_feat = np.divide(self.img_feat, np.transpose(np.tile(temp, (self.img_dim, 1))))\n\n def __getitem__(self, index):\n img_feat = self.img_feat[self.img_list[index]]\n ques = self.question[index]\n ans = self.answer[index]\n ans_mask = self.ans_mask[index]\n ques_ix = self.ques_ix[index]\n return img_feat, ques, ans_mask, ans, ques_ix\n\n def __len__(self):\n return len(self.question)\n\n\n","sub_path":"code/vqaDataset_mask.py","file_name":"vqaDataset_mask.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530769982","text":"#!/usr/bin/env python2\n# (C) Fedor Goncharov \n# GPL3\n# sudo easy_install intermine\n# For further documentation you can visit:\n# http://www.intermine.org/wiki/PythonClient\nfrom intermine.webservice import Service\nimport gzip\nfh = gzip.open(\"modencode.tab.gz\", \"w\")\nservice = Service(\"http://intermine.modencode.org/release-33/service\")\n# Get a new query on the class (table) you will be querying:\nsubCol = [\"antibodies.targetName\", \"cellLines.name\", \"DCCid\", \"title\"\n , \"experiment.category\", \"experiment.name\"\n , \"experimentType\" , \"project.name\", \"project.surnamePI\" ]\nbsCol = [\"chromosome.primaryIdentifier\"\n , \"chromosomeLocation.start\", \"chromosomeLocation.end\",]\nfh.write(\"\\t\".join( bsCol + subCol) + \"\\n\")\nquery = service.new_query(\"Submission\")\n# The view specifies the output columns\nquery.add_view(*subCol)\nquery.add_constraint(\"experimentType\", \"ONE OF\", [\"ChIP-chip\", \"ChIP-seq\"], code = \"A\")\nquery.add_constraint(\"organism.name\", \"=\", \"Drosophila melanogaster\", code = \"B\")\n\nfor subRow in query.rows():\n subVal = map(str, map(subRow, subCol))\n bsQuery = service.new_query(\"BindingSite\")\n # The view specifies the output columns\n bsQuery.add_view(*bsCol)\n bsQuery.add_constraint(\"submissions.DCCid\", \"=\", subRow[\"DCCid\"],\n code = \"A\")\n for bsRow in bsQuery.rows():\n bsVal = map(str, map(bsRow, bsCol))\n fh.write(\"\\t\".join(bsVal + subVal) + \"\\n\")\n","sub_path":"modencode1.py","file_name":"modencode1.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"620173072","text":"# Создать программу, выводящую на экран ближайшее к 10 из двух чисел, введенных пользователем. Например, среди чисел 8,5 и 11,45 ближайшее к десяти 11,45.\n\n\ndef closer_to_ten(number1, number2):\n delta1 = abs(10 - number1)\n delta2 = abs(10 - number2)\n if delta1 < delta2:\n return number1\n elif delta2 < delta1:\n return number2\n elif delta2 == delta1:\n return number1\n\n\nprint(closer_to_ten(int(input()), int(input())))\n","sub_path":"hw_1_5.py","file_name":"hw_1_5.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"512372761","text":"from ROOT import TLorentzVector, TVector2, TVector3\nfrom math import *\nfrom copy import copy\n\n# parameter used to set lower bounds while searching\nmc=0.0\n\n\"\"\"\nCalculate the M_{T2} variable given two Four-Vector inputs and the MET four-vector\n\"\"\"\ndef calcMt2(vis1in, vis2in, childin):\n\tif vis1in.M()>vis2in.M():\n\t\tvis1=copy(vis2in)\n\t\tvis2=copy(vis1in)\n\telse:\n\t\tvis1=copy(vis1in)\n\t\tvis2=copy(vis2in)\n\n\tchild=copy(childin)\n\n\tmag=mt2Sqrt(vis1.Px()*vis1.Px()+vis1.Py()*vis1.Py())\n\tcospart=vis1.Px()/mag\n\tsinpart=vis1.Py()/mag\n\n\tma,pxa,pya=vis1.M(),vis1.Px(),vis1.Py()\n\tmb,pxb,pyb=vis2.M(),vis2.Px(),vis2.Py()\n\tmc,pxc,pyc=child.M(),child.Px(),child.Py()\n\n\tvis1.SetXYZM(mag,0.0,0.0,ma)\n\tvis2.SetXYZM(pxb*cospart+pyb*sinpart, pyb*cospart-pxb*sinpart, 0.0, mb)\n\tchild.SetXYZM(pxc*cospart+pyc*sinpart, pyc*cospart-pxc*sinpart, 0.0, mc)\n\n\toutputmt2=0.0\n\tsolved=False\n\n\tvis1M2=vis1.M()*vis1.M()\n\tvis2M2=vis2.M()*vis2.M()\n\tmc2=mc*mc\n\tvis1Px2=vis1.Px()*vis1.Px()\n\tvis2Px2=vis2.Px()*vis2.Px()\n\tchildPx2=child.Px()*child.Px()\n\tvis2Py2=vis2.Py()*vis2.Py()\n\tchildPy2=child.Py()*child.Py()\n\tvis1Pt2=vis1Px2\n\tvis2Pt2=vis2Px2+vis2Py2\n\tchildPt2=childPx2+childPy2\n\tvis1Et2=vis1M2+vis1Pt2\n\tvis2Et2=vis2M2+vis2Pt2\n\tchildEt2=mc2+childPt2\n\tvis1Et=mt2Sqrt(vis1Et2)\n\tvis2Et=mt2Sqrt(vis2Et2)\n\n\tMtmin=0.0\n\tMtmax=0.0\n\n\tif (not(vis1.M()<=0.0 or vis2.M()<=0.0)):\n\t\txlmin=vis1.Px()*mc/vis1.M()\n\t\txrmin=vis2.Px()*mc/vis2.M()\n\t\tyrmin=vis2.Py()*mc/vis2.M()\n\n\t\taltxlmin=child.Px()-xlmin\n\t\taltxrmin=child.Px()-xrmin\n\t\taltyrmin=child.Py()-yrmin\n\n\t\tMtlmin=vis1.M()+mc\n\t\tMtrmin=vis2.M()+mc\n\n\t\tMtratlmin=mt2Sqrt(vis2M2+mc2+2.0*(vis2Et*mt2Sqrt(mc2+altxlmin*altxlmin+childPy2)-vis2.Px()*altxlmin-vis2.Py()*child.Py()))\n\t\tMtlatrmin=mt2Sqrt(vis1M2+mc2+2.0*(vis1Et*mt2Sqrt(mc2+altxrmin*altxrmin+altyrmin*altyrmin)-vis1.Px()*altxrmin))\n\n\t\tif (Mtlmin>=Mtratlmin):\n\t\t\tsolved=True\n\t\t\toutputmt2=Mtlmin\n\t\telif (Mtrmin>=Mtlatrmin):\n\t\t\tsolved=True\n\t\t\toutputmt2=Mtrmin\n\t\telse:\n\t\t\tif (Mtlmin>Mtrmin):\n\t\t\t\tMtmin=Mtlmin\n\t\t\telse:\n\t\t\t\tMtmin=Mtrmin\n\n\t\t\tif (Mtlatrminbackup2):\n\t\t\tif (backup1=Mtlatrmin):\n\t\t\tsolved=True\n\t\t\toutputmt2=Mtrmin\n\t\telse:\n\t\t\tif (Mtlmin>Mtrmin):\n\t\t\t\tMtmin=Mtlmin\n\t\t\telse:\n\t\t\t\tMtmin=Mtrmin\n\n\t\t\tMtmax=Mtlatrmin\n\n\t\tbackupmid=mt2Sqrt(mc2+(child.Px()*child.Px()+child.Py()*child.Py())*0.25)\n\t\tbackup1=mt2Sqrt(vis1M2+mc2+2.0*(vis1Et*backupmid-0.5*vis1.Px()*child.Px()))\n\t\tbackup2=mt2Sqrt(vis2M2+mc2+2.0*(vis2Et*backupmid-0.5*(vis2.Px()*child.Px()+vis2.Py()*child.Py())))\n\t\tif (backup1>backup2):\n\t\t\tif (backup1trial2):\n\t\t\tMtmax=trial1\n\t\telse:\n\t\t\tMtmax=trial2\n\n\n\tif (not solved):\n\t\tsolved=True\n\t\toutputmt2=Mtmin+(Mtmax-Mtmin)*0.5\n\n\t\tC1=1.0/vis1Et2\n\n\t\tA2=vis2M2+vis2Py2\n\t\tB2=-2.0*vis2.Px()*vis2.Py()\n\t\tC2=1.0/(vis2M2+vis2Px2)\n\n\t\tpreF1=vis1Et2*mc2\n\n\t\tpreD2=-2.0*child.Px()*A2-B2*child.Py()\n\t\tpreE2=-2.0*child.Py()/C2-B2*child.Px()\n\t\tpreF2=vis2Et2*childEt2-childPx2*vis2Px2-childPy2*vis2Py2+B2*child.Px()*child.Py()\n\n\t\tG=B2*0.5*C2\n\t\tJ1=-vis1M2*C1\n\t\tJ2=(B2*B2*0.25*C2-A2)*C2\n\n\t\talpha=G*G-J1-J2\n\t\tp0_4=alpha*alpha-4.0*J1*J2\n\n\t\twhile (outputmt2>Mtmin and outputmt20:\n\t\t\t\t\tp4_0=-1\n\t\t\t\telif p2_2==0:\n\t\t\t\t\tp4_0=0\n\t\t\t\telse:\n\t\t\t\t\tp4_0=1\n\t\t\telse:\n\t\t\t\tp4_0=p2_1*p3_0/p3_1-p2_2*p3_0*p3_0/(p3_1*p3_1)-p2_0\n\n\t\t\tnegroots=1\n\t\t\tposroots=0\n\n\t\t\tif ((p0_4<0.0 and p2_2<0.0) or (p0_4>0.0 and p2_2>0.0)):\n\t\t\t\tnegroots+=1\n\t\t\telif((p0_4<0.0 and p2_2>0.0) or (p0_4>0.0 and p2_2<0.0)):\n\t\t\t\tposroots+=1\n\n\t\t\tif ((p2_2<0.0 and p3_1<0.0) or (p2_2>0.0 and p3_1>0.0)):\n\t\t\t\tnegroots+=1\n\t\t\telif((p2_2<0.0 and p3_1>0.0) or (p2_2>0.0 and p3_1<0.0)):\n\t\t\t\tposroots+=1\n\n\t\t\tif ((p3_1<0.0 and p4_0<0.0) or (p3_1>0.0 and p4_0>0.0)):\n\t\t\t\tnegroots+=1\n\t\t\telif((p3_1<0.0 and p4_0>0.0) or (p3_1>0.0 and p4_0<0.0)):\n\t\t\t\tposroots+=1\n\n\t\t\tif (posroots==negroots):\n\t\t\t\tMtmin=outputmt2\n\t\t\telse:\n\t\t\t\tMtmax=outputmt2\n\n\t\t\toutputmt2=Mtmin+(Mtmax-Mtmin)*0.5\n\treturn outputmt2\n\n\"\"\"\nSpecial version of sqrt() to handle extreme inputs\n\"\"\"\ndef mt2Sqrt(x):\n\tif isnan(x):\n\t\treturn 0.0\n\telif (x<=0.0):\n\t\treturn 0.0\n\telif (isinf(x)):\n\t\treturn 1e99999999999999999999999999999999\n\telse:\n\t\tprev2root=-1.0\n\t\tprevroot=-1.0\n\t\troot=1.0\n\t\twhile((root!=prevroot) and (root!=prev2root)):\n\t\t\tprev2root=prevroot\n\t\t\tprevroot=root\n\t\t\troot=(root+x/root)*0.5\n\n\t\treturn root\n","sub_path":"TopAnalysis/scripts/MT2Calculator.py","file_name":"MT2Calculator.py","file_ext":"py","file_size_in_byte":6224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631269439","text":"import cv2\r\nimport numpy as np\r\n\r\ndef tl_detection(rawImg):\r\n #高斯模糊\r\n image=cv2.GaussianBlur(rawImg,(5,5),3)\r\n image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\r\n sobelx=cv2.Sobel(image,cv2.CV_64F,1,0)\r\n #转回int8\r\n image=cv2.convertScaleAbs(sobelx)\r\n #二值化\r\n ret,img=cv2.threshold(image,127,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)\r\n #补洞\r\n kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(17,5))\r\n img=cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel,iterations=2)\r\n #形态学操作去噪\r\n kernelx=cv2.getStructuringElement(cv2.MORPH_RECT,(22,1))\r\n kernely=cv2.getStructuringElement(cv2.MORPH_RECT,(1,35))\r\n img=cv2.dilate(img,kernelx,iterations=1)\r\n img=cv2.erode(img,kernelx,iterations=1)\r\n img=cv2.erode(img,kernely,iterations=1)\r\n img=cv2.dilate(img,kernely,iterations=1)\r\n #平滑处理\r\n img=cv2.medianBlur(img,17)\r\n #查找轮廓\r\n contours,_=cv2.findContours(img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n #颜色空间\r\n lower_hsv_red=np.array([0,255,135])\r\n upper_hsv_red=np.array([0,149,255])\r\n lower_hsv_yellow = np.array([18,255,130])\r\n upper_hsv_yellow = np.array([26,208,255])\r\n lower_hsv_green = np.array([71,206,255])\r\n upper_hsv_green = np.array([52,226,244])\r\n\r\n #侦测框列表\r\n rectlist=[]\r\n #提取边界矩形\r\n for item in contours:\r\n rect=cv2.boundingRect(item)\r\n x,y,width,height=rect[0],rect[1],rect[2],rect[3]\r\n if height<(width*2.5) and height>(width*2) and width>10:\r\n a=rawImg[y:y+height,x:x+width,:]\r\n cv2.imshow(\"dst\" + str(x), a)\r\n a=cv2.cvtColor(a,cv2.COLOR_BGR2HSV)\r\n mask_red=cv2.inRange(a,lowerb=lower_hsv_red,upperb=upper_hsv_red)\r\n mask_yellow=cv2.inRange(a,lowerb=lower_hsv_yellow,upperb=upper_hsv_yellow)\r\n mask_green=cv2.inRange(a,lowerb=lower_hsv_green,upperb=upper_hsv_green)\r\n\r\n #筛选框颜色\r\n if np.max(mask_red)==255:\r\n rectlist.append((x,y,x+width,y+height,(0,0,255)))\r\n elif np.max(mask_yellow)==255:\r\n rectlist.append((x,y,x+width,y+height,(0,255,255)))\r\n elif np.max(mask_green)==255:\r\n rectlist.append((x,y,x+width,y+height,(0,255,0)))\r\n for item in contours:\r\n rect=cv2.boundingRect(item)\r\n x=rect[0]\r\n y=rect[1]\r\n w=rect[2]\r\n h=rect[3]\r\n if w>(4*h):\r\n #裁剪区域\r\n dst=rawImg[y:y+h,x:x+w,:]\r\n cv2.imshow(\"dst\"+str(x), dst)\r\n\r\n return rectlist,contours\r\n\r\nif __name__ == '__main__':\r\n rawImg=cv2.imread(\"../img/18.jpg\")\r\n rectlist,contours=tl_detection(rawImg)\r\n print(rectlist)\r\n for i in rectlist:\r\n cv2.rectangle(rawImg,(i[0],i[1]),(i[2],i[3]),i[4],thickness=1)\r\n cv2.imshow(\"image\",rawImg)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()","sub_path":"Day004/python/opencv/红绿灯检测.py","file_name":"红绿灯检测.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"5792861","text":"def cut():\n choose = int(input('''\n Cuts:\n1 - None\n2 - LHCbAcceptance\n3 - DaughtersInLHCb\n4 - BiasedBB\n5 - DMuCascadeInAcc\n6 - BCuts\n7 - DaughtersInLHCbAndWithDaughAndBCuts\n8 - LoKi::GenCutTool/TightCut\n9 - My cut\nCut: '''))\n if choose == 1:\n mycut ='None'\n elif choose == 2:\n mycut ='LHCbAcceptance'\n elif choose == 3:\n mycut = 'DaughtersInLHCb'\n elif choose == 4:\n mycut = 'BiasedBB'\n elif choose == 5:\n mycut = 'DMuCascadeInAcc'\n elif choose == 6:\n mycut = 'BCuts'\n elif choose == 7:\n mycut = 'DaughtersInLHCbAndWithDaughAndBCuts'\n elif choose == 8:\n mycut = 'LoKi::GenCutTool/TightCut'\n else:\n print('Include your cut')\n mycut = '{0}'.format(raw_input(\">\"))\n print (mycut)\n return mycut\n#cut()\n","sub_path":"projects/DocWizzard/cuts.py","file_name":"cuts.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336540760","text":"'''\nCreated on 2010-08-14\n\n@author: jonathan\n'''\n\nfrom pymt.ui.window import MTWindow\nfrom pymt.base import runTouchApp\nfrom pymt.ui.widgets.composed.textarea import MTTextArea\n\nif __name__ == '__main__':\n w = MTWindow()\n w.size = (800,800)\n b = MTTextArea(size=(260,100), pos=(75, 250), anchor_x='center', anchor_y='center',\n style={'bg-color':(255, 100,100), 'bg-color-move':(45 ,150 ,150), 'bg-color-full':(50,150,210)})\n b.value = 'This line should be too\\nlong to fit horizontally\\nin the supplied area'\n w.add_widget(b)\n \n runTouchApp()\n","sub_path":"test/src/steve/TestText.py","file_name":"TestText.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"467780652","text":"import gym\nimport holdem\nimport numpy as np\nfrom collections import defaultdict, deque\nfrom include import *\nimport matplotlib.pyplot as plt\nfrom libs import plotting\nimport sys\nimport utilities\nimport random\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nimport os # for creating directories\n\n\nstarting_stack_size = 200000\n\nenv = gym.make('TexasHoldem-v1') # holdem.TexasHoldemEnv(2)\nenv.add_player(0, stack=starting_stack_size) # add a player to seat 0 with 2000 \"chips\"\nenv.add_player(2, stack=starting_stack_size) # aggressive#\n\nstate_size = 18\n\naction_size = env.action_space.n\n\nbatch_size = 32\n\nepsilon = 0.8\n\nn_episodes = 10000 # n games we want agent to play (default 1001)\n\noutput_dir = 'model_output/TexasHoldemDirectory/'\n\nwith_render = True\n\nwith_graph = True\n\nvillain = \"Strong\"\n\ndelay = None\n\n\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n\nclass DQNAgent:\n def __init__(self, state_size, action_size):\n self.state_size = state_size\n self.action_size = action_size\n self.memory = deque(maxlen=2000) # double-ended queue; acts like list, but elements can be added/removed from either end\n self.gamma = 0.95 # decay or discount rate: enables agent to take into account future actions in addition to the immediate ones, but discounted at this rate\n self.epsilon = epsilon # exploration rate: how much to act randomly; more initially than later due to epsilon decay\n self.epsilon_decay = 0.995 # decrease number of random explorations as the agent's performance (hopefully) improves over time\n self.epsilon_min = 0.001 # minimum amount of random exploration permitted\n self.learning_rate = 0.01 # rate at which NN adjusts models parameters via SGD to reduce cost \n self.model = self._build_model() # private method \n \n def _build_model(self):\n # neural net to approximate Q-value function:\n model = Sequential()\n model.add(Dense(32, input_dim=self.state_size, activation='relu')) # 1st hidden layer; states as input\n model.add(Dense(32, activation='relu')) # 2nd hidden layer\n model.add(Dense(self.action_size, activation='linear')) # 2 actions, so 2 output neurons: 0 and 1 (L/R)\n model.compile(loss='mse',\n optimizer=Adam(lr=self.learning_rate))\n return model\n \n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done)) # list of previous experiences, enabling re-training later\n\n def act(self, state, player_infos, community_infos, community_cards, env, _round, n_seats, state_set, policy):\n if np.random.rand() <= self.epsilon: \n action = get_action_policy(player_infos, community_infos, community_cards, env, _round, n_seats, state_set, policy, villain)\n return action\n act_values = self.model.predict(state) # if not acting according to safe_strategy, predict reward value based on current state\n predicted_action = np.argmax(act_values[0])\n env.learner_bot.he.set_community_cards(community_cards, _round)\n range_structure = utilities.fill_range_structure(_round, env.learner_bot)\n utilities.assign_evals_player(env.learner_bot, _round, env)\n choice = None\n if predicted_action == 0:\n choice = 1\n elif predicted_action == 1:\n total_bet = env._tocall + env._bigblind - env.villain.currentbet\n choice = (2, total_bet)\n elif predicted_action == 2:\n choice = 3\n predicted_action = holdem.safe_actions(community_infos[-1], community_infos, villain_choice=None, n_seats=n_seats, choice=choice, player_o=env.learner_bot)\n return predicted_action # pick the action that will give the highest reward (i.e., go left or right?)\n\n def replay(self, batch_size): # method that trains NN with experiences sampled from memory\n minibatch = random.sample(self.memory, batch_size) # sample a minibatch from memory\n for state, action, reward, next_state, done in minibatch: # extract data for each minibatch sample\n target = reward # if done (boolean whether game ended or not, i.e., whether final state or not), then target = reward\n if not done: # if not done, then predict future discounted reward\n target = (reward + self.gamma * # (target) = reward + (discount rate gamma) * \n np.amax(self.model.predict(next_state)[0])) # (maximum target Q based on future action a')\n target_f = self.model.predict(state) # approximately map current state to future discounted reward\n target_f[0][action] = target\n self.model.fit(state, target_f, epochs=1, verbose=0) # single epoch of training with x=state, y=target_f; fit decreases loss btwn target_f and y_hat\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nfile =\"./model_output/TexasHoldemDirectory/weights_1000.hdf5\"\nagent = DQNAgent(state_size, action_size) # initialise agent\n\n\n\ndef create_np_array(player_infos, player_hands, community_cards, community_infos):\n ps1 = (player_infos[0])\n for card in player_hands[0]:\n ps1 = np.append(ps1, card) \n for info in community_infos:\n ps1 = np.append(ps1, info) \n for card in community_cards:\n ps1 = np.append(ps1, card) \n ps1 = np.reshape(ps1, [1, state_size])\n return ps1\n\n\ndef make_epsilon_greedy_policy(Q, epsilon, nA):\n \"\"\"\n Creates an epsilon-greedy policy based on a given Q-function and epsilon.\n \n Args:\n Q: A dictionary that maps from state -> action-values.\n Each value is a numpy array of length nA (see below)\n epsilon: The probability to select a random action . float between 0 and 1.\n nA: Number of actions in the environment.\n \n Returns:\n A function that takes the observation as an argument and returns\n the probabilities for each action in the form of a numpy array of length nA.\n \n \"\"\"\n def policy_fn(observation): # [call/check, raise/bet, fold]\n A = np.ones(nA, dtype=float) * epsilon / nA\n b = Q[observation]\n best_action = np.argmax(b)\n A[best_action] += (1.0 - epsilon)\n return A\n return policy_fn\n\n\n# ***********************************Interacting with environment ********************************\n\n\n\ndef get_action_policy(player_infos, community_infos, community_cards, env, _round, n_seats, state, policy, villain):\n\t\n\tplayer_actions = None\n\tcurrent_player = community_infos[-3]\n\t\n\tplayer_object = env._player_dict[current_player]\n\tto_call = community_infos[-1]\n\tstack, hand_rank, played_this_round, betting, lastsidepot = player_infos[current_player-1] if current_player is 2 else player_infos[current_player]\n\tstack, hand_rank, played_this_round, betting, lastsidepot = player_infos[current_player-1] if current_player == 2 else player_infos[current_player]\n\tplayer_object.he.set_community_cards(community_cards, _round)\n\t\n\tif _round != \"Preflop\": # preflop already evaluated\n\t\tplayer_object.he.evaluate(_round)\n\trange_structure = utilities.fill_range_structure(_round, player_object)\n\tutilities.assign_evals_player(player_object, _round, env)\n\n\tif(current_player == 0): # learner move \n\t\tprobs = policy(state)\n\t\tchoice = np.random.choice(np.arange(len(probs)), p=probs)\n\t\tbest_nonlearning_action = player_object.choose_action(_round, range_structure, env) # Doesn't use\n\t\tplayer_actions = holdem.safe_actions(to_call, community_infos, villain_choice=None, n_seats=n_seats, choice=choice, player_o = player_object, best_nonlearning_action=best_nonlearning_action)\n\t\t\n\telse: # bot move \n\t\tif villain == \"CallChump\":\n\t\t\tplayer_actions = utilities.safe_actions_call_bot(community_infos, villain_choice=None, n_seats=n_seats)\n\t\telse:\n\t\t\tvillain_choice = player_object.choose_action(_round, range_structure, env) \n\t\t\tplayer_actions = holdem.safe_actions(to_call, community_infos, villain_choice, n_seats=n_seats, choice=None, player_o = player_object)\n\t\n\treturn player_actions\n\nif __name__ == \"__main__\":\n\n Q = defaultdict(lambda: np.zeros(env.action_space.n))\n \n # The policy we're following\n policy = make_epsilon_greedy_policy(Q, agent.epsilon, env.action_space.n)\n last_episode = None\n episode_list = []\n stacks_over_time = {}\n for index, player in env._player_dict.items():\n stacks_over_time.update({player.get_seat(): [player.stack]})\n for e in range(n_episodes): # iterate over new episodes of the game # Print out which episode we're on, useful for debugging.\n if e % 50 == 0:\n agent.load(output_dir + \"weights_\" + '{:04d}'.format(e) + \".hdf5\")\n last_episode = e + 1\n if with_render:\n print(\"\\n\\n********Episode {}*********\".format(e)) \n episode = []\n (player_states, (community_infos, community_cards)) = env.reset()\n (player_infos, player_hands) = zip(*player_states)\n current_state = ((player_infos, player_hands), (community_infos, community_cards))\n utilities.compress_bucket(current_state, env, pre=True)\n state = create_np_array(player_infos, player_hands, community_cards, community_infos)\n\n # Only want the state set that is relevant to learner bot every step. \n state_set = utilities.convert_list_to_tupleA(player_states[env.learner_bot.get_seat()], current_state[1])\n\n if with_render:\n env.render(mode='human', initial=True, delay=delay)\n terminal = False\n while not terminal:\n\n _round = utilities.which_round(community_cards)\n current_player = community_infos[-3]\n if current_player != 0:\n action = get_action_policy(player_infos, community_infos, community_cards, env, _round, env.n_seats, state_set, policy, villain)\n else:\n action = agent.act(state, player_infos, community_infos, community_cards, env, _round, env.n_seats, state_set, policy)\n \n #STEP - SET BREAKPOINT ON THE FOLLOWING LINE TO OBSERVE ACTIONS TAKEN ONE BY ONE\n (player_states, (community_infos, community_cards)), action, rewards, terminal, info = env.step(action)\n\n utilities.compress_bucket(player_states, env)\n action = utilities.convert_step_return_to_action(action)\n ps = list(zip(*player_states))\n next_state = create_np_array(ps[0], ps[1], community_cards, community_infos) # Numpy array\n agent.remember(state, action, env.learner_bot.reward, next_state, terminal)\n state = next_state\n if terminal: \n print(\"episode: {}/{}, reward: {}, e: {:.2}, Profit Margin {}\" # print the episode's score and agent's epsilon\n .format(e, n_episodes, env.learner_bot.reward, agent.epsilon, env.learner_bot.stack - starting_stack_size))\n \n current_state = (player_states, (community_infos, community_cards)) # state = next_state\n if with_render:\n env.render(mode='human', delay=delay)\n\n if len(agent.memory) > batch_size:\n agent.replay(batch_size) # train the agent by replaying the experiences of the episode\n if e % 50 == 0:\n agent.save(output_dir + \"weights_\" + '{:04d}'.format(e) + \".hdf5\")\n\n utilities.do_necessary_env_cleanup(env) # assign new positions, remove players if stack < 0 etc ..\n if len(env._player_dict) > 1:\n count_players = len(env._player_dict)\n sum_stack = 0\n for param in env._player_dict:\n sum_stack += env._player_dict[param].stack\n\n if sum_stack != count_players * starting_stack_size:\n raise(\"Stacks should add to equal\"+str(count_players * starting_stack_size))\n stack_list = env.report_game(requested_attributes = [\"stack\"])\n count_existing_players = 0\n for stack_record_index, stack_record in env._player_dict.items():\n arr = stacks_over_time[stack_record_index] + [stack_list[stack_record_index]]\n stacks_over_time.update({stack_record_index: arr})\n if(stack_list[stack_record_index] != 0):\n count_existing_players += 1\n episode_list.append(episode)\n\n if(count_existing_players == 1):\n \n break\n\n # Episode end\n for player_idx, stack in stacks_over_time.items():\n if player_idx == 0:\n plt.plot(stack, label = \"Player {} - Learner\".format(player_idx))\n else:\t\n plt.plot(stack, label = \"Player {}\".format(player_idx))\n p1_stack_t = list(stacks_over_time.values())[0]\n p2_stack_t = list(stacks_over_time.values())[1]\n # diffs = [j-i for i, j in zip(p1_stack_t[:-1], p1_stack_t[1:])]\n # import statistics\n # lost_avg = statistics.mean(diffs)\n won_avg = p1_stack_t[len(p1_stack_t)-1] - p1_stack_t[0]\n # print(p1_stack_t)\n print('mbb/g:{}'.format(1000 * won_avg/(env._bigblind*last_episode)))\n plt.ylabel('Stack Size')\n plt.xlabel('Episode')\n plt.legend()\n if with_graph:\n plt.show()\n","sub_path":"main_files/holdem/DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":13361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"597926450","text":"import boto3\r\nimport requests\r\nimport time\r\nfrom datetime import datetime as dt\r\nfrom datetime import timezone\r\nimport os\r\n\r\ndef get_my_instances(ec2):\r\n my_instances=[]\r\n for instance in ec2.instances.all():\r\n\r\n check= 0\r\n for tag in instance.tags:\r\n if (tag['Key'] == 'Owner' and tag['Value'] == 'alexandre') or (tag['Key']=='Service' and tag['Value'] == 'task_service'):\r\n check+=1\r\n if check == 2:\r\n my_instances.append(instance)\r\n\r\n return my_instances\r\n\r\ndef create_instance(ec2, init_script):\r\n #botar minha keypair, security group e setar a mim mesmo como Owner\r\n #tipo t2.micro com ubuntu 18(.04? Imagino que sim por ser LTS)\r\n\r\n instance= ec2.create_instances(\r\n KeyName='alexandre_keypair',\r\n SecurityGroups=['alexandre_secgroup'],\r\n TagSpecifications=[\r\n {\r\n 'ResourceType': 'instance',\r\n 'Tags':[\r\n {\r\n 'Key': 'Owner',\r\n 'Value': 'alexandre'\r\n },\r\n {\r\n 'Key': 'Service',\r\n 'Value': 'task_service'\r\n }\r\n ]\r\n }\r\n ],\r\n\r\n InstanceType='t2.micro',\r\n ImageId='ami-0ac019f4fcb7cb7e6',\r\n\r\n UserData=init_script,\r\n\r\n MaxCount=1,\r\n MinCount=1\r\n )\r\n\r\n print(\"Criada uma nova instância.\")\r\n\r\n\r\ndef filter_active(my_instances):\r\n active_instances= []\r\n for instance in my_instances:\r\n target_codes=[0, 16] #pending ou running\r\n if instance.state['Code'] in target_codes:\r\n active_instances.append(instance)\r\n\r\n return active_instances\r\n\r\ndef filter_stable(my_instances):\r\n stable_instances= []\r\n for instance in my_instances:\r\n if instance.state['Code'] == 16: #running\r\n\r\n #checar agora se ela ainda não está no mercy time de inicialização\r\n mercy_time= 5 #em minutos\r\n utc_uptime = dt.now(timezone.utc) - instance.launch_time\r\n delta_minutes= utc_uptime.total_seconds() / 60\r\n\r\n if delta_minutes > mercy_time:\r\n stable_instances.append(instance)\r\n\r\n return stable_instances\r\n\r\ndef healthcheck(my_instances):\r\n health_failed_instances=[]\r\n\r\n for instance in my_instances:\r\n url=\"http://\"+instance.public_ip_address+':5000'+'/healthcheck'\r\n try:\r\n response= requests.get(url)\r\n if response.status_code != 200:\r\n health_failed_instances.append(instance)\r\n except:\r\n #Não recebo uma resposta\r\n health_failed_instances.append(instance)\r\n\r\n return health_failed_instances\r\n\r\ndef main():\r\n #Monitora as instâncias, a saúde delas, reinicializa conforme necessário, guarda o ip das stable\r\n\r\n ec2_client= boto3.client('ec2')\r\n ec2_resource= boto3.resource('ec2')\r\n\r\n session = boto3.Session()\r\n credentials = session.get_credentials()\r\n aws_access_key_id= credentials.access_key\r\n aws_secret_access_key= credentials.secret_key\r\n aws_default_region= session.region_name\r\n\r\n with open('task_install.sh', 'r') as install_task:\r\n init_script= install_task.read().format(aws_access_key_id, aws_secret_access_key, aws_default_region)\r\n\r\n while(True):\r\n print(\"Rechecando...\")\r\n\r\n my_instances= get_my_instances(ec2_resource)\r\n active_instances= filter_active(my_instances)\r\n\r\n #cria novas\r\n instances_to_create= INSTANCES_AMOUNT - len(active_instances)\r\n for i in range(instances_to_create):\r\n create_instance(ec2_resource, init_script)\r\n pass\r\n\r\n #apaga caídas\r\n stable_instances= filter_stable(my_instances)\r\n health_failed_instances= healthcheck(stable_instances)\r\n for instance in health_failed_instances:\r\n print(\"Instância de IPv4 \"+instance.public_ip_address+\" falhou o healthcheck, apagando...\")\r\n stable_instances.remove(instance)\r\n #instance.terminate()\r\n\r\n\r\n #salva os IPs\r\n ips_string= \"\"\r\n\r\n if stable_instances:\r\n for instance in stable_instances:\r\n ips_string+= instance.public_ip_address+'\\n'\r\n ips_string= ips_string[:-1]\r\n with open('active_ips.txt', 'w') as ips_file:\r\n ips_file.write(ips_string)\r\n\r\n time.sleep(10)\r\n\r\nINSTANCES_AMOUNT= int(os.environ.get('LOAD_BALANCER_INSTANCE_AMOUNT'))\r\n\r\nmain()\r\n","sub_path":"projeto/load_balancer/lb_monitor.py","file_name":"lb_monitor.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"8545224","text":"# Simple WPL(SMIL) to M3U convertsion\n# by Zsombor Berki, 2013\n\nfrom xml.dom import minidom\nimport sys\n\nclass WplException(Exception):\n\t\"\"\"Custom exception to handle non-XML errors\"\"\"\n\tdef __init__(self, error):\n\t\tself.error = error\n\tdef __str__(self, string):\n\t\treturn string.__repr__(self.string)\n\ntry:\n\t# sys.argv is a string array containing command line arguments\n\tsource = sys.argv[1]\n\ttarget = sys.argv[2]\n\n\t# check and correct input data: if it doesn't have an extension, we know\n\t# what it's supposed to be, so we can correct it\n\tif source[-4:] != '.wpl':\n\t\tsource += '.wpl'\n\tif target[-4:] != '.m3u':\n\t\ttarget += '.m3u'\n\n\t# open file from cmdline\n\t# we are using minidom, which stands for Minimal DOM (Document Object Model). It's a handy XML parsing library\n\t# that comes with Python by default\n\txmldoc = minidom.parse(source)\n\n\t# is this really a SMIL file?\n\t# SMIL stands for Synchronized Multimediate Integration Language. Basically it's a\n\t# set of standard for defining XML documents which describe media information, and Windows Media Player\n\t# uses this format to store playlists\n\tif len(xmldoc.getElementsByTagName('smil')) == 0:\n\t\traise WplException('This is not a real WPL file') # throw the custom exception\n\n\t# if you check out a .wpl file, you'll see that every song/video is contained in a tag\n\tmedia = xmldoc.getElementsByTagName('media')\n\n\t# even if it's a SMIL file, it could be empty, or someone could be trying to trick your code\n\t# so let's just check if the file contains any playlist entries at all\n\tif len(media) == 0:\n\t\traise WplException('No media was found')\n\n\t# create target file\n\tf = file(target, \"w\")\n\tfor m in media:\n\t\tf.write(m.attributes['src'].value + '\\n')\n\n\t# NEVER forget to close your files. As long as a process has a file open, it can't be accessed by anyone else,\n\t# remember this for the rest of your life. YES, it's that important.\n\tf.close()\nexcept IOError as e:\n\tprint('I/O Error: {0}'.format(e.strerror)) # does the file exist? do you have permission to write files in your target path?\nexcept IndexError as e:\n\tprint('Error: No target path given') # did you provide every required argument?\nexcept WplException as e:\n\tprint('XML Error: {0}'.format(e.error)) # did you really provide a wpl file?","sub_path":"wpltom3u.py","file_name":"wpltom3u.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"107530258","text":"# Copyright 2019 CNIT, Francesco Lombardo, Matteo Pergolesi\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport logging\nimport os\nfrom functools import wraps\nfrom typing import List, Dict\n\nfrom requests import get, ConnectionError, Timeout, \\\n TooManyRedirects, URLRequired, HTTPError, post, put, delete\n\nfrom error_handler import ServerError, NfvoNotFound, NfvoCredentialsNotFound, \\\n Unauthorized, BadRequest, SubscriptionNotFound, Unprocessable\n\nlogger = logging.getLogger('app.iwf_repository')\nIWFREPO_HTTPS = os.getenv('IWFREPO_HTTPS', 'false').lower()\nIWFREPO_HOST = os.getenv('IWFREPO_HOST')\nIWFREPO_PORT = os.getenv('IWFREPO_PORT')\nIWFREPO_INTERVAL = os.getenv('IWFREPO_INTERVAL')\n\nprot = 'https' if IWFREPO_HTTPS == 'true' else 'http'\nhost = IWFREPO_HOST if IWFREPO_HOST else 'localhost'\nport = int(IWFREPO_PORT) if IWFREPO_PORT else 8087\ninterval = int(IWFREPO_INTERVAL) if IWFREPO_INTERVAL else 300\nurl = '{0}://{1}:{2}'.format(prot, host, port)\n\n\ndef _server_error(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except (ConnectionError, Timeout, TooManyRedirects, URLRequired) as e:\n raise ServerError('problem contacting iwf repository: ' + str(e))\n\n return wrapper\n\n\n@_server_error\ndef post_vim_safe(osm_vim: Dict, nfvo_self: str):\n vim_found = get(\n url + '/vimAccounts/search/findByVimAccountNfvoId',\n params={'uuid': osm_vim['_id']})\n vim_found.raise_for_status()\n if vim_found.json()['_embedded']['vimAccounts']:\n logger.info('vim {} found in iwf repository, skip'.format(\n osm_vim['_id']\n ))\n else:\n payload = {\n 'vimAccountNfvoId': osm_vim['_id'],\n 'name': osm_vim['name'],\n 'type': osm_vim['vim_type'],\n 'uri': osm_vim['vim_url'],\n 'tenant': osm_vim['vim_tenant_name'],\n }\n new_vim = post(url + '/vimAccounts', json=payload)\n new_vim.raise_for_status()\n logger.info('created new vimAccount with id {0}'.format(\n new_vim.json()['vimAccountNfvoId']))\n put(new_vim.json()['_links']['nfvOrchestrators']['href'],\n data=nfvo_self,\n headers={'Content-Type': 'text/uri-list'}).raise_for_status()\n logger.info('associated vimAccount to {0}'.format(nfvo_self))\n\n\n@_server_error\ndef find_nfvos_by_type(nfvo_type: str):\n response = get(\n url + '/nfvOrchestrators/search/findByTypeIgnoreCase',\n params={'type': nfvo_type})\n response.raise_for_status()\n return response.json()['_embedded']['nfvOrchestrators']\n\n\n@_server_error\ndef _get_nfvo(nfvo_id) -> Dict:\n try:\n resp = get(url + '/nfvOrchestrators/' + nfvo_id)\n resp.raise_for_status()\n nfvo = resp.json()\n except HTTPError as e:\n if e.response.status_code == 404:\n raise NfvoNotFound(nfvo_id)\n elif e.response.status_code == 401:\n raise Unauthorized()\n else:\n raise\n return nfvo\n\n\n@_server_error\ndef _convert_nfvo(nfvo: Dict) -> Dict:\n try:\n site = get(nfvo['_links']['site']['href']).json()['name']\n except HTTPError:\n site = None\n conv = {\n 'id': nfvo['id'],\n 'name': nfvo['name'],\n 'type': nfvo['type'],\n 'site': site\n }\n if nfvo['uri'] is not None:\n conv['uri'] = nfvo['uri']\n if nfvo['createdAt'] is not None:\n conv['createdAt'] = nfvo['createdAt']\n if nfvo['updatedAt'] is not None:\n conv['updatedAt'] = nfvo['updatedAt']\n return conv\n\n\ndef convert_cred(nfvo):\n del nfvo['credentials']['id']\n nfvo['credentials']['nfvo_id'] = nfvo['id']\n nfvo['credentials']['user'] = nfvo['credentials'].pop('username')\n return nfvo['credentials']\n\n\ndef get_nfvo_by_id(nfvo_id: int) -> Dict:\n nfvo = _get_nfvo(nfvo_id)\n return _convert_nfvo(nfvo)\n\n\ndef get_nfvo_cred(nfvo_id: int) -> Dict:\n nfvo = _get_nfvo(nfvo_id)\n if nfvo['credentials'] is None:\n raise NfvoCredentialsNotFound(nfvo_id)\n else:\n return convert_cred(nfvo)\n\n\n@_server_error\ndef get_nfvo_list() -> List[Dict]:\n try:\n resp = get(url + '/nfvOrchestrators')\n resp.raise_for_status()\n except HTTPError as e:\n if e.response.status_code == 401:\n raise Unauthorized()\n else:\n raise\n return [_convert_nfvo(nfvo) for nfvo in\n resp.json()['_embedded']['nfvOrchestrators']]\n\n\n@_server_error\ndef get_subscription_list(nfvo_id: int) -> Dict:\n try:\n resp = get('{0}/nfvOrchestrators/{1}/subscriptions'.format(url,\n nfvo_id))\n resp.raise_for_status()\n except HTTPError as e:\n if e.response.status_code == 401:\n raise Unauthorized()\n if e.response.status_code == 404:\n raise NfvoNotFound(nfvo_id)\n else:\n raise\n return resp.json()\n\n\n@_server_error\ndef create_subscription(nfvo_id: int, body: Dict):\n try:\n create = post('{0}/subscriptions'.format(url), json=body)\n create.raise_for_status()\n associate = put(create.json()['_links']['nfvOrchestrators']['href'],\n data='{0}/nfvOrchestrators/{1}'.format(url,\n nfvo_id),\n headers={'Content-Type': 'text/uri-list'})\n associate.raise_for_status()\n except HTTPError as e:\n if e.response.status_code == 400:\n raise BadRequest(description=e.response.text)\n if e.response.status_code == 404:\n raise NfvoNotFound(nfvo_id)\n if e.response.status_code == 422:\n raise Unprocessable(description=e.response.text)\n else:\n raise\n return create.json()\n\n\n@_server_error\ndef get_subscription(nfvo_id: int, subscriptionId: int) -> Dict:\n try:\n resp = get(\n '{0}/nfvOrchestrators/{1}/subscriptions/{2}'.format(url,\n nfvo_id,\n subscriptionId))\n resp.raise_for_status()\n except HTTPError as e:\n if e.response.status_code == 404:\n raise SubscriptionNotFound(sub_id=subscriptionId)\n else:\n raise\n return resp.json()\n\n\n@_server_error\ndef delete_subscription(subscriptionId: int) -> None:\n try:\n resp = delete(\n '{0}/subscriptions/{1}'.format(url, subscriptionId))\n resp.raise_for_status()\n except HTTPError as e:\n if e.response.status_code == 404:\n raise SubscriptionNotFound(sub_id=subscriptionId)\n else:\n raise\n\n\n@_server_error\ndef search_subs_by_ns_instance(ns_instance_id: str) -> List[Dict]:\n try:\n subs = get(url + '/subscriptions/search/findByNsInstanceId',\n params={'nsInstanceId': ns_instance_id})\n subs.raise_for_status()\n except HTTPError:\n raise\n return subs.json()['_embedded']['subscriptions'] if subs else []\n","sub_path":"adaptation_layer/iwf_repository.py","file_name":"iwf_repository.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"674746","text":"#!/usr/bin/env python3\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn import datasets\n\nBATCH_SIZE = 25\nITERATIONS = 50\nLEARNING_RATE = 0.05\n\ndef load_data():\n iris = datasets.load_iris()\n # 花びらの幅\n x_vals = np.array([x[3] for x in iris.data])\n # 花びらの長さ\n y_vals = np.array([y[0] for y in iris.data])\n\n return (x_vals, y_vals)\n\ndef create_model():\n # プレースホルダー\n x_data = tf.compat.v1.placeholder(shape=[None, 1], dtype=tf.float32)\n y_target = tf.compat.v1.placeholder(shape=[None, 1], dtype=tf.float32)\n\n # 変数\n A = tf.compat.v1.Variable(tf.compat.v1.random_normal(shape=[1, 1]))\n b = tf.compat.v1.Variable(tf.compat.v1.random_normal(shape=[1, 1]))\n\n # モデル式(y = ax + b)\n model_output = tf.compat.v1.add(tf.compat.v1.matmul(x_data, A), b)\n\n return (x_data, y_target, A, b, model_output)\n\ndef select_loss_func(isL1, y_target, model_output):\n\n if isL1:\n # L1損失関数\n return tf.compat.v1.reduce_mean(tf.compat.v1.abs(y_target - model_output))\n else:\n # L2損失関数\n return tf.compat.v1.reduce_mean(tf.compat.v1.square(y_target - model_output))\n\ndef optimize(loss, learning_rate):\n\n # 最適化関数\n my_opt = tf.compat.v1.train.GradientDescentOptimizer(learning_rate)\n train_step = my_opt.minimize(loss)\n\n return train_step\n\ndef train(sess, x_vals, y_vals, iterations, batch_size):\n \n loss_vec = []\n\n for i in range(iterations):\n rand_index = np.random.choice(len(x_vals), size=batch_size)\n rand_x = np.transpose([x_vals[rand_index]])\n rand_y = np.transpose([y_vals[rand_index]])\n sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})\n temp_loss = sess.run(loss_l1, feed_dict={x_data: rand_x, y_target: rand_y})\n loss_vec.append(temp_loss)\n # バッチサイズごとに係数A, b 更新(バッチ学習) sess.run で更新\n if (i+1) % batch_size == 0:\n print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)) + ' b = ' + str(sess.run(b)))\n print('Loss = ' + str(temp_loss))\n\n [slope] = sess.run(A)\n [y_intercept] = sess.run(b)\n\n best_fit = []\n for i in x_vals:\n best_fit.append(slope*i+y_intercept)\n\n return (loss_vec, best_fit)\n\nif __name__ == \"__main__\":\n \n x_vals, y_vals = load_data()\n x_data, y_target, A, b, model_output = create_model()\n\n sess = tf.compat.v1.Session()\n loss_l1 = select_loss_func(True, y_target, model_output)\n train_step = optimize(loss_l1, LEARNING_RATE)\n\n init = tf.compat.v1.global_variables_initializer()\n sess.run(init)\n\n loss1_vec, best_fit_loss1 = train(sess, x_vals, y_vals, ITERATIONS, BATCH_SIZE)\n\n sess = tf.compat.v1.Session()\n loss_l2 = select_loss_func(False, y_target, model_output)\n train_step = optimize(loss_l2, LEARNING_RATE)\n\n init = tf.compat.v1.global_variables_initializer()\n sess.run(init)\n\n loss2_vec, best_fit_loss2 = train(sess, x_vals, y_vals, ITERATIONS, BATCH_SIZE)\n\nplt.plot(loss1_vec, 'k-', label='L1 Loss')\nplt.plot(loss2_vec, 'r--', label='L2 Loss')\nplt.title('L1 and L2 Loss per Generation')\nplt.xlabel('Generation')\nplt.ylabel('L1 Loss')\nplt.legend(loc='upper right')\nplt.show()\n\nplt.show()","sub_path":"02_Linear_Regression/04_Loss_Functions_in_Linear_Regressions/04_lin_reg_l1_vs_l2.py","file_name":"04_lin_reg_l1_vs_l2.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275046768","text":"\nwith open('cook.txt', encoding = 'utf-8') as f:\n cook_book = {}\n\n dish_name_list = []\n# def dish_name_list():\n# while True:\n# dish_name = f.readline().strip()\n# if not dish_name:\n# break\n# ingridient_number = f.readline().strip()\n# ingridient_number_int = int(ingridient_number)\n#\n# for i in range(ingridient_number_int):\n# f.readline() # пустая строка\n# f.readline()\n# dish_name_list.append(dish_name)\n# print(dish_name_list)\n# return dish_name_list\n# def ingridient_list():\n dishes_dic = {}\n ingridient_list = {}\n while True:\n f.readline()\n ingridient_number = f.readline().strip()\n\n if not ingridient_number:\n break\n\n for i in range(int(ingridient_number)):\n str_strip = f.readline().strip()\n str = str_strip.split(' | ')\n dishes_dic['ingridient_name'] = str[0]\n dishes_dic['quantity'] = int(str[1])\n dishes_dic['measure'] = str[2]\n print(dishes_dic)\n f.readline()\n\ndef get_shop_list_by_dishes(dishes, person_count):\n shop_list = {}\n for dish in dishes:\n for ingridient in cook_book[dish]:\n new_shop_list_item = dict(ingridient)\n\n new_shop_list_item['quantity'] *= person_count\n if new_shop_list_item['ingridient_name'] not in shop_list:\n shop_list[new_shop_list_item['ingridient_name']] = new_shop_list_item\n else:\n shop_list[new_shop_list_item['ingridient_name']]['quantity'] += new_shop_list_item['quantity']\n return shop_list\n\ndef print_shop_list(shop_list):\n for shop_list_item in shop_list.values():\n print('{} {} {}'.format(shop_list_item['ingridient_name'], shop_list_item['quantity'],\n shop_list_item['measure']))\n\ndef create_shop_list():\n person_count = int(input('Введите количество человек: '))\n dishes = input('Введите блюда в расчете на одного человека (через запятую): ') \\\n .lower().split(', ')\n shop_list = get_shop_list_by_dishes(dishes, person_count)\n print_shop_list(shop_list)\n\ncreate_shop_list()","sub_path":"Code_from_1_5.py","file_name":"Code_from_1_5.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"282051978","text":"import random\r\nimport discord\r\nimport time, datetime\r\nfrom discord.ext import commands\r\nfrom cogs.util import store, ready_status\r\n\r\nclient = commands.Bot(command_prefix=store('config.json', 'pfx', True))\r\n\r\n@client.event\r\nasync def on_ready():\r\n guild = client.get_guild(788886124159828009)\r\n global emojis\r\n emojis = await guild.fetch_emojis()\r\n await ready_status(client, store('config.json', None, True))\r\n print(\"Ready\")\r\n global starttime\r\n starttime = time.time()\r\n\r\n@client.event\r\nasync def on_command_error(ctx, error):\r\n await ctx.send(f\"ERROR: {error}\")\r\n\r\n@client.event\r\nasync def on_message(message):\r\n if message.author.bot: return\r\n # if message.channel.id == 0:\r\n await client.process_commands(message)\r\n\r\n@client.command()\r\nasync def uptime(ctx):\r\n e = discord.Embed(title=\"Current uptime\", description=f\"The current uptime is: {str(datetime.timedelta(seconds=int(round(time.time()-starttime))))}\", color=0x23272A)\r\n await ctx.send(embed=e)\r\n\r\n@client.command()\r\nasync def wakeupmrwest(ctx):\r\n await ctx.send(\"<:horny:815833288936914944> WAKE UP MR WEST <:horny:815833288936914944>\")\r\n\r\n@client.command(aliases=['q', 'quotes'])\r\nasync def quote(ctx):\r\n await ctx.send(f\"{random.choice(store('quotes.json', None, True))} {random.choice(emojis)}\")\r\n\r\n@client.command(description=\"shows how many quotes exist\")\r\nasync def count(ctx):\r\n await ctx.send(f\"there are {len(store('quotes.json', None, True))} quotes recorded\")\r\n\r\n@client.command()\r\nasync def freeishot(ctx):\r\n await ctx.send(\"<:horny:815833288936914944> <:horny_2:866447638516858880> <:horny_tongue:827959001311346688>\")\r\n\r\n@client.command(description=\"add a quote to the list\")\r\n@commands.has_any_role(872954220884688937, 831577493080113193, 792875711676940321, 788912937481273344, 788911513129058304)\r\nasync def accept(ctx, *, quote):\r\n if quote.startswith(\"\\\"\") or quote.endswith(\"\\\"\"):\r\n await ctx.send(\"WTF MAN YUO HAVE QUOTATION MARKS IN YOUR QUOTE REMOVE THEM OR I WILL FUCK YOU IN THE ASS\")\r\n return\r\n x = store('quotes.json', None, True)\r\n x.append(quote)\r\n store('quotes.json', x)\r\n await ctx.send(\"👍 added\")\r\n\r\nclient.run(store('config.json', 'token', True))\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"44354547","text":"# 마법 공식을 판다스를 이용한 모듈로 작성하기\nimport pandas as pd\n\ndef magic_by_pd(file_path):\n # 엑셀 파일 읽어 오기 - 인덱스 컬럼 설정\n per_data = pd.read_excel(file_path, sheet_name='PER', index_col=0)\n\n # PER 값이 0보다 작은 경우 필터링\n filtered_per = per_data[per_data['PER']>0]\n\n # PER 데이터프레임 정렬\n sorted_per = filtered_per.sort_values(by='PER')\n\n # PER 값으로 순위 만들기\n rank_per = sorted_per['PER'].rank()\n\n # PER 값으로 작성된 순위를 기존 데이터프레임에 합치기\n sorted_per['PER랭킹'] = sorted_per['PER'].rank()\n\n # ROA 데이터 읽어 오기\n roa_data = pd.read_excel(file_path, sheet_name='ROA', index_col=0)\n\n # NaN값 제거하기\n filtered_roa = roa_data.dropna()\n\n # 컬럼명 변경하기 - 컬럼명을 리스트로 입력\n filtered_roa.columns = ['ROA']\n\n # 정렬하고 순위 매기기\n sorted_roa = filtered_roa.sort_values(by='ROA', ascending=False)\n rank_roa = sorted_roa['ROA'].rank(ascending=False)\n sorted_roa['ROA랭킹'] = sorted_roa['ROA'].rank(ascending=False)\n\n # 두 데이터프레임 합치기\n total_df = pd.merge(sorted_per, sorted_roa, how='inner', left_index=True, right_index=True)\n\n # 종합점수 필드 구하기\n total_df['종합점수'] = (total_df['PER랭킹'] + total_df['ROA랭킹'])\n\n # 종합등수를 구한후 정렬해서 보여주기\n total_df['종합등수'] = total_df['종합점수'].rank()\n\n return total_df.sort_values(by='종합등수')\n\nif __name__ == \"__main__\":\n file_path = \"D:\\\\Projects\\\\New_Python\\\\Quant_Strategy\\\\datas\\\\마법공식 데이터.xlsx\"\n res = magic_by_pd(file_path)\n print(res)","sub_path":"Quant_Strategy/Pandas/magic_pandas_module.py","file_name":"magic_pandas_module.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466762459","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom base import views as base_views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n#from django.contrib.flatpages import views\n\nurlpatterns = [\n url(r'^tinymce/', include('tinymce.urls')),\n url(r'^pages/', include('django.contrib.flatpages.urls')),\n url(r'^admin/', admin.site.urls),\n url(r'^basket/$', base_views.basket), \n url(r'^checkout/$', base_views.checkout), \n url(r'^category/([\\w-]+)/$', base_views.category), \n url(r'^category/([\\w-]+)/([\\w-]+)/$', base_views.category), \n url(r'^product/([\\w-]+)/$', base_views.product), \n url(r'^basket/put/([\\d]+)/([\\d-]+)/$', base_views.basket_put), \n url(r'^basket/get/$', base_views.basket_get), \n url(r'^search/([^/]+)/$', base_views.search), \n url(r'^order/status/([\\w-]+)/$', base_views.order), \n url(r'^basket/delete/([\\d]+)/$', base_views.basket_delete), \n url(r'^$', base_views.index), \n]\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n\n\n","sub_path":"vetapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"60177114","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport requests\n\n###############################################################################\n# Tratamento dos dados\n###############################################################################\n# Baixando o dataset\nurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\nr = requests.get(url)\nfile = \"iris.csv\"\nopen(file, 'wb').write(r.content)\n\n# Pegando o dataset com pandas\ndataset = pd.read_csv('iris.csv', header=None, names=['sepal_length','sepal_width','petal_length','petal_width','species'])\ndataset.head()\n\n# One Hot Encoding - para nossas classes\nfrom sklearn.preprocessing import LabelBinarizer\nspecies_lb = LabelBinarizer()\nY = species_lb.fit_transform(dataset['species'])\n\n# Normalizando os dados\nfrom sklearn.preprocessing import normalize\nfeatures = dataset.columns[0:4]\nX_data = dataset[features].values # Only the values in the DataFrame will be returned, the axes labels will be removed.\nX_data = normalize(X_data)\n\n# separando os dados de teste e treinamento\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_data, Y, test_size=0.3, random_state=1)\n\n###############################################################################\n# Modelo RNA\n###############################################################################\n# Paramentros\nlearning_rate = 0.001\ntraining_epochs = 5000\n\n# Rede Neural Paramentros\nn_hidden_1 = 1024 # Numero de neuronios da hiddenlayer 1\nn_input = X_train.shape[1] # input shape (105, 4)\nn_classes = y_train.shape[1] # classes para predizer\n\n# Inputs\nX = tf.placeholder(\"float\", shape=[None, n_input])\ny = tf.placeholder(\"float\", shape=[None, n_classes])\n\n# Pesos\nw = tf.Variable(tf.random_normal([n_input, n_hidden_1]))\nw_out = tf.Variable(tf.random_normal([n_hidden_1, n_classes]))\n\n# Bias\nb = tf.Variable(tf.random_normal([n_hidden_1]))\nb_out = tf.Variable(tf.random_normal([n_classes]))\n\n# Hidden layer1\nlayer_1 = tf.add(tf.matmul(X, w), b)\nlayer_1 = tf.nn.sigmoid(layer_1)\n\n# Output layer\nout_layer = tf.matmul(layer_1, w_out) + b_out\n\n# Predicao do modelo\nypredict = tf.argmax(out_layer, axis=1)\n\n# lost funcition\nloss = tf.reduce_sum(tf.square(y-out_layer))\n\n# Otimizador\noptimizer = tf.train.GradientDescentOptimizer(learning_rate)\ntrain_op = optimizer.minimize(loss)\n\n# Inicializando as variaveis\ninit = tf.global_variables_initializer()\n\n\nfrom datetime import datetime\nstartTime = datetime.now()\n\nwith tf.Session() as sess:\n sess.run(init)\n \n # Epocas\n for epoch in range(training_epochs):\n for i in range(len(X_train)):\n sess.run(train_op, feed_dict={X: X_train[i: i + 1], y: y_train[i: i + 1]})\n \n # acuracias\n train_accuracy = np.mean(np.argmax(y_train, axis=1) == sess.run(ypredict, feed_dict={X: X_train, y: y_train}))\n test_accuracy = np.mean(np.argmax(y_test, axis=1) == sess.run(ypredict, feed_dict={X: X_test, y: y_test}))\n \n if(train_accuracy > 0.95 and test_accuracy > 0.95):\n break;\n \n print()\n print('Treino: ')\n print(np.argmax(y_train, axis=1) == sess.run(ypredict, feed_dict={X: X_train, y: y_train}))\n \n \n print()\n print('Teste:')\n print(np.argmax(y_test, axis=1) == sess.run(ypredict, feed_dict={X: X_test, y: y_test}))\n \n print()\n print(\"Epoca = %d, Treino Acuracia = %.2f%%, Teste Acuracia = %.2f%%\" % (epoch + 1, 100. * train_accuracy, 100. * test_accuracy)) \n\n\nprint(\"Tempo total:\", datetime.now() - startTime)\n ","sub_path":"iris/iris.py","file_name":"iris.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"649637104","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport numpy as np\nfrom astropy.table import Table\nfrom astropy.io import fits\n## Import some helper functions, you can see their definitions by uncomenting the bash shell command\nfrom desispec.workflow.utils import define_variable_from_environment, pathjoin, get_json_dict\nfrom desiutil.log import get_logger\nfrom desispec.util import header2night\n\n#############################################\n##### Exposure Table Column Definitions #####\n#############################################\n## To eventually being turned into a full-fledged data model. For now a brief description.\n# EXPID, int, the exposure ID.\n# EXPTIME, float, the exposure time.\n# OBSTYPE, string, the obstype as defined by ICS.\n# SPECTROGRAPHS, string, the spectrographs as defined by ICS.\n# CAMWORD, string, typically 'a'+ str(spectrographs) meaning all cameras of the available spectrographs.\n# TILEID, int, the TILEID of the tile the exposure observed.\n# NIGHT, int, the night of the observation.\n# EXPFLAG, int, A 0 signifies that it is a good observation. 1 or greater indicates an issue.\n# Each number will be assigned a meaning. Currently 1 just means \"don't use\".\n# HEADERERR, np.ndarray, Given as a \"|\" separated list of key=value pairs describing columns in the table that should\n# be corrected. The workflow transforms these into an array of strings.\n# NOTE: This will be used to change the given key/value pairs in the production table.\n# SURVEY, int, a numeric ID for a given observing run, e.g. CMX is 0. SV0 is 1, etc.\n# SEQNUM, int, The number of the current exposure in a sequence of exposures, as given by ICS. If not a sequence, SEQNUM is 1.\n# SEQTOT, int, The total number of exposures taken in the current sequence, as given by ICS. If not a sequence, SEQTOT is 1.\n# PROGRAM, string, The program as given by ICS.\n# MJD-OBS, float, The MJD-OBS as given by ICS. Modified Julian Date of the observation.\n# REQRA, float, The REQRA as given by ICS. The requested RA.\n# REQDEC, float, The REQDEC as given by ICS. The requested DEC.\n# TARGTRA, float, The TARGTRA as given by ICS. The RA of the target.\n# TARGTDEC, float, The TARGTDEC as given by ICS. The DEC of the target.\n# COMMENTS, np.ndarray, In the csv given as either a \"|\" separated list of comments or one long comment. When loaded it\n# is a numpy array of the strings.These are not used by the workflow but useful for humans\n# to put notes for other humans.\n##################################################\n\ndef get_exposure_table_column_defs(return_default_values=False):\n \"\"\"\n Contains the column names, data types, and default row values for a DESI Exposure table. It returns\n the names and datatypes with the defaults being given with an optional flag. Returned as 2 (or 3) lists.\n\n Args:\n return_default_values, bool. True if you want the default values returned.\n\n Returns:\n colnames, list. List of column names for an exposure table.\n coldtypes, list. List of column datatypes for the names in colnames.\n coldeflts, list. Optionally returned if return_default_values is True. List of default values for the\n corresponding colnames.\n \"\"\"\n ## Define the column names for the exposure table and their respective datatypes, split in two\n ## only for readability's sake\n colnames1 = ['EXPID', 'EXPTIME', 'OBSTYPE', 'SPECTROGRAPHS', 'CAMWORD', 'TILEID']\n coltypes1 = [int, float, 'S8', 'S10', 'S30', int]\n coldeflt1 = [-99, 0.0, 'unknown', '0123456789', 'a09123456789', -99]\n\n colnames2 = ['NIGHT', 'EXPFLAG', 'HEADERERR', 'SURVEY', 'SEQNUM', 'SEQTOT', 'PROGRAM', 'MJD-OBS']\n coltypes2 = [int, int, np.ndarray, int, int, int, 'S30', float]\n coldeflt2 = [20000101, 0, np.array([], dtype=str), 0, 1, 1, 'unknown', 50000.0]\n\n colnames3 = ['REQRA', 'REQDEC', 'TARGTRA', 'TARGTDEC', 'COMMENTS']\n coltypes3 = [float, float, float, float, np.ndarray]\n coldeflt3 = [-99.99, -89.99, -99.99, -89.99, np.array([], dtype=str)]\n\n colnames = colnames1 + colnames2 + colnames3\n coldtypes = coltypes1 + coltypes2 + coltypes3\n coldeflts = coldeflt1 + coldeflt2 + coldeflt3\n\n if return_default_values:\n return colnames, coldtypes, coldeflts\n else:\n return colnames, coldtypes\n\ndef default_exptypes_for_exptable():\n \"\"\"\n Defines the exposure types to be recognized by the workflow and saved in the exposure table by default.\n\n Returns:\n list. A list of default obstypes to be included in an exposure table.\n \"\"\"\n ## Define the science types to be included in the exposure table (case insensitive)\n return ['arc','flat','twilight','science','sci','dither','dark','bias','zero']\n\ndef get_survey_definitions():\n \"\"\"\n Defines a numeric value to a 'survey', which in this context is a duration of of observing nights that\n shared some common theme. Examples: minisv2, SV0, SV1, commissioning, etc. Currently a placeholder for\n future development.\n\n Returns:\n survey_def, dict. A dictionary with keys corresponding to the numeric representation of a particular survey,\n with values being a tuple of ints. The first int is the first valid night and the\n second int is the last valid night of the survey.\n \"\"\"\n ## Create a rudimentary way of assigning \"SURVEY keywords based on what date range a night falls into\"\n survey_def = {0: (20200201, 20200315), 1: (\n 20201201, 20210401)} # 0 is CMX, 1 is SV1, 2 is SV2, ..., 99 is any testing not in these timeframes\n return survey_def\n\ndef get_surveynum(night, survey_definitions=None):\n \"\"\"\n Given a night and optionally the survey definitions (which are looked up if not given), this returns the\n proper numeric survey ID for the night.\n\n Args:\n night, int or str. The night of observations for which you want to know the numeric survey ID.\n survey_definitions, dict. A dictionary with keys corresponding to the numeric representation of a particular survey,\n with values being a tuple of ints. The first int is the first valid night and the\n second int is the last valid night of the survey.\n\n Returns:\n int. The numerical ID corresponding to the survey in which the given night took place.\n \"\"\"\n night = int(night)\n if survey_definitions is None:\n survey_definitions = get_survey_definitions()\n\n for survey, (low, high) in survey_definitions.items():\n if night >= low and night <= high:\n return survey\n return 99\n\ndef night_to_month(night):\n \"\"\"\n Trivial function that returns the month portion of a night. Can be given a string or int.\n\n Args:\n night, int or str. The night you want the month of.\n\n Returns:\n str. The zero-padded (length two) string representation of the month corresponding to the input month.\n \"\"\"\n return str(night)[:-2]\n\ndef get_exposure_table_name(night, extension='csv'):\n \"\"\"\n Defines the default exposure name given the night of the observations and the optional extension.\n\n Args:\n night, int or str. The night of the observations going into the exposure table.\n extension, str. The extension (and therefore data format) without a leading period of the saved table.\n Default is 'csv'.\n\n Returns:\n str. The exposure table name given the input night and extension.\n \"\"\"\n # if night is None and 'PROD_NIGHT' in os.environ:\n # night = os.environp['PROD_NIGHT']\n return f'exposure_table_{night}.{extension}'\n\ndef get_exposure_table_path(night=None):\n \"\"\"\n Defines the default path to save an exposure table. If night is given, it saves it under a monthly directory\n to reduce the number of files in a large production directory.\n\n Args:\n night, int or str or None. The night corresponding to the exposure table. If None, no monthly subdirectory is used.\n\n Returns:\n str. The full path to the directory where the exposure table should be written (or is already written). This\n does not including the filename.\n \"\"\"\n # if night is None and 'PROD_NIGHT' in os.environ:\n # night = os.environp['PROD_NIGHT']\n spec_redux = define_variable_from_environment(env_name='DESI_SPECTRO_REDUX',\n var_descr=\"The exposure table path\")\n # subdir = define_variable_from_environment(env_name='USER', var_descr=\"Username for unique exposure table directories\")\n subdir = define_variable_from_environment(env_name='SPECPROD', var_descr=\"Use SPECPROD for unique exposure table directories\")\n if night is None:\n return pathjoin(spec_redux,subdir,'exposure_tables')\n else:\n month = night_to_month(night)\n path = pathjoin(spec_redux,subdir,'exposure_tables',month)\n return path\n\ndef get_exposure_table_pathname(night, extension='csv'):#base_path,prodname\n \"\"\"\n Defines the default pathname to save an exposure table.\n\n Args:\n night, int or str or None. The night corresponding to the exposure table.\n\n Returns:\n str. The full pathname where the exposure table should be written (or is already written). This\n includes the filename.\n \"\"\"\n # if night is None and 'PROD_NIGHT' in os.environ:\n # night = os.environp['PROD_NIGHT']\n path = get_exposure_table_path(night)\n table_name = get_exposure_table_name(night, extension)\n return pathjoin(path,table_name)\n\ndef instantiate_exposure_table(colnames=None, coldtypes=None, rows=None):\n \"\"\"\n Create an empty exposure table with proper column names and datatypes. If rows is given, it inserts the rows\n into the table, otherwise it returns a table with no rows.\n\n Args:\n colnames, list. List of column names for an exposure table.\n coldtypes, list. List of column datatypes for the names in colnames.\n rows, list or np.array of Table.Rows or dicts. An iterable set of Table.Row's or dicts with keys/colnames and value\n pairs that match the default column names and data types of the\n default exposure table.\n\n Returns:\n exposure_table, Table. An astropy Table with the column names and data types for a DESI workflow exposure\n table. If the input rows was not None, it contains those rows, otherwise it has no rows.\n \"\"\"\n if colnames is None or coldtypes is None:\n colnames, coldtypes = get_exposure_table_column_defs()\n\n exposure_table = Table(names=colnames,dtype=coldtypes)\n if rows is not None:\n for row in rows:\n exposure_table.add_row(row)\n return exposure_table\n\n\n\ndef summarize_exposure(raw_data_dir, night, exp, obstypes=None, surveynum=None, colnames=None, coldefaults=None, verbosely=False):\n \"\"\"\n Given a raw data directory and exposure information, this searches for the raw DESI data files for that\n exposure and loads in relevant information for that flavor+obstype. It returns a dictionary if the obstype\n is one of interest for the exposure table, a string if the exposure signifies the end of a calibration sequence,\n and None if the exposure is not in the given obstypes.\n\n Args:\n raw_data_dir, str. The path to where the raw data is stored. It should be the upper level directory where the\n nightly subdirectories reside.\n night, str or int. Used to know what nightly subdirectory to look for the given exposure in.\n exp, str or int or float. The exposure number of interest.\n obstypes, list or np.array of str's. The list of 'OBSTYPE' keywords to match to. If a match is found, the\n information about that exposure is taken and returned for the exposure\n table. Otherwise None is returned (or str if it is an end-of-cal manifest).\n If None, the default list in default_exptypes_for_exptable() is used.\n surveynum, int. The numeric ID of the survey that the night corresponds to. If none, it is looked up from the\n default in get_surveynum().\n colnames, list or np.array. List of column names for an exposure table. If None, the defaults are taken from\n get_exposure_table_column_defs().\n coldefaults, list or np.array. List of default values for the corresponding colnames. If None, the defaults\n are taken from get_exposure_table_column_defs().\n verbosely, bool. Whether to print more detailed output (True) or more succinct output (False).\n\n Returns:\n outdict, dict. Dictionary with keys corresponding to the column names of an exposure table. Values are\n taken from the data when found, otherwise the values are the corresponding default given in\n coldefaults.\n OR\n str. If the exposures signifies the end of a calibration sequence, it returns a string describing the type of\n sequence that ended. Either \"(short|long|arc) calib complete\".\n OR\n NoneType. If the exposure obstype was not in the requested types (obstypes).\n \"\"\"\n log = get_logger()\n\n ## Make sure the inputs are in the right format\n if type(exp) is not str:\n exp = int(exp)\n exp = f'{exp:08d}'\n night = str(night)\n\n ## Use defaults if things aren't defined\n if obstypes is None:\n obstypes = default_exptypes_for_exptable()\n if surveynum is None:\n surveynum = get_surveynum(night)\n if colnames is None or coldefaults is None:\n cnames, cdtypes, cdflts = get_exposure_table_column_defs(return_default_values=True)\n if colnames is None:\n colnames = cnames\n if coldefaults is None:\n coldefaults = cdflts\n\n ## Give a header for the exposure\n if verbosely:\n log.info(f'\\n\\n###### Summarizing exposure: {exp} ######\\n')\n else:\n log.info(f'Summarizing exposure: {exp}')\n ## Request json file is first used to quickly identify science exposures\n ## If a request file doesn't exist for an exposure, it shouldn't be an exposure we care about\n reqpath = pathjoin(raw_data_dir, night, exp, f'request-{exp}.json')\n if not os.path.isfile(reqpath):\n if verbosely:\n log.info(f'{reqpath} did not exist!')\n else:\n log.info(f'{exp}: skipped -- request not found')\n return None\n\n ## Load the json file in as a dictionary\n req_dict = get_json_dict(reqpath)\n\n ## Check to see if it is a manifest file for calibrations\n if \"SEQUENCE\" in req_dict and req_dict[\"SEQUENCE\"].lower() == \"manifest\":\n if int(night) < 20200310:\n pass\n elif int(night) < 20200801:\n if 'PROGRAM' in req_dict:\n prog = req_dict['PROGRAM'].lower()\n if 'calib' in prog and 'done' in prog:\n if 'short' in prog:\n return \"endofshortflats\"\n elif 'long' in prog:\n return 'endofflats'\n elif 'arc' in prog:\n return 'endofarcs'\n else:\n if 'MANIFEST' in req_dict:\n manifest = req_dict['MANIFEST']\n if 'name' in manifest:\n name = manifest['name'].lower()\n if name in ['endofarcs', 'endofflats', 'endofshortflats']:\n return name\n\n ## If FLAVOR is wrong or no obstype is defines, skip it\n if 'FLAVOR' not in req_dict.keys():\n if verbosely:\n log.info(f'WARNING: {reqpath} -- flavor not given!')\n else:\n log.info(f'{exp}: skipped -- flavor not given!')\n return None\n\n flavor = req_dict['FLAVOR'].lower()\n if flavor != 'science' and 'dark' not in obstypes and 'zero' not in obstypes:\n ## If FLAVOR is wrong\n if verbosely:\n log.info(f'ignoring: {reqpath} -- {flavor} not a flavor we care about')\n else:\n log.info(f'{exp}: skipped -- not science')\n return None\n\n if 'OBSTYPE' not in req_dict.keys():\n ## If no obstype is defines, skip it\n if verbosely:\n log.info(f'ignoring: {reqpath} -- {flavor} flavor but obstype not defined')\n else:\n log.info(f'{exp}: skipped -- obstype not given')\n return None\n else:\n if verbosely:\n log.info(f'using: {reqpath}')\n\n ## If obstype isn't in our list of ones we care about, skip it\n obstype = req_dict['OBSTYPE'].lower()\n if obstype in obstypes:\n ## Look for the data. If it's not there, say so then move on\n datapath = pathjoin(raw_data_dir, night, exp, f'desi-{exp}.fits.fz')\n if not os.path.exists(datapath):\n if verbosely:\n log.info(f'could not find {datapath}! It had obstype={obstype}. Skipping')\n else:\n log.info(f'{exp}: skipped -- data not found')\n return None\n else:\n if verbosely:\n log.info(f'using: {datapath}')\n\n ## Raw data, so ensure it's read only and close right away just to be safe\n hdulist = fits.open(datapath, mode='readonly')\n # log.debug(hdulist.info())\n\n if 'SPEC' in hdulist:\n hdu = hdulist['SPEC']\n if verbosely:\n log.info(\"SPEC found\")\n elif 'SPS' in hdulist:\n hdu = hdulist['SPS']\n if verbosely:\n log.info(\"SPS found\")\n else:\n log.info(f'{exp}: skipped -- \"SPEC\" HDU not found!!')\n hdulist.close()\n return None\n\n header, specs = dict(hdu.header).copy(), hdu.data.copy()\n hdulist.close()\n # log.debug(header)\n # log.debug(specs)\n\n ## Define the column values for the current exposure in a dictionary\n outdict = {}\n for key,default in zip(colnames,coldefaults):\n if key.lower() == 'night':\n continue\n if key in header.keys():\n val = header[key]\n if type(val) is str:\n outdict[key] = val.lower()\n else:\n outdict[key] = val\n else:\n outdict[key] = default\n\n ## Make sure that the night is defined:\n try:\n outdict['NIGHT'] = int(header['NIGHT'])\n except (KeyError, ValueError, TypeError):\n outdict['NIGHT'] = header2night(header)\n\n ## For now assume that all 3 cameras were good for all operating spectrographs\n outdict['SPECTROGRAPHS'] = ''.join([str(spec) for spec in np.sort(specs)])\n outdict['CAMWORD'] = 'a' + outdict['SPECTROGRAPHS']\n\n ## Survey number befined in upper loop based on night\n outdict['SURVEY'] = surveynum\n\n ## As an example of future flag possibilites, flag science exposures are\n ## garbage if less than 60 seconds\n # if header['OBSTYPE'].lower() == 'science' and float(header['EXPTIME']) < 60:\n # outdict['EXPFLAG'] = 2\n # else:\n # outdict['EXPFLAG'] = 0\n outdict['EXPFLAG'] = 0\n\n ## For Things defined in both request and data, if they don't match, flag in the\n ## output file for followup/clarity\n for check in ['OBSTYPE', 'FLAVOR']:\n rval, hval = req_dict[check], header[check]\n if rval != hval:\n log.warning(f'In keyword {check}, request and data header disagree: req:{rval}\\tdata:{hval}')\n outdict['EXPFLAG'] = 1\n outdict['HEADERERR'] = np.append(outdict['HEADERERR'],f'For {check}- req:{rval} but hdu:{hval}|')\n else:\n if verbosely:\n log.info(f'{check} checks out')\n\n ## Special logic for EXPTIME because of real-world variance on order 10's - 100's of ms\n check = 'EXPTIME'\n rval, hval = req_dict[check], header[check]\n if np.abs(float(rval)-float(hval))>0.5:\n log.warning(f'In keyword {check}, request and data header disagree: req:{rval}\\tdata:{hval}')\n outdict['EXPFLAG'] = 1\n outdict['HEADERERR'] = np.append(outdict['HEADERERR'],f'For {check}- req:{rval} but hdu:{hval}|')\n else:\n if verbosely:\n log.info(f'{check} checks out')\n #outdict['COMMENTS'] += '|'\n #outdict['HEADERERR'] += '|'\n\n #cnames,ctypes,cdefs = get_exposure_table_column_defs(return_default_values=True)\n #for nam,typ,deflt in zip(cnames,ctypes,cdefs):\n # if nam not in outdict.keys():\n # outdict[nam] = deflt\n \n log.info(f'Done summarizing exposure: {exp}')\n return outdict\n\n","sub_path":"py/desispec/workflow/exptable.py","file_name":"exptable.py","file_ext":"py","file_size_in_byte":21157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641809918","text":"#105\n\"\"\"\nDefinition for singly-linked list with a random pointer.\nclass RandomListNode:\n def __init__(self, x):\n self.label = x\n self.next = None\n self.random = None\n\"\"\"\ndef copy_link_list(head):\n if(head == None):\n return None\n\n cursor = head\n while(cursor != None):\n _clone_node = RandomListNode(cursor.val)\n _clone_node.next = cursor.next\n cursor.next = _clone_node\n cursor = _clone_node.next\n \n cursor = head\n while(cursor != None):\n _cloned = cursor.next\n if(cursor.random != None):\n _cloned.random = cursor.random.next\n cursor = cursor.next.next\n\n _cloned_head = head.next\n cursor_clone = _cloned_head\n cursor_origin = head\n\n while(cursor_origin != None):\n _clone_next = cursor_clone.next.next if cursor_clone.next != None else None\n _origin_next = cursor_origin.next.next\n cursor_origin.next = _origin_next\n cursor_clone.next = _clone_next \n\n cursor_origin = _origin_next\n cursor_clone = _clone_next\n\n return _cloned_head\n\n\nclass Solution:\n # @param head: A RandomListNode\n # @return: A RandomListNode\n def copyRandomList(self, head):\n return copy_link_list(head)\n\n ","sub_path":"py/copy_list_with_random_pointer.py","file_name":"copy_list_with_random_pointer.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"256592804","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models\n\n\nclass AccountAnalyticAccount(models.Model):\n _inherit = 'account.analytic.account'\n\n name = fields.Char(string='Analytic Account', index=True, required=True, track_visibility='onchange', default='New')\n code = fields.Char(string='Reference', index=True, track_visibility='onchange', copy=False)\n subscription_ids = fields.One2many('sale.subscription', 'analytic_account_id', string='Subscriptions')\n subscription_count = fields.Integer(compute='_compute_subscription_count', string='Susbcription Count')\n\n def _compute_subscription_count(self):\n subscription_data = self.env['sale.subscription'].read_group(domain=[('analytic_account_id', 'in', self.ids)],\n fields=['analytic_account_id'],\n groupby=['analytic_account_id'])\n mapped_data = dict([(m['analytic_account_id'][0], m['analytic_account_id_count']) for m in subscription_data])\n for account in self:\n account.subscription_count = mapped_data.get(account.id, 0)\n\n @api.multi\n def subscriptions_action(self):\n subscription_ids = self.mapped('subscription_ids').ids\n result = {\n \"type\": \"ir.actions.act_window\",\n \"res_model\": \"sale.subscription\",\n \"views\": [[False, \"tree\"], [False, \"form\"]],\n \"domain\": [[\"id\", \"in\", subscription_ids]],\n \"context\": {\"create\": False},\n \"name\": \"Subscriptions\",\n }\n if len(subscription_ids) == 1:\n result['views'] = [(False, \"form\")]\n result['res_id'] = subscription_ids[0]\n return result\n","sub_path":"sale_contract/models/account_analytic_account.py","file_name":"account_analytic_account.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"286023036","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n# from django.conf import settings\nfrom rest_framework import serializers\nfrom apps.users.models import User\n\n\nfrom apps.notes.models import Comment\n\nfrom apps.users.serializers.user import UserField\n\n\nclass AddCommentSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n commented_by = UserField(required=False)\n comment_date = serializers.DateField(required=False)\n parent_id = serializers.IntegerField(required=False)\n modified_by = UserField(required=False)\n modified_on = serializers.DateField(required=False)\n\n def validate(self, data):\n if self.context.method != 'PUT':\n if not data.get('comment_date') or not data.get('commented_by'):\n raise serializers.ValidationError('Comment Date or Commented by is missing')\n user_obj = User.objects.filter(id=data.get('commented_by')).first()\n if not user_obj:\n raise serializers.ValidationError('This user is not present')\n else:\n if not data.get('modified_by') or not data.get('modified_on') or not data.get('id'):\n raise serializers.ValidationError('Modified Date or Modified by or id is missing')\n user_obj = User.objects.filter(id=data.get('modified_by')).first()\n if not user_obj:\n raise serializers.ValidationError('This user is not present')\n return data\n\n class Meta:\n model = Comment\n fields = (\n '__all__'\n )\n","sub_path":"apps/notes/serializers/add_comment.py","file_name":"add_comment.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"521890763","text":"#!/usr/bin/env python3\n\n\n__doc__ = '''\nYêu cầu:\n- Lưu file ``https://raw.githubusercontent.com/hvnsweeting/states/master/salt/event/init.sls`` về máy với tên event.yaml\n\n- Dùng pip cài thư viện PyYAML, import yaml và dùng `yaml.load` để biến nội\ndung trong file thành kiểu dữ liệu trên Python.\n\n- In ra số phần tử của kiểu dữ liệu vừa tạo. Dùng thư viện json để\n `json.dump` nội dung, ghi ra một file tên là event.json trong thư mục hiện tại.\n\n- Dùng thư viện pickle để pickle.dump nội dung trên ra file event.pkl trong\n thư mục hiện tại. Chú ý khi mở file, phải mở ở chế độ ghi ở dạng binary. Đọc\n thêm tại đây:\n https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files`\n\n- In ra kích thước của mỗi file đã tạo.\n\nGợi ý: sử dụng os.stat(filename).st_size\n''' # NOQA\n\n\nimport json # NOQA\nimport os # NOQA\nimport pickle # NOQA\nimport yaml # NOQA\n\n\ndef read_write():\n '''Trả về số phần tử của kiểu dữ liệu sau khi dùng module `yaml` để load\n\n Thực hiện các yêu cầu tại ``__doc__``\n\n :rtype int:\n '''\n # Sửa tên và function cho phù hợp, trả về kết quả yêu cầu.\n # Xoá dòng sau và viết code vào đây set các giá trị phù hợp\n file_path = os.path.join(os.path.dirname(__file__), 'event.yaml')\n with open(file_path, 'r') as f:\n data = yaml.load(f.read())\n\n print(len(data))\n print_size('event.yaml')\n\n json_data = json.dumps(data)\n with open(os.path.join(os.path.dirname(__file__), 'event.json'), 'w') as f:\n f.write(json_data)\n\n print_size('event.json')\n\n pickle_data = pickle.dumps(data)\n with open(os.path.join(os.path.dirname(__file__), 'event.pkl'), 'wb') as f:\n f.write(pickle_data)\n\n print_size('event.pkl')\n return data\n\n\ndef print_size(filename):\n path_file = os.path.join(os.path.dirname(__file__), filename)\n print(os.stat(path_file).st_size)\n\n\ndef solve():\n '''Học viên không cần viết code trong hàm `solve`, chỉ thực hiện\n đổi tên lại function của mình cho phù hợp\n\n :rtype int:\n '''\n result = read_write()\n\n return result\n\n\ndef main():\n print(solve())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Ex7/ex7_3.py","file_name":"ex7_3.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"417477573","text":"n = 19\nSum = 0\nsovuanhap = []\nwhile ( True):\n m = int(input(\"Nhap vao mot so:\"))\n if(m > n):\n print(\"So ban vua nhap lon hon so can tim\")\n if(m not in sovuanhap):\n Sum += 1\n sovuanhap.append(m)\n elif( m < n):\n print(\"So ban vua nhap nho hon so can tim\")\n if(m not in sovuanhap):\n Sum += 1\n sovuanhap.append(m)\n else:\n print(f\"Ban nhap chinh xac,so can tim la {n}\")\n Sum += 1\n print(f\"Ban vua nhap {Sum} lan\")\n break","sub_path":"lession 3/Basic/Ex6.py","file_name":"Ex6.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"270218456","text":"\"\"\"\nParser for botocore shape files.\n\"\"\"\nfrom typing import Dict, List, Any, Optional\n\nfrom boto3.session import Session\nfrom boto3.resources.model import Collection\nfrom botocore.exceptions import UnknownServiceError\nfrom botocore import xform_name\nfrom botocore.session import Session as BotocoreSession\nfrom botocore.model import (\n Shape,\n OperationModel,\n ServiceModel,\n StructureShape,\n MapShape,\n ListShape,\n StringShape,\n)\n\nfrom mypy_boto3_builder.service_name import ServiceName, ServiceNameCatalog\nfrom mypy_boto3_builder.structures.argument import Argument\nfrom mypy_boto3_builder.structures.method import Method\nfrom mypy_boto3_builder.import_helpers.import_string import ImportString\nfrom mypy_boto3_builder.type_annotations.fake_annotation import FakeAnnotation\nfrom mypy_boto3_builder.type_annotations.type import Type\nfrom mypy_boto3_builder.type_annotations.type_subscript import TypeSubscript\nfrom mypy_boto3_builder.type_annotations.type_literal import TypeLiteral\nfrom mypy_boto3_builder.type_annotations.type_constant import TypeConstant\nfrom mypy_boto3_builder.type_annotations.external_import import ExternalImport\nfrom mypy_boto3_builder.type_annotations.internal_import import InternalImport\nfrom mypy_boto3_builder.type_annotations.type_typed_dict import TypeTypedDict\nfrom mypy_boto3_builder.logger import get_logger\nfrom mypy_boto3_builder.type_maps.method_type_map import get_method_type_stub\nfrom mypy_boto3_builder.type_maps.typed_dicts import (\n waiter_config_type,\n paginator_config_type,\n)\n\n\nclass ShapeParserError(Exception):\n pass\n\n\nclass ShapeParser:\n \"\"\"\n Parser for botocore shape files.\n\n Arguments:\n session -- Boto3 session.\n service_name -- ServiceName.\n \"\"\"\n\n # Type map for shape types.\n SHAPE_TYPE_MAP = {\n \"integer\": Type.int,\n \"long\": Type.int,\n \"boolean\": Type.bool,\n \"double\": Type.float,\n \"float\": Type.float,\n \"timestamp\": ExternalImport(ImportString(\"datetime\"), \"datetime\"),\n \"blob\": TypeSubscript(Type.Union, [Type.bytes, Type.IO]),\n }\n\n # Alias map fixes added by botocore for documentation build.\n # https://github.com/boto/botocore/blob/develop/botocore/handlers.py#L773\n # https://github.com/boto/botocore/blob/develop/botocore/handlers.py#L1055\n ARGUMENT_ALIASES: Dict[str, Dict[str, Dict[str, str]]] = {\n ServiceNameCatalog.cloudsearchdomain.boto3_name: {\n \"Search\": {\"return\": \"returnFields\"}\n },\n ServiceNameCatalog.logs.boto3_name: {\"CreateExportTask\": {\"from\": \"fromTime\"}},\n ServiceNameCatalog.ec2.boto3_name: {\"*\": {\"Filter\": \"Filters\"}},\n ServiceNameCatalog.s3.boto3_name: {\n \"PutBucketAcl\": {\"ContentMD5\": \"None\"},\n \"PutBucketCors\": {\"ContentMD5\": \"None\"},\n \"PutBucketLifecycle\": {\"ContentMD5\": \"None\"},\n \"PutBucketLogging\": {\"ContentMD5\": \"None\"},\n \"PutBucketNotification\": {\"ContentMD5\": \"None\"},\n \"PutBucketPolicy\": {\"ContentMD5\": \"None\"},\n \"PutBucketReplication\": {\"ContentMD5\": \"None\"},\n \"PutBucketRequestPayment\": {\"ContentMD5\": \"None\"},\n \"PutBucketTagging\": {\"ContentMD5\": \"None\"},\n \"PutBucketVersioning\": {\"ContentMD5\": \"None\"},\n \"PutBucketWebsite\": {\"ContentMD5\": \"None\"},\n \"PutObjectAcl\": {\"ContentMD5\": \"None\"},\n },\n }\n\n def __init__(self, session: Session, service_name: ServiceName):\n loader = session._loader # pylint: disable=protected-access\n botocore_session: BotocoreSession = session._session # pylint: disable=protected-access\n service_data = botocore_session.get_service_data(service_name.boto3_name)\n self.service_name = service_name\n self.service_model = ServiceModel(service_data, service_name.boto3_name)\n self._typed_dict_map: Dict[str, TypeTypedDict] = {}\n self._waiters_shape: Shape = {}\n try:\n self._waiters_shape = loader.load_service_model(\n service_name.boto3_name, \"waiters-2\"\n )\n except UnknownServiceError:\n pass\n self._paginators_shape: Shape = {}\n try:\n self._paginators_shape = loader.load_service_model(\n service_name.boto3_name, \"paginators-1\"\n )\n except UnknownServiceError:\n pass\n self._resources_shape: Shape = {}\n try:\n self._resources_shape = loader.load_service_model(\n service_name.boto3_name, \"resources-1\"\n )\n except UnknownServiceError:\n pass\n\n self.logger = get_logger()\n\n def _get_operation(self, name: str) -> OperationModel:\n return self.service_model.operation_model(name)\n\n def _get_operation_names(self) -> List[str]:\n return list(\n self.service_model.operation_names\n ) # pylint: disable=not-an-iterable\n\n def _get_paginator(self, name: str) -> Shape:\n try:\n return self._paginators_shape[\"pagination\"][name]\n except KeyError:\n raise ShapeParserError(f\"Unknown paginator: {name}\")\n\n def _get_service_resource(self) -> Shape:\n return self._resources_shape[\"service\"]\n\n def _get_resource_shape(self, name: str) -> Shape:\n try:\n return self._resources_shape[\"resources\"][name]\n except KeyError:\n raise ShapeParserError(f\"Unknown resource: {name}\")\n\n def get_paginator_names(self) -> List[str]:\n \"\"\"\n Get available paginator names.\n\n Returns:\n A list of paginator names.\n \"\"\"\n result: List[str] = []\n for name in self._paginators_shape.get(\"pagination\", []):\n result.append(name)\n result.sort()\n return result\n\n def _get_argument_alias(self, operation_name: str, argument_name: str) -> str:\n service_map = self.ARGUMENT_ALIASES.get(self.service_name.boto3_name)\n if not service_map:\n return argument_name\n\n operation_map: Dict[str, str] = {}\n if \"*\" in service_map:\n operation_map = service_map[\"*\"]\n if operation_name in service_map:\n operation_map = service_map[operation_name]\n\n if not operation_map:\n return argument_name\n\n if argument_name not in operation_map:\n return argument_name\n\n return operation_map[argument_name]\n\n def _parse_arguments(\n self,\n class_name: str,\n method_name: str,\n operation_name: str,\n shape: StructureShape,\n ) -> List[Argument]:\n result: List[Argument] = []\n required = shape.required_members\n for argument_name, argument_shape in shape.members.items():\n argument_alias = self._get_argument_alias(operation_name, argument_name)\n if argument_alias == \"None\":\n continue\n\n argument_type_stub = get_method_type_stub(\n self.service_name, class_name, method_name, argument_name\n )\n if argument_type_stub is not None:\n argument_type = argument_type_stub\n else:\n argument_type = self._parse_shape(argument_shape)\n argument = Argument(argument_alias, argument_type)\n if argument_name not in required:\n argument.default = Type.none\n result.append(argument)\n\n result.sort(key=lambda x: not x.required)\n return result\n\n def _parse_return_type(\n self, class_name: str, method_name: str, shape: Optional[Shape]\n ) -> FakeAnnotation:\n argument_type_stub = get_method_type_stub(\n self.service_name, class_name, method_name, \"return\"\n )\n if argument_type_stub is not None:\n return argument_type_stub\n\n if shape:\n return self._parse_shape(shape)\n\n return Type.none\n\n def get_client_method_map(self) -> Dict[str, Method]:\n \"\"\"\n Get client methods from shape.\n\n Returns:\n A map of method name to Method.\n \"\"\"\n result: Dict[str, Method] = {\n \"can_paginate\": Method(\n \"can_paginate\",\n [Argument(\"self\", None), Argument(\"operation_name\", Type.str)],\n Type.bool,\n ),\n \"generate_presigned_url\": Method(\n \"generate_presigned_url\",\n [\n Argument(\"self\", None),\n Argument(\"ClientMethod\", Type.str),\n Argument(\"Params\", Type.DictStrAny, Type.none),\n Argument(\"ExpiresIn\", Type.int, TypeConstant(3600)),\n Argument(\"HttpMethod\", Type.str, Type.none),\n ],\n Type.str,\n ),\n }\n for operation_name in self._get_operation_names():\n operation_model = self._get_operation(operation_name)\n arguments: List[Argument] = [Argument(\"self\", None)]\n method_name = xform_name(operation_name)\n\n if operation_model.input_shape is not None:\n arguments.extend(\n self._parse_arguments(\n \"Client\",\n method_name,\n operation_name,\n operation_model.input_shape,\n )\n )\n\n return_type = self._parse_return_type(\n \"Client\", method_name, operation_model.output_shape\n )\n\n method = Method(\n name=method_name, arguments=arguments, return_type=return_type\n )\n result[method.name] = method\n\n return result\n\n @staticmethod\n def _parse_shape_string(shape: StringShape) -> FakeAnnotation:\n if not shape.enum:\n return Type.str\n\n type_literal = TypeLiteral()\n for option in shape.enum:\n type_literal.add_literal_child(option)\n\n return type_literal\n\n def _parse_shape_map(self, shape: MapShape) -> FakeAnnotation:\n type_subscript = TypeSubscript(Type.Dict)\n if shape.key:\n type_subscript.add_child(self._parse_shape(shape.key))\n else:\n type_subscript.add_child(Type.str)\n if shape.value:\n type_subscript.add_child(self._parse_shape(shape.value))\n else:\n type_subscript.add_child(Type.Any)\n return type_subscript\n\n def _parse_shape_structure(self, shape: StructureShape) -> FakeAnnotation:\n if not shape.members.items():\n return Type.DictStrAny\n\n required = shape.required_members\n typed_dict_name = f\"{shape.name}TypeDef\"\n if typed_dict_name in self._typed_dict_map:\n return self._typed_dict_map[typed_dict_name]\n typed_dict = TypeTypedDict(typed_dict_name)\n self._typed_dict_map[typed_dict_name] = typed_dict\n for attr_name, attr_shape in shape.members.items():\n typed_dict.add_attribute(\n attr_name, self._parse_shape(attr_shape), attr_name in required,\n )\n return typed_dict\n\n def _parse_shape_list(self, shape: ListShape) -> FakeAnnotation:\n type_subscript = TypeSubscript(Type.List)\n if shape.member:\n type_subscript.add_child(self._parse_shape(shape.member))\n else:\n type_subscript.add_child(Type.Any)\n return type_subscript\n\n def _parse_shape(self, shape: Shape) -> FakeAnnotation:\n if shape.type_name in self.SHAPE_TYPE_MAP:\n return self.SHAPE_TYPE_MAP[shape.type_name]\n\n if isinstance(shape, StringShape):\n return self._parse_shape_string(shape)\n\n if isinstance(shape, MapShape):\n return self._parse_shape_map(shape)\n\n if isinstance(shape, StructureShape):\n return self._parse_shape_structure(shape)\n\n if isinstance(shape, ListShape):\n return self._parse_shape_list(shape)\n\n if shape.type_name in self._resources_shape[\"resources\"]:\n return InternalImport(shape.type_name)\n\n self.logger.warning(f\"Unknown shape: {shape}\")\n return Type.Any\n\n def get_paginate_method(self, paginator_name: str) -> Method:\n \"\"\"\n Get Paginator `paginate` method.\n\n Arguments:\n paginator_name -- Paginator name.\n\n Returns:\n Method.\n \"\"\"\n operation_name = paginator_name\n paginator_shape = self._get_paginator(paginator_name)\n operation_shape = self._get_operation(operation_name)\n skip_argument_names: List[str] = []\n input_token = paginator_shape[\"input_token\"]\n if isinstance(input_token, list):\n skip_argument_names.extend(input_token)\n else:\n skip_argument_names.append(input_token)\n if \"limit_key\" in paginator_shape:\n skip_argument_names.append(paginator_shape[\"limit_key\"])\n\n arguments: List[Argument] = [Argument(\"self\", None)]\n\n if operation_shape.input_shape is not None:\n for argument in self._parse_arguments(\n \"Paginator\", \"paginate\", operation_name, operation_shape.input_shape\n ):\n if argument.name in skip_argument_names:\n continue\n arguments.append(argument)\n\n arguments.append(Argument(\"PaginationConfig\", paginator_config_type, Type.none))\n\n return_type: FakeAnnotation = Type.none\n if operation_shape.output_shape is not None:\n return_type = TypeSubscript(\n Type.Generator,\n [\n self._parse_return_type(\n \"Paginator\", \"paginate\", operation_shape.output_shape\n ),\n Type.none,\n Type.none,\n ],\n )\n\n return Method(\"paginate\", arguments, return_type)\n\n def get_wait_method(self, waiter_name: str) -> Method:\n \"\"\"\n Get Waiter `wait` method.\n\n Arguments:\n waiter_name -- Waiter name.\n\n Returns:\n Method.\n \"\"\"\n operation_name = self._waiters_shape[\"waiters\"][waiter_name][\"operation\"]\n operation_shape = self._get_operation(operation_name)\n\n arguments: List[Argument] = [Argument(\"self\", None)]\n\n if operation_shape.input_shape is not None:\n arguments.extend(\n self._parse_arguments(\n \"Waiter\", \"wait\", operation_name, operation_shape.input_shape\n )\n )\n\n arguments.append(Argument(\"WaiterConfig\", waiter_config_type, Type.none))\n\n return Method(name=\"wait\", arguments=arguments, return_type=Type.none)\n\n def get_service_resource_method_map(self) -> Dict[str, Method]:\n \"\"\"\n Get methods for ServiceResource.\n\n Returns:\n A map of method name to Method.\n \"\"\"\n result: Dict[str, Method] = {\n \"get_available_subresources\": Method(\n \"get_available_subresources\",\n [Argument(\"self\", None)],\n TypeSubscript(Type.List, [Type.str]),\n ),\n }\n service_resource_shape = self._get_service_resource()\n for action_name, action_shape in service_resource_shape.get(\n \"actions\", {}\n ).items():\n method = self._get_resource_method(\n \"ServiceResource\", action_name, action_shape\n )\n result[method.name] = method\n\n return result\n\n def get_resource_method_map(self, resource_name: str) -> Dict[str, Method]:\n \"\"\"\n Get methods for Resource.\n\n Arguments:\n resource_name -- Resource name.\n\n Returns:\n A map of method name to Method.\n \"\"\"\n resource_shape = self._get_resource_shape(resource_name)\n result: Dict[str, Method] = {\n \"get_available_subresources\": Method(\n \"get_available_subresources\",\n [Argument(\"self\", None)],\n TypeSubscript(Type.List, [Type.str]),\n ),\n \"load\": Method(\"load\", [Argument(\"self\", None)], Type.none),\n \"reload\": Method(\"reload\", [Argument(\"self\", None)], Type.none),\n }\n\n for action_name, action_shape in resource_shape.get(\"actions\", {}).items():\n method = self._get_resource_method(resource_name, action_name, action_shape)\n result[method.name] = method\n\n for waiter_name in resource_shape.get(\"waiters\", {}):\n method = Method(\n f\"wait_until_{xform_name(waiter_name)}\",\n [Argument(\"self\", None)],\n Type.none,\n )\n result[method.name] = method\n\n return result\n\n def _get_resource_method(\n self, resource_name: str, action_name: str, action_shape: Dict[str, Any]\n ) -> Method:\n return_type: FakeAnnotation = Type.none\n method_name = xform_name(action_name)\n arguments: List[Argument] = [Argument(\"self\", None)]\n if \"resource\" in action_shape:\n return_type = self._parse_return_type(\n resource_name, method_name, Shape(\"resource\", action_shape[\"resource\"])\n )\n\n if \"request\" in action_shape:\n operation_name = action_shape[\"request\"][\"operation\"]\n operation_shape = self._get_operation(operation_name)\n skip_argument_names: List[str] = [\n i[\"target\"]\n for i in action_shape[\"request\"].get(\"params\", {})\n if i[\"source\"] == \"identifier\"\n ]\n if operation_shape.input_shape is not None:\n for argument in self._parse_arguments(\n resource_name,\n method_name,\n operation_name,\n operation_shape.input_shape,\n ):\n if argument.name not in skip_argument_names:\n arguments.append(argument)\n if operation_shape.output_shape is not None:\n return_type = self._parse_shape(operation_shape.output_shape)\n\n return Method(name=method_name, arguments=arguments, return_type=return_type)\n\n def get_collection_filter_method(self, name: str, collection: Collection) -> Method:\n \"\"\"\n Get `filter` classmethod for Resource collection.\n\n Arguments:\n name -- Collection record name.\n collection -- Boto3 Collection.\n\n Returns:\n Filter Method record.\n \"\"\"\n arguments: List[Argument] = [Argument(\"cls\", None)]\n result = Method(\n \"filter\",\n arguments,\n InternalImport(name=name, service_name=self.service_name),\n decorators=[Type.classmethod],\n )\n if not collection.request:\n return result\n\n operation_name = collection.request.operation\n operation_model = self._get_operation(operation_name)\n\n if operation_model.input_shape is not None:\n for argument in self._parse_arguments(\n name, result.name, operation_name, operation_model.input_shape,\n ):\n if argument.required:\n continue\n arguments.append(argument)\n\n return result\n\n def get_collection_batch_methods(\n self, name: str, collection: Collection\n ) -> List[Method]:\n \"\"\"\n Get batch operations for Resource collection.\n\n Arguments:\n name -- Collection record name.\n collection -- Boto3 Collection.\n\n Returns:\n List of Method records.\n \"\"\"\n result = []\n for batch_action in collection.batch_actions:\n method = Method(\n batch_action.name,\n [Argument(\"cls\", None)],\n Type.none,\n decorators=[Type.classmethod],\n )\n result.append(method)\n if batch_action.request:\n operation_name = batch_action.request.operation\n operation_model = self._get_operation(operation_name)\n if operation_model.input_shape is not None:\n for argument in self._parse_arguments(\n name,\n batch_action.name,\n operation_name,\n operation_model.input_shape,\n ):\n if argument.required:\n continue\n method.arguments.append(argument)\n if operation_model.output_shape is not None:\n return_type = self._parse_shape(operation_model.output_shape)\n method.return_type = return_type\n\n return result\n","sub_path":"builder/mypy_boto3_builder/parsers/shape_parser.py","file_name":"shape_parser.py","file_ext":"py","file_size_in_byte":20890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"513624828","text":"# Import Statements\nimport sys\nsys.path.append('../')\nimport csv\nfrom absl import app, flags\nimport collections\nimport constants_mimic3\nfrom constants_mimic3 import MIMIC_3_DIR, MIMIC_3_DIR_VM,PROJECT_DIR, PROJECT_DIR_VM\nfrom inference_and_metrics import metrics, inference\nimport datasetloader_mimic3_bert as datasetloader_mimic3\n\nimport torch as th\nimport torch.nn as nn\nimport pytorch_lightning as pl\nimport torchmetrics\nimport transformers\nimport matplotlib.pyplot as plot\nfrom sklearn.model_selection import KFold\nfrom pytorch_lightning.loggers import TensorBoardLogger\nfrom pytorch_lightning.callbacks import EarlyStopping\nfrom utils import save_model, save_results\nfrom label_attention.label_attention_classifier import LabelAttention\nfrom label_attention.label_embedder import LabelEmbedder\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\n# Define flags\nFLAGS = flags.FLAGS\n# Model related flags\nflags.DEFINE_boolean('training', None, 'Indicate whether to train or test model')\nflags.DEFINE_boolean('Dataset_full', None, 'Choose Full Dataset or Top 50 codes, default full dataset')\nflags.DEFINE_boolean('local',None, '')\nflags.DEFINE_boolean('debug',None, '')\nflags.DEFINE_boolean('inference',None, '')\nflags.DEFINE_integer('k_folds', 5, '')\nflags.DEFINE_boolean('lr_finder',None, '')\nflags.DEFINE_integer('epochs', 25, '')\nflags.DEFINE_integer('batch_size', 4, '') # old=2\nflags.DEFINE_float('lr', 1.41e-5, '') #old=1e-5\nflags.DEFINE_boolean('freeze_longformer', None, '')\nnum_classes = 50 #8921\n\n# data related flags: All codes\nflags.DEFINE_string('dev_full_lm', constants_mimic3.dev_full_lm, 'Path to dev dataset lm ')\nflags.DEFINE_string('dev_full_vm', constants_mimic3.dev_full_vm, 'Path to dev dataset vm')\nflags.DEFINE_string('train_full_lm', constants_mimic3.train_full_lm, 'Path to train dataset lm ')\nflags.DEFINE_string('train_full_vm', constants_mimic3.train_full_vm, 'Path to train dataset vm')\nflags.DEFINE_string('test_full_lm', constants_mimic3.test_full_lm, 'Path to test dataset lm ')\nflags.DEFINE_string('test_full_vm', constants_mimic3.test_full_vm, 'Path to test dataset vm')\n# data related flags: Top 50 codes\nflags.DEFINE_string('dev_50_lm', constants_mimic3.dev_50_lm, 'Path to dev top_50 dataset lm ')\nflags.DEFINE_string('dev_50_vm', constants_mimic3.dev_50_vm, 'Path to dev top_50 ataset vm')\nflags.DEFINE_string('train_50_lm', constants_mimic3.train_50_lm, 'Path to train top_50 dataset lm ')\nflags.DEFINE_string('train_50_vm', constants_mimic3.train_50_vm, 'Path to train top_50 dataset vm')\nflags.DEFINE_string('test_50_lm', constants_mimic3.test_50_lm, 'Path to test top_50 dataset lm ')\nflags.DEFINE_string('test_50_vm', constants_mimic3.test_50_vm, 'Path to test top_50 dataset vm')\n\n# label embedding related flags\nflags.DEFINE_string('model_w2v_lm', constants_mimic3.word2vec_model_lm, 'pre-trained w2v model on all labels lm')\nflags.DEFINE_string('model_w2v_vm', constants_mimic3.word2vec_model_vm, 'pre-trained w2v model on all labels vm')\nflags.DEFINE_string('labels_desc_dict_lm', constants_mimic3.full_codes_desc_dict_lm, 'dict including all labels with coressponding textual description lm ')\nflags.DEFINE_string('labels_desc_dict_vm', constants_mimic3.full_codes_desc_dict_vm, 'dict including all labels with coressponding textual description vm ')\nflags.DEFINE_string('top_50_labels_lm', constants_mimic3.labels_top_50_lm , 'top_50 labels used in order of MLB lm')\nflags.DEFINE_string('top_50_labels_vm', constants_mimic3.labels_top_50_vm , 'top_50 labels used in order of MLB vm')\nflags.DEFINE_string('full_labels_lm', constants_mimic3.labels_full_lm , 'full labels used in order of MLB lm')\nflags.DEFINE_string('full_labels_vm', constants_mimic3.labels_full_vm , 'full labels used in order of MLB vm')\n\n\n\nflags.mark_flag_as_required('training')\nflags.mark_flag_as_required('Dataset_full')\nflags.mark_flag_as_required('local')\nflags.mark_flag_as_required('debug')\nflags.mark_flag_as_required('inference')\nflags.mark_flag_as_required('lr_finder')\nflags.mark_flag_as_required('freeze_longformer')\n\n\n\n\nclass classifier(pl.LightningModule):\n\n def __init__(self):\n super().__init__()\n # Instantiate Longformer Model accordingly wheter parameters are freezed or not\n if FLAGS.freeze_longformer == True:\n self.model = transformers.BertModel.from_pretrained('bert-base-uncased', gradient_checkpointing=True, output_hidden_states=True, return_dict=True)\n for p in self.model.parameters():\n p.requires_grad = False\n else:\n self.model = transformers.BertModel.from_pretrained('bert-base-uncased',gradient_checkpointing=True, output_hidden_states=True, return_dict=True)\n\n # Instantiate Label Embedding\n if FLAGS.Dataset_full == True:\n full_labels = FLAGS.full_labels_lm if FLAGS.local else FLAGS.full_labels_vm\n else:\n top_50_labels = FLAGS.top_50_labels_lm if FLAGS.local else FLAGS.top_50_labels_vm\n label_embedder = LabelEmbedder(FLAGS.model_w2v_lm if FLAGS.local else FLAGS.model_w2v_vm, FLAGS.labels_desc_dict_lm if FLAGS.local else FLAGS.labels_desc_dict_vm, full_labels if FLAGS.Dataset_full else top_50_labels)\n self.label_embedding = label_embedder.initialize_label_embedding()\n\n # Instantiate Label Attention Layer\n self.label_att = LabelAttention(hidden_size= 768, label_embed_size=self.label_embedding.weight.size(1) ,dropout_rate=0.1)\n\n # Instantiate FCN for classifier\n self.fcs = nn.ModuleList([nn.Linear(768, 1) for code in range(num_classes)])\n\n # Instantiate loss function and other metrics\n self.loss = th.nn.BCEWithLogitsLoss()\n self.accuracy = torchmetrics.Accuracy()\n self.accuracy_subset = torchmetrics.Accuracy(subset_accuracy=True)\n\n def forward(self, input_ids, attention_mask):\n \"\"\"\n Define forward function of longformer model\n Parameters\n ----------\n input_ids: tensor (batch_size x input_seq_length)\n attention_mask: tensor (batch_size x input_seq_length)\n global_attention_mask: None\n\n Returns\n -------\n logits: tensor (batch_size x num_classes)\n \"\"\"\n output = self.model(input_ids,attention_mask= attention_mask)\n last_hidden_state = output.last_hidden_state\n\n # Compute label wise self attention\n weighted_output, attn_weights= self.label_att.forward(last_hidden_state,self.label_embedding)\n\n # classifier\n outputs = th.zeros((weighted_output.size(0), num_classes))\n outputs = outputs.type_as(weighted_output)\n for code, fc in enumerate(self.fcs):\n outputs[:, code:code + 1] = fc(weighted_output[:, code, :])\n return outputs, attn_weights\n\n def training_step(self, batch, batch_idx):\n \"\"\"\n Training step of longformer model.\n Parameters\n ----------\n batch: tensor (batch_size)\n batch_idx: tensor (batch_idx)\n\n Returns\n -------\n loss: integer\n BCE loss for computed for all labels\n \"\"\"\n logits, _ = self.forward(batch['input_ids'], batch['attention_mask'])\n loss = self.loss(logits, batch['label'])\n self.log(\"train_loss\", loss, on_step=True, on_epoch=True, logger=True)\n return {'loss': loss}\n\n def validation_step(self, batch, batch_idx):\n \"\"\"\n Validation step of longformer model.\n Parameters\n ----------\n batch: tensor (batch_size)\n batch_idx: tensor (batch_idx)\n\n Returns\n -------\n output: OrderedDict (8 items)\n output dictionary containing different metrics for validation step\n \"\"\"\n logits, _ = self.forward(batch['input_ids'], batch['attention_mask'])\n loss = self.loss(logits, batch['label'])\n y_pred, y_true = metrics.prepare_outputs(logits, batch['label'])\n accuracy = self.accuracy(y_pred, y_true)\n accuracy_subset = self.accuracy_subset(y_pred, y_true)\n # outputs\n output = collections.OrderedDict({\n 'val_loss': loss, 'accuracy': accuracy, 'accuracy_subset': accuracy_subset})\n return output\n\n def validation_epoch_end(self, outputs):\n \"\"\"\n Compute the the aggregated output metrics over all epochs of the validation step and log them.\n Parameters\n ----------\n outputs: Ordered dict output of validation step (containing different metrics)\n \"\"\"\n loss = th.stack([x['val_loss'] for x in outputs]).mean()\n accuracy = th.stack([x['accuracy'] for x in outputs]).mean()\n accuracy_subset = th.stack([x['accuracy_subset'] for x in outputs]).mean()\n self.log(\"val_loss\", loss), self.log(\"val_accuracy\", accuracy), self.log(\"val_accuracy_subset\", accuracy_subset)\n\n def test_step(self, batch, batch_idx):\n \"\"\"\n Test step of longformer model.\n Parameters\n ----------\n batch: tensor (batch_size)\n batch_idx: tensor (batch_idx)\n\n Returns\n -------\n output: OrderedDict (8 items)\n output dictionary containing different metrics for test step\n \"\"\"\n logits, _ = self.forward(batch['input_ids'], batch['attention_mask'])\n loss = self.loss(logits, batch['label'])\n y_pred, y_true = metrics.prepare_outputs(logits, batch['label'])\n\n outputs = {'pred':y_pred, 'truth': y_true, 'logits': logits}\n return outputs\n\n def test_epoch_end(self, outputs):\n \"\"\"\n Compute the the aggregated output metrics over all epochs of the test step and log them.\n Parameters\n ----------\n outputs: Ordered dict output of test step (containing different metrics)\n \"\"\"\n logits = th.cat([x['logits'] for x in outputs], dim=0)\n y_pred = th.cat([x['pred']for x in outputs], dim=0)\n y_true = th.cat([x['truth'] for x in outputs], dim=0)\n # calculate all metrics\n results = metrics.all_metrics(y_pred, y_true, logits, num_classes, top_k=5)\n self.log(\"Results\", results)\n return results\n\n def test_dataloader(self):\n \"\"\"\n Loads the test dataset for the test step.\n Returns\n -------\n datatset: returns the full_test_dataset or the top_50_test_dataset\n \"\"\"\n if FLAGS.Dataset_full == True:\n test_full_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.test_full_lm if FLAGS.local else FLAGS.test_full_vm, mode=True if FLAGS.inference else False)\n else:\n test_50_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.test_50_lm if FLAGS.local else FLAGS.test_50_vm, mode=True if FLAGS.inference else False)\n test_ds = test_full_ds if FLAGS.Dataset_full else test_50_ds\n\n # print shape of test_ds\n datasetloader_mimic3.print_dataset(test_ds)\n\n return th.utils.data.DataLoader(test_ds, batch_size=FLAGS.batch_size, drop_last=True, shuffle=False, num_workers=4, pin_memory=True)\n\n def configure_optimizers(self):\n \"\"\"\n Configuring the optmimizer for the model.\n \"\"\"\n optimizer = th.optim.Adam(\n self.parameters(),\n lr=FLAGS.lr)\n\n scheduler = th.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer,\n patience=1,\n verbose=True)\n return {\n 'optimizer': optimizer,\n 'lr_scheduler': scheduler, # Changed scheduler to lr_scheduler\n 'monitor': 'val_loss'\n }\n\n\ndef main(_):\n # retrieve train_full_kfold_ds or train_50_kfold_ds for training\n if FLAGS.inference == False:\n if FLAGS.Dataset_full == True:\n dev_full_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.dev_full_lm if FLAGS.local else FLAGS.dev_full_vm, mode=True if FLAGS.inference else False)\n train_full_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.train_full_lm if FLAGS.local else FLAGS.train_full_vm, mode=True if FLAGS.inference else False)\n datasets_full = [dev_full_ds, train_full_ds]\n train_full_kfold_ds = th.utils.data.ConcatDataset(datasets_full)\n\n else:\n dev_50_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.dev_50_lm if FLAGS.local else FLAGS.dev_50_vm, mode=True if FLAGS.inference else False)\n train_50_ds = datasetloader_mimic3.MimicIII_Dataloader(FLAGS.train_50_lm if FLAGS.local else FLAGS.train_50_vm, mode=True if FLAGS.inference else False)\n datasets_50 = [dev_50_ds, train_50_ds]\n train_50_kfold_ds = th.utils.data.ConcatDataset(datasets_50)\n\n\n # k fold cross validation\n if FLAGS.training == True:\n # instantiate results list to store test results of every split of k-fold cv\n results_kfold =[]\n # perform k-fold cv\n kfold = KFold(n_splits=FLAGS.k_folds)\n for fold, (train_idx, val_idx) in enumerate(kfold.split(train_full_kfold_ds if FLAGS.Dataset_full else train_50_kfold_ds)):\n\n # Instantiate logger for every split of k-fold cv\n if FLAGS.local == True:\n if FLAGS.Dataset_full == False:\n logger = TensorBoardLogger(\"tb_logs\", name=\"classifier_kfold_50_bert_lac_vm\")\n logger.log_hyperparams(\n {'learning_rate': FLAGS.lr, 'epochs': FLAGS.epochs, 'batch_size': FLAGS.batch_size,\n 'num_labels': num_classes})\n else:\n logger = TensorBoardLogger(\"tb_logs\", name=\"classifier_kfold_full_bert_lac_lm\")\n logger.log_hyperparams(\n {'learning_rate': FLAGS.lr, 'epochs': FLAGS.epochs, 'batch_size': FLAGS.batch_size,\n 'num_labels': num_classes})\n else:\n if FLAGS.Dataset_full == False:\n logger = TensorBoardLogger(\"tb_logs\", name=\"classifier_kfold_50_bert_lac_vm\")\n logger.log_hyperparams(\n {'learning_rate': FLAGS.lr, 'epochs': FLAGS.epochs, 'batch_size': FLAGS.batch_size,\n 'num_labels': num_classes})\n else:\n logger = TensorBoardLogger(\"tb_logs\", name=\"classifier_kfold_50_bert_lac_vm\")\n logger.log_hyperparams(\n {'learning_rate': FLAGS.lr, 'epochs': FLAGS.epochs, 'batch_size': FLAGS.batch_size,\n 'num_labels': num_classes})\n\n # Instantiate model for every split of k-fold cv\n model = classifier()\n\n # Instantiate trainer for every split of k-fold cv\n trainer = pl.Trainer(\n logger=logger,\n gpus=(-1 if th.cuda.is_available() else 0),\n max_epochs=FLAGS.epochs,\n fast_dev_run=FLAGS.debug,\n callbacks=[EarlyStopping(monitor='val_loss', min_delta=0.002, patience=3, mode='min')],\n checkpoint_callback=False,\n accumulate_grad_batches=16, #old config=32\n amp_level='O2')\n\n # print current split\n print(f\"training {fold} of {FLAGS.k_folds} folds ...\")\n\n # split covidx_train further into train and val data\n train_ds = datasetloader_mimic3.TransformableSubset(train_full_kfold_ds if FLAGS.Dataset_full else train_50_kfold_ds, train_idx)\n val_ds = datasetloader_mimic3.TransformableSubset(train_full_kfold_ds if FLAGS.Dataset_full else train_50_kfold_ds, val_idx)\n\n # print shape of train_ds, val_ds\n datasetloader_mimic3.print_dataset(train_ds), datasetloader_mimic3.print_dataset(val_ds)\n\n # instantiate train, val dataloaders\n train_dl = th.utils.data.DataLoader(train_ds,batch_size=FLAGS.batch_size, drop_last=True, shuffle=True, num_workers=4, pin_memory=True)\n val_dl = th.utils.data.DataLoader(val_ds, batch_size=FLAGS.batch_size, drop_last=False, shuffle=False, num_workers=4, pin_memory=True)\n\n # Run learning rate finder\n if FLAGS.lr_finder == True:\n lr_finder = trainer.tuner.lr_find(model, train_dataloader= train_dl, val_dataloaders= val_dl)\n # Plot with\n fig = lr_finder.plot(suggest=True)\n suggested_lr = lr_finder.suggestion()\n print('The suggested learning rate is:', suggested_lr)\n if FLAGS.local:\n plot.savefig(logger.log_dir, format='png')\n else:\n plot.savefig(logger.log_dir,format='png')\n break\n\n # Perform pl training when not in inference mode\n else:\n trainer.fit(model, train_dataloader= train_dl, val_dataloaders= val_dl)\n # iteratively increase max epochs of trainer\n trainer.max_epochs += FLAGS.epochs\n trainer.current_epoch = trainer.current_epoch + 1\n # test current split and retrieve test_results for split of k-fold cv\n results = trainer.test(model)\n results_kfold.append(results)\n\n # save model of current split of k-fold cv\n save_model(model, logger.log_dir, logger.name)\n\n all_metrics = metrics.compute_kfold_metrics(results_kfold, FLAGS.k_folds)\n print(all_metrics)\n save_results(all_metrics, logger.log_dir, logger.name)\n\n else:\n # Perform pl testing when not in inference mode\n model = classifier()\n model.load_state_dict(th.load('%s/model_files/classifier_kfold_50_bert_lac_vm_18_08_2021_07:14:00.pth' % PROJECT_DIR if FLAGS.local else PROJECT_DIR_VM, map_location=th.device('cpu')))\n print(\"Loading model for testing from model state dict\")\n trainer = pl.Trainer(\n logger=False,\n gpus=(1 if th.cuda.is_available() else 0),\n max_epochs=FLAGS.epochs,\n fast_dev_run=FLAGS.debug,\n callbacks=[EarlyStopping(monitor='val_loss', min_delta=0.002, patience=3, mode='min')],\n checkpoint_callback=False,\n accumulate_grad_batches=16,\n amp_level='O2')\n results = trainer.test(model)\n print(results)\n\n\n # Perform inference when in inference mode\n if FLAGS.inference == True:\n # instantiate model\n model = classifier()\n model.load_state_dict(th.load('%s/model_files/classifier_kfold_50_bert_lac_vm_18_08_2021_07:14:00.pth' % PROJECT_DIR if FLAGS.local else PROJECT_DIR_VM, map_location=th.device('cpu')))\n model.eval()\n\n if FLAGS.Dataset_full == True:\n inference_dataset_full = datasetloader_mimic3.MimicIII_Dataloader(constants_mimic3.test_full_lm, mode=True if FLAGS.inference else False)\n dict_full = inference.create_mlb_dict('%s/notes_labeled_binarized.csv' % MIMIC_3_DIR if FLAGS.local else MIMIC_3_DIR_VM)\n else:\n inference_dataset_50 = datasetloader_mimic3.MimicIII_Dataloader(constants_mimic3.test_50_lm, mode=True if FLAGS.inference else False)\n dict_50 = inference.create_mlb_dict('%s/notes_labeled_50_binarized.csv' % MIMIC_3_DIR if FLAGS.local else MIMIC_3_DIR_VM)\n # print samples loaded for inference\n inference.print_inference_set(inference_dataset_full if FLAGS.Dataset_full else inference_dataset_50)\n\n # instantiate imference dataloader -> batch_size setting to 1 important and not to be changed.\n inference_dataloader = th.utils.data.DataLoader(\n inference_dataset_full if FLAGS.Dataset_full else inference_dataset_50,\n batch_size=1,\n drop_last=False,\n shuffle=False)\n\n # instantiate csv writer\n if FLAGS.Dataset_full:\n with open('%s/results/bert_lac/predictions_bert_lac_full.csv' % PROJECT_DIR if FLAGS.local else '%s/results/bert_lac/predictions_bert_lac_full.csv' % PROJECT_DIR_VM,'w') as outfile:\n columns = ['HADM_ID', 'TEXT', 'TOKENIZED_TEXT', 'GROUND_TRUTH', 'PREDICTIONS', 'ATTENTION_INDICES']\n w = csv.DictWriter(outfile, fieldnames=columns)\n w.writeheader()\n else:\n with open(\n '%s/results/bert_lac/predictions_bert_lac_50.csv' % PROJECT_DIR if FLAGS.local else '%s/results/bert_lac/predictions_bert_lac_50.csv' % PROJECT_DIR_VM,\n 'w') as outfile:\n columns = ['HADM_ID', 'TEXT', 'TOKENIZED_TEXT', 'GROUND_TRUTH', 'PREDICTIONS', 'ATTENTION_INDICES']\n w = csv.DictWriter(outfile, fieldnames=columns)\n w.writeheader()\n\n for batch in inference_dataloader:\n logits, attn_weights = model.forward(batch['input_ids'], batch['attention_mask'])\n y_pred, y_true = metrics.prepare_outputs_inference(logits, batch['label'])\n y_pred, y_true = y_pred.squeeze().detach().numpy(), y_true.squeeze().detach().numpy()\n y_pred, y_true = list(y_pred), list(y_true)\n attention_scores = th.squeeze(inference.compute_attention_scores(attn_weights, y_pred))\n if FLAGS.Dataset_full == True:\n predicted_labels, true_labels = inference.predict_ICD_codes(y_pred, y_true, dict_full)\n print(\"The HADM_ID is\", batch['HADM_ID'])\n print(\"The Input text is:\", batch['discharge_summary'])\n print('Predicted labels:', predicted_labels)\n print('True labels:', true_labels)\n else:\n predicted_labels, true_labels = inference.predict_ICD_codes(y_pred, y_true, dict_50)\n print(\"The HADM_ID is\", batch['HADM_ID'])\n print(\"The Input text is:\", batch['discharge_summary'])\n print('Predicted labels:', predicted_labels)\n print('True labels:', true_labels)\n w.writerow({'HADM_ID': batch['HADM_ID'], 'TEXT': batch['discharge_summary'], 'TOKENIZED_TEXT': batch['tokenized_discharge_summary'],'GROUND_TRUTH': true_labels, 'PREDICTIONS': predicted_labels, 'ATTENTION_INDICES':attention_scores})\n outfile.close()\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n app.run(main)\n\n\n\n\n\n#import IPython; IPython.embed();exit(1)\n\n\n\n","sub_path":"bert_lrc/classifier_kfold_bert_lac.py","file_name":"classifier_kfold_bert_lac.py","file_ext":"py","file_size_in_byte":22804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"108277204","text":"matrix = []\ncounter = 0\nposition_i = 0\nposition_j = 0\n\nfor i in range(5):\n matrix.append([int(j) for j in input().split()])\n\nfor i in range(5):\n for j in range(5):\n if matrix[i][j] == 1:\n position_i = i\n position_j = j\n\nif position_i > 2:\n counter = position_i - 2\nelif position_i < 2:\n counter = 2 - position_i\n\nif position_j > 2:\n counter = counter + position_j - 2\nelif position_j < 2:\n counter = counter + (2 - position_j)\n\nprint(counter)\n\n\n\n\n\n\n","sub_path":"codeforces/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"25984337","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport os\r\nimport seaborn as sns\r\nfrom sklearn.preprocessing import Imputer\r\n\r\n# change directory\r\nos.chdir('E:\\\\Programing\\\\UdemyML\\\\Machine Learning A-Z Template Folder\\\\Part 9 - Dimensionality Reduction\\\\Section 43 - Principal Component Analysis (PCA)')\r\ndf = pd.read_csv('Wine.csv')\r\n\r\nx = df.iloc[:,0:13].values\r\ny = df.iloc[:, 13].values\r\n\r\n\r\n# Train test Split\r\nfrom sklearn.model_selection import train_test_split\r\nx_train , x_test , y_train , y_test = train_test_split(x,y,test_size=0.25,random_state=0)\r\n\r\n\r\n# Feature Scaling\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc_x = StandardScaler()\r\nx_train = sc_x.fit_transform(x_train)\r\nx_test = sc_x.transform(x_test)\r\n\r\n# Apply PCA\r\nfrom sklearn.decomposition import PCA\r\npca = PCA(n_components= 2)\r\nx_train=pca.fit_transform(x_train)\r\nx_test = pca.transform(x_test)\r\n\r\n\r\n# Fitting Model\r\nfrom sklearn.linear_model import LogisticRegression\r\ncls = LogisticRegression()\r\ncls.fit(x_train,y_train)\r\n\r\ny_predict = cls.predict(x_test)\r\n\r\n# Confusion Matrix to evaluate our model\r\nfrom sklearn.metrics import confusion_matrix\r\ncm = confusion_matrix(y_test,y_predict)\r\nprint(cm)\r\n\r\n# Visualising the Test set results\r\nfrom matplotlib.colors import ListedColormap\r\n\r\n# create a copy of X_train and y_train\r\n# for code resusability\r\nX_set, y_set = x_train, y_train\r\n# generate coordinate matrics using meshgrid\r\nX1, X2 = np.meshgrid(np.arange(start=X_set[:, 0].min()-1, stop=X_set[:, 0].max()+1, step=0.01),\r\n np.arange(start=X_set[:, 1].min()-1, stop=X_set[:, 1].max()+1, step=0.01))\r\n# now we need to plot the prediction for every coordinate from X1 and X2 therefore we need to first get the prediction from coordinate matrics\r\n# convert X1 coordinate matrix to a flattened array - putting all the elements in one column\r\nX1_ravel = X1.ravel()\r\n# convert X2 coordinate matrix to a flattened array - putting all the elements in one column\r\nX2_ravel = X2.ravel()\r\n# create an array having 2 rows by placing X1_ravel over X2_ravel\r\nX1X2_array = np.array([X1_ravel, X2_ravel])\r\n# Since predict function takes an array which has 2 columns therefore we need to generate Transpose of X1X2_array - columns are converted into rows\r\nX1X2_array_t = X1X2_array.T\r\n# predict result using the classifier\r\nX1X2_pred = cls.predict(X1X2_array_t)\r\n#result of prediction will be used to plot againt the coordinate matrics therefore we need to reshape the result to match the shape of coordinate matrics\r\n#generated array contains prediction for every coordinate value\r\nX1X2_pred_reshape = X1X2_pred.reshape(X1.shape)\r\n#plot the predictions against coordinate matrics using contourf (filled)\r\nresult_plt = plt.contourf(X1, X2, X1X2_pred_reshape,\r\n alpha=0.75,\r\n cmap = ListedColormap(('red', 'green','blue'))\r\n)\r\n#not mandatory\r\nplt.xlim(X1.min(), X1.max())\r\nplt.ylim(X2.min(), X2.max())\r\n#plot the actual points on the graph\r\nfor i, j in enumerate(np.unique(y_set)):\r\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\r\n c = ListedColormap(('red', 'green','blue'))(i), label = j)\r\n#for housekeeping\r\nplt.title('Logistic Regression (Training set)')\r\nplt.xlabel('PC1')\r\nplt.ylabel('PC2')\r\nplt.legend()\r\nplt.show()\r\n\r\n","sub_path":"PCA/PCA+LogReg.py","file_name":"PCA+LogReg.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"167704016","text":"import random\nimport pylab\n\n# Global Variables\nMAXRABBITPOP = 1000\nCURRENTRABBITPOP = 500\nCURRENTFOXPOP = 30\n\ndef rabbitGrowth():\n \"\"\" \n rabbitGrowth is called once at the beginning of each time step.\n\n It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP.\n\n The global variable CURRENTRABBITPOP is modified by this procedure.\n\n For each rabbit, based on the probabilities in the problem set write-up, \n a new rabbit may be born.\n Nothing is returned.\n \"\"\"\n # you need this line for modifying global variables\n global CURRENTRABBITPOP\n\n for r in range(CURRENTRABBITPOP):\n rabbitChance = 1.0 - (float(CURRENTRABBITPOP) / float(MAXRABBITPOP))\n #print float(CURRENTRABBITPOP), float(MAXRABBITPOP), (float(CURRENTRABBITPOP) / float(MAXRABBITPOP)), rabbitChance\n if random.random() < rabbitChance:\n CURRENTRABBITPOP += 1\n \ndef foxGrowth():\n \"\"\" \n foxGrowth is called once at the end of each time step.\n\n It makes use of the global variables: CURRENTFOXPOP and CURRENTRABBITPOP,\n and both may be modified by this procedure.\n\n Each fox, based on the probabilities in the problem statement, may eat \n one rabbit (but only if there are more than 10 rabbits).\n\n If it eats a rabbit, then with a 1/3 prob it gives birth to a new fox.\n\n If it does not eat a rabbit, then with a 1/10 prob it dies.\n\n Nothing is returned.\n \"\"\"\n # you need these lines for modifying global variables\n global CURRENTRABBITPOP\n global CURRENTFOXPOP\n\n for f in range(CURRENTFOXPOP):\n foxEatsChance = (float(CURRENTRABBITPOP) / float(MAXRABBITPOP))\n if CURRENTRABBITPOP > 10 and random.random() < foxEatsChance:\n CURRENTRABBITPOP -= 1\n if random.choice(['X', ' ', ' ']) == 'X':\n CURRENTFOXPOP += 1\n else:\n if CURRENTFOXPOP > 10 and random.random() < 0.1:\n CURRENTFOXPOP -= 1\n \n \ndef runSimulation(numSteps):\n \"\"\"\n Runs the simulation for `numSteps` time steps.\n\n Returns a tuple of two lists: (rabbit_populations, fox_populations)\n where rabbit_populations is a record of the rabbit population at the \n END of each time step, and fox_populations is a record of the fox population\n at the END of each time step.\n\n Both lists should be `numSteps` items long.\n \"\"\"\n\n #stepResults = []\n stepRabbits = []\n stepFoxes = []\n for s in range(numSteps):\n rabbitGrowth()\n foxGrowth()\n #stepResults.append((CURRENTRABBITPOP, CURRENTFOXPOP))\n stepRabbits.append(CURRENTRABBITPOP)\n stepFoxes.append(CURRENTFOXPOP)\n\n #return stepResults\n return (stepRabbits, stepFoxes)\n","sub_path":"mitx6.00.2x/exam_problem3.py","file_name":"exam_problem3.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"362726346","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import get_object_or_404\nfrom django.apps import apps\n\nfrom rest_framework.viewsets import GenericViewSet\nfrom rest_framework.views import APIView\nfrom rest_framework import mixins\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom talentmap_api.common.mixins import FieldLimitableSerializerMixin\n\nfrom talentmap_api.user_profile.models import UserProfile\nfrom talentmap_api.messaging.models import Notification, Sharable, Task\nfrom talentmap_api.messaging.filters import NotificationFilter, TaskFilter\nfrom talentmap_api.messaging.serializers import NotificationSerializer, SharableSerializer, TaskSerializer\n\n\nclass NotificationView(FieldLimitableSerializerMixin,\n GenericViewSet,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin):\n '''\n partial_update:\n Edits a saved notification\n\n retrieve:\n Retrieves a specific notification\n\n list:\n Lists all notifications\n\n destroy:\n Deletes a specified notification\n '''\n\n serializer_class = NotificationSerializer\n filter_class = NotificationFilter\n permission_classes = (IsAuthenticated,)\n\n def get_queryset(self):\n queryset = Notification.objects.filter(owner=self.request.user.profile)\n self.serializer_class.prefetch_model(Notification, queryset)\n return queryset\n\n\nclass TaskView(FieldLimitableSerializerMixin,\n GenericViewSet,\n mixins.ListModelMixin,\n mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin):\n '''\n partial_update:\n Edits a saved task\n\n retrieve:\n Retrieves a specific task\n\n list:\n Lists all tasks\n\n destroy:\n Deletes a specified task\n '''\n\n serializer_class = TaskSerializer\n filter_class = TaskFilter\n permission_classes = (IsAuthenticated,)\n\n def get_queryset(self):\n queryset = Task.objects.filter(owner=self.request.user.profile)\n self.serializer_class.prefetch_model(Task, queryset)\n return queryset\n\n\nclass ShareView(FieldLimitableSerializerMixin,\n APIView):\n\n AVAILABLE_TYPES = {\n \"position\": \"position.Position\"\n }\n\n serializer_class = SharableSerializer\n permission_classes = (IsAuthenticated,)\n\n def patch(self, request, pk):\n '''\n Update a shared notification\n\n This method is mainly used to update the read status of a share\n '''\n share = get_object_or_404(Sharable, receiving_user=self.request.user.profile, id=pk)\n serializer = self.serializer_class(share, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n def post(self, request, format=None):\n '''\n Shares a TalentMAP element\n\n Post method accepts an object with at minimum the following parameters:\n * type - the type of object to be shared (position)\n * id - the id of the object to be shared\n * email - the email to send the share to\n '''\n valid, error = self.validate(request)\n user = self.request.user\n\n if valid:\n response = None\n if \"@state.gov\" in request.data.get(\"email\"):\n response = self.internal_share(user, request.data.get(\"email\"), request.data.get(\"type\"), request.data.get(\"id\"))\n else:\n response = self.email_share(user, request.data.get(\"email\"), request.data.get(\"type\"), request.data.get(\"id\"))\n return response\n else:\n return Response({\"message\": error}, status=status.HTTP_400_BAD_REQUEST)\n\n def validate(self, request):\n '''\n Validates that the request is a properly formatted share request, returning (True, None) in that case.\n If the request fails validation, it will return (False, String) where the second item of the tuple is\n a string explanation of the validation error.\n '''\n if \"type\" not in request.data:\n return (False, \"POSTs to this endpoint require the 'type' parameter\")\n elif request.data.get(\"type\") not in self.AVAILABLE_TYPES.keys():\n return (False, f\"Type must be one of the following: {','.join(self.AVAILABLE_TYPES.keys())}\")\n\n if \"id\" not in request.data:\n return (False, \"id of sharable object must be specified\")\n\n if \"email\" not in request.data:\n return (False, \"E-mail shares require an 'email' parameter to be specified\")\n\n return (True, None)\n\n def email_share(self, user, email, type, id):\n # Get our e-mail formatter\n formatter = self.get_email_formatter(type)\n instance = None\n\n # Attempt to get the object instance we want to share\n try:\n instance = apps.get_model(self.AVAILABLE_TYPES[type]).objects.get(id=id)\n except ObjectDoesNotExist:\n # If it doesn't exist, respond with a 404\n return Response({\"message\": f\"Object with id {id} does not exist\"}, status=status.HTTP_404_NOT_FOUND)\n\n # Create our e-mail body\n email_body = {\n \"to\": email,\n \"subject\": f\"[TalentMAP] Shared {type}\",\n \"body\": formatter(instance)\n }\n\n # TODO: Implement actual e-mail sending here when avaiable e-mail servers are clarified\n\n # Return a 202 ACCEPTED with a copy of the email body\n return Response({\"message\": f\"Position shared externally via email at {email}\", \"email_body\": email_body}, status=status.HTTP_202_ACCEPTED)\n\n def internal_share(self, user, email, type, id):\n receiving_user = None\n\n # Attempt to get the object instance we want to share\n try:\n apps.get_model(self.AVAILABLE_TYPES[type]).objects.get(id=id)\n except ObjectDoesNotExist:\n # If it doesn't exist, respond with a 404\n return Response({\"message\": f\"Object with id {id} does not exist\"}, status=status.HTTP_404_NOT_FOUND)\n\n # Attempt to get the receiving user by e-mail address\n try:\n receiving_user = UserProfile.objects.get(user__email=email)\n except ObjectDoesNotExist:\n return Response({\"message\": f\"User with email {email} does not exist\"}, status=status.HTTP_404_NOT_FOUND)\n\n # Create our sharable object using the source user, receiving user, id, and model\n # This will auto-populate in the receiving user's received shares on their profile\n Sharable.objects.create(sharing_user=user.profile,\n receiving_user=receiving_user,\n sharable_id=id,\n sharable_model=self.AVAILABLE_TYPES[type])\n\n return Response({\"message\": f\"Position shared internally to user with email {email}\"}, status=status.HTTP_202_ACCEPTED)\n\n def get_email_formatter(self, type):\n formatter = None\n if type == \"position\":\n def formatter(instance):\n return f\"This position has been shared with you via TalentMAP\\n\\n\" \\\n f\"\\tPosition Number: {instance.position_number}\\n\\tPosition Title: {instance.title}\\n\" \\\n f\"\\tPost: {instance.post}\"\n return formatter\n","sub_path":"talentmap_api/messaging/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"491249735","text":"'''\nTeam JAJ\nCS 555 Project\nI pledge my honor that I have abided by the Stevens Honor System.\n'''\nimport sys, os\nimport project04.src.utils as utils\nimport project04.src.marriageAge as marriageAge, project04.src.includeAge as includeAge\nimport project04.src.siblingAge as siblingAge, project04.src.illegitimateDates as illegitimateDates, project04.src.correctGender as correctGender\nfrom prettytable import PrettyTable\ntags0 = [\"HEAD\", \"TRLR\", \"NOTE\"]\ntags1 = [\"NAME\", \"SEX\", \"BIRT\", \"DEAT\", \"FAMC\",\n \"FAMS\", \"MARR\", \"HUSB\", \"WIFE\", \"CHIL\", \"DIV\"]\ntags2 = [\"DATE\"]\nother_tags = [\"INDI\", \"FAM\"]\ndateTags = [\"BIRT\", \"DEAT\", \"MARR\", \"DIV\"]\nfamilyDict = {}\nindividualDict = {}\ndictDict = {\"FAM\": familyDict, \"INDI\": individualDict}\ndef loadFile():\n fileName = raw_input(\"Please enter the desired GEDCOM file name: \")\n fileName = fileName.strip()\n outputFileName = \"parsedOutput\" + os.path.basename(fileName)\n if (len(fileName) > 0):\n if(len(fileName) <= 4):\n fileName += \".ged\"\n outputFileName += \".txt\"\n elif(fileName[-4:] == \".ged\"):\n outputFileName = outputFileName[0:-4] + \".txt\"\n else:\n fileName += \".ged\"\n outputFileName += \".txt\"\n return (fileName, outputFileName)\n else:\n print(\"You have entered an invalid file name!\")\n raise ValueError\n\ndef writeFileAndFillDict(inputFileName, outputFileName):\n loadedFile = open(inputFileName, 'r')\n writtenFile = open(outputFileName, 'a')\n currentObject = {}\n for i in loadedFile: \n if i.strip() == \"\":\n continue\n oldLine = \"-->\" + i.strip() + \"\\n\"\n lineArr = i.split()\n lev = int(lineArr[0])\n tag = lineArr[1]\n arg = ' '.join(lineArr[2:])\n constructedLine = \"\"\n if lev > 2:\n constructedLine = \"<--\" + \\\n str(lev) + \"|\"+tag+\"|\"+\"N\"+\"|\"+arg.strip() + \"\\n\"\n elif (lev == 1 and tag in tags1) or (lev == 2 and tag in tags2):\n constructedLine = \"<--\"+str(lev)+\"|\" + \\\n tag+\"|\"+\"Y\"+\"|\"+arg.strip() + \"\\n\"\n if tag in dateTags:\n lastDate = tag\n if tag == \"DATE\":\n currentObject[lastDate] = [arg]\n else:\n if tag in currentObject:\n currentObject[tag] = currentObject[tag]+[arg]\n else:\n currentObject[tag] = [arg]\n elif lev == 0 and tag in tags0:\n constructedLine = \"<--\"+str(lev)+\"|\" + \\\n tag+\"|\"+\"Y\"+\"|\"+arg.strip() + \"\\n\"\n if currentObject != {}:\n dictDict[currentObject[\"type\"]\n ][currentObject[\"ID\"]] = currentObject\n currentObject = {}\n elif lineArr[-1] in other_tags and lev == 0:\n constructedLine = \"<--\" + \\\n str(lev)+\"|\" + str(lineArr[-1]).strip() + \\\n \"|\"+\"Y\"+\"|\" + str(lineArr[1]) + \"\\n\"\n if currentObject != {}:\n dictDict[currentObject[\"type\"]\n ][currentObject[\"ID\"]] = currentObject\n currentObject = {}\n currentObject[\"type\"] = str(lineArr[-1]).strip()\n currentObject[\"ID\"] = lineArr[1]\n else:\n constructedLine = \"<--\" + \\\n str(lev) + \"|\"+tag+\"|\"+\"N\"+\"|\"+arg.strip() + \"\\n\"\n writtenFile.write(oldLine)\n writtenFile.write(constructedLine)\n loadedFile.close()\n writtenFile.close()\n return\n\ndef constructAndWriteIndiTable(file):\n file.write('Individuals:\\n')\n indiTable = PrettyTable(\n ['ID', 'Name', 'Gender', 'Birth', 'Death', 'Alive', 'Child', 'Spouse', 'Age'])\n for key in individualDict:\n addlist = [key] + individualDict[key]['NAME'] + \\\n individualDict[key]['SEX'] + individualDict[key]['BIRT']\n if 'DEAT' in individualDict[key].keys():\n addlist += individualDict[key]['DEAT']\n addlist.append('N')\n else:\n addlist.append('N/A')\n addlist.append('Y')\n if 'FAMC' in individualDict[key].keys():\n addlist += individualDict[key]['FAMC']\n else:\n addlist.append('N/A')\n if 'FAMS' in individualDict[key].keys():\n addlist += individualDict[key]['FAMS']\n else:\n addlist.append('N/A')\n addlist.append(individualDict[key]['AGE'])\n indiTable.add_row(addlist)\n file.write(indiTable.get_string() + '\\n')\n return\n\ndef constructAndWriteFamTable(writefi):\n writefi.write('Families:\\n')\n famTable = PrettyTable(['ID', 'Married', 'Divorced', 'Husband ID',\n 'Husband Name', 'Wife ID', 'Wife Name', 'Children'])\n for key in familyDict:\n addlist = [key] + familyDict[key]['MARR']\n if 'DIV' in familyDict.keys():\n addlist += familyDict[key]['DIV']\n else:\n addlist.append('N/A')\n hid = familyDict[key]['HUSB'][0]\n wid = familyDict[key]['WIFE'][0]\n addlist += [hid] + individualDict[hid]['NAME'] + \\\n [wid] + individualDict[wid]['NAME']\n if 'CHIL' in familyDict[key].keys():\n addlist += [familyDict[key]['CHIL']]\n else:\n addlist.append('N/A')\n famTable.add_row(addlist)\n writefi.write(famTable.get_string() + \"\\n\")\n\nif __name__ == \"__main__\":\n fileName, outputFileName = loadFile()\n writeFileAndFillDict(fileName, outputFileName)\n includeAge.addAgeToAll(individualDict)\n writefi = open('printoutput.txt', 'a')\n constructAndWriteIndiTable(writefi)\n constructAndWriteFamTable(writefi)\n siblingList = siblingAge.siblingAge(familyDict,individualDict)\n us10Anomalies = marriageAge.detectPedophilia(familyDict, individualDict)\n us42Anomalies = illegitimateDates.badDate(familyDict, individualDict)\n us21Anomalies = correctGender.confirmGender(familyDict, individualDict)\n utils.writeErrors(us10Anomalies, writefi)\n utils.writeErrors(us42Anomalies, writefi)\n utils.writeErrors(us21Anomalies, writefi)\n utils.writeErrors(siblingList, writefi)\n print(familyDict)\n writefi.close()\n\n\n","sub_path":"project04/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"94069260","text":"import discord\nimport requests \nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready() :\n print(client.user.id)\n print('ready')\n game = discord.Game(\"테스트봇\")\n await client.change_presence(status=discord.Status.online, activity=game)\n\n\n\n@client.event\nasync def on_message(message) :\n\n # 봇 응답메세지의 반복을 멈춤 \n if message.author.bot :\n return None \n\n # 인사 메세지 \n if message.content.startswith('안녕') :\n await message.channel.send('안녕하세요!')\n\n if message.content.startswith('코로나') :\n await message.channel.send(coronaInfo())\n\n if message.content.startswith('EPL') :\n \n await message.channel.send(getDate() + ' 기준 EPL 순위 - Sky Sports ') \n epl_data = getEplData()\n for data in epl_data :\n await message.channel.send(data) #순차적으로 순위, 팀명, 승점 출력\n\n if message.content.startswith('오늘날짜') :\n await message.channel.send(getDate()) \n \n\n\n\n# 코로나 정보 출력 함수\ndef coronaInfo() :\n\n # 1. 코로나 확진 환자\n # 2. 코로나 검사 진행\n # 3. 격리해제\n # 4. 사망자 \n\n # 크롤링 할 URL\n url = \"http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=&brdGubun=&ncvContSeq=&contSeq=&board_id=&gubun=\"\n\n response = requests.get(url)\n\n # 파이썬 내장 html.parser 사용\n domain = BeautifulSoup(response.content, 'html.parser')\n\n # 데이터 업데이트 시간\n corona_update_time = domain.select_one('p.s_descript').text.strip()\n\n # 확진환자, 검사진행 환자, 격리해제 환자, 사망자 수 \n corona_text = domain.select_one('.num').text.strip()\n\n print(corona_text)\n\n return corona_update_time +'\\n'+ corona_text\n\ndef getEplData() :\n\n # Sky Sports 크롤링 후 EPL 팀의 순위를 가져오는 함수\n\n\n # 1. 순위\n # 2. 팀\n # 3. 승점 \n\n datas = [] #데이터\n teams = [] # 팀명 \n ranks = [] # 순위\n points = [] # 승점\n\n\n index = 0 # 데이터 추출을 위한 list 접근용 인덱스\n\n\n # 크롤링 할 URL\n url = \"https://www.skysports.com/premier-league-table\"\n\n response = requests.get(url)\n # 파이썬 내장 html.parser 사용\n domain = BeautifulSoup(response.content, 'html.parser') \n rankTable = domain.find_all(\"a\",{\"class\" : \"standing-table__cell--name-link\"})\n\n rankPoint = domain.find_all(\"td\",{\"class\" : \"standing-table__cell\"})\n\n for team in rankTable :\n\n teams.append(team.string)\n \n\n # 팀명을 제외한 순위, 점수, 가지고 오기 \n for text in rankPoint :\n datas.append(text.string)\n \n \n\n # 데이터에서 순위 가지고 오기 \n for rank in datas : \n\n if index % 11 == 0 :\n ranks.append(str(rank)) \n index = index + 1\n else :\n index = index + 1 \n\n index = 0 \n\n # 데이터에서 승점 가지고 오기\n\n for point in datas : \n\n if index == 9 :\n points.append(str(point))\n index = index + 1 \n elif index == 10 :\n index = 0 \n else :\n index = index + 1\n \n chat_string = getEPLDataString(teams,ranks,points)\n return chat_string\n\n\ndef getEPLDataString(teams,ranks,points) :\n\n \n # 가져온 데이터들을 모두 하나의 문자열로 합치는 함수\n\n index = 0 # 배열에 접근하고자 하는 index\n\n \n \n final_string = [] # 봇이 출력할 최종 문자열 리스트4\n\n for rank in ranks :\n\n final_string.append(rank + \". \") \n\n for team in teams :\n\n final_string[index] = final_string[index] + team + \" - 승점 : \"\n index = index + 1\n \n index = 0 # index 재초기화\n\n for point in points :\n\n final_string[index] = final_string[index] + point\n index = index + 1\n\n return final_string\n\n\ndef getDate() :\n\n # 오늘의 연 / 월 / 일 을 구해주는 함수\n \n return datetime.today().strftime(\"%Y년 %m월 %d일\")\n \n\n\nclient.run(\"NjgzNjQ0Nzk1MDQ1OTM3MTUz.XmD59Q.SVbYsFKnLUt-cPEArqUhtdmKmB0\")\n\ncoronaInfo()\n\n","sub_path":"testBot.py","file_name":"testBot.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"598040","text":"#! /usr/bin/env python\n# -*- coding: latin-1; -*-\n\n''' \n\nCopyright 2018 University of Liège\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. \n\n'''\n\nimport os, sys\n\nfilePath = os.path.abspath(os.path.dirname(sys.argv[0]))\nfileName = os.path.splitext(os.path.basename(__file__))[0]\nFSICouplerPath = os.path.join(os.path.dirname(__file__), '../../')\n#appsPath = os.path.join(os.path.dirname(__file__), '../../apps')\n\nsys.path.append(FSICouplerPath)\n#sys.path.append(appsPath)\n\nfrom math import *\nfrom optparse import OptionParser\n\nimport cupydo.utilities as cupyutil\nimport cupydo.manager as cupyman\nimport cupydo.interpolator as cupyinterp\nimport cupydo.criterion as cupycrit\nimport cupydo.algorithm as cupyalgo\n\ndef getParameters(_p):\n # --- Input parameters --- #\n p = {}\n p['nDim'] = 3\n p['tollFSI'] = 1e-6\n p['dt'] = 0.0\n p['tTot'] = 0.05\n p['nFSIIterMax'] = 4\n p['timeIterTreshold'] = -1\n p['omegaMax'] = 1.0\n p['computationType'] = 'steady'\n p['mtfSaveAllFacs'] = False\n p['nodalLoadsType'] = 'force'\n p['nZones_SU2'] = 0\n p['withMPI'] = True\n p.update(_p)\n return p \n\ndef main(_p, nogui):\n\n p = getParameters(_p)\n\n comm = None\n myid = 0\n numberPart = 0\n rootProcess = 0\n\n cupyutil.load(fileName, p['withMPI'], comm, myid, numberPart)\n\n if p['withMPI']:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n myid = comm.Get_rank()\n numberPart = comm.Get_size()\n else:\n comm = None\n myid = 0\n numberPart = 1\n\n # --- Input parameters --- #\n CFD_file = '../../../tests/SU2_Metafor/AGARD445_Static_SU2Conf.cfg'\n CSD_file = 'AGARD445_Static_MetaforConf'\n\n # --- Initialize the fluid solver --- #\n import cupydoInterfaces.SU2Interface\n if comm != None:\n FluidSolver = cupydoInterfaces.SU2Interface.SU2Solver(CFD_file, p['nZones_SU2'], p['nDim'], p['computationType'], p['nodalLoadsType'], p['withMPI'], comm)\n else:\n FluidSolver = cupydoInterfaces.SU2Interface.SU2Solver(CFD_file, p['nZones_SU2'], p['nDim'], p['computationType'], p['nodalLoadsType'], p['withMPI'], 0)\n cupyutil.mpiBarrier(comm)\n\n # --- Initialize the solid solver --- #\n SolidSolver = None\n if myid == rootProcess:\n import cupydoInterfaces.MtfInterface\n SolidSolver = cupydoInterfaces.MtfInterface.MtfSolver(CSD_file, p['computationType'])\n SolidSolver.saveAllFacs = p['mtfSaveAllFacs']\n cupyutil.mpiBarrier(comm)\n\n # --- Initialize the FSI manager --- #\n manager = cupyman.Manager(FluidSolver, SolidSolver, p['nDim'], p['computationType'], comm)\n cupyutil.mpiBarrier()\n\n # --- Initialize the interpolator --- #\n interpolator = cupyinterp.TPSInterpolator(manager, FluidSolver, SolidSolver, comm)\n solverList = interpolator.getLinearSolvers()\n for ii in range(2):\n solverList[ii].setMaxNumberIterations(1000)\n solverList[ii].setPreconditioner(\"JACOBI\")\n\n # --- Initialize the FSI criterion --- #\n criterion = cupycrit.DispNormCriterion(p['tollFSI'])\n cupyutil.mpiBarrier()\n\n # --- Initialize the FSI algorithm --- #\n algorithm = cupyalgo.AlgorithmBGSStaticRelax(manager, FluidSolver, SolidSolver, interpolator, criterion, p['nFSIIterMax'], p['dt'], p['tTot'], p['timeIterTreshold'], p['omegaMax'], comm)\n\n # --- Launch the FSI computation --- #\n algorithm.run()\n \n # --- Exit computation --- #\n del manager\n del criterion\n del FluidSolver\n del SolidSolver\n del interpolator\n del algorithm\n cupyutil.mpiBarrier(comm)\n return 0\n\n\n# -------------------------------------------------------------------\n# Run Main Program\n# -------------------------------------------------------------------\n\n# --- This is only accessed if running from command prompt --- #\nif __name__ == '__main__':\n\n p = {}\n \n parser=OptionParser()\n parser.add_option(\"--nogui\", action=\"store_true\",\n help=\"Specify if we need to use the GUI\", dest=\"nogui\", default=False)\n\n (options, args)=parser.parse_args()\n \n nogui = options.nogui\n \n main(p, nogui)\n","sub_path":"tests/SU2_Metafor/fsi_AGARD445_Static_BGS_interpTPS_parallel.py","file_name":"fsi_AGARD445_Static_BGS_interpTPS_parallel.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"629033746","text":"#高阶函数\n#接受函数作为参数,或者将函数作为返回值的函数就是高阶函数\n#创建一个列表\nl = [1,2,3,4,5,6,7,8,9,10]\n\n\n# 定义一个函数,用来检查\ndef fn2(i):\n if i % 2 == 0:\n return True\n return False\n\n\ndef fn3(i):\n if i > 5:\n return True\n return False\n#定义一个函数\ndef fn(func,list) :\n\n\n '''\n \n :param list: \n :return: \n '''\n #创建一个新列表\n new_list = []\n\n #对列表进行筛选\n for n in list :\n # if n % 2 == 0 :\n # new_list.append(n)\n if func(n) :\n new_list.append(n)\n #返回新列表\n return new_list\n\n#print(fn(fn3,l))\n\n\n#print(list(filter(fn3,l)))\n\n\n#lambda函数表达式 匿名函数\n#语法 :lambda 参数列表:返回值\ndef fn5(a , b):\n return a + b\n\nlambda a,b : a+b\n\nr = filter(lambda i : i > 5,l)\nprint(list(r))\n\n#map()\n#map()函数可以对迭代对象中的所有元素做指定的操作\nr = map(lambda i : i+1,l)\nprint(list(r))","sub_path":"day03/08.高阶函数.py","file_name":"08.高阶函数.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238626260","text":"import tensorflow as tf\nfrom tensorflow import pad\nfrom tensorflow.keras.layers import Layer, Conv2D, ReLU, Add\n\nfrom tensorflow_addons.layers import InstanceNormalization\n\n\n# ReflectionPadding-Implementation from:\n# https://www.machinecurve.com/index.php/2020/02/10/using-constant-padding-reflection-padding-and-replication-padding-with-keras/\n'''\n 2D Reflection Padding\n Attributes:\n - padding: (padding_width, padding_height) tuple\n'''\nclass ReflectionPadding2D(Layer):\n def __init__(self, padding=(1, 1), **kwargs):\n self.padding = tuple(padding)\n super(ReflectionPadding2D, self).__init__(**kwargs)\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1] + 2 * self.padding[0], input_shape[2] + 2 * self.padding[1], input_shape[3])\n\n def call(self, input_tensor, mask=None):\n padding_width, padding_height = self.padding\n return pad(input_tensor, [[0,0], [padding_height, padding_height], [padding_width, padding_width], [0,0] ], 'REFLECT')\n \n \n \n \ndef resnet_convBlock(n_filters):\n result = tf.keras.Sequential()\n \n layers = [\n ReflectionPadding2D(padding=(1, 1)),\n Conv2D(n_filters, kernel_size=(3,3), strides=(1,1), padding=\"valid\"),\n InstanceNormalization(axis=-1),\n ReLU(),\n \n ReflectionPadding2D(padding=(1, 1)),\n Conv2D(n_filters, kernel_size=(3,3), strides=(1,1), padding=\"valid\"),\n InstanceNormalization(axis=-1)\n ]\n \n for layer in layers:\n result.add(layer)\n \n return result\n\ndef resnet_block(input_layer, n_filters):\n t = resnet_convBlock(n_filters)(input_layer)\n output = Add()([t, input_layer])\n return output\n \n \n ","sub_path":"cyclegan/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"216309483","text":"import pandas as pd\r\nimport numpy as np\r\ndata = pd.read_csv(\"train.csv\",encoding='ISO-8859-15')\r\ndata_AMB = np.array([object()]*12)\r\ndata_CH4 = np.array([object()]*12)\r\ndata_CO = np.array([object()]*12)\r\ndata_NMHC = np.array([object()]*12)\r\ndata_NO = np.array([object()]*12)\r\ndata_NO2 = np.array([object()]*12)\r\ndata_NOx = np.array([object()]*12)\r\ndata_O3 = np.array([object()]*12)\r\ndata_PM10 = np.array([object()]*12)\r\ndata_PM2_5 = np.array([object()]*12)\r\n#missing data\r\ndata_RH = np.array([object()]*12)\r\ndata_SO2 = np.array([object()]*12)\r\ndata_THC = np.array([object()]*12)\r\ndata_WD_HR = np.array([object()]*12)\r\ndata_WIND_DIREC = np.array([object()]*12)\r\ndata_WIND_SPEED = np.array([object()]*12)\r\ndata_WS_HR = np.array([object()]*12)\r\n\r\nfor i in range(12):\r\n data_AMB[i] = data.iloc[0+i*360,3::]\r\n data_AMB[i] = np.array(data_AMB[i], float)\r\n data_CH4[i] = data.iloc[1+i*360,3::]\r\n data_CH4[i] = np.array(data_CH4[i], float)\r\n data_CO[i] = data.iloc[2+i*360,3::]\r\n data_CO[i] = np.array(data_CO[i], float)\r\n data_NMHC[i] = data.iloc[3+i*360,3::]\r\n data_NMHC[i] = np.array(data_NMHC[i], float)\r\n data_NO[i] = data.iloc[4+i*360,3::]\r\n data_NO[i] = np.array(data_NO[i], float)\r\n data_NO2[i] = data.iloc[5+i*360,3::]\r\n data_NO2[i] = np.array(data_NO2[i], float)\r\n data_NOx[i] = data.iloc[6+i*360,3::]\r\n data_NOx[i] = np.array(data_NOx[i], float)\r\n data_O3[i] = data.iloc[7+i*360,3::]\r\n data_O3[i] = np.array(data_O3[i], float)\r\n data_PM10[i] = data.iloc[8+i*360,3::]\r\n data_PM10[i] = np.array(data_PM10[i], float)\r\n data_PM2_5[i] = data.iloc[9+i*360,3::]\r\n data_PM2_5[i] = np.array(data_PM2_5[i], float)\r\n #missing data\r\n data_RH[i] = data.iloc[11+i*360,3::]\r\n data_RH[i] = np.array(data_RH[i], float)\r\n data_SO2[i] = data.iloc[12+i*360,3::]\r\n data_SO2[i] = np.array(data_SO2[i], float)\r\n data_THC[i] = data.iloc[13+i*360,3::]\r\n data_THC[i] = np.array(data_THC[i], float)\r\n data_WD_HR[i] = data.iloc[13+i*360,3::]\r\n data_WD_HR[i] = np.array(data_WD_HR[i], float) \r\n data_WIND_DIREC[i] = data.iloc[13+i*360,3::]\r\n data_WIND_DIREC[i] = np.array(data_WIND_DIREC[i], float)\r\n data_WIND_SPEED[i] = data.iloc[13+i*360,3::]\r\n data_WIND_SPEED[i] = np.array(data_WIND_SPEED[i], float)\r\n data_WS_HR[i] = data.iloc[13+i*360,3::]\r\n data_WS_HR[i] = np.array(data_WS_HR[i], float)\r\n \r\n \r\n for j in range(18+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_AMB[i] =np.hstack((data_AMB[i], temp))\r\n for j in range(19+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_CH4[i] =np.hstack((data_CH4[i], temp)) \r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_CO[i] =np.hstack((data_CO[i], temp))\r\n for j in range(21+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_NMHC[i] =np.hstack((data_NMHC[i], temp))\r\n for j in range(22+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_NO[i] =np.hstack((data_NO[i], temp))\r\n for j in range(23+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_NO2[i] =np.hstack((data_NO2[i], temp))\r\n for j in range(24+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_NOx[i] =np.hstack((data_NOx[i], temp))\r\n for j in range(25+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_O3[i] =np.hstack((data_O3[i], temp))\r\n for j in range(26+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_PM10[i] =np.hstack((data_PM10[i], temp))\r\n for j in range(27+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_PM2_5[i] =np.hstack((data_PM2_5[i], temp))\r\n \r\n #missing data\r\n \r\n for j in range(29+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_RH[i] =np.hstack((data_RH[i], temp))\r\n for j in range(30+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_SO2[i] =np.hstack((data_SO2[i], temp))\r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_THC[i] =np.hstack((data_THC[i], temp))\r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_WD_HR[i] =np.hstack((data_WD_HR[i], temp))\r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_WIND_DIREC[i] =np.hstack((data_WIND_DIREC[i], temp))\r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_WIND_SPEED[i] =np.hstack((data_WIND_SPEED[i], temp))\r\n for j in range(20+i*360, 360*(i+1), 18):\r\n temp = data.iloc[j,3::]\r\n temp = np.array(temp, float)\r\n data_WS_HR[i] =np.hstack((data_WS_HR[i], temp))\r\n\r\nfor i in range(12):\r\n for j in range(data_AMB[i].size):\r\n if data_AMB[i][j] <= 0:\r\n data_AMB[i][j] = data_AMB[i][j-1]\r\n if data_CH4[i][j] <= 0:\r\n data_CH4[i][j] = data_CH4[i][j-1]\r\n if data_CO[i][j] <= 0:\r\n data_CO[i][j] = data_CO[i][j-1]\r\n if data_NMHC[i][j] <= 0:\r\n data_NMHC[i][j] = data_NMHC[i][j-1]\r\n if data_NO[i][j] <= 0:\r\n data_NO[i][j] = data_NO[i][j-1]\r\n if data_NO2[i][j] <= 0:\r\n data_NO2[i][j] = data_NO2[i][j-1]\r\n if data_NOx[i][j] <= 0:\r\n data_NOx[i][j] = data_NOx[i][j-1]\r\n if data_O3[i][j] <= 0:\r\n data_O3[i][j] = data_O3[i][j-1]\r\n if data_PM10[i][j] <= 0:\r\n data_PM10[i][j] = data_PM10[i][j-1]\r\n if data_PM2_5[i][j] <= 2 or data_PM2_5[i][j] > 120:\r\n data_PM2_5[i][j] = data_PM2_5[i][j-1]\r\n if data_RH[i][j] <= 0.0:\r\n data_RH[i][j] = data_RH[i][j-1]\r\n if data_SO2[i][j] <= 0:\r\n data_SO2[i][j] = data_SO2[i][j-1]\r\n if data_THC[i][j] < 0:\r\n data_THC[i][j] = data_THC[i][j-1]\r\n if data_WD_HR[i][j] < 0:\r\n data_WD_HR[i][j] = data_WD_HR[i][j-1]\r\n if data_WIND_DIREC[i][j] < 0:\r\n data_WIND_DIREC[i][j] = data_WIND_DIREC[i][j-1]\r\n if data_WIND_SPEED[i][j] < 0:\r\n data_WIND_SPEED[i][j] = data_WIND_SPEED[i][j-1]\r\n if data_WS_HR[i][j] < 0:\r\n data_WS_HR[i][j] = data_WS_HR[i][j-1]\r\n\r\n#使用每筆data9小時內PM2.5的一次項(含bias項)\r\nnum = 9\r\n\r\nlr = 0.1\r\niteration = 1000\r\n\r\nmonth = 12\r\n\r\n\r\n\r\nb = 0\r\nw = [0]*num\r\nb_lr = 0.0\r\nw_lr = [0.0]*num\r\n\r\nfor i in range(iteration):\r\n b_grad = 0.0\r\n w_grad = [0.0]*num\r\n for j in range(month):\r\n for k in range(0, len(data_PM2_5[j])-9):\r\n data_past = [data_PM2_5[j][k], data_PM2_5[j][k+1], data_PM2_5[j][k+2], data_PM2_5[j][k+3], data_PM2_5[j][k+4], data_PM2_5[j][k+5], data_PM2_5[j][k+6], data_PM2_5[j][k+7], data_PM2_5[j][k+8]]\r\n formula = data_PM2_5[j][k+9] - b\r\n for l in range(num):\r\n formula -= data_past[l] * w[l]\r\n formula *= 2.0\r\n\r\n b_grad = b_grad - formula*1.0\r\n for l in range(num):\r\n w_grad[l] = w_grad[l] - formula * data_past[l]\r\n\r\n b_lr = b_lr + b_grad**2\r\n b = b - lr/np.sqrt(b_lr) * b_grad\r\n for k in range(num):\r\n w_lr[k] = w_lr[k] + w_grad[k]**2\r\n w[k] = w[k] - lr/np.sqrt(w_lr[k]) * w_grad[k]\r\n\r\n\r\nerror = 0\r\nfor j in range(month):\r\n for k in range(len(data_PM2_5[j]) - 9):\r\n estimation = b + data_PM2_5[j][k] * w[0] + data_PM2_5[j][k+1] * w[1] + data_PM2_5[j][k+2] * w[2] + data_PM2_5[j][k+3] * w[3] + data_PM2_5[j][k+4] * w[4] + data_PM2_5[j][k+5] * w[5] + data_PM2_5[j][k+6] * w[6] + data_PM2_5[j][k+7] * w[7] + data_PM2_5[j][k+8] * w[8]\r\n error += (np.abs(data_PM2_5[j][k + 9] - estimation))**2\r\nerror /= (471 * 12)\r\nerror = np.sqrt(error)","sub_path":"hw1/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"109348336","text":"#! /usr/bin/env python\n\n# Find commit date/time for every commit, list files in the commit\n# and set the file's modification time to the date/time of the latest commit.\n\n# Adapted from https://git.wiki.kernel.org/index.php/ExampleScripts#Setting_the_timestamps_of_the_files_to_the_commit_timestamp_of_the_commit_which_last_touched_them # noqa\n\nimport os\nimport subprocess\n\nseparator = '----- GIT LOG SEPARATOR -----'\n\ngit_log = subprocess.Popen(['git', 'log', '-m', '--first-parent',\n '--name-only', '--no-color',\n '--format=%s%%n%%ct' % separator],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\nfilenames = set()\n# stages: 1 - start of commit, 2 - timestamp, 3 - empty line, 4 - files\nstage = 1\nwhile True:\n line = git_log.stdout.readline()\n if not line: # EOF\n break\n line = line.strip()\n if (stage in (1, 4)) and (line == separator): # Start of a commit\n stage = 2\n elif stage == 2:\n stage = 3\n time = int(line)\n elif stage == 3:\n if line == separator: # Null-merge (git merge -s ours), no files\n stage = 2\n continue\n stage = 4\n assert line == '', line\n elif stage == 4:\n filename = line\n if filename not in filenames:\n filenames.add(filename)\n if os.path.exists(filename):\n os.utime(filename, (time, time))\n else:\n raise ValueError(\"stage: %d, line: %s\" % (stage, line))\n\ngit_log.wait()\ngit_log.stdout.close()\n","sub_path":"devscripts/set-commit-date.py","file_name":"set-commit-date.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"445232584","text":"def ordinal(num: int) -> str:\n number = \"\"\n\n if num == 1:\n number = \"first\"\n elif num == 2:\n number = \"second\"\n elif num == 3:\n number = \"third\"\n elif num == 4:\n number = \"fourth\"\n elif num == 5:\n number = \"fifth\"\n elif num == 6:\n number = \"sixth\"\n elif num == 7:\n number = \"seventh\"\n elif num == 8:\n number = \"eighth\"\n elif num == 9:\n number = \"ninth\"\n elif num == 10:\n number = \"tenth\"\n elif num == 11:\n number = \"eleventh\"\n elif num == 12:\n number = \"twelfth\"\n else:\n raise Exception(\"Unsupported number provided for ordinal conversion.\")\n\n return number\n\n\ndef first_line(day: int) -> str:\n return \"On the {} day of Christmas my true love gave to me: \".format(ordinal(day))\n\n\ndef last_line(day_num: int) -> str:\n verse = \"a Partridge in a Pear Tree.\"\n\n return verse if day_num == 1 else \"and \" + verse\n\n\ndef daily_lyrics(day_num: int) -> str:\n lyrics = [\n \"twelve Drummers Drumming, \",\n \"eleven Pipers Piping, \",\n \"ten Lords-a-Leaping, \",\n \"nine Ladies Dancing, \",\n \"eight Maids-a-Milking, \",\n \"seven Swans-a-Swimming, \",\n \"six Geese-a-Laying, \",\n \"five Gold Rings, \",\n \"four Calling Birds, \",\n \"three French Hens, \",\n \"two Turtle Doves, \",\n last_line(day_num),\n ]\n\n return \"\".join(lyrics[-day_num::1])\n\n\ndef recite(start_verse, end_verse):\n lyrics = []\n\n for day in range(start_verse, end_verse + 1):\n lyrics.append(first_line(day) + daily_lyrics(day))\n\n return lyrics\n","sub_path":"python/twelve-days/twelve_days.py","file_name":"twelve_days.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"250550564","text":"# Floor 6 of \"Who wants to be a Mafsologist!\"\n# The Second Combination Room\n\nimport time, random\nfrom level7 import *\nfrom operators import mul, div\n\ndef floor6():\n\n print()\n print(\"This floor (#3). This floor will test your multiplication and division skills and is split into 3 levels.\")\n print(\"This room should be getting harder (6A)!\")\n print(\"We will take two integers, between 0 & 10 for multiplication, and 1 & 10 for division.\")\n operators = (\"*\", \"/\")\n rando = random.choice(operators)\n\n if rando == \"*\":\n rand1 = random.randint(0, 10)\n rand2 = random.randint(0, 10)\n rans = mul(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"*\" + str(rand2) + \"?\")\n else:\n rand1 = random.randint(1, 10)\n rand2 = random.randint(1, 10)\n rans = div(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"/\" + str(rand2) + \"?\")\n\n ransa01 = rans + 0.01\n ransm01 = rans - 0.01\n\n if rans == float(gans) or ransa01 > float(gans) > ransm01: # First test.\n print()\n print(\"Well done, You have passed the first level of floor six!\")\n time.sleep(1)\n print(\"This is the Beta-Room of floor 6 (6B), This should be a little harder\")\n print(\"We will take two integers, between 0 & 15 for multiplication, and 1 & 15 for division.\")\n rando = random.choice(operators)\n\n\n if rando == \"*\":\n rand1 = random.randint(0, 15)\n rand2 = random.randint(0, 15)\n rans = mul(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"*\" + str(rand2) + \"?\")\n else:\n rand1 = random.randint(1, 15)\n rand2 = random.randint(1, 15)\n rans = div(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"/\" + str(rand2) + \"?\")\n\n ransa01 = rans + 0.01\n ransm01 = rans - 0.01\n\n if rans == float(gans) or ransa01 > float(gans) > ransm01: # Second Test.\n print()\n print(\"You have just passed the Second level of floor 6! Lets move on.\")\n time.sleep(1)\n print(\"This is the Ceta-Room of floor 6 (6C), This should challenge you.\")\n print(\"We will now take 2 integers, between 0 & 25 for multiplication, and 1 & 25 for division.\")\n rando = random.choice(operators)\n\n if rando == \"*\":\n rand1 = random.randint(0,25)\n rand2 = random.randint(0,25)\n rans = mul(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"*\" + str(rand2) + \"?\")\n else:\n rand1 = random.randint(1,25)\n rand2 = random.randint(1,25)\n rans = div(rand1, rand2)\n gans = input(\"What is the answer to: \" + str(rand1) + \"/\" + str(rand2) + \"?\")\n\n ransa01 = rans + 0.01\n ransm01 = rans - 0.01\n\n if rans == float(gans) or ransa01 > float(gans) > ransm01: # Third Test.\n print()\n print(\"You have passed all three levels of the sixth floor, Congratulations!\")\n time.sleep(1)\n print(\"Lets move on to floor 7, The last one!\")\n print()\n floor7()\n\n else:\n print()\n print(\"You just failed the level: 6C, Sorry!\")\n print(\"Did your mafs education stop at the end of primary school?\")\n print()\n return\n\n\n else:\n print()\n print(\"You just failed the level: 6B, Sorry!\")\n print(\"Did your mafs education stop in the middle of primary school?\")\n print()\n return\n\n else:\n print()\n print(\"Your mafs has not succeeded!\")\n print(\"You have failed on level: 6A, this is just disappointing.\")\n print(\"Your mafs skills are just about primary school level!\")\n return\n","sub_path":"ex45/level6.py","file_name":"level6.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466009684","text":"# coding: utf-8\n# pylint: disable=invalid-name, exec-used\n\"\"\"Setup lightgbm package.\"\"\"\nfrom __future__ import absolute_import\n\nimport struct\nimport os\nimport sys\nimport getopt\nimport distutils\nimport shutil\nfrom distutils import dir_util\nfrom distutils import file_util\nfrom setuptools import find_packages, setup\n\nif __name__ == \"__main__\":\n build_sdist = sys.argv[1] == 'sdist'\n if (8 * struct.calcsize(\"P\")) != 64:\n raise Exception('Cannot install LightGBM in 32-bit python, please use 64-bit python instead.')\n use_gpu = False\n use_mingw = False\n use_precompile = False\n try:\n opts, args = getopt.getopt(sys.argv[2:], 'mgp', ['mingw', 'gpu', 'precompile'])\n for opt, arg in opts:\n if opt in ('-m', '--mingw'):\n use_mingw = True\n elif opt in ('-g', '--gpu'):\n use_gpu = True\n elif opt in ('-p', '--precompile'):\n use_precompile = True\n sys.argv = sys.argv[0:2]\n except getopt.GetoptError as err:\n pass\n if not use_precompile or build_sdist:\n if not os.path.isfile('./_IS_SOURCE_PACKAGE.txt'):\n if os.path.exists(\"../include\"):\n if os.path.exists(\"./lightgbm/include\"):\n shutil.rmtree('./lightgbm/include')\n distutils.dir_util.copy_tree(\"../include\", \"./lightgbm/include\")\n else:\n raise Exception('Cannot copy ../include folder')\n if os.path.exists(\"../src\"):\n if os.path.exists(\"./lightgbm/src\"):\n shutil.rmtree('./lightgbm/src')\n distutils.dir_util.copy_tree(\"../src\", \"./lightgbm/src\")\n else:\n raise Exception('Cannot copy ../src folder')\n if use_gpu:\n if os.path.exists(\"../compute\"):\n if os.path.exists(\"./lightgbm/compute\"):\n shutil.rmtree('./lightgbm/compute')\n distutils.dir_util.copy_tree(\"../compute\", \"./lightgbm/compute\")\n else:\n raise Exception('Cannot copy ../compute folder')\n distutils.file_util.copy_file(\"../CMakeLists.txt\", \"./lightgbm/\")\n distutils.file_util.copy_file(\"../VERSION.txt\", \"./lightgbm/\")\n if build_sdist:\n file_flag = open(\"./_IS_SOURCE_PACKAGE.txt\", 'w')\n file_flag.close()\n\n if not os.path.exists(\"build\"):\n os.makedirs(\"build\")\n os.chdir(\"build\")\n\n cmake_cmd = \"cmake \"\n build_cmd = \"make _lightgbm\"\n\n if os.name == \"nt\":\n if use_mingw:\n cmake_cmd = cmake_cmd + \" -G \\\"MinGW Makefiles\\\" \"\n build_cmd = \"mingw32-make.exe _lightgbm\"\n else:\n cmake_cmd = cmake_cmd + \" -DCMAKE_GENERATOR_PLATFORM=x64 \"\n build_cmd = \"cmake --build . --target _lightgbm --config Release\"\n if use_gpu:\n cmake_cmd = cmake_cmd + \" -DUSE_GPU=ON \"\n if not build_sdist:\n print(\"Start to compile libarary.\")\n os.system(cmake_cmd + \" ../lightgbm/\")\n os.system(build_cmd)\n os.chdir(\"..\")\n\n data_files = []\n\n if build_sdist:\n print(\"remove library when building source distribution\")\n if os.path.exists(\"./lightgbm/Release/\"):\n shutil.rmtree('./lightgbm/Release/')\n if os.path.isfile('./lightgbm/lib_lightgbm.so'):\n os.remove('./lightgbm/lib_lightgbm.so')\n else:\n sys.path.insert(0, '.')\n CURRENT_DIR = os.path.dirname(__file__)\n libpath_py = os.path.join(CURRENT_DIR, 'lightgbm/libpath.py')\n libpath = {'__file__': libpath_py}\n exec(compile(open(libpath_py, \"rb\").read(), libpath_py, 'exec'), libpath, libpath)\n\n LIB_PATH = [os.path.relpath(path, CURRENT_DIR) for path in libpath['find_lib_path']()]\n print(\"Install lib_lightgbm from: %s\" % LIB_PATH)\n data_files = [('lightgbm', LIB_PATH)]\n version = '2.0.1'\n if os.path.isfile('./lightgbm/VERSION.txt'):\n version = open('./lightgbm/VERSION.txt').read().strip()\n elif os.path.isfile('../VERSION.txt'):\n version = open('../VERSION.txt').read().strip()\n setup(name='lightgbm',\n version=version,\n description='LightGBM Python Package',\n install_requires=[\n 'wheel',\n 'numpy',\n 'scipy',\n 'scikit-learn'\n ],\n maintainer='Guolin Ke',\n maintainer_email='guolin.ke@microsoft.com',\n zip_safe=False,\n packages=find_packages(),\n include_package_data=True,\n data_files=data_files,\n license='The MIT License(https://github.com/Microsoft/LightGBM/blob/master/LICENSE)',\n url='https://github.com/Microsoft/LightGBM')\n if build_sdist and os.path.isfile('./_IS_SOURCE_PACKAGE.txt'):\n os.remove('./_IS_SOURCE_PACKAGE.txt')\n","sub_path":"python-package/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"596421028","text":"from PySide.QtGui import *\nfrom PySide.QtCore import *\n\nclass myWidget(QWidget):\n def __init__(self):\n super(myWidget, self).__init__()\n layout = QVBoxLayout(self)\n self.setLayout(layout)\n self.label = QLabel('text')\n layout.addWidget(self.label)\n self.button = QPushButton(\"press\")\n layout.addWidget(self.button)\n self.button.clicked.connect(self.action)\n\n def action(self):\n self.label.setText('new text')\n self.button.setText('pressed')\n \n\n\nif __name__=='__main__':\n app = QApplication([])\n w = myWidget()\n w.show()\n app.exec_()\n","sub_path":"07_PySide/02_widget.py","file_name":"02_widget.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"422355974","text":"from models import * ##\ntry:\n from models import *\nexcept Exception:\n from .models import *\nimport random\n\n\nclass interview_methods:\n @staticmethod\n def random_slot(applicant):\n print(applicant.school)\n\n if applicant.school is not None:\n free_slots = InterviewSlot.select().join(Mentor).where(\n (InterviewSlot.reserved == False) & (Mentor.school == applicant.school.id))\n else:\n print('Applicant has no school yet,please assign school first')\n return None\n try:\n free_slot = random.choice(free_slots)\n except IndexError:\n return None\n return free_slot\n\n @classmethod\n def assign_interviews(cls):\n sub = interview_methods.select_applicant_wo_interview()\n for applicant in sub:\n slot = cls.random_slot(applicant)\n if slot is None:\n print('There is no available interview slot for ', applicant.first_name, applicant.last_name)\n return False\n Interview.create(applicant=applicant.id, slot=slot.id)\n InterviewSlot.update(reserved=True).where(InterviewSlot.id == slot.id).execute()\n\n @classmethod\n def assign_second_mentor(cls, interview):\n sub = InterviewSlot.select().join(Interview, join_type=JOIN_LEFT_OUTER).switch(InterviewSlot).join(\n Mentor).where((InterviewSlot.start == interview.slot.start) & (InterviewSlot.reserved == False) &\n (Mentor.school == interview.applicant.school))\n if len(sub) == 0:\n print('Impossibru')\n else:\n slot = random.choice(sub)\n Interview.update(slot_mentor2=slot.id).where(Interview.id == interview.id).execute()\n InterviewSlot.update(reserved=True).where(InterviewSlot.id == slot.id).execute()\n\n @classmethod\n def assign_interview(cls, applicant):\n slot = cls.random_slot(applicant)\n if slot is None:\n print('There is no available interview slot for ', applicant.first_name, applicant.last_name)\n return False\n Interview.create(applicant=applicant.id, slot=slot.id)\n InterviewSlot.update(reserved=True).where(InterviewSlot.id == slot.id).execute()\n \n @classmethod\n def get_interviews(cls):\n return Interview.select()\n\n @staticmethod\n def filter_redirect(choice, query):\n if choice == \"applicant\":\n return \"filter_by_applicant\"\n elif choice == \"mentor\":\n return \"filter_by_mentor\"\n elif choice == \"location\":\n return \"filter_by_location\"\n","sub_path":"school-system-with-flask/interview_methods.py","file_name":"interview_methods.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"376193205","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# rmsd.py\n\nimport sys\nimport math\nimport matplotlib.pyplot as plt\nimport structureTools_TaylorArnaud as st\n\n\n\n## renvoie le RMSD entre deux proteines pour un atome donnée\n# @a : dictionnaire de la premire proteine \n# @b : dictionnaire de la deuxieme proteine\n# @liste : l'atome presente dans les proteines avec le quel on calcul le RMSD, par defaut la fonction prend le carbone alpha\ndef simple_rmsd(a,b,liste=['CA']): #Atome par défaut CA\n\tN = 0\n\tres = 0\n\ts=0.0\n\tfor mod in a.keys():\n\t\tfor dom in a[mod].keys():\n\t\t\tfor j in a[mod][dom].keys():# dans les chaines\n\t\t\t\tfor k in a[mod][dom][j].keys(): # dans les résidus\n\t\t\t\t\tres+=1\n\t\t\t\t\tfor l in a[mod][dom][j][k].keys(): #dans les dictionnaires d'info\n\t\t\t\t\t\tl2=st.selectElement(l)\n\t\t\t\t\t\tif(l2 in liste): #On ignore le centre de masse s'il y en a un\n\t\t\t\t\t\t\ts+=pow(st.distanceAtomes(a[mod][dom][j][k][l],b[mod][dom][j][k][l]),2)\n\t\t\t\t\t\t\tN+=1\n\tprint(\"Paires d'atomes alignées : \",N)\n\t#~ print(\"Nombre résidus: \",res)\n\tif(N>0):\n\t\treturn(math.sqrt(s/N))\n\t#Sinon aucune paire n'a été alignée : retourne None (car division par 0 impossible)\n\n\n## renvoie le RMSD entre deux proteines pour un atome donnée\n# @a : dictionnaire de la premire proteine \n# @b : dictionnaire de la deuxieme proteine \n# @modA : correspond à la conformation souhaiter de la proteine 1 \n# @modB : correspond à la conformation souhaiter de la proteine 2\n# @liste : l'atome presente dans les proteines avec le quel on calcul le RMSD, par defaut la fonction prend le carbone alpha\ndef rmsd(a,b,modA,modB,liste=['CA']): #Atome par défaut CA\n\tN = 0\n\tres = 0\n\ts=0.0\n\tfor dom in a[modA].keys(): # dans les domaines\n\t\tfor j in a[modA][dom].keys():\t# dans les chaines\n\t\t\tfor k in a[modA][dom][j].keys(): # dans les résidus\n\t\t\t\tres+=1\n\t\t\t\tfor l in a[modA][dom][j][k].keys(): # dans l'info\n\t\t\t\t\tl2=st.selectElement(l)\n\t\t\t\t\tif(l2 in liste): #On ignore le centre de masse s'il y en a un\n\t\t\t\t\t\ts+=pow(st.distanceAtomes(a[modA][dom][j][k][l],b[modB][dom][j][k][l]),2) # On peut écrire ça car même protéine, même chaine/résidus/atomes seul le modèle change\n\t\t\t\t\t\tN+=1\n\t#~ print(\"Paires d'atomes alignées : \",N)\n\t#~ print(\"Nombre résidus: \",res)\n\tif(N>0):\n\t\treturn(math.sqrt(s/N))\n\t#Sinon aucune paire n'a été alignée : retourne None (car division par 0 impossible)\n\n## calcule le rmsd entre chaque résidus des protéines pour un atome donnée (sortie : colonne 1 position du résidus; colonne 2: RMDS entre les deux conf)\n# @a : dictionnaire de la premire proteine \n# @b : dictionnaire de la deuxieme proteine\n# @liste : l'atome presente dans les proteines avec le quel on calcul le RMSD, par defaut la fonction prend le carbone alpha\ndef res_rmsd(a,b,liste=['CA']): #Atome par défaut CA\n\tnbRes = 0\n\tdicoRmsd = dict()\n\tfor mod in a.keys(): # dans les modèles\n\t\tfor dom in a[mod].keys(): # dans les domaines\t\t\t\n\t\t\tfor j in a[mod][dom].keys():# dans les chaines\n\t\t\t\tfor k in a[mod][dom][j].keys(): # dans les résidus\n\t\t\t\t\t\n\t\t\t\t\t## pour chaque résidu k, on calcul le rmsd des atomes de ce résidu et on le stoque dans un dictionnaire\n\t\t\t\t\tnbRes+=1; N = 0; s=0.0;\n\t\t\t\t\t\n\t\t\t\t\tfor l in a[mod][dom][j][k].keys(): #dans les dictionnaires d'info de chaque atome\n\t\t\t\t\t\tl2=st.selectElement(l)\n\t\t\t\t\t\tif(l2 in liste): #Si l'atome fait partie de la liste des atomes sur lesquels on calcule le rmsd:\n\t\t\t\t\t\t\ts+=pow(st.distanceAtomes(a[mod][dom][j][k][l],b[mod][dom][j][k][l]),2)\n\t\t\t\t\t\t\tN+=1\n\t\t\t\t\t\t\t\n\t\t\t\t\t# Si N>0 : Au moins 1 paire d'atome alignée pour le résidu : calcul et stockage du rmsd \n\t\t\t\t\tif(N>0):\n\t\t\t\t\t\tdicoRmsd[float(k)]=float(math.sqrt(s/N)) #Sauvegarde du RMSD du résidu k\n\t\t\t\t\n\tprint(\"Nombre résidus: \",nbRes)\n\treturn(dicoRmsd)\t\n\n## Fonction qui permettra d'afficher le graphique RMDS vs AA positions (pas de dictionnaire en entrée car temporalité importante) (liste probablement)\n# @dic : dictionnaire de RMSD\n# @lType : type de tracer, par defaut en ligne \ndef drawRMDS(dic,lType='-',title=\"A Graph Has No Name.\"):\n\tlistCle =list()\n\tlistVal =list()\n\tfor a in sorted(dic.keys()):\n\t\tlistCle.append(a)\n\t\tlistVal.append(dic[a])\n\t\n\tprint(\"Je dessine\")\n\tplt.plot(listCle,listVal,lType)\n\tplt.title(title)\n\tplt.ylabel('RMSD(A)')\n\tplt.xlabel('aa positions')\n\tprint(\"Dessin terminé !\")\n\tplt.show()\n\n\n\n\nif __name__ == '__main__':\n\tmonDico = dict()\n\t\n\t#faire un check sur les paramètres (si le bon nombre n'est pas entré ou que les fichiers n'existent pas, on retourne usage().\n\tif (len(sys.argv) == 4):\n\t\tprot1 =sys.argv[1]\n\t\tprot2 =sys.argv[2]\n\t\tficAtome=sys.argv[3]\n\t\tprint(\"Fichier \",ficAtome,\" fourni comme fichier d'atomes !\")\n\telif (len(sys.argv)== 3):\n\t\tprot1 =sys.argv[1]\n\t\tprot2 =sys.argv[2]\n\t\tprint(\"Default mode !\")\n\telse:\n\t\tprint(\"Le format d'entrée attendu est : structureTools_TaylorArnaud.py fichier_1.PDB fichier_2.PDB [atomes.txt]\")\n\t\texit()\n\t\t\n\t\n\t# Récupérer la fonction lirePDB d'arnaud pour cette partie car on a pas besoin de l'info sur les atomes.\n\t# Ou ajouter à la fonction lirePDB une valeur par défaut genre : useAtomWeight = FALSE par défaut. Si True, on utilise le fichier atome.txt\n\tdicoProt1 = st.lirePDB(prot1)\n\tdicoProt2 = st.lirePDB(prot2)\n\n\t#~ #Calculer rmsd\n\t\n\tdicTest = res_rmsd(dicoProt1,dicoProt2)\n\tprint(len(dicTest))\n\tdrawRMDS(dicTest)\n","sub_path":"rmsd.py","file_name":"rmsd.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"584694421","text":"from math import log, inf\n\n\nclass Node:\n leaves = []\n\n def __init__(self, attribute, children=None):\n self.attribute = attribute\n self.children = children\n self.parent = None\n self.next = None\n\n\ndef ID3(R, S, Y): # R - non-categorical attributes, S - training set, Y - classes\n if not S:\n return Node('Failure')\n value = set()\n for i in S:\n value.add(i['class'])\n if len(value) > 1:\n break\n\n if len(value) == 1:\n n = Node(value.pop())\n Node.leaves.append(n)\n return n\n\n if not R:\n count = dict.fromkeys(Y, 0)\n for i in S:\n count[i['class']] += 1\n\n maxCount = -inf\n for x, y in count.items():\n if y > maxCount:\n maxCount = y\n ans = x\n\n n = Node(ans)\n Node.leaves.append(n)\n return n\n\n maxInfGain = -inf\n ent = entropy(S, Y)\n for i in R:\n InfGain = ent - AveInfEnt(R, i, S, Y)\n if InfGain > maxInfGain:\n maxInfGain = InfGain\n d = i\n\n root = Node(d, list(R[d]))\n R.pop(d)\n child = []\n for i in root.children:\n child.append(ID3(R, [x for x in S if x[d] == i], Y))\n\n for i in child:\n i.parent = root\n\n root.next = child\n\n return root\n\n\ndef entropy(S, Y):\n count = dict.fromkeys(Y, 0)\n\n for i in S:\n count[i['class']] += 1\n\n entr = 0\n for i in count.values():\n if i != 0:\n entr -= (i/len(S) * log(i/len(S)))\n\n return entr\n\n\ndef AveInfEnt(R, attr, S, Y):\n\n ans = 0\n for i in R[attr]:\n S_attr = [x for x in S if x[attr] == i]\n ans += len(S_attr)/len(S)*entropy(S_attr, Y)\n\n return ans\n","sub_path":"andrzej/drzewo/ID3.py","file_name":"ID3.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375852986","text":"import base64\nimport urllib2\nfrom email import message_from_string\nfrom email.utils import parseaddr\n\nfrom django.conf import settings\nfrom django.core.files.storage import get_storage_class\n\nimport commonware.log\nimport waffle\nfrom email_reply_parser import EmailReplyParser\n\nfrom mkt.access import acl\nfrom mkt.access.models import Group\nfrom mkt.comm.models import (CommunicationNoteRead, CommunicationThreadToken,\n user_has_perm_thread)\nfrom mkt.constants import comm\nfrom mkt.users.models import UserProfile\n\n\nlog = commonware.log.getLogger('comm')\n\n\nclass CommEmailParser(object):\n \"\"\"Utility to parse email replies.\"\"\"\n\n address_prefix = comm.REPLY_TO_PREFIX\n\n def __init__(self, email_text):\n \"\"\"Decode base64 email and turn it into a Django email object.\"\"\"\n try:\n email_text = base64.standard_b64decode(\n urllib2.unquote(email_text.rstrip()))\n except TypeError:\n # Corrupt or invalid base 64.\n self.decode_error = True\n return\n\n self.email = message_from_string(email_text)\n self.reply_text = EmailReplyParser.read(self.email.get_payload()).reply\n\n def _get_address_line(self):\n return parseaddr(self.email['to'])\n\n def get_uuid(self):\n name, addr = self._get_address_line()\n\n if addr.startswith(self.address_prefix):\n # Strip everything between \"reply+\" and the \"@\" sign.\n uuid = addr[len(self.address_prefix):].split('@')[0]\n else:\n log.info('TO: address missing or not related to comm. (%s)'\n % unicode(self.email).strip())\n return False\n\n return uuid\n\n def get_body(self):\n return self.reply_text\n\n\ndef save_from_email_reply(reply_text):\n parser = CommEmailParser(reply_text)\n if hasattr(parser, 'decode_error'):\n return False\n\n uuid = parser.get_uuid()\n\n if not uuid:\n return False\n try:\n tok = CommunicationThreadToken.objects.get(uuid=uuid)\n except CommunicationThreadToken.DoesNotExist:\n log.error('An email was skipped with non-existing uuid %s.' % uuid)\n return False\n\n if user_has_perm_thread(tok.thread, tok.user) and tok.is_valid():\n # Deduce an appropriate note type.\n note_type = comm.NO_ACTION\n if (tok.user.addonuser_set.filter(addon=tok.thread.addon).exists()):\n note_type = comm.DEVELOPER_COMMENT\n elif acl.action_allowed_user(tok.user, 'Apps', 'Review'):\n note_type = comm.REVIEWER_COMMENT\n\n t, note = create_comm_note(tok.thread.addon, tok.thread.version,\n tok.user, parser.get_body(),\n note_type=note_type)\n log.info('A new note has been created (from %s using tokenid %s).'\n % (tok.user.id, uuid))\n return note\n elif tok.is_valid():\n log.error('%s did not have perms to reply to comm email thread %s.'\n % (tok.user.email, tok.thread.id))\n else:\n log.error('%s tried to use an invalid comm token for thread %s.'\n % (tok.user.email, tok.thread.id))\n\n return False\n\n\ndef filter_notes_by_read_status(queryset, profile, read_status=True):\n \"\"\"\n Filter read/unread notes using this method.\n\n `read_status` = `True` for read notes, `False` for unread notes.\n \"\"\"\n # Get some read notes from db.\n notes = list(CommunicationNoteRead.objects.filter(\n user=profile).values_list('note', flat=True))\n\n if read_status:\n # Filter and return read notes if they exist.\n return queryset.filter(pk__in=notes) if notes else queryset.none()\n else:\n # Exclude read notes if they exist.\n return queryset.exclude(pk__in=notes) if notes else queryset.all()\n\n\ndef get_reply_token(thread, user_id):\n tok, created = CommunicationThreadToken.objects.get_or_create(\n thread=thread, user_id=user_id)\n\n # We expire a token after it has been used for a maximum number of times.\n # This is usually to prevent overusing a single token to spam to threads.\n # Since we're re-using tokens, we need to make sure they are valid for\n # replying to new notes so we reset their `use_count`.\n if not created:\n tok.update(use_count=0)\n else:\n log.info('Created token with UUID %s for user_id: %s.' %\n (tok.uuid, user_id))\n return tok\n\n\ndef get_recipients(note):\n \"\"\"\n Determine email recipients based on a new note based on those who are on\n the thread_cc list and note permissions.\n Returns reply-to-tokenized emails.\n \"\"\"\n thread = note.thread\n recipients = []\n\n # Whitelist: include recipients.\n if note.note_type == comm.ESCALATION:\n # Email only senior reviewers on escalations.\n seniors = Group.objects.get(name='Senior App Reviewers')\n recipients = seniors.users.values_list('id', 'email')\n else:\n # Get recipients via the CommunicationThreadCC table, which is usually\n # populated with the developer, the Mozilla contact, and anyone that\n # posts to and reviews the app.\n recipients = set(thread.thread_cc.values_list(\n 'user__id', 'user__email'))\n\n # Blacklist: exclude certain people from receiving the email based on\n # permission.\n excludes = []\n if not note.read_permission_developer:\n # Exclude developer.\n excludes += thread.addon.authors.values_list('id', 'email')\n # Exclude note author.\n excludes.append((note.author.id, note.author.email))\n # Remove excluded people from the recipients.\n recipients = [r for r in recipients if r not in excludes]\n\n # Build reply-to-tokenized email addresses.\n new_recipients_list = []\n for user_id, user_email in recipients:\n tok = get_reply_token(note.thread, user_id)\n new_recipients_list.append((user_email, tok.uuid))\n\n return new_recipients_list\n\n\ndef send_mail_comm(note):\n \"\"\"\n Email utility used globally by the Communication Dashboard to send emails.\n Given a note (its actions and permissions), recipients are determined and\n emails are sent to appropriate people.\n \"\"\"\n from mkt.reviewers.utils import send_mail\n\n if not waffle.switch_is_active('comm-dashboard'):\n return\n\n recipients = get_recipients(note)\n name = note.thread.addon.name\n data = {\n 'name': name,\n 'sender': note.author.name,\n 'comments': note.body,\n 'thread_id': str(note.thread.id)\n }\n\n subject = {\n comm.ESCALATION: u'Escalated Review Requested: %s' % name,\n }.get(note.note_type, u'Submission Update: %s' % name)\n\n log.info(u'Sending emails for %s' % note.thread.addon)\n for email, tok in recipients:\n reply_to = '{0}{1}@{2}'.format(comm.REPLY_TO_PREFIX, tok,\n settings.POSTFIX_DOMAIN)\n send_mail(subject, 'reviewers/emails/decisions/post.txt', data,\n [email], perm_setting='app_reviewed', reply_to=reply_to)\n\n\ndef create_comm_note(app, version, author, body, note_type=comm.NO_ACTION,\n perms=None, no_switch=False, attachments=None):\n \"\"\"\n Creates a note on an app version's thread.\n Creates a thread if a thread doesn't already exist.\n CC's app's Mozilla contacts to auto-join thread.\n\n app -- app object.\n version -- app version.\n author -- UserProfile for the note's author.\n body -- string/text for note comment.\n note_type -- integer for note_type (mkt constant), defaults to 0/NO_ACTION\n (e.g. comm.APPROVAL, comm.REJECTION, comm.NO_ACTION).\n perms -- object of groups to grant permission to, will set flags on Thread.\n (e.g. {'developer': False, 'staff': True}).\n no_switch -- whether to ignore comm switch, needed after we migrate\n reviewer tools from ActivityLog to notes.\n attachments -- formset of attachment files\n\n \"\"\"\n if not no_switch and not waffle.switch_is_active('comm-dashboard'):\n return None, None\n\n # Dict of {'read_permission_GROUP_TYPE': boolean}.\n # Perm for reviewer, senior_reviewer, moz_contact, staff True by default.\n # Perm for developer False if is escalation or reviewer comment by default.\n perms = perms or {}\n if 'developer' not in perms and note_type in (comm.ESCALATION,\n comm.REVIEWER_COMMENT):\n perms['developer'] = False\n create_perms = dict(('read_permission_%s' % key, has_perm)\n for key, has_perm in perms.iteritems())\n\n # Create thread + note.\n thread, created_thread = app.threads.safer_get_or_create(\n version=version, defaults=create_perms)\n note = thread.notes.create(\n note_type=note_type, body=body, author=author, **create_perms)\n\n if attachments:\n create_attachments(note, attachments)\n\n post_create_comm_note(note)\n\n return thread, note\n\n\ndef post_create_comm_note(note):\n \"\"\"Stuff to do after creating note, also used in comm api's post_save.\"\"\"\n thread = note.thread\n app = thread.addon\n\n # Add developer to thread.\n for developer in app.authors.all():\n thread.join_thread(developer)\n\n # Add Mozilla contact to thread.\n for email in app.get_mozilla_contacts():\n try:\n moz_contact = UserProfile.objects.get(email=email)\n thread.join_thread(moz_contact)\n except UserProfile.DoesNotExist:\n pass\n\n # Add note author to thread.\n author = note.author\n cc, created_cc = thread.join_thread(author)\n if not created_cc:\n # Mark their own note as read.\n note.mark_read(note.author)\n\n # Send out emails.\n send_mail_comm(note)\n\n\ndef create_attachments(note, formset):\n \"\"\"Create attachments from CommAttachmentFormSet onto note.\"\"\"\n errors = []\n storage = get_storage_class()()\n\n for form in formset:\n if not form.is_valid():\n errors.append(form.errors)\n continue\n\n data = form.cleaned_data\n if not data:\n continue\n\n attachment = data['attachment']\n attachment_name = _save_attachment(\n storage, attachment,\n '%s/%s' % (settings.REVIEWER_ATTACHMENTS_PATH, attachment.name))\n\n note.attachments.create(\n description=data.get('description'), filepath=attachment_name,\n mimetype=attachment.content_type)\n\n return errors\n\n\ndef _save_attachment(storage, attachment, filepath):\n \"\"\"Saves an attachment and returns the filename.\"\"\"\n filepath = storage.save(filepath, attachment)\n # In case of duplicate filename, storage suffixes filename.\n return filepath.split('/')[-1]\n","sub_path":"mkt/comm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"402536643","text":"#! python3\n# sudoku_solver.py - solves the Sudoku 9x9 square like a real human \n# would, checking for possible value in a 3x3 square, row or column \n# where 1x1 cell belongs.\n\n# grid variable represents Sudoku cell where zeros stand for emty square.\ngrid = [[0, 0, 0, 0, 0, 0, 0, 8, 0],\n [6, 8, 0, 4, 7, 0, 0, 2, 0],\n [0, 1, 9, 5, 0, 8, 6, 4, 7],\n [0, 6, 0, 9, 0, 0, 0, 0, 4],\n [3, 4, 2, 6, 8, 0, 0, 0, 0],\n [1, 9, 0, 0, 5, 0, 8, 3, 0],\n [0, 0, 0, 7, 2, 0, 4, 0, 3],\n [0, 0, 0, 0, 0, 5, 0, 1, 0],\n [0, 0, 3, 8, 9, 1, 5, 0, 0]]\n\n# Set, which subtracting the values from we will \n# get the set of possible values for each square\nsubtract_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n\ndef print_grid(grid):\n ''' Displays Sudoku on the screen '''\n for i in range(len(grid)):\n if i % 3 == 0 and i != 0:\n print('- - - - - - - - - - - -')\n\n for j in range(len(grid[0])):\n if j % 3 == 0 and j != 0:\n print(' | ', end='')\n\n if j == 8:\n print(grid[i][j])\n else:\n print(str(grid[i][j]) + ' ', end='')\n\n\n# check_ functions finds possible values for each 1x1 square \n# (i and j its indexes) in a row, column and 3x3 square.\ndef check_horizontal(i, j):\n '''Searching for possible values horizontally'''\n return subtract_set - set(grid[i])\n\n\ndef check_vertical(i, j):\n '''Searching for possible values vertically checking each row.'''\n return_set = []\n for n in range(9):\n return_set.append(grid[n][j])\n return subtract_set - set(return_set)\n\n\ndef check_square(i, j):\n '''Searching for possible valuws in the 3x3 square.'''\n \n # Finds the 3x3 square of the selected value and its indexes \n # ([0, 1, 2] or [3, 4, 5] or [6, 7, 8]).\n first = [0, 1, 2]\n second = [3, 4, 5]\n third = [6, 7, 8]\n find_square = [first, second, third]\n for p in find_square:\n if i in p:\n row = p\n if j in p:\n col = p\n \n # Checks the possible values in the found 3x3 square .\n return_set = []\n for x in row:\n for y in col:\n return_set.append(grid[x][y])\n return subtract_set - set(return_set)\n\n\ndef get_poss_vals(i, j):\n '''Finds the common possible values for 1x1 square, combining founded \n sets of possible values in a row, column and square'''\n poss_vals = list(check_square(i, j).intersection(check_horizontal(i, j)) \\\n .intersection(check_vertical(i, j)))\n return poss_vals\n\n\ndef solver(grid):\n '''Main function which will go through each empty 1x1 square and\n finding the only possible value for it until there is more \n than one empty square'''\n while True:\n zeros = 0\n # i iterates through columns, j through rows\n # zeros - is a number of empty 1x1 squares\n for i in range(9):\n for j in range(9):\n if grid[i][j] == 0:\n poss_vals = get_poss_vals(i, j)\n if len(poss_vals) == 1:\n grid[i][j] = poss_vals[0]\n \n if grid[i][j] == 0:\n zeros += 1\n if zeros == 0:\n return grid\n\n\n \ngrid = solver(grid)\nprint_grid(grid)\n","sub_path":"sudoku_solver.py","file_name":"sudoku_solver.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496594031","text":"import re\n\nfrom requests_html import HTML\n\nfrom scylla.database import ProxyIP\nfrom .base_provider import BaseProvider\n\n\nclass ProxyNovaProvider(BaseProvider):\n\n def parse(self, html: HTML) -> [ProxyIP]:\n ip_list: [ProxyIP] = []\n\n for tr in html.find('#tbl_proxy_list > tbody:nth-child(2) > tr'):\n if not 'data-proxy-id' in tr.attrs:\n continue\n\n script_element = tr.find('td:nth-child(1) > abbr > script', first=True)\n port_element = tr.find('td:nth-child(2)', first=True)\n if not script_element or not port_element:\n continue\n\n groups = re.findall(r\"document\\.write\\('12345678(\\d{1,3}\\.\\d{1,3})'\\.substr\\(8\\) \\+ '(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'\\)\", script_element.text)\n if not groups or len(groups) != 1:\n continue\n ip = groups[0][0] + groups[0][1]\n port = port_element.text\n ip_list.append(ProxyIP(ip=ip, port=port))\n return ip_list\n\n def urls(self) -> [str]:\n return ['https://www.proxynova.com/proxy-server-list/']\n\n @staticmethod\n def should_render_js() -> bool:\n return False\n\n","sub_path":"scylla/providers/proxynova_provider.py","file_name":"proxynova_provider.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"603327924","text":"#-*-coding:utf-8-*- \r\n#保存每天每个艺人被操作的用户数,即有多少用户操作这个艺人的歌曲\r\n__author__ = 'yxt'\r\n#4,order by一个,5二个,6,2个并且写入文件\r\nimport MySQLdb\r\nimport csv\r\n\r\n# 打开数据库连接\r\ndb=MySQLdb.connect('localhost','root','yxt','tianchi')\r\n# 使用cursor()方法获取操作游标 \r\ncursor = db.cursor()\r\n# 使用execute方法执行SQL语句\r\nsql='select artist_id,count(user_id),Ds from songs,user_actions where songs.song_id=user_actions.song_id group by artist_id,Ds order by artist_id'\r\ncursor.execute(sql)\r\n# 使用 fetchone() 方法获取一条数据库。\r\n# 使用 fetchall() 方法获取一条数据库。,得到的为tuple,((),())\r\ndata = cursor.fetchall()\r\nwith open('out_listener2222222222.csv','wb')as f:\r\n\tw=csv.writer(f)\r\n\tw.writerows(data)\r\n# 关闭数据库连接\r\ndb.close()\r\n","sub_path":"timeseries/art_listener_day.py","file_name":"art_listener_day.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"193050075","text":"#!/usr/bin/env python\n#\n\nimport datetime\nimport unittest\nimport os\nimport sys\nfrom AxisMr import AxisMr\nfrom AxisCom import AxisCom\n\nfilnam = \"123xx.py\"\n\n###\n\n\nclass Test(unittest.TestCase):\n url_string = os.getenv(\"TESTEDMOTORAXIS\")\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} url_string={url_string}\"\n )\n\n axisCom = AxisCom(url_string, log_debug=False)\n axisMr = AxisMr(axisCom)\n\n # self.axisCom.put('-DbgStrToLOG', \"Start \" + os.path.basename(__file__)[0:20])\n\n hlm = axisCom.get(\".HLM\")\n llm = axisCom.get(\".LLM\")\n jvel = axisCom.get(\".JVEL\")\n\n margin = 1.1\n # motorRecord stops jogging 1 second before reaching HLM\n jog_start_pos = hlm - jvel - margin\n\n msta = int(axisCom.get(\".MSTA\"))\n\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} llm={llm:f} hlm={hlm:f} jog_start_pos={jog_start_pos:f}\"\n )\n\n # Assert that motor is homed\n def test_TC_1231(self):\n tc_no = \"1231\"\n if not (self.msta & self.axisMr.MSTA_BIT_HOMED):\n self.axisMr.powerOnHomeAxis(tc_no)\n self.msta = int(self.axisCom.get(\".MSTA\"))\n self.assertNotEqual(\n 0,\n self.msta & self.axisMr.MSTA_BIT_HOMED,\n \"MSTA.homed (Axis is not homed)\",\n )\n\n # per90 UserPosition\n def test_TC_1232(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1232\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisMr.moveWait(tc_no, self.jog_start_pos)\n UserPosition = self.axisCom.get(\".RBV\", use_monitor=False)\n print(\n \"%s postion=%f jog_start_pos=%f\"\n % (tc_no, UserPosition, self.jog_start_pos)\n )\n\n # High soft limit in controller when using MoveVel\n def test_TC_1233(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"1233\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n\n jar = self.axisCom.get(\".JAR\")\n self.axisCom.put(\"-ACCS\", jar)\n\n rbv = self.axisCom.get(\".RBV\")\n destination = self.axisCom.get(\".HLM\") + 1\n jvel = self.axisCom.get(\".JVEL\")\n timeout = self.axisMr.calcTimeOut(destination, jvel)\n print(\n f\"{tc_no} rbv={rbv:f} destination={destination:f} timeout={timeout:f}\"\n )\n res = self.axisCom.put(\"-MoveVel\", jvel)\n # TODO: The -MoveVel PV is not always there ?\n # Investigations needed\n # if (res == None):\n # print('%s caput -MoveVel res=None' % (tc_no))\n # self.assertNotEqual(res, None, 'caput -MoveVel retuned not None. PV not found ?')\n # else:\n # print('%s caput -MoveVel res=%d' % (tc_no, res))\n # self.assertEqual(res, 1, 'caput -MoveVel returned 1')\n\n self.axisMr.waitForStartAndDone(tc_no, timeout)\n\n msta = int(self.axisCom.get(\".MSTA\"))\n miss = int(self.axisCom.get(\".MISS\"))\n\n if msta & self.axisMr.MSTA_BIT_PROBLEM:\n self.axisMr.resetAxis(tc_no)\n\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_MINUS_LS,\n \"DLY Minus hard limit not reached MoveVel\",\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PLUS_LS,\n \"DLY Plus hard limit not reached MoveVel\",\n )\n self.assertEqual(0, miss, \"DLY MISS not set MoveVel\")\n\n # per90 UserPosition\n def test_TC_1234(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"TC-1234-90-percent-UserPosition\"\n print(f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}\")\n self.axisMr.moveWait(tc_no, self.jog_start_pos)\n UserPosition = self.axisCom.get(\".RBV\", use_monitor=False)\n print(\n \"%s postion=%f jog_start_pos=%f\"\n % (tc_no, UserPosition, self.jog_start_pos)\n )\n\n # High soft limit in controller when using MoveAbs\n def test_TC_1235(self):\n if self.msta & self.axisMr.MSTA_BIT_HOMED:\n tc_no = \"TC-1235-high-soft-limit-Moveabs\"\n print(\n f\"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} {tc_no}: Start\"\n )\n drvUseEGU = self.axisCom.get(\"-DrvUseEGU-RB\")\n if drvUseEGU == 1:\n mres = 1.0\n else:\n mres = self.axisCom.get(\".MRES\")\n rbv = self.axisCom.get(\".RBV\")\n\n jar = self.axisCom.get(\".JAR\")\n self.axisCom.put(\"-ACCS\", jar / mres)\n\n jvel = self.axisCom.get(\".JVEL\")\n self.axisCom.put(\"-VELO\", jvel / mres)\n\n destination = self.hlm + 1\n timeout = self.axisMr.calcTimeOut(destination, jvel)\n print(\n f\"{tc_no}: rbv={rbv:f} destination={destination:f} timeout={timeout:f}\"\n )\n\n res = self.axisCom.put(\"-MoveAbs\", (destination) / mres)\n # if (res == None):\n # print('%s caput -Moveabs res=None' % (tc_no))\n # self.assertNotEqual(res, None, 'caput -Moveabs retuned not None. PV not found ?')\n # else:\n # print('%s caput -Moveabs res=%d' % (tc_no, res))\n # self.assertEqual(res, 1, 'caput -Moveabs returned 1')\n\n self.axisMr.waitForStartAndDone(tc_no, timeout)\n\n msta = int(self.axisCom.get(\".MSTA\"))\n miss = int(self.axisCom.get(\".MISS\"))\n self.axisMr.verifyRBVinsideRDBD(tc_no, destination)\n\n if msta & self.axisMr.MSTA_BIT_PROBLEM:\n self.axisMr.resetAxis(tc_no)\n # TODO: Check error; errorId\n\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_MINUS_LS,\n \"DLY Minus hard limit not reached Moveabs\",\n )\n self.assertEqual(\n 0,\n msta & self.axisMr.MSTA_BIT_PLUS_LS,\n \"DLY Plus hard limit not reached Moveabs\",\n )\n self.assertEqual(0, miss, \"DLY MISS not set Moveabs\")\n","sub_path":"test/pytests36/123_Ethercat-MoveVel_MCU_Hsoftlimit.py","file_name":"123_Ethercat-MoveVel_MCU_Hsoftlimit.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582066297","text":"# torch.multiprocessing.set_start_method(\"forkserver\")\nfrom utils.exp_logger import setup_logging_from_config\nfrom huepy import yellow \n# from models.model import save_model\nfrom munch import munchify\nfrom pathlib import Path\n\nfrom utils.io_utils import save_yaml, load_yaml\nfrom utils.eval import eval_modules, eval_paths\nfrom utils.utils import setup\n\nimport argparse\nimport os\nimport sys\nimport time\nimport torch\nfrom torch import nn\nimport torch.multiprocessing\n\nFILE_PATH = os.path.abspath(os.path.dirname(__file__))\nRECOGNITION_PATH = os.path.abspath(FILE_PATH + '/..')\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\ntorch.autograd.set_detect_anomaly(True)\n\ndef get_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--config', type=str, default='config.yml')\n return parser\n\nparser = get_args()\n\n\n# Gather args across modules\nargs = parser.parse_args()\n\nconfig = load_yaml(args.config)\nextension = config['extension']\nsys.path.append(RECOGNITION_PATH)\nsys.path.append(f'extensions/{extension}')\n\n\n# Setup logging and creates save dir\nwriter = setup_logging_from_config(config, exp_name_use_date=True)\n\n# Dump args\nsave_yaml(config, Path(config['experiment_dir'])/'config.yml')\n\neval_modules(config)\neval_paths(config)\n\nconfig['dumps_dir'] = config['experiment_dir']/'dumps'\n\n\n\n# Setup everything else\n# setup(config)\n\n# Load dataloaders\ndata_factory = config['data_factory_fn'](config)\n \ndataloader_train = data_factory.make_loader(is_train=True)\ndataloader_val = data_factory.make_loader(is_train=False)\n\nprint(len(dataloader_train), len(dataloader_val))\nwrapper = config['wrapper_fn']()\npipeline = wrapper.get_pipeline(config, data_factory)#.to(device)\n \ntrain_factory = config['train_factory_fn']\n\n# Load runner\nrunner = config['runner_fn']#(config)\n\n# Load saver\n# saver = get_saver('DummySaver')\n\n\n\n# def set_param_grad(model, value, set_eval_mode=True):\n# for param in model.parameters():\n# param.requires_grad = value\n \n# if set_eval_mode:\n# model.eval()\n\n# Run \nfor stage_num, (stage_name, stage_args_) in enumerate(config['stages'].items()):\n\n print (yellow(f' - Starting stage \"{stage_name}\"!'))\n\n stage_args = munchify({**stage_args_, **config['train_args'] }) \n\n optimizers = train_factory.make_optimizers(stage_args, pipeline)\n schedulers = train_factory.make_schedulers(stage_args, optimizers, pipeline)\n \n \n print('schedulers', schedulers.keys())\n train_factory.set_trainable(stage_args, pipeline)\n criterions = train_factory.make_criterions(stage_args)\n \n print('criterions', criterions.keys())\n \n if stage_args.parallel:\n pipeline = nn.DataParallel(pipeline)\n# print(pipeline)\n\n# if args.fp16:\n# import apex \n\n# optimizer = apex.fp16_utils.FP16_Optimizer(optimizer, dynamic_loss_scale=True, verbose=False)\n# else:\n# optimizer.backward = lambda x: x.backward()\n \n # Go\n for epoch in range(0, stage_args.num_epochs):\n dumps_dir = config['dumps_dir']/str(epoch)\n os.makedirs(dumps_dir, exist_ok=True)\n pipeline.train()\n \n# if epoch % stage_args.save_frequency == 0:\n# if isinstance(pipeline, nn.DataParallel):\n# pipeline.module.save(config['dumps_dir'], epoch, stage_args)\n# else:\n# pipeline.save(config['dumps_dir'], epoch, stage_args)\n# if stage_args.save_optimizers:\n# torch.save(optimizers, config['dumps_dir']/f'optimizers{epoch}')\n \n # ===================\n # Train\n # ===================\n with torch.set_grad_enabled(True):\n runner.run_epoch(dataloader_train, pipeline, criterions, optimizers, epoch, stage_args, phase='train', writer=writer, dumps_dir=dumps_dir)\n \n\n\n # ===================\n # Validate\n # ===================\n torch.cuda.empty_cache()\n \n pipeline.eval()\n \n \n with torch.set_grad_enabled(False):\n if stage_args.supervised_eval:\n val_loss = runner.run_epoch(dataloader_val, pipeline, criterions, None, epoch, stage_args, phase='val', writer=writer, dumps_dir=dumps_dir)\n else:\n runner.evaluate(dataloader_val, pipeline, epoch, stage_args, writer)\n \n \n for k, scheduler in schedulers.items():\n if isinstance(scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) and stage_args.supervised_eval:\n scheduler.step(val_loss)\n else:\n scheduler.step()\n\n\n # Save\n if epoch % stage_args.save_frequency == 0:\n if isinstance(pipeline, nn.DataParallel):\n pipeline.module.save(config['dumps_dir'], epoch, stage_args)\n else:\n pipeline.save(config['dumps_dir'], epoch, stage_args)\n if stage_args.save_optimizers:\n torch.save(optimizers, config['dumps_dir']/f'optimizers{epoch}')\n# save_model(model, epoch, stage_args, optimizer, stage_num)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"595521993","text":"# -*- coding: utf-8 -*-\n\n# pyHEMCO GUI: a graphical user interface for the Harvard Emission Component (HEMCO).\n# \n# History:\n# 27 Jun 2014 - C. Keller - Initial version\n# \n\n# imports\nimport sys, os\nsys.path.append('/Users/Christoph/Documents/PROJECTS/HEMCO/prog/PyProg/pyHEMCO')\nfrom pygchem import emissions\nfrom pyhemco_gui_cls import *\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\ntry:\n _fromUtf8 = QString.fromUtf8\nexcept AttributeError:\n def _fromUs():\n return s\n \ntry:\n _encoding = QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QApplication.translate(context, text, disambig)\n\n\nDEFAULT_FILE_PATH = '/Users/Christoph/Documents/PROJECTS/HEMCO/prog/PyProg/pyHEMCO'\n\n#-----------------------------------------------------------------------------\n# Display class definitions \n#-----------------------------------------------------------------------------\nclass Ui_MainWindow(QMainWindow):\n \"\"\"\n GUI main window.\n \"\"\"\n \n def __init__(self,parent=None):\n super(Ui_MainWindow, self).__init__(parent)\n self.setupUi(self)\n self.ConfigSetup = []\n self.outfile = \"\"\n \n def setupUi(self, MainWindow):\n \"\"\"\n GUI main window constructor.\n \"\"\"\n MainWindow.setObjectName(_fromUtf8(\"MainWindow\"))\n MainWindow.resize(600, 400)\n \n self.centralWidget = QWidget(MainWindow)\n self.centralWidget.setObjectName(_fromUtf8(\"centralWidget\")) \n MainWindow.setCentralWidget(self.centralWidget)\n\n self.menuBar = QMenuBar(MainWindow)\n self.menuBar.setGeometry(QRect(0, 0, 600, 22))\n self.menuBar.setObjectName(_fromUtf8(\"menuBar\"))\n MainWindow.setMenuBar(self.menuBar)\n\n self.mainToolBar = QToolBar(MainWindow)\n self.mainToolBar.setObjectName(_fromUtf8(\"mainToolBar\"))\n MainWindow.addToolBar(Qt.TopToolBarArea, self.mainToolBar)\n \n self.statusBar = QStatusBar(MainWindow)\n self.statusBar.setObjectName(_fromUtf8(\"statusBar\"))\n MainWindow.setStatusBar(self.statusBar)\n \n # label showing currently loaded/edited configuration file\n self.configFileLabel = QLabel(\"no configuration file loaded yet\", MainWindow)\n self.configFileLabel.setGeometry(QRect(50, 20, 300, 32))\n \n # table view showing base emissions. Populated upon clicking \n # pushButton_Load (-> call of configLoad)\n self.SetupLabel = QLabel(\"Emission setup\", MainWindow)\n self.SetupLabel.setGeometry(QRect(50, 50, 200, 32))\n\n self.SetupTreeView = QTreeView(MainWindow)\n self.SetupTreeView.setGeometry(QRect(50, 80, 250, 250))\n\n # table view showing scale factors of selected base emissions\n self.EmisTableLabel = QLabel(\"Field details\", MainWindow)\n self.EmisTableLabel.setGeometry(QRect(320, 50, 200, 32))\n \n self.EmisTableView = QTableView(MainWindow)\n self.EmisTableView.setGeometry(QRect(320, 80, 250, 250)) \n\n # push buttons to load/save configuration files\n self.pushButton_Load = QPushButton(self.centralWidget)\n self.pushButton_Load.setGeometry(QRect(50, 330, 114, 32))\n self.pushButton_Load.setObjectName(_fromUtf8(\"pushButton_Load\"))\n self.pushButton_Load.clicked.connect(self.configFileLoad)\n \n self.pushButton_Save = QPushButton(self.centralWidget)\n self.pushButton_Save.setGeometry(QRect(170, 330, 114, 32))\n self.pushButton_Save.setObjectName(_fromUtf8(\"pushButton_Save\"))\n self.pushButton_Save.clicked.connect(self.configFileSave)\n\n self.retranslateUi(MainWindow)\n QMetaObject.connectSlotsByName(MainWindow)\n \n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"A super simple HEMCO GUI\", None))\n self.pushButton_Load.setText(_translate(\"MainWindow\", \"Load\", None))\n self.pushButton_Save.setText(_translate(\"MainWindow\", \"Save\", None))\n\n def configFileLoad(self):\n \"\"\"\n Loads the content of a configuration file and displays it's content in the\n base emission and scale factor view.\n \"\"\"\n # select file and read it.\n infile = QFileDialog.getOpenFileName(self, \"Open file\", DEFAULT_FILE_PATH, \n \"All Files(*);;Text Files (*.txt)\")\n self.ConfigSetup = emissions.load_setup(infile)\n \n # create the tree view model.\n self.SetupEmisTreeViewModel()\n \n # Save file name and update file label.\n self.outfile = infile\n self.updateConfigFileLabel()\n self.statusBar.showMessage(os.path.basename(str(infile))+' loaded')\n\n def configFileSave(self):\n \"\"\"\n Saves the configuration file onto disk.\n \"\"\"\n # select file and save it to disk\n self.outfile = QFileDialog.getSaveFileName(self, \"Save file\", DEFAULT_FILE_PATH, \n \"All Files(*);;Text Files (*.txt)\")\n self.statusBar.showMessage('Not implemented yet!')\n# self.ConfigSetup.save(self.outfile)\n \n # update view\n# self.updateConfigFileLabel() \n# self.statusBar.showMessage(os.path.basename(str(self.outfile))+' written')\n \n def updateConfigFileLabel(self):\n \"\"\"\n Displays the file name of the currently editing configuration file.\n \"\"\" \n self.configFileLabel.setText(\"Editing: \" + os.path.basename(str(self.outfile))) \n \n def SetupEmisTreeViewModel(self):\n \"\"\"\n Creates a tree view model from the current configuration setup.\n \"\"\"\n self.TreeViewModel = EmisTreeViewModel(self.ConfigSetup,self)\n self.SetupTreeView.setModel(self.TreeViewModel)\n \n # Connections:\n # - If selecting a field in the tree view, create a sub-model of it in the\n # EditTableView window so that users can edit it.\n self.SetupTreeView.selectionModel().currentChanged.connect(self.EmisTableModelGet)\n \n def EmisTableModelGet(self,currindex,previndex):\n \"\"\"\n Creates an editable display model of the currently selected data.\n \"\"\" \n thisNode = self.TreeViewModel.getNode(currindex)\n thisNode.EmisTableModelCreate()\n self.EmisTableView.setModel(thisNode.EmisTableModel) \n \n#-----------------------------------------------------------------------------\n# Run GUI\n#-----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n MainWindow = QMainWindow()\n ui = Ui_MainWindow()\n ui.setupUi(MainWindow)\n \n MainWindow.show()\n sys.exit(app.exec_())\n\n","sub_path":"pyhemco_gui.py","file_name":"pyhemco_gui.py","file_ext":"py","file_size_in_byte":6973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"271358282","text":"'''\nf. To Count the Frequency of Words Appearing in a String Using a Dictionary. \n'''\n\nx = {i:i**2 for i in range(1,10)}\ny = {i:i**2 for i in range(10,20)}\nx.update(y)\nprint(x)\n\nfor i in sorted(x.keys(),reverse=True):\n print(i,\" = \",x[i])\n\nprint(sorted(list(set(i for i in x.values()))))\n\nprint(x[len(x)],\"+\",x[len(x)-1],\"+\",x[len(x)-2])\n\ny = {}\nx = input(\"Enter the string: \")\n\nfor i in str(x):\n\tif i in y.keys():\n\t\ty[i] = y[i] + 1\n\telse:\n\t\ty.update({i:1})\nfor a,b in y.items():\n\tprint(a,\" = \",b,\"\")\n\n","sub_path":"experiments/exp4.py","file_name":"exp4.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"273260481","text":"import os\nimport time\nimport copy\nimport argparse\ndef read_from_file(path):\n crossword_file = open(path,'r')\n # read board size`\n size = int(crossword_file.readline())\n # read board map\n board = []\n for i in range(size):\n board.append(crossword_file.readline()[:-1])\n # read word list\n word_line = crossword_file.readline()\n word_list = []\n word_list = word_line.split(';')\n word_list.sort(key=lambda item: (-len(item), item))\n return size, board, word_list\n\ndef check_duplicate(word_list):\n duplicate_count = []\n i = 0\n while i=0 and j>=0\n\ndef horizontal_check(board, word, i, j, duplicate_count):\n count = 0\n for k in range(1, len(word)):\n if board[i][j+k] == '-':\n continue\n elif board[i][j+k] == word[k]:\n count += 1\n else:\n return False, duplicate_count\n if count == len(word) - 1 and duplicate_count > 0:\n duplicate_count -= 1\n return False, duplicate_count\n return True, duplicate_count\n\ndef vertical_check(board, word, i, j, duplicate_count):\n count = 0\n for k in range(1, len(word)):\n if board[i+k][j] == '-':\n continue\n elif board[i+k][j] == word[k]:\n count += 1\n else:\n return False, duplicate_count\n if count == len(word) - 1 and duplicate_count > 0:\n duplicate_count -= 1\n return False, duplicate_count\n return True, duplicate_count\n\ndef horizontal_check_before(board, i, j):\n if is_not_out_of_bound(size, i, j-1):\n if board[i][j-1] != '#':\n return False\n return True\n\ndef vertical_check_before(board, i, j):\n if is_not_out_of_bound(size, i-1, j):\n if board[i-1][j] != '#':\n return False\n return True\n\ndef horizontal_check_next(board, word, i, j):\n if is_not_out_of_bound(size, i, j+len(word)):\n if board[i][j+len(word)] != '#':\n return False\n return True\n\ndef vertical_check_next(board, word, i, j):\n if is_not_out_of_bound(size, i+len(word), j):\n if board[i+len(word)][j] != '#':\n return False\n return True\n\ndef will_horizontal_word_not_out_of_bound(size, board, word, j):\n return size - j >= len(word)\n\ndef is_there_horizontal_space(size, board, word, i, j, duplicate_count):\n if horizontal_check_before(board, i, j):\n if will_horizontal_word_not_out_of_bound(size, board, word, j):\n boolean, duplicate_count = horizontal_check(board, word, i, j, duplicate_count)\n if boolean:\n if horizontal_check_next(board, word, i, j):\n return True, duplicate_count\n return False, duplicate_count\n\ndef will_vertical_word_not_out_of_bound(size, board, word, i):\n return size - i >= len(word)\n\ndef is_there_vertical_space(size, board, word, i, j, duplicate_count):\n if vertical_check_before(board, i, j):\n if will_vertical_word_not_out_of_bound(size, board, word, i):\n boolean, duplicate_count = vertical_check(board, word, i, j, duplicate_count)\n if boolean:\n if vertical_check_next(board, word, i, j):\n return True, duplicate_count\n return False, duplicate_count\n\ndef fill_horizontal(board, word, i, j):\n temp_board = copy.deepcopy(board)\n temp_board[i] = board[i][:j] + word + board[i][j+len(word):]\n # print_board(temp_board, size)\n # print(word)\n return temp_board\n\ndef fill_vertical(board, word, i, j):\n temp_board = copy.deepcopy(board)\n for k in range(len(word)):\n temp_board[i+k] = board[i+k][:j] + word[k] + board[i+k][j+1:]\n # print_board(temp_board, size)\n # print(word)\n return temp_board\n\ndef is_full(board, size):\n full = True\n i = 0\n while full and i 0)[0])\n return numberOfpoints\n \n# Finds L1 Norm of a Matrix\ndef findL1Norm(F):\n norm = np.max(F.sum(axis= 0))\n return norm\n\n# Implements Zhang's Method of Fundamental Matrix\ndef zhangsMethod(imageW, imageH, points1, points2):\n dw = int(imageW/8)\n dh = int(imageH/8)\n gridPoints1 = []\n for i in range(0,8):\n for j in range(0,8):\n points1X1 = np.where(points1[:,0] < (i+1)*dw)\n testX1 = points1[points1X1]\n points1X2 = np.where(testX1[:,0] > i*dw)\n testX2 = testX1[points1X2]\n points2X1 = np.where(testX2[:,1] < (j+1)*dh)\n testX3 = testX2[points2X1]\n points2X2 = np.where(testX3[:,1] > j*dh)\n testX4 = testX3[points2X2]\n gridPoints1.append(testX4)\n gridPoints1N = list(filter(lambda x: x.size != 0, gridPoints1))\n return gridPoints1N\n\n\n# Function to Normalize the data for the 8-point Algorithm\ndef normalizeData(points):\n meanX = np.mean(points[:,0])\n meanY = np.mean(points[:,1])\n d = np.sqrt((points[:,0] - meanX)**2 + (points[:,1] - meanY)**2)\n dMean = np.mean(d)\n scale = math.sqrt(2)/dMean\n T = np.array([[scale, 0 , -meanX*scale],[0, scale, -meanY*scale],[0, 0, 1]])\n normalizedPoints = np.matmul(T, points.T)\n return normalizedPoints.T, T #returns points as nx3 \n\n# Function implementing Normalized F Matrix Calculation Method \ndef normalizeFMethod(points1, points2):\n points1Normalize, T1 = normalizeData(points1)\n points2Normalize, T2 = normalizeData(points2)\n in1, in2, in3, in4, in5, in6, in7, in8, in9 = points2Normalize[:,0]*points1Normalize[:,0],points2Normalize[:,0]*points1Normalize[:,1],points2Normalize[:,0],points2Normalize[:,1]*points1Normalize[:,0],points2Normalize[:,1]*points1Normalize[:,1],points2Normalize[:,1],points1Normalize[:,0], points1Normalize[:,1], np.ones(len(points1Normalize[:,1]))\n a = np.vstack((in1, in2, in3, in4, in5, in6, in7, in8, in9))\n A = a.T\n u, s, V = np.linalg.svd(A)\n Fmatrix = np.reshape(V[8,:], (3, 3))\n u1,s1,v1 = np.linalg.svd(Fmatrix)\n avg = (s1[1]+s1[0])/2\n s1[0], s1[1] = avg, avg\n s1[2] = 0\n fmat = np.matmul(u1,np.matmul(np.diag(s1),v1))\n F = np.matmul(T2.T, np.matmul(fmat, T1))\n Fnormal = F/findL1Norm(F)\n Fnormal = Fnormal/Fnormal[2][2]\n if Fnormal[2,2] < 0:\n Fnormal = -1 * Fnormal\n return Fnormal\n\n# Finding FMatrix using RANSAC\ndef findRANSAC(points1, points2, imageW, imageH):\n gridPoints1N = zhangsMethod(imageW, imageH, points1, points2)\n it = 0\n numb = 0\n while(it < 250):\n\n blockNumber = []\n i = 0\n if(len(gridPoints1N) <=8):\n while(i < 8):\n b = random.randint(0,len(gridPoints1N)-1)\n blockNumber.append(b)\n i += 1\n else:\n while(i < 8):\n b = random.randint(0,len(gridPoints1N)-1)\n if not b in blockNumber:\n blockNumber.append(b)\n else:\n i = i - 1 \n i += 1\n pnts1 = []\n pnts2 = []\n for i in blockNumber:\n itr = random.randint(0, len(gridPoints1N[i])-1)\n pnts1.append(list(gridPoints1N[i][itr,:]))\n pos = 0\n for p in range(0 , points1.shape[0]):\n if(points1[p][0] == gridPoints1N[i][itr,0] and points1[p][1] == gridPoints1N[i][itr,1]):\n pos = p\n pnts2.append(list(points2[pos]))\n pnts1 = np.array(pnts1)\n pnts2 = np.array(pnts2)\n F = normalizeFMethod(pnts1, pnts2)\n checkInliner = np.matmul(points2 , np.matmul(F, points1.T))\n diagonalOfInliners = checkInliner.diagonal()\n inliers = np.where(abs(diagonalOfInliners) <= 0.05)[0]\n numberOfInliners = len(inliers)\n if(numberOfInliners > numb):\n numb = numberOfInliners\n Ffinal = F\n inliersPoints1 = points1[inliers]\n inliersPoints2 = points2[inliers]\n it += 1 \n Fn = normalizeFMethod(inliersPoints1, inliersPoints2)\n return Fn \n\n# Finding essential matrix\ndef findEssentialMatrix(F, Ml, Mr):\n E = np.matmul(Mr, np.matmul(F, Ml))\n u,s,v = np.linalg.svd(E)\n s = np.eye(3)\n s[2][2] = 0\n E = np.dot(u,np.dot(s,v))\n E = E/findL1Norm(E)\n return E\n\n# Getting Camera Poses\ndef getCameraPose(E):\n u, s, v = np.linalg.svd(E)\n W = np.array([[0, -1, 0],[1, 0, 0],[0, 0, 1]]) \n a = u[:,2]\n C1 = np.reshape(a,(3,1))\n R1 = np.matmul(u, np.matmul(W, v)) \n a = -u[:,2]\n C2 = np.reshape(a,(3,1))\n R2 = np.matmul(u, np.matmul(W, v))\n a = u[:,2]\n C3 = np.reshape(a,(3,1))\n R3 = np.matmul(u, np.matmul(W.T, v))\n a = -u[:,2]\n C4 = np.reshape(a,(3,1))\n R4 = np.matmul(u, np.matmul(W.T, v))\n if np.linalg.det(R1) < 0:\n R1 = -1 * R1\n C1 = -1 * C1\n if np.linalg.det(R2) < 0:\n R2 = -1 * R2\n C2 = -1 * C2\n if np.linalg.det(R3) < 0:\n R3 = -1 * R3\n C3 = -1 * C3\n if np.linalg.det(R4) < 0:\n R4 = -1 * R4\n C4 = -1 * C4\n C1 = np.dot(-R1.T,C1)\n C2 = np.dot(-R2.T,C2)\n C3 = np.dot(-R3.T,C3)\n C4 = np.dot(-R4.T,C4)\n return C1, R1, C2, R2, C3, R3, C4, R4\n\n# Function to disambiguate the R and Cs\ndef disambiguateChoices(C1, R1, C2, R2, C3, R3, C4, R4):\n cSet = np.hstack((C1,C2,C3,C4)) # 3X4\n rSet = np.dstack((R1,R2,R3,R4))\n ind = []\n for i in range(0,4):\n if cSet[2][i] > 0 :\n ind.append(i)\n \n ind_2 = []\n for i in ind:\n R_test = rSet[:,:,i]\n if(R_test[1][1] > 0.9 and abs(R_test[0][1]) < 0.1 and abs(R_test[1][0]) < 0.1 and abs(R_test[1][2]) < 0.1 and abs(R_test[2][1]) < 0.1):\n ind_2.append(i)\n tF = []\n RF = []\n if len(ind_2) > 0:\n t_min = 1000\n for i in ind_2:\n R = rSet[:,:,i]\n t = cSet[:,i]\n tN = np.array([[t[0]],[0],[t[2]]])\n if(abs(t[1]) < t_min):\n t_min = abs(t[2])\n tF = tN\n RF = R\n RF[0,1] = 0 \n RF[1,0] = 0\n RF[2,1] = 0\n RF[1,2] = 0\n\n if(abs(RF[0,2]) < 0.001):\n RF[0,2] = 0\n if(abs(RF[2,0]) < 0.001):\n RF[2,0] = 0\n if(RF[0,0] > 0.99):\n tF[0] = 0\n else:\n RF = np.identity(3)\n tF = np.zeros((3,1))\n\n return RF, tF \n\n\n# Reading images\nimages = glob.glob('undistorted\\Oxford_dataset\\stereo\\centre\\*.png')\n# Extract the camera parameters usingReadCameraModel.py\nfx, fy, cx, cy, G_camera_image, LUT = ReadCameraModel('Oxford_dataset/model')\n# Essential Matrix \ncalibrationMatrix = np.array([[fx,0,cx],[0,fy,cy],[0,0,1]])\n\nT_t = np.array([0,0,0])\nT_t = T_t.reshape((3,1))\nR_t = np.eye(3)\nTcv = np.array([0,0,0])\nTcv = Tcv.reshape((3,1))\nRcv = np.eye(3)\nf1 = plt.figure()\nax1 = f1.add_subplot(111)\ncount = 0\nfor i in range(30,len(images)-1):#len(images) \n img1 = cv2.imread(images[i],0)\n img2 = cv2.imread(images[i+1],0)\n h,w = img1.shape\n # Initiate ORB detector\n orb = cv2.ORB_create()\n\n # find the keypoints and descriptors with SIFT\n kp1, des1 = orb.detectAndCompute(img1,None)\n kp2, des2 = orb.detectAndCompute(img2,None)\n \n # create BFMatcher object\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n # Match descriptors.\n matches = bf.match(des1, des2)\n \n # Sort them in the order of their distance.\n matches = sorted(matches, key = lambda x:x.distance)\n list1 =[]\n list2 =[]\n for i in range(0,len(matches)):\n list1.append(kp1[matches[i].queryIdx].pt)\n list2.append(kp2[matches[i].trainIdx].pt)\n\n # List to array conversion\n list1,list2 = np.array(list1), np.array(list2) \n onesMatrix = np.ones(len(list1[:,0]))\n point1 = np.vstack((list1[:,0],list1[:,1],onesMatrix))\n point2 = np.vstack((list2[:,0],list2[:,1],onesMatrix))\n #Custom Function\n fmatrix = findRANSAC(point1.T, point2.T, w, h)\n E1 = findEssentialMatrix(fmatrix, calibrationMatrix, calibrationMatrix.T)\n C1, R1, C2, R2, C3, R3, C4, R4 = getCameraPose(E1)\n R,t = disambiguateChoices(C1, R1, C2, R2, C3, R3, C4, R4)\n T_t = T_t + np.dot(R_t , t)\n R_t = np.dot(R_t,R)\n #Opencv\n E,mask1 = cv2.findEssentialMat(list1,list2,calibrationMatrix, cv2.RANSAC,0.999,1.0)\n points1, newRcv, tcv, mask = cv2.recoverPose(E, list1,list2,calibrationMatrix,mask=mask1)\n Tcv = Tcv + np.dot(-1*Rcv,np.dot(newRcv.T,tcv))\n Rcv = np.dot(Rcv,newRcv.T)\n plt.ion()\n ax1.scatter(-T_t[0][0],T_t[2][0],s=10, c= 'b', label=\"Custom VO\")\n ax1.scatter(Tcv[0][0],Tcv[2][0],s=10,c = 'r', label=\"OpenCV VO\")\n ax1.set_title('Visual Odometry Output')\n plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=2, mode=\"expand\", borderaxespad=0.)\n plt.savefig(\"withouttriangulation/\"+str(count)+\".png\")\n print (count)\n count = count+1","sub_path":"src/visualOdometry.py","file_name":"visualOdometry.py","file_ext":"py","file_size_in_byte":11047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567610382","text":"from src.utils.mapper import configmapper\nfrom transformers import AutoTokenizer\nimport pandas as pd\nfrom datasets import load_dataset, Dataset\nfrom evaluation.fix_spans import _contiguous_ranges\n\n\n@configmapper.map(\"datasets\", \"toxic_spans_tokens_spans\")\nclass ToxicSpansTokensSpansDataset:\n def __init__(self, config):\n self.config = config\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.config.model_checkpoint_name\n )\n\n self.dataset = load_dataset(\"csv\", data_files=dict(self.config.train_files))\n self.test_dataset = load_dataset(\"csv\", data_files=dict(self.config.eval_files))\n\n temp_key_train = list(self.dataset.keys())[0]\n self.intermediate_dataset = self.dataset.map(\n self.create_train_features,\n batched=True,\n batch_size=1000000, ##Unusually Large Batch Size ## Needed For Correct ID mapping\n remove_columns=self.dataset[temp_key_train].column_names,\n )\n\n temp_key_test = list(self.test_dataset.keys())[0]\n self.intermediate_test_dataset = self.test_dataset.map(\n self.create_test_features,\n batched=True,\n batch_size=1000000, ##Unusually Large Batch Size ## Needed For Correct ID mapping\n remove_columns=self.test_dataset[temp_key_test].column_names,\n )\n\n self.tokenized_inputs = self.intermediate_dataset.map(\n self.prepare_train_features,\n batched=True,\n remove_columns=self.intermediate_dataset[temp_key_train].column_names,\n )\n self.test_tokenized_inputs = self.intermediate_test_dataset.map(\n self.prepare_test_features,\n batched=True,\n remove_columns=self.intermediate_test_dataset[temp_key_test].column_names,\n )\n\n def create_train_features(self, examples):\n features = {\"context\": [], \"id\": [], \"question\": [], \"title\": [], \"spans\": []}\n id = 0\n # print(examples)\n for row_number in range(len(examples[\"text\"])):\n context = examples[\"text\"][row_number]\n question = \"offense\"\n title = context.split(\" \")[0]\n span = eval(examples[\"spans\"][row_number])\n contiguous_spans = _contiguous_ranges(span)\n for lst in contiguous_spans:\n lst = list(lst)\n dict_to_write = {}\n\n dict_to_write[\"answer_start\"] = [lst[0]]\n dict_to_write[\"text\"] = [context[lst[0] : lst[-1] + 1]]\n # print(dict_to_write)\n if \"answers\" in features.keys():\n features[\"answers\"].append(dict_to_write)\n else:\n features[\"answers\"] = [\n dict_to_write,\n ]\n features[\"context\"].append(context)\n features[\"id\"].append(str(id))\n features[\"question\"].append(question)\n features[\"title\"].append(title)\n features[\"spans\"].append(span)\n id += 1\n\n return features\n\n def create_test_features(self, examples):\n features = {\"context\": [], \"id\": [], \"question\": [], \"title\": []}\n id = 0\n for row_number in range(len(examples[\"text\"])):\n context = examples[\"text\"][row_number]\n question = \"offense\"\n title = context.split(\" \")[0]\n features[\"context\"].append(context)\n features[\"id\"].append(str(id))\n features[\"question\"].append(question)\n features[\"title\"].append(title)\n id += 1\n return features\n\n def prepare_train_features(self, examples):\n \"\"\"Generate tokenized features from examples.\n\n Args:\n examples (dict): The examples to be tokenized.\n\n Returns:\n transformers.tokenization_utils_base.BatchEncoding:\n The tokenized features/examples after processing.\n \"\"\"\n # Tokenize our examples with truncation and padding, but keep the\n # overflows using a stride. This results in one example possible\n # giving several features when a context is long, each of those\n # features having a context that overlaps a bit the context\n # of the previous feature.\n pad_on_right = self.tokenizer.padding_side == \"right\"\n print(\"### Batch Tokenizing Examples ###\")\n tokenized_examples = self.tokenizer(\n examples[\"question\" if pad_on_right else \"context\"],\n examples[\"context\" if pad_on_right else \"question\"],\n **dict(self.config.tokenizer_params),\n )\n\n # Since one example might give us several features if it has\n # a long context, we need a map from a feature to\n # its corresponding example. This key gives us just that.\n sample_mapping = tokenized_examples.pop(\"overflow_to_sample_mapping\")\n # The offset mappings will give us a map from token to\n # character position in the original context. This will\n # help us compute the start_positions and end_positions.\n offset_mapping = tokenized_examples.pop(\"offset_mapping\")\n\n # Let's label those examples!\n token_labels = []\n tokenized_examples[\"start_positions\"] = []\n tokenized_examples[\"end_positions\"] = []\n\n for i, offsets in enumerate(offset_mapping):\n # We will label impossible answers with the index of the CLS token.\n\n token_labels.append([])\n input_ids = tokenized_examples[\"input_ids\"][i]\n spans = examples[\"spans\"][i]\n if self.config.label_cls:\n cls_label = (\n 1\n if (\n len(examples[\"context\"][i]) > 0\n and len(spans) / len(examples[\"context\"][i])\n > self.config.cls_threshold\n )\n else 0\n ) ## Make class label based on threshold\n else:\n cls_label = -100\n for j, offset in enumerate(offsets):\n if tokenized_examples[\"input_ids\"][i][j] == self.tokenizer.cls_token_id:\n token_labels[-1].append(cls_label)\n elif offset[0] == offset[1] and offset[0] == 0:\n token_labels[-1].append(-100) ## SPECIAL TOKEN\n else:\n toxic_offsets = [x in spans for x in range(offset[0], offset[1])]\n ## If any part of the the token is in span, mark it as Toxic\n if (\n len(toxic_offsets) > 0\n and sum(toxic_offsets) / len(toxic_offsets)\n > self.config.token_threshold\n ):\n token_labels[-1].append(1)\n else:\n token_labels[-1].append(0)\n\n cls_index = input_ids.index(self.tokenizer.cls_token_id)\n\n # Grab the sequence corresponding to that example\n # (to know what is the context and what is the question).\n sequence_ids = tokenized_examples.sequence_ids(i)\n\n # One example can give several spans, this is the index of\n # the example containing this span of text.\n sample_index = sample_mapping[i]\n answers = examples[\"answers\"][sample_index]\n # If no answers are given, set the cls_index as answer.\n if len(answers[\"answer_start\"]) == 0:\n tokenized_examples[\"start_positions\"].append(cls_index)\n tokenized_examples[\"end_positions\"].append(cls_index)\n else:\n # Start/end character index of the answer in the text.\n start_char = answers[\"answer_start\"][0]\n end_char = start_char + len(answers[\"text\"][0])\n\n # Start token index of the current span in the text.\n token_start_index = 0\n while sequence_ids[token_start_index] != (1 if pad_on_right else 0):\n token_start_index += 1\n\n # End token index of the current span in the text.\n token_end_index = len(input_ids) - 1\n while sequence_ids[token_end_index] != (1 if pad_on_right else 0):\n token_end_index -= 1\n\n # Detect if the answer is out of the span\n # (in which case this feature is labeled with the CLS index).\n if not (\n offsets[token_start_index][0] <= start_char\n and offsets[token_end_index][1] >= end_char\n ):\n tokenized_examples[\"start_positions\"].append(cls_index)\n tokenized_examples[\"end_positions\"].append(cls_index)\n else:\n # Otherwise move the token_start_index and\n # stoken_end_index to the two ends of the answer.\n # Note: we could go after the last offset\n # if the answer is the last word (edge case).\n while (\n token_start_index < len(offsets)\n and offsets[token_start_index][0] <= start_char\n ):\n token_start_index += 1\n tokenized_examples[\"start_positions\"].append(token_start_index - 1)\n while offsets[token_end_index][1] >= end_char:\n token_end_index -= 1\n tokenized_examples[\"end_positions\"].append(token_end_index + 1)\n tokenized_examples[\"labels\"] = token_labels\n return tokenized_examples\n\n def prepare_test_features(self, examples):\n\n \"\"\"Generate tokenized validation features from examples.\n\n Args:\n examples (dict): The validation examples to be tokenized.\n\n Returns:\n transformers.tokenization_utils_base.BatchEncoding:\n The tokenized features/examples for validation set after processing.\n \"\"\"\n\n # Tokenize our examples with truncation and maybe\n # padding, but keep the overflows using a stride.\n # This results in one example possible giving several features\n # when a context is long, each of those features having a\n # context that overlaps a bit the context of the previous feature.\n print(\"### Tokenizing Validation Examples\")\n pad_on_right = self.tokenizer.padding_side == \"right\"\n tokenized_examples = self.tokenizer(\n examples[\"question\" if pad_on_right else \"context\"],\n examples[\"context\" if pad_on_right else \"question\"],\n **dict(self.config.tokenizer_params),\n )\n\n # Since one example might give us several features if it has a long context,\n # we need a map from a feature to its corresponding example. This key gives us just that.\n sample_mapping = tokenized_examples.pop(\"overflow_to_sample_mapping\")\n\n # We keep the example_id that gave us this feature and we will store the offset mappings.\n tokenized_examples[\"example_id\"] = []\n\n for i in range(len(tokenized_examples[\"input_ids\"])):\n # Grab the sequence corresponding to that example\n # (to know what is the context and what is the question).\n sequence_ids = tokenized_examples.sequence_ids(i)\n context_index = 1 if pad_on_right else 0\n\n # One example can give several spans,\n # this is the index of the example containing this span of text.\n sample_index = sample_mapping[i]\n tokenized_examples[\"example_id\"].append(str(examples[\"id\"][sample_index]))\n\n # Set to None the offset_mapping that are not part\n # of the context so it's easy to determine if a token\n # position is part of the context or not.\n tokenized_examples[\"offset_mapping\"][i] = [\n (o if sequence_ids[k] == context_index else None)\n for k, o in enumerate(tokenized_examples[\"offset_mapping\"][i])\n ]\n\n return tokenized_examples\n","sub_path":"src/datasets/toxic_spans_tokens_spans.py","file_name":"toxic_spans_tokens_spans.py","file_ext":"py","file_size_in_byte":12178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"407467889","text":"# ADS1015.py\n# 5/24/2021\n# Aidan Gray\n# aidan.gray@idg.jhu.edu\n#\n# The ADS1015 is a precision, low-power, 12-bit, I2C compatible\n# analog-to-digital converter.\n\nfrom smbus2 import SMBus, i2c_msg\nimport time\nimport logging\n\nBUS_ID = 1\nDEV_ID = 0x48\n\nclass ADS1015Error(IOError):\n pass\n\nclass ADS1015:\n def __init__(self, eeprom):\n self.eeprom = eeprom\n\n self.ADS1015_reg_dict = {\n 'confAIN_0': [0x01, int.from_bytes(self.eeprom.ADS1015mem[0:2], byteorder='big'), 2], \n 'confAIN_3': [0x01, int.from_bytes(self.eeprom.ADS1015mem[2:4], byteorder='big'), 2]\n }\n\n self.logger = logging.getLogger('smb')\n self.i2cBus = SMBus(BUS_ID)\n self.i2cAddr = DEV_ID\n self.convAddr = 0x00\n self.confAddr = self.ADS1015_reg_dict['confAIN_0'][0]\n self.confAIN_0 = self.ADS1015_reg_dict['confAIN_0'][1] # AIN0 & AIN1 = 000\n self.confAIN_3 = self.ADS1015_reg_dict['confAIN_3'][1] # AIN2 & AIN3 = 011\n self.conversionGain = 0.02647 \n self.conversionOffset = 39.915\n\n def _write(self, regAddr, data):\n \"\"\" \n Input:\n - regAddr: int\n - data: byte Array \n \"\"\"\n\n if len(data) > 2:\n raise ADS1015Error(f\"Cannot write {len(data)} bytes. Max write size is 2 bytes.\")\n\n writeData = regAddr.to_bytes(1, byteorder = 'big') + data\n write = i2c_msg.write(self.i2cAddr, writeData)\n\n with SMBus(BUS_ID) as bus:\n bus.i2c_rdwr(write) \n\n time.sleep(0.005) \n \n def _read(self, regAddr, numBytes):\n \"\"\"\n Input:\n - regAddr: int\n - numBytes: int\n\n Output:\n - returnBytes: byte array\n \"\"\"\n\n write = i2c_msg.write(self.i2cAddr, regAddr.to_bytes(1, byteorder='big'))\n read = i2c_msg.read(self.i2cAddr, numBytes)\n \n with SMBus(BUS_ID) as bus:\n bus.i2c_rdwr(write,read)\n\n time.sleep(0.0005)\n\n returnBytes = bytearray()\n \n for value in read:\n returnBytes.append(value)\n\n return returnBytes\n \n # Perform a read of the configuration register\n def _config_read(self):\n confData = self._read(self.confAddr, 2)\n confData = int.from_bytes(confData, byteorder='big')\n return confData\n\n # Perform a write of the configuration register\n def _config_write(self, data):\n self._write(self.confAddr, data)\n\n # Perform a read of the conversion register\n def conversion_read(self):\n convData = self._read(self.convAddr, 2)\n convData = int.from_bytes(convData, byteorder='big')\n if convData == 0:\n adjData = 0\n else:\n adjData = ((convData * self.conversionGain) + self.conversionOffset) / 1000.0\n return adjData\n\n # Check if a conversion is occurring\n def conversion_status(self):\n status = self._config_read()\n statusBit = status >> 15\n return statusBit\n\n # Return the last conversion input multiplexer config (0 or 3)\n def last_convert(self):\n status = self._config_read()\n statusBit = (status >> 12) & 7\n return statusBit\n\n # Begin a conversion on the 000 multiplexer config\n def convert_0(self):\n self._config_write(self.confAIN_0.to_bytes(2, byteorder='big'))\n\n # Begin a conversion on the 011 multiplexer config\n def convert_3(self):\n self._config_write(self.confAIN_3.to_bytes(2, byteorder='big'))\n\n def update_eeprom_mem(self):\n ADSbyteArray = bytearray()\n\n for reg in self.ADS1015_reg_dict:\n register = self.ADS1015_reg_dict[reg]\n regByteArray = register[1].to_bytes(register[2], byteorder='big')\n ADSbyteArray.extend(regByteArray)\n\n self.eeprom.ADS1015mem = ADSbyteArray\n ","sub_path":"python/ADS1015.py","file_name":"ADS1015.py","file_ext":"py","file_size_in_byte":3911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"297726541","text":"#! /usr/bin/env /home/satos/sotsuron/neural_decompiler/python_fix_seed.sh\n#coding: utf-8\n\nimport c_cfg\nimport clang_ast_dump\nimport types\n\nimport code\n\nfrom clang.cindex import Config,Index,CursorKind\nConfig.set_library_path(\"/usr/lib/llvm-7/lib\")\n\n\n\n# clang python bindings is inefficient,\n# so I need to use information from clang -ast-dump \n\n\n\nimport tokenizer\nimport my_c_ast\n\ndef ast2token_seq(data):\n\tast = my_c_ast.load_astdata(data)\n\tast.before_show()\n\t#code.interact(local={'ast':ast})\n\tsrc = ast.show()\n\twith open('tmp.c','w') as fp:\n\t\tfp.write(src)\n\tres = tokenizer.tokenize('tmp.c')\n\t#print(src,res)\n\treturn res\n\nimport sys\n\ndef src2ast(fn,pfn):\n\tif fn in [\n\t\t'b50b97a5b3e07dd44019949b5fb6ed2303edf46a.tokenized.bef.c', # null case\n\t\t'4c77c60d44f4fa40e75d0ac10a9c1e76f4fa9843.tokenized.bef.c', # null exposedexpr\n\t\t'0606d3a176fa430a5f41a083cd555378dcc499b5.tokenized.bef.c', # strformat\n\t\t'fn: 598d7a9f44792c035d4eda119765daa378bc710f.tokenized.bef.c', #null label\n\t\t'598d7a9f44792c035d4eda119765daa378bc710f.tokenized.bef.c', #null label\n\t\t'7c76f2a14cc170cf7c4e99e77d5ea907a342bfd1.tokenized.bef.c', # NULL file\n\t\t'463844b04dc5a35e393ad9e862aff9e20784f667.tokenized.bef.c', #hen\n\t\t'faa4d26aa28d2681ae5d47c85009011ca5bc1047.tokenized.bef.c',\n\t\t'bd817f210aff59c4c7f32d02f74236cd5a9747f7.tokenized.bef.c', #misterious syntax like void (*signal(int sig, void (*func)(int)))(int)\n\t\t'a669457110bb0f34b581e2ecd4531215c8c0340c.tokenized.bef.c'\n\t\t'83316377e3c0aa84edbdfab83251a88ff0b0e134.tokenized.bef.c', #file structure\n\t\t'557fddcfd8b5b2ace68901180fe715867f98b0fd.tokenized.bef.c',\n\t\t'94401323ace568313410a8e199b2b87112b54ccf.tokenized.bef.c', #enum cast\n\t\t'390537b683a13d85c512ab0f5fce6ab3eaaefc37.tokenized.bef.c', # non type sizeof\n\t\t'3cad1ef0ef40208856c167cb8aeffc491bafdea5.tokenized.bef.c',\n\t\t'17d67d5ed4c95dbb7a48abc807e1d4620c94d7b2.tokenized.bef.c', #nazo\n\t\t'cd31b577d5dc633f211d80b941a7e35974260217.tokenized.c', #ioctl\n\t\t\n\t\t'c124c78dd9cf922a6b12de292eda02174e44149b.tokenized.bef.c', # TODO(satos) nannka type emmbedding bug\n\t\t'28bb854f96b9f83734ef199d0da2982d0905ff38.tokenized.bef.c',\n\t]:\n\t\traise c_cfg.Oteage\n\t\n\tc_cfg.init_idxnize()\n\ttry:\n\t\tast_hint = clang_ast_dump.fn_to_clang_ast(pfn)\n\texcept clang_ast_dump.ParseErr:\n\t\traise c_cfg.Oteage\n\twith open(fn) as fp:\n\t\tsrc = list(map(lambda x: x.strip(),fp.readlines()))\n\tindex = Index.create()\n\tast = index.parse(fn).cursor\n\t#sys.stdin.read()\n\tres = my_c_ast.AST(ast,ast_hint,src)\n\tres.get_astdata()\n\t#resrc = res.show()\n\t#resrc = 'struct __va_list_tag{ unsigned int gp_offset; unsigned int fp_offset; void *overflow_arg_area; void *reg_save_area;};' + resrc\n\treturn res\n\n\n\n\n\nfn = 'y'\nif __name__ == '__main__':\n\timport os\n\tos.system('clang -Xclang -dump-tokens -fsyntax-only ' + fn + '.c 2>&1 | sed -e \"s/[^\\']*\\'\\(.*\\)\\'[^\\']*/\\\\1/\" > ' + fn + '.tokenized.c')\n\tif os.system('gcc -S -std=c99 %s.tokenized.c' % fn) != 0:\n\t\tprint('%s.tokenized.c uncompilable' %fn)\n\t\texit()\n\t\n\tos.system('clang -Xclang -ast-dump -fsyntax-only %s.tokenized.c > %s.astdump 2>/dev/null' % (fn,fn))\n\tcsrc = open('%s.tokenized.c' % fn,'r').read().split('\\n')\n\tast = src2ast('%s.tokenized.c' % fn,'%s.astdump' % fn)\n\taststr = ast.show()\n\twith open('t.c','w') as fp:\n\t\tfp.write(aststr)\n\t#print(ast.get_astdata())\n\t#c_cfg.data_miyasui(ast.get_astdata())\n\tc_cfg.validate_astdata(ast.get_astdata(),CursorKind.TRANSLATION_UNIT)\n\tprint('validate passed')\n\tds = ast.subexpr_line_list()\n\t#print(ds)\n\t#print(ds[-1])\n\t\n\tfor (a,b),nsize,tree in ds:\n\t\t#if nsize<5:\n\t\t#\tcontinue\n\t\tprint(tree)\n\t\tprint(' '.join(csrc[a-1:b]))\n\t\tprint(a,b)\n\t\tnast = my_c_ast.load_astdata(tree)\n\t\tnast.before_show()\n\t\tprint(nast.show())\n\t\t\n\t\ttree = c_cfg.alphaconv(tree)\n\t\tprint(tree)\n\t\tnast = my_c_ast.load_astdata(tree)\n\t\tnast.before_show()\n\t\tprint(nast.show())\n\t\n\t\n","sub_path":"csrc2ast.py","file_name":"csrc2ast.py","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"514566611","text":"import random\nimport numpy as np\nfrom linearRegression import LinearRegression\nfrom statistics import statModule\nimport matplotlib.pyplot as plt\nfrom fibonacciWalk import CorFibonacci\nfrom greatestCircleOfData import *\n\nclass MultipleAreaLinearRegression():\n def __init__(self,X,Y,n = 3):\n self.neighborhoods = n\n self.linear_regression = LinearRegression()\n self.fibOBJ = CorFibonacci()\n R = radius(X,Y)\n self.X,self.Y = X,Y\n self.RadiusPoint = R[0]\n self.radiusLength = R[1]\n self.step =self.findFuncStep() \n\n self.Xfib,self.Yfib = self.fibOBJ.cordinateEachAngle(self.step,originCordinates=self.RadiusPoint)\n\n self.DistanceList = self.findNearestDistances(self.X,self.Y,self.Xfib,self.Yfib)\n self.dataPointDict = self.dataPoints(self.DistanceList)\n\n self.regs = self.regressions()\n\n self.CircleDict = self.circles(self.dataPointDict)\n\n\n #self.graph()\n\n def distance(self,X = (0,0),Y = (0,0)):\n distance = ((X[0]-Y[0])**2+(X[1]-Y[1])**2)**0.5\n return distance\n\n def circlePoints(self,origin = (0,0),radius = 1):\n YCircle = [origin[1]-np.sin(np.deg2rad(i))*radius for i in range(360)]\n XCircle = [origin[0]-np.cos(np.deg2rad(i))*radius for i in range(360)] \n\n return (XCircle,YCircle)\n\n def circles(self,FineDistances):\n\n circlesList = list()\n for origin in FineDistances:\n radius = max(FineDistances[origin], key = lambda element : element[0])\n circlesList.append((origin,radius[0]))\n \n \n return circlesList\n \n\n\n \n\n\n def findFuncStep(self):\n step = 2\n while True:\n x,y = self.fibOBJ.cordinateEachAngle(step,originCordinates=self.RadiusPoint)\n x,y = x[-1],y[-1]\n if self.radiusLength < self.distance(self.RadiusPoint,(x,y)):#Sınır Dışı olması verimisiz olması değildir.Önemli Olan bağlandığı noktadır.\n break\n else:\n step += 1\n return step\n \n def findNearestDistances(self,Xdata,Ydata,Xfunc,Yfunc):\n Xdata,Ydata ,Xfunc,Yfunc = np.ravel(Xdata),np.ravel(Ydata),np.ravel(Xfunc),np.ravel(Yfunc)#Daha iyi veri görütüsü için.\n distanceN = list()\n for xd,yd in zip(Xdata,Ydata):\n dist = [(self.distance(X = (xd,yd),Y = (x,y)),(x,y),(xd,yd)) for x,y in zip(Xfunc,Yfunc)]\n dist = sorted(dist,key = lambda tup: tup[0])#İlk indekse göre sıralar.\n dataPoint = dist[0]#En yakın veri \n distanceN.append(dataPoint)\n\n return distanceN\n \n\n def dataPoints(self,FineDistances):\n \n dataPointDict = dict()\n for distance,A,D in FineDistances:\n try:\n dataPointDict[A].append((distance,D))\n\n except KeyError:\n dataPointDict[A] = list()\n dataPointDict[A].append((distance,D))\n\n return dataPointDict\n \n def prediction(self,x_test):#Prediction problemini çöz\n\n predictionNears = list()\n for x_pred in x_test:#tahmin edilecek veride \n distances = list()\n for real in self.regs:#eğitim verisinde sınıflandırılmış sözlük anahtarları\n for x in real[\"trainPointsX\"]:#eğitim kümesinin x kısmı\n dist = abs(x - x_pred)\n distances.append((dist,x))\n distances = sorted(distances,key = lambda tup:tup[0])[:self.neighborhoods]\n\n predictionNears.append((x_pred,distances))#test veri ile en yakın N noktanın X \n \n #Test kümesinde en yakın n adet değer bulunur.\n\n\n predictions = list()\n for regression in self.regs:\n y_pred = eval(\"self.linReg{}.predict(x_test)\".format(regression[\"prediction\"]))\n rmseMetric = eval(\"self.LinReg{}.rmse_metric(y_test,y_pred)\".format(regression[\"prediction\"]))\n predictions.append((regression[\"origin\"],rmseMetric))\n \n\n def regressions(self):\n index = 1\n predictionlist =list()\n for key in self.dataPointDict:\n predictionDict = {\"origin\": key ,\"prediction\" : None,\"trainPointsX\":list(),\"trainPointsY\":list()}\n Xparted = [element[1][0] for element in self.dataPointDict[key]]\n Yparted = [element[1][1] for element in self.dataPointDict[key]]\n exec(\"self.linReg{} = LinearRegression()\".format(index))\n exec(\"self.linReg{}.fit(Xparted,Yparted)\".format(index))\n predictionDict['prediction'] = index\n predictionDict['x_points'] = Xparted\n predictionDict['y_points'] = Yparted\n\n predictionlist.append(predictionDict)\n \n index += 1\n\n\n return predictionlist\n\n\n def graph(self): \n plt.grid()\n plt.scatter(X,Y)\n for tup in self.CircleDict:\n circleX,circleY = self.circlePoints(origin = tup[0],radius = tup[1])\n plt.plot(circleX,circleY,color = \"black\")\n\n plt.plot(self.Xfib,self.Yfib,color = \"Purple\",label=\"Fibonacci Walk\")\n plt.legend()\n plt.show() \n\nX = list()\nY = list()\n\nfor d in range(200):\n area = random.randint(1,5)\n X.append(random.randint((area-1)*1000,area*1000))\nfor d in range(200):\n area = random.randint(1,5)\n Y.append(random.randint((area-1)*1000,area*1000))\n\n\n#X = [random.randint(1,1000) for i in range(100)]\n#Y = [random.randint(1,1000) for i in range(100)]\n\n\nobj = MultipleAreaLinearRegression(X,Y)\n\n\n\n\n","sub_path":"FibonacciProject/someFibonacci_last/MultipleAreaLinearRegression.py","file_name":"MultipleAreaLinearRegression.py","file_ext":"py","file_size_in_byte":5591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"304249229","text":"\nfrom Model import Model\n\nclass ModelItems(Model):\n def __init__(self):\n self.table_name = 'items'\n self.test_key = {'char_name': 'test_char_01', 'item_id': 'test_item_01'}\n Model.__init__(self)\n\n def create_table(self):\n new_table = self.dynamodb.create_table(\n TableName=self.table_name,\n KeySchema=[\n {\n 'AttributeName': 'char_name',\n 'KeyType': 'HASH'\n },\n {\n 'AttributeName': 'item_id',\n 'KeyType': 'RANGE'\n }\n ],\n AttributeDefinitions=[\n {\n 'AttributeName': 'char_name',\n 'AttributeType': 'S'\n },\n {\n 'AttributeName': 'item_id',\n 'AttributeType': 'S'\n }\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n )\n\n new_table.meta.client.get_waiter('table_exists')\n print('new table status: ' + new_table.table_status)\n\n def test(self):\n self.put(self.test_key)\n self.get(self.test_key)\n self.delete(self.test_key)\n\n","sub_path":"src/ModelItems.py","file_name":"ModelItems.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"237996295","text":"from collections import deque\n\n# bfs 2번 돌리는걸로 했는�� 안된다.\n# 결국 힌트 얻어서 품. -> 벽 뚫는걸 기억하는 배열로 만들어줘야대네.\n\ndef bfs() :\n\n visited = [[[0] * 2 for _ in range(M)] for _ in range(N)]\n q = deque()\n q.append((0,0,1))\n visited[0][0][1] = 1\n\n while q : \n cx,cy,t = q.popleft()\n if cx == N-1 and cy == M-1 :\n return visited[cx][cy][t]\n for dx,dy in zip(dxs,dys) :\n nx = cx + dx\n ny = cy + dy\n if 0 <= nx < N and 0 <= ny < M :\n if maps[nx][ny] == 0 and visited[nx][ny][t] == 0 :\n q.append((nx,ny,t))\n visited[nx][ny][t] = visited[cx][cy][t] + 1\n elif maps[nx][ny] == 1 and t == 1 :\n q.append((nx,ny,0))\n visited[nx][ny][0] = visited[cx][cy][t] + 1\n\n return -1\n\nmaps = []\nN,M = map(int,input().split()) \nfor _ in range(N) :\n # maps.append(list(map(int,list(input().strip()))))\n maps.append(list(map(int, list(input().strip()))))\n\ndxs = [-1,1,0,0]\ndys = [0,0,-1,1]\n\nprint(bfs())","sub_path":"BOJ/24_DFS와BFS/2206_벽부수고이동하기.py","file_name":"2206_벽부수고이동하기.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401346864","text":"from .file_register import FileRegister\nimport json\nimport os\n\n\nclass LocallyRegister(FileRegister):\n\n def __init__(self):\n super().__init__()\n\n def _FileRegister__register(self, day, month, year, data: bytes, base_name='file', page=1):\n\n dir_path = os.path.join(year, month, day)\n if os.path.exists(dir_path) == False:\n try:\n os.makedirs(dir_path)\n except OSError:\n print(\"path already exists\")\n\n with open(self.format_url(year, month, day, base_name, page), \"w\") as write_file:\n json.dump(json.loads(data), write_file)\n","sub_path":"repository/locally_register.py","file_name":"locally_register.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"32515437","text":"# python3\nimport os\nimport warnings\nfrom Bio import BiopythonWarning\nimport argparse\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio import SeqFeature\n# imput parameters\nap = argparse.ArgumentParser(description=\"ligate vectors in genbank format with annotations, with inserts in a multi-fasta file\")\nap.add_argument(\"-fasta\", \"--multi_fasta\", required=True, help=\"multi-fasta file to inport\")\nap.add_argument(\"-dir\", \"--directory\", required=False,default='.', help=\"directory to export the output genbank files. Default is the current directory\")\nargs = vars(ap.parse_args())\n# main\n# remove warnings\nwarnings.simplefilter('ignore',BiopythonWarning)\n# add final list\nfinal_gbs = []\n# linear vectors\n# import each genbank file from the working directory\nfor filename in sorted(os.listdir(str(os.getcwd()))):\n if filename.endswith(\".gb\") or filename.endswith(\".gbk\"): \n plasmid = SeqIO.read(filename, \"genbank\")\n x = str(plasmid.seq)\n gb_file = filename.split(\".\")[0]\n # DNA insert\n # import each fasta file from the working directory\n for record in SeqIO.parse(args['multi_fasta'],\"fasta\"):\n y = str(record.seq)\n # merge\n seqad = x + y\n # add this record to the list\n ligated = SeqRecord(Seq(seqad),id='_'.join([record.id,gb_file]),description=\"\",annotations={\"molecule_type\":\"DNA\",\"topology\":\"circular\"})\n ligated.features = plasmid.features\n final_gbs.append(ligated)\n# select output directory\nos.chdir(args['directory'])\n# export to genbank\nfor final_gb in final_gbs:\n SeqIO.write(final_gb,\"\".join([final_gb.id,\".gb\"]), \"genbank\")\n","sub_path":"src/synbio/ligate_multifasta_with_vectors.py","file_name":"ligate_multifasta_with_vectors.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"117594876","text":"import types\n\n# The Strategy Pattern class\nclass Strategy:\n\tdef __init__(self, function=None):\n\t\tself.name = \"Default Strategy\"\n\n\t\t# If a reference to a function is provided, replace the execute() method with the given function\n\t\tif function:\n\t\t\tself.execute = types.MethodType(function, self)\n\n\t# This gets replaced by abother version if another strategy is provided\n\t# The default method that prints the name of the strategy being used\n\tdef execute(self):\n\t\tprint(\"{} is used!\".format(self.name))\n\n# Replacement method 1\ndef strategy_one(self):\n\tprint(\"{} is used to execute method 1\".format(self.name))\n\n# Replacement method 2\ndef strategy_two(self):\n\tprint(\"{} is used to execute method 2\".format(self.name))\n\n\n# Create our default strategy\ns0 = Strategy()\n\n# Execute our default strategy\ns0.execute()\n\n# Create the first variation of our default strategy by providing a new behavior\ns1 = Strategy(strategy_one)\n\n# Set its name\ns1.name = \"Strategy One\"\n\n# Execute the strategy\ns1.execute()\n\ns2 = Strategy(strategy_two)\ns2.name = \"Strategy Two\"\ns2.execute()","sub_path":"design_patterns/strategy_test.py","file_name":"strategy_test.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"596904576","text":"import NaiveBayes\n\nclass Verifier:\n\tdef __init__(self, models, runtimes):\n\t\tself.models = models\n\t\tself.runtimes = runtimes\n\n\t\tself.compute_all_confusion_matrices()\n\n\t\tself.precision_by_model = self.compute_precision_by_model()\n\t\tself.recall_by_model = self.compute_recall_by_model()\n\t\tself.F1_by_model = self.compute_F1_by_model()\n\t\tself.accuracy_by_model = self.compute_accuracy_by_model()\n\n\tdef construct_and_write_results(self):\n\t\tscreen_o = \"\"\n\n\t\tscreen_o += \"\\n----------------------------\\nAggregate evaluation results\\n----------------------------\\n\"\n\t\tscreen_o += (\"Average Micro Precision: \" + str(round(self.compute_avg_micro_precision(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Micro Recall: \" + str(round(self.compute_avg_micro_recall(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Micro F1: \" + str(round(self.compute_avg_micro_precision(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Macro Precision: \" + str(round(self.compute_macro_precision(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Macro Recall: \" + str(round(self.compute_macro_recall(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Macro F1: \" + str(round(self.compute_macro_F1(), 2)) + '\\n')\n\t\tscreen_o += (\"Average Accuracy: \" + str(round(self.compute_avg_accuracy(), 2)) + '\\n')\n\n\t\tfile_o = \"\"\n\t\tfile_o += \"\\n-------------------\\nRuntime information\\n-------------------\\n\"\n\t\tfor i in range(len(self.models)):\n\t\t\tfile_o += (\"Fold \" + str(i + 1) + \": \" + str(round(self.runtimes[i], 2)) + \" seconds\\n\")\n\n\t\tfor i in range(len(self.models)):\n\t\t\tfile_o += (\"\\n-------------------------------\\n\" + \"Evaluation results for Model \" + str(i + 1) \\\n\t\t \t\t+ \"\\n-------------------------------\\n\")\n\t\t\tfile_o += (\"Micro/Micro precision: \" + str(round(self.precision_by_model[i], 2)) + '\\n')\n\t\t\tfile_o += (\"Micro/Micro recall: \" + str(round(self.recall_by_model[i], 2)) + '\\n')\n\t\t\tfile_o += (\"Micro/Micro F1: \" + str(round(self.F1_by_model[i], 2)) + '\\n')\n\t\t\tfile_o += (\"Micro/Micro accuracy: \" + str(round(self.accuracy_by_model[i], 2)) + '\\n')\n\n\t\tfile_o += screen_o\n\n\t\tprint(screen_o)\n\n\t\toutput_file = open('adult.out', 'w')\n\t\toutput_file.write(file_o)\n\t\toutput_file.close()\n\n\t\tprint(\"Runtime information and results written to 'adult.out'\")\n\n\tdef calculate_confusion_matrix(self, model):\n\t\tfor i in range(len(model.testing_data)):\n\t\t\tif model.classified[i] == '>50K' and model.testing_data[i].get_class_label() == '>50K':\n\t\t\t\tmodel.confusion_matrix['TP'] += 1\n\n\t\t\tif model.classified[i] == '>50K' and model.testing_data[i].get_class_label() == '<=50K': \n\t\t\t\tmodel.confusion_matrix['FP'] += 1\n\n\t\t\tif model.classified[i] == '<=50K' and model.testing_data[i].get_class_label() == '>50K':\n\t\t\t\tmodel.confusion_matrix['FN'] += 1\n\n\t\t\tif model.classified[i] == '<=50K' and model.testing_data[i].get_class_label() == '<=50K':\n\t\t\t\tmodel.confusion_matrix['TN'] += 1\n\n\n\tdef compute_all_confusion_matrices(self):\n\t\tfor i in range(len(self.models)):\n\t\t\tself.calculate_confusion_matrix(self.models[i])\n\n\t# for an individual model, macro precision and micro precision are identical\n\tdef calculate_precision(self, model):\n\t\treturn model.confusion_matrix['TP'] / (model.confusion_matrix['TP'] + model.confusion_matrix['FP'])\n\n\tdef compute_precision_by_model(self):\n\t\tprecision_list = []\n\n\t\tfor i in range(len(self.models)):\n\t\t\tprecision_list.append(self.calculate_precision(self.models[i]))\n\n\t\treturn precision_list\n\n\t# for an individual model, macro recall and micro recall are identical\n\tdef calculate_recall(self, model):\n\t\treturn model.confusion_matrix['TP'] / (model.confusion_matrix['TP'] + model.confusion_matrix['FN'])\n\n\tdef compute_recall_by_model(self):\n\t\trecall_list = []\n\n\t\tfor i in range(len(self.models)):\n\t\t\trecall_list.append(self.calculate_recall(self.models[i]))\n\n\t\treturn recall_list\n\n\t# for an individual model, macro F1 and micro F1 are identical\n\tdef calculate_F1(self, model):\n\t\treturn (2 * self.calculate_recall(model) * self.calculate_precision(model)) / \\\n\t\t\t(self.calculate_recall(model) + self.calculate_precision(model))\n\n\tdef compute_F1_by_model(self):\n\t\tF1_list = []\n\n\t\tfor i in range(len(self.models)):\n\t\t\tF1_list.append(self.calculate_F1(self.models[i]))\n\n\t\treturn F1_list\n\n\tdef calculate_accuracy(self, model):\n\t\treturn (model.confusion_matrix['TP'] + model.confusion_matrix['TN']) / (model.confusion_matrix['TP'] + \\\n\t\t\tmodel.confusion_matrix['TN'] + model.confusion_matrix['FP'] + model.confusion_matrix['FN'])\n\n\tdef compute_accuracy_by_model(self):\n\t\taccuracy_list = []\n\n\t\tfor i in range(len(self.models)):\n\t\t\taccuracy_list.append(self.calculate_accuracy(self.models[i]))\n\n\t\treturn accuracy_list\t\t\n\n\tdef compute_avg_micro_precision(self):\n\t\tnumerator = 0\n\t\tdenominator = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\tnumerator += self.models[i].confusion_matrix['TP']\n\t\t\tdenominator += (self.models[i].confusion_matrix['TP'] + self.models[i].confusion_matrix['FP'])\n\n\t\treturn numerator / denominator\n\n\n\tdef compute_avg_micro_recall(self):\n\t\tnumerator = 0\n\t\tdenominator = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\tnumerator += self.models[i].confusion_matrix['TP']\n\t\t\tdenominator += (self.models[i].confusion_matrix['TP'] + self.models[i].confusion_matrix['FN'])\n\n\t\treturn numerator / denominator\n\n\tdef compute_avg_micro_F1(self):\n\t\tnumerator = 0\n\t\tdenominator = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\tnumerator += (2 * self.calculate_recall(model) * self.calculate_precision(model))\n\t\t\tdenominator += (self.calculate_recall(model) + self.calculate_precision(model))\n\n\t\treturn numerator / denominator\n\n\tdef compute_macro_precision(self):\n\t\ttotal_precision = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\ttotal_precision += self.precision_by_model[i]\n\n\t\treturn total_precision / (i + 1)\n\n\tdef compute_macro_recall(self):\n\t\ttotal_recall = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\ttotal_recall += self.recall_by_model[i]\n\n\t\treturn total_recall / (i + 1)\n\n\tdef compute_macro_F1(self):\n\t\ttotal_F1 = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\ttotal_F1 += self.F1_by_model[i]\n\n\t\treturn total_F1 / (i + 1)\n\n\tdef compute_avg_accuracy(self):\n\t\tnumerator = 0\n\t\tdenominator = 0\n\n\t\tfor i in range(len(self.models)):\n\t\t\tnumerator += (self.models[i].confusion_matrix['TP'] + self.models[i].confusion_matrix['TN'])\n\t\t\tdenominator += (self.models[i].confusion_matrix['TP'] + self.models[i].confusion_matrix['TN'] + \\\n\t\t\t\tself.models[i].confusion_matrix['FP'] + self.models[i].confusion_matrix['FN'])\n\n\t\treturn numerator / denominator\n\n","sub_path":"Data Mining/NaiveBayes/Verifier.py","file_name":"Verifier.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"570579472","text":"from __future__ import (absolute_import, unicode_literals, division,\n print_function)\n\nimport logging\n\nfrom asdf import AsdfFile\nfrom astropy import coordinates as coord\nfrom astropy import units as u\nfrom astropy.modeling.models import Const1D, Mapping, Scale\nfrom gwcs import wcs\nimport gwcs.coordinate_frames as cf\nfrom .util import not_implemented_mode\nfrom . import pointing\nfrom ..transforms.models import NirissSOSSModel\n\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\n\ndef create_pipeline(input_model, reference_files):\n '''\n get reference files from crds\n\n '''\n\n exp_type = input_model.meta.exposure.type.lower()\n pipeline = exp_type2transform[exp_type](input_model, reference_files)\n\n return pipeline\n\n\ndef niriss_soss_set_input(model, order_number):\n \"\"\"\n Get the right model given the order number.\n\n Parameters\n ----------\n model - Input model\n order_number - the, well, order number desired\n\n Returns\n -------\n WCS - the WCS corresponding to the order_number\n\n \"\"\"\n\n # Make sure the order number is correct.\n if order_number < 1 or order_number > 3:\n raise ValueError('Order must be between 1 and 3')\n\n # Return the correct transform based on the order_number\n obj = model.meta.wcs.forward_transform.get_model(order_number)\n\n # use the size of the input subarray7\n detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))\n spec = cf.SpectralFrame(name='spectral', axes_order=(2,), unit=(u.micron,),\n axes_names=('wavelength',))\n sky = cf.CelestialFrame(reference_frame=coord.ICRS(),\n axes_names=('ra', 'dec'),\n axes_order=(0, 1), unit=(u.deg, u.deg), name='sky')\n world = cf.CompositeFrame([sky, spec], name='world')\n pipeline = [(detector, obj),\n (world, None)\n ]\n\n return wcs.WCS(pipeline)\n\n\ndef niriss_soss(input_model, reference_files):\n \"\"\"\n The NIRISS SOSS pipeline includes 3 coordinate frames -\n detector, focal plane and sky\n\n reference_files={'specwcs': 'soss_wavelengths_configuration.asdf'}\n \"\"\"\n\n # Get the target RA and DEC, they will be used for setting the WCS RA and DEC based on a conversation\n # with Kevin Volk.\n try:\n target_ra = float(input_model['meta.target.ra'])\n target_dec = float(input_model['meta.target.dec'])\n except:\n # There was an error getting the target RA and DEC, so we are not going to continue.\n raise ValueError('Problem getting the TARG_RA or TARG_DEC from input model {}'.format(input_model))\n\n # Define the frames\n detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))\n spec = cf.SpectralFrame(name='spectral', axes_order=(2,), unit=(u.micron,),\n axes_names=('wavelength',))\n sky = cf.CelestialFrame(reference_frame=coord.ICRS(),\n axes_names=('ra', 'dec'),\n axes_order=(0, 1), unit=(u.deg, u.deg), name='sky')\n world = cf.CompositeFrame([sky, spec], name='world')\n try:\n with AsdfFile.open(reference_files['specwcs']) as wl:\n wl1 = wl.tree[1].copy()\n wl2 = wl.tree[2].copy()\n wl3 = wl.tree[3].copy()\n except Exception as e:\n raise IOError('Error reading wavelength correction from {}'.format(reference_files['specwcs']))\n\n cm_order1 = (Mapping((0, 1, 0, 1)) | (Const1D(target_ra) & Const1D(target_dec) & wl1)).rename('Order1')\n cm_order2 = (Mapping((0, 1, 0, 1)) | (Const1D(target_ra) & Const1D(target_dec) & wl2)).rename('Order2')\n cm_order3 = (Mapping((0, 1, 0, 1)) | (Const1D(target_ra) & Const1D(target_dec) & wl3)).rename('Order3')\n\n # Define the transforms, they should accept (x,y) and return (ra, dec, lambda)\n soss_model = NirissSOSSModel([1, 2, 3], [cm_order1, cm_order2, cm_order3]).rename('3-order SOSS Model')\n\n # Define the pipeline based on the frames and models above.\n pipeline = [(detector, soss_model),\n (world, None)\n ]\n\n return pipeline\n\n\ndef imaging(input_model, reference_files):\n \"\"\"\n The NIRISS imaging pipeline includes 3 coordinate frames -\n detector, focal plane and sky\n\n reference_files={'distortion': 'jwst_niriss_distortioon_0001.asdf'}\n \"\"\"\n detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))\n v2v3 = cf.Frame2D(name='v2v3', axes_order=(0, 1), unit=(u.deg, u.deg))\n world = cf.CelestialFrame(reference_frame=coord.ICRS(), name='world')\n distortion = imaging_distortion(input_model, reference_files)\n tel2sky = pointing.v23tosky(input_model)\n pipeline = [(detector, distortion),\n (v2v3, tel2sky),\n (world, None)]\n return pipeline\n\n\ndef imaging_distortion(input_model, reference_files):\n distortion = AsdfFile.open(reference_files['distortion']).tree['model']\n # Convert to arcsec\n transform = distortion | Scale(1/60) & Scale(1/60)\n return transform\n\n\nexp_type2transform = {'nis_image': imaging,\n 'nis_wfss': not_implemented_mode,\n 'nis_soss': niriss_soss,\n 'nis_ami': not_implemented_mode,\n 'nis_tacq': imaging,\n 'nis_taconfirm': imaging,\n 'nis_focus': imaging,\n 'nis_dark': not_implemented_mode,\n 'nis_lamp': not_implemented_mode,\n }\n","sub_path":"jwst/assign_wcs/niriss.py","file_name":"niriss.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"382473429","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport math\n\ndef conv3x3(in_planes, out_planes, stride=1):\n\t\"\"\"3x3 convolution with padding\"\"\"\n\treturn nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n\t\t\t\t\t padding=1, bias=False)\n\nclass BasicBlock(nn.Module):\n\texpansion = 1\n\n\tdef __init__(self, inplanes, planes, stride=1, downsample=None):\n\t\tsuper(BasicBlock, self).__init__()\n\t\tself.conv1 = conv3x3(inplanes, planes, stride)\n\t\tself.bn1 = nn.BatchNorm2d(planes)\n\t\tself.relu = nn.ReLU(inplace=True)\n\t\tself.conv2 = conv3x3(planes, planes)\n\t\tself.bn2 = nn.BatchNorm2d(planes)\n\t\tself.downsample = downsample\n\t\tself.stride = stride\n\n\tdef forward(self, x):\n\t\tresidual = x\n\n\t\tout = self.conv1(x)\n\t\tout = self.bn1(out)\n\t\tout = self.relu(out)\n\n\t\tout = self.conv2(out)\n\t\tout = self.bn2(out)\n\n\t\tif self.downsample is not None:\n\t\t\tresidual = self.downsample(x)\n\n\t\tout += residual\n\t\tout = self.relu(out)\n\n\t\treturn out\n\nclass ResNet20(nn.Module):\n\n\tdef __init__(self, block, layers):\n\t\tself.inplanes = 64\n\t\tsuper(ResNet20, self).__init__()\n\n\t\tself.convNew1 = nn.Conv2d(15, 8, kernel_size = 2, stride = 2, padding = 1)\n\t\tself.relu1= nn.ReLU(inplace=True)\n\t\tself.convNew2 = nn.Conv2d(8, 3, kernel_size = 3, stride = 1, padding = 1)\n\n\t\tself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=2, bias=False)\n\t\tself.bn1 = nn.BatchNorm2d(64)\n\t\tself.relu2 = nn.ReLU(inplace=True)\n\t\tself.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n\t\tself.layer1 = self._make_layer(block, 64, layers[0])\n\t\tself.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n\t\tself.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n\t\tself.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n\t\tself.avgpool = nn.AvgPool2d(2, stride=2)\n\t\tself.avgpool1 = nn.AvgPool2d(2, stride=2)\n\t\tself.fcNew = nn.Linear(2048 * block.expansion, 2500)\n\n\t\tfor m in self.modules():\n\t\t\tif isinstance(m, nn.Conv2d):\n\t\t\t\tn = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n\t\t\t\tm.weight.data.normal_(0, math.sqrt(2. / n))\n\t\t\telif isinstance(m, nn.BatchNorm2d):\n\t\t\t\tm.weight.data.fill_(1)\n\t\t\t\tm.bias.data.zero_()\n\n\tdef _make_layer(self, block, planes, blocks, stride=1):\n\t\tdownsample = None\n\t\tif stride != 1 or self.inplanes != planes * block.expansion:\n\t\t\tdownsample = nn.Sequential(\n\t\t\t\tnn.Conv2d(self.inplanes, planes * block.expansion,\n\t\t\t\t\t\t kernel_size=1, stride=stride, bias=False),\n\t\t\t\tnn.BatchNorm2d(planes * block.expansion),\n\t\t\t)\n\n\t\tlayers = []\n\t\tlayers.append(block(self.inplanes, planes, stride, downsample))\n\t\tself.inplanes = planes * block.expansion\n\t\tfor i in range(1, blocks):\n\t\t\tlayers.append(block(self.inplanes, planes))\n\n\t\treturn nn.Sequential(*layers)\n\n\tdef forward(self, x):\n\n\t\tx = self.convNew1(x)\n\t\tx = self.relu1(x)\n\t\tx = self.convNew2(x)\n\n\t\tx = self.conv1(x)\n\t\tx = self.bn1(x)\n\t\tx = self.relu2(x)\n\t\tx = self.maxpool(x)\n\t\tx = self.layer1(x)\n\t\tx = self.layer2(x)\n\t\tx = self.layer3(x)\n\t\tx = self.layer4(x)\n\t\tx = self.avgpool(x)\n\t\tx = self.avgpool1(x)\n\t\tx = x.view(x.size(0), -1)\n\t\tx = self.fcNew(x)\n\n\t\treturn x\n\ndef resnet20(pretrain = False):\n\n\tmodel20 = ResNet20(BasicBlock, [2, 2, 2, 2])\n\n\tif pretrain:\n\n\t\t# Load the pretrained for resnet 18 layers\n\t\tmodel18params = torch.load('resnet18.pkl')\n\t\tmodel20_dict = model20.state_dict()\n\n\t\t# Replace the random init weights with pretrained\n\t\tfor name, par in model18params.items():\n\t\t\tif name not in model20_dict:\n\t\t\t\t# Jump to next loop\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tmodel20_dict[name].copy_(par)\n\n\t\tmodel20.load_state_dict(model20_dict)\n\n\treturn model20","sub_path":"modeling/modelResnet.py","file_name":"modelResnet.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"383081093","text":"import requests\nimport json\nimport wikipedia\nimport random\n\n\nclass Astronauts(object):\n url = 'http://api.open-notify.org/astros.json'\n\n def __init__(self):\n self.astros = []\n\n def _get(self, url):\n \"\"\"Get json from the request.\"\"\"\n response = requests.get(url=url)\n return response.json()\n\n def get_astros(self, url=url):\n \"\"\"Return a list of active astronauts.\"\"\"\n if self.astros == []:\n # get astros json object\n astro_dict = self._get(url=url)\n\n # process the astros\n for astro in astro_dict['people']:\n #if name ends in 'kiy', replace with 'ky'; replace spaces with underscore\n name = astro['name'].replace('kiy', 'ky').replace(' ', '_').lower()\n self.astros.append(name)\n\n return self.astros\n\n def get_index_data(self):\n \"\"\"Get the data needed for the homepage\"\"\"\n astro_data = []\n # get the list of astronauts\n astros = self.get_astros()\n # get a dict for each astronaut in the list\n for astro in astros:\n astro_dict = self.astro_wiki(astro)\n astro_data.append(astro_dict)\n print(astro_data)\n return astro_data\n\n def get_astro_image(self, images):\n \"\"\"Return one image from a list of images.\"\"\"\n images = [img for img in images if img.endswith('.jpg')]\n return random.choice(images)\n\n def astro_wiki(self, astro):\n \"\"\"Get data on an astronaut from wikipedia.\"\"\"\n astro_dict = {}\n\n try:\n # If astronaut is in the list of active astronauts, write the dict.\n if astro in self.astros:\n astro_wiki = wikipedia.page(astro)\n astro_dict['url_name'] = astro\n astro_dict['name'] = astro.replace('_', ' ').title()\n astro_dict['summary'] = wikipedia.summary(astro)\n astro_dict['url'] = astro_wiki.url\n astro_dict['image'] = self.get_astro_image(astro_wiki.images)\n else:\n raise ValueError\n except ValueError:\n print(f\"{astro} is not in space.\")\n except wikipedia.exceptions.PageError:\n print(\"Page not found.\")\n except wikipedia.exceptions.DisambiguationError:\n print(\"Too many entries.\")\n finally:\n return astro_dict\n","sub_path":"spacenauts/astronauts/astros.py","file_name":"astros.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"368764484","text":"\"\"\"\nName: James Callum Peters\n\nUser Name: jpet954\n\nID Number: 314180902\n\nDescription: A simple math quiz. Select the type of question\nyou would like to be asked, enter your answer, and the program\nreturns the correct answers as a percentage of the total questions answered.\n\"\"\"\n\nimport math\nimport random\n\ndef display_intro():\n message = \"** A Simple Math Quiz **\"\n border_1 = \"*\" * len(message)\n print(border_1)\n print(message)\n print(border_1)\n\ndef display_menu():\n menu_line_1 = \"1. Addition\"\n menu_line_2 = \"2. Subtraction\"\n menu_line_3 = \"3. Multiplication\"\n menu_line_4 = \"4. Interger Division\"\n menu_line_5 = \"5. Exit\"\n print(menu_line_1)\n print(menu_line_2)\n print(menu_line_3)\n print(menu_line_4)\n print(menu_line_5)\n\ndef display_separator():\n separator = \"-\" * 24\n print(separator)\n\ndef get_user_input():\n user_selection = int(input(\"Enter your Choice: \"))\n while user_selection >= 6:\n print(\"Error. Please enter valid selection.\")\n user_selection = int(input(\"Enter your Choice: \"))\n return user_selection\n\ndef get_user_solution(problem):\n user_answer = int(input())\n return user_answer\n\ndef check_solution(user_solution, solution, count):\n user_solution = int(input())\n if user_solution == solution:\n print(\"You are correct.\")\n return True\n else:\n print(\"You are incorrect.\")\n return False\n\ndef menu_option(index, count):\n #Init\n rand_num_1 = random.randrange(1, 21)\n rand_num_2 = random.randrange(1, 21)\n equation_question = \"\"\n equation_solution = 0\n user_solution = 0\n #Tests the correct answer against user solution.\n #Adds 1 to total correct if both are equal.\n if index == 1:\n equation_solution = rand_num_1 + rand_num_2\n equation_question = str(rand_num_1) + \" + \" + str(rand_num_2) + \" = \"\n print(equation_question, end = \"\")\n if check_solution(user_solution, equation_solution, count) == True:\n count += 1\n return count\n\n elif index == 2:\n equation_solution = rand_num_1 - rand_num_2\n equation_question = str(rand_num_1) + \" - \" + str(rand_num_2) + \" = \"\n print(equation_question, end = \"\")\n if check_solution(user_solution, equation_solution, count) == True:\n count += 1\n return count\n \n elif index == 3:\n equation_solution = rand_num_1 * rand_num_2\n equation_question = str(rand_num_1) + \" * \" + str(rand_num_2) + \" = \"\n print(equation_question, end = \"\")\n if check_solution(user_solution, equation_solution, count) == True:\n count += 1\n return count\n \n elif index == 4:\n equation_solution = rand_num_1 // rand_num_2\n equation_question = str(rand_num_1) + \" / \" + str(rand_num_2) + \" = \"\n print(equation_question, end = \"\")\n if check_solution(user_solution, equation_solution, count) == True:\n count += 1\n return count\n \n elif index == 5:\n display_result(total, count)\n\n \ndef display_result(total, correct):\n if total == 0:\n print(\"You answered 0 questions. Thank you.\")\n else:\n percentage = correct / total * 100\n print(\"You answered \" + str(total) + \" questions with \" + str(correct) + \" correct.\")\n print(\"Your score is \" + str(round(percentage, 2)) + \"%. Thank you.\")\n \ndef main():\n display_intro()\n display_menu()\n display_separator()\n \n option = get_user_input()\n total = 0\n correct = 0\n while option != 5:\n total = total + 1\n correct = menu_option(option, correct)\n option = get_user_input()\n \n print(\"Exit the quiz.\")\n display_separator()\n display_result(total, correct)\n\nmain()\n","sub_path":"assignment_2.py","file_name":"assignment_2.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"324129046","text":"from flask import Blueprint, jsonify, request, redirect, url_for\nfrom critiquebrainz.db import db, User\nfrom critiquebrainz.exceptions import *\nfrom critiquebrainz.oauth import oauth\nfrom critiquebrainz.parser import Parser\n\nuser_bp = Blueprint('user', __name__)\n\n@user_bp.route('/me', endpoint='me')\n@oauth.require_auth()\ndef user_me_handler(user):\n inc = Parser.list('uri', 'inc', User.allowed_includes, optional=True) or []\n return jsonify(user=user.to_dict(inc, confidential=True))\n\n@user_bp.route('/me/reviews', endpoint='reviews')\n@oauth.require_auth()\ndef user_reviews_handler(user):\n return redirect(url_for('review.list', user_id=user.id, **request.args))\n\n@user_bp.route('/me/clients', endpoint='clients')\n@oauth.require_auth()\ndef user_clients_handler(user):\n return jsonify(clients=[c.to_dict() for c in user.clients])\n\n@user_bp.route('/me/tokens', endpoint='tokens')\n@oauth.require_auth()\ndef user_tokens_handler(user):\n return jsonify(tokens=[t.to_dict() for t in user.tokens])\n\n@user_bp.route('/me', endpoint='modify', methods=['POST'])\n@oauth.require_auth('user')\ndef user_modify_handler(user):\n def fetch_params():\n display_name = Parser.string('json', 'display_name', optional=True)\n email = Parser.email('json', 'email', optional=True)\n show_gravatar = Parser.bool('json', 'show_gravatar', optional=True)\n return display_name, email, show_gravatar\n display_name, email, show_gravatar = fetch_params()\n user.update(display_name, email, show_gravatar)\n return jsonify(message='Request processed successfully')\n\n@user_bp.route('/me', endpoint='delete', methods=['DELETE'])\n@oauth.require_auth('user')\ndef user_delete_handler(user):\n user.delete()\n return jsonify(message='Request processed successfully')\n\n@user_bp.route('/', endpoint='entity', methods=['GET'])\ndef user_entity_handler(user_id):\n user = User.query.get_or_404(str(user_id))\n inc = Parser.list('uri', 'inc', User.allowed_includes, optional=True) or []\n return jsonify(user=user.to_dict(inc))\n\n@user_bp.route('/', endpoint='list', methods=['GET'])\ndef review_list_handler():\n def fetch_params():\n limit = Parser.int('uri', 'limit', min=1, max=50, optional=True) or 50\n offset = Parser.int('uri', 'offset', optional=True) or 0\n return limit, offset\n limit, offset = fetch_params()\n users, count = User.list(limit, offset)\n return jsonify(limit=limit, offset=offset, count=count,\n users=[p.to_dict() for p in users])\n\n","sub_path":"server/critiquebrainz/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"436583018","text":"# Copyright 2018 AT&T Intellectual Property. All other rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport falcon\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\n\nfrom deckhand.control import base as api_base\nfrom deckhand.engine.revision_diff import revision_diff\nfrom deckhand import errors\nfrom deckhand import policy\n\nLOG = logging.getLogger(__name__)\n\n\nclass RevisionDeepDiffingResource(api_base.BaseResource):\n \"\"\"API resource for realizing revision deepdiffing.\"\"\"\n\n @policy.authorize('deckhand:show_revision_deepdiff')\n def on_get(self, req, resp, revision_id, comparison_revision_id):\n try:\n revision_id = int(revision_id)\n except ValueError:\n raise errors.InvalidInputException(input_var=str(revision_id))\n try:\n comparison_revision_id = int(comparison_revision_id)\n except ValueError:\n raise errors.InvalidInputException(\n input_var=str(comparison_revision_id))\n\n try:\n resp_body = revision_diff(\n revision_id, comparison_revision_id, deepdiff=True)\n except errors.RevisionNotFound as e:\n with excutils.save_and_reraise_exception():\n LOG.exception(e.format_message())\n\n resp.status = falcon.HTTP_200\n resp.body = resp_body\n","sub_path":"deckhand/control/revision_deepdiffing.py","file_name":"revision_deepdiffing.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"383392947","text":"\"\"\" pyDataVis window module\n\"\"\"\nimport os, csv\n\nfrom PyQt5.QtCore import (QFileInfo, QSize, Qt)\nfrom PyQt5 import QtWidgets\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.figure import Figure\nfrom matplotlib.pyplot import Arrow\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.backends.backend_qt5agg import (\n FigureCanvasQTAgg as FigureCanvas,\n NavigationToolbar2QT as NavigationToolbar)\n\nfrom utils import (isNumber, isNumeric, isNumData, textToData,\n dataToFile, JcampDX, arrayToString)\n\n\n# - vector class ------------------------------------------------------------\n\nclass vectInfo(object):\n \"\"\" vectInfo is used to store information about a data vector\n \"\"\"\n def __init__(self, blkpos, vidx, name):\n self.blkpos = blkpos # index of array whose vector belongs to\n self.vidx = vidx # index of vector in the array\n self.name = name # vector name\n\n def makecopy(self):\n newVect = vectInfo(self.blkpos, self.vidx, self.name)\n return newVect\n\n# - curveData class ------------------------------------------------------------\n\nclass curveInfo(object):\n \"\"\" curveInfo' is used to store information about a curve\n \"\"\"\n def __init__(self, name=\"\", xvinfo=None, yvinfo=None):\n self.name = name # curve name\n self.xvinfo = xvinfo # vector X\n self.yvinfo = yvinfo # vector Y\n self.axis = 1\n self.plottyp = None # type of plot ('line', 'scat', 'bar')\n\n\n# - dcursor class ------------------------------------------------------------\n\nclass dCursor:\n \"\"\" dCursor handles data marker functions (data cursor and markers).\n\n If typ == 'H' the marker is an horizontal line\n If typ == 'V' the marker is a vertical line\n if typ == '+' the marker is the intersection of an horizontal and\n vertical line\n \"\"\"\n def __init__(self, parent, typ='+'):\n self.parent = parent\n self.typ = typ\n self.colour = 'gray'\n if typ == 'H':\n self.hl = parent.axes.axhline(color=self.colour) # the horiz line\n elif typ == 'V':\n self.vl = parent.axes.axvline(color=self.colour) # the vert line\n else:\n self.typ = '+'\n self.colour = 'chocolate'\n self.hl = parent.axes.axhline(color=self.colour) # the horiz line\n self.vl = parent.axes.axvline(color=self.colour) # the vert line\n self.hl2 = None\n self.blkno = 0 # data block of the active curve\n self.xpos = 0 # index of X data of the active curve\n self.ypos = 1 # index of Y data of the active curve\n self.X = None # X data of the active curve\n self.Y = None # Y data of the active curve\n self.xc = None # x coordinate of the dcursor\n self.yc = None # y coordinate of the dcursor\n self.ic = 0 # index of the dcursor\n self.updateCurve()\n\n\n def updateCurve(self):\n \"\"\" Update the dCursor data when the activcurv is changed\n\n :return: nothing\n \"\"\"\n cinfo = self.parent.curvelist[self.parent.activcurv]\n self.X = self.parent.blklst[cinfo.xvinfo.blkpos][cinfo.xvinfo.vidx]\n self.Y = self.parent.blklst[cinfo.yvinfo.blkpos][cinfo.yvinfo.vidx]\n npt = self.X.size\n self.parent.xascending = (self.X[npt-1] > self.X[0])\n self.blkno = cinfo.yvinfo.blkpos\n if self.xc is None:\n self.ic = 0\n else:\n self.ic = self.parent.xToIdx(self.xc, self.blkno, self.xpos)\n if self.ic is not None:\n if self.ic >= npt:\n self.ic = npt-1\n else:\n self.ic = 0\n if self.parent.curvelist[self.parent.activcurv].axis == 1:\n self.lh2 = None\n else:\n if self.parent.y2axis is not None:\n self.hl2 = self.parent.y2axis.axhline(color=self.colour)\n\n\n def updateLinePos(self, redraw=False):\n \"\"\" Update the cursor position from self.X, self.Y et self.indx\n\n :param redraw: if True redraw everything, if False update only\n the lines.\n :return: nothing\n \"\"\"\n self.xc = self.X[self.ic]\n self.yc = self.Y[self.ic]\n if redraw:\n self.parent.plotCurves()\n else:\n if self.typ == 'V' or self.typ == '+':\n self.vl.set_xdata(self.xc)\n if self.typ == 'H' or self.typ == '+':\n if self.parent.curvelist[self.parent.activcurv].axis == 1:\n self.hl.set_ydata(self.yc)\n else:\n self.hl2.set_ydata(self.yc)\n self.parent.canvas.draw()\n # update status line with the cursor position\n msg = \"{0}: no: {1:d}, xc = {2:g}, yc = {3:g}\".\\\n format(self.parent.curvelist[self.parent.activcurv].name,\n self.ic+1, self.xc, self.yc)\n self.parent.parent.statusbar.showMessage(msg)\n\n\n def setIndex(self, index):\n \"\"\" Move the cursor position to 'index'\n\n :param index: int giving the new data index\n :return: True is success, False otherwise.\n \"\"\"\n if index >= 0 and index < len(self.parent.blklst[self.blkno][self.xpos]):\n self.ic = index\n self.updateLinePos()\n return True\n return False\n\n\n def getIndex(self):\n \"\"\" Return the index position of the Cursor\n\n :return: the index\n \"\"\"\n return self.ic\n\n\n def getxy(self):\n \"\"\" Return the coordinates of the Cursor\n\n :return: a tuple containing\n \"\"\"\n return (self.xc, self.yc)\n\n\n\n def move(self, event=None, indx=None):\n \"\"\" Move the Cursor to a new index position.\n\n :param event: mouse event.\n :param indx: data index of the place to move.\n :return: True is success, False otherwise.\n \"\"\"\n if indx is None and event is None:\n return False\n if indx is None:\n x, y = event.xdata, event.ydata\n if not self.parent.xascending:\n Xr = self.X[::-1]\n indx = self.X.size - np.searchsorted(Xr, x) - 1\n else:\n indx = np.searchsorted(self.X, x)\n if indx < 0:\n indx = 0\n elif indx >= len(self.parent.blklst[self.blkno][self.xpos]):\n indx = len(self.parent.blklst[self.blkno][self.xpos])\n return self.setIndex(indx)\n\n\n# - Line class ------------------------------------------------------------\n\nclass lineSeg:\n \"\"\" Create a line segment marker\n\n \"\"\"\n def __init__(self, x1, y1, x2, y2, color):\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n self.color = color\n\n\n# - plotWin class ------------------------------------------------------------\n\nclass plotWin(QtWidgets.QDialog):\n newcpt = 1 # Global counter for the numbering of new plotWin objects\n\n def __init__(self, parent=None, filename=None):\n \"\"\" Plotting area and Text window.\n\n :param parent: pyDataVis MainWindow\n :param filename: name of the file which stores the data.\n \"\"\"\n super(plotWin, self).__init__(parent)\n\n self.colors = ('blue','red','green','gray','magenta','black','brown',\n 'cyan', 'cadetblue', 'chocolate', 'coral', 'darkred',\n 'burlywood', 'darkgreen', 'darkblue', 'darkcyan',\n 'yellow', 'aqua', 'aquamarine', 'blueviolet',\n 'cornflowerblue', 'crimson', 'darkgoldenrod',\n 'darkkhaki', 'darkmagenta', 'darkolivegreen',\n 'darkorange', 'darksalmon', 'darkseagreen',\n 'darkslateblue', 'darkslategray', 'darkviolet',\n 'deeppink', 'goldenrod','greenyellow', 'hotpink',\n 'indigo', 'white')\n self.filext = ('TXT', 'DAT', 'ASC', 'CSV', 'JDX', 'PLT', 'PRF' )\n self.parent = parent\n if filename is None:\n while True:\n filename = str(\"Unnamed-{0}.txt\".format(plotWin.newcpt))\n filename = os.path.join(filename, self.parent.progpath)\n if self.parent.isAlreadyOpen(filename):\n plotWin.newcpt += 1\n else:\n break\n plotWin.newcpt += 1\n self.filename = filename\n self.dirty = False\n self.colsep = None # Column separator\n self.vectInfolst = [] # list of list of vectInfo object\n self.curvelist = [] # List of curves (curveInfo object)\n self.blklst = None # List of numpy array containing the data blocks\n self.nvect = 0 # number of vectors\n self.nelem = 0 # number of elements in each vector\n self.headers = None # list of list lines storing file header\n self.axes = None # matplotlib.axes.Axes object\n self.y2axis = None # matplotlib.axes.Axes object\n self.labx = None # legend of X axis\n self.laby1 = None # legend of Y1 axis\n self.laby2 = None # legend of Y2 axis\n self.arrows = [] # parameters for drawing arrows on plot\n self.plottext = [] # parameters for writing text label on plot\n self.invertX = False\n self.invertY = False\n self.logX = False\n self.logY = False\n self.dplot = [] # table of Line2D object\n self.legend = None\n self.dcursor = None # data reader (dCursor type)\n self.markList = [] # list of data Markers (dCursor type)\n self.lineList = [] # list of line segment Markers (LinSeg type)\n self.activcurv = 0 # index of the curve followed by the dcursor\n self.tabledlg = None # data Table (tableDlg object)\n\n # Try to adapt the window size to screen resolution\n ww = self.parent.scrsize.width()\n if ww > 1920:\n figdpi = 110\n w = 8.0\n h = 6.0\n else:\n figdpi = 70\n w = 7.0\n h = 6.0\n self.fig = Figure((w, h), dpi=figdpi)\n\n # self.canvas is the \"Plotting area\"\n self.canvas = FigureCanvas(self.fig)\n self.canvas.setParent(self)\n self.canvas.setFocusPolicy(Qt.StrongFocus)\n self.mpl_toolbar = NavigationToolbar(self.canvas, self)\n if ww > 1920:\n self.mpl_toolbar.setIconSize(QSize(25, 25))\n else:\n self.mpl_toolbar.setIconSize(QSize(15, 15))\n # self.datatext is the \"Text editor window\"\n self.datatext = QtWidgets.QTextEdit(self)\n\n # self.scriptwin is the \"Script window\"\n self.scriptwin = QtWidgets.QTextEdit(self)\n # self.info is the \"Information window\"\n self.info = QtWidgets.QTextEdit(self)\n self.info.setReadOnly(True)\n # set the layout\n vbox = QtWidgets.QVBoxLayout()\n vboxgr = QtWidgets.QVBoxLayout()\n vboxgr.addWidget(self.canvas)\n vboxgr.addWidget(self.mpl_toolbar)\n vbox.addLayout(vboxgr, 65)\n vbox.addWidget(self.datatext, 20)\n hbox = QtWidgets.QHBoxLayout()\n hbox.addWidget(self.scriptwin, 55)\n hbox.addWidget(self.info, 45)\n vbox.addLayout(hbox,15)\n self.setLayout(vbox)\n self.setTextFont(self.parent.txteditfont)\n self.setWindowTitle(QFileInfo(self.filename).fileName())\n\n # The FigureCanvas method mpl_connect() returns a connection id\n # which is simply an integer.\n self.canvas.mpl_connect('button_press_event', self.onClick)\n self.canvas.mpl_connect('key_press_event', self.on_key_press)\n\n\n def setTextFont(self, font):\n \"\"\" Set the font for the all the QTextEdit widgets\n\n :param font: Font\n :return: nothing\n \"\"\"\n self.datatext.setFont(font)\n self.info.setFont(font)\n self.scriptwin.setFont(font)\n\n\n def on_key_press(self, event):\n # implement the default mpl key press events described at\n # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts\n self.parent.keyb = event.key\n #print(event.key)\n key_press_handler(event, self.canvas, self.mpl_toolbar)\n\n\n def onClick(self, event):\n \"\"\" Callback function for a user mouse click.\n\n :param event: mouse event\n :return: nothing\n \"\"\"\n self.parent.updateUI()\n if event.inaxes:\n if event.button > 1:\n self.parent.raise_()\n self.parent.activateWindow()\n if self.dcursor == None:\n self.dcursor = dCursor(self)\n self.dcursor.move(event)\n if self.tabledlg is not None:\n self.tabledlg.table.setCurrentPos(self.dcursor.ic)\n self.tabledlg.raise_()\n self.parent.updateUI()\n self.setFocus()\n\n\n def xToIdx(self, x, blkno=0, xpos=0):\n \"\"\" Return the index giving the value closest to 'x'\n\n :param x: the position\n :param blkno: the data block number\n :param xpos: the position of X data in the data block.\n :return: the closest index.\n \"\"\"\n if self.xascending:\n tpidx = np.where(self.blklst[blkno][xpos] >= x)\n else:\n tpidx = np.where(self.blklst[blkno][xpos] <= x)\n if tpidx[0].size == 0:\n return None\n return tpidx[0][0]\n\n\n def clearMarks(self):\n \"\"\" Remove the cursor and all the markers, if any.\n\n :return: nothing\n \"\"\"\n if self.dcursor != None:\n self.dcursor = None\n # remove the data markers if any\n del self.markList[:]\n del self.lineList[:]\n # redraw\n self.parent.statusbar.showMessage(\"\")\n self.plotCurves()\n self.parent.updateUI()\n\n\n\n def closeEvent(self, event):\n if (self.dirty and\n QtWidgets.QMessageBox.question(self.parent,\n \"pyDataVis - Unsaved Changes\",\n \"Save unsaved changes in {0}?\".format(str(self.filename)),\n QtWidgets.QMessageBox.Yes|QtWidgets.QMessageBox.No) ==\n QtWidgets.QMessageBox.Yes):\n try:\n self.save(self.filename)\n except (IOError, OSError) as err:\n QtWidgets.QMessageBox.warning(self.parent,\n \"pyDataVis -- Save Error\",\n \"Failed to save {0}: {1}\".format(str(self.filename), err),\n QtWidgets.QMessageBox.Cancel |\n QtWidgets.QMessageBox.NoButton |\n QtWidgets.QMessageBox.NoButton)\n if self.parent.numpltw > 0:\n self.parent.numpltw -= 1\n self.parent.updateUI()\n\n\n def findNumData(self, txtlines):\n \"\"\" Look for the beginning of the data block (skip non numeric data).\n\n Read the beginning of the file until finding two successive lines\n which contain only numbers. Store the lines before the data\n block in self.header.\n\n :param txtlines: list of strings containing data.\n :return: The index of the first line of the data block or -1.\n \"\"\"\n self.vectnames = []\n header = []\n numflg = 0\n for l, line in enumerate(txtlines):\n line = line.strip(' \\r\\n')\n if line:\n if isNumData(line):\n numflg += 1\n else:\n if numflg == 1:\n # The previous line was numeric but not this one,\n # therefore reset numflg.\n numflg = 0\n if numflg < 2:\n header.append(line)\n else:\n break\n if numflg == 2:\n # The last header line contains the first line of the\n # data block, remove it.\n del header[-1]\n l -= 1\n self.headers.append(header)\n else:\n l = -1\n return l\n\n\n def setVectorNames(self, sep):\n \"\"\" Give a name to the vectors\n\n :param sep: a character, the column separator\n :return: Nothing\n \"\"\"\n if self.headers:\n if self.headers[0]:\n items = self.headers[0][-1].split(sep)\n if sep == ' ':\n # Remove empty elements (case of multiple space separators)\n items = [x for x in items if x]\n nnam = len(items)\n if nnam == self.nvect and not isNumeric(items):\n if items[0].startswith('#'):\n items[0] = items[0][1:]\n # remove leading and trailing spaces\n items = [item.strip() for item in items]\n self.vectnames = items\n return\n # if the vector names are not provided, name them as Vn\n for i in range(self.nvect):\n self.vectnames.append(\"V{0}\".format(i + 1))\n\n\n\n def fileToString(self, filename):\n \"\"\" Convert the text in 'filename' in a string\n\n :param filename: name of the text file\n :return: A tuple with an error message and a string.\n If no error, the error message = \"\" else the string is None.\n \"\"\"\n errmsg = \"\"\n try:\n textfile = open(filename, 'r')\n ftext = textfile.read()\n textfile.close()\n except (IOError, OSError) as err:\n errmsg = err\n except (UnicodeDecodeError) as err:\n try:\n textfile = open(filename, 'r', encoding = 'utf-16')\n ftext = textfile.read()\n textfile.close()\n except (UnicodeDecodeError) as err:\n errmsg = err\n if not errmsg:\n l = len(ftext)\n if l < 1:\n errmsg = \"Empty file\"\n if errmsg:\n ftext = None\n return errmsg, ftext\n\n\n\n def load(self, filename):\n \"\"\" Read the data from the file 'filename'.\n\n :param filename: name of the data file to read.\n :return: if no error, returns an empty string; otherwise an errmsg.\n \"\"\"\n\n # Load the file content in self.datatext\n errmsg, txt = self.fileToString(filename)\n if errmsg:\n return errmsg\n self.datatext.setPlainText(txt)\n self.filename = filename\n blocks = None\n colsep = ' '\n self.headers = []\n txtlines = txt.splitlines()\n if len(txtlines) < 2:\n errmsg = \"Not enough lines to proceed\"\n else:\n # Try with JcampDX format\n errmsg, block, header = JcampDX(txtlines)\n if errmsg == \"\" and block is not None:\n if len(block):\n blocks = [block]\n self.headers.append(header)\n headers = []\n else:\n startidx = self.findNumData(txtlines)\n if startidx != -1:\n # Try to guess the column separator\n if isNumber(txtlines[startidx]):\n # No separator, 1D data\n colsep = None\n else:\n dialect = csv.Sniffer().sniff(txtlines[startidx])\n colsep = dialect.delimiter\n errmsg = \"\"\n else:\n errmsg = \"Cannot decode the text data\"\n\n if not errmsg and blocks is None:\n errmsg, blocks, headers = textToData(txtlines[startidx:], colsep)\n if blocks is None or len(blocks) == 0 or len(blocks[0][0]) == 0:\n errmsg = 'Unable to decode numeric data'\n else:\n try:\n for blk in blocks:\n (self.nvect, self.nelem) = np.shape(np.array(blk))\n self.colsep = colsep\n except ValueError:\n errmsg = \"Cannot decode the text data\"\n\n if not errmsg:\n self.blklst = []\n for i in range(len(blocks)):\n # convert the list of list in blocks into a list of numpy array\n self.blklst.append(np.array(blocks[i]))\n if len(headers) > 1:\n for header in headers[1:]:\n self.headers.append(header)\n errmsg = self.initializeCurves()\n\n if errmsg:\n if self.datatext.toPlainText():\n errmsg += '\\nOnly loading text'\n self.info.setText(errmsg)\n errmsg = \"\"\n else:\n self.updatePlot()\n info = 'Data from {0} loaded'.format(os.path.basename(filename))\n # Display the message in the status bar\n self.parent.statusbar.showMessage(info, 10000)\n self.dirty = False\n return errmsg\n\n\n def initializeCurves(self):\n \"\"\" Initialize vectors and curves\n\n :return: an error message (=\"\") if no error\n \"\"\"\n\n # Initialize self.vectInfolst from data blocks\n self.initVectInfoList()\n self.curvelist = []\n self.datatyp = 'unknown'\n errmsg = \"\"\n\n # Look for plots commands in the header\n if self.headers:\n cmdlist = []\n for header in self.headers[0]:\n if header.startswith('#plot ') or header.startswith('# plot '):\n cmdlist.append(header)\n elif header.startswith('#lab') or header.startswith('# lab'):\n cmdlist.append(header)\n elif header.startswith('#symbol ') or header.startswith('# symbol '):\n cmdlist.append(header)\n elif header.startswith('#text ') or header.startswith('# text '):\n cmdlist.append(header)\n elif header.startswith('#arrow ') or header.startswith('# arrow '):\n cmdlist.append(header)\n elif header.startswith(\"##DATA TYPE=\"):\n if header.find(\"MASS SPECTRUM\") != -1:\n self.datatyp = 'MS'\n self.labx = self.vectInfolst[0][0].name = \"Mass\"\n self.laby1 = self.vectInfolst[0][1].name = \"Intensity\"\n elif header.find(\"INFRARED SPECTRUM\") != -1:\n self.datatyp = 'IR'\n self.labx = self.vectInfolst[0][0].name = \"Wavenumber (/cm)\"\n elif header.find(\"NMR SPECTRUM\") != -1:\n self.datatyp = 'NMR'\n self.laby1 = self.vectInfolst[0][1].name = \"I\"\n elif header.startswith(\"##XUNITS=\"):\n if self.datatyp == 'NMR':\n datatyp = 'line'\n xlab = header.split('=')[1].strip()\n self.labx = self.vectInfolst[0][0].name = xlab\n elif header.startswith(\"##YUNITS=\"):\n if header.find(\"TRANSMITTANCE\") != -1:\n self.laby1 = self.vectInfolst[0][1].name = \"Transmittance\"\n if header.find(\"ABSORBANCE\") != -1:\n self.laby1 = self.vectInfolst[0][1].name = \"Absorbance\"\n elif header.startswith(\"##RRUFFID=R\"):\n self.datatyp = 'Raman'\n self.vectInfolst[0][0].name = \"Raman_Shift\"\n self.labx = \"Raman Shift (/cm)\"\n self.laby1 = self.vectInfolst[0][1].name = \"Intensity\"\n if cmdlist:\n for cmd in cmdlist:\n errmsg = self.plotCmdToCurve(cmd)\n if errmsg != \"\":\n return errmsg\n\n if self.curvelist:\n # check that vector names match curve names\n for curve in self.curvelist:\n curve.yvinfo.name = curve.name\n\n if self.curvelist == []:\n for blk in range(len(self.blklst)):\n (nvec, npt) = np.shape(self.blklst[blk])\n if nvec > npt and npt < 4:\n # Most probably data need to be transposed\n # do not plot anything\n pass\n else:\n for i in range(nvec - 1):\n curvinfo = curveInfo(self.vectInfolst[blk][i+1].name,\n self.vectInfolst[blk][0],\n self.vectInfolst[blk][i+1])\n if npt < 15:\n curvinfo.symbol = True\n self.curvelist.append(curvinfo)\n\n if self.vectInfolst == []:\n errmsg = \"Cannot decode the text data\"\n else:\n if self.curvelist != []:\n if self.datatyp == 'MS':\n self.curvelist[0].plottyp = 'bar'\n else:\n self.curvelist[0].plottyp = 'line'\n return errmsg\n\n\n\n def importSheets(self, filename):\n \"\"\" Import spreadsheet data from the file 'filename'.\n\n :param filename: name of the data file to read.\n :return: if no error, returns an empty string; otherwise an errmsg.\n \"\"\"\n\n basenam, ext = os.path.splitext(filename)\n ext = ext.upper()[1:]\n if ext == 'ODS':\n engine = 'odf'\n elif ext.startswith(\"XL\"):\n engine = 'xlrd'\n else:\n return \"Unrecognized file extension\"\n\n try:\n sheets = pd.read_excel(filename, sheet_name=None, engine=engine)\n except (IOError, OSError, ImportError, ValueError) as err:\n return err\n\n self.blklst = []\n self.headers = []\n for s, sheet in enumerate(sheets):\n # Delete rows where all cells are empty\n df = sheets[sheet]\n df = df.dropna(0, how='all')\n # Delete columns where all cells are empty\n df = df.dropna(1, how='all')\n if df.empty:\n return \"No usable numeric data in {0}\".format(df[s].key)\n self.blklst.append(df.values)\n # the non numeric first row is supposed to contain vector names\n vnamlst = list(df.values[0])\n if isNumeric(vnamlst):\n vnamlst = list(df.columns.values)\n if isNumeric(vnamlst) or vnamlst[0].startswith(\"Unnamed\"):\n for i, vnam in enumerate(vnamlst):\n vnamlst[i] = \"V{0}\".format(i+1)\n else:\n # remove the non numeric first row\n self.blklst[0] = self.blklst[s][1:]\n self.blklst[s] = self.blklst[s].transpose()\n self.headers.append(['\\t'.join(vnamlst)])\n\n errmsg = self.initializeCurves()\n if not errmsg:\n # Build the text for filling the Text editor window\n text = \"\"\n n = len(self.blklst)\n for b, blk in enumerate(self.blklst):\n vnames = \"\"\n for vect in self.vectInfolst[b]:\n vnames += \"{0}\\t\".format(vect.name)\n text += arrayToString(blk, vnames)\n if b < n-1:\n text += \"\\n\\n\"\n self.datatext.setPlainText(text)\n\n self.updatePlot()\n info = 'Data from {0} imported'.format(os.path.basename(filename))\n # Display the message in the status bar\n self.parent.statusbar.showMessage(info, 10000)\n self.dirty = False\n return errmsg\n\n\n\n def save(self, filename):\n \"\"\" Save the current data in file 'filename'\n\n :param filename: the name of the file to save.\n :return: False if an error occurred otherwise return True.\n \"\"\"\n if filename:\n if self.blklst is None:\n # save only the text in datatext\n file = open(filename, 'w')\n file.write(self.datatext.toPlainText())\n else:\n # build the header list\n headers = []\n header = ''\n if self.headers is not None:\n for line in self.headers[0]:\n # Do not add plot commands\n if line.startswith(\"#plot\") or line.startswith(\"#lab\"):\n break\n if self.datatyp != 'unknown' and line.startswith(\"##\"):\n # Remove the first # to avoid confusion with JCAMP-DX file\n line = line[1:]\n header += line + '\\n'\n\n # insert the plot command\n cmdlst = self.curveToPlotCmd(self.curvelist)\n if cmdlst is not None:\n cmd = \"\\n#\".join(cmdlst)\n header += '#'+ cmd + '\\n'\n # insert the plot commands\n if self.labx is not None:\n header += \"#labX {0}\\n\".format(self.labx.strip())\n if self.laby1 is not None:\n header += \"#labY1 {0}\\n\".format(self.laby1.strip())\n if self.laby2 is not None:\n header += \"#labY2 {0}\\n\".format(self.laby2.strip())\n if self.logX or self.logY:\n header += '#logaxis {0},{1}\\n'.format(int(self.logX), int(self.logY))\n if self.arrows:\n for arrowprm in self.arrows:\n header += \"#arrow {0}\\n\".format(arrowprm)\n if self.plottext:\n for txtprm in self.plottext:\n header += \"#text {0}\\n\".format(txtprm)\n if cmdlst is not None:\n header += '#\\n'\n\n # Insert the line containing vector names\n header += '#'\n for i, nparray in enumerate(self.blklst):\n for j in range(len(self.vectInfolst[i])):\n if j > 0:\n header += '\\t'\n header += self.vectInfolst[i][j].name\n header += '\\n'\n headers.append(header)\n header = '#'\n\n errno, errmsg = dataToFile(filename, self.blklst, headers)\n if errno:\n QtWidgets.QMessageBox.warning(self.parent, \"Save\", errmsg,\n QtWidgets.QMessageBox.Cancel |\n QtWidgets.QMessageBox.NoButton |\n QtWidgets.QMessageBox.NoButton)\n else:\n info = 'Data saved'.format(os.path.basename(filename))\n self.dirty = False\n # Display the message in the status bar\n self.parent.statusbar.showMessage(info, 10000)\n self.dirty = False\n return True\n return False\n\n\n def exportToCSV(self, blkno, filename):\n \"\"\" Save the data block 'blkno' in file 'filename' with CSV format.\n\n :param blkno: the number of the data block to save (=0 for the 1st blk).\n :param filename: the name of the file to save.\n :return: False if an error occurred otherwise return True.\n \"\"\"\n if blkno < 0 or blkno > len(self.blklst):\n return False\n\n if filename:\n # Build the header containing the vector names\n header = []\n for j in range(len(self.vectInfolst[blkno])):\n header.append(self.vectInfolst[blkno][j].name)\n err = 0\n df = pd.DataFrame(self.blklst[blkno].transpose())\n try:\n df.to_csv(filename, header=header, index=False)\n except (IOError, OSError) as err:\n QtWidgets.QMessageBox.warning(self.parent, \"Save\", err,\n QtWidgets.QMessageBox.Cancel |\n QtWidgets.QMessageBox.NoButton |\n QtWidgets.QMessageBox.NoButton)\n if not err:\n info = 'Data exported as CSV in {0}'.format(os.path.basename(filename))\n # Display the message in the status bar\n self.parent.statusbar.showMessage(info, 10000)\n return True\n return False\n\n\n\n def getvectInfo(self, noblk, nvect, header):\n \"\"\" Try to extract the vector names in the data header\n and initialize a vectInfo list\n\n The vector names are supposed to be just before the numerical data\n and thus to be in the last line of the header.\n This line should contains as much items as vectors in the block.\n\n :param noblk: is the index of the data block in the list.\n :param nvect: is the number of vectors in the data block.\n :param header: a list of string\n :return: a list of vectInfo\n \"\"\"\n lh = len(header)\n vinfolist = []\n if lh > 0:\n # the last line is supposed to contains the vector name\n vnam = header[lh - 1]\n if vnam.startswith('#'):\n # remove the # at the beginning\n vnam = vnam[1:]\n vnam = vnam.strip()\n if self.colsep is not None:\n vlst = list(vnam.split(self.colsep))\n else:\n vlst = list(vnam.split())\n if vlst:\n if len(vlst) == nvect:\n # Correct the names containing unauthorized characters\n charlst = list(' (),;:=-+*/')\n for i, vnam in enumerate(vlst):\n vnam = vnam.strip()\n for c in charlst:\n if c in vnam:\n items = vnam.split(c, 1)\n vnam = items[0]\n break\n vinfo = vectInfo(noblk, i, vnam)\n vinfolist.append(vinfo)\n return vinfolist\n\n\n def autovectInfo(self, noblk, nvect):\n \"\"\" Create automatically a vectInfo list associated to a data block.\n\n The generic name is 'VjBi' where j and i are respectively the\n indexes of the vector and the index of the block whose vector belongs.\n\n :param noblk: is the index of the data block in the list\n :param nvect: is the number of vectors in the data block\n :return: a list of vectInfo\n \"\"\"\n vinfolist = []\n for j in range(nvect):\n name = 'V{}B{}'.format(j+1, noblk+1)\n vinfo = vectInfo(noblk, j, name)\n vinfolist.append(vinfo)\n return vinfolist\n\n\n def initVectInfoList(self):\n \"\"\" Initialize self.vectInfolst from data blocks\n\n :return: nothing\n \"\"\"\n vectInfolst = []\n for i, nparray in enumerate(self.blklst):\n nvec, npt = np.shape(nparray)\n vinfolst = self.getvectInfo(i, nvec, self.headers[i])\n if len(vinfolst) != nvec:\n vinfolst = self.autovectInfo(i, nvec)\n else:\n # remove the line with vector names from header\n lh = len(self.headers[i])\n self.headers[i].pop(lh-1)\n vectInfolst.append(vinfolst)\n self.vectInfolst = vectInfolst\n\n\n def setDataInfo(self, blklst, vectInfolst):\n \"\"\" Create a multiline string containing basic information about the data.\n\n :param blklst: list of numpy array containing the data\n :param vectInfolst: list of list of vectInfo object\n :return: the 'info' string.\n \"\"\"\n info = 'Number of data block = {0}\\n'.format(len(blklst))\n for i, nparray in enumerate(blklst):\n nvect, nrow = np.shape(nparray)\n info += 'Block {0} : {1} vector(s) of size {2}\\n'.format(i+1, nvect, nrow)\n for j, vinfo in enumerate (vectInfolst[i]):\n if j == 0:\n info += 'Vector names = ' + vectInfolst[i][0].name\n else:\n info += ', ' + vectInfolst[i][j].name\n info += '\\n'\n return info\n\n\n def getVinfo(self, vnam, vectInfolst=None):\n \"\"\" Find the vectInfo object in 'vectInfolst' whose name is 'vname'\n\n If 'vectInfolst' is None use 'self.vectInfolst'.\n\n :param vnam: name of the searched vector\n :param vectInfolst: list of list of vectInfo objets.\n :return: the vectInfo object or None if not found.\n \"\"\"\n if not vnam:\n return None\n if vectInfolst is None:\n vectInfolst = self.vectInfolst\n for vinfolst in vectInfolst:\n for vinfo in vinfolst:\n if vinfo.name == vnam:\n return vinfo\n return None\n\n\n def getVnam(self, blkno, vidx, vectInfolst=None):\n \"\"\" Find the name of the vector from its block number and position.\n\n If 'vectInfolst' is None use 'self.vectInfolst'.\n\n :param blkno: number of the block whose vector belongs\n :param vidx: index of the vector in this block\n :param vectInfolst: list of list of vectInfo objets.\n :return: name of the searched vector\n \"\"\"\n\n if vectInfolst is None:\n vectInfolst = self.vectInfolst\n for vinfolst in vectInfolst:\n for vinfo in vinfolst:\n if vinfo.blkpos == blkno:\n if vinfo.vidx == vidx:\n return vinfo.name\n return None\n\n\n def getCurvinfo(self, cname, curvinfolst=None):\n \"\"\" Find the first curveInfo object in 'curvinfolst' whose name is 'cname'\n\n If 'curvinfolst' is None use 'self.curvelist'.\n\n :param cname: Name of the searched curveInfo object.\n :param curvinfolst: List of cureInfo objets.\n :return: the curveinfo object or None if not found.\n \"\"\"\n if curvinfolst is None:\n curvinfolst = self.curvelist\n for curvinfo in curvinfolst:\n if curvinfo.name == cname:\n return curvinfo\n return None\n\n\n\n def plotCurves(self, curvelist=None):\n \"\"\" Plot the curves in curvelist\n\n If 'curvelist' is None use self.curvelist\n\n :param curvelist: List of the curveInfo objets\n :return: nothing\n \"\"\"\n if curvelist is None:\n curvelist = self.curvelist\n nc = len(curvelist)\n self.canvas.setFocus()\n self.fig.clf()\n if nc > 0:\n self.axes = self.fig.add_subplot(111)\n else:\n # nothing to plot\n self.canvas.draw()\n return\n\n if self.invertX:\n self.axes.invert_xaxis()\n if self.invertY:\n self.axes.invert_yaxis()\n self.dplot = []\n\n # draw the cursor\n if self.dcursor:\n self.dcursor.vl = self.axes.axvline(self.dcursor.xc, color='chocolate')\n if self.curvelist[self.activcurv].axis == 1:\n self.dcursor.hl = self.axes.axhline(self.dcursor.yc, color='chocolate')\n else:\n self.dcursor.hl2 = self.y2axis.axhline(self.dcursor.yc, color='chocolate')\n # draw the data markers\n if len(self.markList):\n for i in range (len(self.markList)):\n self.markList[i].vl = self.axes.axvline(self.markList[i].xc, color='gray')\n\n # draw the line markers\n if len(self.lineList):\n for i in range (len(self.lineList)):\n self.axes.plot([self.lineList[i].x1,\n self.lineList[i].x2],\n [self.lineList[i].y1,\n self.lineList[i].y2],\n linewidth=3,\n color=self.lineList[i].color,\n linestyle='--')\n\n # draw the data curves\n for i in range(nc):\n vx = self.blklst[curvelist[i].xvinfo.blkpos][curvelist[i].xvinfo.vidx]\n vy = self.blklst[curvelist[i].yvinfo.blkpos][curvelist[i].yvinfo.vidx]\n if i < len(self.colors):\n color = self.colors[i]\n else:\n color = 'black'\n if curvelist[i].plottyp == 'scat':\n marker = 'o'\n else:\n marker = None\n if curvelist[i].axis == 1:\n if curvelist[i].plottyp == 'bar':\n self.axes.bar(vx, vy)\n elif curvelist[i].plottyp == 'scat':\n self.dplot.append(self.axes.scatter(vx, vy,\n color=color,\n marker=marker,\n label=curvelist[i].name))\n else:\n # plotting against Y1 axis\n self.dplot.append(self.axes.plot(vx, vy,\n color=color,\n marker=marker,\n label=curvelist[i].name))\n elif curvelist[i].axis == 2:\n # add y2axis\n self.y2axis = self.axes.twinx()\n self.dplot.append(self.y2axis.plot(vx, vy,\n color=color,\n label=curvelist[i].name))\n\n # Set axis labels\n self.axes.tick_params(axis='x', labelsize=self.parent.chartfontsiz)\n self.axes.tick_params(axis='y', labelsize=self.parent.chartfontsiz)\n # put axis legend\n if self.labx is not None:\n self.axes.set_xlabel(self.labx, fontweight='bold', fontsize=self.parent.chartfontsiz)\n if self.laby1 is not None:\n self.axes.set_ylabel(self.laby1, fontweight='bold', fontsize=self.parent.chartfontsiz)\n if self.laby2 is not None:\n self.y2axis.set_ylabel(self.laby2, fontweight='bold', fontsize=self.parent.chartfontsiz)\n # Log scale is set with MatPlotLib toolbar\n #if self.logX:\n # self.axes.set_xscale('log')\n #if self.logY:\n # self.axes.set_yscale(\"log\")\n\n # Set legends\n if nc > 1:\n c = []\n legendlist = []\n for i in range(nc):\n if curvelist[i].plottyp == 'scat':\n c.append(self.dplot[i])\n else:\n c.append(self.dplot[i][0])\n legendlist.append(curvelist[i].name)\n self.axes.legend(tuple(c), tuple(legendlist),\n loc='best', fontsize=self.parent.chartfontsiz, numpoints=1, shadow=True)\n # draw arrow\n if len(self.arrows):\n for arrw in self.arrows:\n # Arrow function draws arrow from (x, y) to (x + dx, y + dy)\n # x, y, dx, dy, head_width, head_length, color\n prmlst = arrw.split(',')\n if len(prmlst) == 5:\n xmin, xmax, ymin, ymax = self.axes.axis()\n if xmin < 0 and xmax > 0:\n xspan = xmax - xmin\n else:\n xspan = xmax - xmin\n if ymin < 0 and ymax > 0:\n yspan = ymax - ymin\n else:\n yspan = ymax - ymin\n xpos = float(prmlst[0])\n ypos = float(prmlst[1])\n dx = float(prmlst[2])\n dy = float(prmlst[3])\n if dx == 0.0:\n # vertical arrow\n w = xspan/50.0\n elif dy == 0.0:\n # horizontal arrow\n w = yspan/50.0\n else:\n w = xspan/50.0\n arrw = Arrow(xpos, ypos, dx, dy, width=w, color=prmlst[4], gid='exo')\n self.axes.add_patch(arrw)\n\n # print text labels\n if len(self.plottext):\n for txtprm in self.plottext:\n prmlst = txtprm.split(',')\n if len(prmlst) == 5:\n # xpos, ypos, text, color, fontsize\n xpos = float(prmlst[0])\n ypos = float(prmlst[1])\n fntsiz = int(prmlst[4])\n self.axes.text(xpos, ypos, prmlst[2], color=prmlst[3], fontsize=fntsiz)\n\n self.canvas.draw()\n\n\n def checkPlotCmd(self, line, curvelist=None):\n \"\"\" Check the plot command in 'line'\n\n :return: an error message (= \"\" if no error).\n \"\"\"\n if curvelist is None:\n curvelist = self.curvelist\n if line.startswith('plot'):\n items = line[5:].split(',')\n l = len(items)\n if l < 2 or l > 3 or (l == 3 and items[2] != '2'):\n return \"Accept only two vectors\"\n else:\n v1nam = items[0]\n v1info = self.getVinfo(v1nam.strip())\n v2nam = items[1]\n v2info = self.getVinfo(v2nam.strip())\n if v1info is None or v2info is None:\n return \"Unknown vector name\"\n if v1info.blkpos != v2info.blkpos:\n return \"{0} and {1} must belong to the same data block\".format(v1nam, v2nam)\n return \"\"\n\n elif line.startswith('lab'):\n items = line[3:].split(' ')\n if len(items) < 2:\n return \"Missing axis label\"\n else:\n if not items[0] in ['X', 'Y1', 'Y2']:\n return \"Accept only either labX, labY1 or labY2\"\n if items[0] == 'Y2' and self.y2axis is None:\n return \"No secondary Y axis\"\n return \"\"\n\n elif line.startswith('symbol'):\n items = line.split(' ')\n if len(items) != 2:\n return \"One parameter is required\"\n curvinfo = self.getCurvinfo(items[1].strip(), curvelist)\n if curvinfo is not None:\n return \"\"\n else:\n return (1, \"Wrong curve name\")\n\n elif line.startswith('nosymbol'):\n items = line.split(' ')\n if len(items) != 2:\n return \"Only one parameters is required\"\n curvinfo = self.getCurvinfo(items[1].strip(), curvelist)\n if curvinfo is not None:\n return \"\"\n else:\n return (1, \"Wrong curve name\")\n\n elif line.startswith('logaxis'):\n items = line[8:].split(',')\n if len(items) != 2:\n return \"Two values are required\"\n if isNumber(items[0]) and isNumber(items[1]):\n if int(items[0]) == 0 or int(items[1]) == 0 or \\\n int(items[0]) == 1 or int(items[1]) == 1:\n return \"\"\n return \"Only 0 or 1 are allowed\"\n\n elif line.startswith('arrow'):\n items = line[6:].split(',')\n if len(items) != 5:\n return \"Accept only 5 parameters\"\n else:\n # xpos, ypos, dx, dy, color\n if isNumber(items[0]):\n xpos = float(items[0])\n else:\n return \"X position should be a number\"\n if isNumber(items[1]):\n ypos = float(items[1])\n else:\n return \"Y position should be a number\"\n if isNumber(items[2]):\n dx = float(items[2])\n else:\n return \"dx should be a number\"\n if isNumber(items[3]):\n dy = float(items[3])\n else:\n return \"dy should be a number\"\n if not items[4] in self.colors:\n return \"Unknown color\"\n else:\n return \"\"\n\n elif line.startswith('text'):\n items = line[5:].split(',')\n if len(items) != 5:\n return \"Accept only 5 parameters\"\n else:\n # xpos, ypos, text, color, fontsize\n if isNumber(items[0]):\n xpos = float(items[0])\n else:\n return \"X position should be a number\"\n if isNumber(items[1]):\n ypos = float(items[1])\n else:\n return \"Y position should be a number\"\n if self.axes is not None:\n xmin, xmax, ymin, ymax = self.axes.axis()\n if xpos < xmin or xpos > xmax:\n return \"X position is incorrect\"\n if ypos < ymin or ypos > ymax:\n return \"Y position is incorrect\"\n color = items[3]\n if not color in self.colors:\n return \"Unknown color\"\n if not isNumber(items[4]):\n return \"Font size should be a number\"\n else:\n fntsiz = int(items[4])\n if fntsiz < 2 or fntsiz > 50:\n return \"Font size should be in the range 2-50\"\n else:\n return \"\"\n else:\n return \"Unknown plot command\"\n\n\n\n\n def plotCmdToCurve(self, cmd):\n \"\"\" Create or modify a 'curveinfo' object from the plot command 'cmd'.\n\n This function is the symmetric of curveToPlotCmd.\n\n :param cmd: a string containing the plot command.\n :return: an error message (=\"\" if no error).\n \"\"\"\n errmsg = \"\"\n # remove # for plot command coming from file\n if cmd.startswith('#'):\n cmd = cmd[1:]\n cmd = cmd.strip()\n\n # axes labels\n if cmd.startswith('lab'):\n params = cmd[3:]\n items = params.split(' ')\n if items[0] == 'X':\n self.labx = params[1:].strip()\n elif items[0] == 'Y1':\n self.laby1 = params[2:].strip()\n elif items[0] == 'Y2':\n self.laby2 = params[2:].strip()\n\n elif cmd.startswith('plot'):\n params = cmd[5:]\n items = params.split(',')\n for i in range(2):\n vnam = items[i]\n vinfo = self.getVinfo(vnam.strip())\n if vinfo is not None:\n if i == 0:\n xvinfo = vinfo\n else:\n cinfo = curveInfo(vnam, xvinfo, vinfo)\n cinfo.axis = 1\n if len(items) > 2:\n cinfo.axis = int(items[2])\n if self.blklst[xvinfo.blkpos][xvinfo.vidx].size < 15:\n cinfo.symbol = True\n self.curvelist.append(cinfo)\n else:\n errmsg = \"Unknown vector name {0}\".format(vnam)\n break\n\n elif cmd.startswith('logaxis'):\n params = cmd[8:]\n items = params.split(',')\n self.logX = int(items[0]) != 0\n self.logY = int(items[1]) != 0\n\n elif cmd.startswith('text'):\n if self.checkPlotCmd(cmd) == \"\":\n self.plottext.append(cmd[4:])\n\n elif cmd.startswith('arrow'):\n if self.checkPlotCmd(cmd) == \"\":\n self.arrows.append(cmd[5:])\n\n elif cmd.startswith('symbol'):\n if self.checkPlotCmd(cmd) == \"\":\n items = cmd.split(' ')\n if len(items) == 2:\n curvinfo = self.getCurvinfo(items[1])\n if curvinfo is not None:\n curvinfo.plottyp = 'scat'\n\n elif cmd.startswith('nosymbol'):\n if self.checkPlotCmd(cmd) == \"\":\n items = cmd.split(' ')\n if len(items) == 2:\n curvinfo = self.getCurvinfo(items[1])\n if curvinfo is not None:\n curvinfo.plottyp = 'line'\n\n else:\n errmsg = \"Unknown plot command\"\n if errmsg:\n QtWidgets.QMessageBox.warning(self.parent, \"Plot\", errmsg,\n QtWidgets.QMessageBox.Cancel |\n QtWidgets.QMessageBox.NoButton |\n QtWidgets.QMessageBox.NoButton)\n return errmsg\n\n\n\n\n def curveToPlotCmd(self, curvlist=None):\n \"\"\" Create a plot command list from the list 'curvlist'.\n\n This function is the symmetric of plotCmdToCurve.\n If 'curvlist' is None use self.curvelist.\n\n :param curvlist: a list of curveInfo objets.\n :return: the plot command list or None if there is no curve in list.\n \"\"\"\n if curvlist is None:\n curvlist = self.curvelist\n if len(curvlist) == 0:\n return None\n cmdlist = []\n for curve in curvlist:\n cmd = 'plot ' + curve.xvinfo.name + ',' + curve.yvinfo.name\n if curve.axis != 1 and len(curvlist) > 1:\n cmd += ',' + str(curve.axis)\n cmdlist.append(cmd)\n if curve.plottyp == 'scat':\n cmd = \"symbol {0}\".format(curve.name)\n cmdlist.append(cmd)\n return cmdlist\n\n\n\n def checkPlotOrder(self, plotlist):\n \"\"\" Test if the first plot command is against Y1\n\n :param plotlist: a list of plot command\n :return: an error message (= \"\" if no error)\n \"\"\"\n Y1flg = False\n for cmd in plotlist:\n if cmd.startswith(\"plot\"):\n params = cmd[5:]\n items = params.split(',')\n l = len(items)\n if l == 2 and not Y1flg:\n # it is a plot against Y1\n Y1flg = True\n else:\n if l == 3 and Y1flg == False:\n return \"Plot first against primary Y-axis\"\n return \"\"\n\n\n\n def scriptPlot(self, cmdlist):\n \"\"\" Plot or update the curves from the plot command list 'cmdlist'.\n\n :param cmdlist: a list of plot command.\n :return: nothing\n \"\"\"\n if cmdlist:\n if cmdlist[0].startswith(\"plot\"):\n # if it is a plot command, clear previous curves\n self.curvelist = []\n for cmd in cmdlist:\n self.plotCmdToCurve(cmd)\n self.updatePlot()\n\n\n def displayInfo(self):\n \"\"\" Display info on the current data in the information window.\n\n :return: nothing\n \"\"\"\n if self.blklst is None:\n return \"\"\n else:\n info = self.setDataInfo(self.blklst, self.vectInfolst)\n plotcmdlst = self.curveToPlotCmd()\n if plotcmdlst is not None:\n info += '\\n'.join(plotcmdlst)\n self.info.setText(info)\n\n\n def updatePlot(self):\n \"\"\" Display info on data and plot self.curvelist curves.\n\n :return: nothing.\n \"\"\"\n self.displayInfo()\n if self.curvelist:\n if self.dcursor is not None:\n self.dcursor.updateCurve()\n else:\n blkno = self.curvelist[self.activcurv].xvinfo.blkpos\n xpos = self.curvelist[self.activcurv].xvinfo.vidx\n X = self.blklst[blkno][xpos]\n self.xascending = (X[X.size - 1] > X[0])\n self.plotCurves(self.curvelist)\n\n\n def delBlock(self, blkno):\n \"\"\" Delete the data block having index 'blkno'.\n\n :param blkno: the data block number\n :return: True if done, False otherwise.\n \"\"\"\n # check the parameters\n if blkno < 0 or blkno >= len(self.blklst):\n return False\n\n vinfolst = self.vectInfolst[blkno]\n # update self.curvelist\n for vinfo in vinfolst:\n for curve in self.curvelist:\n if curve.xvinfo == vinfo:\n self.curvelist.remove(curve)\n break\n for curve in self.curvelist:\n if curve.yvinfo == vinfo:\n self.curvelist.remove(curve)\n break\n\n # delete the vectorInfolst in self.vectInfolst\n del self.vectInfolst[blkno]\n\n # update blkno position in vectors belonging to the following blocks\n for vinfolist in self.vectInfolst:\n for vinfo in vinfolist:\n if vinfo.blkpos > blkno:\n vinfo.blkpos -= 1\n\n # delete the data block\n del self.blklst[blkno]\n\n self.dirty = True\n self.updatePlot()\n return True\n\n\n def delVector(self, vnam):\n \"\"\" Delete the vector which name is 'vnam'.\n\n :param vnam: the name of the vector to delete.\n :return: True if done, False otherwise.\n \"\"\"\n # check the parameters\n vectinfo = self.getVinfo(vnam)\n if vectinfo is None:\n return False\n blkno = vectinfo.blkpos\n vpos = vectinfo.vidx\n nvect, nrow = np.shape(self.blklst[blkno])\n\n # delete the vector\n if nvect == 1:\n # It the vector is the only one in the data block\n # delete the data block\n del self.blklst[blkno]\n # update blkno position in vectors belonging to the following blocks\n for vinfolist in self.vectInfolst:\n for vinfo in vinfolist:\n if vinfo.blkpos > blkno:\n vinfo.blkpos -= 1\n else:\n newset = np.vstack((self.blklst[blkno][:vpos], self.blklst[blkno][vpos+1:]))\n self.blklst[blkno] = newset\n\n # update self.vectInfolst\n for vinfo in self.vectInfolst[blkno]:\n if vinfo.vidx == vpos:\n self.vectInfolst[blkno].remove(vinfo)\n break\n if len(self.vectInfolst[blkno]) == 0:\n self.vectInfolst.remove(self.vectInfolst[blkno])\n else:\n for vinfo in self.vectInfolst[blkno]:\n if vinfo.vidx > vpos:\n vinfo.vidx -= 1\n # update self.curvelist\n for curve in self.curvelist:\n if curve.xvinfo == vectinfo:\n self.curvelist.remove(curve)\n break\n for curve in self.curvelist:\n if curve.yvinfo == vectinfo:\n self.curvelist.remove(curve)\n break\n\n self.dirty = True\n self.updatePlot()\n return True\n\n\n def delCurve(self, cpos):\n \"\"\" Delete the curve having the index 'cpos' in self.curvelist\n\n :param cpos: index of the curve in self.curvelist.\n :return: True if done, False otherwise.\n \"\"\"\n if len(self.curvelist) == 0:\n return False\n # check the parameters\n if cpos < 0 or cpos >= len(self.curvelist):\n return False\n xvinfo = self.curvelist[cpos].xvinfo\n yvinfo = self.curvelist[cpos].yvinfo\n blkno = yvinfo.blkpos\n nvect, nrow = np.shape(self.blklst[blkno])\n delx = True # used to check if X will be deleted\n delblk = False\n # If X and Y vectors are the only ones in the block,\n # delete the whole block\n if nvect == 2:\n del self.blklst[blkno]\n delblk = True\n else:\n # Check if the vector X is used by another curve\n for curve in self.curvelist:\n if curve.xvinfo == xvinfo:\n delx = False\n break\n # If not find, delete the vector X\n if delx:\n newset = np.vstack((self.blklst[blkno][:xvinfo.vidx],\n self.blklst[blkno][xvinfo.vidx + 1:]))\n self.blklst[blkno] = newset\n # delete the vector Y\n newset = np.vstack((self.blklst[blkno][:yvinfo.vidx],\n self.blklst[blkno][yvinfo.vidx + 1:]))\n self.blklst[blkno] = newset\n\n # update vector index in self.vectInfolst\n infolst = self.vectInfolst[blkno]\n if delx:\n for vinfo in infolst:\n if vinfo.vidx == xvinfo.vidx:\n infolst.remove(vinfo)\n break\n for vinfo in infolst:\n if vinfo.vidx != yvinfo.vidx and vinfo.vidx > xvinfo.vidx:\n vinfo.vidx -= 1\n for vinfo in infolst:\n if vinfo.vidx == yvinfo.vidx:\n infolst.remove(vinfo)\n break\n for vinfo in infolst:\n if vinfo.vidx > yvinfo.vidx:\n vinfo.vidx -= 1\n\n # update blkno position if a whole block was deleted\n if delblk:\n delidx = None\n for i, vinfolist in enumerate(self.vectInfolst):\n if not vinfolist:\n delidx = i\n else:\n for vinfo in vinfolist:\n if vinfo.blkpos > blkno:\n vinfo.blkpos -= 1\n if delidx is not None:\n del self.vectInfolst[delidx]\n\n # update self.curvelist\n if delx:\n for curve in self.curvelist:\n if curve.xvinfo == xvinfo:\n self.curvelist.remove(curve)\n break\n for curve in self.curvelist:\n if curve.yvinfo == yvinfo:\n self.curvelist.remove(curve)\n break\n self.dirty = True\n self.updatePlot()\n if self.tabledlg is not None:\n self.tabledlg.table.initTable()\n return True\n\n\n def pasteVector(self, vect, blkno, vname):\n \"\"\" Paste the vector 'vect' at the end of the block 'blkno'\n\n :param vect: a 1D ndarray containing the vector elements.\n :param blkno: the data block number where the new vector will be added.\n :param vname: the vector name.\n :return: True if done, False otherwise.\n \"\"\"\n (nvect, npt) = np.shape(self.blklst[blkno])\n if vect.size != npt:\n QtWidgets.QMessageBox.warning(self.parent, \"Paste a vector\",\n \"Incompatible size of the vector in memory\",\n QtWidgets.QMessageBox.Cancel |\n QtWidgets.QMessageBox.NoButton |\n QtWidgets.QMessageBox.NoButton)\n return False\n newset = np.vstack((self.blklst[blkno], vect))\n self.blklst[blkno] = newset\n vinfo = self.getVinfo(vname)\n if vinfo is not None:\n # If the name already exists, prepends the name with #\n vname += '#'\n # update self.vectInfolst\n infolst = self.vectInfolst[blkno]\n # Create a new vectInfo object and append it to the list.\n vinfo = vectInfo(blkno, nvect, vname)\n infolst.append(vinfo)\n self.dirty = True\n return True\n\n\n def duplicateCurve(self, cidx):\n \"\"\" Duplicate the curve having the index 'cidx' in self.curvelist\n\n :param cidx: the index of the curve in self.curvelist.\n :return: True if done, False otherwise.\n \"\"\"\n if len(self.curvelist) == 0:\n return False\n # check the parameters\n if cidx < 0 or cidx >= len(self.curvelist):\n return False\n cname = self.curvelist[cidx].name + '#'\n xvinfo = self.curvelist[cidx].xvinfo\n yvinfo = self.curvelist[cidx].yvinfo\n blkno = yvinfo.blkpos\n if self.pasteVector(self.blklst[blkno][yvinfo.vidx], blkno, cname):\n yvinfo = self.getVinfo(cname)\n self.curvelist.append(curveInfo(cname, xvinfo, yvinfo))\n self.plotCurves()\n self.displayInfo()\n if self.tabledlg is not None:\n self.tabledlg.table.initTable()\n self.parent.updateUI()\n return True\n return False\n\n\n def pasteCurve(self, vectX, xnam, vectY, ynam):\n \"\"\" Add a curve in the current plotWindow\n\n If vectX already existing in the block add only vectY\n at the end of the block 'blkno' otherwise create a new\n data block.\n\n :param vectX: a 1D ndarray containing the X vector elements.\n :param xnam: the name of X vector.\n :param vectY: a 1D ndarray containing the Y vector elements.\n :param ynam: the name of the Y vector.\n :return: True if done, False otherwise.\n \"\"\"\n title = \"Paste a curve\"\n blkno = None\n xidx = 0\n done = False\n if self.blklst is None:\n self.blklst = []\n else:\n # If the Y vector name is already existing add the suffix '#'\n while True:\n vinfo = self.getVinfo(ynam)\n if vinfo is not None:\n ynam += '#'\n else:\n break\n # check if the 'vectX' is already existing in a data block\n for n, nparray in enumerate(self.blklst):\n if blkno is not None:\n break\n nvect, npt = np.shape(self.blklst[0])\n for i in range(nvect):\n if nparray[i].size == vectX.size:\n if np.allclose(vectX, nparray[i]):\n blkno = n\n xidx = i\n break\n if blkno is not None:\n # vectX already existing, ask user to add vectY\n # at the end of self.blklst[blkno]\n msg = \"Add this data as a new vector in current data block ?\"\n reply = QtWidgets.QMessageBox.question(self, title,\n msg, QtWidgets.QMessageBox.Yes |\n QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)\n if reply == QtWidgets.QMessageBox.Yes:\n newset = np.vstack((self.blklst[blkno], vectY))\n self.blklst[blkno] = newset\n # update self.vectInfolst and self.curvelist\n xnam = self.getVnam(blkno, xidx)\n if xnam is not None:\n vx = vectInfo(blkno, xidx, xnam)\n vy = vectInfo(blkno, nvect, ynam)\n self.vectInfolst[blkno].append(vy)\n self.curvelist.append(curveInfo(ynam, vx, vy))\n done = True\n if not done:\n # Create a new data block to store vectX and vectY.\n newset = np.vstack((vectX, vectY))\n self.blklst.append(newset)\n blkno = len(self.blklst)-1\n # If the X vector name is already existing add the suffix '#'\n while True:\n vinfo = self.getVinfo(xnam)\n if vinfo is not None:\n xnam += '#'\n else:\n break\n # update self.vectInfolst and self.curvelist\n vinfolst = []\n vx = vectInfo(blkno, 0, xnam)\n vy = vectInfo(blkno, 1, ynam)\n vinfolst.append(vx)\n vinfolst.append(vy)\n self.vectInfolst.append(vinfolst)\n self.curvelist.append(curveInfo(ynam, vx, vy))\n done = True\n if done:\n self.dirty = True\n self.plotCurves()\n if self.tabledlg is not None:\n self.tabledlg.table.initTable()\n self.displayInfo()\n return done\n\n\n def saveCurveInFile(self, cpos, filename):\n \"\"\" Save a curve (X,Y vector pair) in a file\n\n :param cpos: the index of the curve in self.curvelist\n :param filename: name of the file in which curve data will be saved.\n :return: True if success, False otherwise.\n \"\"\"\n if filename:\n if self.blklst is not None:\n xvinfo = self.curvelist[cpos].xvinfo\n yvinfo = self.curvelist[cpos].yvinfo\n blkno = yvinfo.blkpos\n # build a new array by stacking X and Y vectors\n newdata = np.vstack((self.blklst[blkno][xvinfo.vidx],\n self.blklst[blkno][yvinfo.vidx]))\n # save the data in the file\n vnames = xvinfo.name + ' ' + yvinfo.name\n np.savetxt(filename, np.transpose(newdata), header=vnames)\n return True\n return False\n","sub_path":"plotWindow.py","file_name":"plotWindow.py","file_ext":"py","file_size_in_byte":69039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"416226734","text":"###############################################################################\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"). #\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# or in the \"license\" file accompanying this file. This file is distributed #\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express #\n# or implied. See the License for the specific language governing permissions#\n# and limitations under the License. #\n###############################################################################\n\nfrom os import environ\n\nimport pytest\nfrom cfct.manifest.stage_to_s3 import StageFile\nfrom cfct.utils.logger import Logger\n\nlogger = Logger(\"info\")\n\n\n@pytest.mark.unit\ndef test_convert_url():\n bucket_name = \"my-bucket-name\"\n key_name = \"my-key-name\"\n relative_path = \"s3://\" + bucket_name + \"/\" + key_name\n sf = StageFile(logger, relative_path)\n s3_url = sf.get_staged_file()\n logger.info(s3_url)\n assert s3_url.startswith(\n \"{}{}{}{}{}{}\".format(\n \"https://\",\n bucket_name,\n \".s3.\",\n environ.get(\"AWS_REGION\"),\n \".amazonaws.com/\",\n key_name,\n )\n )\n","sub_path":"source/tests/test_stage_to_s3.py","file_name":"test_stage_to_s3.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"450344832","text":"import pytest\nfrom binary_tree import BinaryTreeNode\nfrom bst.property import check_bst_property\n\n\ndef test_check_bst_property():\n # 19\n # / \\\n # 4 20\n # / \\\n # 1 9\n root_prop_true = BinaryTreeNode(\n left=BinaryTreeNode(\n left=BinaryTreeNode(data=1),\n right=BinaryTreeNode(data=9),\n data=4\n ),\n right=BinaryTreeNode(data=20),\n data=19,\n )\n\n result_prop_true = check_bst_property(root_prop_true)\n expected_result_prop_true = True\n if result_prop_true != expected_result_prop_true:\n pytest.fail(f'check_bst_property() [True] returned {result_prop_true}, while expected {expected_result_prop_true}')\n\n # 19\n # / \\\n # 4 20\n # / \\\n # 1 0\n root_prop_false = BinaryTreeNode(\n left=BinaryTreeNode(\n left=BinaryTreeNode(data=1),\n right=BinaryTreeNode(data=0),\n data=4\n ),\n right=BinaryTreeNode(data=20),\n data=19,\n )\n\n result_prop_false = check_bst_property(root_prop_false)\n expected_result_prop_false = False\n if result_prop_false != expected_result_prop_false:\n pytest.fail(f'check_bst_property() [False] returned {result_prop_false}, while expected {expected_result_prop_false}')\n","sub_path":"source/bst/property_test.py","file_name":"property_test.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"122351821","text":"import csv\nimport urllib.request\nimport urllib\nimport ssl\nfrom data.get_new_file import get_last\n\n\nclass Info:\n\n def __init__(self, filename):\n self.filename = filename\n if filename.endswith('txt'):\n self.data = self.txt_read(filename)\n if filename.endswith('csv'):\n self.data = self.csv_read(filename)\n\n def txt_read(self, filename):\n \"\"\"\n (str, list) -> list\n Function read data from txt file\n \"\"\"\n # limiter\n k = 0\n DATA = []\n context = ssl._create_unverified_context()\n with urllib.request.urlopen(filename, context=context) as webpage:\n webpage.readline()\n for b in webpage:\n line = b.strip()\n line = line.decode(\"utf-8\")\n DATA.append(line)\n k += 1\n if k == 2000:\n break\n\n return DATA\n\n\n def csv_read(self, filename):\n \"\"\"\n (str) -> list\n\n Function reads from csv file and returns a list\n \"\"\"\n DATA = []\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n newrow = []\n for el in row:\n newrow.append(el.lower())\n DATA.append(newrow[3:6] + newrow[-2:])\n\n return DATA\n\n\n def __add__(self, other):\n txt_data = self.data if self.filename.endswith('txt') else other.data\n csv_data = self.data if self.filename.endswith('csv') else other.data\n DATA = []\n numbers = [str(i) for i in range(10)]\n for line in txt_data:\n # line = b.strip()\n line = line.lower().split(\",\")\n # print(line)\n for s in csv_data:\n if s[0] in line:\n if s[2] in line:\n line.append(str(s[-2]))\n line.append(str(s[-1]))\n break\n # print(\"ADDED COORDS\")\n else:\n if [i for i in line[3] if i in numbers] \\\n == [i for i in s[2] if i in numbers] \\\n and abs(len(line[3]) - len(s[2])) <= 4:\n\n line.append(str(s[-2]))\n line.append(str(s[-1]))\n break\n else:\n pass\n line = \",\".join(line)\n # print(line)\n DATA.append(line)\n\n return DATA\n\n\nif __name__ == \"__main__\":\n txt_data = Info(\"http://web.mta.info/developers/\" + get_last()[0])\n csv_data = Info(\"Stations.csv\")\n # print(txt_data)\n # print(csv_data)\n data = txt_data + csv_data\n\n # print(data)\n f = open('data_new.txt', 'w')\n for i in data:\n # print(i)\n f.write(i)\n f.write(\"\\n\")\n","sub_path":"info_ADT.py","file_name":"info_ADT.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"87824557","text":"import re\n\ndef course_normalization(\n input_string: str\n):\n \"\"\"\n Function that normalizes student entered course information\n Args:\n :param input_string = string composed of department, course number, semester, and year\n :return: dictionary with the properties and values for department, course number, semester and year parsed from input string\n\n Example:\n >>> course_normalization(\"CS111 2016 Fall\")\n \"\"\"\n\n # parse input string into constituent properties\n regex_pattern = re.compile(\"([a-zA-Z]+)[\\s\\-:]?(\\d+)\\s(\\d{2}(?:\\d{2})?)[\\s]?([a-zA-Z]+)\")\n groups = regex_pattern.search(input_string)\n if groups:\n department = groups.group(1)\n course_number = groups.group(2)\n year = groups.group(3)\n semester = groups.group(4)\n else:\n regex_pattern = re.compile(\"([a-zA-Z]+)[\\s\\-:]?(\\d+)\\s([a-zA-Z]+)[\\s]?(\\d{2}(?:\\d{2})?)\")\n groups = regex_pattern.search(input_string)\n if groups:\n department = groups.group(1)\n course_number = groups.group(2)\n semester = groups.group(3)\n year = groups.group(4)\n else:\n raise ValueError(\"input_string invalid and does not contain requisite properties - department, course number, \"\n \"semester, and year\")\n\n # validate year\n if len(year) not in [2,4]:\n raise ValueError(\"input string must contain year that is either 2 or 4 digits\")\n # validate semester\n if not semester.lower() in (\"f\", \"w\", \"s\", \"su\", \"fall\", \"spring\", \"winter\", \"summer\"):\n raise ValueError(\"input string does not contain valid semester\")\n\n # standardize semester\n semester_map = {\"f\": \"Fall\", \"w\": \"Winter\", \"s\": \"Spring\", \"su\": \"Summer\"}\n if len(semester) <= 2:\n semester = semester_map[semester.lower()]\n else:\n semester = semester.title()\n # standardize year\n if len(year) == 2:\n year = \"20%s\" % year\n\n return {\n \"department\": department.upper(),\n \"course_number\": int(course_number),\n \"semester\": semester,\n \"year\": int(year)\n }\n\n\n","sub_path":"course_selection/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230080420","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/17 23:58\n# @Author : weiyu\n# @File : 242_valid_anagram.py\n\n\n# 字典\nclass Solution:\n def isAnagram(self, s, t):\n dict1, dict2 = {}, {}\n for item in s:\n dict1[item] = dict1.get(item, 0) + 1\n for item in t:\n dict2[item] = dict2.get(item, 0) + 1\n return dict1 == dict2\n\n# # 暴力sort\n# class Solution:\n# def isAnagram(self, s, t):\n# return sorted(s) == sorted(t)\n\nt = Solution()\nprint(t.isAnagram(s = \"anagram\", t = \"nagaram\"))\nprint(t.isAnagram(s = \"anagram\", t = \"nasaram\"))\n\n","sub_path":"Week_06/242_valid_anagram.py","file_name":"242_valid_anagram.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"352146250","text":"__author__ = 'sinisa'\n\nimport io\nfrom sbg_cli import __version__ as version\nfrom setuptools import setup, find_packages\n\n\nrequires = [\n x.strip() for x in\n io.open('requirements.txt')\n]\n\nsetup(\n name=\"sbg-cli\",\n version=version,\n packages=find_packages(),\n entry_points={\n 'console_scripts': ['sbg = sbg_cli.main:main']\n },\n install_requires=requires,\n package_data={'': ['*.expr-plugin']},\n long_description=io.open('README.md').read(),\n license='AGPLv3'\n)","sub_path":"pypi_install_script/sbg-cli-0.1.8.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"144600125","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework_jwt.views import ObtainJSONWebToken\nfrom rest_framework import mixins\nfrom django.http import Http404\nfrom rest_framework import status, authentication, viewsets, generics\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\nfrom apps.users.serializer.serializers_back import *\nfrom django.db import transaction\nfrom rest_framework.decorators import action\nfrom rest_framework_jwt.views import jwt_response_payload_handler\n\n\nclass UserViewSet(ObtainJSONWebToken):\n \"\"\"用户模块接口\"\"\"\n\n # authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)\n# 后台用户登录\n\n def post(self, request, *args, **kwargs):\n \"\"\"后台用户登录\"\"\"\n serializer = self.get_serializer(data=request.data)\n print(request.data)\n # self.get_object()\n if serializer.is_valid():\n\n user = serializer.object.get('user') or request.user\n print(user)\n token = serializer.object.get('token')\n print(token)\n # 返回前台登陆数据\n response_data = jwt_response_payload_handler(token, user, request)\n response_data['user'] = UserSerializer(user).data\n\n # 获取用户菜单\n if user.is_superuser:\n menus = Menu.objects.all()\n menus_serializer = MenuCreateSerializer(menus, many=True)\n response_data['menus'] = menus_serializer.data\n else:\n groups = Group.objects.filter(user=user)\n menus = set()\n for group in groups:\n role_menus = RoleMenu.objects.filter(role=group)\n for role_menu in role_menus:\n menus.add(role_menu.menu)\n if menus:\n menus_serializer = MenuCreateSerializer(menus, many=True)\n response_data['menus'] = menus_serializer.data\n else:\n response_data['menus'] = []\n response = Response(response_data)\n return response\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# 用户组(角色)\nclass GroupViewSet(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n 角色详情\n list:\n 后台角色列表\n create:\n 新增角色\n delete:\n 删除角色\n update:\n 更新角色\n \"\"\"\n queryset = Group.objects.all()\n serializer_class = GroupListSerializer\n authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)\n\n def update(self, request, *args, **kwargs):\n \"\"\"修改角色菜单\"\"\"\n try:\n with transaction.atomic():\n group = Group.objects.get(id=request.data['group']['id'])\n group.name = request.data['group']['name']\n group.save()\n\n # 新的集合数组\n new_menus = request.data['menus']\n\n role_menus = RoleMenu.objects.filter(role=group)\n old_menus = [role_menu.menu.id for role_menu in role_menus]\n # 获取差集\n # list(set(b).difference(set(a))) # b中有而a中没有的 删除\n remove_menus = list(set(old_menus).difference(set(new_menus)))\n for menu_id in remove_menus:\n menu = Menu.objects.get(id=menu_id)\n role_menu = RoleMenu.objects.get(menu=menu, role=group)\n role_menu.delete()\n\n # list(set(a).difference(set(b))) # a中有而b中没有的 新增\n add_menus = list(set(new_menus).difference(set(old_menus)))\n role_menus = []\n for menu_id in add_menus:\n menu = Menu.objects.get(id=menu_id)\n role_menus.append(RoleMenu(role=group, menu=menu))\n RoleMenu.objects.bulk_create(role_menus)\n return Response({'message': 'ok'}, status=status.HTTP_200_OK)\n except Group.DoesNotExist:\n return Response({'message': '不存在的对象'}, status=status.HTTP_400_BAD_REQUEST)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"\n 获取角色详情\n \"\"\"\n # get 方式传参数\n group_id = kwargs.get(\"pk\", None)\n # data = {\"message\": \"ok\"}\n data = {}\n try:\n group = Group.objects.get(pk=group_id)\n group_serializer = GroupListSerializer(group)\n role_menus = RoleMenu.objects.filter(role=group)\n menus = [role_menu.menu for role_menu in role_menus]\n menu_serializer = MenuCreateSerializer(menus, many=True)\n data['group'] = group_serializer.data\n data['menus'] = menu_serializer.data\n # return Response(data, status=status.HTTP_200_OK)\n except Group.DoesNotExist:\n return Response({'pk': group_id, \"error\": \"不存在的对象\"}, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(data, status=status.HTTP_200_OK)\n\n def create(self, request, *args, **kwargs):\n \"\"\"新增角色\"\"\"\n try:\n with transaction.atomic():\n role = Group(name=request.data[\"group\"]['name'])\n role.save()\n menus = request.data['menus']\n # 新增用户对应的菜单\n for menu_id in menus:\n menu = Menu.objects.get(id=menu_id)\n role = Group.objects.get(name=role.name)\n role_menu = RoleMenu(menu=menu, role=role)\n role_menu.save()\n return Response({'message': 'ok'}, status=status.HTTP_200_OK)\n except Exception as e:\n print(e)\n return Response({'message': 'error'}, status=status.HTTP_400_BAD_REQUEST)\n\n def get_serializer_class(self):\n \"\"\"\n # 动态选择序列化方式\n # 1. UserRegSerializer (用户注册), 只返回username 和 mobile\n # 2. UserSerializer (用户中心) 返回用户详细数据\n :return:\n \"\"\"\n if self.action == 'list':\n return GroupListSerializer\n elif self.action in ['create', 'update', 'retrieve', 'partial_update']:\n return GroupCreateSerializer\n return GroupSerializer\n\n # def get_permissions(self):\n # return [permissions.IsAuthenticated() or permissions.IsAdminUser()]\n\n # def get_permissions(self):\n # return [permissions.IsAuthenticated() or permissions.IsAdminUser()]\n\n\n# 权限\nclass PermissionViewSet(generics.ListCreateAPIView, viewsets.GenericViewSet):\n \"\"\"\n list:\n 权限列表\n create:\n 权限新增\n \"\"\"\n\n queryset = Permission.objects.all()\n serializer_class = PermissionListSerializer\n\n # def create(self, request, *args, **kwargs):\n # # print(request.data)\n # serializer = self.get_serializer(data=request.data)\n # if serializer.is_valid():\n # serializer.save()\n # return Response({'message': \"ok\"}, status=status.HTTP_200_OK)\n # else:\n # return Response({'message': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n def get_queryset(self):\n queryset = Permission.objects.filter(content_type_id='57')\n return queryset\n\n def get_serializer_class(self):\n if self.action == 'list':\n return PermissionListSerializer\n else:\n return PermissionCreateSerializer\n\n # def get_permissions(self):\n # return [permissions.IsAuthenticated() or permissions.IsAdminUser()]\n\n\n# 菜单\nclass MenuViewSet(generics.ListCreateAPIView, viewsets.GenericViewSet):\n \"\"\"\n list:\n 菜单列表(嵌套子类)\n menu_list:\n 菜单列表(无嵌套子类)\n create:\n 菜单新增\n \"\"\"\n queryset = Menu.objects.all()\n serializer_class = MenuListSerializer\n\n # def list(self, request, *args, **kwargs):\n # print(request)\n @action(['get'], detail=False)\n def menu_list(self, request):\n menus = Menu.objects.all()\n serializer = MenuCreateSerializer(menus, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n # def list(self, request, *args, **kwargs):\n # menus = Menu.objects.filter(parent=None)\n # serializer = self.get_serializer(menus, many=True)\n # return Response(serializer.data, status=status.HTTP_200_OK)\n\n def get_serializer_class(self):\n if self.action == 'list':\n return MenuListSerializer\n else:\n return MenuCreateSerializer\n\n def get_queryset(self):\n return Menu.objects.filter(parent=None)\n\n\nclass IndexViewSet(APIView):\n # permission_classes = [IsAuthenticated]\n\n def get(self, request, *args, **kwargs):\n \"\"\"首页接口\"\"\"\n try:\n user = User.objects.get(username=request.user.username)\n except User.DoesNotExist:\n return Response({\"error\": \"不存在的对象\"}, status=status.HTTP_400_BAD_REQUEST)\n response = Response(UserSerializer(user).data, status=status.HTTP_200_OK)\n return response\n\n\n# 后端(后台用户接口)\nclass UserBackView(viewsets.ModelViewSet):\n \"\"\"\n 后台用户模块接口\n\n retrieve:\n 后台用户详情\n list:\n 后台用户列表\n create:\n 后台用户新增\n delete:\n 后台用户删除\n update:\n 后台用户更新\n \"\"\"\n serializer_class = UserRegSerializer\n queryset = User.objects.filter(is_staff=True, is_active=True)\n authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)\n\n def get_serializer_class(self):\n if self.action in ['create']:\n return UserRegBackSerializer\n elif self.action in [\"update\", 'partial_update']:\n return UserUpdateBackSerializer\n elif self.action == \"list\":\n return UserListBackSerializer\n return UserSerializer\n\n def perform_update(self, serializer):\n instance = self.get_object()\n return serializer.update_user(instance)\n\n def perform_create(self, serializer):\n instance = serializer.save()\n instance.is_staff = True\n instance.save()\n\n def perform_destroy(self, instance):\n instance.is_active = False\n instance.save()\n\n def get_object(self):\n try:\n return User.objects.get(id=self.kwargs[self.lookup_field], is_active=True, is_staff=True)\n except User.DoesNotExist:\n raise Http404('不存在的对象.')\n\n\nclass UserMemberView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):\n \"\"\"\n retrieve:\n 后台会员用户详情\n list:\n 后台会员用户列表\n create:\n 后台会员用户新增\n delete:\n 后台会员用户删除\n update:\n 后台会员用户更新\n \"\"\"\n serializer_class = UserMemberListSerializer\n queryset = User.objects.all()\n authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)\n # filter_backends = (filters.SearchFilter, filters.OrderingFilter)\n search_fields = ('username', 'company_name')\n ordering_fields = ('date_joined',)\n # pagination_class = UserPagination\n\n def get_serializer_class(self):\n if self.action == 'retrieve':\n return UserBackDetailSerializer\n return UserMemberListSerializer\n\n def perform_destroy(self, instance):\n instance.is_active = False\n instance.save()\n\n def get_object(self):\n try:\n return User.objects.get(id=self.kwargs[self.lookup_field], is_active=True, is_staff=False)\n except User.DoesNotExist:\n raise Http404('不存在的对象.')\n","sub_path":"apps/users/views/views_back.py","file_name":"views_back.py","file_ext":"py","file_size_in_byte":12131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"313463473","text":"#!/usr/bin/python -d\n\n#Copyright (c) 2013 Stewart Fletcher\n#\n#Permission is hereby granted, free of charge, to any person obtaining a copy of\n#this software and associated documentation files (the \"Software\"), to deal in\n#the Software without restriction, including without limitation the rights to\n#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n#the Software, and to permit persons to whom the Software is furnished to do so,\n#subject to the following conditions:\n#\n#The above copyright notice and this permission notice shall be included in all\n#copies or substantial portions of the Software.\n#\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n__description__ = '''\npython SU stdin/stdout interface module\n\n data = readSU()\n writeSU(data)\n\nuses custom dtypes for a very fast read/write to stdin/stdout\nreturns a single np.ndarray with dtype=sufile\na numpy 2d array of traces can be addressed as data['traces']\neach header term can also be addressed via data['insertheaderterm']\n'''\n\nimport numpy as np, sys, os, os.path\nimport tables as tb\nsu_header_dtype = np.dtype([\n('tracl', np.int32),\n('tracr', np.int32),\n('fldr', np.int32),\n('tracf', np.int32),\n('ep', np.int32),\n('cdp', np.int32),\n('cdpt', np.int32),\n('trid', np.int16),\n('nvs', np.int16),\n('nhs', np.int16),\n('duse', np.int16),\n('offset', np.int32),\n('gelev', np.int32),\n('selev', np.int32),\n('sdepth', np.int32),\n('gdel', np.int32),\n('sdel', np.int32),\n('swdep', np.int32),\n('gwdep', np.int32),\n('scalel', np.int16),\n('scalco', np.int16),\n('sx', np.int32),\n('sy', np.int32),\n('gx', np.int32),\n('gy', np.int32),\n('counit', np.int16),\n('wevel', np.int16),\n('swevel', np.int16),\n('sut', np.int16),\n('gut', np.int16),\n('sstat', np.int16),\n('gstat', np.int16),\n('tstat', np.int16),\n('laga', np.int16),\n('lagb', np.int16),\n('delrt', np.int16),\n('muts', np.int16),\n('mute', np.int16),\n('ns', np.uint16),\n('dt', np.uint16),\n('gain', np.int16),\n('igc', np.int16),\n('igi', np.int16),\n('corr', np.int16),\n('sfs', np.int16),\n('sfe', np.int16),\n('slen', np.int16),\n('styp', np.int16),\n('stas', np.int16),\n('stae', np.int16),\n('tatyp', np.int16),\n('afilf', np.int16),\n('afils', np.int16),\n('nofilf', np.int16),\n('nofils', np.int16),\n('lcf', np.int16),\n('hcf', np.int16),\n('lcs', np.int16),\n('hcs', np.int16),\n('year', np.int16),\n('day', np.int16),\n('hour', np.int16),\n('minute', np.int16),\n('sec', np.int16),\n('timebas', np.int16),\n('trwf', np.int16),\n('grnors', np.int16),\n('grnofr', np.int16),\n('grnlof', np.int16),\n('gaps', np.int16),\n('otrav', np.int16), #179,180\n('d1', np.float32), #181,184\n('f1', np.float32), #185,188\n('d2', np.float32), #189,192\n('f2', np.float32), #193, 196\n('ShotPoint', np.int32), #197,200\n('unscale', np.int16), #201, 204\n('TraceValueMeasurementUnit', np.int16),\n('TransductionConstantMantissa', np.int32),\n('TransductionConstantPower', np.int16),\n('TransductionUnit', np.int16),\n('TraceIdentifier', np.int16),\n('ScalarTraceHeader', np.int16),\n('SourceType', np.int16),\n('SourceEnergyDirectionMantissa', np.int32),\n('SourceEnergyDirectionExponent', np.int16),\n('SourceMeasurementMantissa', np.int32),\n('SourceMeasurementExponent', np.int16),\n('SourceMeasurementUnit', np.int16),\n('UnassignedInt1', np.int32),\n('ns1', np.int32),\n])\n\n\nclass su:\n def __init__(self, database, **kwargs):\n #~ if not set(kwargs.keys()).issubset(keylist):\n #~ raise Exception(\"Invalid key in segy kwargs\")\n #~ if not filename:\n #~ self.initialiseFramework()\n #~ else:\n #~ self.loadFramework()\n self.db = tb.openFile(database, mode = \"w\", title='test')\n\n def read(self, filelist):\n \n def read_ns(filename):\n return np.fromfile(filename, dtype=su_header_dtype, count=1)['ns']\n\n node = self.db.createGroup(\"/\", 'jobname', 'PySeis Node')\n\n for index, file_ in enumerate(filelist):\n ns = read_ns(file_)\n sutype = np.dtype(su_header_dtype.descr + [('data', ('f4',ns))])\n th = self.db.createTable(node, \"gather\"+str(index), sutype, \"Gather\")\n #will need to add chunking at some point.\n with open(file_, 'rb') as f:\n data = np.fromfile(f, dtype=sutype)\n th.append(data)\n\n\nif __name__ == '__main__':\n os.chdir('../../data/')\n path = '/misc/coalStor/University_QLD/crystal_mountain/2014/data/'\n filelist = [path+a for a in os.listdir(path) if '.su' in a]\n a = su('su_test.h5')\n a.read(filelist)\n\n\n","sub_path":"notebooks/toolbox/su.py","file_name":"su.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"136054265","text":"\"\"\"\nPiCloud realtime management.\nThis module allows the user to manage their realtime cores programmatically.\nSee http://docs.picloud.com/tech_overview.html#scheduling\n\"\"\"\nfrom __future__ import absolute_import\n\"\"\"\nCopyright (c) 2011 `PiCloud, Inc. `_. All rights reserved.\n\nemail: contact@picloud.com\n\nThe cloud package is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis package is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this package; if not, see \nhttp://www.gnu.org/licenses/lgpl-2.1.html \n\"\"\"\n\n\nimport cloud\nimport types\nfrom cloud.util import fix_time_element\n\nimport logging, datetime\n\n\n_request_query = 'realtime/request/'\n_release_query = 'realtime/release/'\n_list_query = 'realtime/list/'\n_change_max_duration_query = 'realtime/change_max_duration/'\n\n\n\"\"\"\nReal time requests management\n\"\"\"\ndef list(request_id=\"\"):\n \"\"\"Returns a list of dictionaries describing realtime core requests.\n If *request_id* is specified, only show realtime core request with that request_id\n \n The keys within each returned dictionary are:\n \n * request_id: numeric ID associated with the request \n * type: Type of computation resource this request grants\n * cores: Number of (type) cores this request grants\n * start_time: Time when real time request was satisfied; None if still pending\"\"\"\n \n if request_id != \"\":\n try:\n int(request_id)\n except ValueError:\n raise TypeError('Optional parameter to list_rt_cores must be a numeric request_id')\n \n conn = cloud._getcloudnetconnection()\n rt_list = conn.send_request(_list_query, {'rid': str(request_id)})\n return [fix_time_element(rt,'start_time') for rt in rt_list['requests']]\n\ndef request(type, cores, max_duration=None):\n \"\"\"Request a number of *cores* of a certain compute resource *type* \n Returns a dictionary describing the newly created realtime request, with the same format\n as the requests returned by list_rt_cores.\n If specified, request will terminate after being active for *max_duration* hours\n \"\"\"\n \n if max_duration != None:\n if not isinstance(max_duration, (int, long)):\n raise TypeError('Optional parameter max_duration should be an integer value > 0')\n if max_duration <= 0:\n raise TypeError('Optional parameter max_duration should be an integer value > 0')\n \n conn = cloud._getcloudnetconnection()\n return fix_time_element(conn.send_request(_request_query, \n {'cores': cores,\n 'type' : type,\n 'cap_duration': max_duration if max_duration else 0}), \n 'start_time')\n\ndef release(request_id):\n \"\"\"Release the realtime core request associated with *request_id*. \n Request must have been satisfied to terminate.\"\"\"\n \n try:\n int(request_id)\n except ValueError:\n raise TypeError('release_rt_cores requires a numeric request_id')\n \n conn = cloud._getcloudnetconnection()\n conn.send_request(_release_query, {'rid': str(request_id)})\n\ndef change_max_duration(request_id, new_max_duration=None):\n\n try:\n int(request_id)\n except ValueError:\n raise TypeError('release_rt_cores requires a numeric request_id')\n \n if new_max_duration != None:\n if not isinstance(new_max_duration, (int, long)):\n raise TypeError('Optional parameter max_duration should be an integer value > 0')\n if new_max_duration <= 0:\n raise TypeError('Optional parameter max_duration should be an integer value > 0')\n \n conn = cloud._getcloudnetconnection()\n \n conn.send_request(_change_max_duration_query, {'rid': str(request_id), 'cap_duration':new_max_duration})\n\n","sub_path":"src/realtime.py","file_name":"realtime.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"638164718","text":"import numpy as np\n\nfrom .widedeep import WideDeepRegDecoder, get_decay_power\nfrom .._base_._base_regressor import RegressorModule\nfrom ..bert.bert import BERTEncoder, BERTConfig\nfrom ...token import WordPieceTokenizer\nfrom ...third import tf\nfrom ... import com\n\n\nclass WideDeepRegressor(RegressorModule):\n \"\"\" Regressor on Wide & Deep structure with BERT. \"\"\"\n\n _INFER_ATTRIBUTES = { # params whose value cannot be None in order to infer without training\n \"max_seq_length\": \"An integer that defines max sequence length of input tokens\",\n \"label_size\": \"An integer that defines number of possible labels of outputs\",\n \"init_checkpoint\": \"A string that directs to the checkpoint file used for initialization\",\n \"wide_features\": \"Names of `Wide` features\",\n }\n\n def __init__(\n self,\n config_file,\n vocab_file,\n max_seq_length=128,\n label_size=None,\n init_checkpoint=None,\n output_dir=None,\n gpu_ids=None,\n wide_features=None,\n do_lower_case=True,\n truncate_method=\"LIFO\",\n ):\n self.__init_args__ = locals()\n super(RegressorModule, self).__init__(init_checkpoint, output_dir, gpu_ids)\n\n self.max_seq_length = max_seq_length\n self.label_size = label_size\n self.truncate_method = truncate_method\n self.wide_features = wide_features\n\n self.bert_config = BERTConfig.from_json_file(config_file)\n self.tokenizer = WordPieceTokenizer(vocab_file, do_lower_case)\n self.decay_power = get_decay_power(self.bert_config.num_hidden_layers)\n\n if \"[CLS]\" not in self.tokenizer.vocab:\n self.tokenizer.add(\"[CLS]\")\n self.bert_config.vocab_size += 1\n tf.logging.info(\"Add necessary token `[CLS]` into vocabulary.\")\n if \"[SEP]\" not in self.tokenizer.vocab:\n self.tokenizer.add(\"[SEP]\")\n self.bert_config.vocab_size += 1\n tf.logging.info(\"Add necessary token `[SEP]` into vocabulary.\")\n\n def convert(self, X=None, y=None, sample_weight=None, X_tokenized=None, is_training=False, is_parallel=False):\n self._assert_legal(X, y, sample_weight, X_tokenized)\n\n if is_training:\n assert y is not None, \"`y` can't be None.\"\n if is_parallel:\n assert self.label_size, \"Can't parse data on multi-processing when `label_size` is None.\"\n\n n_inputs = None\n data = {}\n\n # convert X\n if X is not None or X_tokenized is not None:\n tokenized = False if X is not None else X_tokenized\n (input_ids, input_mask, segment_ids,\n wide_ids, wide_weights, wide_length) = self._convert_X(X_tokenized if tokenized else X, tokenized=tokenized)\n data[\"input_ids\"] = np.array(input_ids, dtype=np.int32)\n data[\"input_mask\"] = np.array(input_mask, dtype=np.int32)\n data[\"segment_ids\"] = np.array(segment_ids, dtype=np.int32)\n data[\"wide_ids\"] = np.array(wide_ids, dtype=np.int32)\n data[\"wide_weights\"] = np.array(wide_weights, dtype=np.float32)\n data[\"wide_length\"] = np.array(wide_length, dtype=np.int32)\n n_inputs = len(input_ids)\n\n if n_inputs < self.batch_size:\n self.batch_size = max(n_inputs, len(self._gpu_ids))\n\n # convert y\n if y is not None:\n label_floats = self._convert_y(y)\n data[\"label_floats\"] = np.array(label_floats, dtype=np.float32)\n\n # convert sample_weight\n if is_training or y is not None:\n sample_weight = self._convert_sample_weight(sample_weight, n_inputs)\n data[\"sample_weight\"] = np.array(sample_weight, dtype=np.float32)\n\n return data\n\n def _convert_X(self, X_target, tokenized):\n\n # tokenize input texts\n segment_inputs = []\n for idx, sample in enumerate(X_target):\n try:\n segment_inputs.append({\n \"w\": sample[\"w\"],\n \"d\": self._convert_x(sample[\"d\"], tokenized),\n })\n for v in sample[\"w\"].values():\n float(v)\n except Exception as e:\n raise ValueError(\n \"Wrong input format (%s): %s. An untokenized \"\n \"example: X = [{\\\"w\\\": {\\\"timeliness\\\": 0.78, \\\"is_negative\\\": 1, \\\"is_porn\\\": 0}, \"\n \"\\\"d\\\": \\\"You can not put your faith on anyone.\\\"}, ...]\"\n % (sample, e)\n )\n\n if self.wide_features is None:\n self.wide_features = set()\n for segments in segment_inputs:\n for feature in segments[\"w\"]:\n self.wide_features.add(feature)\n self.wide_features = list(self.wide_features)\n elif not isinstance(self.wide_features, list):\n raise ValueError(\n \"`wide_features` should be a list of wide feature names (integer or string). \"\n \"E.g. [\\\"timeliness\\\", \\\"is_negative\\\", \\\"is_porn\\\"].\"\n )\n wide_features_map = {self.wide_features[i]: i + 1 for i in range(len(self.wide_features))}\n\n input_ids = []\n input_mask = []\n segment_ids = []\n wide_ids = []\n wide_weights = []\n wide_length = []\n for idx, segments in enumerate(segment_inputs):\n _input_tokens = [\"[CLS]\"]\n _input_ids = []\n _input_mask = [1]\n _segment_ids = [0]\n _wide_ids = []\n _wide_weights = []\n for feature, weight in segments[\"w\"].items():\n try:\n _wide_ids.append(wide_features_map[feature])\n _wide_weights.append(float(weight))\n except Exception:\n tf.logging.warning(\"Unregistered wide feature: %s. Ignored.\" % feature)\n continue\n _wide_length = len(_wide_ids)\n\n segments = segments[\"d\"]\n com.truncate_segments(segments, self.max_seq_length - len(segments) - 1, truncate_method=self.truncate_method)\n for s_id, segment in enumerate(segments):\n _segment_id = min(s_id, 1)\n _input_tokens.extend(segment + [\"[SEP]\"])\n _input_mask.extend([1] * (len(segment) + 1))\n _segment_ids.extend([_segment_id] * (len(segment) + 1))\n\n _input_ids = self.tokenizer.convert_tokens_to_ids(_input_tokens)\n\n # padding\n _input_ids += [0] * (self.max_seq_length - len(_input_ids))\n _input_mask += [0] * (self.max_seq_length - len(_input_mask))\n _segment_ids += [0] * (self.max_seq_length - len(_segment_ids))\n _wide_ids += [0] * (len(self.wide_features) - len(_wide_ids))\n _wide_weights += [0] * (len(self.wide_features) - len(_wide_weights))\n\n input_ids.append(_input_ids)\n input_mask.append(_input_mask)\n segment_ids.append(_segment_ids)\n wide_ids.append(_wide_ids)\n wide_weights.append(_wide_weights)\n wide_length.append(_wide_length)\n\n return input_ids, input_mask, segment_ids, wide_ids, wide_weights, wide_length\n\n def _set_placeholders(self, **kwargs):\n self.placeholders = {\n \"input_ids\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"input_ids\"),\n \"input_mask\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"input_mask\"),\n \"segment_ids\": tf.placeholder(tf.int32, [None, self.max_seq_length], \"segment_ids\"),\n \"wide_ids\": tf.placeholder(tf.int32, [None, len(self.wide_features)], \"wide_ids\"),\n \"wide_weights\": tf.placeholder(tf.float32, [None, len(self.wide_features)], \"wide_weights\"),\n \"wide_length\": tf.placeholder(tf.int32, [None], \"wide_length\"),\n \"label_floats\": tf.placeholder(tf.float32, [None, self.label_size], \"label_floats\"),\n \"sample_weight\": tf.placeholder(tf.float32, [None], \"sample_weight\"),\n }\n\n def _forward(self, is_training, placeholders, **kwargs):\n\n encoder = BERTEncoder(\n bert_config=self.bert_config,\n is_training=is_training,\n input_ids=placeholders[\"input_ids\"],\n input_mask=placeholders[\"input_mask\"],\n segment_ids=placeholders[\"segment_ids\"],\n **kwargs,\n )\n encoder_output = encoder.get_pooled_output()\n decoder = WideDeepRegDecoder(\n is_training=is_training,\n input_tensor=encoder_output,\n wide_ids=placeholders[\"wide_ids\"],\n wide_weights=placeholders[\"wide_weights\"],\n wide_length=placeholders[\"wide_length\"],\n label_floats=placeholders[\"label_floats\"],\n label_size=self.label_size,\n sample_weight=placeholders.get(\"sample_weight\"),\n scope=\"reg\",\n **kwargs,\n )\n train_loss, tensors = decoder.get_forward_outputs()\n return train_loss, tensors\n","sub_path":"uf/apps/widedeep/widedeep_regressor.py","file_name":"widedeep_regressor.py","file_ext":"py","file_size_in_byte":9062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"281482643","text":"#! python\n# pylint: disable=W0312, E1101\n\nimport threading\nimport time\nimport random\nimport pygame\nimport numpy as np\n\n\nimport config\nfrom FRONTEND import mainRenderer\nfrom FRONTEND import userListener\nfrom BACKEND import player\nfrom BACKEND import mapGenerator\nfrom BACKEND import worm\n\nrunning = False\nplayers = np.empty(config.NUMPLAYERS, dtype=player.Player)\nmap = []\nclock = 0\nactivePlayer = 0\n\ndef main():\n\tpygame.init()\n\tmainLoop()\n\ndef generatePlayers():\n\tglobal map, players\n\n\tfor i in range(config.NUMPLAYERS):\n\t\tplayers[i] = player.Player(map, i)\n\ndef initiateNextRound():\n\tglobal activePlayer, clock\n\tclock = time.clock()\n\tactivePlayer = (activePlayer + 1) % config.NUMPLAYERS\n\ndef outputLoop(gui):\n\tglobal running, map, players, clock, activePlayer\n\n\twhile running:\n\t\ttime.sleep(0.01)\n\t\tnextRound = gui.update(clock, map.colours, players, activePlayer)\n\t\tif nextRound:\n\t\t\tinitiateNextRound()\n\ndef inputLoop(ui):\n\tglobal running, players, activePlayer\n\n\twhile running:\n\t\ttime.sleep(0.03) #0.07 is good\n\t\trunning, nextRound = ui.getNextEvent(players, activePlayer)\n\t\tif nextRound:\n\t\t\tinitiateNextRound()\n\ndef gravityLoop():\n\tglobal running, players\n\n\twhile running:\n\t\ttime.sleep(0.01)\n\t\tfor player in players:\n\t\t\tfor worm in player.worms:\n\t\t\t\tworm.move(\"down\")\n\ndef mainLoop():\n\tglobal map, running, activePlayer\n\n\tmap = mapGenerator.MapBackend()\n\tgeneratePlayers()\n\n\tactivePlayer = random.randrange(config.NUMPLAYERS)\n\n\tgui = mainRenderer.mainRenderer()\n\tui = userListener.userListener()\n\n\trunning = True\n\n\tgravityThread = threading.Thread(target=gravityLoop)\n\toutputThread = threading.Thread(target=outputLoop, args=(gui,))\n\n\tgravityThread.start()\n\toutputThread.start()\n\tinitiateNextRound()\n\tinputLoop(ui)\n\toutputThread.join()\n\n\tpygame.quit()\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102683116","text":"\n\nfrom xai.brain.wordbase.nouns._perjury import _PERJURY\n\n#calss header\nclass _PERJURIES(_PERJURY, ):\n\tdef __init__(self,): \n\t\t_PERJURY.__init__(self)\n\t\tself.name = \"PERJURIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"perjury\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_perjuries.py","file_name":"_perjuries.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"429608391","text":"from functools import partial\n\nfrom ows_refactored.ows_legend_cfg import legend_idx_0_1_5ticks\nfrom ows_refactored.ows_util_tools import swap_scale\n\nstyle_ls_simple_rgb = {\n \"name\": \"simple_rgb\",\n \"title\": \"Simple RGB\",\n \"abstract\": \"Simple true-colour image, using the red, green and blue bands\",\n \"components\": {\"red\": {\"red\": 1.0}, \"green\": {\"green\": 1.0}, \"blue\": {\"blue\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_irg = {\n \"name\": \"infrared_green\",\n \"title\": \"False colour - Green, SWIR, NIR\",\n \"abstract\": \"False Colour image with SWIR1->Red, NIR->Green, and Green->Blue\",\n \"components\": {\n \"red\": {\"swir1\": 1.0},\n \"green\": {\"nir\": 1.0},\n \"blue\": {\"green\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_ndvi = {\n \"name\": \"ndvi\",\n \"title\": \"NDVI - Red, NIR\",\n \"abstract\": \"Normalised Difference Vegetation Index - a derived index that correlates well with the existence of vegetation\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"nir\", \"band2\": \"red\"},\n },\n \"needed_bands\": [\"red\", \"nir\"],\n \"color_ramp\": [\n {\"value\": -0.0, \"color\": \"#8F3F20\", \"alpha\": 0.0},\n {\"value\": 0.0, \"color\": \"#8F3F20\", \"alpha\": 1.0},\n {\"value\": 0.1, \"color\": \"#A35F18\"},\n {\"value\": 0.2, \"color\": \"#B88512\"},\n {\"value\": 0.3, \"color\": \"#CEAC0E\"},\n {\"value\": 0.4, \"color\": \"#E5D609\"},\n {\"value\": 0.5, \"color\": \"#FFFF0C\"},\n {\"value\": 0.6, \"color\": \"#C3DE09\"},\n {\"value\": 0.7, \"color\": \"#88B808\"},\n {\"value\": 0.8, \"color\": \"#529400\"},\n {\"value\": 0.9, \"color\": \"#237100\"},\n {\"value\": 1.0, \"color\": \"#114D04\"},\n ],\n \"legend\": legend_idx_0_1_5ticks,\n}\n\n\nstyle_ls_ndwi = {\n \"name\": \"ndwi\",\n \"title\": \"NDWI - Green, NIR\",\n \"abstract\": \"Normalised Difference Water Index - a derived index that correlates well with the existence of water (McFeeters 1996)\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"green\", \"band2\": \"nir\"},\n },\n \"needed_bands\": [\"green\", \"nir\"],\n \"color_ramp\": [\n {\"value\": -0.1, \"color\": \"#f7fbff\", \"alpha\": 0.0},\n {\n \"value\": 0.0,\n \"color\": \"#d8e7f5\",\n },\n {\"value\": 0.1, \"color\": \"#b0d2e8\"},\n {\n \"value\": 0.2,\n \"color\": \"#73b3d8\",\n },\n {\"value\": 0.3, \"color\": \"#3e8ec4\"},\n {\n \"value\": 0.4,\n \"color\": \"#1563aa\",\n },\n {\n \"value\": 0.5,\n \"color\": \"#08306b\",\n },\n ],\n \"legend\": {\n \"begin\": \"0.0\",\n \"end\": \"0.5\",\n \"decimal_places\": 1,\n \"ticks\": [\"0.0\", \"0.2\", \"0.4\", \"0.5\"],\n \"tick_labels\": {\n \"0.0\": {\"prefix\": \"<\"},\n \"0.2\": {\"label\": \"0.2\"},\n \"0.4\": {\"label\": \"0.4\"},\n \"0.5\": {\"prefix\": \">\"},\n },\n },\n}\n\nstyle_ls_mndwi = {\n \"name\": \"mndwi\",\n \"title\": \"MNDWI - Green, SWIR\",\n \"abstract\": \"Modified Normalised Difference Water Index - a derived index that correlates well with the existence of water (Xu 2006)\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"green\", \"band2\": \"swir1\"},\n },\n \"needed_bands\": [\"green\", \"swir1\"],\n \"color_ramp\": [\n {\"value\": -0.1, \"color\": \"#f7fbff\", \"alpha\": 0.0},\n {\"value\": 0.0, \"color\": \"#d8e7f5\"},\n {\"value\": 0.2, \"color\": \"#b0d2e8\"},\n {\"value\": 0.4, \"color\": \"#73b3d8\"},\n {\"value\": 0.6, \"color\": \"#3e8ec4\"},\n {\"value\": 0.8, \"color\": \"#1563aa\"},\n {\"value\": 1.0, \"color\": \"#08306b\"},\n ],\n \"legend\": legend_idx_0_1_5ticks,\n}\n\nstyle_ls_pure_blue = {\n \"name\": \"blue\",\n \"title\": \"Blue - 480\",\n \"abstract\": \"Blue band, centered on 480nm\",\n \"components\": {\"red\": {\"blue\": 1.0}, \"green\": {\"blue\": 1.0}, \"blue\": {\"blue\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_pure_green = {\n \"name\": \"green\",\n \"title\": \"Green - 560\",\n \"abstract\": \"Green band, centered on 560nm\",\n \"components\": {\n \"red\": {\"green\": 1.0},\n \"green\": {\"green\": 1.0},\n \"blue\": {\"green\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_pure_red = {\n \"name\": \"red\",\n \"title\": \"Red - 660\",\n \"abstract\": \"Red band, centered on 660nm\",\n \"components\": {\"red\": {\"red\": 1.0}, \"green\": {\"red\": 1.0}, \"blue\": {\"red\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_pure_nir = {\n \"name\": \"nir\",\n \"title\": \"Near Infrared (NIR) - 840\",\n \"abstract\": \"Near infra-red band, centered on 840nm\",\n \"components\": {\"red\": {\"nir\": 1.0}, \"green\": {\"nir\": 1.0}, \"blue\": {\"nir\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_ls_pure_swir1 = {\n \"name\": \"swir1\",\n \"title\": \"Shortwave Infrared (SWIR) - 1650\",\n \"abstract\": \"Short wave infra-red band 1, centered on 1650nm\",\n \"components\": {\n \"red\": {\"swir1\": 1.0},\n \"green\": {\"swir1\": 1.0},\n \"blue\": {\"swir1\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\nstyle_ls_pure_swir2 = {\n \"name\": \"swir2\",\n \"title\": \"Shortwave Infrared (SWIR) - 2220\",\n \"abstract\": \"Short wave infra-red band 2, centered on 2220nm\",\n \"components\": {\n \"red\": {\"swir2\": 1.0},\n \"green\": {\"swir2\": 1.0},\n \"blue\": {\"swir2\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_sentinel_pure_blue = {\n \"name\": \"blue\",\n \"title\": \"Blue - 490\",\n \"abstract\": \"Blue band, centered on 490nm\",\n \"components\": {\"red\": {\"blue\": 1.0}, \"green\": {\"blue\": 1.0}, \"blue\": {\"blue\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\n\nstyle_sentinel_pure_nir = {\n \"name\": \"nir\",\n \"title\": \"Near Infrared (NIR) - 870\",\n \"abstract\": \"Near infra-red band, centered on 870nm\",\n \"components\": {\"red\": {\"nir\": 1.0}, \"green\": {\"nir\": 1.0}, \"blue\": {\"nir\": 1.0}},\n \"scale_range\": [0.0, 3000.0],\n}\n\n\nstyle_sentinel_pure_swir1 = {\n \"name\": \"swir1\",\n \"title\": \"Shortwave Infrared (SWIR) - 1610\",\n \"abstract\": \"Short wave infra-red band 1, centered on 1610nm\",\n \"components\": {\n \"red\": {\"swir1\": 1.0},\n \"green\": {\"swir1\": 1.0},\n \"blue\": {\"swir1\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\n\n\nstyle_sentinel_pure_swir2 = {\n \"name\": \"swir2\",\n \"title\": \"Shortwave Infrared (SWIR) - 2200\",\n \"abstract\": \"Short wave infra-red band 2, centered on 2200nm\",\n \"components\": {\n \"red\": {\"swir2\": 1.0},\n \"green\": {\"swir2\": 1.0},\n \"blue\": {\"swir2\": 1.0},\n },\n \"scale_range\": [0.0, 3000.0],\n}\n\nstyle_nd_ferric_iron = {\n \"name\": \"nd_ferric_iron\",\n \"title\": \"Ferric Iron\",\n \"abstract\": \"Normalised Difference Ferric Iron Index - a derived index that correlates well with the existence of Ferric Iron Content\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"red\", \"band2\": \"blue\"},\n },\n \"needed_bands\": [\"red\", \"blue\"],\n \"color_ramp\": [\n {\"value\": -0.1, \"color\": \"#3B97C3\", \"alpha\": 0.0},\n {\"value\": 0.0, \"color\": \"#6EA9B0\", \"alpha\": 1.0},\n {\"value\": 0.1, \"color\": \"#83B3A9\"},\n {\"value\": 0.2, \"color\": \"#9FC29D\"},\n {\"value\": 0.3, \"color\": \"#F3F56C\"},\n {\"value\": 0.4, \"color\": \"#FCDE56\"},\n {\"value\": 0.5, \"color\": \"#FCC54C\"},\n {\"value\": 0.6, \"color\": \"#F77F2F\"},\n {\"value\": 0.7, \"color\": \"#F55F25\"},\n {\"value\": 0.8, \"color\": \"#F25622\"},\n {\"value\": 0.9, \"color\": \"#EB1E15\"},\n {\"value\": 1.0, \"color\": \"#E81515\"},\n ],\n \"legend\": legend_idx_0_1_5ticks,\n}\n\nstyle_nd_soil = {\n \"name\": \"nd_soil\",\n \"title\": \"Normalised Difference Soil Index\",\n \"abstract\": \"Normalised Difference Soil Index - a derived index that correlates well with the existence of bare Soil/Rock\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"swir1\", \"band2\": \"nir\"},\n },\n \"needed_bands\": [\"nir\", \"swir1\"],\n \"color_ramp\": [\n {\"value\": -0.1, \"color\": \"#f7fbff\", \"alpha\": 0.0},\n {\"value\": 0.0, \"color\": \"#d8e7f5\"},\n {\"value\": 0.2, \"color\": \"#b0d2e8\"},\n {\"value\": 0.4, \"color\": \"#73b3d8\"},\n {\"value\": 0.6, \"color\": \"#3e8ec4\"},\n {\"value\": 0.8, \"color\": \"#1563aa\"},\n {\"value\": 1.0, \"color\": \"#08306b\"},\n ],\n \"legend\": legend_idx_0_1_5ticks,\n}\n\nstyle_nd_clay_mica = {\n \"name\": \"nd_clay_mica\",\n \"title\": \"Clay and Mica Minerals\",\n \"abstract\": \"Normalised Difference Clay and Mica Minerals Index - a derived index that correlates well with the existence of hydroxyl bearing minerals (clay and mica minerals)\",\n \"index_function\": {\n \"function\": \"datacube_ows.band_utils.norm_diff\",\n \"mapped_bands\": True,\n \"kwargs\": {\"band1\": \"swir1\", \"band2\": \"swir2\"},\n },\n \"needed_bands\": [\"swir1\", \"swir2\"],\n \"color_ramp\": [\n {\"value\": -0.1, \"color\": \"#ffffb2\", \"alpha\": 0.0},\n {\"value\": 0.0, \"color\": \"#ffef97\", \"alpha\": 1.0},\n {\"value\": 0.1, \"color\": \"#ffe07d\"},\n {\"value\": 0.2, \"color\": \"#fecc5c\"},\n {\"value\": 0.3, \"color\": \"#feb450\"},\n {\"value\": 0.4, \"color\": \"#fd8d3c\"},\n {\"value\": 0.5, \"color\": \"#f86b30\"},\n {\"value\": 0.6, \"color\": \"#f44f26\"},\n {\"value\": 0.7, \"color\": \"#f03b20\"},\n {\"value\": 0.8, \"color\": \"#de2522\"},\n {\"value\": 0.9, \"color\": \"#cc1024\"},\n {\"value\": 1.0, \"color\": \"#bd0026\"},\n ],\n \"legend\": legend_idx_0_1_5ticks,\n}\n\n\nstyles_ls_list = [\n style_ls_simple_rgb,\n style_ls_irg,\n style_ls_ndvi,\n style_ls_ndwi,\n style_ls_mndwi,\n style_sentinel_pure_blue,\n style_ls_pure_green,\n style_ls_pure_red,\n style_ls_pure_nir,\n style_ls_pure_swir1,\n style_ls_pure_swir2,\n]\n\nstyles_barest_earth_mosaic_list = [\n style_ls_simple_rgb,\n style_ls_irg,\n style_ls_ndvi,\n style_ls_pure_blue,\n style_ls_pure_green,\n style_ls_pure_red,\n style_sentinel_pure_nir,\n style_sentinel_pure_swir1,\n style_sentinel_pure_swir2,\n]\n\nstyles_barest_earth_list = styles_barest_earth_mosaic_list + [\n style_nd_ferric_iron,\n style_nd_soil,\n style_nd_clay_mica,\n]\n\nswap_scale_p = partial(swap_scale, [0.0, 0.3])\n\nstyles_tide_list = list([swap_scale_p(s) for s in styles_ls_list])\n","sub_path":"dev/services/wms/ows_refactored/surface_reflectance/style_ls_cfg.py","file_name":"style_ls_cfg.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"99352414","text":"# -*- coding: utf-8 -*-\n\n'''\n traing_cost 与 testing_cost 什么区别??\n trainging_cost: 预测值 与 训练数据的cost\n testing_cost : 预测值 与 测试数据的cost\n\n feed_dict ??\n display_step : 什么意思??\n\n 函数API整理:\n numpy.asarray()\n numpy.assaray().shape\n \n tf.placeholder()\n tf.Variable()\n tf.add()\n tf.multiply()\n tf.reduce_sum()\n tf.pow()\n tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n tf.global_variables_initializer()\n tf.Session()\n with tf.Session() as sess:\n sess.run()\n \n\n'''\n\nfrom __future__ import print_function\n\nimport tensorflow as tf \nimport numpy\nimport matplotlib.pyplot as plt \n\nrng = numpy.random\n\n# parameters\nlearning_rate = 0.01 # 学习率\ntraining_epochs = 1000 # 训练次数\ndisplay_step = 50\n\n# Training Data\ntrain_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,\n 7.042,10.791,5.313,7.997,5.654,9.27,3.1])\ntrain_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,\n 2.827,3.465,1.65,2.904,2.42,2.94,1.3])\n'''\nnp.shanpe是对数组的描述:\nx = np.array([1, 2])\ny = np.array([[1],[2]])\nprint x.shape\n>>> (2,) # 说明是一维数组,包含2个元素\nprint y.shape\n>>>(2, 1) # 说明是二维数组,每一维包含1个元素\n'''\nn_samples = train_X.shape[0]\n\n# tf Graph Input\nX = tf.placeholder(\"float\")\nY = tf.placeholder(\"float\")\n\n# 设置权重\nW = tf.Variable(rng.randn(),name = 'weight')\nb = tf.Variable(rng.randn(),name = 'bias')\n\n# 建立模型\npred = tf.add(tf.multiply(X,W),b)\n\n'''\n均方误差 Mean squared error(https://baike.baidu.com/item/%E5%9D%87%E6%96%B9%E8%AF%AF%E5%B7%AE/9024810?fr=aladdin&fromid=11324926&fromtitle=mean+squared+error)\n\n用 Mean squared error 来设置cost函数\n'''\ncost = tf.reduce_sum(tf.pow(pred - Y, 2)) / (2 * n_samples)\n# 梯度下降\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\n# initialize the variables\ninit = tf.global_variables_initializer()\n\n\n# Start training\nwith tf.Session() as sess:\n\n\tsess.run(init)\n\n\tfor epoch in range(training_epochs):\n\t\tfor (x,y) in zip(train_X,train_Y):\n\t\t\t# 为什么没有 train.next_batch(100) ?? 这是加载了所有的数据来训练???\n\t\t\tsess.run(optimizer, feed_dict = {X:x, Y:y})\n\t\n\tif (epoch + 1) % display_step == 0:\n\t\tc = sess.run(cost, feed_dict = {X:train_X, Y:train_Y})\n\t\tprint (\"Epoch:\", \"%04d\" % (epoch + 1), \"cost= \", \"{:.9f}\".format(c),\\\n\t\t\t\"W=\", sess.run(W), \"b=\", sess.run(b))\n\n\tprint (\"Optimization over ...\")\n\ttraining_cost = sess.run(cost, feed_dict = {X:train_X, Y:train_Y})\n\tprint (\"Traing cost:= \",training_cost, \"W=\", sess.run(W), \"b=\", sess.run(b)) \n\t# QUESTION:这里的w,b会和上面的一样吗?? 根据输出来看是一样的\n\n\t# Graphic display\n\tplt.plot(train_X, train_Y,'ro',label = \"Original data\")\n\tplt.plot(train_X, sess.run(W) * train_X + sess.run(b), label = \"Fitted line\")\n\tplt.legend()\n\tplt.show()\n\n\t# Testing example, as requested (Issue #2)\n\ttest_X = numpy.asarray([6.83, 4.668, 8.9, 7.91, 5.7, 8.7, 3.1, 2.1])\n\ttest_Y = numpy.asarray([1.84, 2.273, 3.2, 2.831, 2.92, 3.24, 1.35, 1.03])\n\n\tprint (\"Testing... (Mean square loss comparison...)\")\n\ttesting_cost = sess.run(\n\t\ttf.reduce_sum(tf.pow(pred - Y,2)) / (2 * test_X.shape[0]),\n\t\tfeed_dict = {X:test_X,Y:test_Y}\n\t\t)\n\tprint (\"Testing cost = \",testing_cost)\n\tprint (\"Absolute mean square loss difference:\", abs(training_cost - testing_cost))\n\t# testing_cost 与 training_cost 区别??\n\n\tplt.plot(test_X,test_Y,'bo',label = 'Testing data')\n\tplt.plot(train_X, sess.run(W) * train_X + sess.run(b), label = \"Fitted line\")\n\tplt.legend()\n\tplt.show()\n\n\n","sub_path":"tensorflow_temp/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"40690253","text":"import requests\nimport shutil\nimport os\n\n#Year 2011 is missing\nPHYSICS_ROUND1 = [\n [2018, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/resultat-r1-1718-diplom-rettet.pdf\"],\n [2017, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/resultat11617(1).pdf\"],\n [2016, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/resultat11516.pdf\"],\n [2015, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/resultat11415b(1).pdf\"],\n [2014, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/resultat_1314.pdf\"],\n [2013, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/res_1R_1213.pdf\"],\n [2012, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/Res_1R_1112.pdf\"],\n [2010, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/res_1R_0910.pdf\"],\n [2009, \"https://www.mn.uio.no/fysikk/forskning/grupper/skolelab/fysikk-ol/res_1R_0809.pdf\"]\n ]\nINFORMATICS_ROUND1 = [\n [2018, \"http://nio.no/resultater-1-runde-nio-2017-2018/\"],\n [2017, \"http://nio.no/resultater-1-runde-nio-2016-2017/\"],\n [2016, \"http://nio.no/resultater-fra-1-runde-i-nio-20152016/\"],\n [2015, \"http://nio.no/resultater-fra-1-runde-i-nio-2014-2015/\"],\n [2014, \"http://nio.no/resultater-fra-1-runde-2013-2014/\"],\n [2013, \"http://nio.no/resultater-fra-1-runde-2012-2013/\"]\n ]\n\nCHEM_ROUND1 = [\n [2019, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2019.pdf\"],\n [2018, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2018.pdf\"],\n [2017, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2017.pdf\"],\n [2016, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2016.pdf\"],\n [2015, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2015.pdf\"],\n\n [2013, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2013.pdf\"],\n [2012, \"https://foreninger.uio.no/kjemiolympiaden/resultater/Runde1-2012.pdf\"],\n ]\n\nMATH_ROUND1 = [\n [2019, \"https://abelkonkurransen.no/files/runde1-2018.pdf\"],\n [2018, \"https://abelkonkurransen.no/files/runde1-2017.pdf\"],\n [2017, \"https://abelkonkurransen.no/files/runde1-2016.pdf\"]\n ]\n\n\ndef get_physics_files(folder=\"raw_data/physics/pdf\"):\n urls = PHYSICS_ROUND1\n if not os.path.exists(folder):\n os.makedirs(folder)\n for u in urls:\n year = u[0]\n url = u[1]\n r = requests.get(url, verify=False, stream=True)\n r.raw.decode_content = True\n with open(f\"{folder}/round1_{year}.pdf\", 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n\n\ndef get_math_files(folder=\"raw_data/mathematics/pdf\"):\n urls = MATH_ROUND1\n if not os.path.exists(folder):\n os.makedirs(folder)\n for u in urls:\n year = u[0]\n url = u[1]\n r = requests.get(url, verify=False, stream=True)\n r.raw.decode_content = True\n with open(f\"{folder}/round1_{year}.pdf\", 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n\n\ndef get_chemistry_files(folder=\"raw_data/chemistry/pdf\"):\n urls = CHEM_ROUND1\n if not os.path.exists(folder):\n os.makedirs(folder)\n for u in urls:\n year = u[0]\n url = u[1]\n r = requests.get(url, verify=False, stream=True)\n r.raw.decode_content = True\n with open(f\"{folder}/round1_{year}.pdf\", 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n\n\ndef get_informatics_files(folder=\"raw_data/informatics/pdf\"):\n urls = INFORMATICS_ROUND1\n if not os.path.exists(folder):\n os.makedirs(folder)\n for u in urls:\n year = u[0]\n url = u[1]\n r = requests.get(url, verify=False, stream=True)\n r.raw.decode_content = True\n with open(f\"{folder}/round1_{year}.pdf\", 'wb') as f:\n shutil.copyfileobj(r.raw, f)\n\n\nget_math_files()\nget_physics_files()\nget_chemistry_files()\nget_informatics_files()\n","sub_path":"science_olympiads/download_source_files.py","file_name":"download_source_files.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"180988763","text":"'''\nCreated on Feb 4, 2016\n\nSolved.\n\n@author: Ronbo\n'''\n\nx = 600851475143\nlargest = 0\nfactor = 2\nwhile x > 1:\n if x % factor == 0:\n x /= factor\n if factor > largest:\n largest = factor\n else:\n factor += 1\nprint(largest)","sub_path":"me/ronbo/euler3.py","file_name":"euler3.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"184888991","text":"from django.core.exceptions import ObjectDoesNotExist\nfrom django.db import models\n\nfrom authtools.models import AbstractNamedUser\n\n\nclass Counter(models.Model):\n name = models.CharField(max_length=32, unique=True)\n total = models.IntegerField(default=0)\n\n def __str__(self):\n return '{}: {}'.format(self.name, self.total)\n\n\nclass Setting(models.Model):\n INTEGER = 0\n FLOAT = 1\n STRING = 2\n BOOL = 3\n TYPE_CHOICES = (\n (INTEGER, 'Integer'),\n (FLOAT, 'Float'),\n (STRING, 'String'),\n (BOOL, 'Bool'),\n )\n name = models.CharField(max_length=32, unique=True)\n setting_type = models.PositiveIntegerField(choices=TYPE_CHOICES,\n default=INTEGER)\n data = models.TextField()\n\n def get(self):\n if self.setting_type == self.INTEGER:\n return int(self.data)\n elif self.setting_type == self.FLOAT:\n return float(self.data)\n elif self.setting_type == self.BOOL:\n return self.data == 'True'\n else:\n return self.data\n\n def __str__(self):\n return '{}: {}'.format(self.name, self.data)\n\n\nclass RadioUser(AbstractNamedUser):\n is_dj = models.BooleanField(default=False)\n\n def get_username(self):\n if self.is_dj:\n return Setting.objects.get(name='dj_name').get()\n elif self.name:\n return self.name\n else:\n return super().get_username()\n\n\ndef get_setting(name):\n setting = Setting.objects.get(name=name)\n return setting.get()\n\ndef set_setting(name, value, setting_type=None):\n SETTING_TYPES = { 'Integer': 0, 'Float': 1, 'String': 2, 'Bool': 3 }\n try:\n setting = Setting.objects.get(name=name)\n setting.data = str(value)\n if setting_type in SETTING_TYPES:\n setting.setting_type = SETTING_TYPES[setting_type]\n setting.save()\n except ObjectDoesNotExist:\n if setting_type in SETTING_TYPES:\n Setting.objects.create(name=name,\n setting_type=SETTING_TYPES[setting_type],\n data=str(value))\n else:\n error_msg = 'New settings need a type (Integer, Float, String, Bool)'\n raise TypeError(error_msg)\n return\n","sub_path":"savepointradio/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"534655810","text":"# Your last recorded submission was :(Working)\na,b = [int(x) for x in input().split()]\nif (a>b):\n print(b)\nif (b>a):\n print(a)\nif (b==a):\n print(a)\n\n\n\n# Sample solutions (Provided by instructor)\nx,y = input().split(\" \")\nx = int(x)\ny = int(y)\n\nif(x None\n \"\"\" This method processes the Fulfillment Requests in Pending status for change subscription action.\n If vendor system does not support the change in the subscription check the request details\n to reject the request with proper message. \"\"\"\n\n subscription_id = Utils.get_param_value(request, 'fulfillment', 'subscription_id')\n # In this Product Example up/downsizes are allowed, Upgrades or downgrades does not.\n if len(Utils.get_value(request, 'asset', 'items')) == 1:\n new_quantity = Utils.get_value(request, 'asset', 'items')[0]['quantity']\n\n api_client = Utils.get_api_client()\n change_payload = {\n \"licences\": {\n \"limit\": new_quantity\n }\n }\n api_client.change_subscription(change_payload, subscription_id)\n\n Utils.approve_fulfillment_request(request, client)\n else:\n request_id = Utils.get_basic_value(request, 'id')\n reason = 'Change not allowed'\n Utils.reject_fulfillment_request(request_id, reason, client)\n","sub_path":"connect_ext/app/change.py","file_name":"change.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"85184944","text":"import math\n\nimport talib\nfrom datetime import datetime\nfrom unittest import TestCase\nimport numpy as np\nimport datetime\nfrom algotrader.technical import Indicator\nfrom algotrader.technical.pipeline import PipeLine\nfrom algotrader.technical.pipeline.make_vector import MakeVector\nfrom algotrader.technical.pipeline.pairwise import Plus, Minus, Times, Divides, Greater, PairCorrelation\nfrom algotrader.technical.talib_wrapper import SMA\nfrom algotrader.utils.time_series import DataSeries\nfrom algotrader.config.app import ApplicationConfig\nfrom algotrader.trading.context import ApplicationContext\n\n\nclass PairwiseTest(TestCase):\n def setUp(self):\n self.app_context = ApplicationContext()\n\n def test_name(self):\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n\n bar0_plus_bar1 = Plus(bar0, bar1, input_key='close')\n bar0_plus_bar1.start(self.app_context)\n\n self.assertEquals(\"Plus('bar0','bar1',close)\",\n bar0_plus_bar1.name)\n\n spread = Minus(bar0, bar1, input_key='close')\n spread.start(self.app_context)\n\n self.assertEquals(\"Minus('bar0','bar1',close)\",\n spread.name)\n\n def test_empty_at_initialize(self):\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n\n bar0_plus_bar1 = Plus(bar0, bar1, input_key='close')\n bar0_plus_bar1.start(self.app_context)\n\n self.assertEquals(0, len(bar0_plus_bar1.get_data()))\n\n def test_shape(self):\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n\n bar0_plus_bar1 = Plus(bar0, bar1, input_key='close')\n bar0_plus_bar1.start(self.app_context)\n\n try:\n np.testing.assert_almost_equal(np.array([1, 1]), bar0_plus_bar1.shape(), 5)\n except AssertionError as e:\n self.fail(e.message)\n\n\n # def test_nan_before_size(self):\n def test_with_single_bar_multi_time(self):\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n\n plus = Plus(bar0, bar1, input_key='close')\n minus = Minus(bar0, bar1, input_key='close')\n times = Times(bar0, bar1, input_key='close')\n divides = Divides(bar0, bar1, input_key='close')\n pcorr = PairCorrelation(bar0, bar1, length=4, input_key='close')\n\n plus.start(self.app_context)\n minus.start(self.app_context)\n times.start(self.app_context)\n divides.start(self.app_context)\n pcorr.start(self.app_context)\n\n now = datetime.datetime.now()\n x = np.array([80.0, 102.0, 101.0, 99.0])\n y = np.array([95.0, 98.0, 105.2, 103.3])\n ts = [now + datetime.timedelta(0, i*3) for i in range(4)]\n x_p_y = x + y\n x_m_y = x - y\n x_t_y = x * y\n x_d_y = x / y\n\n bar0.add({\"timestamp\": ts[0], \"close\": x[0], \"open\": 0})\n bar1.add({\"timestamp\": ts[0], \"close\": y[0], \"open\": 0})\n\n self.assertEqual(plus.now('value'), 175.0)\n self.assertEqual(minus.now('value'), -15.0)\n self.assertEqual(times.now('value'), 7600.0)\n self.assertEqual(divides.now('value'), 80.0/95.0)\n\n bar0.add({\"timestamp\": ts[1], \"close\": x[1], \"open\": 0})\n bar1.add({\"timestamp\": ts[1], \"close\": y[1], \"open\": 0})\n\n self.assertEqual(plus.now('value'), 200.0)\n self.assertEqual(minus.now('value'), 4.0)\n self.assertEqual(times.now('value'), 102.0*98.0)\n self.assertEqual(divides.now('value'), 102.0/98.0)\n\n bar0.add({\"timestamp\": ts[2], \"close\": x[2], \"open\": 0})\n bar1.add({\"timestamp\": ts[2], \"close\": y[2], \"open\": 0})\n\n bar0.add({\"timestamp\": ts[3], \"close\": x[3], \"open\": 0})\n bar1.add({\"timestamp\": ts[3], \"close\": y[3], \"open\": 0})\n\n # self.assertEqual(pcorr.now('value'), np.corrcoef(x, y))\n self.__np_assert_almost_equal(pcorr.now('value'), np.corrcoef(x, y))\n\n def test_with_pair_corr_with_vec(self):\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n bar2 = self.app_context.inst_data_mgr.get_series(\"bar2\")\n bar3 = self.app_context.inst_data_mgr.get_series(\"bar3\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n bar2.start(self.app_context)\n bar3.start(self.app_context)\n\n vec0 = MakeVector([bar0, bar1], input_key='close')\n vec1 = MakeVector([bar2, bar3], input_key='close')\n\n vec0.start(self.app_context)\n vec1.start(self.app_context)\n\n pcorr = PairCorrelation(vec0, vec1, length=4, input_key=PipeLine.VALUE)\n pcorr.start(self.app_context)\n\n\n now = datetime.datetime.now()\n x0 = np.array([80.0, 102.0, 101.0, 99.0 ])\n x1 = np.array([102.0, 101.5, 99.0, 97.0])\n x2 = np.array([94.0, 98.5, 91.0, 87.0])\n x3 = np.array([104.5, 107.5, 97.0, 91.0])\n ts = [now + datetime.timedelta(0, i*3) for i in range(4)]\n\n for i in range(4):\n bar0.add({\"timestamp\": ts[i], \"close\": x0[i], \"open\": 0})\n bar1.add({\"timestamp\": ts[i], \"close\": x1[i], \"open\": 0})\n bar2.add({\"timestamp\": ts[i], \"close\": x2[i], \"open\": 0})\n bar3.add({\"timestamp\": ts[i], \"close\": x3[i], \"open\": 0})\n\n x = np.vstack([x0, x1])\n y = np.vstack([x2, x3])\n self.__np_assert_almost_equal(pcorr.now('value'), np.corrcoef(x, y))\n\n def test_infix_arithmetic(self):\n from infix import or_infix as infix\n\n @infix\n def PipeLinePlus(x, y):\n return Plus(x, y, input_key='close')\n\n @infix\n def PipeLineMinus(x, y):\n return Minus(x, y, input_key='close')\n\n @infix\n def PipeLineTimes(x, y):\n return Times(x, y, input_key='close')\n\n @infix\n def PipeLineDivides(x, y):\n return Divides(x, y, input_key='close')\n\n bar0 = self.app_context.inst_data_mgr.get_series(\"bar0\")\n bar1 = self.app_context.inst_data_mgr.get_series(\"bar1\")\n\n bar0.start(self.app_context)\n bar1.start(self.app_context)\n\n # plus = Plus(bar0, bar1, input_key='close')\n # minus = Minus(bar0, bar1, input_key='close')\n # times = Times(bar0, bar1, input_key='close')\n # divides = Divides(bar0, bar1, input_key='close')\n plus = bar0 |PipeLinePlus| bar1\n minus = bar0 |PipeLineMinus| bar1\n times = bar0 |PipeLineTimes| bar1\n divides = bar0 |PipeLineDivides| bar1\n\n plus.start(self.app_context)\n minus.start(self.app_context)\n times.start(self.app_context)\n divides.start(self.app_context)\n\n now = datetime.datetime.now()\n x = np.array([80.0, 102.0, 101.0, 99.0])\n y = np.array([95.0, 98.0, 105.2, 103.3])\n ts = [now + datetime.timedelta(0, i*3) for i in range(4)]\n x_p_y = x + y\n x_m_y = x - y\n x_t_y = x * y\n x_d_y = x / y\n\n bar0.add({\"timestamp\": ts[0], \"close\": x[0], \"open\": 0})\n bar1.add({\"timestamp\": ts[0], \"close\": y[0], \"open\": 0})\n\n self.assertEqual(plus.now('value'), 175.0)\n self.assertEqual(minus.now('value'), -15.0)\n self.assertEqual(times.now('value'), 7600.0)\n self.assertEqual(divides.now('value'), 80.0/95.0)\n\n bar0.add({\"timestamp\": ts[1], \"close\": x[1], \"open\": 0})\n bar1.add({\"timestamp\": ts[1], \"close\": y[1], \"open\": 0})\n\n self.assertEqual(plus.now('value'), 200.0)\n self.assertEqual(minus.now('value'), 4.0)\n self.assertEqual(times.now('value'), 102.0*98.0)\n self.assertEqual(divides.now('value'), 102.0/98.0)\n\n bar0.add({\"timestamp\": ts[2], \"close\": x[2], \"open\": 0})\n bar1.add({\"timestamp\": ts[2], \"close\": y[2], \"open\": 0})\n\n bar0.add({\"timestamp\": ts[3], \"close\": x[3], \"open\": 0})\n bar1.add({\"timestamp\": ts[3], \"close\": y[3], \"open\": 0})\n\n # self.assertEqual(pcorr.now('value'), np.corrcoef(x, y))\n\n def __np_assert_almost_equal(self, target, output, precision=10):\n try:\n np.testing.assert_almost_equal(target, output, precision)\n except AssertionError as e:\n self.fail(e.message)\n","sub_path":"tests/test_pipeline_pairwise.py","file_name":"test_pipeline_pairwise.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"231343372","text":"#!/usr/bin/env python\n# -*- coding:utf8 -*-\n# @TIME :2019/4/23 19:01\n# @Author : 洪松\n# @File : UtibetWordMergeSort.py\n\nimport csv, time, term\nimport UtibetWordStructureSplit\n\n\ndef MoveCircle(q):\n i = 1\n for j in q[1:]:\n if '\\u0f90' <= j <= '\\u0fbc':\n x = ord(j) - 80\n q[i] = chr(x)\n i += 1\n return q\n\n\ndef EmptyFill(n):\n i = 1\n for j in n[1:]:\n if j == '':\n n[i] = '\\u0001'\n i += 1\n return n\n\n\ndef IdentifyStructure():\n with open('D:\\全藏字归并排序\\结构识别.csv', newline='', encoding='utf-8') as csvfile:\n num = 0\n li = []\n reader = csv.reader(csvfile)\n for row in reader:\n num += 1\n if num > 1:\n x = row\n withoutcircle = MoveCircle(x)\n withoutempty = EmptyFill(withoutcircle)\n withoutcircleempty = withoutempty[3], withoutempty[2], withoutempty[1], withoutempty[4], withoutempty[5], \\\n withoutempty[6], withoutempty[7], withoutempty[8], withoutempty[0]\n withoutcircleempty_list = list(withoutcircleempty)\n li.append(withoutcircleempty_list)\n return li\n\n\ndef merge_sort(alist):\n n = len(alist) # 获取当前传入的列表的长度\n if n <= 1: # 如果列表长度为1,即已经拆分到最后一步了,就直接返回当前列表,不再往下继续执行了\n return alist\n mid = n // 2 # 取中间值,把当前输入的列表从中间拆分\n\n left_li = merge_sort(alist[:mid]) # 取左半部分\n right_li = merge_sort(alist[mid:]) # 取右半部分\n\n left_pointer = 0 # 设定左半部分的指针,从0开始\n right_pointer = 0 # 设定右半部分的指针,从0开始\n result = [] # 定义一个空列表result用于存储每次递归产生的排好序的列表\n\n while left_pointer < len(left_li) and right_pointer < len(right_li): # 当各部分指针还没走到末尾时\n if left_li[left_pointer] <= right_li[right_pointer]: # 把较小的值存入result并让相应的指针+1\n result.append(left_li[left_pointer])\n left_pointer += 1\n else:\n result.append(right_li[right_pointer])\n right_pointer += 1\n result += left_li[left_pointer:] # 如果是奇数个元素,别忘了把最后单个的元素也添加到result里\n result += right_li[right_pointer:]\n return result # 最终返回的是一个新的排好序的列表result,因此空间复杂度要多一倍\n\n\nif __name__ == '__main__':\n start = time.time()\n result_list = merge_sort(IdentifyStructure())\n for i in result_list:\n # with open('D:\\全藏字归并排序\\归并排序.txt', 'a+', encoding='utf-8') as f:\n # f.write(i[-1] + '\\n')\n print(i[-1])\n end = time.time()\n\nterm.writeLine(str(end - start) + '秒', term.green)\n","sub_path":"Task_6/UtibetWordMergeSort.py","file_name":"UtibetWordMergeSort.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"590828327","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Prediction pipeline.\n\nThis pipeline executes following two tasks:\n1. Generate scoring dataset.\n2. Batch score using pretrained BQML model.\n\"\"\"\n\nimport os\nfrom typing import Any, Dict, Optional, Union\n\nfrom airflow import configuration\nfrom airflow import models\nfrom airflow.contrib.operators import bigquery_operator\nfrom airflow.operators import python_operator\n# from airflow.utils import helpers\n\nfrom . import constants\nfrom . import utils\nfrom .subdags import bq_query\nfrom .subdags import mlwp_features\n\n# DAG configuration.\n_DAG_ID = constants.PREDICTION_DAG_ID\n# This DAG should not be scheduled as it will be tiggerred by\n# `dataset_pipeline_dag`.\n_DAG_SCHEDULE = None\n# Dag directory containing subdags and custom SQL scripts.\n_DAG_DIR = configuration.get('core', 'dags_folder')\n\n\ndef _create_prediction_feature_generator_task(\n main_dag: models.DAG,\n feature_generator: constants.FeatureGenerator,\n sql_params: Optional[Dict[str, Any]] = None\n) -> Union[python_operator.PythonOperator, bigquery_operator.BigQueryOperator]:\n \"\"\"Creates prediction feature generator task.\n\n Args:\n main_dag: The models.DAG instance.\n feature_generator: Either custom query or MLWP pipeline is used to generate\n prediction features.\n sql_params: Custom parameters to apply to features.sql script. It is\n required only in FeatureGenerator.CUSTOM mode.\n\n Returns:\n task: Either PyhonOperator or BigQueryOperator.\n \"\"\"\n if feature_generator == constants.FeatureGenerator.MLWP:\n task = mlwp_features.create_operator(\n parent_dag_id=_DAG_ID,\n dag=main_dag,\n pipeline_mode=constants.PipelineMode.PREDICT)\n elif feature_generator == constants.FeatureGenerator.CUSTOM:\n assert sql_params is not None, ('Provide `sql_params` to apply to '\n 'features.sql.')\n sql_path = os.path.join(_DAG_DIR, constants.FEATURES_SQL_PATH)\n\n task = bq_query.create_operator(\n parent_dag_id=_DAG_ID,\n dag=main_dag,\n sql_params=sql_params,\n sql_path=sql_path)\n else:\n raise ValueError(f'{feature_generator.value} is not supported.'\n 'Provide either \"custom\" or \"mlwp\".')\n return task\n\n\ndef _create_batch_predictor_task(\n main_dag: models.DAG,\n sql_params: Dict[str, str]) -> bigquery_operator.BigQueryOperator:\n \"\"\"Creates batch predictor task based on BQML model.\n\n Args:\n main_dag: The models.DAG instance.\n sql_params: Custom parameters to apply to constants.PREDICTION_SQL_PATH\n script.\n\n Returns:\n Instance of bigquery_operator.BigQueryOperator.\n \"\"\"\n sql_path = os.path.join(_DAG_DIR, constants.PREDICTION_SQL_PATH)\n\n return bq_query.create_operator(\n parent_dag_id=_DAG_ID,\n dag=main_dag,\n sql_params=sql_params,\n sql_path=sql_path)\n\n\ndef create_dag() -> models.DAG:\n \"\"\"Creates Airflow DAG for prediction pipeline.\n\n This execture two workflows:\n 1. Generate BigQuery table with scoring dataset.\n 2. Execute BQML prediction job and save outputs as BigQuery table.\n\n Returns:\n main_dag: An instance of models.DAG.\n \"\"\"\n base_config = utils.get_airflow_variable_as_dict(constants.BASE_CONFIG)\n dag_schedule_interval = base_config['schedule_interval']\n dag_retries = constants.DAG_RETRIES\n dag_retry_delay = constants.DAG_RETRY_DELAY\n main_dag = utils.create_dag(_DAG_ID, dag_schedule_interval, dag_retries,\n dag_retry_delay)\n prediction_config = utils.get_airflow_variable_as_dict(\n constants.PREDICTION_PIPELINE_CONFIG)\n mlwp = constants.FeatureGenerator.MLWP\n if str(prediction_config['feature_generator']).lower() == mlwp.value:\n feature_generator = mlwp\n else:\n feature_generator = constants.FeatureGenerator.CUSTOM\n\n feature_generator_task = _create_prediction_feature_generator_task(\n main_dag=main_dag,\n feature_generator=feature_generator,\n sql_params=prediction_config['features_sql_params'])\n batch_predictor_task = _create_batch_predictor_task(\n main_dag=main_dag, sql_params=prediction_config['prediction_sql_params'])\n feature_generator_task.set_downstream(batch_predictor_task)\n\n return main_dag\n\n\nif os.getenv(constants.AIRFLOW_ENV):\n dag = create_dag()\n","sub_path":"dags/prediction_pipeline.py","file_name":"prediction_pipeline.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"241430514","text":"#!/usr/bin/python3\n# coding=utf-8\n\nimport sys\nfrom preprocessor import preprocess\nimport json\nimport re\nfrom collections import Counter\n\nif len(sys.argv) != 2:\n print(u\"usage: {},uc.file, \".format(__file__))\n exit(-1)\n\ndata_file = sys.argv[1]\nline_counter = 0\n# content_list = []\nwordcounter = Counter()\nwordcount = 0\nwordset = set()\npattern = re.compile(r\"\\w+\")\n# wordmap = {}\nwith open(data_file) as f:\n for line in f:\n splits = line.strip().split('\\t')\n assert len(splits) == 2, len(splits)\n content = splits[-1]\n preprocessed_content = preprocess(content)\n # print(preprocessed_content)\n # break\n word2count = {}\n for sent in preprocessed_content:\n for token in sent:\n if len(token) > 1 and re.fullmatch(pattern, token):\n if token not in word2count.keys():\n word2count[token] = 1\n wordset.add(token)\n wordcount += 1\n wordcounter += Counter(word2count)\n line_counter += 1\n if line_counter%1000 == 0:\n print(\"line count:{}, wordset size:{}\".format(line_counter, len(wordset)))\n print(\"wordcounter size:{}, word count:{}\".format(len(wordcounter), wordcount))\n # if line_counter == 10000:\n # break\nfor word in wordset:\n if wordcounter[word] < 10:\n del wordcounter[word]\n\nprint(\"sum of values of counter:\", sum(wordcounter.values()))\n\nprint(\"size of word2count:{}\".format(len(wordcounter)))\nwith open(\"data/word2count.json\", \"w\") as write_file:\n json.dump(wordcounter, write_file)","sub_path":"word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347393522","text":"def get_word(sentence, n):\n\tsentence=sentence.split()\n\tif len(sentence)>n and n>0:\n\t\treturn sentence[n-1]\n\telse:\n\t\tsentence=\"Nothing\"\n\t\treturn sentence\n\nprint(get_word(\"This is a lesson about lists\", 4)) # Should print: lesson\nprint(get_word(\"This is a lesson about lists\", -4)) # Nothing\nprint(get_word(\"Now we are cooking!\", 1)) # Should print: Now\nprint(get_word(\"Now we are cooking!\", 5)) # Nothing","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"488171780","text":"'''\nCreated on Mar 10, 2016\n\n@author: Mark Edwards\n'''\n\n\nif __name__ == '__main__':\n# import threading\n import multiprocessing\n import time\n from AdderServer import AdderRequestHandler, AdderServer\n import logging\n import socket\n \n\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"gmail.com\",80))\n ext_ip = s.getsockname()[0]\n s.close()\n logger = logging.getLogger('client')\n logger.info('My External IP is: %s', ext_ip)\n \n def start_server(server_args):\n address, o_list, server_id = server_args\n server = AdderServer(address, AdderRequestHandler, \n others_list= o_list, server_id=server_id,\n my_value=1)\n server.serve_forever()\n \n \n portlist = range(7771,7775)\n server_arg_list = [None]*len(portlist)\n \n for port_ind in range(len(portlist)):\n port = portlist[port_ind]\n address = ('localhost', port)\n o_list = [('localhost', x) for x in portlist[:port_ind] + portlist[port_ind+1:]]\n server_id = port_ind\n server_arg_list[port_ind] = (address, o_list, server_id)\n \n worker_pool = multiprocessing.Pool(len(portlist))\n worker_pool.map_async(start_server, server_arg_list)\n time.sleep(2) \n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('localhost', 7771)) \n s.send('1')\n s.close()\n worker_pool.close()\n worker_pool.join()\n \n \n ","sub_path":"Ring_Leadership_Algorithm/example1.py","file_name":"example1.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"181113310","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 5 12:20:49 2017\n\n@author: b5013167\n\"\"\"\n\n\n\"\"\" Filtering: Functions which enable filtering of UK Biobank data.\n\n Currently includes (Oct 17):\n \n -Filter_by_multiple\n -code2word\n -get_matched_sample (WIP)\n \n\n\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport time\nimport sys\nimport re\n\ndef cleanup(out_df,subset=None):\n \"\"\" Drop all nan rows, columns and duplicates\"\"\"\n \n if out_df is None:\n print(\"Dataframe is empty\")\n elif len(out_df)<1:\n out_df=None\n print(\"Dataframe is empty\")\n else: \n #out_df.dropna(axis=0, how='all',inplace=True, subset=subset)# drop if all columns in row are nan\n out_df.dropna(axis=1, how='all',inplace=True)# drop if all rows in column are nan\n out_df.drop_duplicates(inplace=True)#drop duplicate rows\n \n return out_df\n\n\n\ndef convert_list(i):\n \"\"\"convert strings to lists\"\"\"\n ls=[]\n if type(i)==str:\n ls.append(i)\n o=ls[:]\n else:\n o=i[:]\n \n return o\n \n\ndef code2word(ukbc, df=None): \n \"\"\" Converts numerical values in dataframe to text based upon UK biobank coding \"\"\"\n \n if df is not None: \n \n #dataframe to be returned\n out_df=df.copy()\n \n #Converting medication coding \n med_cols=out_df.filter(regex='Treatment/medication code').columns.tolist()#coding columns..\n \n #If medication code columns exist, then continue\n if len(med_cols)>0:\n codes_dict=ukbc.MedicationCodes.to_dict()['meaning']\n for col in med_cols:\n out_df[col].replace(codes_dict, inplace=True)\n \n \n #Converting illness coding \n illness_cols=[]\n \n illness_cols.extend(out_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist())\n \n \n #If illness code columns exist, then continue\n if len(illness_cols)>0:\n codes_dict=ukbc.IllnessCodes.to_dict()['meaning']\n codes_dict = {int(k):v for k,v in codes_dict.items()}#converting keys to int\n for col in illness_cols:\n out_df[col].replace(codes_dict, inplace=True)\n \n cancer_cols=[]\n cancer_cols.extend(out_df.filter(regex='Cancer code, self-reported').columns.tolist())\n \n #If cancer code columns exist, then continue\n if len(cancer_cols)>0:\n codes_dict=ukbc.CancerCodes.to_dict()['meaning']\n codes_dict = {int(k):v for k,v in codes_dict.items()}#converting keys to int\n for col in cancer_cols:\n out_df[col].replace(codes_dict, inplace=True)\n \n \n #TODO: continue to implement other types of coding (see UK biobank showcase)... \n \n #e.g.1 ethnic background.\n #e.g. 2\tJob SOC coding (data coding 2) (req download of coding file and assignment to ukbc object...)\n return out_df\n\n\n\ndef select_by_illness(ukbc, in_df=None, illness=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with given string of list of illnesses\n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n\n \n #If string given then convert to list\n illness=convert_list(illness)\n\n \n ill_codes=[]\n cancer_codes=[]\n for i in illness: \n #Gather illness code(s) codes must be list of int\n x=ukbc.IllnessCodes[ukbc.IllnessCodes==i]#illness codes\n x.dropna(inplace=True) \n \n y=ukbc.CancerCodes[ukbc.CancerCodes==i]#cancer codes\n y.dropna(inplace=True)\n \n if len(x)<0 and len(y)<0: \n raise Exception('Error: cannot find the illness: {0}. Please ensure that you are using medications exactly as specified in ''IllnessCodes or CancerCodes'''.format(i))\n \n #TODO: Currently this function will treat illnessess & cancer which share the same code as the same\n #How to overcome, include 'Cancer' flag' in function\n elif len(x)>0:\n ill_codes.append(int(x.index.tolist()[0]))\n else:\n cancer_codes.append(int(y.index.tolist()[0])) \n \n \n illness_df=ukbc.extract_many_vars(keywords=['Cancer code, self-reported','Non-cancer illness code, self-reported'],visit=visit,instance=instance)\n \n #selecting only illness columns\n cancer_cols_of_interest=illness_df.filter(regex='Cancer code, self-reported').columns.tolist()\n illness_cols_of_interest=illness_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist()\n \n \n #If the code is contained within df then append to out_df...\n include_rows=[]\n \n for c in ill_codes: \n #Is code in dataframe?\n bool_df=illness_df[illness_cols_of_interest]==c \n #If any element in a row is true, then include this row \n inc=bool_df[bool_df.any(axis=1)].index.tolist() \n include_rows.extend(inc)\n \n for c in cancer_codes: \n #Is code in dataframe?\n bool_df=illness_df[cancer_cols_of_interest]==c \n #If any element in a row is true, then include this row \n inc=bool_df[bool_df.any(axis=1)].index.tolist() \n include_rows.extend(inc)\n \n \n #Append included rows\n out_df=illness_df.loc[include_rows,:] \n \n cols_of_interest2=[]\n cols_of_interest2.extend(out_df.filter(regex='Cancer code, self-reported').columns.tolist())\n cols_of_interest2.extend(out_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist())\n \n #merge incoming dataframe\n if in_df is not None:\n cols_to_use=in_df.columns.difference(out_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = out_df.merge(in_df[cols_to_use],on='eid',how='inner')\n \n out_df=cleanup(out_df,subset=cols_of_interest2) \n \n \n return out_df\n\n\ndef select_by_illness_free(ukbc, in_df=None, illness=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with no record of a given list of medications\n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n \n #If string given then convert to list\n illness=convert_list(illness)\n \n \n ill_codes=[]\n cancer_codes=[]\n for i in illness: \n #Gather illness code(s) codes must be list of int\n x=ukbc.IllnessCodes[ukbc.IllnessCodes==i]#illness codes\n x.dropna(inplace=True) \n \n y=ukbc.CancerCodes[ukbc.CancerCodes==i]#cancer codes\n y.dropna(inplace=True)\n \n if len(x)<0 and len(y)<0: \n raise Exception('Error: cannot find the illness: {0}. Please ensure that you are using medications exactly as specified in ''IllnessCodes or CancerCodes'''.format(i))\n \n elif len(x)>0:\n ill_codes.append(int(x.index.tolist()[0]))\n else:\n cancer_codes.append(int(y.index.tolist()[0])) \n \n \n illness_df=ukbc.extract_many_vars(keywords=['Cancer code, self-reported','Non-cancer illness code, self-reported'],visit=visit,instance=instance)\n \n #selecting only illness columns\n cols_of_interest=[]\n cols_of_interest.extend(illness_df.filter(regex='Cancer code, self-reported').columns.tolist())\n cols_of_interest.extend(illness_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist())\n \n cancer_cols_of_interest=illness_df.filter(regex='Cancer code, self-reported').columns.tolist()\n illness_cols_of_interest=illness_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist()\n \n \n #If the code is contained within df then append to out_df...\n dont_include_rows=[]\n \n for c in ill_codes: \n #Is code in dataframe?\n bool_df=illness_df[illness_cols_of_interest]==c \n #If any element in a row is true, then include this row \n dont_inc=bool_df[bool_df.any(axis=1)].index.tolist() \n dont_include_rows.extend(dont_inc)\n \n for c in cancer_codes: \n #Is code in dataframe?\n bool_df=illness_df[cancer_cols_of_interest]==c \n #If any element in a row is true, then include this row \n dont_inc=bool_df[bool_df.any(axis=1)].index.tolist() \n dont_include_rows.extend(dont_inc)\n \n \n #Append included rows\n out_df=illness_df.drop(dont_include_rows)\n \n \n cols_of_interest2=[]\n cols_of_interest2.extend(out_df.filter(regex='Cancer code, self-reported').columns.tolist())\n cols_of_interest2.extend(out_df.filter(regex='Non-cancer illness code, self-reported').columns.tolist())\n \n #merge incoming dataframe\n if in_df is not None:\n \n #finding column which are present in in_df but not out_df, merging with out_df\n cols_to_use=in_df.columns.difference(out_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = out_df.merge(in_df[cols_to_use],on='eid',how='inner')\n \n \n out_df=cleanup(out_df,subset=cols_of_interest2)\n \n return out_df\n\n\ndef select_by_medication(ukbc, in_df=None, medication=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with given string of list of medications \"\"\"\n \n #If string given then convert to list\n medication=convert_list(medication)\n \n #Gather medication code(s) codes must be list of int\n codes=[]\n for i in medication: \n x=ukbc.MedicationCodes[ukbc.MedicationCodes==i]\n x.dropna(inplace=True)\n if len(x)<1:\n raise Exception('Error: cannot find the medication {0}. Please ensure that you are using medications exactly as specified in ''MedicationCodes'''.format(i))\n else:\n codes.append(int(x.index.tolist()[0]))\n \n \n medication_df=ukbc.extract_many_vars(keywords=['Treatment/medication code'],visit=visit,instance=instance)\n \n #selecting only illness columns -ugly workaround (basically we want to avoid including the demographics columns here (which are returned by the \n #above function by default. If an add_demographics() function is implemented then demographics=False can be implemeted above to circumvent this))\n cols_of_interest=[]\n cols_of_interest.extend(medication_df.filter(regex='Treatment/medication code').columns.tolist())\n \n #If the code is contained within df then append to out_df...\n include_rows=[]\n \n for c in codes: \n #Is code in dataframe?\n bool_df=medication_df[cols_of_interest]==c \n #If any element in a row is true, then include this row \n inc=bool_df[bool_df.any(axis=1)].index.tolist() \n include_rows.extend(inc)\n \n #Append included rows\n out_df=medication_df.loc[include_rows,:]\n \n cols_of_interest2=out_df.filter(regex='Treatment/medication code').columns.tolist() \n \n #merge incoming dataframe\n if in_df is not None:\n cols_to_use=in_df.columns.difference(out_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = out_df.merge(in_df[cols_to_use],on='eid',how='inner')\n \n \n out_df=cleanup(out_df,subset=cols_of_interest2)\n\n return out_df\n\n\n\ndef select_by_medication_free(ukbc, in_df=None, medication=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with no record of a given list of medications \n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n \n #If string given then convert to list\n medication=convert_list(medication)\n\n \n \n codes=[]\n for i in medication: \n #Gather medication code(s) codes must be list of int\n x=ukbc.MedicationCodes[ukbc.MedicationCodes==i]\n x.dropna(inplace=True)\n if len(x)<1:\n raise Exception('Error: cannot find that medication: {0}. Please ensure that you are using medications exactly as specified in ''MedicationCodes'''.format(i))\n else:\n codes.append(int(x.index.tolist()[0]))\n \n \n medication_df=ukbc.extract_many_vars(keywords=['Treatment/medication code'],visit=visit,instance=instance)\n \n #selecting only illness columns -ugly workaround (basically we want to avoid including the demographics columns here (which are returned by the \n #above function by default. If an add_demographics() function is implemented then demographics=False can be implemeted above to circumvent this))\n cols_of_interest=[]\n cols_of_interest.extend(medication_df.filter(regex='Treatment/medication code').columns.tolist())\n \n \n dont_include_rows=[]\n for c in codes: \n #Is code in dataframe?\n bool_df=medication_df[cols_of_interest]==c\n \n #If any element in a row is true, then DONT include this row\n dont_inc=bool_df[bool_df.any(axis=1)].index.tolist() \n \n dont_include_rows.extend(dont_inc)\n \n #Append included rows\n out_df=medication_df.drop(dont_include_rows)\n \n \n cols_of_interest2=out_df.filter(regex='Treatment/medication code').columns.tolist() \n \n #merge incoming dataframe\n if in_df is not None:\n \n #finding column which are present in in_df but not out_df, merging with out_df\n cols_to_use=in_df.columns.difference(out_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = out_df.merge(in_df[cols_to_use],on='eid',how='inner')\n \n \n out_df=cleanup(out_df,subset=cols_of_interest2)\n \n return out_df\n\n\n\n\n\n\n\n\ndef select_by_medications(ukbc, in_df=None, on_medication=None, off_medication=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with given string of list of medications \n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n \n if on_medication is not None and off_medication is not None: \n on_df=select_by_medication(ukbc=ukbc,in_df=in_df, medication=on_medication, visit=visit, instance=instance)\n off_df=select_by_medication_free(ukbc=ukbc,in_df=in_df, medication=off_medication, visit=visit, instance=instance)\n \n #Find common 'eids' between on and off dfs and merge\n #finding column which are present in in_df but not out_df, merging with out_df\n cols_to_use=on_df.columns.difference(off_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = off_df.merge(on_df[cols_to_use],on='eid',how='inner')\n \n elif on_medication is not None and off_medication is None:\n out_df=select_by_medication(ukbc=ukbc,in_df=in_df, medication=on_medication, visit=visit, instance=instance)\n\n elif on_medication is None and off_medication is not None:\n out_df=select_by_medication_free(ukbc=ukbc,in_df=in_df, medication=off_medication, visit=visit, instance=instance)\n \n else: \n ValueError('Error: you must specify either on_medication OR off_medication')\n out_df=None\n\n\n return out_df\n\ndef select_by_illnesses(ukbc, in_df=None, on_illness=None, off_illness=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with given string of list of illnesses\n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n \n if on_illness is not None and off_illness is not None: \n on_df=select_by_illness(ukbc=ukbc,in_df=in_df, illness=on_illness, visit=visit, instance=instance)\n off_df=select_by_illness_free(ukbc=ukbc,in_df=in_df, illness=off_illness, visit=visit, instance=instance)\n \n #Find common 'eids' between on and off dfs and merge. Finding column which are present in in_df but not out_df, merging with out_df\n cols_to_use=on_df.columns.difference(off_df.columns).tolist()\n cols_to_use.append('eid')\n out_df = off_df.merge(on_df[cols_to_use],on='eid',how='inner')\n \n elif on_illness is not None and off_illness is None:\n out_df=select_by_illness(ukbc=ukbc,in_df=in_df, illness=on_illness, visit=visit, instance=instance)\n\n elif on_illness is None and off_illness is not None:\n out_df=select_by_illness_free(ukbc=ukbc,in_df=in_df, illness=off_illness, visit=visit, instance=instance)\n \n else: \n ValueError('Error: you must specify either on_illness OR off_illness')\n out_df=None\n\n\n return out_df\n\n\n\n#TODO insert 'in_df' functionality into here\ndef select_by_multiple(ukbc, on_med=None,off_med=None, on_illness=None, off_illness=None, visit=None, instance=None): \n \"\"\" Returns a dataframe containing subjects with given illnesses and medications.\n NOTE: If a list [A,B,C] is supplied, then an instance is treated as if A OR B OR C is present \"\"\"\n \n \n to_merge=[]#collecting df's to merge\n\n \n if on_med is not None and len(on_med)>0:\n on_med_df=select_by_medication(ukbc=ukbc, medication=on_med, visit=visit, instance=instance)\n to_merge.append(on_med_df)\n \n if off_med is not None and len(off_med)>0:\n off_med_df=select_by_medication_free(ukbc=ukbc,medication=off_med, visit=visit, instance=instance)\n to_merge.append(off_med_df)\n \n if on_illness is not None and len(on_illness)>0:\n on_ill_df=select_by_illness(ukbc=ukbc, illness=on_illness, visit=visit, instance=instance)\n to_merge.append(on_ill_df)\n \n if off_illness is not None and len(off_illness)>0:\n off_ill_df=select_by_illness_free(ukbc=ukbc,illness=off_illness, visit=visit, instance=instance)\n to_merge.append(off_ill_df)\n \n \n #if any dataframes in 'to_merge' list are empty then drop them\n temp=to_merge[:]\n to_merge=[]\n for i in temp:\n if i is not None:\n if len(i)>0:\n to_merge.append(i)\n \n\n #Merging dataframes in to_merge list. Must be a simpler, cleaner way. Currenlty deciding which columns to use is v.messy . . .\n \n #if only one input option\n if len(to_merge)==1:\n out_df=to_merge[0].copy()\n \n #if two options selected\n elif len(to_merge)==2:\n cols1=to_merge[1].columns.difference(to_merge[0].columns).tolist()\n cols1.append('eid')\n out_df=to_merge[0].merge(to_merge[1][cols1],on='eid',how='inner')\n \n elif len(to_merge)==3:\n cols1=to_merge[1].columns.difference(to_merge[0].columns).tolist()\n cols1.append('eid')\n cols2=to_merge[2].columns.difference(to_merge[1].columns).tolist()\n cols2.append('eid')\n \n out_df=to_merge[0].merge(to_merge[1][cols1],on='eid',how='inner').merge(to_merge[2][cols2],on='eid',how='inner')\n \n elif len(to_merge)==4:\n cols1=to_merge[1].columns.difference(to_merge[0].columns).tolist()\n cols1.append('eid')\n cols2=to_merge[2].columns.difference(to_merge[1].columns).tolist()\n cols2.append('eid')\n cols3=to_merge[3].columns.difference(to_merge[2].columns).tolist()\n cols3.append('eid')\n \n out_df=to_merge[0].merge(to_merge[1][cols1],on='eid',how='inner').merge(to_merge[2][cols2],on='eid',how='inner').merge(to_merge[3][cols3],on='eid',how='inner')\n \n else:\n out_df=None\n #no illness/medication options chosen or results found \n\n out_df=cleanup(out_df)\n \n return out_df\n\n \ndef add_vars(ukbc, in_df=None, add_vars=None, visit=None, instance=None):\n \"\"\" Adds selected variables to the current dataframe \"\"\"\n \n if in_df is None or add_vars is None:\n ValueError('Error: you have failed to provide in_df and/or add_vars')\n out_df=None\n \n #extract variables #deleted: (but we dont want demographics columns)\n variables_df=ukbc.extract_many_vars(keywords=add_vars, visit=visit, instance=instance, demographics=False)\n \n #extract rows based on eids from in_df and all columns (except eid)\n in_eids=in_df['eid'] # gather encoded subject IDs\n rows=variables_df['eid'].isin(in_eids)\n variables_df=variables_df.loc[rows,:]\n \n #select only columns unique to variables_df\n cols_to_use=variables_df.columns.difference(in_df.columns).tolist()\n cols_to_use.append('eid')\n \n #join dataframes (variables_df and in_df)\n out_df=in_df.merge(variables_df[cols_to_use],on='eid',how='inner')\n \n out_df=cleanup(out_df)\n \n \n #TODO add option to rename this output file potentially..?\n #saving list of bulk fields requested if variable requested is bulk.\n if len(ukbc.bulk_request)>0:\n outtxt = open('bulk_fields.txt', 'w')\n for subj in out_df['eid']:\n for item in ukbc.bulk_request:\n outtxt.write(\"%s %s\\n\" % (subj, item))\n outtxt.close()\n print(\"You have requested bulk fields in your add variables, these are being saved to bulk_fields.txt and can be downloaded from Ukbiobank using ukbfetch\" )\n \n \n \n \n return out_df\n\n\n\n\ndef get_illness_code(ukbc, text_in):\n \"\"\"Returns illness code\n given text input\"\"\"\n \n codes_dict=ukbc.IllnessCodes\n code=codes_dict[codes_dict['meaning']==text_in].index.tolist()[0]\n\n return code\n\n#TODO: add functions which add variables to a new 'addvariables' document\n#Work in progress . . .\ndef initial_diagnosis(ukbc, in_df=None, illness=None, visit=None, instance=None):\n \"\"\" Adds a column labelling Year and Age of first diagnosis for selected illnesses.\n Illness is expected as text, e.g. 'depression', (not corresponding code)\"\"\"\n \n \n out_df=in_df.copy()\n \n #getting initial diagnosis year and age of participans\n for v in ['Year','Age of participant']:\n \n #If string given then convert to list\n illness=convert_list(illness)\n \n \"\"\"find code (or string) in in_df\"\"\"\n \n #get non cancer illness columns\n cols=out_df.filter(regex='Non-cancer illness code, self-reported')\n cols=cols.columns.tolist()\n \n \n #1. check that interpolated diagnosis year column exists, if not then request it\n if len(out_df.filter(regex='Interpolated '+v+' when non-cancer illness first diagnosed').columns)<1:\n out_df=add_vars(ukbc, in_df=out_df, add_vars='Interpolated '+v+' when non-cancer illness first diagnosed')\n \n \n \n #for each illness identify column\n for i in illness:\n \n \n #get code for illness\n illness_code=get_illness_code(ukbc,i)\n \n #creating dict to store year of diagnosis variable\n var_name=i+'_'+v+'_first_diagnosed'\n res_dict={'eid':[],var_name:[]}\n \n #iterrate over each row in df\n for row in out_df.iterrows():\n \n #get columns with matching code\n matching_columns=row[1][row[1]==illness_code].index.tolist()\n \n \n #TODO: #NOTE only one value for 'INterpolated year..' wil be generated. TODO: If two different values exist then the mean will be taken\n if len(matching_columns)>0:\n \n c=matching_columns[0]\n \n found=re.findall('(.*)_(\\d+).(\\d+)',c)\n visit=found[0][1]\n instance=found[0][2]\n \n #extract intial diagnosis year based upon year and instance\n initial_diagnosis_year=row[1]['Interpolated '+v+' when non-cancer illness first diagnosed_'+str(visit)+'.'+str(instance)]\n eid=row[1]['eid']\n \n #create variable\n res_dict['eid'].append(eid)\n res_dict[var_name].append(initial_diagnosis_year) \n \n \n new_df=pd.DataFrame.from_dict(res_dict)\n \n #for each illness merge latest new_df with in_df on 'eid' \n out_df=out_df.merge(new_df,on='eid',how='outer')\n \n out_df=cleanup(out_df)\n \n return out_df\n\n\n\n\n\n#Work in progress . . .\ndef get_matched_sample(ukbc, to_match=None, off_illness=None, off_med=None, visit=None, num_samples=1): \n \"\"\" This function aims to return a dataframe returning a matched sample according with\n same M/F and same age distribution and allows the user to specificy illnesses NOT\n to be contained within the sample\n \n The returned sample will differ each time as the sampling df is shuffled\"\"\"\n \n if visit is None:\n sys.exit('You must provide a visit so that the sample can be age matched for the target visit')\n \n\n \n \n #getting dataframe free from illness (to gather matched sample from)\n if off_illness is not None and off_med is not None:\n off_ill_df=select_by_illness_free(ukbc,illness=off_illness,visit=visit)\n off_med_df=select_by_medication_free(ukbc, medication=off_med, visit=visit)\n df=off_ill_df.merge(off_med_df, how='inner')\n elif off_illness is not None:\n df=select_by_illness_free(ukbc,illness=off_illness,visit=visit)\n elif off_med is not None:\n df=select_by_medication_free(ukbc, medication=off_med,visit=visit)\n else:\n df=ukbc.gather_related_vars()\n \n #for each sample \n matched_samples=[]\n for sample in range(num_samples):\n \n #shuffling healthy df\n df=df.sample(frac=1)\n \n #df to store out matched sample\n out_df=pd.DataFrame()\n \n #Gathering M/F age information for current distribution\n currentSexAge=[]\n for row in to_match.iterrows():\n currentSexAge.append((row[1][\"Age when attended assessment centre_\"+str(visit)+\".0\"],row[1][\"Sex_0.0\"]))\n \n #could remove timeout\n timeout = time.time() + 60 #times out after 1 minute\n \n \n #gathering matched sample from 'df'\n covered_rows=[]\n \n #cycling through each requirement, e.g.30yrs Female...\n for targetSexAge in currentSexAge:\n \n moveOn=False\n \n \n if time.time()>timeout:\n sys.exit('Error: Couldn''t find a sample matching your AGE criteria')\n \n \n #checking each row in the ill/med free df\n for i,row in enumerate(df.iterrows()):\n \n \n #while a match has not been found\n if moveOn is False:\n \n #if current row has not already been selected\n if i not in covered_rows:\n \n #if current row matches requirements \n if (row[1][\"Age when attended assessment centre_\"+str(visit)+\".0\"] == targetSexAge[0]) & (row[1][\"Sex_0.0\"] == targetSexAge[1]):\n \n #append row to out df\n out_df=out_df.append(row[1])\n \n #make sure this row isn't re-used\n covered_rows.append(i)\n \n #Pass onto next target sexAge\n moveOn=True\n\n matched_samples.append(out_df)\n \n \n return matched_samples","sub_path":"ukbc/ukbc_functions/Filtering.py","file_name":"Filtering.py","file_ext":"py","file_size_in_byte":27806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"379084702","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport random \nimport numpy as np\nimport math\nimport sys\nimport random\nimport time\nfrom numpy import random\n\n\n# In[3]:\nfile_arg = sys.argv[1]\n\ndef svm_tree_parse(filepath):\n l = []\n new_l = []\n\n with open(filepath,'r') as file:\n for line in file:\n row = line.split('\\n')\n l.append(row)\n\n l = [i[0].strip('')for i in l] \n\n for i in l:\n new_l.append(i.split(','))\n\n x = [[int(float(j)) for j in i] for i in new_l]\n\n for i in range(len(x)):\n if x[i][-1]==0:\n x[i][-1]=-1\n\n\n return np.array(x) \n\n\ndef acc_check_bagged(x_train):\n label = []\n mistake = 0\n for i in x_train:\n count_pos = 0\n count_neg = 0\n for j in i[:len(i)-1]:\n if j ==1:\n count_pos += 1\n else:\n count_neg += 1 \n #print(count_pos)\n #print(count_neg)\n if count_pos>=count_neg:\n label.append(1)\n elif count_pos;\n [[builtin(position)]] pos: vec4;\n };\n\n [[group(0), binding(1)]]\n var r_sampler: sampler;\n [[group(0), binding(2)]]\n var r_tex: texture_2d;\n\n [[stage(vertex)]]\n fn vs_main([[builtin(vertex_index)]] index: u32) -> VertexOutput {\n var positions = array, 4>(vec2(0.0, 1.0), vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0));\n let pos = positions[index];\n var out: VertexOutput;\n out.texcoord = vec2(pos.x, 1.0 - pos.y);\n out.pos = vec4(pos * 2.0 - 1.0, 0.0, 1.0);\n return out;\n }\n\n [[stage(fragment)]]\n fn fs_main(in: VertexOutput) -> [[location(0)]] vec4 {\n // Get info about the smoothing\n let sigma = u_render.sigma;\n let support = min(5, u_render.support);\n\n // Determine distance between pixels in src texture\n let stepp = vec2(1.0 / u_render.size.x, 1.0 / u_render.size.y);\n // Get texcoord, and round it to the center of the source pixels.\n // Thus, whether the sampler is linear or nearest, we get equal results.\n var tex_coord = in.texcoord.xy;\n {{ tex_coord_map }}\n let ref_coord = vec2(vec2(tex_coord / stepp)) * stepp + 0.5 * stepp;\n\n // Convolve. Here we apply a Gaussian kernel, the weight is calculated\n // for each pixel individually based on the distance to the actual texture\n // coordinate. This means that the textures don't even need to align.\n var val: vec4 = vec4(0.0, 0.0, 0.0, 0.0);\n var weight: f32 = 0.0;\n for (var y:i32 = -support; y <= support; y = y + 1) {\n for (var x:i32 = -support; x <= support; x = x + 1) {\n let coord = ref_coord + vec2(f32(x), f32(y)) * stepp;\n let dist = length((tex_coord - coord) / stepp); // in src pixels\n let t = dist / sigma;\n let w = exp(-0.5 * t * t);\n val = val + textureSample(r_tex, r_sampler, coord) * w;\n weight = weight + w;\n }\n }\n var out = val / weight;\n {{ color_map }}\n return out;\n }\n \"\"\"\n )\n\n\nclass RenderFlusher:\n \"\"\"\n Utility to flush (render) the current state of a renderer into a texture.\n \"\"\"\n\n # todo: Once we also have the depth here, we can support things like fog\n\n uniform_type = dict(\n size=\"2xf4\",\n sigma=\"f4\",\n support=\"i4\",\n )\n\n def __init__(self, device):\n self._shader = FinalShader()\n self._device = device\n self._pipelines = {}\n\n self._uniform_data = array_from_shadertype(self.uniform_type)\n self._uniform_buffer = self._device.create_buffer(\n size=self._uniform_data.nbytes,\n usage=wgpu.BufferUsage.UNIFORM | wgpu.BufferUsage.COPY_DST,\n )\n\n self._sampler = self._device.create_sampler(\n label=\"render sampler\",\n mag_filter=\"nearest\",\n min_filter=\"nearest\",\n )\n\n def render(self, src_color_tex, src_depth_tex, dst_color_tex, dst_format):\n \"\"\"Render the (internal) result of the renderer into a texture.\"\"\"\n # NOTE: cannot actually use src_depth_tex as a sample texture (BindingCollision)\n assert src_depth_tex is None\n assert isinstance(src_color_tex, wgpu.base.GPUTextureView)\n assert isinstance(dst_color_tex, wgpu.base.GPUTextureView)\n\n # Recreate pipeline? Use ._internal as a true identifier of the texture view\n hash = src_color_tex.size, src_color_tex._internal\n stored_hash = self._pipelines.get(dst_format, [\"invalidhash\"])[0]\n if hash != stored_hash:\n bind_group, render_pipeline = self._create_pipeline(\n src_color_tex, dst_format\n )\n self._pipelines[dst_format] = hash, bind_group, render_pipeline\n\n self._update_uniforms(src_color_tex, dst_color_tex)\n self._render(dst_color_tex, dst_format)\n\n def _update_uniforms(self, src_color_tex, dst_color_tex):\n # Get factor between texture sizes\n factor_x = src_color_tex.size[0] / dst_color_tex.size[0]\n factor_y = src_color_tex.size[1] / dst_color_tex.size[1]\n factor = (factor_x + factor_y) / 2\n\n if factor > 1:\n # The src has higher res, we can do ssaa.\n sigma = 0.5 * factor\n support = min(5, int(sigma * 3))\n else:\n # The src has lower res, interpolate + smooth.\n # Smoothing a bit more helps reduce the blockiness.\n sigma = 1\n support = 2\n\n self._uniform_data[\"size\"] = src_color_tex.size[:2]\n self._uniform_data[\"sigma\"] = sigma\n self._uniform_data[\"support\"] = support\n\n def _render(self, dst_color_tex, dst_format):\n device = self._device\n _, bind_group, render_pipeline = self._pipelines[dst_format]\n\n command_encoder = device.create_command_encoder()\n\n tmp_buffer = device.create_buffer_with_data(\n data=self._uniform_data,\n usage=wgpu.BufferUsage.COPY_SRC,\n )\n command_encoder.copy_buffer_to_buffer(\n tmp_buffer, 0, self._uniform_buffer, 0, self._uniform_data.nbytes\n )\n\n render_pass = command_encoder.begin_render_pass(\n color_attachments=[\n {\n \"view\": dst_color_tex,\n \"resolve_target\": None,\n \"load_value\": (0, 0, 0, 0), # LoadOp.load or color\n \"store_op\": wgpu.StoreOp.store,\n }\n ],\n depth_stencil_attachment=None,\n occlusion_query_set=None,\n )\n render_pass.set_pipeline(render_pipeline)\n render_pass.set_bind_group(0, bind_group, [], 0, 99)\n render_pass.draw(4, 1)\n render_pass.end_pass()\n device.queue.submit([command_encoder.finish()])\n\n def _create_pipeline(self, src_texture_view, dst_format):\n\n device = self._device\n\n shader = self._shader\n shader.define_uniform(\n 0, 0, Binding(\"u_render\", \"buffer/uniform\", self._uniform_data.dtype)\n )\n shader_module = device.create_shader_module(code=shader.generate_wgsl())\n\n binding_layouts = [\n {\n \"binding\": 0,\n \"visibility\": wgpu.ShaderStage.FRAGMENT,\n \"buffer\": {\"type\": wgpu.BufferBindingType.uniform},\n },\n {\n \"binding\": 1,\n \"visibility\": wgpu.ShaderStage.FRAGMENT,\n \"sampler\": {\"type\": wgpu.SamplerBindingType.filtering},\n },\n {\n \"binding\": 2,\n \"visibility\": wgpu.ShaderStage.FRAGMENT,\n \"texture\": {\n \"sample_type\": wgpu.TextureSampleType.float,\n \"view_dimension\": wgpu.TextureViewDimension.d2,\n \"multisampled\": False,\n },\n },\n ]\n bindings = [\n {\n \"binding\": 0,\n \"resource\": {\n \"buffer\": self._uniform_buffer,\n \"offset\": 0,\n \"size\": self._uniform_data.nbytes,\n },\n },\n {\"binding\": 1, \"resource\": self._sampler},\n {\"binding\": 2, \"resource\": src_texture_view},\n ]\n\n bind_group_layout = device.create_bind_group_layout(entries=binding_layouts)\n pipeline_layout = device.create_pipeline_layout(\n bind_group_layouts=[bind_group_layout]\n )\n bind_group = device.create_bind_group(\n layout=bind_group_layout, entries=bindings\n )\n\n render_pipeline = device.create_render_pipeline(\n layout=pipeline_layout,\n vertex={\n \"module\": shader_module,\n \"entry_point\": \"vs_main\",\n \"buffers\": [],\n },\n primitive={\n \"topology\": wgpu.PrimitiveTopology.triangle_strip,\n \"strip_index_format\": wgpu.IndexFormat.uint32,\n },\n depth_stencil=None,\n multisample=None,\n fragment={\n \"module\": shader_module,\n \"entry_point\": \"fs_main\",\n \"targets\": [\n {\n \"format\": dst_format,\n \"blend\": {\n \"alpha\": (\n wgpu.BlendFactor.one,\n wgpu.BlendFactor.zero,\n wgpu.BlendOperation.add,\n ),\n \"color\": (\n wgpu.BlendFactor.src_alpha,\n wgpu.BlendFactor.one_minus_src_alpha,\n wgpu.BlendOperation.add,\n ),\n },\n }\n ],\n },\n )\n\n return bind_group, render_pipeline\n","sub_path":"pygfx/renderers/wgpu/_renderutils.py","file_name":"_renderutils.py","file_ext":"py","file_size_in_byte":10664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"267517935","text":"import pygame\nfrom pygame.locals import *\nimport sys\n\ndef main():\n window = pygame.display.set_mode((400,400))\n pygame.display.set_caption(\"Pygame\")\n\n # Podemos crear un rectangulo en pygame con una clase\n rectangle = pygame.Rect(0,0,100,50)\n rectangle2 = pygame.Rect(150,350,100,50)\n \n pos_x = 150\n pos_y = 350\n velocity = 0.2\n\n move_right:bool = True\n \n while True:\n window.fill((255,255,255))\n pygame.draw.rect(window,(0,128,0),rectangle2)\n pygame.draw.rect(window,(0, 128, 0),rectangle)\n \n # obtenere la posción del mouse en una tupal\n actually_pos_mouse:tuple = pygame.mouse.get_pos() # x, y mouse\n\n rectangle.left = actually_pos_mouse[0] # coordenada en x \n rectangle.top = actually_pos_mouse[1] # coordenada en y\n \n # COLISIONES ENTRE RECTANGULOS\n \n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n \n if move_right:\n if pos_x < 300:\n pos_x += velocity\n rectangle2.left = pos_x\n else:\n move_right = False\n else:\n if pos_x > 0:\n pos_x -= velocity\n rectangle2.left = pos_x\n else:\n move_right = True\n \n if rectangle2.colliderect(rectangle):\n velocity = 0\n\n pygame.display.update()\n \n\n\nif __name__ == '__main__':\n pygame.init()\n main()","sub_path":"pygame/basico/7_colisiones.py","file_name":"7_colisiones.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544596690","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 17 16:29:43 2019\n\n@author: Administrator\n边际检测 Canny\n阀值化 threshold\n边缘 findContours\n侵蚀 erode\n膨胀 dilate\n位运算 bitwise_and,bitwise_or/xor/not\n旋转 getRotationMatrix2D\n高斯模糊 GaussianBlur\n矩形 rectangle\n圆形实心 circle\n直线 line\n文字 putText\ngetPerspectiveTransform\nwarpPerspective\narcLength\napproxPolyDP\n\"\"\"\n\nimport cv2 as cv\nfrom . import convenience\n\ndef main():\n img = cv.imread('sp.jpg')\n #print(type(img))\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n edge = cv.Canny(gray,30,150)\n mo='edge'\n cv.namedWindow(mo, cv.WINDOW_NORMAL)\n cv.resizeWindow(mo, 200,200)\n ts = cv.threshold(gray, 225, 255, cv.THRESH_BINARY_INV)[1]\n findc = ts.copy()\n contours0 = cv.findContours(findc, \n cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n #contours = [cv.approxPolyDP(cnt, 3, True) for cnt in contours0]\n# outp = img.copy()\n# for c in len(contours0):\n# cv.drawContours(outp, [c], -1, (240,0,193),3)\n# cv.imshow(\"contours\",outp)\n# cv.waitkey(0)\n #print(contours0)\n #print(len(contours0))\n \n #cv.imshow('threshold',ts)\n mask = ts.copy()\n #mask = cv.erode(mask, None, iterations=5)\n mask = cv.dilate(mask, None, iterations=5)\n output = cv.bitwise_or(img, img, mask=mask)\n cv.imshow(\"Output\", output)\n cv.imshow(mo,mask)\n cv.waitKey(0)\n\ndef test():\n path = \"20190218170703.png\"\n img = cv.imread(path)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n gray = cv.GaussianBlur(gray, (5,5),0)\n edged = cv.Canny(gray, 75, 200)\n \n \nif (__name__ == \"__main__\"):\n main()\n","sub_path":"open_cv/count_object.py","file_name":"count_object.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"596188935","text":"\"\"\"\nThis is the testing for basic model CRUD\n\"\"\"\nimport nose\nfrom sqlalchemy.exceptions import *\nfrom demisauce.tests import *\nfrom demisauce import model\nfrom demisauce.model import mapping, meta\nfrom demisauce.model import cms, site, email, person, \\\n help, group, poll, tag\nfrom demisauce.model.help import helpstatus\n\n\nclass TestHelp(TestController):\n def test_help(self):\n h = help.Help(site_id=1,email='guest@demisauce.org')\n h.url = '/yourfolder/path'\n h.content = 'user comment goes here'\n h.save()\n h2 = help.Help.get(1,h.id)\n assert h.id == h2.id\n p = person.Person.get(1,1)\n hr = help.HelpResponse(help_id=h.id, site_id=1,person_id=p.id)\n hr.status = helpstatus['completed']\n assert hr.site_id == 1\n hr.url = h.url\n hr.title = 'title of response'\n hr.response = 'testing response'\n h.helpresponses.append(hr)\n # add tag portion\n tag1 = tag.Tag(tag='test',person=p)\n h.tags.append(tag1)\n \n h.save()\n assert tag1.id > 0\n tag2 = h.tags[0]\n assert tag2.value == 'test'\n assert tag2.assoc_id > 0\n assert tag2.association.type == 'help'\n assert hr.id > 0, 'should have saved'\n hr2 = help.HelpResponse.get(1,hr.id)\n assert hr2.response == 'testing response'\n assert hr2.url == '/yourfolder/path'\n h3 = help.Help.get(1,h.id)\n hr3 = h3.helpresponses[0]\n assert hr3.response == hr2.response\n \n","sub_path":"demisauce/trunk/demisauce/tests/test_help.py","file_name":"test_help.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"632064394","text":"# If we want to match the same pattern for multiple times, we usually pre-compile regular expressions into pattern objects.\n\nimport re\n\ndatepat = re.compile(r'\\d+/\\d+/\\d+')\n\n# If we want to find all the matching part, use findall()\n\ntext = 'Today is 5/5/2016. PyCon starts 3/13/2013.'\n\nprint (datepat.findall(text))\n","sub_path":"2_string_text/4_match_and_search_for_text_patterns/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"474152223","text":"import datetime\nimport calendar\nimport csv\nimport sys\nfrom io import BytesIO, StringIO\n\nfrom flask import render_template, request, url_for, Response, redirect, abort\nfrom flask_babel import gettext\n\nfrom . import app, tryton, cache\nfrom . import util\nfrom .compat import HTTPStatus\n\nPER_PAGE = 4 * 5\n\nCategory = tryton.pool.get('product.webshop.category')\nCountry = tryton.pool.get('country.country')\nProduct = tryton.pool.get('product.product')\n\n\n@app.route(\n '//category/all')\n@app.route(\n '//category/')\n@app.route(\n '//category'\n '//')\n@tryton.transaction()\ndef category(category=None, name=None):\n if category and util.slugify(category.name) != name:\n return redirect(util.url_for_category(category, **request.args))\n try:\n page = int(request.args.get('page', 1))\n except ValueError:\n abort(HTTPStatus.BAD_REQUEST)\n if page < 1:\n abort(HTTPStatus.BAD_REQUEST)\n search_args = dict(\n names=request.args.getlist('name'),\n category=category.id if category else None,\n made_in=request.args.getlist('made_in'),\n organic=request.args.get('organic'),\n available=request.args.getlist('available'),\n season=request.args.getlist('season'),\n )\n count = search_product(**search_args, order_by=[], count=True)\n products = search_product(\n **search_args,\n order_by=request.args.getlist('order_by') or ['name'],\n offset=(page - 1) * PER_PAGE,\n limit=PER_PAGE)\n\n sale = util.get_session_sale()\n if sale:\n currency = sale.currency\n else:\n currency = util.get_company().currency\n sale_prices, quantity_prices = util.get_all_sale_prices(products)\n dataLayer = [{\n 'ecommerce': {\n 'currencyCode': currency.code,\n 'impressions': [{\n 'name': p.name,\n 'id': str(p.id),\n 'price': str(sale_prices[p.id]),\n 'position': i,\n } for i, p in enumerate(products, 1)],\n },\n }]\n pagination = util.Pagination(page, PER_PAGE, count)\n return render_template('category.html',\n pagination=pagination,\n category=category,\n products=products,\n countries=countries(),\n filters=filters,\n sale_prices=sale_prices,\n quantity_prices=quantity_prices,\n dataLayer=dataLayer)\n\n\n@app.route('//category/all/facebook.csv')\n@app.route('//category'\n '//facebook.csv')\n@cache.cached(timeout=60 * 60)\n@tryton.transaction()\ndef facebook(category=None):\n if sys.version_info < (3,):\n data = BytesIO()\n encode = lambda s: s.encode('utf-8') # noqa: E731\n else:\n data = StringIO()\n encode = lambda s: s # noqa: E731\n products = search_product(category=category, available=[True, False])\n reference_prices = util.get_sale_prices_reference(products)\n sale_prices = util.get_sale_prices(products)\n company = util.get_company()\n currency = company.currency\n\n shipping = []\n codes = app.config.get('COUNTRIES', [])\n countries = Country.search([('code', 'in', codes)])\n for country in countries:\n carriers = util.available_carriers(country)\n for carrier in carriers:\n price, currency = util.compute_carrier_cost(carrier)\n shipping.append(\n '%(country)s::%(carrier)s:%(price)s %(currency)s' % {\n 'country': country.code,\n 'carrier': carrier.carrier_product.name,\n 'price': price,\n 'currency': currency.code,\n })\n shipping = ','.join(shipping)\n\n fieldnames = [\n # Required\n 'id', 'availability', 'condition', 'description', 'image_link', 'link',\n 'title', 'price', 'brand',\n # Optional\n 'product_type', 'sale_price', 'shipping',\n 'custom_label_0', 'custom_label_1',\n ]\n writer = csv.DictWriter(data, fieldnames=fieldnames)\n writer.writeheader()\n for product in products:\n if product.available and product.available_quantity != 'out':\n availability = 'in stock'\n else:\n availability = 'out of stock'\n writer.writerow({\n 'id': encode(product.code[:100]),\n 'availability': availability,\n 'condition': 'new',\n 'description': encode(\n (product.description or product.name\n )[:5000]),\n 'image_link': encode(util.url_for_product_image(\n product, _external=True)),\n 'link': encode(util.url_for_product(product, _external=True)),\n 'title': encode(product.name),\n 'price': encode('%s %s' % (\n currency.round(\n reference_prices[product.id]), currency.code)),\n 'brand': \"Jurassic Fruit\",\n 'product_type': encode(\n product.webshop_categories[0].rec_name),\n 'sale_price': encode('%s %s' % (\n currency.round(\n sale_prices[product.id]), currency.code)),\n 'shipping': shipping,\n 'custom_label_0': (\n gettext(\"Organic\") if product.organic else \"\"),\n 'custom_label_1': (\n gettext(\"From %(country)s\", country=product.made_in.name)\n if product.made_in else \"\"),\n })\n return Response(data.getvalue(), mimetype='text/csv')\n\n\ndef search_product(\n names=None, category=None, made_in=None, organic=None, available=None,\n season=None, order_by=None, offset=0, limit=None, count=False):\n domain = [\n ('salable', '=', True),\n ('type', '=', 'goods'),\n ]\n if names:\n if len(names) == 1:\n name, = names\n domain.append(('name', 'ilike', '%' + name + '%'))\n else:\n domain_name = ['OR']\n for name in names:\n domain_name.append(('name', 'ilike', '%' + name + '%'))\n domain.append(domain_name)\n if category:\n domain.append(('webshop_categories', '=', int(category)))\n else:\n domain.append(('webshop_categories', '!=', None))\n if made_in:\n domain.append(('made_in', 'in', made_in))\n if organic:\n domain.append(('organic', '=', True))\n available = set(map(bool, available or [True]))\n if len(available) == 1:\n available, = available\n available_domain = []\n domain.append(available_domain)\n available_domain.append(('available', '=', available))\n available_domain.append(\n ('available_quantity', '!=' if available else '=', 'out'))\n if not available:\n available_domain.insert(0, 'OR')\n if season:\n season = [s if s else None for s in season]\n month = datetime.date.today().month\n name = 'season_%s' % calendar.month_name[month].lower()\n domain.append((name, 'in', season))\n\n if order_by:\n order = [(c, 'ASC') for c in order_by]\n else:\n order = None\n return Product.search(\n domain, order=order, offset=offset, limit=limit, count=count)\n\n\ndef filters(sale=None, category=None):\n def url(name, value):\n args = {}\n for key in request.args:\n if key in {'sale', 'category'}:\n continue\n values = request.args.getlist(key)[:]\n if key == name:\n values.remove(value)\n if values:\n args[key] = values\n return url_for(request.endpoint, sale=sale, category=category, **args)\n\n for key in request.args:\n values = request.args.getlist(key)\n for value in values:\n if key == 'name':\n name = value\n elif key == 'made_in':\n name = Country(int(value)).rec_name\n elif key == 'organic' and value:\n name = gettext(\"Bio\")\n elif key == 'available':\n if value:\n name = gettext(\"Available\")\n else:\n name = gettext(\"Unavailable\")\n elif key == 'season':\n if not value:\n name = gettext(\"Out of season\")\n else:\n name = {\n 'low': gettext(\"Low season\"),\n 'high': gettext(\"High season\"),\n }.get(value, value)\n elif key == 'order_by':\n column = {\n 'name': gettext(\"Name\"),\n }.get(value, value)\n name = gettext(\"Sort by: %(column)s\", column=column)\n else:\n continue\n yield name, key, url(key, value)\n\n\n@cache.cached(timeout=24 * 60 * 60)\ndef countries():\n products = Product.search([('made_in', '!=', None)])\n return [{'id': c.id, 'rec_name': c.rec_name} for c in sorted(\n set(p.made_in for p in products), key=lambda c: c.rec_name)]\n","sub_path":"fruit/webshop/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":9348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"473588789","text":"from django.shortcuts import render, redirect, reverse\nfrom django.views.generic import View\nfrom .forms import LearnRegisterForm\nfrom .models import SubjectKeyModel, LearnTimeModel\nfrom .pygra import OutputGra\n# Create your views here.\n\nfile_name = 'static/learn/static.png'\n\n\nclass LearnRegisterView(View):\n def get(self, request, *args, **kwargs):\n form = LearnRegisterForm()\n context = {\n 'form': form\n }\n return render(request, 'learn/register.html', context)\n\n\nclass LearnGlaView(View):\n def get(self, request, *args, **kwargs):\n form = LearnRegisterForm()\n\n context = {\n 'form': form\n }\n return render(request, 'learn/view.html', context)\n\n\nLearnRegister = LearnRegisterView.as_view\n\n\nclass LearnRegisterDBView(View):\n def get(self, request, *args, **kwargs):\n key = request.GET.get('learn_subject_key')\n\n ful = LearnTimeModel.objects.filter(learn_subject_key=key)\n f = LearnTimeModel()\n x = f.make_data_date(ful)\n y = f.make_data_time(ful)\n making = OutputGra(x, y, file_name)\n making.file_remove()\n making.make_bar()\n\n context = {\n 'fil': ful,\n\n }\n return render(request, 'learn/display.html', context)\n\n\nclass LearnSaveView(View):\n def post(self, request, *args, **kwargs):\n form = LearnRegisterForm(request.POST)\n is_valid = form.is_valid()\n if not is_valid:\n pass\n form.save()\n\n return redirect(reverse('learn:register'))\n\n\n\n\n","sub_path":"proces/glaphApp/learn/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"69005272","text":"import logging\nimport inspect\nimport json\n\n\nclass Message(object):\n \"\"\" Message generic class \"\"\"\n\n def __str__(self):\n \"\"\"\n Overrides the str() operator and converts\n the message into a UTF-8 JSON string\n \"\"\"\n\n return json.dumps({\n attr: getattr(self, attr)\n for attr in self.__dir__()\n if not attr.startswith('_')\n and not inspect.ismethod(getattr(self, attr))\n }).replace('\\n', ' ')\n\n def __bytes__(self):\n \"\"\"\n Overrides the bytes() operator, converts the message into\n its JSON-serialized UTF-8-encoded representation\n \"\"\"\n return str(self).encode('utf-8')\n\n @classmethod\n def parse(cls, msg):\n \"\"\"\n Parse a generic message into a key-value dictionary\n Params:\n msg -- Original message - can be a dictionary, a Message,\n or a string/bytearray, as long as it's valid UTF-8 JSON\n \"\"\"\n\n if isinstance(msg, cls):\n msg = str(msg)\n if isinstance(msg, bytes) or isinstance(msg, bytearray):\n msg = msg.decode('utf-8')\n if isinstance(msg, str):\n try:\n msg = json.loads(msg.strip())\n except:\n logging.warning('Invalid JSON message: {}'.format(msg))\n\n assert isinstance(msg, dict)\n return msg\n\n @classmethod\n def build(cls, msg):\n \"\"\"\n Builds a Message object from a dictionary.\n Params:\n msg -- The message as a key-value dictionary, Message object or JSON string\n \"\"\"\n from platypush.utils import get_message_class_by_type\n\n\n msg = cls.parse(msg)\n msgtype = get_message_class_by_type(msg['type'])\n if msgtype != cls: return msgtype.build(msg)\n\n# vim:sw=4:ts=4:et:\n\n","sub_path":"platypush/message/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"405734748","text":"import h5py\nimport pandas as pd\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.signal\n\ndef read_met_data(dfile):\n df_snow=pd.read_csv(dfile,sep='\\s+')\n [m,n]=df_snow.shape\n print ('matrix dimensions:',m,n)\n\n df_time = pd.DataFrame({'year': df_snow.Year.values,\n 'month': df_snow.Mon.values,\n 'day': df_snow.Day.values,\n 'hour': df_snow.Hour.values})\n df_time=pd.to_datetime(df_time)\n frames = [df_time, df_snow.iloc[:, 4:]]\n df_data = pd.concat(frames, axis=1)\n df_data.columns = [\"Time\", \"Tair\", \"U\", \"Uang\", \"So_d\", \n \"So_u\", \"rain\", \"snowD\", \"Tg5cm\", \"Tg10cm\", \"Tg15cm\", \"Tg20cm\",\n \"Tg25cm\", \"Tg30cm\", \"Tg45cm\", \"Tg70cm\", \"Tg95cm\", \"Tg120cm\", \"Smoist\"]\n return df_data\n\ndef plot_met_data(ddata):\n fig, axs = plt.subplots(4, 2, figsize=(10, 6))\n axs[0, 0].plot(ddata['Time'],ddata['Tair'])\n axs[0, 0].set_title('Tair')\n axs[0, 1].plot(ddata['Time'],ddata['So_d'], 'tab:orange')\n axs[0, 1].set_title('Downwelling Shortwave Flux')\n axs[1, 0].plot(ddata['Time'],ddata['So_u'], 'tab:green')\n axs[1, 0].set_title('Upwelling Shortwave Flux')\n axs[1, 1].plot(ddata['Time'],ddata['rain'], 'tab:red')\n axs[1, 1].set_title('rain [mm/h]')\n axs[2, 0].plot(ddata['Time'],ddata['snowD'], 'tab:red')\n axs[2, 0].set_title('snowD [cm]')\n axs[2, 1].plot(ddata['Time'],ddata['Smoist'], 'tab:red')\n axs[2, 1].set_title('Smoist [-]')\n axs[3, 0].plot(ddata['Time'],ddata['U'], 'tab:red')\n axs[3, 0].set_title('Wind speed [m/s]')\n axs[3, 1].plot(ddata['Time'],ddata['Uang'], 'tab:red')\n axs[3, 1].set_title('Wind Direction [degrees]')\n plt.tight_layout()\n \n\ndef longwave(Tskin):\n #NOTE: Tskin in Kelvin \n eps=0.97 #bulk emissivity of land surface\n sigma=5.6686e-6 #Stefan‐Boltzmann constant 5.6686 × 10−6 (W m−2 K−4);\n #Tskin=df['Temp,°C (LBL: AirTemp)']+273.15\n Lw=eps*sigma*Tskin**4/100\n return Lw\n \ndef compare_data_column(data1,data2,Tcolumn,mask1,mask2):\n\n plt.plot(data1['Time'].loc[mask1], data1[Tcolumn].loc[mask1])\n plt.plot(data2['Time'].loc[mask2], data2[Tcolumn].loc[mask2],alpha=0.7)\n \n plt.title('Data series comparison')\n plt.legend(['DewPoint','Ikpikpuk']);\n plt.xlabel('Time [yr]')\n plt.ylabel(Tcolumn)\n\ndef plot_compare_data(data1,data2,mask1,mask2):\n \n #mask1 = (data2['Time'] >= '2006-9-1 14:00:00') & \\\n # (data2['Time'] <= '2017-9-1 09:00:00')\n #mask = (data1['Time'] >= '2006-9-1 14:00:00') & \\\n # (data1['Time'] <= '2017-9-1 09:00:00')\n fig, axs = plt.subplots(3, 2, figsize=(10, 6))\n axs[0, 0].plot(data1['Time'].loc[mask1], data1['Tair'].loc[mask1])\n axs[0, 0].plot(data2['Time'].loc[mask2], data2['Tair'].loc[mask2],alpha=0.7)\n axs[0, 0].set_title('Tair')\n axs[0, 1].plot(data1['Time'].loc[mask1], data1['So_d'].loc[mask1])\n axs[0, 1].plot(data2['Time'].loc[mask2], data2['So_d'].loc[mask2],alpha=0.7) \n axs[0, 1].set_title('Downwelling Shortwave Flux')\n axs[1, 0].plot(data1['Time'].loc[mask1], data1['So_u'].loc[mask1])\n axs[1, 0].plot(data2['Time'].loc[mask2], data2['So_u'].loc[mask2],alpha=0.7) \n axs[1, 0].set_title('Upwelling Shortwave Flux')\n axs[1, 1].plot(data1['Time'].loc[mask1], data1['rain'].loc[mask1])\n axs[1, 1].plot(data2['Time'].loc[mask2], data2['rain'].loc[mask2],alpha=0.7) \n axs[1, 1].set_title('rain [mm/h]')\n #axs[2, 0].plot(ddata['Time'],ddata['snowD'], 'tab:red')\n axs[2, 0].plot(data1['Time'].loc[mask1], data1['snowD'].loc[mask1])\n axs[2, 0].plot(data2['Time'].loc[mask2], data2['snowD'].loc[mask2],alpha=0.7) \n axs[2, 0].set_title('snowD [cm]')\n #axs[2, 1].plot(ddata['Time'],ddata['Smoist'], 'tab:red')\n axs[2, 1].plot(data1['Time'].loc[mask1], data1['Smoist'].loc[mask1])\n axs[2, 1].plot(data2['Time'].loc[mask2], data2['Smoist'].loc[mask2],alpha=0.7) \n axs[2, 1].set_title('Smoist [-]')\n plt.legend(['DewPoint','Ikpikpuk']);\n plt.tight_layout()\n \ndef preprocess2ats(df,swe):\n # fill nans by interpolating and zeroing out\n [m,n]=df.shape\n data=np.zeros((m,8))\n df['Tair'] = df['Tair'].interpolate() # fill nans\n data[:,0]=df['Tair'].values+273.15\n data[:,1]=longwave(data[:,0])\n df['So_d'] = df['So_d'].interpolate() # fill nans\n data[:,2]=df['So_d'].values\n \n swe[np.isnan(swe)]=0\n snow = np.where(df[\"Tair\"] < 0, swe, 0)\n rain = np.where(df[\"Tair\"] >= 0, df['rain'].values, 0)\n rain[np.isnan(rain)]=0\n \n # rain is in mm/h -> 1e-3/3600 m/s ~ 2.77e-07\n data[:,3]=rain*2.77e-07 # precip rain\n data[:,4]=snow*2.77e-07 # precip snow\n data[:,5]=0.8*np.ones(m) # humidity\n data[:,6]=range(m) \n df['U'] = df['U'].interpolate() # fill nans\n data[:,7]=df['U'].values\n \n df1=pd.DataFrame(data=data) \n df1.columns = [\"Temp [K]\",\"LWdown [W/m2]\",\"SWdown [W/m2]\",\"rain [m/s]\",\n \"snow [m/s]\",\"Hum [kg/kg]\",\"Time [s]\",\"Wind speed [m/s]\"]\n return df1\n\ndef hourly_to_daily(data):\n [m,n]=np.shape(data)\n h=list(data.columns.values)\n print ('hourly matrix:',m,n)\n ndays=m//24\n data_days=np.zeros((ndays,n))\n print ('days:',ndays)\n t_days=np.zeros(ndays)\n for j in range(n):\n for i in range(ndays):\n #data_days[i,j]=np.mean(data[i*24:24*(i+1),j])\n data_days[i,j]=np.mean(data[h[j]].loc[i*24:24*(i+1)])\n \n df1=pd.DataFrame(data=data_days) \n df1.columns = [\"Temp [K]\",\"LWdown [W/m2]\",\"SWdown [W/m2]\",\"rain [m/s]\",\n \"snow [m/s]\",\"Hum [kg/kg]\",\"Time [s]\",\"Wind speed [m/s]\"]\n return df1\n\ndef smooth_timeseries(df,w):\n df1=df.copy()\n df1[\"Temp [K]\"] = scipy.signal.savgol_filter(df1[\"Temp [K]\"], w, 2, mode='wrap')\n df1[\"LWdown [W/m2]\"] = scipy.signal.savgol_filter(df1[\"LWdown [W/m2]\"], w, 2, mode='wrap')\n df1[\"SWdown [W/m2]\"] = scipy.signal.savgol_filter(df1[\"SWdown [W/m2]\"], w, 2, mode='wrap')\n df1[\"Wind speed [m/s]\"] = scipy.signal.savgol_filter(df1[\"Wind speed [m/s]\"], w, 2, mode='wrap')\n m_precip_rain = df1[\"rain [m/s]\"].mean()\n m_precip_snow = df1[\"snow [m/s]\"].mean()\n snow = np.where(df1[\"Temp [K]\"] < 273.15, m_precip_snow, 0)\n rain = np.where(df1[\"Temp [K]\"] >= 273.15, m_precip_rain, 0)\n df1[\"rain [m/s]\"] = rain\n df1[\"snow [m/s]\"] = snow\n\n return df1\n \ndef save2ats_met_file(df,filename):\n [m,n]=df.shape\n print (m,n)\n time = np.arange(0, 86400.0*m, 86400.0)\n with h5py.File(filename,'w') as out:\n out.create_dataset(\"time [s]\", data=time)\n out.create_dataset(\"air temperature [K]\", data=df[\"Temp [K]\"].values)\n out.create_dataset(\"relative humidity [-]\", data=df[\"Hum [kg/kg]\"].values)\n out.create_dataset(\"precipitation rain [m s^-1]\", data=df[\"rain [m/s]\"].values)\n out.create_dataset(\"precipitation snow [m SWE s^-1]\", data=df[\"snow [m/s]\"].values)\n out.create_dataset(\"incoming shortwave radiation [W m^-2]\", data=df[\"SWdown [W/m2]\"].values)\n out.create_dataset(\"incoming longwave radiation [W m^-2]\", data=df[\"LWdown [W/m2]\"].values)\n out.create_dataset(\"wind speed [m s^-1]\", data=df[\"Wind speed [m/s]\"].values)\n out.attrs.create(\"wind speed reference height [m]\", data=3.0) # fix me\n\ndef plot_ats_h5_met_data(filename):\n d = h5py.File(filename,'r')\n print(d.keys())\n\n fax = plt.subplots(4,2,figsize=(10,20))\n ax = fax[1].ravel()\n\n time = d['time [s]'][:]\n print (d['time [s]'][:].shape)\n\n for i,k in enumerate([k for k in d.keys() if not \"reference height\" in k]):\n print (d[k])\n ax[i].plot(time/86400.0/365.0, d[k][:], 'b')\n ax[i].set_title(k);\n \ndef relative_humidity(Tair):\n # not working, need pressure data\n # relative humidity via Buck equation (eg.) https://en.wikipedia.org/wiki/Vapour_pressure_of_water\n Ta_c = Ta - 273.15\n vp_sat = 611.21 * np.exp((18.678 - Ta_c/234.5)*(Ta_c/(257.14-Ta_c)))\n rh = df['vp (Pa)']/vp_sat\n\n ka0_ = 16.635764\n ka_ = -6096.9385\n kb_ = -2.7111933e-2\n kc_ = 1.673952e-5\n kd_ = 2.433502\n vp_sat2 = 100.0*np.exp(ka0_ + ka_/Ta + (kb_ + kc_*Ta)*Ta + kd_*np.log(Ta))\n rh2 = df['vp (Pa)']/vp_sat2\n\n print (df['vp (Pa)'].min(), df['vp (Pa)'].max())\n print (vp_sat.min(), vp_sat.max())\n print (vp_sat2.min(), vp_sat2.max())\n\n print (rh.min(), rh.max())\n print (rh2.min(), rh2.max())\n\n #plt.plot(df['vp (Pa)'], 'k')\n #plt.plot(vp_sat,'b')\n #plt.plot(vp_sat2, 'r')\n #plt.show()\n\n # a few bad data points with 0 vapor pressure\n RH = np.where(rh2 > 1, 1, np.where(rh2 <= 0, np.nan, rh2))\n for i in range(len(RH)):\n if np.isnan(RH[i]):\n j = (j for j in range(i,len(RH)) if RH[j] > 0).next()\n RH[i] = RH[j]\n\n # spinup RH -- daily averages of the full dataset\n fax = plt.subplots(2,1)\n\n RH_raw = RH.reshape((-1,365)).transpose()\n for i in range(RH_raw.shape[1]):\n fax[1][0].plot(RH_raw[:,i])\n\n\n RH_m = RH_raw.mean(axis=1)\n fax[1][0].plot(RH_m,'k',linewidth=3)\n\n import scipy.signal\n RH_sm = scipy.signal.savgol_filter(RH_m, 61, 2, mode='wrap')\n fax[1][1].plot(RH_m, 'k')\n fax[1][1].plot(RH_sm, 'b')\n\ndef USGS2LAKE_met_data(df,fLAKEname,swe):\n swe[np.isnan(swe)]=0\n [m,n]=df.shape\n pi_180= np.pi/180\n df['Wind Direction, ø (LBL: Dir)']=df['Wind Direction, ø (LBL: Dir)'].interpolate()\n wind_dir=df['Wind Direction, ø (LBL: Dir)'].copy()\n wind_dir[wind_dir==360]=0\n df['Wind Speed, m/s (LBL: Wind)']=df['Wind Speed, m/s (LBL: Wind)'].interpolate()\n wind_speed=df['Wind Speed, m/s (LBL: Wind)'].copy()\n u=-wind_speed*np.cos(wind_dir*pi_180)\n v=-wind_speed*np.sin(wind_dir*pi_180)\n u[abs(u)<0.1]=0\n v[abs(v)<0.1]=0\n\n df['Temp,°C (LBL: AirTemp)']=df['Temp,°C (LBL: AirTemp)'].interpolate()\n TAVG=df['Temp,°C (LBL: AirTemp)'].copy() # this is valid for the Celsuis temperatures \n RH=df['RH, % (LBL: RelHum)'].copy()\n ASP=df['Pressure, mbar (LBL: Press)'].copy()*100\n N=len(TAVG)\n hr=np.zeros(N)\n for i in range(N):\n if TAVG[i]>0:\n pws=610.94*np.exp(1)**(17.625*TAVG[i]/(TAVG[i]+243.04))\n else:\n pws=611.21*np.exp(1)**(22.587*TAVG[i]/(TAVG[i]+273.86))\n pw = (pws*RH[i])/100\n hr[i] = 0.62198*pw/(ASP[i] - pw)\n\n #Estimation of surface longwave radiation components from ground‐based historical net radiation and weather data\n eps=0.97 #bulk emissivity of land surface\n sigma=5.6686e-6 #Stefan‐Boltzmann constant 5.6686 × 10−6 (W m−2 K−4);\n Tskin=df['Temp,°C (LBL: AirTemp)']+273.15\n Lw=eps*sigma*Tskin**4/100\n # rain is in mm/h -> 1e-3/3600 m/s ~ 2.77e-07#\n precip=swe*2.77e-07\n\n pres=df['Pressure, mbar (LBL: Press)'].copy()*100\n pres[pres<97000]=101325 \n pres[pres>104500]=101325\n data=np.zeros((m,n-2))\n np.shape(data[:,0])\n data[:,0]=df['Temp,°C (LBL: AirTemp)']+273.15\n data[:,1]=pres\n data[:,2]=Lw\n data[:,3]=df['Solar Radiation, W/m² (LBL: SolarUP)']\n data[:,4]=u\n data[:,5]=v\n data[:,6]=hr\n data[:,7]=precip\n\n df1=pd.DataFrame(data=data) \n df1.columns = [\"Temp [K]\",\"Pres [Pa]\",\"LWdown [W/m2]\",\"SWdown [W/m2]\",\n \"Uspeed [m/s]\",\"Vspeed [m/s]\",\"Hum [kg/kg]\",\"Precip [m/s]\"]\n df1.plot(subplots=True, layout=(4,2),figsize=(12, 10));\n plt.tight_layout()\n df1.to_csv(fLAKEname,index=False,header=False,float_format='%.3e')\n return df1","sub_path":"scripts/Atqasuk/preproccess_USGS_data_utils.py","file_name":"preproccess_USGS_data_utils.py","file_ext":"py","file_size_in_byte":11510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"341903397","text":"#*************************************************************************\n# Multiclass classification tutorial\n'''\nThis program will categorically classify 3 labels\nBuilds off of the deep neural network and perceptron tutorials.\nUses the keras library.\n'''\n#*************************************************************************\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense # connect preceeding layers to proceeding layers in the neural networks\nfrom keras.optimizers import Adam\nfrom keras.utils.np_utils import to_categorical\n\n#=========================================================================\n# Coorelate each specific coordinate with its respective prediction probability.\n'''\nX: refers to data created (Xa and Xb)\ny: matrix that contains labels for our data set (1 for bottom, 0 for top)\nmodel: model that was trained to fir our data \n'''\n#=========================================================================\ndef plot_decision_boundary(X, y_cat, model):\n x_span = np.linspace(min(X[:, 0]) - 1, max(X[:, 0]) + 1, 50)\n y_span = np.linspace(min(X[:, 1]) - 1, max(X[:, 1]) + 1, 50)\n xx, yy = np.meshgrid(x_span, y_span)\n xx_, yy_ = xx.ravel(), yy.ravel()\n grid = np.c_[xx_, yy_]\n pred_func = model.predict_classes(grid) # predict for multiclass\n z = pred_func.reshape(xx.shape)\n plt.contourf(xx, yy, z)\n\n#-------------------------------------------------------------------------\n\nn_pts = 500\ncenters = [[-1, 1], [-1, -1], [1, -1]] # \"focii\" of data blobs\n'''\nArg 1: define number of samples/points\nArg 2: seed random number generator\nArg 3: give centers for each category\nArg 4: the distance between each data point\n'''\nX, y = datasets.make_blobs(n_samples=n_pts, random_state=123, centers=centers, cluster_std=0.4) # make blobs in different coords in the grid\n\n# Scatter plot for data\n'''\nplt.scatter(X[y==0, 0], X[y==0, 1])\nplt.scatter(X[y==1, 0], X[y==1, 1])\nplt.scatter(X[y==2, 0], X[y==2, 1])\n'''\n\n# Replace numerical labels with hot encoded labels\nprint(y)\ny_cat = to_categorical(y, 3) # labels, number of data classes (in our case 3)\nprint(y_cat)\n\n# Define neural network, one with an input layer, and an output layer\nmodel = Sequential()\nmodel.add(Dense(units=3, input_shape=(2, ), activation='softmax')) # number of ouput nodes (the next layer), input nodes, using the softmax function.\nmodel.compile(Adam(0.1), loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(x=X, y=y_cat, verbose=1, batch_size=50, epochs=100) # train the model (with hot-encoded labels)\n\n'''\n# Plot final model\nplot_decision_boundary(X, y_cat, model)\nplt.scatter(X[y==0, 0], X[y==0, 1])\nplt.scatter(X[y==1, 0], X[y==1, 1])\nplt.scatter(X[y==2, 0], X[y==2, 1])\n'''\n\n# Predict probability of a value using the trained model\nplot_decision_boundary(X, y_cat, model)\nplt.scatter(X[y==0, 0], X[y==0, 1])\nplt.scatter(X[y==1, 0], X[y==1, 1])\nplt.scatter(X[y==2, 0], X[y==2, 1])\nx = 0.5\ny = 0.5\npoint = np.array([[x, y]])\nprediction = model.predict_classes(point)\nplt.plot([x], [y], marker='o', markersize=10, color='r')\nprint('Prediction is: ', prediction)\n\nplt.show()\n","sub_path":"multiclass_classification/multiclass-3.py","file_name":"multiclass-3.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"258686243","text":"# -*- coding: utf-8 -*\nimport json\nfrom yandex_geocoder import Client\nfrom geopy import distance\nimport folium\nfrom flask import Flask\n\n\ndef coords_swap(coords):\n coords[1], coords[0] = coords[0], coords[1]\n return coords\n\ndef get_bar_distance(bar):\n return bar['distance']\n\ndef hello_world():\n with open('output/index.html', encoding='utf-8') as html_file:\n return html_file.read()\n\n\ndef main():\n\n location = input(\"Где вы находитесь? \")\n\n mycoords = coords_swap(list(Client.coordinates(location)))\n\n bardata = []\n\n with open('data/data-2897-2019-04-09.json', encoding='cp1251') as jsonfile:\n bars_data = json.load(jsonfile)\n\n for bar in bars_data:\n title = bar['Name']\n latitude = float(bar['Latitude_WGS84'])\n longitude = float(bar['Longitude_WGS84'])\n\n bar_distance = distance.distance(mycoords, (latitude,longitude)).km\n bardata.append({'title':title, 'latitude':latitude, 'longitude':longitude, 'distance':bar_distance})\n\n\n sorted_bars = sorted(bardata, key=get_bar_distance)\n\n map = folium.Map(location=[float(mycoords[0]), float(mycoords[1])])\n tooltip = 'Бар здесь!'\n\n for item in sorted_bars[:5]:\n title = item['title']\n folium.Marker([item['latitude'], item['longitude']], popup='{}'.format(title), \\\n tooltip=tooltip).add_to(map)\n\n map.save('output/index.html')\n\n app = Flask(__name__)\n\n app.add_url_rule('/', 'hello', hello_world)\n app.run('0.0.0.0')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587225070","text":"import tensorflow as tf\nimport numpy as np\n\nW_ = np.array([[1, 0, 1], [1, 2, 0]], dtype=np.float32)\nX_ = np.array([[1, -1, 1]], dtype=np.float32)\ny_ = np.array([1], dtype=np.float32)\nV_ = np.array([[0, 1]], dtype=np.float32)\n\n# tf\nX = tf.placeholder(tf.float32, (1, 3))\ny = tf.placeholder(tf.float32, (1))\nW = tf.Variable(tf.convert_to_tensor(W_))\nV = tf.Variable(tf.convert_to_tensor(V_))\nb = tf.matmul(W, tf.transpose(X))\nh = tf.maximum(0., b)\n\ny_hat = tf.matmul(V, h)\nloss = 0.5 * (y_hat - y)**2\n\ntrain = tf.train.GradientDescentOptimizer(0.01).minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n Wgradient, Vgradient, hvalue, bvalue, lvalue, wvalue, vvalue, _ = sess.run(\n [\n tf.gradients(loss, W),\n tf.gradients(loss, V), h, b, loss, W, V, train\n ],\n feed_dict={\n X: X_,\n y: y_\n })\n\n print('loss', lvalue)\n print('Wgrad', Wgradient)\n print('Vgrad', Vgradient)\n print('h', hvalue)\n print('b', bvalue)\n print('W', wvalue)\n print('V', vvalue)\n","sub_path":"workspace/mid_check/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"235819537","text":"import os\n\nfrom django.conf import settings\nfrom django.core.cache import cache\n\nfrom naremitcms.classes import NaremitApplication\nfrom .models import DocImport\n\nclass DocImportApplication(NaremitApplication):\n # define the markup language to use, current options are:\n # - 'markdown': Markdown (default)\n # - 'rest': reStructured Text\n # it is trivial to add other markup languages, just add them to the\n # get_html() function in docimport/management/commands/docimport.py\n MARKUP_LANGUAGE = 'markdown'\n\n # The template used for the documentation pages\n TEMPLATE = 'naremitcms-docimport/example.html'\n\n def find_current(self, url, tree):\n for node in tree:\n if node['url'] == url:\n self.node_id = node['id']\n break\n else:\n self.find_current(url, node['children'])\n\n def get_data_dir(self):\n if not os.path.isdir(self.DATA_DIR):\n raise Exception('Invalid DATA_DIR directory')\n return self.DATA_DIR\n\n def get_group(self):\n return ('%s.%s' % (\n self.__class__.__module__,\n self.__class__.__name__)\n )[-255:]\n\n def get_tree(self):\n # get from cache\n cache_key = ('%s_docimporttree' % self.get_group())[-230:]\n tree = cache.get(cache_key)\n if tree is not None:\n return tree\n\n # not in cache, generate tree\n try:\n root = DocImport.objects.get(group=self.get_group(), level=0)\n tree = self.get_tree_recurse(root)\n except:\n tree = []\n\n # save to cache\n cache.set(cache_key, tree, 60 * 60 * 24)\n return tree\n\n def get_tree_path(self):\n if settings.APPEND_SLASH:\n path = '/%s/' % self.naremit['page']['cached_url']\n else:\n path = '/%s' % self.naremit['page']['cached_url']\n if self.naremit['lang']['is_active']:\n path = '/%s%s' % (self.naremit['lang']['code'], path)\n return path\n\n def get_tree_recurse(self, parent_node):\n nodes = parent_node.get_children().values('id', 'url', 'title', 'has_content')\n for node in nodes:\n node['children'] = self.get_tree_recurse(DocImport.objects.get(id=node['id']))\n return nodes\n\n def homepage(self):\n self.set_context('docimport', {\n 'tree': self.get_tree(),\n 'path': self.get_tree_path(),\n })\n\n def page(self, url):\n self.node_id = None\n tree = self.get_tree()\n self.find_current('%s/' % url, tree)\n\n # output\n if self.node_id is None:\n self.raise_404()\n else:\n self.set_template(self.TEMPLATE)\n self.set_context('docimport', {\n 'tree': tree,\n 'path': self.get_tree_path(),\n 'html': DocImport.objects.get(id=self.node_id).html\n })\n\n def urls(self):\n return (\n (r'^$', 'homepage'),\n (r'^(?P(.*))$', 'page'),\n )\n\n def get_all_urls(self):\n urls = []\n path = ('/%s/' % self.naremit['page']['cached_url']).replace('//', '/')\n tree = DocImport.objects.filter(group=self.get_group())\n for node in tree:\n if not node.is_root_node():\n urls.append( ('%s%s' % (path, node.url)).replace('//', '/') )\n\n # handle multilanguage\n if self.naremit['lang']['is_active']:\n multilang_urls = []\n for lang in settings.LANGUAGES:\n for url in urls:\n multilang_urls.append('/%s%s' % (lang[0], url))\n return multilang_urls\n else:\n return urls\n\n # unfinished\n def sitemap(self):\n return self.get_all_urls()\n\n def medusa_urls(self):\n return sorted(self.get_all_urls())\n","sub_path":"naremitcms_docimport/docimport.py","file_name":"docimport.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"474955620","text":"import tensorflow as tf\nimport ml_model_para\n# import numpy as np\n\nsize = ml_model_para.size\nimg_channel = ml_model_para.img_channel\n\nn_classes = ml_model_para.n_classes_4\n# batch_size = ml_model_para.batch_size\n# min_after_dequeue = ml_model_para.min_after_dequeue\n# capacity = ml_model_para.capacity\n# dropout = ml_model_para.dropout_train # Dropout, probability to keep units\n\nkernal_size_1 = ml_model_para.kernal_size_1\nkernal_size_2 = ml_model_para.kernal_size_2\nkernal_size_3 = ml_model_para.kernal_size_3\n\n# Parameters\nlearning_rate = ml_model_para.learning_rate\ntraining_iters = ml_model_para.training_iters\ndisplay_step = ml_model_para.display_step\nl2_regularization_penalty = ml_model_para.l2_regularization_penalty\n\n\n# Create some wrappers for simplicity\ndef conv2d(x, W, b, strides=1):\n # Conv2D wrapper, with bias and relu activation\n x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n\ndef maxpool2d(x, k=2):\n # MaxPool2D wrapper (NOTE: ksize = strides, padding = 'SAME')\n return tf.nn.max_pool(x, ksize=[1, k + 1, k + 1, 1], strides=[1, k, k, 1],\n padding='SAME')\n\n\n# def norm_lrn(x):\n# return tf.nn.lrn(x, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)\n\n\ndef _variable_with_weight_decay(var, wd):\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n\n\n# Create model\ndef conv_net(x, dropout):\n # Store layers weight & bias\n weights = {\n # 5x5 conv, 1 input, 32 outputs\n 'wc1': tf.Variable(tf.random_normal([kernal_size_1[0], kernal_size_1[1], img_channel, 32])),\n # 5x5 conv, 32 inputs, 64 outputs\n 'wc2': tf.Variable(tf.random_normal([kernal_size_2[0], kernal_size_2[1], 32, 32])),\n 'wc21': tf.Variable(tf.random_normal([kernal_size_2[0], kernal_size_2[1], 32, 32])),\n # 'wc22': tf.Variable(tf.random_normal([kernal_size_2[0], kernal_size_2[1], 32, 32])),\n # 5x5 conv, 64 inputs, 32 outputs\n 'wc3': tf.Variable(tf.random_normal([kernal_size_3[0], kernal_size_3[1], 32, 64])),\n # 5x5 conv, 64 inputs, 32 outputs\n # 'wc4': tf.Variable(tf.random_normal([kernal_size[0], kernal_size[1], 64, 32])),\n # fully connected, 7*7*64 inputs, 1024 outputs\n 'wd1': tf.Variable(tf.random_normal([size[0] / 8 * size[1] / 8 * 64, 1024])),\n # fully connected\n # 'wd2': tf.Variable(tf.random_normal([1024, 200])),\n # 1024 inputs, 10 outputs (class prediction)\n 'out': tf.Variable(tf.random_normal([1024, n_classes]))\n }\n\n biases = {\n 'bc1': tf.Variable(tf.random_normal([32])),\n 'bc2': tf.Variable(tf.random_normal([32])),\n 'bc21': tf.Variable(tf.random_normal([32])),\n # 'bc22': tf.Variable(tf.random_normal([32])),\n 'bc3': tf.Variable(tf.random_normal([64])),\n # 'bc4': tf.Variable(tf.random_normal([32])),\n 'bd1': tf.Variable(tf.random_normal([1024])),\n # 'bd2': tf.Variable(tf.random_normal([200])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n }\n\n tf.summary.histogram(\"WC1\", weights['wc1'])\n tf.summary.histogram(\"WC2\", weights['wc2'])\n tf.summary.histogram('WC21', weights['wc21'])\n tf.summary.histogram('WC3', weights['wc3'])\n tf.summary.histogram(\"WD1\", weights['wd1'])\n tf.summary.histogram(\"out\", weights['out'])\n\n _variable_with_weight_decay(weights['wc1'], l2_regularization_penalty)\n _variable_with_weight_decay(weights['wc2'], l2_regularization_penalty)\n _variable_with_weight_decay(weights['wc21'], l2_regularization_penalty)\n _variable_with_weight_decay(weights['wc3'], l2_regularization_penalty)\n _variable_with_weight_decay(weights['wd1'], l2_regularization_penalty)\n _variable_with_weight_decay(weights['out'], l2_regularization_penalty)\n\n # Reshape input picture\n x = tf.reshape(x, shape=[-1, size[0], size[1], img_channel])\n\n # Convolution Layer\n conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n # Max Pooling (down-sampling)\n conv1 = maxpool2d(conv1, k=2)\n # norm1 = norm_lrn(conv1)\n\n # Convolution Layer\n conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n conv21 = conv2d(conv2, weights['wc21'], biases['bc21'])\n # conv22 = conv2d(conv21, weights['wc22'], biases['bc22'])\n # Max Pooling (down-sampling)\n conv2 = maxpool2d(conv21, k=2)\n\n # Convolution Layer\n conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])\n # Max Pooling (down-sampling)\n conv3 = maxpool2d(conv3, k=2)\n\n # Fully connected layer\n # Reshape conv2 output to fit fully connected layer input\n fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n # fc1 = tf.nn.relu(fc1)\n # Apply Dropout\n fc1 = tf.nn.dropout(fc1, dropout)\n\n # fully connected\n # fc2 = tf.add(tf.matmul(fc1, weights['wd2']), biases['bd2'])\n # fc2 = tf.nn.relu(fc2)\n # Apply Dropout\n # fc2 = tf.nn.dropout(fc2, dropout)\n\n # Output, class prediction\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out\n\n\ndef loss(pred, y):\n # tf Graph input\n # x = tf.placeholder(tf.float32, [None, n_input])\n # y = tf.placeholder(tf.float32, [None, n_classes])\n # keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)\n\n cross_entropy = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=pred, labels=y))\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n\n # The total loss is defined as the cross entropy loss plus all of the weight\n # decay terms (L2 loss).\n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\n\ndef train(cost):\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n return optimizer\n","sub_path":"multilabel/build_cnn.py","file_name":"build_cnn.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"383007368","text":"#TODO: 52 week high and low\n\n# app/robo_advisor.py\nimport requests\nimport json\nimport os\nimport csv # for prices.csv\nimport datetime # for date and time \nfrom twilio.rest import Client # twilio stuff\nfrom dotenv import load_dotenv\n\nimport plotly #plotly graph\nimport plotly.graph_objects as go #plotly graph, ADD TO README\n\n\n# date and time calculations\nnow = datetime.datetime.now().strftime(\"%Y-%m-%d %I:%M %p\")\n\nload_dotenv() # load env\n\ndef to_usd(my_price):\n return \"${0:,.2f}\".format(my_price)\n\n# function for symbol inputs like this: 'ad42'\ndef num_there(s):\n return any(i.isdigit() for i in s)\n\nAPI_KEY = os.getenv(\"ALPHAVANTAGE_API_KEY\", default=\"OOPS\")\n\n# empty list for multiple stocks\nstocks = []\n\nstock_num = input(\"\\nWelcome to the robo-advisor!\\n\\nHow many stocks would you like to evaluate?\\n\\n***> Disclaimer: you may only enter 5 stocks per request <***\\n\\nEnter Number Here: \")\n\n\n\nif stock_num == '0':\n print(\"You must enter a number higher than 0. Please try again.\")\n\nelif num_there(stock_num):\n\n if stock_num.isnumeric(): #still need to fix for input like ad34\n stock_num = eval(stock_num)\n if stock_num > 5:\n print(\"You must enter less than 5 stocks.\")\n\n else:\n for i in range(1, stock_num + 1):\n symbol = input(\"Please enter your desired stock symbol #\" + str(i) + \":\\n\")\n if len(symbol) > 5 or num_there(symbol):\n print(\"Invalid symbol. Input will be discarded.\")\n else:\n stocks.append(symbol)\n else:\n print(\"Invalid symbol. Restarting program...\")\n\nelse:\n print(\"Invalid symbol. Restarting program...\")\n\nfor symbol in stocks:\n\n request_url = f\"https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol={symbol}&apikey={API_KEY}\" # change to weekly\n\n response = requests.get(request_url)\n\n parsed_response = json.loads(response.text)\n\n last_refresed = parsed_response[\"Meta Data\"][\"3. Last Refreshed\"]\n\n wts = parsed_response[\"Weekly Time Series\"]\n\n dates = list(wts.keys())\n\n latest_day = dates[0]\n\n latest_close = wts[latest_day][\"4. close\"]\n\n second_latest_week = dates[1]\n\n second_latest_close = wts[second_latest_week][\"4. close\"]\n\n high_prices = []\n low_prices = [] \n closes = []\n\n for date in dates[0:52]: #0-52 for the 52 week time stamp\n high_price = wts[date][\"2. high\"]\n low_price = wts[date][\"3. low\"]\n close = wts[date][\"4. close\"]\n high_prices.append(float(high_price))\n low_prices.append(float(low_price))\n closes.append(close)\n\n recent_high = max(high_prices)\n recent_low = min(low_prices)\n\n # for comparing latest close to recent 80% of recent high\n HIGHthreshold = recent_high * (8/10)\n\n # for comparing low\n LOWthreshold = recent_low * 1.2\n\n if eval(latest_close) < HIGHthreshold and eval(latest_close) > LOWthreshold:\n recommendation = \"HOLD\"\n reason = \"STOCK IS LESS THAN 80% OF THE RECENT HIGH AND MORE THAN 120% OF THE RECENT LOW\"\n elif eval(latest_close) >= HIGHthreshold:\n recommendation = \"SELL!\"\n reason = \"STOCK IS OVERVALUED BECAUSE IT IS GREATER THAN 80% OF THE RECENT HIGH\" \n elif eval(latest_close) <= LOWthreshold:\n recommendation = \"BUY!\"\n reason = \"STOCK IS UNDERVALUED BECAUSE IT IS WITHIN 120% OF THE RECENT LOW\"\n\n print(\"-------------------------\")\n print(\"SELECTED SYMBOL:\",symbol)\n print(\"-------------------------\")\n print(\"REQUESTING STOCK MARKET DATA...\")\n print(\"REQUEST AT:\", now)\n print(\"-------------------------\")\n print(f\"LATEST DAY: {last_refresed}\")\n print(f\"LATEST CLOSE: {to_usd(float(latest_close))}\")\n print(f\"52-WEEK HIGH: {to_usd(float(recent_high))}\")\n print(f\"52-WEEK LOW: {to_usd(float(recent_low))}\")\n print(\"-------------------------\")\n print(\"RECOMMENDATION: \" + recommendation)\n print(\"RECOMMENDATION REASON: \" + reason)\n print(\"-------------------------\")\n print(\"HAPPY INVESTING!\")\n print(\"-------------------------\")\n\n # csv stuff\n file = \"data/prices_\" + symbol + \".csv\"\n\n with open(file, 'w+') as csvfile:\n csvfile.write('timestamp, open, high, low, close, volume\\n')\n\n for date in dates[0:52]:\n csvfile.write(date)\n csvfile.write(\", \")\n csvfile.write(wts[date][\"1. open\"])\n csvfile.write(\", \")\n csvfile.write(wts[date][\"2. high\"])\n csvfile.write(\", \")\n csvfile.write(wts[date][\"3. low\"])\n csvfile.write(\", \")\n csvfile.write(wts[date][\"4. close\"])\n csvfile.write(\", \")\n csvfile.write(wts[date][\"5. volume\"])\n csvfile.write(\"\\n\")\n\n TWILIO_ACCOUNT_SID = os.environ.get(\"TWILIO_ACCOUNT_SID\", \"OOPS, please specify env var called 'TWILIO_ACCOUNT_SID'\")\n TWILIO_AUTH_TOKEN = os.environ.get(\"TWILIO_AUTH_TOKEN\", \"OOPS, please specify env var called 'TWILIO_AUTH_TOKEN'\")\n SENDER_SMS = os.environ.get(\"SENDER_SMS\", \"OOPS, please specify env var called 'SENDER_SMS'\")\n RECIPIENT_SMS = os.environ.get(\"RECIPIENT_SMS\", \"OOPS, please specify env var called 'RECIPIENT_SMS'\")\n\n\n\n # OUTPUT FOR USER'S SMS\n price_increase = (eval(second_latest_close) * 1.05)\n price_decrease = (eval(second_latest_close) * .95)\n\n # COMPILE REQUEST PARAMETERS (PREPARE THE MESSAGE)\n if eval(latest_close) >= price_increase:\n content = \"Wow! The latest closing price for \" + symbol.upper() + \" has spiked 5% or more since the last closing week!\"\n elif eval(latest_close) <= price_decrease:\n content = \"Uh oh, the latest closing price for \" + symbol.upper() + \" has dropped 5% or more since the last closing week!\"\n else:\n content = \"The price for \" + symbol.upper() + \" has been steady since the past closing week, maintaining no more than 5% growth or decline since.\"\n\n # AUTHENTICATE\n client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)\n\n # ISSUE REQUEST (SEND SMS)\n message = client.messages.create(to=RECIPIENT_SMS, from_=SENDER_SMS, body=content)\n\n # plotly stuff\n # produces different graph in different window for each ticker symbol entered\n fig = go.Figure()\n\n # Create and style traces\n fig.add_trace(go.Scatter(x=dates, y=closes, name=symbol, line = dict(color='firebrick', width=4, dash='dot')))\n \n # Edit the layout\n fig.update_layout(title=symbol.upper() + ' Prices Over the Past 52 Weeks', xaxis_title='Time', yaxis_title='Price')\n\n\n fig.show()\n\n\n\n\n\n","sub_path":"app/robo_advisor.py","file_name":"robo_advisor.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"189074344","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# Thinkopen - Portugal & Brasil\n# Copyright (C) Thinkopen Solutions ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport logging\n\nfrom odoo import fields, api, models\n\n_logger = logging.getLogger(__name__)\n\n\nclass MultipleDuplicates(models.TransientModel):\n _name = 'multiple.duplicates'\n\n name = fields.Integer('Duplicate in')\n\n @api.multi\n def duplicate_records(self):\n context = dict(self._context)\n self.ensure_one()\n new_invs = []\n res_model = context.get('active_model')\n res_id = context.get('active_id')\n if res_model and res_id:\n for i in range(0, self.name):\n new_inv = self.env[res_model].browse(res_id).copy()\n new_invs.append(new_inv.id)\n _logger.info(\"Duplicating record %s for model %s %s time\" % (res_id, res_model, i + 1))\n return {\n 'view_type': 'form',\n 'view_mode': 'tree,form',\n 'res_model': res_model,\n 'domain': [('id', 'in', new_invs)],\n 'type': 'ir.actions.act_window',\n }\n","sub_path":"tko_base_multiple_duplicate_invoices-10.0.0.005.1/tko_base_multiple_duplicate/wizard/multiple_duplicate.py","file_name":"multiple_duplicate.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"547150655","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution(object):\n\n def removeElements(self, head, val):\n \"\"\"\n :type head: ListNode\n :type val: int\n :rtype: ListNode\n \"\"\"\n fakeHead = last = ListNode(0)\n last.next = head\n while last.next:\n if last.next.val == val:\n last.next = last.next.next\n else:\n \tlast = last.next\n return fakeHead.next\n","sub_path":"203.py","file_name":"203.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"5659295","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\nfrom PIL import Image\nimport numpy as np\nimport gym\nfrom keras import models, layers, optimizers\nfrom rl.agents import NAFAgent\nfrom rl.memory import SequentialMemory\nfrom rl.random import OrnsteinUhlenbeckProcess\nfrom rl.core import Processor\nfrom rl.callbacks import FileLogger, ModelIntervalCheckpoint\nfrom kerasrl_extensions import *\nimport sys\n\n# Turning off the logger.\nimport logging\nlogger = logging.getLogger(\"gym-duckietown\")\nlogger.propagate = False\n\n\nINPUT_SHAPE = (84, 84)\nWINDOW_LENGTH = 4\n#environment_name = \"Duckietown-straight_road-v0\"\nenvironment_name = \"CarRacing-v0\"\n\n\nclass CarRacingProcessor(Processor):\n \"\"\"\n Transforms observations, state-batches and rewards of\n Flappy-Bird.\n \"\"\"\n\n def process_observation(self, observation):\n \"\"\"\n Takes an observation, resizes it and turns it into greyscale.\n \"\"\"\n img = Image.fromarray(observation)\n img = img.resize(INPUT_SHAPE).convert('L')\n processed_observation = np.array(img)\n return processed_observation.astype('uint8')\n\n def process_state_batch(self, batch):\n \"\"\"\n Normalizes a batch of observations.\n \"\"\"\n processed_batch = batch.astype('float32') / 255.\n return processed_batch\n\n def process_reward(self, reward):\n \"\"\"\n Clips the rewards.\n \"\"\"\n return reward\n #return np.clip(reward, -1., 1.)\n\n def process_info(self, info):\n \"\"\"\n Ignores the info.\n \"\"\"\n return {}\n\n\ndef train(index, policy_nb_steps, fit_nb_steps):\n\n # Get the environment and extract the number of actions.\n print(\"Using environment\", environment_name)\n environment = gym.make(environment_name)\n np.random.seed(666)\n nb_actions = environment.action_space.shape[0]\n\n # Build the model.\n v_model, mu_model, l_model = build_models((WINDOW_LENGTH,) + INPUT_SHAPE, nb_actions)\n v_model.summary()\n mu_model.summary()\n l_model.summary()\n\n # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and\n # even the metrics!\n memory = SequentialMemory(limit=1000000, window_length=WINDOW_LENGTH)\n processor = CarRacingProcessor()\n random_process = OrnsteinUhlenbeckProcess(theta=.15, mu=0., sigma=.3, size=nb_actions)\n\n agent = NAFAgent(nb_actions=nb_actions, V_model=v_model, L_model=l_model, mu_model=mu_model,\n memory=memory, nb_steps_warmup=100, random_process=random_process,\n gamma=.99, target_model_update=1e-3, processor=processor)\n agent.compile(optimizers.Adam(lr=.001, clipnorm=1.), metrics=['mae'])\n\n weights_filename = 'naf_{}_{}_weights.h5f'.format(environment_name, index)\n\n # Okay, now it's time to learn something! We capture the interrupt exception so that training\n # can be prematurely aborted. Notice that now you can use the built-in Keras callbacks!\n checkpoint_weights_filename = 'naf_' + environment_name + '_weights_{step}.h5f'\n log_filename = 'naf_{}_log.json'.format(environment_name)\n callbacks = [ModelIntervalCheckpoint(checkpoint_weights_filename, interval=250000)]\n callbacks += [TensorboardCallback()]\n callbacks += [FileLogger(log_filename, interval=100)]\n agent.fit(\n environment,\n callbacks=callbacks,\n #nb_steps=1750000,\n nb_steps=fit_nb_steps,\n log_interval=10000,\n visualize=\"visualize\" in sys.argv)\n\n # After training is done, we save the final weights one more time.\n agent.save_weights(weights_filename, overwrite=True)\n\n # Finally, evaluate our algorithm for 10 episodes.\n #dqn.test(environment, nb_episodes=10, visualize=False)\n\ndef build_models(input_shape, actions):\n\n cnn_model = models.Sequential()\n cnn_model.add(layers.Permute((2, 3, 1), input_shape=input_shape))\n cnn_model.add(layers.Convolution2D(32, (8, 8), strides=(4, 4), activation=\"relu\"))\n cnn_model.add(layers.Convolution2D(64, (4, 4), strides=(2, 2), activation=\"relu\"))\n cnn_model.add(layers.Convolution2D(64, (3, 3), strides=(1, 1), activation=\"relu\"))\n cnn_model.add(layers.Flatten())\n\n v_model_input = layers.Input(shape=input_shape)\n v_model_output = cnn_model(v_model_input)\n v_model_output = layers.Dense(512, activation=\"relu\")(v_model_output)\n v_model_output = layers.Dense(1, activation=\"linear\")(v_model_output)\n v_model = models.Model(v_model_input, v_model_output)\n\n mu_model_input = layers.Input(shape=input_shape)\n mu_model_output = cnn_model(mu_model_input)\n mu_model_output = layers.Dense(512, activation=\"relu\")(mu_model_output)\n mu_model_output = layers.Dense(actions, activation=\"linear\")(mu_model_output)\n mu_model = models.Model(mu_model_input, mu_model_output)\n\n l_model_action_input = layers.Input(shape=(actions,))\n l_model_action_output = l_model_action_input\n l_model_observation_input = layers.Input(shape=input_shape)\n l_model_observation_output = cnn_model(l_model_observation_input)\n l_model_output = layers.Concatenate()([l_model_action_output, l_model_observation_output])\n l_model_output = layers.Dense(512, activation=\"relu\")(l_model_output)\n l_model_output = layers.Dense(((actions * actions + actions) // 2), activation=\"linear\")(l_model_output)\n l_model = models.Model([l_model_action_input, l_model_observation_input], l_model_output)\n\n return v_model, mu_model, l_model\n\n\nif __name__ == \"__main__\":\n parameters = [\n (4000, 5000),\n (40000, 50000),\n (400000, 500000),\n ]\n for index, (policy_nb_steps, fit_nb_steps) in enumerate(parameters):\n train(index, policy_nb_steps, fit_nb_steps)\n","sub_path":"carracing_kerasrl_naf_train.py","file_name":"carracing_kerasrl_naf_train.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"222049318","text":"import copy\nimport math\n\nimport numpy as np\n\nfrom animation_framework import modifier\nfrom animation_framework import posquat as pq\nfrom animation_framework import utilities as tr\nfrom animation_framework import modifier_displacement as disp\nfrom animation_framework import skeleton\nfrom animation_framework import inertialize as iner\n\n\ndef _build_one_animation_db(skel, anim):\n\n lfpos = anim[0][:, skel.leftfootid, :]\n rfpos = anim[0][:, skel.rightfootid, :]\n hipsvec = tr.compute_vector(anim[0][:, skel.hipsid, :])\n lfvec = tr.compute_vector(lfpos)\n rfvec = tr.compute_vector(rfpos)\n\n # using the speed let's find how far we can try to find the best first frame\n # we will say that we can go up to the middle of the first step\n # find which foot moves first\n lfvel = tr.compute_speed(lfpos)\n rfvel = tr.compute_speed(rfpos)\n lfstart = np.argwhere(lfvel > 2)[0][0]\n rfstart = np.argwhere(rfvel > 2)[0][0]\n foot_velocity = lfvel\n foot_start = lfstart\n if rfstart < lfstart:\n foot_velocity = rfvel\n foot_start = rfstart\n # find middle of the foot motion\n max_starting_frame = foot_start + np.argwhere(foot_velocity[foot_start:] < 2)[0][0] // 2\n\n # now we check how many frames at the end of the animation we can match\n # we will only look for frames where both feet are on the ground\n max_end_frame = np.argwhere(np.bitwise_or(lfvel[::-1] > 2, rfvel[::-1] > 2))[0][0] - 1\n\n db = []\n\n # build the matrix of mapping\n for startFrame in range(0, max_starting_frame, 3):\n for endFrame in range(len(lfvel)-max_end_frame, len(lfvel), 3):\n start_anim_frame = startFrame\n end_anim_frame = endFrame\n assert(end_anim_frame > start_anim_frame)\n\n frame_lfpos = lfpos[start_anim_frame, :]\n frame_rfpos = rfpos[start_anim_frame, :]\n frame_hipsvec = hipsvec[start_anim_frame, :]\n frame_lfvec = lfvec[start_anim_frame, :]\n frame_rfvec = rfvec[start_anim_frame, :]\n frame_lastlf = lfpos[end_anim_frame, :]\n frame_lastrf = rfpos[end_anim_frame, :]\n frame_lasthips = pq.transform_point(\n (anim[0][end_anim_frame, 0, :], anim[1][end_anim_frame, 0, :]),\n np.array([0, 30, 0])\n )\n\n inverse_root = pq.inv((anim[0][start_anim_frame, 0, :], anim[1][start_anim_frame, 0, :]))\n table = np.concatenate([\n pq.transform_point(inverse_root, frame_lfpos)[np.newaxis, ...],\n pq.transform_point(inverse_root, frame_rfpos)[np.newaxis, ...],\n pq.transform_vector(inverse_root, frame_lfvec)[np.newaxis, ...],\n pq.transform_vector(inverse_root, frame_rfvec)[np.newaxis, ...],\n pq.transform_vector(inverse_root, frame_hipsvec)[np.newaxis, ...],\n pq.transform_point(inverse_root, frame_lastlf)[np.newaxis, ...],\n pq.transform_point(inverse_root, frame_lastrf)[np.newaxis, ...],\n pq.transform_point(inverse_root, frame_lasthips)[np.newaxis, ...]],\n axis=-1\n ).reshape(8, 3)\n\n # check if it is useful to add this in the list\n if db :\n vec = db[-1][1] - table\n dist = np.sum(vec * vec)\n if dist < 0.05:\n continue\n db.append(((start_anim_frame, end_anim_frame), table))\n\n return db\n\n\ndef _build_one_query(skel, a, b):\n lfpos = a[0][-2:, skel.leftfootid, :]\n rfpos = a[0][-2:, skel.rightfootid, :]\n hipsvec = tr.compute_vector(a[0][-2:, skel.hipsid, :])[-1]\n lfvec = tr.compute_vector(lfpos)[-1]\n rfvec = tr.compute_vector(rfpos)[-1]\n lfpos = lfpos[-1]\n rfpos = rfpos[-1]\n lastlf = b[0][0, skel.leftfootid, :]\n lastrf = b[0][0, skel.rightfootid, :]\n lasthips = pq.transform_point(\n (b[0][0, 0, :], b[1][0, 0, :]),\n np.array([0, 30, 0])\n )\n\n inverse_root = pq.inv((a[0][-1, 0, :], a[1][-1, 0, :]))\n return np.concatenate([\n pq.transform_point(inverse_root, lfpos)[np.newaxis, ...],\n pq.transform_point(inverse_root, rfpos)[np.newaxis, ...],\n pq.transform_vector(inverse_root, lfvec)[np.newaxis, ...],\n pq.transform_vector(inverse_root, rfvec)[np.newaxis, ...],\n pq.transform_vector(inverse_root, hipsvec)[np.newaxis, ...],\n pq.transform_point(inverse_root, lastlf)[np.newaxis, ...],\n pq.transform_point(inverse_root, lastrf)[np.newaxis, ...],\n pq.transform_point(inverse_root, lasthips)[np.newaxis, ...]],\n axis=-1\n ).reshape(8, 3)\n\n\ndef find_best_frame(mapping_db, query):\n weights = np.array([\n [1, 1, 1],\n [1, 1, 1],\n [30, 30, 30],\n [30, 30, 30],\n [45, 45, 45],\n [1, 1, 1],\n [1, 1, 1],\n [3, 3, 3]\n ])\n min_error = 1E+8\n animid = 0\n framesid = 0\n for i, mapping in enumerate(mapping_db):\n for frames, matrix in mapping:\n vec = matrix - query\n dist = np.sum(vec * vec * weights)\n if dist < min_error:\n min_error = dist\n animid = i\n framesid = frames\n return animid, framesid[0], framesid[1]\n\n\ndef build_mapping_table(skel:skeleton.Skeleton, animation_db):\n\n return [_build_one_animation_db(skel, anim) for anim in animation_db]\n\n\ndef create_transition(skel:skeleton.Skeleton, anim_db, mapping_db, a, b):\n\n # build animation\n total_len = len(a[0]) + len(b[0]) + 500\n gpos, gquat = np.zeros([total_len, len(skel.bones), 3]), np.zeros([total_len, len(skel.bones), 4])\n\n # start\n cframe = 0\n clen = len(a[0])\n gpos[cframe:cframe+clen, ...] = a[0][...]\n gquat[cframe:cframe+clen, ...] = a[1][...]\n cframe = cframe+clen\n\n\n # build query\n query = _build_one_query(skel, a, b)\n bestanim, beststartframe, bestendframe = find_best_frame(mapping_db, query)\n print(('transition found in', bestanim, beststartframe, bestendframe))\n\n # re align to the end of the animation\n gpostr, gquattr = anim_db[bestanim][0][beststartframe:bestendframe, ...], anim_db[bestanim][1][beststartframe:bestendframe, ...]\n gpostr, gquattr = disp.set_displacement_origin(\n skel,\n (gpostr, gquattr),\n (a[0][-1, 0, :], a[1][-1, 0, :])\n )\n\n '''\n # warp\n gpostr, gquattr = modifier.warp(\n skel,\n (gpostr, gquattr),\n (a[0][-1, :, :], a[1][-1, :, :]),\n (b[0][0, :, :], b[1][0, :, :])\n )\n '''\n\n clen = len(gpostr)\n gpos[cframe:cframe + clen, ...] = gpostr\n gquat[cframe:cframe + clen, ...] = gquattr\n warpframe = cframe\n warpframeend = cframe+clen\n cframe = cframe + clen\n\n clen = len(b[0])\n gpos[cframe:cframe + clen, ...] = b[0][...]\n gquat[cframe:cframe + clen, ...] = b[1][...]\n\n modifier.inplace_warp_feet_inertialize_body(\n skel,\n (gpos, gquat),\n warpframe,\n warpframeend,\n 15\n )\n\n hipsp, hipsq = gpos[cframe:cframe + clen, skel.hipsid, ...], gquat[cframe:cframe + clen, skel.hipsid, ...]\n lfp, lfq = gpos[cframe:cframe + clen, skel.leftfootid, ...], gquat[cframe:cframe + clen, skel.leftfootid, ...]\n rfp, rfq = gpos[cframe:cframe + clen, skel.rightfootid, ...], gquat[cframe:cframe + clen, skel.rightfootid, ...]\n\n gpos, gquat = skel.local_to_global(\n iner.inplace_inertialize(\n skel.global_to_local((gpos, gquat)),\n cframe, 20\n )\n )\n\n gpos[cframe:cframe + clen, ...], gquat[cframe:cframe + clen, ...] = skel.foot_ik(\n (hipsp, hipsq),\n (lfp, lfq),\n (rfp, rfq),\n (gpos[cframe:cframe + clen, ...], gquat[cframe:cframe + clen, ...])\n )\n\n cframe = cframe + clen\n\n return gpos[:cframe, ...], gquat[:cframe, ...]\n","sub_path":"animation/npk/transition_type_b.py","file_name":"transition_type_b.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"73674397","text":"from utils.ClientModels import *\n\n\nclass sqlOperation:\n\n @classmethod\n def selectusecasegroup(cls):\n # 查询所有用例组\n lis = []\n gops = UsecaseGroup.select()\n for gop in gops:\n lis.append([gop.usecase_group_number, gop.name, gop.usecase])\n return lis\n\n @classmethod\n def selectProcedures(cls):\n # 查询规程\n lis = []\n gops = Procedure.select()\n for gop in gops:\n lis.append([gop.number, gop.name, gop.usecase])\n return lis\n\n @classmethod\n def selectUsecase(cls, name):\n # 通过用例组名称查询用例组\n gops = UsecaseGroup.select().where(UsecaseGroup.name == name)\n for gop in gops:\n return eval(gop.usecase)\n\n @classmethod\n def selectProceduresID(cls, number):\n # 根据规程编码查询对应规程id\n gops = Procedure.select().where(Procedure.number == number)\n for gop in gops:\n return gop.id\n\n @classmethod\n def deleteProcedures(cls, number):\n # 删除规程\n Procedure.delete_obj(cls.selectProceduresID(number))\n\n @classmethod\n def selectUsecaseNum(cls, number):\n \"\"\"通过用例编号查找\"\"\"\n gops = Usecase.select().where(Usecase.number == number)\n for gop in gops:\n return gop.id\n\n @classmethod\n def deleteUsecase(cls, number):\n \"\"\"删除\"\"\"\n Usecase.delete_obj(cls.selectUsecaseNum(number))\n\n @classmethod\n def searchUsecaseGroup(cls, text):\n \"\"\"模糊查询用例组\"\"\"\n lis = []\n usecasegroups = UsecaseGroup.select().where(\n (UsecaseGroup.name.contains(text)) |\n (UsecaseGroup.usecase_group_number.contains(text))\n )\n if len(usecasegroups):\n for usecasegroup in usecasegroups:\n lis.append([usecasegroup.usecase_group_number, usecasegroup.name, usecasegroup.usecase])\n return lis\n\n @classmethod\n def searchProcedures(cls, text):\n \"\"\"模糊查询规程\"\"\"\n lis = []\n procedures = Procedure.select().where(\n (Procedure.name.contains(text)) |\n (Procedure.number.contains(text))\n )\n if len(procedures):\n for procedure in procedures:\n lis.append([procedure.number, procedure.name, procedure.usecase])\n return lis\n","sub_path":"DcsUi/useCaseGroupManagement/SQLOperation.py","file_name":"SQLOperation.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125254722","text":"#file path to insert: hangman.txt\n\n#Welcome screen of the game\ndef ascii_art ():\n HANGMAN_ASCII_ART=\"\"\"\n _ _\n | | | |\n | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __\n | __ |/ _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\\\\n | | | | (_| | | | | (_| | | | | | | (_| | | | |\n |_| |_|\\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_|\n __/ |\n |___/\"\"\"\n print(HANGMAN_ASCII_ART)\n\n#reading the file contains words list\ndef choose_word(file_path, index):\n input_file = open(file_path, \"r\")\n words_lst= input_file.read()\n words_lst= words_lst.split(' ')\n unique_word=[]\n len_lst=len(words_lst)\n # in case the user insert an index that not exists (bigger than max),\n # Continue counting from the beginning of the list\n if index > len_lst:\n index=index-len_lst\n for i in words_lst:\n if i not in unique_word:\n unique_word.append(i)\n specific_word= words_lst[index-1]\n return specific_word\n\n#hangman photo for each number of incorrect guesses\ndef print_hangman(num_of_tries):\n HANGMAN_PHOTOS = {\n 1:\"\"\"\n x-------x\"\"\",\n\n\n 2:\"\"\"\n x-------x\n |\n |\n |\n |\n |\"\"\",\n\n 3:\"\"\"\n x-------x\n | |\n | 0\n |\n |\n |\"\"\",\n\n 4:\"\"\"\n x-------x\n | |\n | 0\n | |\n |\n |\"\"\",\n\n 5:\"\"\"\n x-------x\n | |\n | 0\n | /|\\\\\n |\n |\"\"\",\n\n 6:\"\"\"\n x-------x\n | |\n | 0\n | /|\\\\\n | /\n |\"\"\",\n\n 7:\"\"\"\n x-------x\n | |\n | 0\n | /|\\\\\n | / \\\\\n |\"\"\"}\n print (HANGMAN_PHOTOS[num_of_tries])\n\n#showing the current status of the hidden word- letters/blanks\ndef show_hidden_word(secret_word, old_letters_guessed):\n user_guess_list=[]\n for letter in secret_word:\n if letter in old_letters_guessed:\n user_guess_list.append(letter+\" \")\n else:\n user_guess_list.append(\"_ \")\n user_guess_str= \"\".join (user_guess_list)\n print( user_guess_str)\n\n#check validation of the guess and show letters that was guessed\ndef try_update_letter_guessed(letter_guessed, old_letters_guessed):\n if len(letter_guessed) > 1 or letter_guessed.isalpha() == False or letter_guessed.lower() in old_letters_guessed:\n old_letters_guessed.sort()\n old_letters_guessed_arrow = \"-> \".join(old_letters_guessed)\n print ('X')\n print(old_letters_guessed_arrow)\n return False\n else:\n letters_guessed_lower = letter_guessed.lower()\n old_letters_guessed.append(letters_guessed_lower)\n return True\n\n# Check if the user win or lose the game\ndef check_win(secret_word, old_letters_guessed):\n right_guesses=0\n for letter in secret_word:\n if letter in old_letters_guessed:\n right_guesses+=1\n if right_guesses == len(secret_word):\n print ('WIN')\n return True\n else:\n return False\n\ndef main():\n #variables\n num_of_tries=1\n win=False\n MAX_TRIES=int(7)\n old_letters_guessed = []\n\n ascii_art()\n print ('Number of tries:',MAX_TRIES-1)\n print ('Let’s start!')\n user_path= input (\"Enter file path:\")\n user_index= int(input (\"Enter index:\"))\n secret_word= choose_word(user_path,user_index)\n print_hangman(1)\n show_hidden_word(secret_word,old_letters_guessed)\n\n while num_of_tries < MAX_TRIES and win==False:\n user_guessed = input(\"Guess a letter:\")\n valid_letter = try_update_letter_guessed(user_guessed, old_letters_guessed)\n if valid_letter:\n show_hidden_word(secret_word, old_letters_guessed)\n num_of_tries += 1\n if user_guessed in secret_word:\n if user_guessed not in old_letters_guessed :\n old_letters_guessed.append(user_guessed)\n else:\n print(':(')\n print_hangman(num_of_tries)\n win = check_win(secret_word, old_letters_guessed)\n if num_of_tries ==MAX_TRIES and win==False:\n print ('LOSE')\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Hangman10.py","file_name":"Hangman10.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"95316095","text":"#!/usr/bin/env python\n\nimport datetime \nimport sys \nimport threading \nfrom tkinter import * ##tkinter is the one of the GUI library\n\nminute = 60 * int(sys.argv[1]) \nCurtime = datetime.datetime.now() \nprint (\"time now\",Curtime) \nScrtime = Curtime + datetime.timedelta(0,minute,0) \nprint(\"distance time\",Scrtime) \n\ndef wait(): \n\tthreading._sleep(minute) \n\ndef Start(): \n\tDsttime = datetime.datetime.now() \n\ttmp = Dsttime - Scrtime + Scrtime \n\tprint(\"current time\",tmp) \n\tif tmp == Dsttime: \n\t\tclass App(Frame): \n\t\t\tdef __init__(self,master = None): \n\t\t\t\tFrame.__init__(self,master) \n\t\t\t\tself.pack() \n\t\tmyapp = App() \n\t\tmyapp.master.title(\"\") \n\t\tmyapp.master.maxsize(150,0) \n\t\tmyapp.mainloop() \n\telse: \n\t\tprint(\"NO\") \n\twait() \n\nStat() \n\n\n","sub_path":"python_practise/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283814620","text":"import abc\nfrom enum import Enum\nimport tensorflow as tf\nfrom .flowlib import flow_to_image\nimport numpy as np\nslim = tf.contrib.slim\n\n\nclass Mode(Enum):\n TRAIN = 1\n TEST = 2\n\n\nclass Net(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, mode=Mode.TRAIN, debug=False):\n self.global_step = slim.get_or_create_global_step()\n self.mode = mode\n self.debug = debug\n\n @abc.abstractmethod\n def model(self, inputs, training_schedule):\n \"\"\"\n Defines the model and returns a tuple of Tensors needed for calculating the loss.\n \"\"\"\n return\n\n @abc.abstractmethod\n def loss(self, **kwargs):\n \"\"\"\n Accepts prediction Tensors from the output of `model`.\n Returns a single Tensor representing the total loss of the model.\n \"\"\"\n return\n\n def train(self, log_dir, training_schedule, input_a, input_b, flow):\n tf.summary.image(\"image_a\", input_a, max_outputs=2)\n tf.summary.image(\"image_b\", input_b, max_outputs=2)\n\n self.learning_rate = tf.train.piecewise_constant(\n self.global_step,\n [tf.cast(v, tf.int64) for v in training_schedule['step_values']],\n training_schedule['learning_rates'])\n\n optimizer = tf.train.AdamOptimizer(\n self.learning_rate,\n training_schedule['momentum'],\n training_schedule['momentum2'])\n\n inputs = {\n 'input_a': input_a,\n 'input_b': input_b,\n }\n predictions = self.model(inputs, training_schedule)\n total_loss = self.loss(flow, predictions)\n tf.summary.scalar('loss', total_loss)\n\n # Show the generated flow in TensorBoard\n if 'flow' in predictions:\n pred_flow_0 = predictions['flow'][0, :, :, :]\n pred_flow_0 = tf.py_func(flow_to_image, [pred_flow_0], tf.uint8)\n pred_flow_1 = predictions['flow'][1, :, :, :]\n pred_flow_1 = tf.py_func(flow_to_image, [pred_flow_1], tf.uint8)\n pred_flow_img = tf.stack([pred_flow_0, pred_flow_1], 0)\n tf.summary.image('pred_flow', pred_flow_img, max_outputs=2)\n\n true_flow_0 = flow[0, :, :, :]\n true_flow_0 = tf.py_func(flow_to_image, [true_flow_0], tf.uint8)\n true_flow_1 = flow[1, :, :, :]\n true_flow_1 = tf.py_func(flow_to_image, [true_flow_1], tf.uint8)\n true_flow_img = tf.stack([true_flow_0, true_flow_1], 0)\n tf.summary.image('true_flow', true_flow_img, max_outputs=2)\n\n train_op = slim.learning.create_train_op(\n total_loss,\n optimizer,\n summarize_gradients=True)\n\n if self.debug:\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n tf.train.start_queue_runners(sess)\n slim.learning.train_step(\n sess,\n train_op,\n self.global_step,\n {\n 'should_trace': tf.constant(1),\n 'should_log': tf.constant(1),\n 'logdir': log_dir + '/debug',\n }\n )\n else:\n slim.learning.train(\n train_op,\n log_dir,\n # session_config=tf.ConfigProto(allow_soft_placement=True),\n global_step=self.global_step,\n save_summaries_secs=60,\n number_of_steps=training_schedule['max_iter']\n )\n","sub_path":"src/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"373721423","text":"\"\"\"\nМ х N. M и N задаёт пользователь с клавиатуры.\n\nОбязательные условия:\n\nматрица создаётся при помощи list comprehension. При создании, список заполняется случайными числами (используйте генератор случайных чисел)\nнеобходимо посчитать сумму значений каждой строки (функцию sum() использовать НЕЛЬЗЯ). Сумма выводится напротив соответствующих строк\nнеобходимо посчитать сумму значений каждой колонки (функцию sum() использовать НЕЛЬЗЯ). Сумма выводится под соответствующей колонкой\nможно использовать ТОЛЬКО ОДИН, одномерный, дополнительный список\nможно использовать ТОЛЬКО ОДНУ дополнительную переменную\nвывод программы ДОЛЖЕН соответствовать примеру ниже (для форматирования вывода, вам понадобится функция format())\nзадача считается выполненной ТОЛЬКО при строгом выполнении всех условий.\n\"\"\"\n\nfrom random import randint\n\nM = int(input('Please enter the number of columns: '))\nN = int(input('Please enter the number of strings: '))\n\nmatrix = [[randint(10, 99) for j in range(M)] for i in range(N)]\n\n\ndef sum_elements_row(array, num1, num2):\n sum_lst = []\n for i in range(num1):\n sum_el = 0\n for j in range(num2):\n sum_el += array[i][j]\n sum_lst.insert(i, sum_el)\n return sum_lst\n\n\ndef sum_elements_col(array, num1, num2):\n sum_lst = []\n for i in range(num1):\n sum_el = 0\n for j in range(num2):\n sum_el += array[j][i]\n sum_lst.insert(i, sum_el)\n return sum_lst\n\n\nfor i in range(N):\n for j in range(M):\n print(' {}'.format(matrix[i][j]), end=' ')\n print('| {}'.format(sum_elements_row(matrix, N, M)[i]))\n\nfor k in range(M):\n print('{}'.format(sum_elements_col(matrix, M, N)[k]), end=' ')","sub_path":"Lesson_11/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"60687913","text":"## Loads preprocessed train and test data, applies linear\n# regression and generalized linear regression to the data\n\nimport json\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.model_selection import cross_val_score, KFold\nfrom movie_lengths_lib import *\n\n#------------------------------------------------------------------------------\n\nprint (\"Loading data from files\")\n\nX_train = load_data_from_file ( file_X_train )\ny_train = load_data_from_file ( file_y_train )\nX_test = load_data_from_file ( file_X_test )\ny_test = load_data_from_file ( file_y_test )\nheader = load_data_from_file ( file_header )\n\nprint (\"X_train shape: {}\".format(X_train.shape))\nprint (\"y_train shape: {}\".format(y_train.shape))\nprint (\"X_test shape: {}\".format(X_test.shape))\nprint (\"y_test shape: {}\".format(y_test.shape))\nprint ()\n\nprint (\"Linear regression:\")\nlinear_regression = LinearRegression(fit_intercept=True, normalize=True, copy_X=True)\ntheta = linear_regression.fit(X_train, y_train)\n\n\nprint (\"ATTRIBUTE | COEFFICIENT\")\nprint (\"-----------------------------------------\")\nfor col in range(header.shape[1]):\n print ( \"{:15s}{}\".format(header[0,col], linear_regression.coef_[0,col]) )\nprint (\"-----------------------------------------\")\n\n\nkf = KFold(n_splits=10)\ntrain_score = (cross_val_score(linear_regression, X_train, y_train, cv=kf)).mean()\ntest_score = linear_regression.score(X_test, y_test)\nprint(\"Train score: {}\".format(train_score))\nprint(\"Test score: {}\".format(test_score))\n\n\nprint ()\nprint (\"Generalized linear regression on first 500 train samples (100 test samples)\")\n\ndef polynomial(X_train, y_train, X_test, y_test, k):\n print (\"-----------------------------------------\")\n print (\"k = {}\".format(k))\n poly = PolynomialFeatures(degree=k)\n X_train_t = poly.fit_transform(X_train)\n X_test_t = poly.fit_transform(X_test)\n linear_regression = LinearRegression(fit_intercept=True, normalize=True, copy_X=True)\n theta = linear_regression.fit(X_train_t, y_train)\n kf = KFold(n_splits=10)\n train_score = (cross_val_score(linear_regression, X_train_t, y_train, cv=kf)).mean()\n train_score = linear_regression.score (X_train_t, y_train)\n test_score = linear_regression.score (X_test_t, y_test)\n print(\"Train score: {}\".format(train_score))\n print(\"Test score: {}\".format(test_score))\n\n\nfor i in range(1,5):\n polynomial(X_train[:500,:], y_train[:500,:], X_test[:100,:], y_test[:100,:], i)","sub_path":"p3_reg.py","file_name":"p3_reg.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"13811957","text":"#!/usr/bin/env python3\n\nimport argparse\nimport ast\nimport datetime\nimport fnmatch\nimport hashlib\nimport os\nimport shutil\nimport subprocess\nimport sys\n\n\n# Python 2 compatibility fix.\ntry:\n FileNotFoundError\nexcept NameError:\n FileNotFoundError = IOError\n\n\nclass Error(Exception):\n pass\n\n\nclass _Path(object):\n def __init__(self, path=[]):\n if not path:\n self._comps = []\n elif isinstance(path, _Path):\n self._comps = path._comps\n elif isinstance(path, list):\n self._comps = path\n else:\n assert isinstance(path, str), repr(path)\n self._comps = [path]\n\n def get_as_string(self):\n return os.path.join(*tuple(self._comps))\n\n def __add__(self, other):\n return _Path(self._comps + _Path(other)._comps)\n\n def get_dirname(self):\n return _Path(self._comps[:-1])\n\n def get_basename(self):\n return self._comps[-1]\n\n def add_extension(self, ext):\n new_basename = self.get_basename() + ext\n return self.get_dirname() + new_basename\n\n def __iter__(self):\n for comp in self._comps:\n yield comp\n\n\nclass _Package(object):\n def __init__(self, filehash, filename):\n self._filehash = filehash\n self._filename = filename\n\n def get_filehash(self):\n return self._filehash\n\n def get_filename(self):\n return self._filename\n\n\nclass _RepositoryIndex(object):\n def __init__(self, collect_files=False):\n self._collect_files = collect_files\n if collect_files:\n self._index = dict()\n\n def add_file_path(self, path):\n if not self._collect_files:\n return\n\n i = self._index\n for comp in path.get_dirname():\n i = i.setdefault(comp, dict())\n i[path.get_basename()] = None\n\n def get(self):\n assert self._collect_files\n index_copy = dict(self._index)\n return index_copy\n\n\nclass _ComponentArch(object):\n def __init__(self, arch_id, component):\n self._id = arch_id\n self._component = component\n\n def get_id(self):\n return self._id\n\n def get_component(self):\n return self._component\n\n def get_component_id(self):\n return self._component.get_id()\n\n def get_distribution(self):\n return self._component.get_distribution()\n\n def get_packages(self):\n return self._component.get_packages_in_arch(self)\n\n def get_path_in_distribution(self):\n return self._component.get_path_in_distribution()\n\n\nclass _Component(object):\n def __init__(self, component_id, dist):\n self._id = component_id\n self._dist = dist\n\n def get_id(self):\n return self._id\n\n def get_distribution(self):\n return self._dist\n\n def get_archs(self):\n return self._dist.get_archs_in_component(self)\n\n def get_packages_in_arch(self, arch):\n assert isinstance(arch, _ComponentArch)\n assert arch.get_component() is self\n return self._dist.get_packages_in_component_arch(arch)\n\n def get_path_in_distribution(self):\n return _Path([self._id])\n\n\nclass _DistributionArch(object):\n def __init__(self, arch_id, dist):\n self._id = arch_id\n self._dist = dist\n\n def get_id(self):\n return self._id\n\n def get_distribution(self):\n return self._dist\n\n def get_packages(self):\n return self._dist.get_packages_in_arch(self)\n\n def get_path_in_distribution(self):\n return _Path()\n\n\nclass _DistributionIndex(object):\n def __init__(self):\n self._index = dict()\n\n def get(self):\n return self._index\n\n def add(self, path, hashes, filesize):\n assert path not in self._index\n self._index[path] = hashes, filesize\n\n\nclass _Distribution(object):\n def __init__(self, dist_id, repo_index):\n self._id = dist_id\n self._index = _DistributionIndex()\n self._repo_index = repo_index\n self._packages = dict()\n\n def get_id(self):\n return self._id\n\n def get_index(self):\n return self._index\n\n def get_repository_index(self):\n return self._repo_index\n\n def add_package(self, component_id, arch_id, package):\n key = component_id, arch_id\n filenames = self._packages.setdefault(key, dict())\n filename = package.get_filename()\n if filename in filenames:\n full_component_id = '%s:%s' % (self._dist_id, component_id)\n raise Error('More than one package %r in component %r, '\n 'architecture %r.' % (filename, full_component_id,\n arch_id))\n\n filenames[filename] = package.get_filehash()\n\n # Returns components of this distribution.\n def get_components(self):\n ids = {component_id for component_id, arch_id in self._packages}\n for id in ids:\n yield _Component(id, self)\n\n # Returns architectures of this distribution's component.\n def get_archs_in_component(self, component):\n assert component.get_distribution() is self\n component_id = component.get_id()\n ids = {arch_id for comp_id, arch_id in self._packages\n if comp_id == component_id}\n for id in ids:\n yield _ComponentArch(id, component)\n\n # Returns architectures of all components in this distribution.\n def get_archs_in_all_components(self):\n for component in self.get_components():\n for arch in component.get_archs():\n yield arch\n\n # Returns architectures of this distribution.\n def get_archs(self):\n ids = {arch_id for component_id, arch_id in self._packages}\n for id in ids:\n yield _DistributionArch(id, self)\n\n # Returns packages for specific component architecture in\n # this distribution.\n def get_packages_in_component_arch(self, arch):\n assert isinstance(arch, _ComponentArch)\n assert arch.get_distribution() is self\n target_key = arch.get_component_id(), arch.get_id()\n for key, filenames in self._packages.items():\n if key == target_key:\n for filename, filehash in filenames.items():\n yield _Package(filehash, filename)\n\n # Returns packages for a specific architecture in this distribution.\n def get_packages_in_arch(self, arch):\n assert isinstance(arch, _DistributionArch)\n assert arch.get_distribution() is self\n target_arch_id = arch.get_id()\n for (component_id, arch_id), filenames in self._packages.items():\n if arch_id == target_arch_id:\n for filename, filehash in filenames.items():\n yield _Package(filehash, filename)\n\n\nclass Repository(object):\n _DEFAULT_CONFIG = {\n 'origin': 'Default Origin',\n 'label': 'Default Label',\n 'gpg_key_id': 'none',\n }\n\n _PACKAGE_FIELD = 'Package'\n _SECTION_FIELD = 'Section'\n _ARCH_FIELD = 'Architecture'\n\n _MAKEAPT_FIELD_PREFIX = '__'\n _CONTENTS_FIELD = '%scontents' % _MAKEAPT_FIELD_PREFIX\n _FILESIZE_FIELD = '%sfilesize' % _MAKEAPT_FIELD_PREFIX\n\n # We prefer these fields always be specified in this order.\n _DEB_INFO_FIELDS = [\n _PACKAGE_FIELD,\n 'Version',\n _SECTION_FIELD,\n 'Priority',\n _ARCH_FIELD,\n 'Installed-Size',\n 'Depends',\n 'Maintainer',\n 'Uploaders',\n 'Homepage',\n 'Description',\n ]\n\n # The name of the directory where we store .deb files.\n POOL_DIR_NAME = 'pool'\n\n # The directory where we store distribution index files.\n DISTS_DIR = _Path('dists')\n\n # Canonical makeapt names of hash algorithms. APT\n # repositories use different names for the same hash\n # algorithms, so for internal use we have to define their\n # canonical names.\n _CANONICAL_HASH_NAMES = {\n 'md5': 'md5',\n 'MD5Sum': 'md5',\n 'MD5sum': 'md5',\n 'sha1': 'sha1',\n 'SHA1': 'sha1',\n 'sha256': 'sha256',\n 'SHA256': 'sha256',\n 'sha512': 'sha512',\n 'SHA512': 'sha512',\n }\n\n # The map of known hash algorithms. The keys are their\n # canonical names.\n _HASH_ALGOS = {\n 'md5': hashlib.md5,\n 'sha1': hashlib.sha1,\n 'sha256': hashlib.sha256,\n 'sha512': hashlib.sha512,\n }\n\n # The hash algorithm used to find identical packages.\n _KEY_HASH_NAME = _CANONICAL_HASH_NAMES['sha1']\n\n # The names of hashes used in main distribution indexes. Come\n # in order we want them in the index files.\n _DISTRIBUTION_INDEX_HASH_NAMES = [\n 'MD5Sum', # Note the uppercase 'S' in 'MD5Sum'.\n 'SHA1', 'SHA256']\n\n # Buffer size for file I/O, in bytes.\n _BUFF_SIZE = 4096\n\n # Names of various makeapt files.\n _CONFIG_FILENAME = 'config'\n _INDEX_FILENAME = 'index'\n _CACHE_FILENAME = 'cache'\n\n def __init__(self, path='', use_makeapt_dir=True):\n self._apt_path = _Path(path)\n self._use_makeapt_dir = use_makeapt_dir\n if use_makeapt_dir:\n self._makeapt_path = self._apt_path + '.makeapt'\n self._pool_path = self._apt_path + self.POOL_DIR_NAME\n\n def __enter__(self):\n # TODO: Lock the repository.\n self._load_config()\n self._load_index()\n self._load_cache()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._flush_index()\n self._flush_cache()\n self._flush_config()\n # TODO: Unlock the repository.\n\n def get_config(self):\n # Always return a copy of the actual config.\n config_copy = dict(self._config)\n return config_copy\n\n def get_config_field(self, field):\n config = self.get_config()\n return config[field]\n\n def set_config_field(self, field, value):\n self._config[field] = value\n\n def _make_dir(self, path):\n path_string = path.get_as_string()\n if not os.path.exists(path_string):\n os.makedirs(path_string)\n\n def _make_file_dir(self, path):\n self._make_dir(path.get_dirname())\n\n def _save_file(self, path, content):\n self._make_file_dir(path)\n with open(path.get_as_string(), 'wb') as f:\n for chunk in content:\n if isinstance(chunk, str):\n chunk = chunk.encode('utf-8')\n f.write(chunk)\n\n def _gzip(self, path):\n # TODO: Can _run_shell() return a generator?\n # TODO: Should we do that with a Python library?\n yield self._run_shell(['gzip', '--keep', '--best', '--no-name',\n '--stdout', path.get_as_string()])\n\n def _bzip2(self, path):\n # TODO: Can _run_shell() return a generator?\n # TODO: Should we do that with a Python library?\n yield self._run_shell(['bzip2', '--keep', '--best',\n '--stdout', path.get_as_string()])\n\n def init(self):\n '''Initializes APT repository.'''\n if self._use_makeapt_dir:\n self._make_dir(self._makeapt_path)\n self._make_dir(self._pool_path)\n # TODO: Should we make the 'dists' directory?\n\n def _load_makeapt_file(self, filename, default):\n if not self._use_makeapt_dir:\n return default\n\n try:\n path = self._makeapt_path + filename\n with open(path.get_as_string(), 'r') as f:\n return ast.literal_eval(f.read())\n except FileNotFoundError:\n return default\n\n # Writes a given value in consistent and human-readable way.\n def _emit_literal(self, value, level=0):\n indent = ' '\n nested_level = level + 1\n if isinstance(value, dict):\n yield '{\\n'\n for key in sorted(value):\n yield indent * nested_level\n yield '%r: ' % key\n for chunk in self._emit_literal(value[key], nested_level):\n yield chunk\n yield indent * level + '}'\n elif isinstance(value, set):\n yield '{\\n'\n for element in sorted(value):\n yield indent * nested_level\n for chunk in self._emit_literal(element, nested_level):\n yield chunk\n yield indent * level + '}'\n else:\n yield repr(value)\n\n if level > 0:\n yield ','\n yield '\\n'\n\n def _save_makeapt_file(self, filename, value):\n if not self._use_makeapt_dir:\n return\n\n path = self._makeapt_path + filename\n with open(path.get_as_string(), 'w') as f:\n for chunk in self._emit_literal(value):\n f.write(chunk)\n\n def _load_config(self):\n default_config_copy = dict(self._DEFAULT_CONFIG)\n config = self._load_makeapt_file(self._CONFIG_FILENAME,\n default_config_copy)\n\n # Make sure all fields are in place.\n for field, default_value in self._DEFAULT_CONFIG.items():\n if field not in config:\n config[field] = default_value\n\n self._config = config\n\n def _flush_config(self):\n self._save_makeapt_file(self._CONFIG_FILENAME, self._config)\n del self._config\n\n def _load_index(self):\n index = self._load_makeapt_file(self._INDEX_FILENAME, dict())\n\n # Fix the type of empty groups that 'literal_eval()'\n # reads as dict's and not set's.\n for filehash, filenames in index.items():\n for filename, groups in filenames.items():\n if isinstance(groups, dict):\n assert not groups\n groups = set()\n filenames[filename] = groups\n\n self._index = index\n\n def _flush_index(self):\n self._save_makeapt_file(self._INDEX_FILENAME, self._index)\n del self._index\n\n def _load_cache(self):\n self._cache = self._load_makeapt_file(self._CACHE_FILENAME, dict())\n\n def _flush_cache(self):\n self._save_makeapt_file(self._CACHE_FILENAME, self._cache)\n del self._cache\n\n # Hashes a given file with a set of specified algorithms.\n def _hash_file(self, path, hash_names):\n # Handle the case when only one algorithm is specified.\n if isinstance(hash_names, str):\n hash_name = hash_names\n return self._hash_file(path, {hash_name})[hash_name]\n\n # Initialize messages.\n msgs = {name: self._HASH_ALGOS[self._CANONICAL_HASH_NAMES[name]]()\n for name in hash_names}\n\n # Read out the file by chunks and update messages.\n with open(path.get_as_string(), 'rb') as f:\n for chunk in iter(lambda: f.read(self._BUFF_SIZE), b''):\n for hash_name, msg in msgs.items():\n msg.update(chunk)\n\n return {hash_name: msg.hexdigest() for hash_name, msg in msgs.items()}\n\n def _copy_file(self, src, dest, overwrite=True):\n self._make_file_dir(dest)\n\n dest_string = dest.get_as_string()\n if overwrite or not os.path.exists(dest_string):\n shutil.copyfile(src.get_as_string(), dest_string)\n\n def _link_or_copy_apt_file(self, src, dest_in_apt):\n # TODO: Use links by default and fallback to copies on an option.\n self._copy_file(src, self._apt_path + dest_in_apt)\n\n def _get_package_path_in_pool(self, package):\n filehash = package.get_filehash()\n filename = package.get_filename()\n return _Path([filehash[:2], filehash[2:], filename])\n\n def _get_package_path_in_apt(self, package):\n return (_Path([self.POOL_DIR_NAME]) +\n self._get_package_path_in_pool(package))\n\n def _get_full_package_path(self, package):\n return self._apt_path + self._get_package_path_in_apt(package)\n\n def _add_package_to_pool(self, path):\n filehash = self._hash_file(_Path([path]), self._KEY_HASH_NAME)\n filename = os.path.basename(path)\n package = _Package(filehash, filename)\n path_in_pool = self._get_package_path_in_pool(package)\n dest_path = self._pool_path + path_in_pool\n self._copy_file(_Path([path]), dest_path, overwrite=False)\n return package\n\n def _add_packages_to_pool(self, paths):\n unique_paths = set(paths)\n return {self._add_package_to_pool(path) for path in unique_paths}\n\n def _add_package_to_index(self, package):\n filenames = self._index.setdefault(package.get_filehash(), dict())\n filenames.setdefault(package.get_filename(), set())\n\n def _add_packages_to_index(self, packages):\n for package in packages:\n self._add_package_to_index(package)\n\n def add(self, paths):\n '''Adds packages to repository.'''\n packages = self._add_packages_to_pool(paths)\n self._add_packages_to_index(packages)\n return packages\n\n def _get_empty_generator(self):\n return (x for x in [])\n\n def _cat_generators(self, *generators):\n for g in generators:\n for i in g:\n yield i\n\n def _get_none_packages(self):\n return self._get_empty_generator()\n\n def _get_all_packages(self):\n for filehash, filenames in self._index.items():\n for filename, groups in filenames.items():\n yield _Package(filehash, filename), groups\n\n def _get_all_package_files(self):\n for package, groups in self._get_all_packages():\n yield package\n\n def _get_package_files_by_hash(self, filehash):\n for filename in self._index[filehash]:\n yield _Package(filehash, filename)\n\n def _get_any_package_file_by_hash(self, filehash):\n for package in self._get_package_files_by_hash(filehash):\n return package\n return None\n\n def _parse_package_spec(self, spec):\n excluding = spec.startswith('!')\n pattern = spec if not excluding else spec[1:]\n return (excluding, pattern)\n\n def _match_group(self, group, pattern):\n return fnmatch.fnmatch(group, pattern)\n\n def _get_package_groups(self, package):\n filehash = package.get_filehash()\n filename = package.get_filename()\n return self._index[filehash][filename]\n\n def _match_groups(self, package, pattern, invert=False):\n # Consider name and hash of the file to be its implicit groups.\n groups = (self._get_package_groups(package) |\n {package.get_filehash(), package.get_filename()})\n\n matches = any(self._match_group(group, pattern) for group in groups)\n if invert:\n matches = not matches\n return matches\n\n def _filter_packages(self, pattern, packages, invert=False):\n for package in packages:\n if self._match_groups(package, pattern, invert):\n yield package\n\n def _get_packages_by_specs(self, package_specs):\n packages = self._get_all_package_files()\n\n first = True\n for spec in package_specs:\n excluding, pattern = self._parse_package_spec(spec)\n\n # If the first specifier is including, use it instead of\n # considering all packages.\n if first and not excluding:\n packages = self._get_none_packages()\n\n if excluding:\n packages = self._filter_packages(pattern, packages,\n invert=True)\n else:\n all_packages = self._get_all_package_files()\n packages = self._cat_generators(\n packages,\n self._filter_packages(pattern, all_packages))\n\n first = False\n\n return packages\n\n def add_to_group(self, group, packages):\n for package in packages:\n self._get_package_groups(package).add(group)\n\n def group(self, group, package_specs):\n '''Makes packages part of a group.'''\n packages = self._get_packages_by_specs(package_specs)\n self.add_to_group(group, packages)\n\n def rmgroup(self, group, package_specs):\n '''Excludes packages from a group.'''\n for package in self._get_packages_by_specs(package_specs):\n self._get_package_groups(package).discard(group)\n\n def ls(self, package_specs):\n '''Lists packages.'''\n return self._get_packages_by_specs(package_specs)\n\n def _run_shell(self, args):\n child = subprocess.Popen(args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n out, err = child.communicate()\n\n if child.returncode:\n raise Error('subprocess returned %d: %s: %s' % (\n child.returncode, ' '.join(args), err))\n\n return out\n\n def _is_key_hash_name(self, hash_name):\n return self._CANONICAL_HASH_NAMES[hash_name] == self._KEY_HASH_NAME\n\n def _get_hash_field_name(self, hash_name):\n return (self._MAKEAPT_FIELD_PREFIX +\n self._CANONICAL_HASH_NAMES[hash_name])\n\n def _get_deb_control_info(self, package):\n # Run 'dpkg-deb' to list the control package fields.\n # TODO: We can run several processes simultaneously.\n path = self._get_full_package_path(package)\n output = self._run_shell(['dpkg-deb',\n '--field', path.get_as_string()] +\n self._DEB_INFO_FIELDS)\n output = output.decode('utf-8')\n\n # Handle spliced lines.\n mark = '{makeapt_linebreak}'\n output = output.replace('\\n ', mark + ' ')\n output = output.split('\\n')\n output = [x.replace(mark, '\\n') for x in output if x != '']\n\n filename = package.get_filename()\n info = dict()\n for line in output:\n parts = line.split(':', maxsplit=1)\n if len(parts) != 2:\n raise Error('Unexpected control line %r in package %r.' % (\n line, filename))\n\n field, value = tuple(parts)\n field = field.strip()\n value = value.strip()\n\n if field not in self._DEB_INFO_FIELDS:\n raise Error('Unknown control field %r in package %r.' % (\n field, filename))\n\n if field in info:\n raise Error('Duplicate control field %r in package %r.' % (\n field, filename))\n\n info[field] = value\n\n # TODO: Make sure all the necessary fields are in place.\n\n return info\n\n def _get_deb_contents(self, package):\n path = self._get_full_package_path(package)\n out = self._run_shell(['dpkg-deb', '--contents', path.get_as_string()])\n out = out.decode('utf-8').split('\\n')\n\n # Remove empty lines.\n out = [line for line in out if line]\n\n # Get only filenames.\n out = [line.split()[5] for line in out]\n\n # Strip directories.\n out = [line for line in out if not line.endswith('/')]\n\n # Strip './' in the beginning of paths.\n out = [line[2:] if line.startswith('./') else line for line in out]\n\n return set(out)\n\n # Retrieves info for packages with a given hash or None if\n # there are no such packages.\n def _get_package_info(self, filehash):\n # See if the info is already cached.\n if filehash in self._cache:\n return self._cache[filehash]\n\n # Get any package with the given hash, if there are some.\n package = self._get_any_package_file_by_hash(filehash)\n if package is None:\n return None\n\n info = self._get_deb_control_info(package)\n\n info[self._CONTENTS_FIELD] = self._get_deb_contents(package)\n\n path = self._get_full_package_path(package)\n info[self._FILESIZE_FIELD] = os.path.getsize(path.get_as_string())\n\n hashes = self._hash_file(path, {'md5', 'sha1', 'sha256', 'sha512'})\n for hash_name, hash in hashes.items():\n if not self._is_key_hash_name(hash_name):\n field = self._get_hash_field_name(hash_name)\n info[field] = hash\n\n # Cache the results.\n self._cache[filehash] = info\n\n return info\n\n def _get_package_arch(self, filehash):\n package_info = self._get_package_info(filehash)\n return package_info[self._ARCH_FIELD]\n\n def _get_package_hash(self, filehash, hash_name):\n if self._is_key_hash_name(hash_name):\n return filehash\n\n package_info = self._get_package_info(filehash)\n field = self._get_hash_field_name(hash_name)\n return package_info[field]\n\n def _parse_distribution_component_group(self, group):\n ids = group.split(':')\n return tuple(ids) if len(ids) == 2 else None\n\n def _get_distributions(self, repo_index):\n dists = dict()\n for package, groups in self._get_all_packages():\n for group in groups:\n ids = self._parse_distribution_component_group(group)\n if not ids:\n continue\n\n dist_id, component_id = ids\n if dist_id in dists:\n dist = dists[dist_id]\n else:\n dist = _Distribution(dist_id, repo_index)\n dists[dist_id] = dist\n\n arch_id = self._get_package_arch(package.get_filehash())\n dist.add_package(component_id, arch_id, package)\n\n for dist_id, dist in dists.items():\n yield dist\n\n def _generate_package_index(self, package):\n # Emit the control fields from the deb file itself. Note that we want\n # them in this exactly order they come in the list.\n info = self._get_package_info(package.get_filehash())\n for field in self._DEB_INFO_FIELDS:\n if field in info:\n yield '%s: %s\\n' % (field, info[field])\n\n # Emit additional fields.\n filename_field = self._get_package_path_in_apt(package).get_as_string()\n yield 'Filename: %s\\n' % filename_field\n\n yield 'Size: %u\\n' % info[self._FILESIZE_FIELD]\n\n hash_algos = ['MD5sum', # Note the lowercase 's' in 'MD5sum'.\n 'SHA1', 'SHA256', 'SHA512']\n for algo in hash_algos:\n hash = self._get_package_hash(package.get_filehash(), algo)\n yield '%s: %s\\n' % (algo, hash)\n\n def _generate_packages_index(self, packages):\n for package in packages:\n for chunk in self._generate_package_index(package):\n yield chunk\n\n def _save_apt_file(self, path, content, repo_index, is_temporary=False):\n full_path = self._apt_path + path\n self._save_file(full_path, content)\n if not is_temporary and repo_index:\n repo_index.add_file_path(path)\n return full_path\n\n def _save_index_file(self, dist, path_in_dist, content,\n is_temporary=False):\n path_in_apt = self.DISTS_DIR + dist.get_id() + path_in_dist\n repo_index = dist.get_repository_index()\n path = self._save_apt_file(path_in_apt, content, repo_index,\n is_temporary=is_temporary)\n\n # Remember the hashes and the size of the resulting file.\n path_in_dist_string = path_in_dist.get_as_string()\n hashes = self._hash_file(path, self._DISTRIBUTION_INDEX_HASH_NAMES)\n filesize = os.path.getsize(path.get_as_string())\n dist.get_index().add(path_in_dist_string, hashes, filesize)\n\n # Create by-hash copies.\n if not is_temporary:\n hash_names = ['MD5Sum', # Note the uppercase 'S'.\n 'SHA256']\n for hash_name, hash in self._hash_file(path, hash_names).items():\n dir = path_in_apt.get_dirname()\n dest_path = dir + 'by-hash' + hash_name + hash\n self._link_or_copy_apt_file(path, dest_path)\n repo_index.add_file_path(dest_path)\n\n return path\n\n def _save_index(self, dist, path_in_dist, index,\n create_compressed_versions=True,\n keep_uncompressed_version=True):\n path = self._save_index_file(\n dist, path_in_dist, index,\n is_temporary=not keep_uncompressed_version)\n if create_compressed_versions:\n self._save_index_file(dist, path_in_dist.add_extension('.gz'),\n self._gzip(path))\n self._save_index_file(dist, path_in_dist.add_extension('.bz2'),\n self._bzip2(path))\n\n # Note that the uncompressed version goes to the\n # distribution index even if it doesn't present in the\n # repository.\n if not keep_uncompressed_version:\n os.remove(path.get_as_string())\n\n def _generate_release_index(self, arch):\n yield 'Origin: %s\\n' % self._config['origin']\n yield 'Label: %s\\n' % self._config['label']\n yield 'Component: %s\\n' % arch.get_component().get_id()\n yield 'Architecture: %s\\n' % arch.get_id()\n yield 'Acquire-By-Hash: yes\\n' # TODO: Should be configurable.\n\n def _generate_contents_index(self, packages):\n index = dict()\n for package in packages:\n package_info = self._get_package_info(package.get_filehash())\n location = '%s/%s' % (package_info[self._SECTION_FIELD],\n package_info[self._PACKAGE_FIELD])\n\n # TODO: Debian documentation reads so that use of the\n # area name part is deprecated. Despite that, Debian\n # archvies still seem to be using them. So do we.\n # https://wiki.debian.org/DebianRepository/Format?action=show&redirect=RepositoryFormat#A.22Contents.22_indices\n # http://ftp.debian.org/debian/dists/stable/non-free/Contents-i386.gz\n # location = '/'.join(location.split('/')[1:])\n\n contents = package_info[self._CONTENTS_FIELD]\n for contents_filename in contents:\n index.setdefault(contents_filename, set()).add(location)\n\n if not index:\n return\n\n yield 'FILE LOCATION\\n'\n for contents_filename in sorted(index):\n locations = ','.join(sorted(index[contents_filename]))\n yield '%s %s\\n' % (contents_filename, locations)\n\n def _save_contents_index(self, arch):\n # Note that according to the Debian specification, we\n # have to add the uncompressed version of the index to\n # the release index regardless of whether we store the\n # first. This way apt clients can check indexes both\n # before and after decompression.\n contents_index = self._generate_contents_index(arch.get_packages())\n path = arch.get_path_in_distribution() + 'Contents-%s' % arch.get_id()\n self._save_index(arch.get_distribution(), path, contents_index,\n keep_uncompressed_version=False)\n\n def _index_architecture(self, arch):\n # Generate packages index.\n dir_in_dist = _Path([arch.get_component().get_id(),\n 'binary-%s' % arch.get_id()])\n dist = arch.get_distribution()\n self._save_index(dist, dir_in_dist + 'Packages',\n self._generate_packages_index(arch.get_packages()))\n\n # Generate release index.\n release_index = self._generate_release_index(arch)\n self._save_index(dist, dir_in_dist + 'Release',\n release_index, create_compressed_versions=False)\n\n # Generate component contents index.\n self._save_contents_index(arch)\n\n def _index_distribution_component(self, component):\n for arch in component.get_archs():\n self._index_architecture(arch)\n\n def _generate_distribution_index(self, dist):\n yield 'Origin: %s\\n' % self._config['origin']\n yield 'Label: %s\\n' % self._config['label']\n yield 'Suite: %s\\n' % dist.get_id()\n yield 'Codename: %s\\n' % dist.get_id()\n\n now = datetime.datetime.utcnow()\n yield 'Date: %s\\n' % now.strftime('%a, %d %b %Y %H:%M:%S +0000')\n\n components = (component.get_id()\n for component in dist.get_components())\n yield 'Components: %s\\n' % ' '.join(sorted(components))\n\n archs = (arch.get_id() for arch in dist.get_archs())\n yield 'Architectures: %s\\n' % ' '.join(sorted(archs))\n\n yield 'Acquire-By-Hash: yes\\n'\n\n dist_index = dist.get_index().get()\n for hash_name in self._DISTRIBUTION_INDEX_HASH_NAMES:\n yield '%s:\\n' % hash_name\n for index in sorted(dist_index):\n hashes, filesize = dist_index[index]\n yield ' %s %s %s\\n' % (hashes[hash_name], filesize, index)\n\n def _index_distribution(self, dist):\n # Generate component-specific indexes.\n for component in dist.get_components():\n self._index_distribution_component(component)\n\n # Generate distribution contents indexes.\n for arch in dist.get_archs():\n self._save_contents_index(arch)\n\n # Generate distribution index.\n index = self._generate_distribution_index(dist)\n index_path = self.DISTS_DIR + dist.get_id() + 'Release'\n full_index_path = self._save_apt_file(index_path, index,\n dist.get_repository_index())\n\n # Sign the index.\n gpg_key_id = self._config['gpg_key_id']\n if gpg_key_id != 'none':\n digest_algo = 'SHA256' # Should be configurable?\n full_index_gpg_path = full_index_path.add_extension('.gpg')\n path = self._apt_path + index_path\n self._run_shell(['gpg', '--armor', '--detach-sign', '--sign',\n '--default-key', gpg_key_id,\n '--personal-digest-preferences', digest_algo,\n '--output', full_index_gpg_path.get_as_string(),\n '--yes', path.get_as_string()])\n\n full_inrelease_path = full_index_path.get_dirname() + 'InRelease'\n self._run_shell(['gpg', '--armor', '--clearsign', '--sign',\n '--default-key', gpg_key_id,\n '--personal-digest-preferences', digest_algo,\n '--output', full_inrelease_path.get_as_string(),\n '--yes', path.get_as_string()])\n\n def index(self, repo_index=_RepositoryIndex()):\n '''Generates APT indexes.'''\n # TODO: Remove the whole 'dists' directory before re-indexing.\n for dist in self._get_distributions(repo_index):\n self._index_distribution(dist)\n\n # Add all packages in the pool to the repository index.\n if repo_index:\n for package in self._get_all_package_files():\n path = self._get_package_path_in_apt(package)\n repo_index.add_file_path(path)\n\n\nclass CommandLineDriver(object):\n def __init__(self):\n self._prog_name = os.path.basename(sys.argv[0])\n\n self.COMMANDS = {\n 'config': (self.config, 'List or set configuration fields.'),\n 'add': (self.add, 'Add .deb files to repository.'),\n 'group': (self.group, 'Make packages part of a group.'),\n 'index': (self.index, 'Generate APT index files.'),\n 'init': (self.init, 'Initialize APT repository.'),\n 'ls': (self.ls, 'List packages.'),\n 'rmgroup': (self.rmgroup, 'Excludes packages from a group.'),\n }\n\n def init(self, repo, parser, args):\n args = parser.parse_args(args)\n repo.init()\n\n def add(self, repo, parser, args):\n parser.add_argument('group', help='Group name.')\n parser.add_argument('path', nargs='+',\n help='The package files to add.')\n args = parser.parse_args(args)\n packages = repo.add(args.path)\n repo.add_to_group(args.group, packages)\n\n def group(self, repo, parser, args):\n parser.add_argument('group', help='Group name.')\n parser.add_argument('package', nargs='*',\n help='The packages to add.')\n args = parser.parse_args(args)\n repo.group(args.group, args.package)\n\n def rmgroup(self, repo, parser, args):\n parser.add_argument('group', help='Group name.')\n parser.add_argument('package', nargs='*',\n help='The packages to exclude from the group.')\n args = parser.parse_args(args)\n repo.rmgroup(args.group, args.package)\n\n def ls(self, repo, parser, args):\n parser.add_argument('package', nargs='*',\n help='The packages to list.')\n args = parser.parse_args(args)\n files = {(package.get_filename(), package.get_filehash()) for\n package in repo.ls(args.package)}\n for filename, filehash in sorted(files):\n print(filehash[:8], filename)\n\n def index(self, repo, parser, args):\n args = parser.parse_args(args)\n repo.index()\n\n def _print_config_field(self, field, value):\n print('%s=%s' % (field, value))\n\n def config(self, repo, parser, args):\n parser.add_argument('field', nargs='?',\n help='The field to display or set.')\n parser.add_argument('value', nargs='?',\n help='The new value to set to the field.')\n args = parser.parse_args(args)\n if args.field and args.value:\n repo.set_config_field(args.field, args.value)\n elif args.field:\n value = repo.get_config_field(args.field)\n self._print_config_field(args.field, value)\n else:\n config = repo.get_config()\n for field in sorted(config):\n self._print_config_field(field, config[field])\n\n def execute_command_line(self, args):\n parser = argparse.ArgumentParser(\n prog=self._prog_name,\n description='Debian APT repositories generator.')\n parser.add_argument('command', help='The command to run.')\n\n command = sys.argv[1:2]\n command_args = sys.argv[2:]\n\n args = parser.parse_args(command)\n if args.command not in self.COMMANDS:\n raise Error('Unknown command %r.' % args.command)\n\n handler, descr = self.COMMANDS[args.command]\n command_parser = argparse.ArgumentParser(\n prog='%s %s' % (self._prog_name, args.command),\n description=descr)\n\n with Repository() as repo:\n handler(repo, command_parser, command_args)\n\n def run(self):\n self.execute_command_line(sys.argv[1:])\n\n\ndef main():\n driver = CommandLineDriver()\n driver.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"makeapt.py","file_name":"makeapt.py","file_ext":"py","file_size_in_byte":38943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"227236702","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# 显示灰度图像\n# img = cv2.imread('timg.jpg', 0)\n#\n# cv2.imshow('timg.jpg', img)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n\n# img = np.zeros((512, 512), np.uint8)\n# cv2.rectangle(img, (0, 0), (51, 51), (55, 255, 155), 8)\n# plt.imshow(img, 'brg')\n# cv2.circle(img, (100, 100), 50, (12, 24, 21),8)\n# plt.imshow(img, 'brg')\n#\n# plt.show()\n\n# img = cv2.imread('timg.jpg')\n# # H = np.float32([[1, 0, 100], [0, 1, 50]])\n# # rows, cols = img.shape[:2]\n# # res = cv2.warpAffine(img, H, (rows, cols))\n# # plt.subplot(121)\n# # plt.imshow(img)\n# # plt.subplot(122)\n# # plt.imshow(res)\n# # plt.show()\n\n# img = cv2.imread('timg.jpg')\n# res1 = cv2.resize(img,None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)\n# height, width = img.shape[:2]\n# res2 = cv2.resize(img, (2*width, 2*height), interpolation=cv2.INTER_CUBIC)\n# plt.subplot(131)\n# plt.imshow(img)\n# plt.subplot(132)\n# plt.imshow(res1)\n# plt.subplot(133)\n# plt.imshow(res2)\n# plt.show()\n# print(img.shape)\n\nimg = cv2.imread('timg.jpg',0) #直接读为灰度图像\nret,thresh1 = cv2.threshold(img,10,255,cv2.THRESH_BINARY)\nret,thresh2 = cv2.threshold(img,10,255,cv2.THRESH_BINARY_INV)\nret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)\nret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)\nret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)\ntitles = ['img','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']\nimages = [img, thresh1, thresh2, thresh3, thresh4, thresh5]\nfor i in range(6):\n plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')\n plt.title(titles[i])\n plt.xticks([]),plt.yticks([])\nplt.show()","sub_path":"testhui.py","file_name":"testhui.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"75792340","text":"import json, codecs, requests, pickle, datetime\r\nimport urllib.request, urllib.parse, urllib.error\r\nimport re\r\nimport subprocess\r\nfrom googleapiclient.discovery import build \r\nfrom itertools import repeat\r\nfrom unidecode import unidecode\r\nfrom bs4 import BeautifulSoup, SoupStrainer\r\nfrom urllib.request import Request, urlopen\r\n\r\n\r\nAVAILABLE_TOKEN_SETS = {\r\n 'ess': {\r\n 'api_key': 'AIzaSyB_QXKEohLw7XvtgecsshkzkqUOJ8FzSCc',\r\n 'cse_id': '009043117829057268965:tgiqlni9v2w'\r\n },\r\n 'ssk': {\r\n 'api_key': 'AIzaSyAn_YOSbC43zmv2cexCddaIYfJfMb9d08s',\r\n 'cse_id': '003565523015477317201:lwtcnf2u57i'\r\n }\r\n}\r\n\r\nNAME_OF_TOKEN_SET_TO_USE_FOR_THIS_RUN = 'ess'\r\n\r\nAPI_KEY_TO_USE_FOR_THIS_RUN = AVAILABLE_TOKEN_SETS[NAME_OF_TOKEN_SET_TO_USE_FOR_THIS_RUN]['api_key']\r\nCSE_ID_TO_USE_FOR_THIS_RUN = AVAILABLE_TOKEN_SETS[NAME_OF_TOKEN_SET_TO_USE_FOR_THIS_RUN]['cse_id']\r\n\r\n# CODEFORCASH_BASE_URL = 'https://i.codefor.cash'\r\nCODEFORCASH_API_KEY = '5b26197b391c5dab05c5606d43fba9c6'\r\n\r\nMAXIMUM_NUMBER_OF_SEARCH_RESULTS_PER_GOOGLE_API_QUERY = 10\r\n\r\ndef do_google_search(search_term, api_key, cse_id, **kwargs):\r\n service = build(\"customsearch\", \"v1\", developerKey=api_key)\r\n res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()\r\n # print(res['items'])\r\n print('ran')\r\n length = int(len(res['items']))\r\n length2 = int(res['queries']['request'][0]['totalResults'])\r\n if length == length2:\r\n print('equals')\r\n pass\r\n else:\r\n return res['items']\r\n\r\n# results_from_GSE_query = []\r\n\r\n# #local manual per listing test\r\n# def get_job_listings_from_google():\r\n# data_get_job_listings_from_google = results_from_GSE_query\r\n# return data_get_job_listings_from_google\r\n\r\n# >>> NOT THE ORIGINAL .. GET ORIG THAT FIRST POSTED 100\r\n # https://i.codefor.cash/job_alerts/generate_subscriber_keywords\r\ndef get_job_listings_from_google(number_of_listings_to_get = 20):\r\n return_value = []\r\n for search_result_number_from_which_api_query_results_start in range(1, number_of_listings_to_get + 1, MAXIMUM_NUMBER_OF_SEARCH_RESULTS_PER_GOOGLE_API_QUERY):\r\n return_value.extend(do_google_search(\r\n search_term='engineer software site:jobs.lever.co/brightedge',\r\n api_key=API_KEY_TO_USE_FOR_THIS_RUN, cse_id=CSE_ID_TO_USE_FOR_THIS_RUN,\r\n num=MAXIMUM_NUMBER_OF_SEARCH_RESULTS_PER_GOOGLE_API_QUERY,\r\n # start=1))\r\n start=search_result_number_from_which_api_query_results_start))\r\n return return_value[:number_of_listings_to_get]\r\n\r\ndef save_gse_call_results(listings):\r\n with open('finalResults.txt','a+') as f:\r\n f.write(json.dumps(get_job_listings_from_google(), sort_keys = True,\r\n indent = 4))\r\n\r\ndef send_job_listings_to_codeforcash(listings):\r\n for listing in range(len(listings)):\r\n data_to_send_in_request_body = {\r\n \"key\": CODEFORCASH_API_KEY,\r\n \"title\": listings[listing][\"title\"],\r\n \"website\": listings[listing][\"link\"],\r\n # \"description\": listings[listing][\"snippet\"],\r\n \"description\": \"\",\r\n \"utc_datetime\": datetime.datetime.utcnow().isoformat(),\r\n \"lat\": \"\",\r\n \"lng\": \"\",\r\n \"country\": \"\",\r\n \"employment_type\": \"\",\r\n \"remote_ok\": \"\",\r\n \"time_commitment\": \"\"\r\n }\r\n data_send_job_lisitings_to_codeforcash = json.dumps(data_to_send_in_request_body)\r\n data_of_each_listing = json.loads(data_send_job_lisitings_to_codeforcash)\r\n\r\n try:\r\n html = urllib.request.urlopen(data_of_each_listing[\"website\"]).read()\r\n except urllib.error.HTTPError as e:\r\n print(e)\r\n else:\r\n only_tag_class = SoupStrainer(\"div\", {\"class\" : \"section-wrapper page-full-width\"})\r\n soup = BeautifulSoup(html, \"html.parser\", parse_only=only_tag_class)\r\n htmlDecode = soup.encode('utf-8').decode('utf-8', 'ignore')\r\n \r\n f = open('Lynx.htm','w')\r\n try:\r\n f.write(htmlDecode)\r\n except:\r\n print('POTENTIAL ENCODE ERROR')\r\n f.close()\r\n\r\n #refactor as functions\r\n web_data = ''\r\n cmd = 'lynx -dump -width 1024 -nolist -notitle \\\"{0}\\\"'.format('./Lynx.htm')\r\n lynx = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\r\n web_data = lynx.stdout.read()\r\n web_data = web_data.decode('utf-8', 'replace')\r\n \r\n #test print lynx formatted description \r\n # print(web_data)\r\n\r\n data_to_send_in_request_body[\"description\"] = web_data\r\n\r\n for data_key in data_to_send_in_request_body:\r\n # data_to_send_in_request_body[data_key] = data_to_send_in_request_body[data_key].encode('UTF8').decode('utf-8')\r\n data_to_send_in_request_body[data_key] = data_to_send_in_request_body[data_key]\r\n\r\n #test print json formatted complete listing\r\n # print(data_to_send_in_request_body)\r\n \r\n # response_per_post = requests.post(\r\n # url=CODEFORCASH_BASE_URL+'/api/metum/create',\r\n # data=data_to_send_in_request_body)\r\n \r\n # with open('responseFromCodeforcash','ab+') as f:\r\n # pickle.dump(response_per_post, f)\r\n\r\nif __name__ == '__main__':\r\n # save_gse_call_results(send_job_listings_to_codeforcash(get_job_listings_from_google()))\r\n\r\n get_job_listings_from_google()\r\n\r\n # save_gse_call_results(send_job_listings_to_codeforcash(remove_non_ascii(get_job_listings_from_google())))\r\n\r\n # send_job_listings_to_codeforcash(return_value)\r\n # save_gse_call_results(return_value)\r\n\r\n # save_result_of_sending_job_listings_to_codeforcash(send_job_listings_to_codeforcash(return_value))\r\n\r\n # save_gse_call_results(get_job_listings_from_google())\r\n\r\n # save_result_of_sending_job_listings_to_codeforcash(\r\n # get_job_listings_from_google())\r\n \r\n","sub_path":"c4c/executables/b4 oct17/8GSENoPostC4C.py","file_name":"8GSENoPostC4C.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"275342668","text":"\"\"\"\nA simple implementation of\nKnuth-Morris-Pratt (KMP) String\nMatching algorithm\n\"\"\"\n\ndef define_fail(pattern) :\n \"\"\"\n Preprocess the pattern to find matches of\n prefixes of the pattern with the pattern itself.\n \"\"\"\n \n # Defining variables\n length = len(pattern)\n fail = [0 for i in range(length)] # array of integer fail[]\n k = 1\n j = 0\n\n # Fail[0] is not defined\n fail[0] = 0\n\n # Initiate loop\n while k < length:\n if pattern[k] == pattern[j]: # found a matching suffix and prefix from \n # pattern P[0..k-1]\n fail[k] = j + 1 # Sets the value of fail[k]\n k += 1\n j += 1\n else:\n if j > 0:\n # Previous prefix\n j = fail[j-1]\n else:\n # No matching prefix-suffix\n fail[k] = 0\n k += 1 # next index\n # k >= length\n\n return fail\n\ndef match_kmp_string(text, pattern):\n \"\"\"\n Finds the first occurence of pattern\n inside of a text using KMP algorithm\n \"\"\"\n\n #Defining Variables\n fail = define_fail(pattern)\n text_length = len(text)\n pattern_last_index = len(pattern) - 1\n i = 0 # For traversing text\n j = 0 # For traversing pattern, changes back and forth\n found = False # True, if pattern is found in text \n\n if pattern_last_index + 1 > text_length:\n return -1 # Pattern is longer than text\n\n # Initiate loop\n while i < text_length and not found:\n\n if text[i] == pattern[j]: # Continue matching\n if j == pattern_last_index: # Pattern found\n found = True\n else : # Does an iteration\n i += 1\n j += 1\n \n else: # If pattern does not match, do a shift\n\n if j <= 0: # If the mismatch occured on the first index (index-0)\n # does a shift to the right just for one step\n i += 1\n else: # Finds the size of the next shift by\n # the fail fucntion\n k = j-1\n j = fail[k]\n \n # i == text_length or found\n\n if found:\n # Index where pattern occured in text\n return i - pattern_last_index \n \n return -1 # Pattern not found\n\ndef match(text, pattern):\n \"\"\"\n Returns True if pattern\n is found within the text\n \"\"\"\n return match_kmp_string(text, pattern) != -1\n","sub_path":"src/matcher/kmp.py","file_name":"kmp.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458009892","text":"import logging\nfrom django.conf import settings\nimport twitter\n\nfrom .models import TrackedAccount, Follower, TweetToShoot\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_twitter_api_object():\n return twitter.Api(consumer_key=settings.TWITTER_CONSUMER_KEY,\n consumer_secret=settings.TWITTER_CONSUMER_SECRET,\n access_token_key=settings.TWITTER_ACCESS_TOKEN,\n access_token_secret=settings.TWITTER_ACCESS_TOKEN_SECRET,\n sleep_on_rate_limit=True)\n\n\ndef shoot_a_tweet():\n api = get_twitter_api_object()\n for tweet in TweetToShoot.objects.all():\n try:\n api.PostUpdate(tweet.tweet_text)\n except twitter.TwitterError as e:\n logger.exception(e)\n\n\ndef fill_followers():\n api = get_twitter_api_object()\n tracked_accounts = TrackedAccount.objects.all()\n for account in tracked_accounts:\n try:\n next_cursor = -1\n while next_cursor != 0:\n request_result = api.GetFollowersPaged(screen_name=account.screen_name, count=200, cursor=next_cursor)\n logger.debug(request_result)\n next_cursor = request_result[0]\n followers = request_result[2]\n for follower in followers:\n Follower.objects.update_or_create(\n twitter_user_id=follower.id,\n defaults={\n 'followers_count': follower.followers_count,\n 'following': account,\n 'already_followed': follower.following,\n }\n )\n except twitter.TwitterError as e:\n logger.exception(e)\n","sub_path":"src/twitter_bot_sample/juliacoding/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139851212","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 6 00:55:52 2018\n\n@author: stremler\n\"\"\"\n\nimport numpy as np\nimport scipy\nfrom scipy.spatial.distance import cdist\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\nclass KernelPerceptron:\n \"\"\"KernelPerceptron\"\"\"\n def __init__(self, kernel=\"gaussian\", kernel_param=1):\n if kernel == \"gaussian\":\n self.kernel = self._gaussian_kernel\n else: \n self.kernel = self._polynomial_kernel\n \n self.kernel_param = kernel_param\n \n def fit(self, X, y):\n self.X = np.column_stack((np.ones(X.shape[0]), X))\n self.y = y\n self.alpha = np.zeros(self.X.shape[0])\n self.alpha_steps = self.alpha\n kernel_m = self.kernel(self.X, self.kernel_param)\n \n while True:\n error = False\n \n for i in range(X.shape[0]):\n if y[i] * np.dot(self.alpha * y, kernel_m[i,]) <= 0:\n self.alpha[i] += 1\n self.alpha_steps = np.row_stack((self.alpha_steps, self.alpha))\n error = True\n \n if not error:\n break\n \n return self.alpha\n \n def _gaussian_kernel(self, X, s):\n pairwise_sq_dists = cdist(self.X, X, 'sqeuclidean')\n return scipy.exp(-pairwise_sq_dists / (2*s**2))\n \n def _polynomial_kernel(self, X, d):\n return (np.matmul(self.X, np.transpose(X)) + 1) ** d\n \n def _predict(self, X, alpha): \n return np.sign(np.matmul(alpha * self.y, self.kernel(X, self.kernel_param)))\n \n def predict(self, X):\n X = np.column_stack((np.ones(X.shape[0]), X))\n return self._predict(X, self.alpha)\n \n def score(self):\n y = self._predict(self.X)\n unique, counts = np.unique(-1 * y * self.y, return_counts=True)\n return(counts[0] / np.sum(counts))\n \n def plot_animation(self, interval=400, xinch=5, yinch=5, notebook=True, smoothness=400): \n xlim = (np.min(self.X[:,1]) - 0.2 * np.std(self.X[:,1]), np.max(self.X[:,1]) - 0.2 * - np.std(self.X[:,1]))\n ylim = (np.min(self.X[:,2]) - 0.2 * np.std(self.X[:,2]), np.max(self.X[:,2]) - 0.2 * - np.std(self.X[:,2]))\n ycolor = np.where(self.y>0, \"#DC0026\", \"#457CB6\")\n yshape = np.where(self.y>0, \"o\", \"^\")\n \n xlin = np.linspace(xlim[0], xlim[1], smoothness)\n ylin = np.linspace(ylim[0], ylim[1], smoothness)\n \n xv, yv = np.meshgrid(xlin, ylin)\n pinp = np.c_[xv.ravel(), yv.ravel()]\n pinp = np.column_stack((np.ones(pinp.shape[0]), pinp))\n \n if notebook:\n plt.ioff()\n \n fig = plt.figure()\n fig.subplots_adjust(left=0, right=1, bottom=0, top=1)\n ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, \n xlim=xlim, ylim=ylim)\n\n for s, c, x, y in zip(yshape, ycolor, self.X[:,1], self.X[:,2]):\n ax.scatter(x, y, c=c, marker=s)\n\n conts = []\n for i in range(self.alpha_steps.shape[0]):\n z = self._predict(pinp, self.alpha_steps[i,])\n z = z.reshape(xv.shape)\n cont = ax.contourf(xv, yv, z, colors=[\"#DC0026\", \"#457CB6\"], alpha=1/5)\n te = ax.text(0.10, 0.95, u\"Step: {}\".format(i), bbox={'facecolor':'w', 'alpha':0.5, 'pad':5},\n transform=ax.transAxes, ha=\"center\")\n conts.append(cont.collections + [te])\n\n fig.set_size_inches(xinch, yinch, True)\n anim = animation.ArtistAnimation(fig, conts, interval=interval, blit=False)\n \n return anim","sub_path":"vizml/kernel_perceptron.py","file_name":"kernel_perceptron.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"2074485","text":"import bpy\nimport imp\nfrom mathutils import ( Vector , Matrix )\n\nif bpy.app.version < (2, 80, 0):\n from .. import Utils as Utils\nelse:\n from .. import Utils28 as Utils\n\n imp.reload(Utils)\n\n\nfrom . import lib\nimp.reload(lib)\n\ndef register():\n bpy.utils.register_class(GetSwitchBones)\n bpy.utils.register_class(SwitchInfluence_0)\n bpy.utils.register_class(SwitchInfluence_100)\n bpy.utils.register_class(KeySwitchBones)\n bpy.utils.register_class(Return_Matrix_UncheckedBones)\n bpy.utils.register_class(RigTool_Pose_Panel)\n\n bpy.utils.register_class(Matrix_Copy)\n bpy.utils.register_class(Matrix_Paste)\n bpy.utils.register_class(Matrix_Keep)\n bpy.utils.register_class(Matrix_Return)\n bpy.utils.register_class(Matrix_Paste_Mirror)\n bpy.utils.register_class(Matrix_Auto_Mirror)\n\n\ndef unregister():\n bpy.utils.unregister_class(GetSwitchBones)\n bpy.utils.unregister_class(SwitchInfluence_0)\n bpy.utils.unregister_class(SwitchInfluence_100)\n bpy.utils.unregister_class(KeySwitchBones)\n bpy.utils.unregister_class(Return_Matrix_UncheckedBones)\n bpy.utils.unregister_class(RigTool_Pose_Panel)\n\n bpy.utils.unregister_class(Matrix_Copy)\n bpy.utils.unregister_class(Matrix_Paste)\n bpy.utils.unregister_class(Matrix_Keep)\n bpy.utils.unregister_class(Matrix_Return)\n bpy.utils.unregister_class(Matrix_Paste_Mirror)\n bpy.utils.unregister_class(Matrix_Auto_Mirror)\n\n \n\nSWITCHBONE_MATRIX_ARRAY = {}\nSWITCHBONE_MATRIX = []\n\n#マトリックスコピペ用の配列\nBONE_MATRIX_ARRAY = {}\nBONE_DATA_ARRAY = []\nBONE_MATRIX = []\n\n\ndef copy_matrix():\n amt = bpy.context.object\n BONE_MATRIX.clear()\n bonematrixarray = {}\n\n bpy.ops.object.mode_set(mode = 'POSE')\n for bone in bpy.context.selected_pose_bones:\n \n m = Matrix(bone.matrix)\n pos =(m[0][3] , m[1][3] , m[2][3] )\n bonematrixarray[bone.name] = [Matrix(bone.matrix) , pos]\n\n bpy.ops.object.mode_set(mode = 'EDIT')\n for bone in bpy.context.active_object.data.bones:\n if bone.name in bonematrixarray:\n initmat = Matrix(bone.matrix_local)\n initmat.invert()\n print(bone.matrix_local)\n m = bonematrixarray[bone.name][0] * initmat\n\n BONE_MATRIX.append([bonematrixarray[bone.name][0] , m ,bonematrixarray[bone.name][1]])\n\n bpy.ops.object.mode_set(mode = 'POSE')\n\n\n\nclass BoneData:\n def __init__(self,bone):\n self.amt = bpy.context.object\n self.name = bone.name\n self.m = Matrix(bone.matrix)\n self.pos =(self.m[0][3] , self.m[1][3] , self.m[2][3])\n #bonematrixarray[bone.name] = [Matrix(bone.matrix) , pos]\n\n def setup(self):\n bone = self.amt.data.edit_bones[self.name]\n initmat = Matrix(bone.matrix)\n initmat.invert()\n\n self.diff = Utils.m_mul(self.m , initmat)\n #self.diff = self.m * initmat #初期姿勢からの差分マトリックス\n #self.diff = self.m @ initmat #初期姿勢からの差分マトリックス\n\n\n def mirror_auto(self):\n\n #変化の差分の反転\n m0 = self.diff\n m0.transpose()\n\n m_sym =Matrix(\n (\n ( m0[0][0],-m0[0][1],-m0[0][2], 0 ), \n (-m0[1][0], m0[1][1], m0[1][2], 0 ),\n (-m0[2][0], m0[2][1], m0[2][2], 0 ),\n (0,0,0,1)\n ))\n\n m_sym.transpose()\n\n\n #反対のボーン名 (L_ R_) , (.l .r)\n if self.name[0:2] == 'L_':\n symmetric_bonename = 'R_' + self.name[2:]\n elif self.name[0:2] == 'R_':\n symmetric_bonename = 'L_' + self.name[2:]\n elif self.name[-2:] == '.l':\n symmetric_bonename = self.name[:-2] + '.r'\n elif self.name[-2:] == '.r':\n symmetric_bonename = self.name[:-2] + '.l'\n\n\n #反対のボーンの初期姿勢マトリックスを取得し、そこに反転差分マトリックスを掛ける\n\n bpy.ops.object.mode_set(mode = 'EDIT')\n symmetric_bone = self.amt.data.edit_bones[symmetric_bonename]\n initmat = Matrix(symmetric_bone.matrix)\n\n\n bpy.ops.object.mode_set(mode = 'POSE')\n symmetric_posebone = self.amt.pose.bones[symmetric_bonename]\n\n m = Utils.m_mul(m_sym , initmat)\n #m = m_sym * initmat\n #m = m_sym @ initmat\n\n m[0][3] = -self.pos[0]\n m[1][3] = self.pos[1]\n m[2][3] = self.pos[2]\n\n symmetric_posebone.matrix = m \n\n\n\n\n\n\nclass RigTool_Pose_Panel(Utils.Panel_):\n bl_label = \"リグポーズツール\"\n bl_idname = \"rig_pose_tools\"\n\n def draw(self, context):\n layout = self.layout\n row = layout.row(align=False)\n box = row.box()\n box.label(text = 'IKFKスイッチ')\n row = box.row()\n row.operator(\"rigtool.get_switch_bones\" , icon='CURVE_DATA' )\n row.operator(\"rigtool.switchinfluence_0\" , icon='CURVE_DATA' )\n row.operator(\"rigtool.switchinfluence_100\" , icon='CURVE_DATA' )\n row.operator(\"rigtool.key_switch_bones\" , icon='CURVE_DATA' )\n\n row = box.row()\n row.operator(\"rigtool.return_matrix_uncheckedbones\" , icon='CURVE_DATA' )\n\n row = self.layout.row(align=False)\n box = row.box()\n box.label(text = 'マトリックス')\n\n row = box.row()\n row.operator(\"rigtool.matrix_copy\")\n row.operator(\"rigtool.matrix_paste\")\n row.operator(\"rigtool.matrix_keep\")\n row.operator(\"rigtool.matrix_return\")\n row.operator(\"rigtool.matrix_paste_mirror\")\n box.operator(\"rigtool.matrix_auto_mirror\")\n\n\nclass BoneInf:\n def __init__(self , bonename ,val):\n self.bonename = bonename\n self.val = val\n\n amt = bpy.context.object\n\n bone = amt.pose.bones[bonename]\n self.bone_matrix = Matrix(bone.matrix)\n\n subtarget = bpy.context.object.pose.bones[bone.constraints[0].subtarget]\n self.subtarget_matrix = Matrix(subtarget.matrix)\n\n\n def mcopy(self):\n amt = bpy.context.object\n bone = amt.pose.bones[self.bonename]\n\n for const in bone.constraints:\n const.influence = self.val\n subtarget = amt.pose.bones[const.subtarget]\n\n if self.val == 1.0:\n subtarget.matrix = self.bone_matrix\n elif self.val == 0:\n bone.matrix = self.subtarget_matrix\n\n\n\n#インフルエンスの値を変更し、マトリックスをコピーする\ndef setInfluenceValue(val):\n amt = bpy.context.object\n biarray = []\n for bonename in lib.list_get_checked():\n print(bonename)\n biarray.append(BoneInf(bonename,val))\n\n for bi in biarray:\n bi.mcopy()\n\n\n\n#インフルエンスの値を変更し、マトリックスをコピーする\ndef setInfluenceValue_(val):\n amt = bpy.context.object\n for bonename in lib.list_get_checked():\n bone = amt.pose.bones[bonename]\n\n for const in bone.constraints:\n const.influence = val\n subtarget = amt.pose.bones[const.subtarget]\n\n if val == 1.0:\n subtarget.matrix = bone.matrix\n elif val == 0:\n bone.matrix = subtarget.matrix\n\n\n\n#スイッチボーンチェックされていないマトリックス保持。\n#コンストレインのターゲットボーンも同時に保持する\ndef keep_matrix():\n SWITCHBONE_MATRIX.clear()\n amt = bpy.context.object\n\n for bonename in lib.list_get_unchecked():\n bone = amt.pose.bones[bonename]\n if len(bone.constraints) > 0:\n subtarget = amt.pose.bones[bone.constraints[0].subtarget]\n\n SWITCHBONE_MATRIX.append([bone.name,Matrix(bone.matrix)])\n SWITCHBONE_MATRIX.append([subtarget.name,Matrix(subtarget.matrix)])\n \n\ndef keep_matrix_():\n SWITCHBONE_MATRIX_ARRAY.clear()\n amt = bpy.context.object\n\n for bonename in lib.list_get_all():\n bone = amt.pose.bones[bonename]\n subtarget = amt.pose.bones[bone.constraints[0].subtarget]\n\n SWITCHBONE_MATRIX_ARRAY[bone.name] = Matrix(bone.matrix)\n SWITCHBONE_MATRIX_ARRAY[subtarget.name] = Matrix(subtarget.matrix)\n\n\n#チェックされていないボーンのマトリックスを返す\ndef return_matrix_unchecked():\n amt = bpy.context.object\n\n # for bonename in lib.list_get_unchecked():\n \n # bone = amt.pose.bones[bonename]\n # if (bone.name in SWITCHBONE_MATRIX_ARRAY):\n # bone.matrix =SWITCHBONE_MATRIX_ARRAY[bone.name]\n # print(bonename)\n # print(bone.matrix)\n\n for b in SWITCHBONE_MATRIX: \n bone = amt.pose.bones[b[0]]\n bone.matrix =b[1]\n\n\n\n#IKFKを切り替える。まず切り替えたいノードをボーングループの\"Switch\"にアサイン\n#ボーングループのメンバを選択しリストに表示\nclass GetSwitchBones(bpy.types.Operator):\n bl_idname = \"rigtool.get_switch_bones\"\n bl_label = \"Get\"\n\n def execute(self, context):\n ui_list = context.window_manager.rig_ui_list\n\n # if bpy.context.object.mode == 'POSE':\n # bpy.ops.pose.select_all(action='DESELECT')\n # for node in self.itemlist:\n # if node.bool_val == True:\n # amt.pose.bones[node.name].bone.select = True\n\n # elif bpy.context.object.mode == 'EDIT':\n # bpy.ops.armature.select_all(action='DESELECT')\n # for node in self.itemlist:\n # if node.bool_val == True:\n # amt.data.edit_bones[node.name].select = True\n\n amt=bpy.context.object\n bpy.ops.object.mode_set(mode='POSE')\n\n\n #現在選択されているノードをとっておく\n selected = []\n for pose in bpy.context.selected_pose_bones:\n selected.append(pose)\n\n bpy.ops.pose.select_all(action='DESELECT')\n bone_groups = amt.pose.bone_groups\n\n bone_groups.active = bone_groups[\"Switch\"]\n bpy.ops.pose.group_select() \n ui_list.add()\n\n bpy.ops.pose.select_all(action='DESELECT')\n\n for pose in selected:\n pose.bone.select = True\n\n return {'FINISHED'}\n\n\n#インフルエンスを0に\nclass SwitchInfluence_0(bpy.types.Operator):\n bl_idname = \"rigtool.switchinfluence_0\"\n bl_label = \"inf0\"\n\n def execute(self, context):\n keep_matrix()\n setInfluenceValue(0)\n return {'FINISHED'}\n\n\n#インフルエンスを1.0に\nclass SwitchInfluence_100(bpy.types.Operator):\n bl_idname = \"rigtool.switchinfluence_100\"\n bl_label = \"inf100\"\n\n def execute(self, context):\n keep_matrix()\n setInfluenceValue(1.0)\n return {'FINISHED'}\n\nclass Return_Matrix_UncheckedBones(bpy.types.Operator):\n \"\"\"チェックされていないボーンのマトリックスを復帰させる。\\nスイッチしたときにポーズが変わってしまったボーンがあった場合このボタンを押せば修正される。\"\"\"\n bl_idname = \"rigtool.return_matrix_uncheckedbones\"\n bl_label = \"Return\"\n\n def execute(self, context):\n return_matrix_unchecked()\n return {'FINISHED'}\n\n\n\n#キーを打つ\nclass KeySwitchBones(bpy.types.Operator):\n bl_idname = \"rigtool.key_switch_bones\"\n bl_label = \"Key\"\n\n def execute(self, context):\n amt = bpy.context.object\n for bonename in lib.list_get_checked():\n bone = amt.pose.bones[bonename]\n\n for const in bone.constraints:\n const.keyframe_insert(data_path=\"influence\")\n\n\n return {'FINISHED'}\n\n\n\n\n#マトリックスのコピペをミラーにも使いたいため、初期マトリックスからの差分を持っておく\n#マトリックスの掛け算だけだと位置のミラーがうまくいかないので、ポジション情報も持たせておく\n#BONE_MATRIX ( matrix , 差分matrix , ポジション )\nclass Matrix_Copy(bpy.types.Operator):\n \"\"\"マトリックスコピー\\n\"\"\"\n bl_idname = \"rigtool.matrix_copy\"\n bl_label = \"コピー\"\n\n def execute(self, context):\n copy_matrix()\n return {'FINISHED'}\n\n\n\nclass Matrix_Paste(bpy.types.Operator):\n \"\"\"マトリックスペースト\"\"\"\n bl_idname = \"rigtool.matrix_paste\"\n bl_label = \"ペースト\"\n\n def execute(self, context):\n for bone in bpy.context.selected_pose_bones:\n bone.matrix =BONE_MATRIX[0]\n\n return {'FINISHED'}\n\n\n#エディットモードに入ればマトリックスの初期値が得られることを利用\nclass Matrix_Paste_Mirror(bpy.types.Operator):\n \"\"\"マトリックスミラーペースト\"\"\"\n bl_idname = \"rigtool.matrix_paste_mirror\"\n bl_label = \"ミラーペースト\"\n\n def execute(self, context):\n m0 = BONE_MATRIX[0][1] \n m0.transpose()\n\n l = (-BONE_MATRIX[0][2][0],BONE_MATRIX[0][2][1],BONE_MATRIX[0][2][2])\n m1 =Matrix(((m0[0][0],-m0[0][1],-m0[0][2],0),(-m0[1][0],m0[1][1],m0[1][2],0),(-m0[2][0],m0[2][1],m0[2][2],0),(0,0,0,1)))\n m1.transpose()\n\n\n bonematrixarray = {}\n initmatrixarray = {}\n\n for bone in bpy.context.selected_pose_bones:\n bonematrixarray[bone.name] = bone.matrix\n\n\n bpy.ops.object.mode_set(mode = 'EDIT')\n for bone in bpy.context.active_object.data.bones:\n if bone.name in bonematrixarray:\n initmatrixarray[bone.name] = Matrix(bone.matrix_local)\n\n\n\n bpy.ops.object.mode_set(mode = 'POSE')\n for bone in bpy.context.selected_pose_bones:\n\n m = m1 * initmatrixarray[bone.name]\n\n print(m)\n m[0][3] = l[0]\n m[1][3] = l[1]\n m[2][3] = l[2]\n\n bone.matrix = m\n\n\n return {'FINISHED'}\n\n\n\n#----------------------------------------------------\n#マトリックスのコピペ\n#選択したボーンのマトリックスを保持して書き戻す\n#別の骨にコピーするコマンドではない\n#----------------------------------------------------\nclass Matrix_Keep(bpy.types.Operator):\n \"\"\"マトリックス保持\\n選択したボーンのマトリックスを保持して書き戻す\\n別の骨にコピーするコマンドではない\"\"\"\n bl_idname = \"rigtool.matrix_keep\"\n bl_label = \"保持\"\n\n def execute(self, context):\n global BONE_MATRIX_ARRAY\n BONE_MATRIX_ARRAY.clear()\n amt = bpy.context.object\n\n for bone in bpy.context.selected_pose_bones:\n BONE_MATRIX_ARRAY[bone.name] = Matrix(bone.matrix)\n return {'FINISHED'}\n\n\nclass Matrix_Return(bpy.types.Operator):\n \"\"\"選択したボーンのマトリックス復帰\"\"\"\n bl_idname = \"rigtool.matrix_return\"\n bl_label = \"復帰\"\n\n def execute(self, context):\n global BONE_MATRIX_ARRAY\n for bone in bpy.context.selected_pose_bones:\n if (bone.name in BONE_MATRIX_ARRAY):\n bone.matrix =BONE_MATRIX_ARRAY[bone.name]\n\n return {'FINISHED'}\n\n\n\n\n#姿勢のミラーコピー\nclass Matrix_Auto_Mirror(bpy.types.Operator):\n \"\"\"命名規則を元に姿勢をミラーリング\\nコピーしたいボーンを選択して実行する。\"\"\"\n bl_idname = \"rigtool.matrix_auto_mirror\"\n bl_label = \"反転コピー\"\n\n def execute(self, context):\n amt = bpy.context.object\n BONE_DATA_ARRAY.clear()\n bonematrixarray = {}\n\n \n\n\n bpy.ops.object.mode_set(mode = 'POSE')\n for bone in bpy.context.selected_pose_bones:\n BONE_DATA_ARRAY.append(BoneData(bone))\n \n \n bpy.ops.object.mode_set(mode = 'EDIT')\n for b in BONE_DATA_ARRAY:\n b.setup()\n\n bpy.ops.object.mode_set(mode = 'POSE') \n for b in BONE_DATA_ARRAY:\n b.mirror_auto()\n\n return {'FINISHED'}","sub_path":"rig_pose.py","file_name":"rig_pose.py","file_ext":"py","file_size_in_byte":15788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"161679656","text":"# -*- coding: utf-8 -*-\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom math import sin, cos\nimport cv2\n\nOFF = -100\nBH_SIZE = 40\n\nLOGOS_MALE_FEMALE = [cv2.resize(cv2.imread(x), (0,0), fx=0.2, fy=0.2) for x in [\"male.png\", \"female.png\"]]\nLOGO_ANGUS = cv2.imread(\"logo.png\")\nLOGO_ANGUS = cv2.resize(LOGO_ANGUS, (0,0), fx=0.05, fy=0.05)\nLINETH = 3\n\ndef display_logo(frame, lx, ly):\n if ly+LOGO_ANGUS.shape[0] < frame.shape[0] and ly > 0 and lx+LOGO_ANGUS.shape[1] < frame.shape[1] and lx > 0:\n sub = frame[ly:ly+LOGO_ANGUS.shape[0],lx:lx+LOGO_ANGUS.shape[1]]\n cv2.addWeighted(sub, 0, LOGO_ANGUS, 1, 0.0, dst=sub)\n\ndef rotateLine(ptx, pty, centerx, centery, alpha):\n s = sin(alpha)\n c = cos(alpha)\n ptxn = (+c*(ptx-centerx) + s*(pty-centery)) + centerx\n ptyn = (-s*(ptx-centerx) + c*(pty-centery)) + centery\n return (int(ptxn), int(ptyn))\n\ndef rect(frame, p1, p2, rect_color=None, thickness=1):\n x1, y1 = p1\n x2, y2 = p2\n sub = frame[y1:y2, x1:x2]\n if rect_color:\n cv2.rectangle(frame, (x1, y1), (x2, y2), rect_color, thickness=thickness)\n\ndef blur(frame, p1, p2, rect_color=None, thickness=1):\n x1, y1 = p1\n x2, y2 = p2\n sub = frame[y1:y2, x1:x2]\n cv2.GaussianBlur(sub, (31, 31), 130, dst=sub)\n if rect_color:\n cv2.rectangle(frame, (x1, y1), (x2, y2), rect_color, thickness=thickness)\n\ndef get_age(age):\n label =\"20-30\"\n if age < 10:\n label = \"0-10\"\n elif age < 20:\n label = \"10-20\"\n elif age < 30:\n label = \"20-30\"\n elif age < 40:\n label = \"30-40\"\n elif age < 50:\n label = \"40-50\"\n elif age >= 50:\n label = \"50+\"\n return label\n\ndef displayAge(frame, idx, h, f_roi_conf, f_age_conf):\n if h['face_roi_confidence'] > f_roi_conf:\n roi = h['face_roi']\n x1 = int(roi[0])\n x2 = int(roi[0]+roi[2])\n y1 = int(roi[1])\n y2 = int(roi[1]+roi[3])\n sub = frame[y1:y2,x1:x2]\n age = h['age']\n gender = h['gender']\n ih = idx\n if h['age_confidence'] > f_age_conf:\n age = h[\"age\"]\n color = (100, 100, 100)\n cv2.putText(frame, get_age(age) + \" ans\",\n (int(roi[0]+ 10), int(roi[1] + OFF - int(BH_SIZE*2))), cv2.FONT_HERSHEY_SIMPLEX,\n 1, color, 2)\n x = int(roi[0]+0.5*roi[2])\n y = int(roi[1])\n return (x,y)\n else:\n return None\n\n\ndef displayHair(frame, idx, h):\n el_x = h['face_eye'][0][0]\n el_y = h['face_eye'][0][1]\n er_x = h['face_eye'][1][0]\n er_y = h['face_eye'][1][1]\n m_x = h['face_mouth'][0]\n m_y = h['face_mouth'][1]\n\n em_x = (0.5*(el_x + er_x))\n em_y = (0.5*(el_y + er_y))\n\n v_x = m_x - em_x\n v_y = m_y - em_y\n\n h_x =int(em_x - 1.3*v_x)\n h_y = int(em_y - 1.3*v_y)\n\n dim = frame.shape\n if h_x < dim[1] and h_y < dim[0]:\n ch = frame[h_y, h_x]\n return (int(ch[0]), int(ch[1]), int(ch[2]))\n else:\n return None\n\ndef mo(color, strength):\n c1, c2, c3 = color\n strength = strength * 70 + 30\n return (c1*strength/100,\n c2*strength/100,\n c3*strength/100)\n\ndef drawHalCircleRounded(image, center, radius, c, s_angle, e_angle, thickness):\n axes = (radius, radius)\n angle = 0\n cv2.ellipse(image, center, axes, angle, s_angle, e_angle, (c[2], c[1], c[0]), thickness)\n\ndef displayAvatar(frame, h, pt, ch):\n if pt is not None:\n conf = max(h[\"full_body_roi_confidence\"], h[\"face_roi_confidence\"])\n #hair\n if ch is not None:\n cv2.circle(frame, (pt[0], pt[1] - int(BH_SIZE*0.5) + OFF), int(BH_SIZE*1.2), mo((ch[2], ch[1], ch[0]), conf), -5)\n #face\n cv2.circle(frame, (pt[0], pt[1] + OFF), BH_SIZE, mo((102, 178, 255), conf), -5)\n\n\ndef displayEmotion(frame, h, pt):\n if h['emotion_smiling_degree'] > 0.30:\n rr = h['emotion_smiling_degree']*90\n\n drawHalCircleRounded(frame, (pt[0], pt[1] + int(BH_SIZE*0.3) + OFF), int(BH_SIZE*0.5), (0, 0, 0), 90-rr, 90+rr, 4)\n return\n\n if h['emotion_surprise'] > 0.50:\n drawHalCircleRounded(frame, (pt[0], pt[1] + int(BH_SIZE*0.5) + OFF), int(BH_SIZE*0.3), (0, 0, 0), 0, 360, 2)\n return\n\n if h['emotion_anger'] > 0.40:\n cv2.line(frame, (pt[0] - int(BH_SIZE*0.3), pt[1] - int(BH_SIZE*0.2) + OFF), (pt[0] - int(BH_SIZE*0.6), pt[1] - int(BH_SIZE*0.3) + OFF), (0, 0, 0), 2)\n cv2.line(frame, (pt[0] + int(BH_SIZE*0.3), pt[1] - int(BH_SIZE*0.2) + OFF), (pt[0] + int(BH_SIZE*0.6), pt[1] - int(BH_SIZE*0.3) + OFF), (0, 0, 0), 2)\n drawHalCircleRounded(frame, (pt[0], pt[1] + int(BH_SIZE*1) + OFF), 15, (0, 0, 0), 240, 300, 4)\n return\n\n if h['emotion_smiling_degree'] < 0.20:\n drawHalCircleRounded(frame, (pt[0], pt[1] + int(BH_SIZE*0.3) + OFF), 15, (0, 0, 0), 60, 120, 4)\n return\n\ndef displayGender(frame, h, pt):\n conf = h['gender_confidence']\n if conf > 0.5 and pt is not None:\n logo = LOGOS_MALE_FEMALE[h['gender'] == \"female\"]\n lx = pt[0] + int(BH_SIZE*1.5)\n ly = pt[1] + OFF - int(BH_SIZE*1)\n if ly+logo.shape[0] < frame.shape[0] and ly > 0 and lx+logo.shape[1] < frame.shape[1] and lx > 0:\n sub = frame[ly:ly+logo.shape[0],lx:lx+logo.shape[1]]\n cv2.addWeighted(sub, 1, logo, conf, 0.0, dst=sub)\n\n\ndef displayGaze(frame, idx, h, pt, f_roi_conf):\n if h['face_roi_confidence'] > f_roi_conf:\n nose = (pt[0], pt[1] + OFF)\n eyel = (pt[0] - int(BH_SIZE*0.5), pt[1] - int(BH_SIZE*0.2) + OFF)\n eyer = (pt[0] + int(BH_SIZE*0.5), pt[1] - int(BH_SIZE*0.2) + OFF)\n\n theta = - h['head'][0]\n phi = h['head'][1]\n psi = h['head'][2]\n\n length = 50\n xvec = int(length*(sin(phi)*sin(psi) - cos(phi)*sin(theta)*cos(psi)))\n yvec = int(- length*(sin(phi)*cos(psi) - cos(phi)*sin(theta)*sin(psi)))\n cv2.line(frame, nose, (nose[0]+xvec, nose[1]+yvec), (10, 10, 10), LINETH)\n\n psi = 0\n theta = - h['gaze'][0]\n phi = h['gaze'][1]\n\n\n length = 150\n xvec = int(length*(sin(phi)*sin(psi) - cos(phi)*sin(theta)*cos(psi)))\n yvec = int(- length*(sin(phi)*cos(psi) - cos(phi)*sin(theta)*sin(psi)))\n cv2.line(frame, eyel, (eyel[0]+xvec, eyel[1]+yvec), (132, 70, 39), LINETH)\n\n xvec = int(length*(sin(phi)*sin(psi) - cos(phi)*sin(theta)*cos(psi)))\n yvec = int(- length*(sin(phi)*cos(psi) - cos(phi)*sin(theta)*sin(psi)))\n cv2.line(frame, eyer, (eyer[0]+xvec, eyer[1]+yvec), (132, 70, 39), LINETH)\n\n\ndef computeConversion(res, events, entities, engaged, stats, animation, g_conf, eng_conf):\n for e in events:\n if e[\"entity_type\"] == \"appearance\":\n stats.add_engaged(False)\n\n for idx, h in entities.iteritems():\n if h['gaze_confidence'] > g_conf:\n length = 150\n psi = 0\n theta = - h['gaze'][0]\n phi = h['gaze'][1]\n xvec = int(length*(sin(phi)*sin(psi) - cos(phi)*sin(theta)*cos(psi)))\n yvec = int(- length*(sin(phi)*cos(psi) - cos(phi)*sin(theta)*sin(psi)))\n if xvec*xvec + yvec*yvec < eng_conf:\n if idx not in engaged:\n engaged.append(idx)\n stats.add_engaged(True)\n stats.add_age(h[\"age\"])\n stats.add_gender(h[\"gender\"])\n animation.append({\"title\":\"+1 !\", \"counter\":0})\n\ndef displayConversion(frame, stats, pt):\n data = stats.engaged()\n tot = data[\"engaged\"] + data[\"not_engaged\"]\n if tot != 0:\n a = 100*data[\"engaged\"]/float(tot)\n b = 100*data[\"not_engaged\"]/float(tot)\n datap = [{\"title\": \"Has looked\" + \" (\" + '%s'%int(data[\"engaged\"]) + \")\", \"width\": a, \"color\": (221,155,30)},\n {\"title\":\"Not looked\" + \" (\" + '%s'%int(data[\"not_engaged\"]) + \")\", \"width\": b, \"color\": (0, 140, 255)}]\n displayNumber(frame, (pt[0], pt[1] - 150), 60, int(100*data[\"engaged\"]/(data[\"engaged\"]+abs(data[\"not_engaged\"]))), \"Engagement\", 30)\n\n data = stats.ages()\n tot = 0\n for key, value in data.iteritems():\n tot += value\n\n datap = []\n color = [(100,255,100), (100,255,100), (255,0,255), (0,255,255), (255,255,0), (255,100,100), (100,100,255)]\n if tot != 0:\n i = 0\n for key, value in data.iteritems():\n a = 100*value/float(tot)\n datap.append({\"title\": key, \"width\": a, \"color\": color[i]})\n i += 1\n displayPieChartBlock(frame, (pt[0], pt[1]), 40, datap, \"Age\", 20)\n\n\n data = stats.genders()\n tot = 0\n for key, value in data.iteritems():\n tot += value\n\n datap = []\n color = [(255,128,0), (127,0,255)]\n if tot != 0:\n i = 0\n for key, value in data.iteritems():\n a = 100*value/float(tot)\n datap.append({\"title\": key, \"width\": a, \"color\": color[i]})\n i += 1\n displayPieChartBlock(frame, (pt[0], pt[1] + 200), 40, datap, \"Sexe\", 20)\n\ndef displayAnimation(frame, animation):\n # pprint.pprint(animation)\n for a in animation:\n if a[\"counter\"] < 30:\n if a[\"title\"] == \"+1 passing\":\n cv2.putText(frame, a[\"title\"],\n (500, 500 - 15*a[\"counter\"]), cv2.FONT_HERSHEY_SIMPLEX,\n 5, (0, 140, 255), 3)\n elif a[\"title\"] == \"+1 !\":\n cv2.putText(frame, a[\"title\"],\n (500, 500 - 25*a[\"counter\"]), cv2.FONT_HERSHEY_SIMPLEX,\n 3, mo((255,255,255),1.0 - 0.002*25*a[\"counter\"]), 5)\n a[\"counter\"] += 1\n else:\n animation.remove(a)\n\ndef displayPieChartBlock(frame, pt, size, data, title, thickness):\n textSize = cv2.getTextSize(title, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)[0];\n\n cv2.putText(frame, title,\n (int(pt[0] - 0.5*textSize[0]), pt[1] - int(1.5*size)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.8, (255, 255, 255), 2)\n\n displayPieChart(frame, pt, size, data, thickness)\n\ndef displayNumber(frame, pt, size, data, title, thickness):\n textSize = cv2.getTextSize(title, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)[0];\n\n cv2.putText(frame, title,\n (int(pt[0] - 0.5*textSize[0]), pt[1] - int(1.5*size)), cv2.FONT_HERSHEY_SIMPLEX,\n 0.8, (255, 255, 255), 2)\n\n ss = str(data) + \"%\"\n textSize = cv2.getTextSize(ss, cv2.FONT_HERSHEY_SIMPLEX, 3, 2)[0];\n cv2.putText(frame, ss,\n (int(pt[0] - 0.5*textSize[0]), pt[1]), cv2.FONT_HERSHEY_SIMPLEX,\n 3, (255, 255, 255), 2)\n\n\n\ndef displayPieChart(frame, pt, size, data, thickness):\n axes = (size, size)\n alpha = 0.0\n s_angle = alpha\n for cat in data:\n if cat[\"width\"] > 0:\n e_angle = s_angle + 360*cat[\"width\"]/100.0\n cv2.ellipse(frame, pt, axes, alpha, s_angle, e_angle, cat[\"color\"], thickness)\n mid_angle = 0.5*(e_angle + s_angle)\n s_angle = e_angle\n tg = rotateLine(pt[0]+size+50, pt[1], pt[0], pt[1], -3.1415/180.0*mid_angle)\n tt = cat[\"title\"]\n\ndef blur(frame, p1, p2, rect_color=None, thickness=1):\n x1, y1 = p1\n x2, y2 = p2\n sub = frame[y1:y2, x1:x2]\n cv2.GaussianBlur(sub, (31,31), 130, dst=sub)\n if rect_color:\n cv2.rectangle(frame, (x1, y1), (x2, y2), rect_color, thickness=thickness)\n","sub_path":"demo_sceneanalysis/angus_display.py","file_name":"angus_display.py","file_ext":"py","file_size_in_byte":12053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"194749202","text":"# This script creates a plot of the fraction of OVI\n# gas in the simulations GM1 & GM3(GM4 in old terms)\n# at a variety of densities\n\n# N. Nicole Sanchez -- Created: July 9, 2018\n# Univ. of Wash, S -- Edited:\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom hdf5_Novi_R import *\nimport numpy as np\nimport pynbody\nimport sys\n\nif len(sys.argv) == 1:\n print('No galaxy selected. Current options: P0, GM1, GM7, GM4')\n print('Syntax: \"f_ovi_vs_T.py GM1\"')\n quit()\nelse:\n if (str(sys.argv[1]) == 'P0'):\n sim = pynbody.load('/nobackupp2/nnsanche/pioneer50h243.1536g1bwK1BH/pioneer50h243.1536gst1bwK1BH.003456')\n elif (str(sys.argv[1]) == 'GM1'):\n sim = pynbody.load('/nobackupp2/nnsanche/pioneer50h243GM1.1536gst1bwK1BH/pioneer50h243GM1.1536gst1bwK1BH.003456')\n elif (str(sys.argv[1]) == 'GM4'):\n sim = pynbody.load('/nobackupp2/nnsanche/pioneer50h243GM4.1536gst1bwK1BH/pioneer50h243GM4.1536gst1bwK1BH.003456') \n elif (str(sys.argv[1]) == 'GM5'):\n sim = pynbody.load('/nobackup/nnsanche/pioneer50h243GM5.1536gst1bwK1BH/pioneer50h243GM5.1536gst1bwK1BH.003546')\n elif (str(sys.argv[1]) == 'GM6'):\n sim = pynbody.load('/nobackupp8/fgoverna/pioneer50h243GM6.1536gst1bwK1BH/pioneer50h243GM6.1536gst1bwK1BH.003456')\n elif (str(sys.argv[1]) == 'GM7'):\n sim = pynbody.load('/nobackupp2/nnsanche/pioneer50h243GM7.1536gst1bwK1BH/pioneer50h243GM7.1536gst1bwK1BH.003456') \n\n else :\n print('Not a valid option. Current options: P0, GM1, GM7, GM4')\n print('Syntax: \"f_ovi_vs_T.py GM1\"')\n quit() \n\n if str(sys.argv[1]) == 'GM4':\n name = 'GM3'\n elif str(sys.argv[1]) == 'GM7':\n name = 'GM2'\n else:\n name = str(sys.argv[1])\n print(name+' simulation at z = ','%.2f' % sim.properties['z'] )\n\nsim.properties\nsim.properties['time'].in_units('Gyr')\nsim.loadable_keys()\nsim.physical_units()\nh = sim.halos()\nh1 = h[1]\npynbody.analysis.angmom.faceon(h1)\n\n# Constants\nm_H = 1.6733 * 10**-24 #g\n\n# Want to isolate CGM \n# Isolate and remove disk stars within radius 0-10 kpc & vertically 4 kpc \nr_max = 10 # kpc\nz_max = 10 # kpc\n\nRg_d = ((h1.g['x'].in_units('kpc'))**2. + (h1.g['y'].in_units('kpc'))**2.)**(0.5)\ndisk_gas_xymax = (Rg_d < r_max)\ndisk_gas_zmax = (h1.g['z'].in_units('kpc') < z_max) & (h1.g['z'].in_units('kpc') > -z_max)\n\ndisk_gas_mask = disk_gas_xymax & disk_gas_zmax\ndisk_gas = h1.g[disk_gas_xymax & disk_gas_zmax]\nCGM_gas = h1.g[~disk_gas_mask]\n\ndensity_array = [r'10$^{-2}$',r'10$^{-3}$',r'10$^{-4}$',r'10$^{-5}$']\n\n# Using original .npz table from Stinson 2012\novi_npz = pynbody.analysis.ionfrac.calculate(CGM_gas,ion='ovi',mode='new') \n\n#rho_10_m2 = (CGM_gas['rho'] > 0.05) & (CGM_gas['rho'] > 0.005)\n#CGMg_10_m2 = CGM_gas[rho_10_m2]\n\n#CGMg_fovi = (CGM_gas['mass']*CGM_gas['OxMassFrac']*ovi_npz)/CGM_gas['mass']\n#plt.hexbin(np.log10(CGM_gas['temp']),CGMg_fovi,C=np.log10(CGM_gas['rho']),cmap=cm.plasma)\n#plt.plot(CGMg_10_m2['temp'],CGMg_10_m2['mass']*CGMg_10_m2['OxMassFrac']*ovi_npz[rho_10_m2],label=density_array[0],linestyle=None,marker='.')\n#plt.ylabel(r'f$_{OVI}$')\n#plt.xlabel('T [K]')\n#plt.colorbar(label=r'$\\rho$')\n#plt.title(name+', using .npz table')\n#plt.savefig(name+'_fovi_T_npz.pdf')\n#plt.show()\n\n# Using new HDF5 table from Corlies and Hummels\novi_hdf5 = hdf5_ion_frac(CGM_gas,ion='ovi')\n\nCGMg_fovi = (CGM_gas['mass']*CGM_gas['OxMassFrac']*ovi_hdf5)/CGM_gas['mass']\nplt.hexbin(np.log10(CGM_gas['temp']),CGMg_fovi,C=np.log10(CGM_gas['rho']),cmap=cm.plasma)\nplt.ylabel(r'f$_{OVI}$')\nplt.xlabel('T [K]')\nplt.colorbar(label=r'$\\rho$')\nplt.title(name+', using hdf5 table')\nplt.savefig(name+'_fovi_T_hdf5.pdf')\nplt.show()\n\n\nplt.hexbin(np.log10(CGM_gas['rho'].in_units('g cm**-3')/m_H),CGMg_fovi,C=np.log10(CGM_gas['temp']),cmap=cm.plasma)\nplt.ylabel(r'f$_{OVI}$')\nplt.xlabel(r'Log$_{10}$ n$_H$ (cm$^{-3}$)',size=15)\nplt.colorbar(label=r'T [K]')\nplt.title(name+', using hdf5 table')\nplt.savefig(name+'_fovi_rho_hdf5.pdf')\nplt.show()\n\n\n\n\n\n\n\n","sub_path":"ion_fracs/f_ovi_vs_T.py","file_name":"f_ovi_vs_T.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"565055623","text":"import numpy\nimport urllib3\nimport urllib\nimport time\nimport cv2\nfrom datetime import datetime, timedelta\nimport base64\nimport json\nimport requests\nimport os, os.path\n\n\nclass FeatureExtraction:\n def __init__(self):\n self.fpp = Facepp()\n self.frame_counter = 1\n self.start_time = self.now()\n self.delta = timedelta(seconds=1.2)\n self.block = False\n self.counter = len(\n [name for name in os.listdir(\"./imgs/\") if os.path.isfile(name)]\n )\n\n def now(self):\n return datetime.now()\n\n def parse_frame(self, frame):\n # if self.now() - self.start_time > self.delta and not self.block:\n self.block = True\n self.counter += 1\n path = \"./imgs/mmegg \" + str(self.counter) + \".jpeg\"\n cv2.imwrite(path, frame)\n\n try:\n data = self.fpp.parse_frame(path)\n print(data)\n return data\n\n except Exception as e:\n print(e)\n\n self.start_time = self.now()\n self.block = False\n\n\nclass Facepp:\n def __init__(self):\n self.http_url = \"https://api-us.faceplusplus.com/facepp/v3/detect\"\n self.key = \"LX2oRHchELnqIswcEGQMCpMslc05lE7m\"\n self.secret = \"4sK29DKX4gJrJ-wv9l4RQyR0VlQQS9Mw\"\n self.http = urllib3.PoolManager()\n\n def getBaseFormat(self):\n data_dict = {}\n\n data_dict[\"api_key\"] = self.key\n data_dict[\"return_attributes\"] = \"gender,age,ethnicity\"\n data_dict[\"api_secret\"] = self.secret\n\n return data_dict\n\n def parse_frame(self, path):\n querystring = self.getBaseFormat()\n\n files = {\n \"image_file\": (\"whatever.jpg\", open(path, \"rb\")),\n \"Content-Type\": \"image/jpeg\",\n }\n\n try:\n # post data to server\n resp = requests.request(\n \"POST\", self.http_url, files=files, params=querystring\n )\n qrcont = resp.text\n jason = json.loads(qrcont)\n print(jason)\n return jason[\"faces\"]\n except Exception as e:\n print(e)\n\n","sub_path":"FE_branch.py","file_name":"FE_branch.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"192217273","text":"\n#===========================================================================\n#\tAuthor : MAHNOOR ANJUM\n#\tDescription : Cancer Dataset Solution\n#\tUsing multiple algorithms and plotting their results\n#\tObtaining Classification reports\n#\n#\tReferences:\n#\tSuperDataScience\n#\tOfficial Documentation\n#\n#\tData Source:\n#\thttps://www.kaggle.com/uciml/breast-cancer-wisconsin-data\n#\n#\tCOMMENT AND UNCOMMENT MODELS ACCORDING TO YOUR NEEDS\n#===========================================================================\n# Importing the libraries\nimport numpy as np#Numpy for data importing, array management\nimport matplotlib.pyplot as plt#for data plotting \nimport pandas as pd#for data manipulation, data mining, data munging\n\n# Importing the dataset\ndataset = pd.read_csv('data2.csv')#importing the label encoded dataset\nX = dataset.iloc[:, 3:33].values#selecting the independent variables MATRIX\ny = dataset.iloc[:, 2].values#selecting/slicing a dependent variable VECTOR\n\n\n# Splitting the dataset into the Training set and Test set\nfrom sklearn.model_selection import train_test_split#Importing library module for splitting dataset into\n#test and train subsets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15)\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler#for feature scaling\nsc = StandardScaler()#making an instance of a class\nX_train = sc.fit_transform(X_train)#fitting on the train set\nX_test = sc.transform(X_test)#transforming on the test set \n\n#PRINCIPLE COMPONENT ANALYSIS\n\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 2)\nX_train = pca.fit_transform(X_train)\nX_test = pca.transform(X_test)\nexplained_variance = pca.explained_variance_ratio2\n\n#===================================================================\n#ARTIFICIAL NEURAL NETWORK\n# Importing the Keras libraries and packages\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n\n# Initialising the ANN\nclassifierann = Sequential()\n\n# Adding the input layer and the first hidden layer CHANGE INPUT_DIM TO 2 WITH PCA\nclassifierann.add(Dense(output_dim = 9, init = 'uniform', activation = 'relu', input_dim = 30))\n\n# Adding the second hidden layer\n#classifier.add(Dense(output_dim = 16, init = 'uniform', activation = 'relu'))\n# Adding the output layer\nclassifierann.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))\n\n# Compiling the ANN\nclassifierann.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting the ANN to the Training set\nclassifierann.fit(X_train, y_train, batch_size = 20, nb_epoch = 100)\n\n# Predicting the Test set results\ny_pred_ann = classifierann.predict(X_test)\ny_pred_ann = y_pred_ann.round()\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncmann = confusion_matrix(y_test, y_pred_ann)\n#===============================================================================\n\n#NAIVE BAYES\n\n\nfrom sklearn.naive_bayes import GaussianNB\nclassifiernb = GaussianNB()\nclassifiernb.fit(X_train, y_train)\n\ny_pred_nb = classifiernb.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncmnb = confusion_matrix(y_test, y_pred_nb)\n\n\nfrom sklearn.metrics import accuracy_score\nasnb = accuracy_score(y_test, y_pred_nb)\n#===============================================================================\n\n#KNN\n\n# Fitting K-NN to the Training set\nfrom sklearn.neighbors import KNeighborsClassifier\nclassifierknn = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)\nclassifierknn.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_predknn = classifierknn.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncmknn = confusion_matrix(y_test, y_predknn)\n# Making the predictions and evaluating the model\n#===============================================================================\n#DECISION TREES\n# Fitting Decision Tree Classification to the Training set\nfrom sklearn.tree import DecisionTreeClassifier\nclassifierdt = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\nclassifierdt.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_preddt = classifierdt.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncmdt = confusion_matrix(y_test, y_preddt)\n\n#===============================================================================\n#KERNEL GAUSSIAN\n\nfrom sklearn.svm import SVC\nclassifierksvm = SVC(kernel = 'rbf', random_state = 0)\nclassifierksvm.fit(X_train, y_train)\n\n# Predicting the Test set results\ny_predksvm = classifierksvm.predict(X_test)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_predksvm)\n\nclassifier = classifierann\n\n\n# Visualising the Training set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.55, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('ANN(Train set)')\nplt.xlabel('PC1')\nplt.ylabel('PC2')\nplt.legend()\nplt.show()\n\n# Visualising the Test set results\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = X_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.55, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Naive Bayes (Test set)')\nplt.xlabel('PC1')\nplt.ylabel('PC2')\nplt.legend()\nplt.show()\n\n\n\n#MODEL EVALUATION\nfrom sklearn import metrics\n# calculate the fpr and tpr for all thresholds of the classification\ny_pred = classifier.predict(X_test)\n#y_pred = y_prob[:,1]\nfpr, tpr, threshold = metrics.roc_curve(y_test, y_pred)\nroc_auc = metrics.auc(fpr, tpr)\n\n# method I: plt\nimport matplotlib.pyplot as plt\nplt.title('Receiver Operating Characteristic')\nplt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % roc_auc)\nplt.legend(loc = 'lower right')\nplt.plot([0, 1], [0, 1],'r--')\nplt.xlim([0, 1])\nplt.ylim([0, 1.02])\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()\n\n\n\n\n\n\n\n","sub_path":"Cancer.py","file_name":"Cancer.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"130330105","text":"import typing\n\n\nclass Application:\n def __init__(self, scope: typing.Dict) -> None:\n self.scope = scope\n print(\"SCOPE\", scope)\n\n async def __call__(\n self,\n receive: typing.Callable[..., typing.Awaitable[typing.Dict]],\n send: typing.Callable[..., typing.Awaitable[None]],\n ) -> None:\n i = 1\n\n while True:\n msg = await receive()\n\n if msg[\"type\"] in [\"nats.connect\", \"nats.disconnect\"]:\n print(\"Conn EVENT: \", msg)\n continue\n\n print(\"MESSAGE: \", msg, \"counter\", i)\n\n # await send(\n # {\n # \"type\": \"nats.request\",\n # \"subject\": \"whale.reply\",\n # \"bytes_data\": msg[\"bytes_data\"],\n # \"timeout\": 3,\n # }\n # )\n\n if i % 5 == 0:\n # Raise exception to test exception handling\n raise ValueError(\"Catch this :)\")\n\n i += 1\n\n\napplication = Application\n","sub_path":"contrib/asgi.py","file_name":"asgi.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"494762719","text":"\"\"\"\nCreated By : Nikesh\nCreated On :\nReviewed By :\nReviewed On :\nVersion :\n\"\"\"\nimport json\nimport os\nfrom string import Template\n\nfrom examsystemapp.models.payment_advice_header import PaymentAdviceHeaderModel\nfrom examsystemapp.models.notification.notification_default_recipients import NotificationDefaultRecipientsModel\nfrom examsystemapp.services.notification.base_notification_service import BaseNotificationService\nfrom examsystemapp.utils.helpers.request_helper import ParamsObject\nfrom examsystemapp.services.user_service import UserService\nfrom examsystemapp.services.entity_service import EntityService\n\n\n# from examsystemapp.services.invoice_header_service import InvoiceHeaderService\n\n\nclass PaymentAdviceNotificationService(BaseNotificationService):\n\n def __init__(self, ext_params={}, is_transaction_owner=True, event_type=None):\n BaseNotificationService.__init__(self, ext_params, is_transaction_owner, event_type)\n\n def _object_type(self):\n payment_advice_object: PaymentAdviceHeaderModel = PaymentAdviceHeaderModel()\n return payment_advice_object.OBJECT_TYPE\n\n def _get_payload(self, action, data):\n return None\n\n def _get_url(self, action, data):\n if action == \"ADD\" or action == \"UPDATE\":\n return '/payment-request/get?id=' + str(data.advice_id)\n else:\n return None\n\n def _get_object_id(self, action, data):\n if action == \"ADD\" or action == \"UPDATE\":\n return data.advice_id\n else:\n return None\n\n def _build_title(self, action, data, template, conf):\n return template\n\n def _build_description(self, action, data, template, conf):\n \"\"\" Get Payment Advice Detail \"\"\"\n _params: ParamsObject = ParamsObject()\n _params.set_params_list([data.advice_id])\n\n payment = self.get_direct(\"sNotificationPaymentAdviceGet\", _params, False)\n payment = payment[0]\n\n self.ext_params[\"send_to\"] = payment[\"Requested_By\"]\n\n template = template.replace(\"\", str(payment[\"User_Name\"]) + os.linesep)\n template = template.replace(\"\", str(payment[\"Bills\"]) + os.linesep)\n template = template.replace(\"\", str(payment[\"Vendors\"]) + os.linesep)\n template = template.replace(\"\", str(payment[\"Total\"]))\n return template\n\n def _get_recipients(self, data: PaymentAdviceHeaderModel, conf):\n user_device_list = []\n params: ParamsObject = ParamsObject()\n params_list = []\n params_list.append(self.ext_params.get(\"send_to\"))\n params.set_params_list(params_list)\n\n device_list = self.get_direct(\"sUserDeviceByIDGet\", params, False)\n if device_list != \"\" and device_list is not None:\n if len(device_list) != 0:\n user_device_list.append(device_list)\n\n return user_device_list\n","sub_path":"examsystemapp/services/notification/payment_advice_notification_service.py","file_name":"payment_advice_notification_service.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"486043601","text":"# prompting the user\nprint(\"User, how long do you want your list to be?\")\nprint(\"Enter how long you want your list to be:\")\n\n# users list length and list\nlist_length = int(input())\nnumber_list = []\n\n# asking the user to input the amount of numbers they wanted and adding them the list\nfor i in range(list_length):\n print(\"User enter a number\")\n users_num = float(input())\n number_list.append(users_num)\n\n# finding the mean of the list\n\n\ndef mean():\n print(number_list, \"is your list.\")\n num_list_sum = sum(number_list)\n print(num_list_sum/list_length, \"is the mean of your list.\")\n\n# calling the function\n\n\nmean()\n\n","sub_path":"Mean2.py","file_name":"Mean2.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"207596184","text":"\"\"\"\nPercival client example application with ncurses text-gui interface\n\n\"\"\"\nfrom __future__ import print_function\n\nimport traceback\nimport argparse\nimport zmq\nimport npyscreen\n\nfrom percival.log import get_exclusive_file_logger\nfrom percival.detector.ipc_channel import IpcChannel\nfrom percival.detector.ipc_message import IpcMessage\nfrom percival.carrier import const\n\n\nclass PercivalClientApp(npyscreen.NPSAppManaged):\n \"\"\"\n This application class serves as a wrapper for the initialization of curses\n and also manages the actual forms of the application\n \"\"\"\n def __init__(self, ctrl_endpoint, status_endpoint):\n super(PercivalClientApp, self).__init__()\n self.ctrl_endpoint = ctrl_endpoint\n self.status_endpoint = status_endpoint\n self.poller = zmq.Poller()\n self.ctrl_channel = None\n self.status_channel = None\n self.current_value = None\n self.prev_value = None\n self.reply = None\n\n def onStart(self):\n self.keypress_timeout_default = 1\n self.registerForm(\"MAIN\", IntroForm())\n self.registerForm(\"MAIN_MENU\", MainMenu())\n self.registerForm(\"SYS_CMD\", SendSystemCommand())\n\n def send_message(self, ipc_message):\n log.debug(\"sending message: %s\", ipc_message)\n self.ctrl_channel.send(ipc_message.encode())\n pollevts = self.ctrl_channel.poll(1000)\n log.debug(\"poll event: %s\", pollevts)\n if pollevts == zmq.POLLIN:\n reply = IpcMessage(from_str=self.ctrl_channel.recv())\n log.debug(\"Message reply: %s\", reply)\n if reply:\n self.reply = reply\n self.current_value = str(reply)\n elif pollevts == 0:\n log.error(\"poll timeout without reply\")\n self.current_value = \"ERROR: poll timeout without reply\"\n\n def read_message(self, timeout):\n pollevts = self.ctrl_channel.poll(timeout)\n if pollevts == zmq.POLLIN:\n reply = IpcMessage(from_str=self.ctrl_channel.recv())\n return reply\n return None\n\n def read_status_message(self, timeout):\n pollevts = self.status_channel.poll(timeout)\n while pollevts == zmq.POLLIN:\n reply = IpcMessage(from_str=self.status_channel.recv())\n self.current_value = str(reply)\n pollevts = self.status_channel.poll(timeout)\n\n\n# This form class defines the display that will be presented to the user.\nclass IntroForm(npyscreen.Form):\n def create(self):\n self.name = \"Percival Carrier Board Client\"\n self.add(npyscreen.TitleText, labelColor=\"LABELBOLD\", name=\"Set the control and status endpoints of the application\", value=\"\", editable=False)\n self.ctrl = self.add(npyscreen.TitleText, name=\"Control Endpoint: \", value=\"\")\n self.stat = self.add(npyscreen.TitleText, name=\"Status Endpoint: \", value=\"\")\n\n def beforeEditing(self):\n self.ctrl.value = self.parentApp.ctrl_endpoint\n self.stat.value = self.parentApp.status_endpoint\n\n def afterEditing(self):\n log.debug(\"Connecting to IPC channel (status): %s\", self.stat.value)\n self.parentApp.status_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_SUB)\n self.parentApp.status_channel.connect(self.stat.value)\n self.parentApp.status_channel.subscribe(\"\")\n log.debug(\"Connected (status): %s\", self.parentApp.status_channel)\n self.parentApp.poller.register(self.parentApp.status_channel.socket, zmq.POLLIN)\n\n log.debug(\"Connecting to IPC channel (control): %s\", self.ctrl.value)\n self.parentApp.ctrl_channel = IpcChannel(IpcChannel.CHANNEL_TYPE_PAIR)\n self.parentApp.ctrl_channel.connect(self.ctrl.value)\n log.debug(\"Connected (control): %s\", self.parentApp.ctrl_channel)\n self.parentApp.setNextForm(\"MAIN_MENU\")\n\n\nclass MainMenu(npyscreen.FormBaseNew):\n def create(self):\n self.status_loop = False\n self.keypress_timeout = 1\n self.name = \"Percival Carrier Board Client\"\n self.t2 = self.add(npyscreen.BoxTitle, name=\"Main Menu:\", relx=2, max_width=28) # , max_height=20)\n self.t3 = self.add(npyscreen.BoxTitle, name=\"Response:\", rely=2, relx=30) # , max_width=45, max_height=20)\n\n self.t2.values = [\"Read Board Parameters\",\n \"Start Status Loop\",\n \"Stop Status Loop\",\n \"List Control Devices\",\n \"List Monitor Devices\",\n \"Send System Command\",\n \"Exit\"]\n self.t2.when_value_edited = self.button\n\n def button(self):\n selected = self.t2.entry_widget.value\n try:\n if selected == 0:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"list\", \"device\")\n self.parentApp.send_message(msg)\n self.parentApp.boards = self.parentApp.reply.get_param(\"device\")\n if selected == 1:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"status_loop\", \"run\")\n self.parentApp.send_message(msg)\n self.status_loop = True\n if selected == 2:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"status_loop\", \"stop\")\n self.parentApp.send_message(msg)\n self.status_loop = False\n if selected == 3:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"list\", \"controls\")\n self.parentApp.send_message(msg)\n if selected == 4:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"list\", \"monitors\")\n self.parentApp.send_message(msg)\n if selected == 5:\n self.parentApp.setNextForm(\"SYS_CMD\")\n self.editing = False\n self.parentApp.switchFormNow()\n if selected == 6:\n self.parentApp.setNextForm(None)\n self.parentApp.switchFormNow()\n except Exception as e:\n log.exception(e)\n tb = traceback.format_exc()\n self.parentApp.current_value = \"ERROR:\\n------------------------\\n\" + tb\n\n def while_waiting(self):\n if self.status_loop == True:\n self.parentApp.read_status_message(0.05)\n if self.parentApp.current_value != self.parentApp.prev_value:\n self.t3.values = self.parentApp.current_value.split(\"\\n\")\n self.t3.display()\n self.parentApp.prev_value = self.parentApp.current_value\n self.t2.entry_widget.value = None\n self.t2.entry_widget._old_value = None\n self.t2.display()\n\n\nclass SendSystemCommand(npyscreen.FormBaseNew):\n def create(self):\n self.keypress_timeout = 1\n self.name = \"Percival Carrier Board Client\"\n self.t2 = self.add(npyscreen.BoxTitle, name=\"Select system command to send:\")\n\n # Add all available system commands to the select list - and an exit (no-op) option at the end\n self.t2.values = [cmd.name for cmd in const.SystemCmd] + [\"Exit\"]\n self.t2.when_value_edited = self.button\n\n def button(self):\n selected = self.t2.entry_widget.value\n if selected is not None:\n self.t2.entry_widget.value = None\n self.t2.entry_widget._old_value = None\n if self.t2.values[selected] == \"Exit\":\n self.parentApp.setNextForm(\"MAIN_MENU\")\n self.editing = False\n self.parentApp.switchFormNow()\n else:\n msg = IpcMessage(IpcMessage.MSG_TYPE_CMD, IpcMessage.MSG_VAL_CMD_CONFIGURE)\n msg.set_param(\"system_command\", self.t2.values[selected])\n self.parentApp.send_message(msg)\n self.parentApp.setNextForm(\"MAIN_MENU\")\n self.editing = False\n self.parentApp.switchFormNow()\n\n\ndef options():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--control\", action=\"store\", default=\"tcp://127.0.0.1:8888\", help=\"ZeroMQ control endpoint\")\n parser.add_argument(\"-s\", \"--status\", action=\"store\", default=\"tcp://127.0.0.1:8889\", help=\"ZeroMQ status endpoint\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n global log\n log = get_exclusive_file_logger(\"client_example.log\")\n\n args = options()\n log.info(args)\n\n app = PercivalClientApp(args.control, args.status)\n app.run()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"percival/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":8737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230437917","text":"# The first line says that we'll use Flask to render a template, redirecting to another url, and creating a URL\r\nfrom flask import Flask, render_template, redirect, url_for\r\n# The second line says we'll use PyMongo to interact with our Mongo database.\r\nfrom flask_pymongo import PyMongo\r\n# The third line says that to use the scraping code, we will convert from Jupyter notebook to Python\r\nimport mars_scraping\r\n\r\n# Setup Flask\r\napp = Flask(__name__)\r\n \r\n# Use flask_pymongo to set up mongo connection\r\n# app.config[\"MONGO_URI\"] tells Python that our app will connect to Mongo using a URI, \r\n # URI: a uniform resource identifier similar to a URL\r\n# \"mongodb://localhost:27017/mars_app\" is the URI we'll be using to connect our app to Mongo. \r\n# This URI is saying that the app can reach Mongo through our localhost server, \r\n # using port 27017, using a database named \"mars_app\"\r\napp.config[\"MONGO_URI\"] = \"mongodb://localhost:27017/mars_app\"\r\nmongo = PyMongo(app)\r\n\r\n# Create the route for the HTML page\r\n@app.route(\"/\")\r\n# This function is what links our visual representation of our work, our web app, to the code that powers it\r\ndef index():\r\n # mars = mongo.db.mars.find_one() uses PyMongo to find the \"mars\" collection in our database, \r\n # which we will create when we convert our Jupyter scraping code to Python Script. \r\n # We will also assign that path to the mars variable for use later\r\n mars = mongo.db.mars.find_one()\r\n # return render_template(\"index.html\" tells Flask to return an HTML template using an index.html file. \r\n # We'll create this file after we build the Flask routes\r\n # , mars=mars) tells Python to use the \"mars\" collection in MongoDB.\r\n return render_template(\"index.html\", mars=mars)\r\n\r\n# Create the route for the scraping 'button'\r\n@app.route(\"/scrape\")\r\n# This function will scrape the updated data when we tell it to\r\n# The next lines allow us to access the database, scrape new data using our scraping.py script, \r\n # update the database, and return a message when successful\r\ndef scrape():\r\n # Assign a new variable that points to our Mongo database: mars = mongo.db.mars.\r\n mars = mongo.db.mars\r\n # created a new variable to hold the newly scraped data:\r\n # In this line, we're referencing the scrape_all function in the mars_scraping.py file \r\n # exported from Jupyter Notebook\r\n mars_data = mars_scraping.scrape_all()\r\n # Now that we've gathered new data, we need to update the database using .update()\r\n # Syntax is as follows: .update(query_parameter, data, options)\r\n # {} inserts a blank json object\r\n # we will choose the scraped data we have placed in mars_data\r\n # upsert=True tells Mongo to create a new document if one doesn't already exist \r\n mars.update({}, mars_data, upsert=True)\r\n # Finally, we will add a redirect after successfully scraping the data\r\n # This brings up back to the / route where we can see the updated data \r\n return redirect('/', code=302)\r\n\r\n# The final bit of code we need for Flask is to tell it to run\r\nif __name__ == \"__main__\":\r\n app.run()","sub_path":"Lesson/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77766872","text":"from selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom test.TestClass import TestClass\n\n\nclass NavigationBarTests(TestClass):\n def __init__(self, driver, name=\"NavigationBar\"):\n super().__init__(driver, name)\n\n def run(self):\n self.tests[\"test_navigationbar_homebutton\"] = self.test_homebutton()\n self.tests[\"test_navigationbar_projectsbutton\"] = self.test_projectsbutton()\n super().run()\n\n def test_homebutton(self):\n self.driver.get(\"http://localhost:8000/\")\n current_url = self.driver.current_url\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located((By.LINK_TEXT, \"Home\"))\n )\n element.click()\n except TimeoutException:\n return False\n finally:\n return current_url != self.driver.current_url\n\n def test_projectsbutton(self):\n self.driver.get(\"http://localhost:8000/\")\n current_url = self.driver.current_url\n try:\n element = WebDriverWait(self.driver, 10).until(\n EC.presence_of_element_located((By.LINK_TEXT, \"Projecten\"))\n )\n element.click()\n except TimeoutException:\n return False\n finally:\n return current_url != self.driver.current_url\n","sub_path":"test/NavigationBarTests.py","file_name":"NavigationBarTests.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"341421096","text":"\"\"\"\nRead and preprocess data.\n\"\"\"\n\nimport os\n\nimport nltk\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\nfrom semeval import SEMLoad\n\n\ndef read_relation2id(filepath='support/relation2id.txt'):\n label_to_index = {}\n with open(filepath, 'r') as f:\n for i in range(19):\n line = f.readline()\n index, label = line.split()\n label_to_index[label] = int(index)\n return label_to_index\n\n\ndef process_sentence_line(line):\n sent_id, sentence = line.split('\\t')\n sentence = sentence[1:-2] # remove quot \\n\n e1_left, e1_right = sentence.split('')\n e1_phrase, e2_sentence = e1_right.split('')\n between, e2_right = e2_sentence.split('')\n e2_phrase, e2_right = e2_right.split('')\n\n e1_left_sen_tokens = nltk.word_tokenize(e1_left)\n e1_left_index = len(e1_left_sen_tokens)\n e1_tokens = nltk.word_tokenize(e1_phrase)\n e1_right_index = e1_left_index + len(e1_tokens)\n between_tokens = nltk.word_tokenize(between)\n e2_left_index = e1_right_index + len(between_tokens)\n e2_tokens = nltk.word_tokenize(e2_phrase)\n e2_right_index = e2_left_index + len(e2_tokens)\n e2_right_tokens = nltk.word_tokenize(e2_right)\n\n all_tokens = e1_left_sen_tokens + e1_tokens + between_tokens + e2_tokens + e2_right_tokens\n\n return sent_id, e1_left_index, e1_right_index - 1, e2_left_index, e2_right_index - 1, all_tokens\n\n\ndef rewrite_semEval2010_task8(infolder='data/', outfolder='support', label_file='support/relation2id.txt'):\n \"\"\" Rewrite SemEval2010 dataset. Each line is\n label_index, index, index, index, index, sentence.\n\n Also output the sentence to another file to pretrain word embedding. Each line contains a sentence.\n This file contains all the sentences in both training and testing.\n\n Args:\n infolder: data folder\n train: training data or testing data\n\n Returns:\n\n \"\"\"\n\n label_to_index = read_relation2id(label_file)\n\n corpus = []\n\n print('Processing training data')\n filepath = os.path.join(infolder, 'SemEval2010_task8_training', 'TRAIN_FILE.TXT')\n output = []\n with open(filepath, 'r') as f:\n for _ in tqdm(range(8000)):\n sentence_line = f.readline()\n sent_id, e1_left_index, e1_right_index, e2_left_index, e2_right_index, all_tokens = \\\n process_sentence_line(sentence_line)\n # lower all tokens\n all_tokens = [token.lower() for token in all_tokens]\n\n label = f.readline()[:-1] # remove \\n\n label_index = label_to_index[label]\n\n label_index = str(label_index)\n e1_left_index = str(e1_left_index)\n e1_right_index = str(e1_right_index)\n e2_left_index = str(e2_left_index)\n e2_right_index = str(e2_right_index)\n all_tokens = \" \".join(all_tokens)\n\n corpus.append(all_tokens)\n\n f.readline() # comments\n f.readline() # empty line\n\n output.append(\" \".join([sent_id, label_index, e1_left_index, e1_right_index, e2_left_index,\n e2_right_index, all_tokens]))\n\n train, val = train_test_split(output, test_size=0.1, random_state=1)\n with open(os.path.join(outfolder, 'train.txt'), 'w') as f:\n f.write(\"\\n\".join(train))\n f.write(\"\\n\")\n with open(os.path.join(outfolder, 'val.txt'), 'w') as f:\n f.write(\"\\n\".join(val))\n f.write(\"\\n\")\n\n print('Processing testing data')\n filepath = os.path.join(infolder, 'SemEval2010_task8_testing', 'TEST_FILE.txt')\n output = []\n with open(filepath, 'r') as f:\n for _ in tqdm(range(2717)):\n sentence_line = f.readline()\n sent_id, e1_left_index, e1_right_index, e2_left_index, e2_right_index, all_tokens = \\\n process_sentence_line(sentence_line)\n # lower all tokens\n all_tokens = [token.lower() for token in all_tokens]\n\n label_index = -1\n\n label_index = str(label_index)\n e1_left_index = str(e1_left_index)\n e1_right_index = str(e1_right_index)\n e2_left_index = str(e2_left_index)\n e2_right_index = str(e2_right_index)\n all_tokens = \" \".join(all_tokens)\n\n corpus.append(all_tokens)\n\n output.append(\" \".join([sent_id, label_index, e1_left_index, e1_right_index, e2_left_index,\n e2_right_index, all_tokens]))\n\n output_file = os.path.join(outfolder, 'test.txt')\n with open(output_file, 'w') as f:\n f.write(\"\\n\".join(output))\n f.write(\"\\n\")\n\n with open(os.path.join(outfolder, 'corpus.txt'), 'w') as f:\n f.write(\"\\n\".join(corpus))\n f.write(\"\\n\")\n\n\nif __name__ == '__main__':\n rewrite_semEval2010_task8()\n\n embedding_size = 50\n\n os.makedirs('support/train/npy', exist_ok=True)\n os.makedirs('support/val/npy', exist_ok=True)\n os.makedirs('support/test/npy', exist_ok=True)\n\n data = SEMLoad('support/', data_type='train', embedding_size=embedding_size)\n data.save()\n data = SEMLoad('support/', data_type='val', embedding_size=embedding_size)\n data.save()\n data = SEMLoad('support/', data_type='test', embedding_size=embedding_size)\n data.save()\n","sub_path":"hw2/preprocess_data.py","file_name":"preprocess_data.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"200132003","text":"# -*- coding: utf-8 -*-\nfrom odoo import api, fields, models, tools, _, SUPERUSER_ID\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError, AccessError, ValidationError\n\nclass DnkBomsTemp(models.Model):\n _name = 'dnk.mrp.bom'\n _rec_name = 'name'\n\n @api.model\n def create(self, vals):\n print (vals)\n return super(DnkBomsTemp, self).create(vals)\n\n\n @api.multi\n def dnk_get_name(self):\n for rec in self:\n rec.name = \"[MXN $\"+str(rec.dnk_bom_cost)+ \"] \" + rec.dnk_bom_id.code\n\n\n dnk_product_id = fields.Many2one('product.product', '- Product', ondelete='cascade')\n dnk_product_tmpl_id = fields.Many2one('product.template', '- Product Template')\n dnk_bom_id = fields.Many2one('mrp.bom')\n name = fields.Char(compute='dnk_get_name')\n dnk_bom_cost = fields.Float(string=\"- Bom Cost\", digits=dp.get_precision('Product Price'), groups=\"base.group_user\")\n #dnk_bom_ids = fields.One2many('mrp.bom', 'product_id', string='- Bill Of Materials',default=lambda self: self.env['dnk.product.costs']._get_dnk_bom_ids(), ondelete='cascade')\n #dnk_bom_lines_ids = fields.One2many('mrp.bom.line', related='dnk_bom_ids.bom_line_ids')\n\n #dnk_tmpl_bom_ids = fields.One2many('mrp.bom', 'product_tmpl_id', string='- Bill Of Materials', default=lambda self: self.env['dnk.product.costs']._get_dnk_tmpl_bom_ids(), ondelete='cascade')\n #dnk_tmpl_bom_ids = fields.One2many('mrp.bom', related='dnk_product_tmpl_id.bom_ids')\n #dnk_tmpl_bom_lines_ids = fields.One2many('mrp.bom.line', related='dnk_tmpl_bom_ids.bom_line_ids')\n\nclass DnkProductCosts(models.Model):\n _name = 'dnk.product.costs'\n _rec_name = 'dnk_name'\n\n #@api.multi\n #def get_lines(self, boms):\n # product_lines = []\n # for bom in boms:\n # products = bom.product_id\n # if not products:\n # products = bom.product_tmpl_id.product_variant_ids\n # for product in products:\n # attributes = []\n # for value in product.attribute_value_ids:\n # attributes += [(value.attribute_id.name, value.name)]\n # result, result2 = bom.explode(product, 1)\n # product_line = {'bom': bom, 'name': product.name, 'lines': [], 'total': 0.0,\n # 'currency': self.env.user.company_id.currency_id,\n # 'product_uom_qty': bom.product_qty,\n # 'product_uom': bom.product_uom_id,\n # 'attributes': attributes}\n # total = 0.0\n # for bom_line, line_data in result2:\n # price_uom = bom_line.product_id.uom_id._compute_price(bom_line.product_id.standard_price, bom_line.product_uom_id)\n # line = {\n # 'product_id': bom_line.product_id,\n # 'product_uom_qty': line_data['qty'], #line_data needed for phantom bom explosion\n # 'product_uom': bom_line.product_uom_id,\n # 'price_unit': price_uom,\n # 'total_price': price_uom * line_data['qty'],\n # }\n # total += line['total_price']\n # product_line['lines'] += [line]\n # product_line['total'] = total\n # product_lines += [product_line]\n # return product_lines\n\n #@api.model\n #def dnk_get_report_values(self):\n # for rec in self:\n # boms = self.env['mrp.bom'].browse(docids)\n # res = self.get_lines(boms)\n # return {'lines': res}\n\n @api.model\n def _get_dnk_product_id(self):\n if 'active_model' in self._context and self._context['active_model'] == 'product.product':\n return self._context['active_id']\n @api.model\n def _get_dnk_product_tmpl_id(self):\n if 'active_model' in self._context and self._context['active_model'] == 'product.template':\n return self._context['active_id']\n\n @api.multi\n @api.onchange(\"dnk_mrp_product_tmpl_bom_cost\", \"dnk_mrp_product_bom_cost\")\n def change_material_cost(self):\n #print (\"YA entre a change_material_cost\")\n #print (self._fields)\n for rec in self:\n if len(rec.dnk_mrp_product_tmpl_bom_cost) == 1:\n print (rec.dnk_mrp_product_tmpl_bom_cost.dnk_bom_cost)\n self.dnk_cost_mp = rec.dnk_mrp_product_tmpl_bom_cost.dnk_bom_cost\n if len(rec.dnk_mrp_product_bom_cost) == 1:\n self.dnk_cost_mp = rec.dnk_mrp_product_bom_cost.dnk_bom_cost\n\n @api.model\n def get_dnk_product_tmpl_cost_id(self):\n dnk_bom_cost = []\n print (\"ENTRO AQUI en el de template??\")\n if 'active_model' in self._context and self._context['active_model'] == 'product.template':\n boms = self.env['product.template'].search([('id', '=', self._context['active_id'])]).bom_ids\n for bom in boms:\n print (bom.id)\n total_price = 0\n lines = self.env['mrp.bom.line'].search([('bom_id', '=', bom.id)])\n for bom_line in lines:\n price_uom = bom_line.product_id.uom_id._compute_price(bom_line.product_id.standard_price, bom_line.product_uom_id)\n total_price = total_price + (price_uom * bom_line.product_qty)\n #print ('total_price %s ', total_price)\n self.env.cr.execute(\"DELETE FROM dnk_mrp_bom WHERE dnk_product_tmpl_id = %s\" % self._context['active_id'])\n dnk_bom_cost = self.env['dnk.mrp.bom'].create(\n {'dnk_product_tmpl_id': self._context['active_id'],\n 'dnk_bom_id': bom.id,\n 'name':bom.code,\n 'dnk_bom_cost': total_price})\n print (dnk_bom_cost.id)\n dnk_bom_cost.id\n return dnk_bom_cost\n\n @api.model\n def get_dnk_product_cost_id(self):\n dnk_bom_cost = []\n print (\"ENTRO AQUI en el product product??\")\n print (self._context)\n if 'active_model' in self._context and self._context['active_model'] == 'product.product':\n boms = self.env['product.product'].search([('id', '=', self._context['active_id'])]).bom_ids\n for bom in boms:\n print (bom.id)\n total_price = 0\n lines = self.env['mrp.bom.line'].search([('bom_id', '=', bom.id)])\n for bom_line in lines:\n price_uom = bom_line.product_id.uom_id._compute_price(bom_line.product_id.standard_price, bom_line.product_uom_id)\n total_price = total_price + (price_uom * bom_line.product_qty)\n #print ('total_price %s ', total_price)\n self.env.cr.execute(\"DELETE FROM dnk_mrp_bom WHERE dnk_product_id = %s\" % self._context['active_id'])\n dnk_bom_cost = self.env['dnk.mrp.bom'].create(\n {'dnk_product_id': self._context['active_id'],\n 'dnk_bom_id': bom.id,\n 'name':bom.code,\n 'dnk_bom_cost': total_price})\n print (dnk_bom_cost.id)\n dnk_bom_cost.id\n return dnk_bom_cost\n\n #@api.model\n #def _get_dnk_bom_ids(self):\n # if 'active_model' in self._context and self._context['active_model'] == 'product.product':\n # return self.env['product.product'].search([('id', '=', self._context['active_id'])]).bom_ids\n\n\n #@api.model\n #def _get_dnk_tmpl_bom_ids(self):\n # if 'active_model' in self._context and self._context['active_model'] == 'product.template':\n # return self.env['product.template'].search([('id', '=', self._context['active_id'])]).bom_ids\n\n @api.model\n def _get_total_cost(self):\n self.dnk_cost_total = self.dnk_cost_mp+self.dnk_cost_mo+self.dnk_cost_gif\n\n @api.model\n def _update_product_cost(self):\n productos = self.env['product.product']\n dnk_product_cost = dnk_costos.search([('id', '=', self._origin.id)], limit =1)\n\n @api.model\n def create(self, vals):\n if 'active_model' in self._context:\n NombreMod = self._context['active_model']\n id = self._context['active_id']\n else:\n if vals['dnk_product_tmpl_id']:\n NombreMod = 'product.template'\n id = vals['dnk_product_tmpl_id']\n else:\n NombreMod = 'product.product'\n id = vals['dnk_product_id']\n vals['dnk_name'] = self.env[NombreMod].search([('id', '=', id)]).default_code\n Productos = self.env[NombreMod]\n producto = Productos.browse(id)\n producto.dnk_cost_mp = vals['dnk_cost_mp']\n producto.dnk_cost_mo = vals['dnk_cost_mo']\n producto.dnk_cost_gif = vals['dnk_cost_gif']\n producto.dnk_costs_currency_id = 3 # sustituir esto\n if NombreMod == 'product.template':\n vals['dnk_usd_cost_fixed_rate'] = producto.company_id.dnk_usd_cost_fixed_rate\n vals['dnk_product_tmpl_id'] = id\n vals['dnk_tmpl_bom_ids'] = producto.bom_ids\n else :\n vals['dnk_usd_cost_fixed_rate'] = producto.product_tmpl_id.company_id.dnk_usd_cost_fixed_rate\n vals['dnk_product_id'] = id\n vals['dnk_bom_ids'] = producto.bom_ids\n print (\"ESTOY EN CREATE\")\n print(vals['dnk_bom_ids'])\n vals['dnk_cost_total'] = vals['dnk_cost_mp']+vals['dnk_cost_mo']+vals['dnk_cost_gif']\n return super(DnkProductCosts, self).create(vals)\n\n @api.multi\n def dnk_change_costs(self):\n return {'type': 'ir.actions.act_window_close'}\n\n dnk_name = fields.Char(string='- Default Code', index=True, readonly=True, default=lambda self: _('New'))\n dnk_company_id = fields.Many2one('res.company',string='- Company', default=lambda self: self.env['res.company']._company_default_get(), readonly=True, track_visibility='onchange')\n dnk_active = fields.Boolean('- Activo', default=True)\n\n dnk_cost_std = fields.Float(string=\"- Standard Cost\", digits=dp.get_precision('Product Price'), groups=\"base.group_user\")\n dnk_cost_mp = fields.Float(string=\"- Material Cost\", digits=dp.get_precision('Product Price'), groups=\"base.group_user\")\n dnk_cost_mo = fields.Float(string=\"- Labor Cost\", digits=dp.get_precision('Product Price'), groups=\"base.group_user\")\n dnk_cost_gif = fields.Float(string=\"- GIF Cost\", digits=dp.get_precision('Product Price'), groups=\"base.group_user\")\n dnk_cost_total = fields.Float(string=\"- Total Cost\", digits=dp.get_precision('Product Price'), readonly=True, compute=\"_get_total_cost\", store=True, groups=\"base.group_user\")\n\n dnk_currency_rate = fields.Many2one('res.currency', string='- Cost Currency', default=3, readonly=True)\n dnk_usd_cost_fixed_rate = fields.Monetary(string=\"- USD Cost Fixed Rate\", currency_field='dnk_currency_rate', readonly=True, help=\"USD Cost Fixed Rate to use on Margin.\")\n dnk_product_id = fields.Many2one('product.product', '- Product', ondelete='cascade', default=lambda self: self.env['dnk.product.costs']._get_dnk_product_id())\n dnk_product_tmpl_id = fields.Many2one('product.template', '- Product Template',default=lambda self: self.env['dnk.product.costs']._get_dnk_product_tmpl_id())\n #dnk_mrp_product_bom_cost = fields.Many2one('dnk.mrp.bom', default=lambda self: self.env['dnk.product.costs']._get_dnk_product_cost_id())\n #dnk_mrp_product_tmpl_bom_cost = fields.One2many('dnk.mrp.bom', default=lambda self: self.env['dnk.product.costs']._get_dnk_product_tmpl_cost_id())\n dnk_mrp_product_tmpl_bom_cost = fields.Many2one('dnk.mrp.bom', compute=\"get_dnk_product_tmpl_cost_id\", default=lambda self: self.env['dnk.product.costs'].get_dnk_product_tmpl_cost_id())\n dnk_mrp_product_bom_cost = fields.Many2one('dnk.mrp.bom', compute=\"get_dnk_product_cost_id\", default=lambda self: self.env['dnk.product.costs'].get_dnk_product_cost_id())\n dnk_bom_ids = fields.One2many('mrp.bom', related='dnk_product_id.bom_ids')\n\n #dnk_bom_ids = fields.One2many('mrp.bom', 'product_id', string='- Bill Of Materials',default=lambda self: self.env['dnk.product.costs']._get_dnk_bom_ids(), ondelete='cascade')\n #dnk_bom_lines_ids = fields.One2many('mrp.bom.line', related='dnk_bom_ids.bom_line_ids')\n\n #dnk_tmpl_bom_ids = fields.One2many('mrp.bom', 'product_tmpl_id', string='- Bill Of Materials', default=lambda self: self.env['dnk.product.costs']._get_dnk_tmpl_bom_ids(), ondelete='cascade')\n #dnk_tmpl_bom_ids = fields.One2many('mrp.bom', related='dnk_product_tmpl_id.bom_ids')\n #dnk_tmpl_bom_lines_ids = fields.One2many('mrp.bom.line', related='dnk_tmpl_bom_ids.bom_line_ids')\n","sub_path":"denker/dnk_sale_costs/models/dnk_product_costs.py","file_name":"dnk_product_costs.py","file_ext":"py","file_size_in_byte":12732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"342050584","text":"class Damage:\n def __init__(self, pokemon, move, effectiveness=None):\n self.pokemon = pokemon\n\n if move in [\"Tackle\", \"Ember\", \"Vine Whip\", \"Water Gun\", \"Thunder Shock\", \"Rock Throw\", \"Confusion\",\n \"Mach Punch\", \"Wing Attack\", \"Powder Snow\"]:\n self.level = 2\n\n elif move in [\"Body Slam\", \"Flamethrower\", \"Razor Leaf\", \"Hydro Pump\", \"Thunderbolt\", \"Earthquake\", \"Psychic\",\n \"High Jump Kick\", \"Fly\", \"Ice Beam\"]:\n self.level = 4\n\n if effectiveness is not None:\n self.level *= effectiveness.multiplier\n self.level = int(self.level)\n","sub_path":"src/statements/commands/damage.py","file_name":"damage.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"454470452","text":"############################ HANGMAN GAME #############################\n########### CRAFTED WITH LOVE AND PYTHON BY MrGEAR (CHIANG) ###########\n\nfrom termcolor import colored\nimport random\nimport urllib.request\nimport os\n\n\n# Call color scheme\nos.system('color')\n\n\nclass Player:\n \"\"\"\n Create Player Details\n \"\"\"\n\n def __init__(self, name):\n \"\"\"Inititation\"\"\"\n self.name = name\n self.lives = 5\n\n def detail(self):\n \"\"\"Show Player's Details\"\"\"\n return 'Player: {} has {} live(s) left'.format(self.name, self.lives)\n\n\nclass Word_factory:\n \"\"\"\n Create the collections of words (dict)\n \"\"\"\n\n def __init__(self, word_box):\n \"\"\"Inititation\"\"\"\n self.keys = [i for i in range(len(word_box))]\n self.values = list(map(lambda i: i.upper(), word_box))\n # Create a dictionary from a list of given words\n self.word_box = dict(zip(self.keys, self.values))\n\n def detail(self):\n \"\"\"Show All Words in a List\"\"\"\n return 'Word Box: {}'.format(\n self.word_box) # Call to see the word collection\n\n def chosen(self):\n \"\"\"Choose a word from a list\"\"\"\n self.chosen_word = self.word_box.get(\n random.randrange(len(self.keys))) # Random from a key\n return self.chosen_word\n\n\ndef interface(player, word):\n \"\"\"\n Create an Introductory Interface\n \"\"\"\n\n print('Welcome {}. You start with {} lives. Enjoy!'.format(\n player.name, player.lives))\n print('\\nThe word has {} letters'.format(len(word)))\n\n\ndef word_status(word, guessed):\n \"\"\"\n Create a word status\n \"\"\"\n\n check = []\n for i in word:\n if(i in guessed):\n check.append(i)\n else:\n check.append('__')\n return check\n\n\ndef chosen_difficulty(difficulty):\n \"\"\"\n Categories based on Difficulties\n \"\"\"\n\n def easy():\n word_box_1 = Word_factory(['ANT',\n 'CAT',\n 'BAT',\n 'RAT',\n 'BANANA',\n 'FIRE',\n 'APPLE',\n 'INTERNATIONAL',\n 'RHINO',\n 'CODE',\n 'TEST',\n 'QUICK']) # Example of Word List 1\n return word_box_1\n\n def impossible():\n word_site = \"http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain\"\n response = urllib.request.urlopen(word_site)\n long_txt = response.read().decode()\n # Example of Word List 2\n word_box_2 = Word_factory(long_txt.splitlines())\n return word_box_2\n\n if(difficulty == '1'):\n print('You have selected EASY')\n return easy()\n elif(difficulty == '2'):\n print('You have selected IMPOSSIBLE')\n return impossible()\n else:\n print('Wrong input!! We will choose IMPOSSIBLE for you!!')\n return impossible()\n\n\ndef play(player, word):\n \"\"\"\n Start the game\n \"\"\"\n\n guess = False\n word = list(word)\n player_guess = None\n guessed = [] # Collect guessed words from a player\n\n while(guess != True and player.lives > 0):\n # Print out word_status (ex. __ A __)\n list(map(lambda i: print(i, end=' '), word_status(word, guessed)))\n player_guess = input('Your guess: ').upper() # Capitalise an input\n guessed.append(player_guess) # Collect an input to a list 'guessed'\n if(player_guess == ''.join(word) or word_status(word, guessed) == word): # Check winning conditions\n if(word_status(word, guessed) == word):\n list(map(lambda i: print(i, end=' '), word_status(word, guessed)))\n else:\n list(map(lambda i: print(i, end=' '), word))\n guess = True\n elif(player_guess in word): # Giving a hint\n print('{} is in the word!!'.format(player_guess))\n else:\n # Incorrect condition\n print('Sorry, that\\'s incorrect. Please try again.')\n player.lives -= 1\n print(player.detail())\n\n return guess\n\n\ndef result(guess, word):\n \"\"\"\n Show the result\n \"\"\"\n\n if guess:\n print(colored('\\nYOU WON!! THE WORD IS \\\"{}\\\"'.format(word), 'green'))\n else:\n print(colored('\\nYOU DIED... THE WORD IS \\\"{}\\\"'.format(word), 'red'))\n\n\ndef main():\n \"\"\"\n Call All Functions to Play the Game\n \"\"\"\n\n ## Values Declarations ##\n print('########### WELCOME TO HANGMAN ###########')\n print('\\t---------Rules---------\\n1) Type only one character (case-insensitive)\\n2) Type a whole word, when you are certian :) ')\n player_1 = Player(input(\"Please enter your name: \"))\n player_1_difficulty = chosen_difficulty(\n input('Please choose a difficulty, 1 for Easy, 2 for Impossible (1 or 2): '))\n print('##########################################')\n\n ## LET'S PLAY THE GAME ##\n chosen_word = player_1_difficulty.chosen() # Randomly use a word from a dict\n interface(player_1, chosen_word) # Inititate an interface\n res = play(player_1, chosen_word) # Return the game's result (True/ False)\n result(res, chosen_word) # Show the result from the game\n\n\n######################## CALL THE MAIN FUNCTION ########################\nif __name__ == '__main__':\n main()\n","sub_path":"Hangman/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"224351697","text":"import ROOT as r\nimport os, sys, argparse, math, json\nimport warnings as wr\nfrom array import array\nfrom copy import deepcopy\nfrom multiprocessing import Pool\nimport CombineHarvester.CombineTools.plotting as plot\nimport CombineHarvester.CombineTools.combine.rounding as rounding\n\nsys.path.append('{cmsswpath}/src/CMGTools/TTHAnalysis/python/plotter/tw-run2/differential/'.format(cmsswpath = os.environ['CMSSW_BASE']))\n#import varList as vl\n\nr.PyConfig.IgnoreCommandLineOptions = True\nr.TH1.AddDirectory(0)\n\ncomm1 = \"combineTool.py -M Impacts -d {incard} --doInitialFit --robustFit 1 {ncores} {asimov} {extra} -m 1 -n {prefix} --out {outdir} --X-rtd MINIMIZER_analytic --X-rtd MINIMIZER_MaxCalls=5000000 --cminDefaultMinimizerStrategy 0\" # --cminDefaultMinimizerType Minuit\ncomm2 = \"combineTool.py -M Impacts -d {incard} --robustFit 1 --doFits {ncores} {asimov} {extra} -m 1 -n {prefix} --X-rtd MINIMIZER_analytic --X-rtd MINIMIZER_MaxCalls=5000000 --cminDefaultMinimizerStrategy 0\" # --cminDefaultMinimizerType Minuit\ncomm3 = \"combineTool.py -M Impacts -d {incard} -o impacts{prefix}.json {ncores} {asimov} {extra} -m 1 -n {prefix} --robustFit 1 --X-rtd MINIMIZER_analytic --X-rtd MINIMIZER_MaxCalls=5000000 --cminDefaultMinimizerStrategy 0\" # --cminDefaultMinimizerType Minuit\ncomm4 = \"plotImpacts.py -i impacts{prefix}.json -o impacts{prefix} {bl}\"\n\n\ndef confirm(message = \"Do you wish to continue?\"):\n \"\"\"\n Ask user to enter y(es) or n(o) (case-insensitive).\n :return: True if the answer is Y.\n :rtype: bool\n \"\"\"\n answer = \"\"\n while answer not in [\"y\", \"n\", \"yes\", \"no\"]:\n answer = raw_input(message + \" [Y/N]\\n\").lower()\n return answer[0] == \"y\"\n\n\ndef checkNfits(tsk):\n thepath, thename = tsk\n failed = False\n\n thef = r.TFile(thepath + \"/\" + thename, \"READ\")\n if thef.limit.GetEntries() < 3:\n failed = True\n thef.Close(); del thef\n return (failed, thename)\n\n\ndef reviewThePreviousStepsFiles(thefolder, nth, verbose):\n thelist = os.listdir(thefolder)\n thetasks = []\n theres = []\n for el in thelist:\n if \"higgsCombine_\" in el:\n thetasks.append( (thefolder, el) )\n\n if nth > 1:\n pool = Pool(nth)\n theres = pool.map(checkNfits, thetasks)\n pool.close()\n pool.join()\n else:\n for tsk in thetasks:\n theres.append(checkNfits(tsk))\n\n if any(theres[:][0]):\n print(\"\\n#######################################\\nERROR!!\\n#######################################\\n\\nOne or more fits to calculate the impacts have failed. In particular, the following parameters (either nuisances or POI) have one or more failed fits.\")\n for el in theres:\n if el[0]: print(\"\\t- \" + \"_\".join(el[1].replace(\"higgsCombine_\", \"\").replace(\"paramFit_\", \"\").replace(\"initialFit_\", \"\").replace(\".MultiDimFit.mH1.root\", \"\").split(\"_\")[2:]))\n\n print(\"\")\n if not confirm(\"Do you want to, in any case, create the impacts? Please, take into account that the nuisance or POI that has one or more failed fits will NOT be present in the impacts' plot.\"):\n sys.exit()\n elif verbose:\n print(\"\\t- No failed fits!\")\n\n return\n\n\n\n\ndef makeImpacts(task):\n inpath, year, region, ncores, pretend, verbose, extra, doobs, doBlind = task\n\n print('\\n> Creating impacts for region(s)', region, 'from year', year, '\\n')\n \n impactsoutpath = inpath + \"/\" + iY + \"/\" + (\"Obs\" * doObs) + \"Impacts_\" + region\n\n if \",\" not in region:\n physicsModel = 'text2workspace.py -m 125 {infile} -o {outfile}'.format(infile = inpath + \"/\" + iY + \"/{r}/cuts-tw-{r}.txt\".format(r = region),\n outfile = inpath + \"/\" + iY + \"/{r}/cuts-tw-{r}_ws.root\".format(r = region),)\n if verbose:\n print(\"Text2Workspace command:\", physicsModel, \"\\n\")\n\n if not pretend:\n if os.path.isfile(inpath + \"/\" + iY + \"/{r}/cuts-tw-{r}_ws.root\".format(r = region)):\n if verbose:\n print(\" - Erasing old workspace...\")\n os.system(\"rm \" + inpath + \"/\" + iY + \"/{r}/cuts-tw-{r}_ws.root\".format(r = region))\n outstat = os.system(physicsModel)\n if outstat:\n raise RuntimeError(\"FATAL: text2workspace.py failed to execute for year {y} and regions {r}.\".format(y = year, r = region))\n\n firstcomm = comm1.format(y = year,\n ncores = (\"--parallel \" + str(ncores)) if ncores else \"\",\n asimov = \"\" if doobs else \"-t -1 --setParameters r=1\",\n incard = \"../combcard_{r}.root\".format(r = region.replace(\",\", \"\")) if \",\" in region else \"../{r}/cuts-tw-{r}_ws.root\".format(r = region),\n outdir = \"./\",\n extra = extra,\n prefix = year + \"_\" + region.replace(\",\", \"\"),\n )\n\n if verbose:\n print(\"\\nFirst command:\", firstcomm, \"\\n\")\n\n if not pretend:\n outstat = os.system(\"cd \" + impactsoutpath + \"; \" + firstcomm + \"; cd -\")\n if outstat:\n raise RuntimeError(\"FATAL: first command failed to execute for region {r} of year {y}.\".format(v = region,\n y = year))\n\n secondcomm = comm2.format(y = year,\n ncores = (\"--parallel \" + str(ncores)) if ncores else \"\",\n asimov = \"\" if doobs else \"-t -1 --setParameters r=1\",\n incard = \"../combcard_{r}.root\".format(r = region.replace(\",\", \"\")) if \",\" in region else \"../{r}/cuts-tw-{r}_ws.root\".format(r = region),\n outdir = \"./\",\n extra = extra,\n prefix = year + \"_\" + region.replace(\",\", \"\"),\n )\n\n if verbose:\n print(\"\\nSecond command:\", secondcomm, \"\\n\")\n \n if not pretend:\n outstat = os.system(\"cd \" + impactsoutpath + \"; \" + secondcomm + \"; cd -\")\n if outstat:\n raise RuntimeError(\"FATAL: second command failed to execute for region {r} of year {y}.\".format(v = region,\n y = year))\n \n thirdcomm = comm3.format(y = year,\n ncores = (\"--parallel \" + str(ncores)) if ncores else \"\",\n asimov = \"\" if doobs else \"-t -1 --setParameters r=1\",\n incard = \"../combcard_{r}.root\".format(r = region.replace(\",\", \"\")) if \",\" in region else \"../{r}/cuts-tw-{r}_ws.root\".format(r = region),\n outdir = \"./\",\n extra = extra,\n prefix = year + \"_\" + region.replace(\",\", \"\"),\n )\n\n if verbose and not pretend:\n print(\"\\nChecking whether any fit might have failed.\")\n\n if not pretend:\n reviewThePreviousStepsFiles(impactsoutpath, ncores if ncores else 1, verbose)\n\n\n if verbose:\n print(\"\\nThird command:\", thirdcomm, \"\\n\")\n \n if not pretend:\n outstat = os.system(\"cd \" + impactsoutpath + \"; \" + thirdcomm + \"; cd -\")\n if outstat:\n raise RuntimeError(\"FATAL: third command failed to execute for region {r} of year {y}.\".format(v = region,\n y = year))\n\n fourthcomm = comm4.format(y = year,\n ncores = (\"--parallel \" + str(ncores)) if ncores else \"\",\n asimov = \"\" if doobs else \"-t -1 --setParameters r=1\",\n incard = \"../combcard_{r}.root\".format(r = region.replace(\",\", \"\")) if \",\" in region else \"../{r}/cuts-tw-{r}_ws.root\".format(r = region),\n outdir = \"./\",\n bl = \"--blind\" if doBlind else \"\",\n prefix = year + \"_\" + region.replace(\",\", \"\"),\n )\n\n if verbose:\n print(\"Fourth command:\", fourthcomm, \"\\n\")\n\n if not pretend:\n outstat = os.system(\"cd \" + impactsoutpath + \"; \" + fourthcomm + \"; cd -\")\n if outstat:\n raise RuntimeError(\"FATAL: fourth command failed to execute for region {r} of year {y}.\".format(v = region,\n y = year))\n \n \n print('\\n> Region(s)', region, \"' impacts produced.\\n\")\n return\n\n\n\nif __name__ == '__main__':\n# vl.SetUpWarnings()\n r.gROOT.SetBatch(True)\n print(\"===== Fitting procedure with some uncertainty profiling\\n\")\n parser = argparse.ArgumentParser(usage = \"python nanoAOD_checker.py [options]\", description = \"Checker tool for the outputs of nanoAOD production (NOT postprocessing)\", formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--inpath', '-i', metavar = 'inpath', dest = \"inpath\", required = False, default = \"./temp/differential/\")\n parser.add_argument('--year', '-y', metavar = 'year', dest = \"year\", required = False, default = \"all\")\n parser.add_argument('--region', '-r', metavar = 'region', dest = \"region\", required = False, default = \"1j1t\")\n parser.add_argument('--extraArgs', '-e', metavar = 'extra', dest = \"extra\", required = False, default = \"\")\n parser.add_argument('--nthreads', '-j', metavar = 'nthreads', dest = \"nthreads\", required = False, default = 0, type = int)\n parser.add_argument('--pretend', '-p', action = \"store_true\", dest = \"pretend\", required = False, default = False)\n parser.add_argument('--verbose', '-V', action = \"store_true\", dest = \"verbose\", required = False, default = False)\n parser.add_argument('--doObserved', '-O', action = \"store_true\", dest = \"doobs\", required = False, default = False)\n parser.add_argument('--blindSignalStrength','-b',action=\"store_true\",dest=\"blindmu\", required = False, default = False)\n\n\n args = parser.parse_args()\n year = args.year\n nthreads = args.nthreads\n pretend = args.pretend\n inpath = args.inpath\n verbose = args.verbose\n region = args.region\n extra = args.extra\n doObs = args.doobs\n doBlind = args.blindmu\n\n\n tasks = []\n theyears = []\n presentyears = next(os.walk(inpath))[1]\n\n if \"2016\" in presentyears:\n theyears.append(\"2016\")\n if \"2017\" in presentyears:\n theyears.append(\"2017\")\n if \"2018\" in presentyears:\n theyears.append(\"2018\")\n if \"run2\" in presentyears:\n theyears.append(\"run2\")\n\n if year.lower() != \"all\" and year in presentyears:\n theyears = [ year ]\n elif year.lower() != \"all\":\n raise RuntimeError(\"FATAL: the year requested is not in the provided input folder.\")\n\n if region.lower() == \"all\":\n raise RuntimeError(\"FATAL: you must provide a region, or various of them!\")\n \n for iY in theyears:\n if not os.path.isdir(inpath + \"/\" + iY + \"/\" + \"/\" + (\"Obs\" * doObs) + \"Impacts_\" + region):\n os.system(\"mkdir -p \" + inpath + \"/\" + iY + \"/\" + (\"Obs\" * doObs) + \"Impacts_\" + region)\n tasks.append( (inpath, iY, region, nthreads, pretend, verbose, extra, doObs, doBlind) )\n\n #print tasks\n for task in tasks:\n print(\"\\nProcessing \" + str(task) + \"\\n\")\n makeImpacts(task)\n","sub_path":"TTHAnalysis/python/plotter/tw-run3/getInclusiveImpacts.py","file_name":"getInclusiveImpacts.py","file_ext":"py","file_size_in_byte":11605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"632493090","text":"# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import TYPE_CHECKING, Any\n\nimport torch\nimport torch.optim\n\nif TYPE_CHECKING:\n from torch.optim.optimizer import _params_t\nelse:\n _params_t = Any\n\n\nclass DAdaptAdam(torch.optim.Optimizer):\n \"\"\"\n Implements Adam with D-adaptation automatic step-sizes. Leave LR set to 1\n unless you encounter instability.\n\n Args:\n params (iterable): Iterable of parameters to optimize or dicts defining\n parameter groups.\n lr (float): Learning rate adjustment parameter. Increases or decreases\n the D-adapted learning rate.\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n momentum (float): Momentum value in the range [0,1) (default: 0.9).\n eps (float): Term added to the denominator outside of the root\n operation to improve numerical stability. (default: 0).\n weight_decay (float): Weight decay, i.e. a L2 penalty (default: 0).\n log_every (int): Log using print every k steps, default 0 (no logging).\n decouple (bool): Use AdamW style decoupled weight decay\n d0 (float): Initial D estimate for D-adaptation (default 1e-6). Rarely\n needs changing.\n growth_rate (float): prevent the D estimate from growing faster than\n this multiplicative rate. Default is inf, for unrestricted. Values\n like 1.02 give a kind of learning rate warmup effect.\n \"\"\"\n\n def __init__(self, params, lr=1.0,\n betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, log_every=0,\n decouple=False,\n d0=1e-6, growth_rate=float('inf')):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\n \"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\n \"Invalid beta parameter at index 1: {}\".format(betas[1]))\n\n if decouple:\n print(\"Using decoupled weight decay\")\n\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay,\n d=d0,\n k=0,\n gsq_weighted=0.0,\n log_every=log_every,\n growth_rate=growth_rate,\n decouple=decouple)\n\n super().__init__(params, defaults)\n\n @property\n def supports_memory_efficient_fp16(self):\n return False\n\n @property\n def supports_flat_params(self):\n return True\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n g_sq = 0.0\n sksq_weighted = 0.0\n sk_l1 = 0.0\n\n ngroups = len(self.param_groups)\n\n group = self.param_groups[0]\n gsq_weighted = group['gsq_weighted']\n d = group['d']\n lr = group['lr']\n dlr = d*lr\n\n growth_rate = group['growth_rate']\n decouple = group['decouple']\n log_every = group['log_every']\n\n beta1, beta2 = group['betas']\n\n for group in self.param_groups:\n decay = group['weight_decay']\n k = group['k']\n eps = group['eps']\n\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n\n # Apply weight decay (coupled variant)\n if decay != 0 and not decouple:\n grad.add_(p.data, alpha=decay)\n\n state = self.state[p]\n\n # State initialization\n if 'step' not in state:\n state['step'] = 0\n state['s'] = torch.zeros_like(p.data).detach()\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data).detach()\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data).detach()\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n\n # Adam EMA updates\n exp_avg.mul_(beta1).add_(grad, alpha=dlr*(1-beta1))\n exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1-beta2)\n\n denom = exp_avg_sq.sqrt().add_(eps)\n\n g_sq += (grad * grad).div_(denom).sum().item()\n\n s = state['s']\n s.mul_(beta2).add_(grad, alpha=dlr*(1-beta2))\n sksq_weighted += (s * s).div_(denom).sum().item()\n sk_l1 += s.abs().sum().item()\n\n ######\n\n gsq_weighted = beta2*gsq_weighted + g_sq*(dlr**2)*(1-beta2)\n d_hat = d\n\n if lr > 0.0:\n d_hat = (sksq_weighted/(1-beta2) - gsq_weighted)/sk_l1\n d = max(d, min(d_hat, d*growth_rate))\n\n if log_every > 0 and k % log_every == 0:\n print(f\"ng: {ngroups} lr: {lr} dlr: {dlr} d_hat: {d_hat}, d: {d}. \"\n f\"sksq_weighted={sksq_weighted:1.1e} sk_l1={sk_l1:1.1e} \"\n f\"gsq_weighted={gsq_weighted:1.1e}\")\n\n for group in self.param_groups:\n group['gsq_weighted'] = gsq_weighted\n group['d'] = d\n\n decay = group['weight_decay']\n k = group['k']\n eps = group['eps']\n\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n\n state = self.state[p]\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n\n state['step'] += 1\n\n denom = exp_avg_sq.sqrt().add_(eps)\n\n # Apply weight decay (decoupled variant)\n if decay != 0 and decouple:\n p.data.add_(p.data, alpha=-decay * dlr)\n\n # Take step\n p.data.addcdiv_(exp_avg, denom, value=-1)\n\n group['k'] = k + 1\n\n return loss\n","sub_path":"dadapt_adam.py","file_name":"dadapt_adam.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"21529575","text":"class cTree(object):\r\n def __init__(self,data = None):\r\n self._data = data\r\n self.children = []\r\n\r\n def travel(self,node=None,depth = 1):\r\n if node is None:\r\n node = self \r\n yield (node._data,depth)\r\n depth += 1 \r\n for child in node.children:\r\n yield from self.travel(child,depth)\r\n depth -= 1\r\n\r\nclass test_cTree(object):\r\n def __init__(self):\r\n self.root = cTree('html')\r\n head = cTree('head')\r\n a = cTree('a')\r\n b = cTree('b')\r\n head.children.append(a)\r\n head.children.append(b)\r\n body = cTree('body')\r\n x = cTree('x')\r\n m = cTree('m')\r\n x.children.append(m)\r\n body.children.append(x)\r\n self.root.children.append(head)\r\n self.root.children.append(body)\r\n \r\n\r\nt = cTree()\r\na = test_cTree()\r\n\r\nfor node,depth in a.root.travel():\r\n print(node,'depth:',depth)","sub_path":"PycharmProjects/Reptile/数据与算法/二叉树/ccTree.py","file_name":"ccTree.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404804393","text":"from functools import reduce\n\n\ndef xor_arr(arr):\n return reduce(lambda x, y: x ^ y, arr, 0)\n\n\ndef missing2nums(arr):\n arr_sum = sum(arr)\n sequence_sum = sum(range(1, len(arr)+3))\n missing_sum = sequence_sum-arr_sum\n pivot_val = int(missing_sum / 2)\n\n xor_lsubarr = xor_arr([el for el in arr if el < pivot_val])\n xor_rsubarr = xor_arr([el for el in arr if el > pivot_val])\n xor_left_seq = xor_arr(range(1, pivot_val+1))\n xor_right_seq = xor_arr(range(pivot_val+1, len(arr)+3))\n\n return [xor_left_seq ^ xor_lsubarr, xor_right_seq ^ xor_rsubarr]\n\n\nprint(missing2nums([1, 2, 3, 6]))\n","sub_path":"algo-practice/missing-2nums.py","file_name":"missing-2nums.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"14025604","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/motmot/flytrax/generate_fake_trx_file.py\n# Compiled at: 2009-04-14 12:30:53\nimport numpy, time, traxio\n(w, h) = (1600, 1200)\nframes = 100\nfname = 'fake'\nx = 30\ny = 40\n(roi_w, roi_h) = (40, 60)\nfor framenumber in range(frames):\n x += 2\n y += 1\n x0 = x - roi_w // 2\n y0 = y - roi_h // 2\n if framenumber == 0:\n a = numpy.zeros((h, w), dtype=numpy.uint8)\n tw = traxio.TraxDataWriter(fname, a)\n else:\n a = numpy.zeros((roi_h, roi_w), dtype=numpy.uint8)\n a[(x - x0, y - y0)] = 200\n tw.write_data(roi_img=a, posx=x, posy=y, orientation=0.0, windowx=x0, windowy=y0, timestamp=time.time(), area=0.0)","sub_path":"pycfiles/motmot.flytrax-0.5.8-py2.5/generate_fake_trx_file.py","file_name":"generate_fake_trx_file.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239066236","text":"import tambotapi\nimport configparser\nimport logging\nimport os\nimport datetime\n\n\n# Read configration.\ndef read_cfg(config):\n parser = configparser.ConfigParser()\n parser.read(config)\n api_token = parser.get('creds', 'token')\n bot_id = api_token.split(':')[0]\n sudo_username = parser.get('creds', 'sudo_username')\n channel_username = parser.get('creds', 'channel_username')\n return api_token, bot_id, sudo_username, channel_username\n\n\nconfig_bot = read_cfg('config.ini')\n\napi_token = config_bot[0]\nbot_id = config_bot[1]\nsudo_username = config_bot[2]\nchannel_username = config_bot[3]\n\nbot = tambotapi.TBot(api_token)\n\n# know_user_info = []\n# know_user_id = []\n# creators_ids = []\n# admins_ids = []\n\n\n# Logger\nlogger = tambotapi.logger\nlogger.setLevel(logging.DEBUG)\n# format log\nlog_format = logging.Formatter(\n '[%(asctime)s] %(thread)d {%(pathname)s:%(lineno)d}\\n%(levelname)s - %(message)s\\n\\n', '%Y.%m.%d-%H.%M.%S')\n# create log folder if not exists.\nif not os.path.exists(\"logs\"):\n os.mkdir(\"logs\")\n# format log file name.\nformat_handler = logging.FileHandler(\n \"logs/\" + datetime.datetime.now().strftime(\"%Y.%m.%d-%H.%M.%S\") + \".log\")\n# set log_format and add handler.\nformat_handler.setFormatter(log_format)\nlogger.addHandler(format_handler)","sub_path":"plugins/botcfg.py","file_name":"botcfg.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"583649894","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 14 14:12:02 2015\n\n@author: rbanderson\n\nThis function allows spectra to be restricted to a specified composition range for a given element. \nOptionally, a file can be provided specifying individual spectra that should be removed, regardless of composition\n\nInputs:\nspectra = float array of spectra\nspect_index = int array of spectrum indices for each target\ncomps = float array of target compositions\ncompindex = the index of comps that corresponds to the element of interest\nmincomp = the lower limit of compositions to keep\nmaxcomp = the upper limit of compositions to keep\nremovelist = string specifying the path to an optional .csv file that lists individual spectra to remove.\nFile should have two columns. The first column should have target names, the second column should have the index of the spectrum to remove.\nSo, to remove the first and third spectrum of AGV2, the file would look like:\nAGV2,1\nAGV2,3\n\nkeepfile = string specifying the path to an optional .csv file that lists the spectra to keep (ALL others are removed)\nFile should have two columns. The first column should have the index of the spectrum to keep,\n(NOTE: For this file, the index should be the index into the full array of spectra, starting at 1, not the 1-5 index for each target)\nthe second column should have the target names.\n\n\n\nOutputs:\nspectra_keep = array of spectra that satisfy the constraints on composition and are not listed in the file\nnames_keep = names of spectra that satisfy the constraints on composition and are not listed in the file\nspect_index_keep = indices of spectra that satisfy the constraints on composition and are not listed in the file\ncomps_keep = = compositions of spectra that satisfy the constraints on composition and are not listed in the file\n\n\"\"\"\nimport numpy\nimport csv\ndef choose_spectra(spectra,spect_index,names,comps,compindex,mincomp=0,maxcomp=100,removefile=None,keepfile=None,which_removed=None,linewvl=None,linestrength=None,wvl=None,clustermask=None):\n\n \n \n #optionally, remove spectra listed in an external file\n if removefile != None:\n #read the list of sample names and spectrum indices from the file\n f=open(removefile,'r')\n data=list(zip(*csv.reader(f)))\n removenames=numpy.array(data[0],dtype='str')\n removeinds=numpy.array(data[1],dtype='int')\n #define an array to hold the indices for each row in the file \n index=numpy.empty([len(names),len(removenames)])\n for i in range(len(removenames)):\n #for each row, find the indices that correspond to the matching \n #name AND spectral index\n index[:,i]=(names==removenames[i])&(spect_index==removeinds[i])\n \n names_removed=names[numpy.any(index,axis=1)]\n spect_index_removed=spect_index[numpy.any(index,axis=1)]\n if which_removed:\n with open(which_removed,'w',newline='') as writefile:\n writer=csv.writer(writefile,delimiter=',')\n for i in range(len(names_removed)):\n writer.writerow([names_removed[i],spect_index_removed[i],'From File'])\n #combine the indices for each row to a single array that indicates which\n #spectra to remove, then invert it to indicate which spectra to keep\n index=numpy.invert(numpy.any(index,axis=1))\n \n \n# if keepfile != None:\n# #read the list of sample names and spectrum indices from the file\n# f=open(keepfile,'r')\n# f.readline()\n# f.readline()\n# data=list(zip(*csv.reader(f)))\n# keepinds=numpy.array(data[0],dtype='int')\n# keepinds=keepinds-1.0\n# index3=numpy.in1d(range(0,len(names)),keepinds)\n# index=numpy.vstack((index,index3))\n# index=numpy.all(index,axis=0)\n# \n# if linewvl!=None:\n#\n# bins=numpy.squeeze((wvl>linewvl[0])&(wvllinestrength[0])&(linesumsmincomp)&(comps_keep[:,compindex] thresh\n mask[mask>0] = 1\n \n ball = makeball(4,4,4,4,4,4,vdim)\n ball2 = makeball(5,5,5,5,5,5,vdim)\n\n mask = morph.binary_erosion(mask.astype(bool), ball)\n mask = morph.binary_dilation(mask.astype(bool), ball2)\n\n for i in range(image_data.shape[2]):\n mask[:,:,i] = morph.binary_fill_holes(mask[:,:,i])\n\n mask = morph.binary_dilation(mask.astype(bool), ball2)\n label_image, num = measure.label(mask.astype(int), return_num = True,\\\n connectivity = mask.ndim)\n\n if num < 2:\n return mask\n else:\n props = measure.regionprops(label_image)\n areas = [prop.area for prop in props]\n maxarea = max(areas)\n newmask = morphology.remove_small_objects(mask, maxarea - 10,\\\n connectivity = mask.ndim)\n\n return newmask\n \ndef makeball(r,l,a,p,d,u,vdim = (1,1,1)):\n r = r/vdim[0]\n l = l/vdim[0]\n a = a/vdim[1]\n p = p/vdim[1]\n d = d/vdim[2]\n u = u/vdim[2]\n\n R = np.ceil(r - 0.5)\n L = np.ceil(l - 0.5)\n A = np.ceil(a - 0.5)\n P = np.ceil(p - 0.5)\n D = np.ceil(d - 0.5)\n U = np.ceil(u - 0.5)\n\n RL = int(max(R,L))\n AP = int(max(A,P))\n DU = int(max(D,U))\n ball = np.zeros((2*RL+1,2*AP+1,2*DU+1), dtype=bool)\n\n xyz_grid = [(x,y,z) for x in range(-RL, RL+1) for y in range(-AP,AP+1) for z in range(-DU,DU+1)]\n for i, j, k in xyz_grid:\n if i < 0:\n x = r + 0.5\n else:\n x = l + 0.5\n if j < 0:\n y = a + 0.5\n else:\n y = p + 0.5\n if k < 0: \n z = d + 0.5\n else:\n z = u + 0.5\n if ((i*i)/(x*x) + (j*j)/(y*y) + (k*k)/(z*z)) <= 1:\n ball[i+RL,j+AP,k+DU] = 1;\n\n return ball\ndef getDifferenceImage(refNii = \"\", resNii = \"\", savename = \"\"):\n imgRef = nib.load(refNii)\n imgRefData = np.array(imgRef.get_data())\n \n imgRes = nib.load(resNii)\n imgResData = np.array(imgRes.get_data())\n \n if imgRefData.shape == imgResData.shape:\n imgDiff = imgResData - imgRefData\n diffNii = nib.Nifti1Image(imgDiff, affine = imgRef.affine, header = imgRef.header)\n nib.save(diffNii, savename)\n else: \n print('resampled nifti not in same space')\n \n \ndef fullpath( path = \"\" ):\n \"\"\"\n Evaluate full path, expanding '~', environment variables and symbolic links\n \"\"\"\n import os\n expandedPath = \"\"\n if path:\n tmpPath = ( os.path.expandvars( path.strip() ) )\n tmpPath = os.path.abspath( os.path.expanduser( tmpPath ) )\n expandedPath = os.path.realpath( tmpPath )\n return expandedPath\n\nif __name__ =='__main__':\n #path to niftyreg executables\n nifty_path = 'C:\\\\NiftyReg\\\\install\\\\bin'\n \n #path to patient data\n path = 'N:\\\\NiiForOptimisation'\n \n pt_num = ['p1', 'p2', 'p3'] \n #pt_num = ['p1']\n \n #parameter to test\n #be = [0.0001 0.001 0.01 0.1];\n # control point spacing to test in units of voxels\n cps = [3, 5, 7, 10, 15]\n bes = [0.01]\n #be = 0.01\n \n for i in range(len(pt_num)):\n pat = pt_num[i]\n dir_name = os.path.join(path,pat)\n os.chdir(dir_name)\n \n patient_list = glob.glob('????????_??????.nii')\n patient_list.sort()\n #use the planning CT as reference CT so that all DVFs in ref\n #coordinate system\n ref = patient_list[0]\n # for optimisation, register pCT with week 3 and week 8 to \n # account for least amount of deformation and largetst amount\n # of deformation\n \n # week 3\n flo1 = patient_list[1]\n # week 8 (usually) but just take last in the list\n flo2 = patient_list[-1]\n \n refmask = ref[0:len(ref)-4] + '_mask.nii'\n flo1mask = flo1[0:len(flo1)-4] + '_mask.nii'\n flo2mask = flo2[0:len(flo2)-4] + '_mask.nii'\n \n #create the body masks if not already created\n if not os.path.isfile(refmask):\n makeBodyMask(ref, refmask)\n if not os.path.isfile(flo1mask):\n makeBodyMask(flo1, flo1mask)\n if not os.path.isfile(flo2mask):\n makeBodyMask(flo2, flo2mask) \n \n for j, cp in enumerate(cps):\n for k, be in enumerate(bes):\n res1 = 'dir_wk3_to_wk0_cps' + str(cp) + '_be' + str(be) +'.nii'\n cppres1 = 'cpp_wk3_to_wk0_cps' + str(cp) + '_be' + str(be) +'.nii'\n output1 = 'output_wk3_to_wk0_cps' + str(cp) + '_be' + str(be) + '.txt'\n lnccoutput1 = 'lncc_wk3_to_wk0_cps' + str(cp) +'_be' + str(be) + '.txt'\n diff1 = 'diff_wk3_to_wk0' + str(cp) + '_be' + str(be) +'.nii'\n \n res2 = 'dir_wk8_to_wk0_cps' + str(cp) + '_be' + str(be) +'.nii'\n cppres2 = 'cpp_wk8_to_wk0_cps' + str(cp) +'_be' + str(be) + '.nii'\n output2 = 'output_wk8_to_wk0_cps' + str(cp) + '_be' + str(be) +'.txt'\n lnccoutput2 = 'lncc_wk8_to_wk0_cps' + str(cp) +'_be' + str(be) + '.txt'\n diff2 = 'diff_wk8_to_wk0' + str(cp) + '_be' + str(be) +'.nii'\n \n reg1Command = nifty_path + '\\\\reg_f3d.exe -flo ' + str(flo1) + \\\n ' -ref ' + str(ref) + ' -rmask ' + str(refmask) + ' -fmask ' \\\n + str(flo1mask) + ' -sx -'+str(cp)+' -sy -'+ str(cp)+\\\n ' -sz -'+str(cp)+' -be ' + str(be) + ' -ln 5 -lp 4 -le 0.001 -vel '+ \\\n '--lncc 10 -res '+ res1 + ' -cpp '+ cppres1 +' > ' + output1 \n \n \n meas1Command = nifty_path + '\\\\reg_measure.exe -ref ' + str(ref) +\\\n ' -flo ' + res1 + ' -lncc -out ' + lnccoutput1\n if not os.path.isfile(res1):\n os.system( reg1Command )\n if not os.path.isfile(lnccoutput1):\n os.system( meas1Command )\n getDifferenceImage(ref, res1, diff1) \n \n reg2Command = nifty_path + '\\\\reg_f3d.exe -flo ' + str(flo2) + \\\n ' -ref ' + str(ref) + ' -rmask ' + str(refmask) + ' -fmask ' \\\n + str(flo2mask) + ' -sx -'+str(cp)+' -sy -'+ str(cp)+ \\\n ' -sz -'+str(cp)+' -be '+ str(be) + ' -ln 5 -lp 4 -le 0.001 -vel '+ \\\n '--lncc 10 -res '+ res2 + ' -cpp '+ cppres2 +' > ' + output2 \n \n meas2Command = nifty_path + '\\\\reg_measure.exe -ref ' + str(ref) +\\\n ' -flo ' + res2 + ' -lncc -out ' + lnccoutput2\n \n if not os.path.isfile(res2):\n os.system( reg2Command )\n if not os.path.isfile(lnccoutput2):\n os.system( meas2Command )\n \n getDifferenceImage(ref, res2, diff2)\n \n \n \n","sub_path":"bin/run_registrations_for_optimisation.py","file_name":"run_registrations_for_optimisation.py","file_ext":"py","file_size_in_byte":7656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"355914832","text":"\"\"\"\nAuthor: Shane Caldwell\nDate Written: 11/8/2015\n\nUse: Should be used to decode bencoded files for garter\n\"\"\"\nimport re\n\ndecimal_match = re.compile('\\d')\n\n\ndef decode(data):\n chunks = list(data)\n chunks.reverse()\n root = _dechunk(chunks)\n return root\n\n\ndef _dechunk(chunks):\n item = chunks.pop()\n # Handles dictionaries\n if item == 'd':\n item = chunks.pop()\n hash = {}\n while item != 'e':\n chunks.append(item)\n key = _dechunk(chunks)\n hash[key] = _dechunk(chunks)\n item = chunks.pop()\n return hash\n # Handles lists\n elif item == 'l':\n item = chunks.pop()\n list = []\n while item != 'e':\n chunks.append(item)\n list.append(_dechunk(chunks))\n item = chunks.pop()\n return list\n # Handles integers\n elif item == \"i\":\n item = chunks.pop()\n num = ''\n while item != 'e':\n num += item\n item = chunks.pop()\n return int(num)\n # Handles strings - not working properly.\n elif decimal_match.search(item):\n num = ''\n while decimal_match.search(item):\n num += item\n item = chunks.pop()\n line = ''\n for i in range(int(num)):\n line += chunks.pop()\n return line\n raise \"Invalid input!\"\n","sub_path":"cracker/torrentClient/debencode.py","file_name":"debencode.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"338165294","text":"#Script sorts a list of numbers with merge sort\n#but uses additional list\n\nimport random\n\ndef merge(list1,list2):\n i = 0\n j = 0\n list = []\n\n while i < len(list1) and j < len(list2):\n if list1[i] > list2[j]:\n list.append(list2[j])\n j += 1\n else:\n list.append(list1[i])\n i += 1\n pass\n\n if i == len(list1):\n while j < len(list2):\n list.append(list2[j])\n j += 1\n pass\n elif j == len(list2):\n while i < len(list1):\n list.append(list1[i])\n i += 1\n\n return list\n\nlist_range = int(input('Type list range >'))\nrandom_range = int(input('Type random range >'))\n\nl = [random.randrange(random_range) for i in range(list_range)]\nprint('\\nInitial list\\n',l,'\\n')\n\n#divide origin list into list of lists with size 1\nl = [l[i:i+1] for i in range(len(l))]\n\n\nk = 0\ntemp_list = []\n\na = []\nb = []\n\n#merge consequent lists, add merged into temp_list and then replace origin with temp\n#do it until there will be one list in a list\nwhile len(l) > 1:\n while k < len(l):\n if k+1 > len(l)-1: # in case of out of index error\n a = l[k]\n b = []\n else:\n a = l[k]\n b = l[k+1]\n\n temp_list.append(merge(a, b))\n k += 2\n\n l = temp_list[:]\n temp_list = []\n k = 0\n\n\nl = l[0]\n#print sorted list\nprint('Sorted list\\n',l)\n","sub_path":"Python_3/merge_sort_2.py","file_name":"merge_sort_2.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"214329033","text":"import time\nfrom src.image_handler import Image_handler\nfrom src.mouse_automate import Mouseomate\nimport os\n\nos.chdir(\".\\images\")\n\nlsleep = 0.005 #adujust this to change pause time at end of line (recommend .002)\nrsleep = 0.025 #adujust this to change pause time at end of row (recommend .025)\nimagename = Image_handler.get_image()\nhandler = Image_handler(imagename)\nresizevalue = int(input(\"What is the approximate pixel size of the input field?\"))\noffset = int(input(\"What is the approximate brush size in pixels? (1 for one to one drawing)\"))\nresizevalue = resizevalue / offset\nhandler.convert_bandw()\nhandler.resize(resizevalue)\n\nhandler.im.show()\nreturnkey = None\nwhile returnkey == None:\n print(\"Preview image loaded. Enter to begin 3 second countdown to start, N to abort. Once image has started, pulling mouse to the upper left corner will abort the program.\")\n returnkey = input()\n if returnkey == 'N' or returnkey =='n':\n exit()\n if returnkey == \"I\" or returnkey ==\"i\":\n handler.invert(imagename)\n handler.convert_bandw()\n resizevalue = resizevalue / offset\n handler.resize(resizevalue)\n handler.im.show()\n returnkey = None\n\ntime.sleep(3)\narray = handler.update_array()\nMouseomate.image_to_lines(array, offset, rsleep, lsleep)\nrepeat = 'Y'\nwhile repeat == 'Y':\n repeat = input(\"Y to redraw after 3 sec pause, or enter to exit\")\n if repeat == 'y' or repeat == 'Y':\n time.sleep(3)\n Mouseomate.image_to_lines(array, offset, rsleep, lsleep)\n else:\n exit()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"285819379","text":"from django.core.paginator import Paginator\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\n\n# Create your views here.\nfrom home.models import Article, Category, Comment\n\n\ndef homepage(request):\n return homepage_detail(request, 1)\n\n\ndef homepage_detail(request, page_num):\n article_list = Article.objects.all().order_by('-id')\n category_list = Category.objects.all()\n\n page_num = int(page_num)\n page = Paginator(article_list, 2)\n page_sum = page.num_pages\n\n start_pos = -1\n end_pos = -1\n if page_num <= 2:\n start_pos = 1\n end_pos = min(5, page_sum)\n if page_num > page_sum - 2:\n start_pos = max(1, page_num - 4+(page_sum-page_num))\n end_pos = page_sum\n if start_pos == -1:\n start_pos = page_num - 2\n end_pos = page_num + 2\n page_list = range(start_pos, end_pos + 1)\n article_list = page.page(page_num)\n\n return render(request, 'homepage.html',\n {'article_list': article_list, 'category_list': category_list, 'page_list': page_list,\n 'page_num': page_num, 'page_sum': page_sum})\n\n\ndef category(request):\n category_list = Category.objects.all()\n return render(request, 'category.html', {'category_list': category_list})\n\n\ndef detail_category(request, category_id):\n category_list = Category.objects.all()\n category = Category.objects.get(id=int(category_id))\n article_list = category.article_set.all()\n return render(request, 'detail_category.html',\n {'category_list': category_list, 'article_list': article_list, 'category': category})\n\n\ndef article(request):\n article_list = Article.objects.all()\n category_list = Category.objects.all()\n return render(request, 'article.html', {'category_list': category_list, 'article_list': article_list})\n\n\ndef detail_article(request, article_id):\n article_id = int(article_id)\n category_list = Category.objects.all()\n article_now = Article.objects.get(id=article_id)\n comment_list = article_now.comment_set.all()\n is_superuser = request.user.is_superuser\n if request.method == \"GET\":\n return render(request, 'detail_article.html', {'category_list': category_list, 'article': article_now,\n 'comment_list': comment_list, 'is_superuser': is_superuser})\n else:\n user_name = request.POST.get('name')\n content = request.POST.get('content')\n parent = request.POST.get('parent', '')\n if parent != '':\n parent = Comment.objects.get(id=int(parent))\n else:\n parent = None\n comment = Comment.objects.create(article=article_now, user_name=user_name, content=content,\n parent_comment=parent)\n comment.save()\n return HttpResponseRedirect(reverse('home:detail_article', kwargs={'article_id': article_id}))\n\n\ndef delete_comment(request, comment_id):\n comment = Comment.objects.get(id=int(comment_id))\n article_id = comment.article.id\n comment.delete()\n return HttpResponseRedirect(reverse('home:detail_article', kwargs={'article_id': article_id}))\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624878335","text":"import qelos_core as q\nimport torch\nimport torchvision\nimport numpy as np\n\n# region new model\n# region from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\nclass ResamplingConv(torch.nn.Module):\n def __init__(self, in_planes, out_planes, kernel=3, padding=None, resample=None, bias=True):\n \"\"\"\n Combines resampling (up/down) with convolution.\n If resample is \"up\", then nn.Upsample(x2) is applied before the conv\n If resample is \"down\", then nn.MaxPool2D(x2) is applied after the conv\n Padding is automatically set to preserve spatial shapes of input.\n If kernel is 0, no conv is applied and the module is reduced to up/down sampling (if any)\n Resample=None and kernel=0 ==> nothing happens\n \"\"\"\n super(ResamplingConv, self).__init__()\n assert(kernel in (0, 1, 3, 5, 7))\n padding = (kernel - 1) // 2 if padding is None else padding\n if kernel == 0:\n self.conv = None\n else:\n self.conv = torch.nn.Conv2d(in_planes, out_planes, kernel_size=kernel, padding=padding, bias=bias)\n self.resample = resample\n if resample == \"up\":\n self.resampler = torch.nn.Upsample(scale_factor=2)\n elif resample == \"down\":\n self.resampler = torch.nn.AvgPool2d(2)\n\n def forward(self, x):\n if self.resample == \"up\":\n x = self.resampler(x)\n if self.conv is not None:\n x = self.conv(x)\n if self.resample == \"down\":\n x = self.resampler(x)\n return x\n\n\nclass ResBlock(torch.nn.Module):\n def __init__(self, inplanes, planes, kernel=3, resample=None, bias=True, batnorm=True):\n \"\"\"\n Residual block with two convs and optional resample.\n If resample == \"up\", the first conv is upsampling by 2, residual is upsampled too\n If resample == \"down\", the last conv is downsampling by 2, residual is downsampled too\n If resample == None, no resampling anywhere\n\n 1x1 conv is applied to residual only if inplanes != planes and resample is None.\n \"\"\"\n super(ResBlock, self).__init__()\n self.conv1 = ResamplingConv(inplanes, planes, kernel,\n resample=resample if resample != \"down\" else None,\n bias=bias)\n self.bn1 = torch.nn.BatchNorm2d(planes) if batnorm else None\n self.relu = torch.nn.ReLU(inplace=True)\n self.conv2 = ResamplingConv(planes, planes, kernel,\n resample=resample if resample != \"up\" else None,\n bias=bias)\n self.bn2 = torch.nn.BatchNorm2d(planes) if batnorm else None\n self.resample = resample\n self.shortcut = ResamplingConv(inplanes, planes, 0 if (inplanes == planes and resample is None) else 1,\n resample=resample,\n bias=bias)\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out) if self.bn1 is not None else out\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out) if self.bn2 is not None else out\n\n residual = self.shortcut(residual)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n# endregion\n\n\nclass Generator(torch.nn.Module):\n def __init__(self, z_dim, dim_g, **kw):\n super(Generator, self).__init__(**kw)\n self.layers = torch.nn.ModuleList([\n q.Lambda(lambda x: x.unsqueeze(2).unsqueeze(3)),\n torch.nn.ConvTranspose2d(z_dim, dim_g, 4),\n torch.nn.BatchNorm2d(dim_g),\n torch.nn.ReLU(),\n ResBlock(dim_g, dim_g, 3, resample='up'),\n ResBlock(dim_g, dim_g, 3, resample='up'),\n ResBlock(dim_g, dim_g, 3, resample='up'),\n torch.nn.Conv2d(dim_g, 3, 3, padding=1),\n torch.nn.Tanh(),\n ])\n\n def forward(self, x):\n for layer in self.layers:\n x = layer(x)\n return x\n\n\nclass Discriminator(torch.nn.Module):\n def __init__(self, dim_d, **kw):\n super(Discriminator, self).__init__(**kw)\n self.layers = torch.nn.ModuleList([\n ResBlock(3, dim_d, 3, resample='down', batnorm=False),\n ResBlock(dim_d, dim_d, 3, resample='down', batnorm=False),\n ResBlock(dim_d, dim_d, 3, resample=None, batnorm=False),\n ResBlock(dim_d, dim_d, 3, resample=None, batnorm=False),\n q.Lambda(lambda x: x.mean(3).mean(2)), # global average pooling over spatial dims\n torch.nn.Linear(dim_d, 1),\n q.Lambda(lambda x: x.squeeze(1))\n ])\n\n def forward(self, x): # (batsize, channels, h?, w?)\n for layer in self.layers:\n x = layer(x)\n return x\n\n# endregion\n\n\nclass SubVGG(torch.nn.Module):\n def __init__(self, version=11, feat_layer=9, **kw):\n \"\"\"\n Pretrained VGG-*version*, taking only first *feat_layer*-th layer's output.\n :param version: 11/13/16/19\n \"\"\"\n super(SubVGG, self).__init__(**kw)\n v2f = {\n 11: torchvision.models.vgg11,\n 13: torchvision.models.vgg13,\n 16: torchvision.models.vgg16,\n 19: torchvision.models.vgg19,\n }\n if version not in v2f:\n raise q.SumTingWongException(\"vgg{} does not exist, please specify valid version number (11, 13, 16 or 19)\".format(version))\n self.vgg = v2f[version](pretrained=False)\n if feat_layer > len(self.vgg.features):\n raise q.SumTingWongException(\"vgg{} does not have layer nr. {}. Please use a valid layer number.\"\n .format(version, feat_layer))\n self.layers = self.vgg.features[:feat_layer]\n def get_numth(num):\n numther = {1: \"st\", 2: \"nd\", 3: \"rd\"}\n if num in numther:\n return numther[num]\n else:\n return \"th\"\n print(\"using VGG{}'s {}{} layer's outputs ({})\".format(version, feat_layer, get_numth(feat_layer), str(self.layers[feat_layer-1])))\n\n def forward(self, x):\n feats = self.layers(x)\n return feats\n\n\ndef tst_subvgg():\n v = 13\n l = 8\n vgg = SubVGG(version=v, feat_layer=l)\n x = torch.rand(1, 3, 32, 32) * 2 - 1\n y = vgg(x)\n print(y.size())\n return y.size(1)\n\n\ndef get_vgg_outdim(v, l):\n vgg = SubVGG(version=v, feat_layer=l)\n x = torch.rand(1, 3, 32, 32) * 2 - 1\n y = vgg(x)\n return y.size(1)\n\n\ndef tst_subvgg_with_disc():\n\n v = 13\n l = 8\n vgg = SubVGG(version=v, feat_layer=l)\n d = OldDiscriminator(128, 128)\n x = torch.rand(2, 3, 32, 32) * 2 - 1\n y = vgg(x)\n z = d(y)\n print(y.size(), z.size(), z)\n\n\n# region oldmodel\nclass Normalize(torch.nn.Module):\n def __init__(self, dim, **kw):\n super(Normalize, self).__init__(**kw)\n self.bn = torch.nn.BatchNorm2d(dim)\n\n def forward(self, x):\n return self.bn(x)\n\n\nclass ConvMeanPool(torch.nn.Module):\n def __init__(self, indim, outdim, filter_size, biases=True, **kw):\n super(ConvMeanPool, self).__init__(**kw)\n assert(filter_size % 2 == 1)\n padding = filter_size // 2\n self.conv = torch.nn.Conv2d(indim, outdim, kernel_size=filter_size, padding=padding, bias=biases)\n self.pool = torch.nn.AvgPool2d(2)\n\n def forward(self, x):\n y = self.conv(x)\n y = self.pool(y)\n return y\n\n\nclass MeanPoolConv(ConvMeanPool):\n def forward(self, x):\n y = self.pool(x)\n y = self.conv(y)\n return y\n\n\nclass UpsampleConv(torch.nn.Module):\n def __init__(self, indim, outdim, filter_size, biases=True, **kw):\n super(UpsampleConv, self).__init__(**kw)\n assert(filter_size % 2 == 1)\n padding = filter_size // 2\n self.conv = torch.nn.Conv2d(indim, outdim, kernel_size=filter_size, padding=padding, bias=biases)\n self.pool = torch.nn.Upsample(scale_factor=2)\n\n def forward(self, x):\n y = self.pool(x)\n y = self.conv(y)\n return y\n\n\nclass ResidualBlock(torch.nn.Module):\n def __init__(self, indim, outdim, filter_size, resample=None, use_bn=False, **kw):\n super(ResidualBlock, self).__init__(**kw)\n assert(filter_size % 2 == 1)\n padding = filter_size // 2\n bn2dim = outdim\n if resample == \"down\":\n self.conv1 = torch.nn.Conv2d(indim, indim, kernel_size=filter_size, padding=padding, bias=True)\n self.conv2 = ConvMeanPool(indim, outdim, filter_size=filter_size)\n self.conv_shortcut = ConvMeanPool\n bn2dim = indim\n elif resample == \"up\":\n self.conv1 = UpsampleConv(indim, outdim, filter_size=filter_size)\n self.conv2 = torch.nn.Conv2d(outdim, outdim, kernel_size=filter_size, padding=padding, bias=True)\n self.conv_shortcut = UpsampleConv\n else: # None\n assert(resample is None)\n self.conv1 = torch.nn.Conv2d(indim, outdim, kernel_size=filter_size, padding=padding, bias=True)\n self.conv2 = torch.nn.Conv2d(outdim, outdim, kernel_size=filter_size, padding=padding, bias=True)\n self.conv_shortcut = torch.nn.Conv2d\n if use_bn:\n self.bn1 = Normalize(indim)\n self.bn2 = Normalize(bn2dim)\n else:\n self.bn1, self.bn2 = None, None\n\n self.nonlin = torch.nn.ReLU()\n\n if indim == outdim and resample == None:\n self.conv_shortcut = None\n else:\n self.conv_shortcut = self.conv_shortcut(indim, outdim, filter_size=1) # bias is True by default, padding is 0 by default\n\n def forward(self, x):\n if self.conv_shortcut is None:\n shortcut = x\n else:\n shortcut = self.conv_shortcut(x)\n y = self.bn1(x) if self.bn1 is not None else x\n y = self.nonlin(y)\n y = self.conv1(y)\n y = self.bn2(y) if self.bn2 is not None else y\n y = self.nonlin(y)\n y = self.conv2(y)\n\n return y + shortcut\n\n\nclass OptimizedResBlockDisc1(torch.nn.Module):\n def __init__(self, dim, **kw):\n super(OptimizedResBlockDisc1, self).__init__()\n self.conv1 = torch.nn.Conv2d(3, dim, kernel_size=3, padding=1, bias=True)\n self.conv2 = ConvMeanPool(dim, dim, filter_size=3, biases=True)\n self.conv_shortcut = MeanPoolConv(3, dim, filter_size=1, biases=True)\n self.nonlin = torch.nn.ReLU()\n\n def forward(self, x):\n y = self.conv1(x)\n y = self.nonlin(y)\n y = self.conv2(y)\n shortcut = self.conv_shortcut(x)\n return y + shortcut\n\n\nclass OldGenerator(torch.nn.Module):\n def __init__(self, z_dim, dim_g, use_bn=True, **kw):\n super(OldGenerator, self).__init__(**kw)\n self.layers = torch.nn.ModuleList([\n torch.nn.Linear(z_dim, 4*4*dim_g),\n q.Lambda(lambda x: x.view(x.size(0), dim_g, 4, 4)),\n ResidualBlock(dim_g, dim_g, 3, resample=\"up\", use_bn=use_bn),\n ResidualBlock(dim_g, dim_g, 3, resample=\"up\", use_bn=use_bn),\n ResidualBlock(dim_g, dim_g, 3, resample=\"up\", use_bn=use_bn),\n Normalize(dim_g),\n torch.nn.ReLU(),\n torch.nn.Conv2d(dim_g, 3, kernel_size=3, padding=1),\n torch.nn.Tanh(),\n ])\n\n def forward(self, a):\n for layer in self.layers:\n a = layer(a)\n return a\n\n\nclass OldDiscriminator(torch.nn.Module):\n def __init__(self, inp_d, dim_d, use_bn=False, **kw):\n super(OldDiscriminator, self).__init__(**kw)\n self.layers = torch.nn.ModuleList([\n # OptimizedResBlockDisc1(dim_d),\n ResidualBlock(inp_d, dim_d, 3, resample=\"down\", use_bn=use_bn),\n ResidualBlock(dim_d, dim_d, 3, resample=\"down\", use_bn=use_bn),\n ResidualBlock(dim_d, dim_d, 3, resample=None, use_bn=use_bn),\n torch.nn.ReLU(),\n q.Lambda(lambda x: x.mean(3).mean(2)),\n torch.nn.Linear(dim_d, 1),\n q.Lambda(lambda x: x.squeeze(1))\n ])\n\n def forward(self, a):\n for layer in self.layers:\n a = layer(a)\n return a\n# endregion\n\n\nclass UnquantizeTransform(object):\n def __init__(self, levels=256, range=(-1., 1.)):\n super(UnquantizeTransform, self).__init__()\n self.rand_range = (range[1] - range[0]) * 1. / (1. * levels)\n\n def __call__(self, x):\n rand = torch.rand_like(x) * self.rand_range\n x = x + rand\n return x\n\n def __repr__(self):\n return self.__class__.__name__ + '(rand_range={0})'.format(self.rand_range)\n\n\ndef load_cifar_dataset(train=True):\n class IgnoreLabelDataset(torch.utils.data.Dataset):\n def __init__(self, orig):\n self.orig = orig\n\n def __getitem__(self, index):\n return self.orig[index][0]\n\n def __len__(self):\n return len(self.orig)\n cifar = torchvision.datasets.CIFAR10(root='../../../datasets/cifar/', download=True, train=train,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.Scale(32),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n )\n cifar = IgnoreLabelDataset(cifar)\n return cifar\n\n\ndef run(lr=0.0001,\n batsize=64,\n epochs=100000,\n lamda=10,\n disciters=5,\n burnin=-1,\n validinter=1000,\n devinter=100,\n cuda=False,\n gpu=0,\n z_dim=128,\n test=False,\n dim_d=128,\n dim_g=128,\n vggversion=13,\n vgglayer=9,\n ):\n\n settings = locals().copy()\n logger = q.log.Logger(prefix=\"wgan_resnet_cifar_feat\")\n logger.save_settings(**settings)\n\n burnin = disciters if burnin == -1 else burnin\n\n if test:\n validinter=10\n burnin=1\n batsize=2\n devinter = 1\n\n tt = q.ticktock(\"script\")\n\n device = torch.device(\"cpu\") if not cuda else torch.device(\"cuda\", gpu)\n\n tt.tick(\"creating networks\")\n gen = OldGenerator(z_dim, dim_g).to(device)\n inpd = get_vgg_outdim(vggversion, vgglayer)\n crit = OldDiscriminator(inpd, dim_d).to(device)\n subvgg = SubVGG(vggversion, vgglayer)\n tt.tock(\"created networks\")\n\n # test\n # z = torch.randn(3, z_dim).to(device)\n # x = gen(z)\n # s = crit(x)\n\n # data\n # load cifar\n tt.tick(\"loading data\")\n traincifar, testcifar = load_cifar_dataset(train=True), load_cifar_dataset(train=False)\n print(len(traincifar))\n\n gen_data_d = q.gan.gauss_dataset(z_dim, len(traincifar))\n disc_data = q.datacat([traincifar, gen_data_d], 1)\n\n gen_data = q.gan.gauss_dataset(z_dim)\n gen_data_valid = q.gan.gauss_dataset(z_dim, 50000)\n\n disc_data = q.dataload(disc_data, batch_size=batsize, shuffle=True)\n gen_data = q.dataload(gen_data, batch_size=batsize, shuffle=True)\n gen_data_valid = q.dataload(gen_data_valid, batch_size=batsize, shuffle=False)\n validcifar_loader = q.dataload(testcifar, batch_size=batsize, shuffle=False)\n\n dev_data_gauss = q.gan.gauss_dataset(z_dim, len(testcifar))\n dev_disc_data = q.datacat([testcifar, dev_data_gauss], 1)\n dev_disc_data = q.dataload(dev_disc_data, batch_size=batsize, shuffle=False)\n # q.embed()\n tt.tock(\"loaded data\")\n\n disc_model = q.gan.WGAN_F(crit, gen, subvgg, lamda=lamda).disc_train()\n gen_model = q.gan.WGAN_F(crit, gen, subvgg, lamda=lamda).gen_train()\n\n disc_optim = torch.optim.Adam(q.params_of(crit), lr=lr, betas=(0.5, 0.9))\n gen_optim = torch.optim.Adam(q.params_of(gen), lr=lr, betas=(0.5, 0.9))\n\n disc_bt = UnquantizeTransform()\n\n disc_trainer = q.trainer(disc_model).on(disc_data).optimizer(disc_optim).loss(3).device(device)\\\n .set_batch_transformer(lambda a, b: (disc_bt(a), b))\n gen_trainer = q.trainer(gen_model).on(gen_data).optimizer(gen_optim).loss(1).device(device)\n\n fidandis = q.gan.FIDandIS(device=device)\n if not test:\n fidandis.set_real_stats_with(validcifar_loader)\n saver = q.gan.GenDataSaver(logger, \"saved.npz\")\n generator_validator = q.gan.GeneratorValidator(gen, [fidandis, saver], gen_data_valid, device=device,\n logger=logger, validinter=validinter)\n\n train_validator = q.tester(disc_model).on(dev_disc_data).loss(3).device(device)\\\n .set_batch_transformer(lambda a, b: (disc_bt(a), b))\n\n train_validator.validinter = devinter\n\n tt.tick(\"training\")\n gan_trainer = q.gan.GANTrainer(disc_trainer, gen_trainer,\n validators=(generator_validator, train_validator),\n lr_decay=True)\n\n gan_trainer.run(epochs, disciters=disciters, geniters=1, burnin=burnin)\n tt.tock(\"trained\")\n\n\nif __name__ == \"__main__\":\n # tst_subvgg()\n # tst_subvgg_with_disc()\n q.argprun(run)","sub_path":"qelos_core/scripts/gan/wgan_resnet_cifar_feat_vanilla.py","file_name":"wgan_resnet_cifar_feat_vanilla.py","file_ext":"py","file_size_in_byte":17067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"86802618","text":"from monitor.thread_pool import *\n\ndef create_pool(numThreads = 3):\n pool = ThreadPool()\n pool.work_queue_get_timeout = 0.2\n if numThreads and numThreads > 0:\n pool.start_threads(numThreads)\n return pool\n\nclass MockTask(Task):\n def __init__(self, actions = None):\n super(MockTask, self).__init__()\n self.errors = []\n self.actions = actions\n def execute(self):\n if self.actions is not None:\n assert len(self.actions) >= self.started, \"Task executed too often.\"\n action = self.actions[self.started - 1]\n if action is not None:\n action()\n def execution_finished(self, exc_info):\n self.errors.append(None if exc_info is None else str(exc_info[1]))\n super(MockTask, self).execution_finished(exc_info)\n def __str__(self):\n return \"%s(%i)\" % (self.__class__.__name__, self.started)\n\ndef test_pool_create():\n pool = create_pool()\n pool.finish()\n\ndef test_pool_executed():\n pool = create_pool(numThreads = 3)\n def error_action():\n raise Exception(\"Expected test error\")\n task = MockTask([None, error_action, None])\n [ pool.add_task(task) for _ in range(3) ]\n pool.finish(timeout=1)\n assert task.scheduled == 3\n assert task.started == 3\n assert task.finished == 3\n assert task.errors == [None, \"Expected test error\", None]\n\nclass EventTask(Task):\n def __init__(self, raise_error=False):\n super(EventTask, self).__init__()\n self.raise_error = raise_error\n self.event = threading.Event()\n self.error = None\n def execute(self):\n if self.raise_error:\n raise Exception(\"Expected error\")\n def execution_finished(self, exc_info):\n super(EventTask, self).execution_finished(exc_info)\n if exc_info is not None:\n self.error = str(exc_info[1])\n self.event.set()\n\ndef test_pool_timeout_finish():\n pool = create_pool(numThreads = 3)\n def forever_action():\n while True: pass\n event_task = EventTask()\n event_task2 = EventTask(raise_error = True)\n task = MockTask([forever_action] * 5)\n\n pool.add_tasks([event_task, event_task2] + [task] * 5)\n assert event_task.event.wait(timeout = 2), 'Waiting for first task timed out.'\n assert event_task2.event.wait(timeout = 2), 'Waiting for second task timed out.'\n\n pool.finish(timeout = 0.03)\n assert event_task.last_exc_info is None and event_task.error is None\n assert event_task2.error == 'Expected error'\n assert task.scheduled == 5\n assert task.started == 3\n assert task.finished == 0\n assert task.errors == []\n","sub_path":"monitor/tests/test_thread_pool.py","file_name":"test_thread_pool.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"476424037","text":"#!/usr/bin/env python\n\nimport data\nfrom model import Seq2SeqTypoModel\n\ndef main():\n datafile = \"./data/imdb.txt\"\n chars, chunks, max_in, max_out = data.load_data(datafile)\n enc_input_data, dec_input_data, dec_output_data = data.format_input_data(chars, chunks, max_in, max_out)\n print(\"[i] Done loading data.\")\n\n num_epochs = 3\n\n model = Seq2SeqTypoModel(chars, chars)\n # model.load(\"typo-small-3.h5\")\n model.train(enc_input_data, dec_input_data, dec_output_data, num_epochs)\n model.save(\"typo-large.h5\")\n\n while True:\n input_str = input(\">>> \")\n print(model.infer(f\"^{input_str}$\"))\n\nif __name__ == \"__main__\":\n main()","sub_path":"seq2seq/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173763844","text":"'''\nPurpose:\n Uses Google Maps API to get location data.\n'''\nimport googlemaps\n\n\ndef get_lat_lng(location):\n '''\n Purpose:\n Gets latitude and longitude from the name of location using Google\n Maps geocode AP\n Inputs:\n location (string): name of the location\n Outputs:\n lat, lng (float): gives floats of latitutde and longitude information\n '''\n gmaps = googlemaps.Client(key='AIzaSyAmmm3Lc1n897ijWvvFuyg1TR-kixbAvAQ')\n geocode_result = gmaps.geocode(location)\n lat = geocode_result[0]['geometry']['location']['lat']\n lng = geocode_result[0]['geometry']['location']['lng']\n return lat, lng\n","sub_path":"website/google_maps.py","file_name":"google_maps.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"102257077","text":"import pytest\n\nfrom bottery.platform import BasePlatform\n\n\ndef test_platform_baseplatform():\n platform = 'TEST_PLATFORM'\n bp = BasePlatform(platform=platform)\n\n assert bp.webhook_endpoint == '/hook/{}'.format(platform)\n assert not len(bp.tasks)\n\n with pytest.raises(Exception):\n bp.build_message()\n","sub_path":"tests/test_platform.py","file_name":"test_platform.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"212643798","text":"from PymoNNto.Exploration.Network_UI.TabBase import *\n\nclass sidebar_activity_sub_module(TabBase):\n\n def __init__(self, add_color_dict={'output': (255, 255, 255), 'Input_Mask': (-100, -100, -100)}):\n self.add_color_dict = add_color_dict\n self.compiled={}\n for param in self.add_color_dict:\n self.compiled[param] = compile('n.'+param, '', 'eval')\n\n def add_recorder_variables(self, neuron_group, Network_UI):\n return\n\n def initialize(self, Network_UI, index):\n\n def mce(event):\n Network_UI.neuron_select_group = event.currentItem.neuron_group_tag\n w = Network_UI.network[Network_UI.neuron_select_group, 0].width\n h = Network_UI.network[Network_UI.neuron_select_group, 0].height\n Network_UI.neuron_select_y = np.clip(int((h - 1) - np.trunc(event.pos().y())), 0, h - 1)\n Network_UI.neuron_select_x = np.clip(int(np.trunc(event.pos().x())), 0, w - 1)\n Network_UI.neuron_select_id = Network_UI.neuron_select_y * w + Network_UI.neuron_select_x\n Network_UI.static_update_func()\n\n group_select_box=QComboBox()\n Network_UI.Add_Sidebar_Element(group_select_box)\n\n Network_UI.group_sliders.append(QSlider(1)) # QtCore.Horizontal\n Network_UI.group_sliders[-1].setMinimum(0)\n Network_UI.group_sliders[-1].setMaximum(100)\n Network_UI.group_sliders[-1].setSliderPosition(100)\n Network_UI.group_sliders[-1].mouseReleaseEvent = Network_UI.static_update_func\n Network_UI.group_sliders[-1].setToolTip('scale neuron-group plots up and down (only visualization)')\n\n Network_UI.sidebar_hblock.addWidget(Network_UI.group_sliders[-1])\n\n self.image_item = Network_UI.Add_Image_Item(False, True, tooltip_message='white: active neurons\\r\\ndarker color: primary input neurons\\r\\ngreen: selected neuron')\n\n self.image_item.neuron_group_tag = Network_UI.group_tags[index]\n Network_UI.neuron_visible_groups.append(Network_UI.group_tags[index])\n self.image_item.mouseClickEvent = mce\n\n def group_changed(select_index):\n tag=Network_UI.group_tags[select_index]\n Network_UI.neuron_select_group = tag\n self.image_item.neuron_group_tag = tag\n Network_UI.neuron_visible_groups[index] = tag\n Network_UI.neuron_select_id = 0\n\n group_select_box.addItems(Network_UI.group_tags)\n group_select_box.setCurrentIndex(index)\n group_select_box.currentIndexChanged.connect(group_changed)\n\n\n\n def update(self, Network_UI):\n\n #for group_tag in Network_UI.group_tags:\n group_tag = self.image_item.neuron_group_tag\n if len(Network_UI.network[group_tag]) > 0:\n\n group = Network_UI.network[group_tag, 0]\n n=group #for eval operations\n\n alpha = group.color[3] / 255.0\n base_color = (group.color[0] * alpha, group.color[1] * alpha, group.color[2] * alpha)\n\n image=np.zeros((group.size,3))\n\n for i in range(3):\n image[:, i] += base_color[i]\n\n if Network_UI.neuron_select_group == group_tag:\n for i in range(3):\n image[Network_UI.neuron_select_id, i] = Network_UI.neuron_select_color[i]\n\n for param, color in self.add_color_dict.items():\n try:\n #if True:#hasattr(group, param):\n data=eval(self.compiled[param])\n\n if (type(data) == np.ndarray and data.dtype == np.dtype('bool')) or (type(data) == bool):\n for i in range(3):\n image[data, i] += color[i]\n else:\n for i in range(3):\n image[:, i] += color[i]*data\n except:\n print(param, \"can not be evaluated\")\n\n image=np.reshape(image, (group.height, group.width,3))\n self.image_item.setImage(np.rot90(image, 3), levels=(0, 255))\n\nclass UI_sidebar_activity_module():\n\n def __init__(self, group_display_count=1, add_color_dict={'output': (255, 255, 255), 'Input_Mask': (-100, -100, -100)}):\n self.group_display_count=group_display_count\n self.add_color_dict=add_color_dict\n\n def add_recorder_variables(self, neuron_group, Network_UI):\n for module in self.sub_modules:\n module.add_recorder_variables(neuron_group, Network_UI)\n\n def initialize(self, SORN_UI):\n\n if SORN_UI.group_display_count is not None:\n self.group_display_count=SORN_UI.group_display_count\n\n self.sub_modules = []\n for i in range(self.group_display_count):\n self.sub_modules.append(sidebar_activity_sub_module(add_color_dict=self.add_color_dict))\n self.sub_modules[-1].initialize(SORN_UI, np.minimum(i, len(SORN_UI.group_tags)))\n\n def update(self, SORN_UI):\n for module in self.sub_modules:\n module.update(SORN_UI)","sub_path":"Exploration/Network_UI/Basic_Tabs/sidebar_activity_module.py","file_name":"sidebar_activity_module.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"642506509","text":"\n\nfrom xai.brain.wordbase.verbs._broil import _BROIL\n\n#calss header\nclass _BROILS(_BROIL, ):\n\tdef __init__(self,): \n\t\t_BROIL.__init__(self)\n\t\tself.name = \"BROILS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"broil\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_broils.py","file_name":"_broils.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"404922165","text":"import pandas as pd\nimport geopandas as gpd\nimport networkx as nx\nfrom shapely.geometry import LineString, Point\nfrom shapely.ops import transform\nimport matplotlib.pyplot as plt\nfrom shapely.ops import nearest_points\n\n\ndef constructSeqLine(df, idColumn='id', seqColumn='seq_id', x='x', y='y'):\n df = df.sort_values([seqColumn])\n grouped = df.groupby(idColumn)\n rows = []\n for name,group in grouped:\n line_coords = group[[x, y]]\n line = LineString(tuple(x) for x in line_coords.to_records(index=False))\n rows.append( (name, line) )\n return pd.DataFrame.from_records(rows, columns=[idColumn, 'geometry'])\n\ndef readGTFS(gtfsFolder, trip='trip.csv', stoptime='stoptime.csv', shape='shape.csv', stop='stops.csv'):\n # read\n gtfs_trips_df = pd.read_csv(gtfsFolder + trip)\n gtfs_stoptime_df = pd.read_csv(gtfsFolder + stoptime)\n gtfs_shape_df = pd.read_csv(gtfsFolder + shape)\n gtfs_stop_df = pd.read_csv(gtfsFolder + stop)\n # gtfs_stop_df = pd.read_csv(gtfsFolder + 'stops.txt')\n return gtfs_trips_df, gtfs_stoptime_df, gtfs_shape_df, gtfs_stop_df\n\ndef getRoadNetworkGeos(simFolder, fromCRS, toCRS):\n # segmentCoords = pd.read_csv(simFolder + 'segment-nodes.csv') #id,x,y,z,seq_id\n segmentCoords = pd.read_csv(simFolder + 'segment_polyline.csv')\n segmentGeo = constructSeqLine(segmentCoords)\n segmentGeo = gpd.GeoDataFrame(segmentGeo, crs=fromCRS)\n segmentGeo = segmentGeo.to_crs(toCRS)\n return segmentGeo\n\ndef getBusRouteGeo(busStops, busShapes, fromCRS, toCRS):\n busStopGeo = [Point(xy) for xy in zip(busStops.stop_lon, busStops.stop_lat)]\n busStopGeo = gpd.GeoDataFrame(busStops, crs=fromCRS, geometry=busStopGeo)\n busStopGeo = busStopGeo.to_crs(toCRS)\n busShapeGeo = constructSeqLine(busShapes, idColumn= 'shape_id', seqColumn='shape_pt_sequence', x='shape_pt_lon', y='shape_pt_lat')\n busGeo = gpd.GeoDataFrame(busShapeGeo, crs=fromCRS)\n busGeo = busGeo.to_crs(toCRS)\n return busStopGeo, busGeo\n\ndef getSegmentsWithEndNodes(simFolder, candidateSegment, CRS, base = 10000000):\n # turningPaths = pd.read_csv(simFolder + 'turning-attributes.csv') #id,from_lane,to_lane,group_id,max_speed,tags\n turningPaths = pd.read_csv(simFolder + 'turning_path.csv')\n turningPaths[\"from_segment\"] = turningPaths[\"from_lane\"] // 100\n turningPaths[\"to_segment\"] = turningPaths[\"to_lane\"] // 100\n connector = pd.read_csv(simFolder + 'connector.csv') #id,from_segment,to_segment,from_lane,to_lane,is_true_connector,tags\n\n connectSegments = list(zip(turningPaths.from_segment, turningPaths.to_segment))\n connectSegments += list(zip(connector.from_segment, connector.to_segment))\n\n # Not necessary to include the following code since turning paths and connectors are enough.\n # segments = segments.sort_values(['id'])\n # segSequence = segments.groupby('link_id')['id'].apply(list).tolist()\n # for seq in segSequence:\n # if len(seq) > 1:\n # connectSegments += list(zip(seq[:-1],seq[1:]))\n\n fromPoint = {} # seg --> node\n toPoint = {}\n NODE_ID = 1\n candidateSegIDs = set(candidateSegment.id.tolist())\n # Create nodes between segments fromPoint --> seg1 --> (toPoint) = (fromPoint) --> seg2\n for seg1, seg2 in connectSegments:\n # We are interested in only candidate segments\n if seg1 in candidateSegIDs and seg2 in candidateSegIDs:\n if seg1 in toPoint and seg2 in fromPoint:\n assert(toPoint[seg1] == fromPoint[seg2])\n elif seg1 in toPoint:\n fromPoint[seg2] = toPoint[seg1]\n elif seg2 in fromPoint:\n toPoint[seg1] = fromPoint[seg2]\n else:\n toPoint[seg1] = fromPoint[seg2] = NODE_ID\n NODE_ID += 1\n # Have to give nodes for dead ends\n for seg in candidateSegIDs:\n if seg not in toPoint: # seg --> toPoint --> None\n toPoint[seg] = NODE_ID\n NODE_ID += 1\n if seg not in fromPoint: # None --> fromPoint --> seg\n fromPoint[seg] = NODE_ID\n NODE_ID += 1\n if seg not in fromPoint: # None --> fromPoint --> seg\n fromPoint[seg] = NODE_ID\n NODE_ID += 1\n\n print('MAX Node id ', NODE_ID)\n candidateSegment['from_node'] = candidateSegment.apply(lambda row: fromPoint[int(row.id)] if int(row.id) in fromPoint else row.link_id * base + row.sequence - 1, axis=1)\n candidateSegment['to_node'] = candidateSegment.apply(lambda row: toPoint[int(row.id)] if int(row.id) in toPoint else row.link_id * base + row.sequence, axis=1)\n candidateSegment['from_node'] = candidateSegment['from_node'].astype('int')\n candidateSegment['to_node'] = candidateSegment['to_node'].astype('int')\n candidateSegment['ends'] = candidateSegment.apply(lambda row: str(int(row.from_node)) + '_' + str(int(row.to_node)), axis=1)\n print(\"Number of segments and unique ends: \", len(candidateSegment), len(candidateSegment.ends.unique()))\n return candidateSegment\n\n\ndef findRouteCandidateSegments(segmentsWithNodes, busShapes, processFolder, bufferSize=50):\n busShapes['geometry'] = busShapes['geometry'].buffer(distance=bufferSize)\n candidateShapeSegments = gpd.sjoin(segmentsWithNodes,busShapes, op='intersects')\n # candidateShapeSegments.to_file(processFolder + 'busShape')\n return candidateShapeSegments\n\ndef getUniqueBusRoutes(stoptime_df, trips_df):\n # Each shape is an unique trip\n trips_df.drop_duplicates(subset=['shape_id'], inplace=True)\n unique_trips = trips_df.trip_id.unique()\n stoptime_df = stoptime_df[stoptime_df.trip_id.isin(unique_trips)]\n stoptime_df.sort_values(by=['trip_id', 'stop_sequence'], inplace=True)\n trip_stops = stoptime_df.groupby('trip_id')['stop_id'].apply(list).to_frame()\n trip_stops = trip_stops.reset_index()\n trip_stops = trip_stops.merge(trips_df[['trip_id', 'shape_id']], on='trip_id', how='left')\n print('Unique trips ', len(unique_trips))\n return trip_stops\n\ndef getShortestPath(trip_stops, shapeSegments, stopSegmentEnd):\n stopSegmentEnd.index = stopSegmentEnd.stop_id\n valid_stops = stopSegmentEnd[stopSegmentEnd['distance'] < 500].stop_id.tolist()\n\n stopConnectionSet = set()\n stopConnection_df = []\n num_no_connection = 0\n for indx, trip in trip_stops.iterrows():\n # print('trip being.. ', indx)\n # Filter trip route segments\n routeSegments = shapeSegments[shapeSegments['shape_id'] == trip.shape_id]\n # print('routeSegments', len(routeSegments))\n edgeList = list(zip(routeSegments['from_node'], routeSegments['to_node']))\n G = nx.MultiDiGraph()\n G.add_edges_from(edgeList)\n\n # Search connection between consequent stops\n consequentStops = zip(trip.stop_id[:-1], trip.stop_id[1:])\n for startStop, endStop in consequentStops:\n # print(startStop, endStop)\n if ((startStop, endStop) not in stopConnectionSet) and (startStop in valid_stops) and (endStop in valid_stops):\n startNode = stopSegmentEnd.loc[startStop, 'from_node']\n endNode = stopSegmentEnd.loc[endStop ,'from_node']\n if startNode in G and endNode in G:\n try:\n nodePath = nx.shortest_path(G, source=startNode, target=endNode)\n stopConnectionSet.add((startStop, endStop))\n stopConnection_df.append((startStop, endStop, nodePath))\n\n if startNode != nodePath[0] or endNode != nodePath[-1]:\n print(startStop, endStop, nodePath)\n except nx.exception.NetworkXNoPath:\n # print('No connection in between ', startStop, endStop)\n num_no_connection += 1\n pass\n stopConnection_df = pd.DataFrame.from_records(stopConnection_df, columns=['startStop', 'endStop', 'nodePath'])\n print('Number of not connected ', num_no_connection)\n print('Number of connected ', len(stopConnection_df))\n return stopConnection_df\n","sub_path":"process-gtfs/bus/process_helper2.py","file_name":"process_helper2.py","file_ext":"py","file_size_in_byte":8079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"223545402","text":"# 本代码用requests进行网页请求,返回的是json,直接解析数据\n\nimport requests\nfrom requests.exceptions import RequestException\nfrom urllib.parse import urlencode\nimport json\nimport time\nimport random\nimport pymongo\n\nclient = pymongo.MongoClient()\ndb = client['jingdong']\nheaders = {\n 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac OS X 10_12_4)'\n 'AppleWebKit/537.36(KHTML,Like Gecko) Chrome/57.0.2987.133 Safari/537.36',\n}\n\ndef get_html(i):\n # global proxies\n # proxy = get_proxy()\n # if proxy:\n # proxies = {\n # 'https':'http://' + proxy[:-2]\n # }\n data = {\n 'productId': productid,\n 'score': '0',\n 'sortType': '5',\n 'page': i,\n 'pageSize': 10,\n }\n url = 'https://sclub.jd.com/comment/productPageComments.action?' + urlencode(data)\n try:\n # response = requests.get(url,headers=headers,proxies=proxies,allow_redirects=False)\n response = requests.get(url,headers=headers)\n print(response.status_code)\n time.sleep(random.random()*3)\n if response.status_code == 200:\n return response.text\n if response.status_code == 302:\n return get_html(i)\n else:\n return None\n except RequestException:\n print('获取页面出错',i)\n return None\n\ndef get_proxy():\n url = 'http://127.0.0.1:5000/get'\n try:\n response = requests.get(url)\n time.sleep(random.random() * 5)\n if response.status_code == 200:\n return response.text\n return None\n except ConnectionError:\n return None\n\ndef judge_end(html):\n try:\n dict = json.loads(html)\n comments = dict['comments']\n if len(comments) == 0:\n return True\n else:\n return False\n except:\n print('判断是否结束出错')\n\ndef get_product(html):\n for data in parse(html):\n save_to_mongo(data)\n\ndef parse(html):\n try:\n dict = json.loads(html)\n infos = dict['comments']\n for info in infos:\n try:\n name = info['nickname']\n comment = info['content']\n c_time = info['creationTime']\n color = info['productColor']\n yield {\n 'name':name,\n 'comment':comment,\n 'time':c_time,\n 'color':color\n }\n except:\n print('解析商品出错')\n except:\n print('解析页面出错')\n\ndef save_to_mongo(data):\n global productid\n try:\n db[productid].insert(data)\n print('存储成功',data['name'])\n except:\n print('存储失败',data['name'])\n\ndef main():\n i = 0\n is_end = False\n html = get_html(i)\n while not is_end:\n get_product(html)\n i += 1\n html = get_html(i)\n is_end = judge_end(html)\n\nif __name__ == '__main__':\n global productid\n productid = '3133847'\n main()","sub_path":"jingdongcomment.py","file_name":"jingdongcomment.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"92019862","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/kieffer/workspace/fabio/build/lib.macosx-10.6-intel-3.5/fabio/compression/compression.py\n# Compiled at: 2020-04-03 09:02:03\n# Size of source mod 2**32: 15532 bytes\n\"\"\"Compression and decompression algorithm for various formats\n\nAuthors: Jérôme Kieffer, ESRF\n email:jerome.kieffer@esrf.fr\n\n\"\"\"\nfrom __future__ import absolute_import, print_function, with_statement, division\n__author__ = 'Jérôme Kieffer'\n__contact__ = 'jerome.kieffer@esrf.eu'\n__license__ = 'MIT'\n__date__ = '22/10/2018'\n__copyright__ = 'European Synchrotron Radiation Facility, Grenoble, France'\nimport sys, base64, hashlib, logging, subprocess, numpy\nlogger = logging.getLogger(__name__)\nfrom ..third_party import six\ntry:\n from ..third_party import gzip\nexcept ImportError:\n logger.error('Unable to import gzip module: disabling gzip compression')\n gzip = None\n\ntry:\n import bz2\nexcept ImportError:\n logger.error('Unable to import bz2 module: disabling bz2 compression')\n bz2 = None\n\ntry:\n import zlib\nexcept ImportError:\n logger.error('Unable to import zlib module: disabling zlib compression')\n zlib = None\n\nif sys.platform != 'win32':\n WindowsError = OSError\n\ndef is_incomplete_gz_block_exception(exception):\n \"\"\"True if the exception looks to be generated when a GZ block is\n incomplete.\n\n :rtype: bool\n \"\"\"\n if six.PY2:\n if isinstance(exception, IOError):\n return 'CRC check failed' in exception.args[0]\n elif six.PY3:\n version = sys.version_info[0:2]\n if version == (3, 3):\n import struct\n return isinstance(exception, struct.error)\n return isinstance(exception, EOFError)\n return False\n\n\ndef md5sum(blob):\n \"\"\"\n returns the md5sum of an object...\n \"\"\"\n return base64.b64encode(hashlib.md5(blob).digest())\n\n\ndef endianness():\n \"\"\"\n Return the native endianness of the system\n \"\"\"\n if numpy.little_endian:\n return 'LITTLE_ENDIAN'\n else:\n return 'BIG_ENDIAN'\n\n\nclass ExternalCompressors(object):\n __doc__ = 'Class to handle lazy discovery of external compression programs'\n COMMANDS = {'.bz2': ['bzip2-dcf'], \n '.gz': ['gzip', '-dcf']}\n\n def __init__(self):\n \"\"\"Empty constructor\"\"\"\n self.compressors = {}\n\n def __getitem__(self, key):\n \"\"\"Implement the dict-like behavior\"\"\"\n if key not in self.compressors:\n if key in self.COMMANDS:\n commandline = self.COMMANDS[key]\n testline = [commandline[0], '-h']\n try:\n lines = subprocess.check_output(testline, stderr=subprocess.STDOUT, universal_newlines=True)\n if 'usage' in lines.lower():\n self.compressors[key] = commandline\n else:\n self.compressors[key] = None\n except (subprocess.CalledProcessError, WindowsError) as err:\n logger.debug('No %s utility found: %s', commandline[0], err)\n self.compressors[key] = None\n\n else:\n self.compressors[key] = None\n return self.compressors[key]\n\n\nCOMPRESSORS = ExternalCompressors()\n\ndef decGzip(stream):\n \"\"\"Decompress a chunk of data using the gzip algorithm from system or from Python\n\n :param stream: compressed data\n :return: uncompressed stream\n\n \"\"\"\n\n def _python_gzip(stream):\n \"\"\"Inefficient implementation based on loops in Python\"\"\"\n for i in range(1, 513):\n try:\n fileobj = six.BytesIO(stream[:-i])\n uncompessed = gzip.GzipFile(fileobj=fileobj).read()\n except IOError:\n logger.debug(\"trying with %s bytes less, doesn't work\" % i)\n else:\n return uncompessed\n\n if gzip is None:\n raise ImportError('gzip module is not available')\n fileobj = six.BytesIO(stream)\n try:\n uncompessed = gzip.GzipFile(fileobj=fileobj).read()\n except IOError:\n logger.warning('Encounter the python-gzip bug with trailing garbage, trying subprocess gzip')\n cmd = COMPRESSORS['.gz']\n if cmd:\n try:\n sub = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)\n uncompessed, err = sub.communicate(input=stream)\n logger.debug('Gzip subprocess ended with %s err= %s; I got %s bytes back' % (sub.wait(), err, len(uncompessed)))\n except OSError as error:\n logger.warning('Unable to use the subprocess gzip (%s). Is gzip available? ' % error)\n uncompessed = _python_gzip(stream)\n\n else:\n uncompessed = _python_gzip(stream)\n if uncompessed is None:\n logger.error('I am totally unable to read this gzipped compressed data block, giving up')\n\n return uncompessed\n\n\ndef decBzip2(stream):\n \"\"\"\n Decompress a chunk of data using the bzip2 algorithm from Python\n \"\"\"\n if bz2 is None:\n raise ImportError('bz2 module is not available')\n return bz2.decompress(stream)\n\n\ndef decZlib(stream):\n \"\"\"\n Decompress a chunk of data using the zlib algorithm from Python\n \"\"\"\n if zlib is None:\n raise ImportError('zlib module is not available')\n return zlib.decompress(stream)\n\n\ndef decByteOffset_numpy(stream, size=None, dtype='int64'):\n \"\"\"\n Analyze a stream of char with any length of exception:\n 2, 4, or 8 bytes integers\n\n :param stream: string representing the compressed data\n :param size: the size of the output array (of longInts)\n :return: 1D-ndarray\n\n \"\"\"\n logger.debug('CBF decompression using Numpy')\n listnpa = []\n key16 = b'\\x80'\n key32 = b'\\x00\\x80'\n key64 = b'\\x00\\x00\\x00\\x80'\n shift = 1\n while True:\n idx = stream.find(key16)\n if idx == -1:\n listnpa.append(numpy.frombuffer(stream, dtype=numpy.int8))\n break\n listnpa.append(numpy.frombuffer(stream[:idx], dtype=numpy.int8))\n if stream[idx + 1:idx + 3] == key32:\n if stream[idx + 3:idx + 7] == key64:\n res = numpy.frombuffer(stream[idx + 7:idx + 15], dtype=numpy.int64)\n listnpa.append(res)\n shift = 15\n else:\n res = numpy.frombuffer(stream[idx + 3:idx + 7], dtype=numpy.int32)\n listnpa.append(res)\n shift = 7\n else:\n res = numpy.frombuffer(stream[idx + 1:idx + 3], dtype=numpy.int16)\n listnpa.append(res)\n shift = 3\n stream = stream[idx + shift:]\n\n if not numpy.little_endian:\n for res in listnpa:\n if res.dtype != numpy.int8:\n res.byteswap(True)\n\n return numpy.ascontiguousarray(numpy.hstack(listnpa), dtype).cumsum()\n\n\ndef decByteOffset_cython(stream, size=None, dtype='int64'):\n \"\"\"\n Analyze a stream of char with any length of exception:\n 2, 4, or 8 bytes integers\n\n :param stream: string representing the compressed data\n :param size: the size of the output array (of longInts)\n :return: 1D-ndarray\n\n \"\"\"\n logger.debug('CBF decompression using cython')\n try:\n from ..ext import byte_offset\n except ImportError as error:\n logger.error('Failed to import byte_offset cython module, falling back on numpy method: %s', error)\n return decByteOffset_numpy(stream, size, dtype=dtype)\n else:\n if dtype == 'int32':\n return byte_offset.dec_cbf32(stream, size)\n else:\n return byte_offset.dec_cbf(stream, size)\n\n\ndecByteOffset = decByteOffset_cython\n\ndef compByteOffset_numpy(data):\n \"\"\"\n Compress a dataset into a string using the byte_offet algorithm\n\n :param data: ndarray\n :return: string/bytes with compressed data\n\n test = numpy.array([0,1,2,127,0,1,2,128,0,1,2,32767,0,1,2,32768,0,1,2,2147483647,0,1,2,2147483648,0,1,2,128,129,130,32767,32768,128,129,130,32768,2147483647,2147483648])\n\n \"\"\"\n flat = numpy.ascontiguousarray(data.ravel(), numpy.int64)\n delta = numpy.zeros_like(flat)\n delta[0] = flat[0]\n delta[1:] = flat[1:] - flat[:-1]\n mask = abs(delta) > 127\n exceptions = numpy.nonzero(mask)[0]\n if numpy.little_endian:\n byteswap = False\n else:\n byteswap = True\n start = 0\n binary_blob = b''\n for stop in exceptions:\n if stop - start > 0:\n binary_blob += delta[start:stop].astype(numpy.int8).tobytes()\n exc = delta[stop]\n absexc = abs(exc)\n if absexc > 2147483647:\n binary_blob += b'\\x80\\x00\\x80\\x00\\x00\\x00\\x80'\n if byteswap:\n binary_blob += delta[stop:stop + 1].byteswap().tobytes()\n else:\n binary_blob += delta[stop:stop + 1].tobytes()\n else:\n if absexc > 32767:\n binary_blob += b'\\x80\\x00\\x80'\n if byteswap:\n binary_blob += delta[stop:stop + 1].astype(numpy.int32).byteswap().tobytes()\n else:\n binary_blob += delta[stop:stop + 1].astype(numpy.int32).tobytes()\n else:\n binary_blob += b'\\x80'\n if byteswap:\n binary_blob += delta[stop:stop + 1].astype(numpy.int16).byteswap().tobytes()\n else:\n binary_blob += delta[stop:stop + 1].astype(numpy.int16).tobytes()\n start = stop + 1\n\n if start < delta.size:\n binary_blob += delta[start:].astype(numpy.int8).tobytes()\n return binary_blob\n\n\ndef compByteOffset_cython(data):\n \"\"\"\n Compress a dataset into a string using the byte_offet algorithm\n\n :param data: ndarray\n :return: string/bytes with compressed data\n\n test = numpy.array([0,1,2,127,0,1,2,128,0,1,2,32767,0,1,2,32768,0,1,2,2147483647,0,1,2,2147483648,0,1,2,128,129,130,32767,32768,128,129,130,32768,2147483647,2147483648])\n\n \"\"\"\n logger.debug('CBF compression using cython')\n try:\n from ..ext import byte_offset\n except ImportError as error:\n logger.error('Failed to import byte_offset cython module, falling back on numpy method: %s', error)\n return compByteOffset_numpy(data)\n else:\n if 'int32' in str(data.dtype):\n return byte_offset.comp_cbf32(data).tobytes()\n else:\n return byte_offset.comp_cbf(data).tobytes()\n\n\ncompByteOffset = compByteOffset_cython\n\ndef decTY1(raw_8, raw_16=None, raw_32=None):\n \"\"\"\n Modified byte offset decompressor used in Oxford Diffraction images\n\n Note: Always expect little endian data on the disk\n\n :param raw_8: strings containing raw data with integer 8 bits\n :param raw_16: strings containing raw data with integer 16 bits\n :param raw_32: strings containing raw data with integer 32 bits\n :return: numpy.ndarray\n\n \"\"\"\n data = numpy.frombuffer(raw_8, dtype=numpy.uint8).astype(int) - 127\n if raw_32 is not None:\n int32 = numpy.frombuffer(raw_32, dtype=numpy.int32)\n if not numpy.little_endian:\n int32.byteswap(True)\n exception32 = numpy.where(data == 128)\n if raw_16 is not None:\n int16 = numpy.frombuffer(raw_16, dtype='int16')\n if not numpy.little_endian:\n int16.byteswap(True)\n exception16 = numpy.where(data == 127)\n data[exception16] = int16\n if raw_32:\n data[exception32] = int32\n summed = data.cumsum()\n smax = summed.max()\n if smax > 2147483647:\n bytecode = 'int64'\n else:\n if smax > 32767:\n bytecode = 'int32'\n else:\n if smax > 127:\n bytecode = 'int16'\n else:\n bytecode = 'int8'\n return summed.astype(bytecode)\n\n\ndecKM4CCD = decTY1\n\ndef compTY1(data):\n \"\"\"\n Modified byte offset compressor used in Oxford Diffraction images\n\n :param data: numpy.ndarray with the input data (integers!)\n :return: 3-tuple of strings: raw_8,raw_16,raw_32 containing raw data with integer of the given size\n\n \"\"\"\n fdata = data.ravel()\n diff = numpy.zeros_like(fdata)\n diff[0] = fdata[0]\n diff[1:] = fdata[1:] - fdata[:-1]\n adiff = abs(diff)\n exception32 = adiff > 32767\n exception16 = (adiff >= 127) ^ exception32\n we16 = numpy.where(exception16)\n we32 = numpy.where(exception32)\n data_16 = diff[we16].astype(numpy.int16)\n data_32 = diff[we32].astype(numpy.int32)\n if not numpy.little_endian:\n data_16.byteswap(True)\n data_32.byteswap(True)\n diff[we16] = 127\n diff[we32] = 128\n diff += 127\n data_8 = diff.astype(numpy.uint8)\n return (data_8.tobytes(), data_16.tobytes(), data_32.tobytes())\n\n\ndef decPCK(stream, dim1=None, dim2=None, overflowPix=None, version=None, normal_start=None, swap_needed=None):\n \"\"\"\n Modified CCP4 pck decompressor used in MAR345 images\n\n :param raw: input string (bytes in python3)\n :param dim1,dim2: optional parameters size\n :param overflowPix: optional parameters: number of overflowed pixels\n :param version: PCK version 1 or 2\n :param normal_start: position of the normal value section (can be auto-guessed)\n :param swap_needed: set to True when reading data from a foreign endianness (little on big or big on little)\n :return: ndarray of 2D with the right size\n\n \"\"\"\n try:\n from ..ext.mar345_IO import uncompress_pck\n except ImportError as error:\n raise RuntimeError('Unable to import mar345_IO to read compressed dataset: %s' % error)\n\n if 'seek' in dir(stream):\n stream.seek(0)\n raw = stream.read()\n else:\n raw = six.binary_type(stream)\n return uncompress_pck(raw, dim1, dim2, overflowPix, version, normal_start, swap_needed)\n\n\ndef compPCK(data):\n \"\"\"\n Modified CCP4 pck compressor used in MAR345 images\n\n :param data: numpy.ndarray (square array)\n :return: compressed stream\n\n \"\"\"\n try:\n from ..ext.mar345_IO import compress_pck\n except ImportError as error:\n raise RuntimeError('Unable to import mar345_IO to write compressed dataset: %s' % error)\n\n return compress_pck(data)","sub_path":"pycfiles/fabio-0.10.0-cp35-cp35m-macosx_10_6_intel/compression.cpython-35.py","file_name":"compression.cpython-35.py","file_ext":"py","file_size_in_byte":14323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"410165521","text":"# encoding: utf-8\n\nimport logging\nimport sqlalchemy\n\nfrom ckan import model\nfrom ckan.plugins.toolkit import config\n\nfrom .model import Comment, CommentThread\nfrom .notification_models import CommentNotificationRecipient\n\n_and_ = sqlalchemy.and_\nlog = logging.getLogger(__name__)\n\n\ndef comment_notification_recipients_enabled():\n return config.get('ckan.comments.follow_mute_enabled', False)\n\n\ndef get_thread_comment_or_both(thread_or_comment_id):\n \"\"\"\n Determine if provided ID is for a thread or comment\n :param thread_or_comment_id: UUID - can be either a thread ID (in the YTP sense) or a comment ID\n :return: CommentThread object, and Comment object (if applicable)\n \"\"\"\n thread = CommentThread.get(thread_or_comment_id)\n\n if thread:\n comment = None\n else:\n # Fallback: check for comment by id provided...\n comment = Comment.get(thread_or_comment_id)\n if comment:\n thread = CommentThread.get(comment.thread_id)\n\n return thread, comment\n\n\ndef get_existing_record(user_id, thread_id, comment_id=None):\n # Condition doesn't seem to get set properly within _and_ filter\n if not comment_id:\n comment_id = u''\n\n record = (\n model.Session.query(\n CommentNotificationRecipient\n )\n .filter(\n _and_(\n CommentNotificationRecipient.user_id == user_id,\n CommentNotificationRecipient.thread_id == thread_id,\n CommentNotificationRecipient.comment_id == comment_id\n )\n )\n ).first()\n\n return record\n\n\ndef get_comment_notification_records_for_user(user_id, thread_id):\n try:\n records = (\n model.Session.query(\n CommentNotificationRecipient\n )\n .filter(\n _and_(\n CommentNotificationRecipient.user_id == user_id,\n CommentNotificationRecipient.thread_id == thread_id\n )\n )\n )\n return records\n except Exception as e:\n log.error('Unable to retrieve comment notification statuses')\n log.error(str(e))\n\n\ndef get_user_comment_follow_mute_status(user_id, content_item_thread_id):\n following_content_item = False\n comments_following = []\n comments_muted = []\n\n for record in get_comment_notification_records_for_user(user_id, content_item_thread_id):\n if record.comment_id == u'':\n following_content_item = True\n elif record.action == 'follow':\n comments_following.append(record.comment_id)\n elif record.action == 'mute':\n comments_muted.append(record.comment_id)\n\n return following_content_item, comments_following, comments_muted\n\n\ndef remove_comment_notification_record(record):\n try:\n model.Session.delete(record)\n model.Session.commit()\n except Exception as e:\n log.error('Error removing `comment_notification_recipient` record:')\n log.error(str(e))\n\n\ndef remove_existing_follows_for_user(user_id, thread_id):\n follows = get_comment_notification_records_for_user(user_id, thread_id)\n for record in follows:\n remove_comment_notification_record(record)\n\n\ndef add_comment_notification_record(user_id, thread_id, comment_id, notification_level, action):\n data_dict = {\n 'user_id': user_id,\n 'thread_id': thread_id,\n 'comment_id': comment_id,\n 'notification_level': notification_level,\n 'action': action\n }\n try:\n model.Session.add(CommentNotificationRecipient(**data_dict))\n model.Session.commit()\n except Exception as e:\n log.error('Error adding `comment_notification_recipient` record:')\n log.error(str(e))\n\n\ndef add_user_to_comment_notifications(user_id, thread_id, comment_id=u''):\n # Is the user attempting to follow at the dataset/data request or the comment level?\n notification_level = 'top_level_comment' if comment_id else 'content_item'\n add_comment_notification_record(user_id, thread_id, comment_id, notification_level, 'follow')\n\n\ndef add_commenter_to_comment_notifications(user_id, thread_id, comment_id=u''):\n existing_record = get_existing_record(user_id, thread_id, comment_id)\n if existing_record and existing_record.action == 'mute':\n remove_comment_notification_record(existing_record)\n add_user_to_comment_notifications(user_id, thread_id, comment_id)\n elif not existing_record or (existing_record and existing_record.action != 'follow'):\n add_user_to_comment_notifications(user_id, thread_id, comment_id)\n\n\ndef mute_comment_thread_for_user(user_id, thread_id, comment_id):\n add_comment_notification_record(user_id, thread_id, comment_id, 'top_level_comment', 'mute')\n\n\ndef process_follow_request(user_id, thread, comment, existing_record, notification_level):\n\n following_content_item, \\\n comments_following, \\\n comments_muted = get_user_comment_follow_mute_status(\n user_id,\n thread.id\n )\n\n if notification_level == 'content_item':\n # Check if user already following comments at content item level\n if following_content_item:\n return 'User already following comments at content item level'\n else:\n add_user_to_comment_notifications(user_id, thread.id)\n else:\n if comment.id in comments_following:\n return 'User already following thread'\n else:\n if comment.id in comments_muted and existing_record and existing_record.action == 'mute':\n # Remove existing mute record\n remove_comment_notification_record(existing_record)\n # If user is following comments at content item level and no mute record in place,\n # there is no need to add follow record for specific comment thread..\n if not following_content_item:\n add_user_to_comment_notifications(user_id, thread.id, comment.id)\n\n\ndef process_mute_request(user_id, thread, comment, existing_record, notification_level):\n\n following_content_item, \\\n comments_following, \\\n comments_muted = get_user_comment_follow_mute_status(\n user_id,\n thread.id\n )\n\n if notification_level == 'content_item':\n # When user mutes comments at content item level we remove ALL existing records for that user\n # in the `comment_notification_recipient` table for the matching YTP thread.id\n remove_existing_follows_for_user(user_id, thread.id)\n return 'Comments muted at content item level for user'\n elif comment.id in comments_muted:\n return 'Thread already muted for user'\n else:\n if comment.id in comments_following and existing_record and existing_record.action == 'follow':\n # Remove existing follow record\n remove_comment_notification_record(existing_record)\n # Only need to add mute record if user is following comments at content item level\n if comment.id not in comments_muted and following_content_item:\n mute_comment_thread_for_user(user_id, thread.id, comment.id)\n\n return 'Thread muted for user'\n\n\ndef get_comment_notification_recipients(action, user_email, thread_id, comment_id=None):\n try:\n if not comment_id:\n comment_id = u''\n\n session = model.Session\n emails = (\n session.query(\n model.User.email\n )\n .join(\n CommentNotificationRecipient,\n CommentNotificationRecipient.user_id == model.User.id\n )\n .filter(CommentNotificationRecipient.thread_id == thread_id)\n .filter(CommentNotificationRecipient.comment_id == comment_id)\n .filter(CommentNotificationRecipient.action == action)\n .filter(model.User.email != user_email)\n .group_by(model.User.email)\n )\n return [email[0] for email in emails.all()]\n except Exception as e:\n log.error('Exception raised in `get_comment_notification_recipients`')\n log.error(str(e))\n return []\n\n\ndef get_content_item_followers(user_email, thread_id):\n return get_comment_notification_recipients('follow', user_email, thread_id)\n\n\ndef get_top_level_comment_followers(user_email, thread_id, comment_id):\n return get_comment_notification_recipients('follow', user_email, thread_id, comment_id)\n\n\ndef get_top_level_comment_mutees(thread_id, comment_id):\n return get_comment_notification_recipients('mute', None, thread_id, comment_id)\n","sub_path":"ckanext/ytp/comments/notification_helpers.py","file_name":"notification_helpers.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239241252","text":"import requests\nfrom bs4 import BeautifulSoup\nimport redis\n\nfrom secrets import from_email, password, to_email, KEYWORDS, urls\n\n\ndef email():\n r = redis.Redis(host='localhost', port=6379, db=0)\n links = [r.get(k) for k in r.keys()]\n\n # email\n import smtplib\n\n from email.mime.multipart import MIMEMultipart\n from email.mime.text import MIMEText\n\n sender = from_email\n receiver = to_email\n\n # Create message container - the correct MIME type is multipart/alternative.\n msg = MIMEMultipart('alternative')\n msg['Subject'] = \"Link\"\n msg['From'] = sender\n msg['To'] = receiver\n\n html = \"\"\"\n

Hej på dig!

\n

Här kommer %s länkar som kan vara intressanta för dig baserade på dina keywords:

\n
    \n %s\n
\n

Dina keywords sedan tidigare är: %s

\n

 

\n \"\"\" % (len(links), \"\".join(['
  • {0}
  • '.format(link)\n for link in links]), \", \".join(KEYWORDS))\n\n # Record the MIME type text/html.\n part2 = MIMEText(html, 'html')\n\n # Attach parts into message container.\n # According to RFC 2046, the last part of a multipart message, in this case\n # the HTML message, is best and preferred.\n msg.attach(part2)\n\n try:\n # Send the message via local SMTP server.\n mail = smtplib.SMTP('smtp.gmail.com', 587)\n mail.ehlo()\n mail.starttls()\n\n mail.login(sender, password)\n mail.sendmail(sender, receiver, msg.as_string())\n mail.quit()\n except Exception as e:\n print(\"Error \", e, \" occurred.\")\n\n # empty db\n r.flushdb()\n print(\"Email sent and db is flushed.\")\n\n\nclass Scraper:\n def __init__(self, keywords):\n #self.markup = requests.get(url=urls[0]).text # test with only one url\n self.keywords = keywords\n\n def parse(self):\n links = []\n for url in urls:\n markup = requests.get(url=url).text\n soup = BeautifulSoup(markup, 'html.parser')\n\n links += soup.findAll(\"a\", {\"class\": \"storylink\"}) # specific to \"Hacker News\" site.\n links += soup.findAll(\"h3\", {\"class\": \"post-item_title\"})\n links += soup.findAll(\"a\", {\"class\": \"blog_post_card__title-link\"})\n #links = soup.findAll(\"h3\", {\"class\": \"t-entry-title h3\"})\n\n self.saved_links = []\n for link in links:\n for keyword in self.keywords:\n if keyword in link.text:\n self.saved_links.append(link)\n\n def store(self):\n r = redis.Redis(host='localhost', port=6379, db=0)\n for link in self.saved_links:\n r.set(link.text, str(link))\n\n\ns = Scraper(KEYWORDS)\ns.parse()\ns.store()\nemail()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"512380211","text":"import os\nfrom xml.etree import ElementTree as ET\n\nfrom django.contrib.gis.geos import Point\nfrom django.core.management.base import BaseCommand\n\nfrom core.lib import geo\nfrom erp.models import Accessibilite, Activite, Commune, Erp\nfrom erp.provider import arrondissements\n\nVALEURS_VIDES = [\n \"nr\",\n \"non renseigné\",\n \"non renseignée\",\n \"Non renseigné(e)\",\n \"#N/A\",\n]\n\n\ndef clean(string):\n if string in VALEURS_VIDES:\n return \"\"\n return str(string).replace(\"\\n\", \" \").replace(\"«\", \"\").replace(\"»\", \"\").replace(\"’\", \"'\").replace('\"', \"\").strip()\n\n\ndef clean_commune(string):\n return clean(\"\".join(i for i in string if not i.isdigit()))\n\n\ndef extract(xml, fieldname=None, attribute=None):\n if fieldname:\n field = xml.find(f\"{fieldname}\")\n else:\n field = xml\n if field is not None and not attribute:\n string = field.text\n else:\n if hasattr(field, \"attrib\"):\n string = field.attrib[attribute]\n else:\n return \"\"\n return clean(string)\n\n\ndef extract_adresse(xml, fieldname):\n fields = xml.findall(f\"{fieldname}\")\n num = lieu_dit = ligne = None\n\n if len(fields) > 1:\n lieu_dit = fields[0].text\n try:\n num, ligne = fields[1].text.split(None, 1)\n except Exception:\n ligne = fields[1].text\n elif len(fields) == 1:\n lieu_dit = None\n try:\n num, ligne = fields[0].text.split(None, 1)\n except Exception:\n ligne = fields[0].text\n return num, ligne, lieu_dit\n\n\nclass Command(BaseCommand):\n help = \"Importe les données Service Public\"\n activites = {}\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--forceupdate\",\n action=\"store_true\",\n help=\"Forcer la mise à jour de la fiche ERP.\",\n )\n\n def handle_5digits_code(self, cpost):\n cpost = clean(cpost).strip()\n if len(cpost) == 4:\n return \"0\" + cpost\n return cpost\n\n def import_row(self, xml, **kwargs):\n fields = {}\n fields[\"source\"] = \"service_public\"\n fields[\"source_id\"] = extract(xml, attribute=\"id\")\n fields[\"nom\"] = extract(xml, fieldname=\"Nom\")\n fields[\"telephone\"] = extract(xml, fieldname=\"*Téléphone\")\n fields[\"contact_email\"] = extract(xml, fieldname=\"*Email\")\n fields[\"site_internet\"] = extract(xml, fieldname=\"*Url\")\n\n fields[\"code_insee\"] = self.handle_5digits_code(extract(xml, attribute=\"codeInsee\"))\n num, voie, lieu_dit = extract_adresse(xml, fieldname=\"*Ligne\")\n fields[\"numero\"] = num\n fields[\"lieu_dit\"] = lieu_dit\n fields[\"voie\"] = voie\n fields[\"code_postal\"] = self.handle_5digits_code(extract(xml, fieldname=\"*CodePostal\"))\n fields[\"commune\"] = clean_commune(extract(xml, fieldname=\"*NomCommune\"))\n fields[\"commune_ext_id\"] = self._retrieve_or_create_commune_ext(\n commune=fields[\"commune\"],\n code_insee=fields[\"code_insee\"],\n code_postal=fields[\"code_postal\"],\n xml=xml,\n )\n lat = extract(xml, fieldname=\"**Latitude\")\n long = extract(xml, fieldname=\"**Longitude\")\n if lat != \"None\" and long != \"None\" and (lat and long):\n fields[\"geom\"] = geo.parse_location((lat, long))\n else:\n return None\n nom_activite = extract(xml, attribute=\"pivotLocal\")\n if nom_activite:\n if nom_activite.lower().strip() in self.activites:\n fields[\"activite_id\"] = self.activites[nom_activite.lower().strip()]\n\n # checks rest\n if any(\n [\n fields[\"nom\"] == \"\",\n fields[\"code_postal\"] == \"\",\n fields[\"commune\"] == \"\",\n fields[\"voie\"] == \"\" and fields[\"lieu_dit\"] == \"\",\n fields[\"geom\"] == \"\",\n \"activite_id\" not in fields,\n ]\n ):\n return None\n\n erp = None\n # check doublons\n try:\n erp = Erp.objects.get(\n nom=fields[\"nom\"],\n voie=fields[\"voie\"],\n commune=fields[\"commune\"],\n activite__pk=fields[\"activite_id\"],\n )\n except Erp.MultipleObjectsReturned:\n # des doublons existent déjà malheureusement :(\n return None\n except Erp.DoesNotExist:\n pass\n\n if erp and self.force_update:\n Erp.objects.filter(pk=erp.pk).update(**fields)\n erp.refresh_from_db()\n\n return erp if erp else Erp(**fields)\n\n def get_xml_dirpath(self):\n here = os.path.abspath(os.path.join(os.path.abspath(__file__), \"..\", \"..\", \"..\"))\n return os.path.join(os.path.dirname(here), \"data\", \"service-public\", \"organismes\")\n\n def _retrieve_or_create_commune_ext(self, commune, code_insee=None, code_postal=None, xml=None):\n \"Assigne une commune normalisée à l'Erp en cours de génération\"\n if code_insee:\n commune_ext = Commune.objects.filter(code_insee=code_insee).first()\n if not commune_ext:\n arrdt = arrondissements.get_by_code_insee(code_insee)\n if arrdt:\n commune_ext = Commune.objects.filter(nom__iexact=arrdt[\"commune\"]).first()\n elif code_postal:\n commune_ext = Commune.objects.filter(code_postaux__contains=[code_postal]).first()\n else:\n raise RuntimeError(f\"Champ code_insee et code_postal nuls (commune: {commune})\")\n\n if not commune_ext:\n print(\n f\"Impossible de résoudre la commune depuis le code INSEE ({code_insee}) \"\n f\"ou le code postal ({code_postal}) \"\n )\n try:\n commune_ext = Commune(\n departement=code_insee[:2],\n nom=commune,\n code_insee=code_insee,\n geom=Point(\n float(extract(xml, fieldname=\"**Longitude\")),\n float(extract(xml, fieldname=\"**Latitude\")),\n ),\n code_postaux=[code_postal],\n )\n except ValueError:\n return None\n else:\n commune_ext.save()\n return commune_ext.pk\n return commune_ext.pk\n\n def get_access(self, xml):\n data = {}\n access = xml.find(\"*Accessibilité\")\n if access is not None and access.attrib:\n if access.attrib[\"type\"] == \"ACC\":\n if access.text is None:\n data[\"commentaire\"] = \"Établissement accessible en fauteuil roulant\"\n else:\n if \"plain pied\" in access.text:\n data[\"entree_plain_pied\"] = True\n\n if \"rampe\" in access.text:\n data[\"entree_plain_pied\"] = False\n data[\"entree_marches_rampe\"] = \"fixe\"\n elif access.attrib[\"type\"] == \"NAC\":\n data[\"entree_plain_pied\"] = False\n elif access.attrib[\"type\"] == \"DEM\":\n data[\"entree_plain_pied\"] = False\n data[\"entree_marches_rampe\"] = \"amovible\"\n data[\"entree_aide_humaine\"] = True\n\n return data\n\n def handle(self, *args, **options):\n self.force_update = options.get(\"forceupdate\")\n self.add_files()\n self.parse_files()\n print(\"Importation effectuée.\")\n print(f\"{len(self.all_files)} fichiers\")\n print(f\"{self.imported_erps} erps importés\")\n print(f\"{self.existed_erps} erps déjà existants\")\n print(f\"{self.erps_with_access_changed} erps avec données d'access modifiées\")\n\n def add_files(self):\n csv_dirpath = self.get_xml_dirpath()\n self.stdout.write(f\"Récupération des fichiers depuis {csv_dirpath}\")\n\n list_dir = os.listdir(csv_dirpath)\n self.stdout.write(f\"{len(list_dir)} dossier(s) à traiter\")\n\n self.all_files = []\n self.imported_erps = 0\n self.existed_erps = 0\n self.erps_with_access_changed = 0\n for root, _, files in os.walk(csv_dirpath, topdown=False):\n for name in files:\n path_file = os.path.join(root, name)\n if os.path.splitext(path_file)[-1] == \".xml\":\n self.all_files.append(path_file)\n self.stdout.write(f\"{len(self.all_files)} fichier(s) à traiter\")\n\n self.activites = {a.nom.lower().strip(): a.pk for a in Activite.objects.all()}\n\n def parse_files(self):\n for f in self.all_files:\n self.stdout.write(f\"{f}\")\n tree = ET.parse(f)\n root = tree.getroot()\n try:\n data_access = self.get_access(root)\n except Exception as e:\n self.stdout.write(f\"Access Data Error : {e}\")\n continue\n try:\n erp = self.import_row(root)\n except Exception as e:\n self.stdout.write(f\"ERP Data Error : {e}\")\n continue\n else:\n data_access = data_access or {\"entree_porte_presence\": True}\n\n if erp:\n self.stdout.write(f\"Ajout de l'ERP depuis {erp.source} (id: {erp.source_id})\")\n if hasattr(erp, \"pk\") and erp.pk:\n self.existed_erps += 1\n self.stdout.write(f\"EXIST {erp.nom} {erp.voie} {erp.commune}\")\n if self.force_update:\n print(\"\\tUPDATE FORCED on this ERP\")\n erp.save()\n else:\n erp.save()\n self.stdout.write(f\"ADD {erp}\")\n self.imported_erps += 1\n if not hasattr(erp, \"accessibilite\"):\n erp.accessibilite = Accessibilite(**data_access)\n erp.accessibilite.save()\n self.erps_with_access_changed += 1\n","sub_path":"erp/management/commands/import_service_public.py","file_name":"import_service_public.py","file_ext":"py","file_size_in_byte":10108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"582931336","text":"from scipy.spatial.distance import pdist, squareform\nfrom scipy import exp\nfrom scipy.linalg import eigh\nimport numpy as np\n\ndef rbf_kernel_pca(X, gamma, n_components):\n \"\"\"RBFカーネルPCAの実装\n\n パラメータ\n -----------\n X: (Numpy ndarray), shape=(n_sample, n_features)\n\n gamma: float\n RBFカーネルのチューニングパラメータ\n n_components: int\n 返される主成分の個数\n 戻り値\n -----------\n X_pc: (Numpy ndarray), shape = [n_samples, k_features]\n 射影されたデータセット\n\n lambdas: list\n 固有値\n \"\"\"\n # M×N次元のデータセットでペアごとの平方ユークリッド距離を計算\n sq_dists = pdist(X, 'sqeuclidean')\n # ペアごとの距離を正方形に変換\n mat_sq_dists = squareform(sq_dists)\n\n #対象カーネル行列を計算\n K = exp(-gamma * mat_sq_dists)\n\n # カーネル行列を中心化\n N = K.shape[0]\n one_n = np.ones((N,N)) / N\n K = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).dot(one_n)\n\n # 中心化されたカーネル行列から固有対象を取得\n # numpy.eighはそれらをノード順に返す\n eigvals, eigvecs = eigh(K)\n\n #上位k個の個数ベクトル(射影されたサンプル)を収集\n alphas = np.column_stack((eigvecs[:, -i]\n for i in range(1, n_components + 1)))\n\n # 対応する固有値を収集\n lambdas = [eigvals[-i] for i in range(1, n_components+1)]\n\n\n return alphas, lambdas\n","sub_path":"5unit/rbf_kernel_pca.py","file_name":"rbf_kernel_pca.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609198782","text":"import sys\n\n\nif len(sys.argv) < 4:\n print(\"Three parameters are required: python splitHepMC.py [input filename] [output filename] [max number of events per output file]\")\n exit()\n\ninputfilename = sys.argv[1]\noutputfilename = sys.argv[2]\nmaxNEvents = int(sys.argv[3])\n\nprint (\"Input file: \" + inputfilename)\nprint (\"Output files: \" + outputfilename)\nprint (\"Max Number of Events in Output: \" + str(maxNEvents))\n\ninputfile = open(inputfilename, \"r\")\ninputEventIndex = -1\ncurrentFileEventIndex = -1;\n\nheaderLines = [\"\",\"HepMC::Version 2.06.09\",\"HepMC::IO_GenEvent-START_EVENT_LISTING\"]\nfileEndLine = [\"HepMC::IO_GenEvent-END_EVENT_LISTING\"]\n\noutputfiles = [outputfilename+\"_0\"+\".hepmc\"]\ntempOutputfile = open(outputfiles[0], \"w\")\n\nfor l in headerLines:\n tempOutputfile.write(l+\"\\n\")\n\n\n\nlineIndex = 0\nfor line in inputfile:\n lineIndex = lineIndex + 1 #increment line counter\n\n #print (\"line \" + str(lineIndex))\n\n #skip the header\n if lineIndex <= 3: \n continue\n\n #end of file\n if \"END_EVENT_LISTING\" in line:\n break\n\n #find event line and increment event number\n #print (\"line 0:1 = \" + line[:2] + \"|\")\n if line[:2] == \"E \":\n #found Event line\n\n #print (str(currentFileEventIndex) + \" \" + str(maxNEvents) + \" | \" + str((currentFileEventIndex+1 >= maxNEvents)))\n\n if (currentFileEventIndex+1 >= maxNEvents):\n\n #Close previous file\n tempOutputfile.write(fileEndLine[0]+\"\\n\")\n tempOutputfile.close()\n\n #Open new file\n fileIndex = len(outputfiles)\n outputfiles.append(outputfilename+\"_\"+str(fileIndex)+\".hepmc\")\n tempOutputfile = open(outputfiles[fileIndex], \"w\") \n print(\"Closed file \" + str(outputfiles[fileIndex-1]))\n print(\"Opening new file \" + str(outputfiles[fileIndex]))\n\n #Write the header\n for l in headerLines:\n tempOutputfile.write(l+\"\\n\")\n\n currentFileEventIndex = 0\n else:\n inputEventIndex = inputEventIndex + 1\n currentFileEventIndex = currentFileEventIndex + 1\n \n if (currentFileEventIndex % 100 == 0):\n print(\"Writing Event \" + str(currentFileEventIndex))\n\n #write event line, but replace original event counter by the current file event counter\n eventLineList = line.split(\" \")\n newEventLine = \"\"\n for i in range(len(eventLineList)):\n if (i==1):\n newEventLine = newEventLine + str(currentFileEventIndex) + \" \"\n elif (i==len(eventLineList)-1):\n newEventLine = newEventLine + eventLineList[i]\n else :\n newEventLine = newEventLine + eventLineList[i] + \" \"\n #print (eventLineList)\n tempOutputfile.write(newEventLine)\n\n else :\n tempOutputfile.write(line)\n \n#write end of hepmc file for last file\ntempOutputfile.write(fileEndLine[0]+\"\\n\")\n\n","sub_path":"scripts/splitHEPMC.py","file_name":"splitHEPMC.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"458894213","text":"import torch\nimport torch.nn.functional as F\n\n\ndef soft_argmin(cost_volume, normalize=True, temperature=1.0):\n # type: (torch.Tensor, bool, [float, int]) -> torch.Tensor\n r\"\"\"Implementation of soft argmin proposed by GC-Net.\n Arguments:\n cost_volume (torch.Tensor): the matching cost after regularization, in [B, max_disp, W, H] layout\n normalize (bool): whether apply softmax on cost_volume, default True\n temperature (float, int): a temperature factor will times with cost_volume\n details can refer to: https://bouthilx.wordpress.com/2013/04/21/a-soft-argmax/\n Returns:\n disp_map (torch.Tensor): a disparity map regressed from cost volume, in [B, 1, W, H] layout\n \"\"\"\n if cost_volume.dim() != 4:\n raise ValueError(\n 'expected 4D input (got {}D input)'.format(cost_volume.dim())\n )\n # grab max disparity\n N, max_disp, H, W = cost_volume.shape\n\n # generate disparity indexes\n disp_index = torch.linspace(0, max_disp - 1, max_disp).to(cost_volume.device)\n disp_index = disp_index.repeat(N, H, W, 1).permute(0, 3, 1, 2).contiguous()\n\n # compute probability volume\n # prob_volume: (BatchSize, MaxDisparity, Height, Width)\n cost_volume = cost_volume * temperature\n if normalize:\n prob_volume = F.softmax(cost_volume, dim=1)\n else:\n prob_volume = cost_volume\n\n # compute disparity: (BatchSize, 1, Height, Width)\n disp_map = torch.sum(prob_volume * disp_index, dim=1, keepdim=True)\n\n return disp_map\n","sub_path":"dmb/modeling/stereo/disp_predictors/soft_argmin.py","file_name":"soft_argmin.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"605956834","text":"import logging\nfrom twitter.persistence import MentionsReplyCursor\n\n\nlogger = logging.getLogger()\n\n\ndef tweet_random_lyrics(twitter_api, lyrics_mixer):\n mixed_lyrics = lyrics_mixer.mix_two_random_lyrics()\n twitter_api.update_status(str(mixed_lyrics)) \n\n\ndef reply_to_mentions(twitter_api, tweet_reply_factory):\n reply_cursor = MentionsReplyCursor()\n logger.info(f\"Mentions reply cursor at position: {reply_cursor.position}\")\n mentions = twitter_api.mentions_since(reply_cursor.position)\n replies = tweet_reply_factory.create_from_many(mentions)\n send(replies)\n\n\ndef send(replies):\n reply_cursor = MentionsReplyCursor()\n\n for reply in replies:\n reply.send()\n reply_cursor.point_to(reply)","sub_path":"lyrics_mixer/twitter/jobs.py","file_name":"jobs.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"394255981","text":"import timeit\n\n\ndef insert_sort():\n a = [5, 2, 4, 6, 1, 3]\n for j in range(1, len(a)):\n key = a[j]\n i = j - 1\n while i >= 0 and a[i] > key:\n a[i + 1] = a[i]\n i -= 1\n a[i + 1] = key\n return a\n\n\ndef bable_sort():\n a = [5, 2, 4, 6, 1, 3]\n for i in range(0, len(a) - 1):\n for j in range(len(a) - 1, i, -1):\n if a[j] < a[j - 1]:\n a[j], a[j - 1] = a[j - 1], a[j]\n return a\n\n\nprint(timeit.timeit(\"insert_sort()\", setup=\"from __main__ import insert_sort\", number=1000))\nprint(timeit.timeit(\"bable_sort()\", setup=\"from __main__ import bable_sort\", number=1000))\n\nprint(insert_sort())\nprint(bable_sort())\n","sub_path":"1_Foundations/01_insert_sort.py","file_name":"01_insert_sort.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"236867813","text":"# import sys\n# sys.stdin = open('input.txt')\n\ndef dfs(x, y, k):\n visit = [[False] * n for _ in range(n)]\n delta = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n visit[x][y] = True\n stack = []\n length = 1\n chance = 1\n max_length = 0\n stack.append((x, y, arr[x][y], length, chance, visit))\n # i, j 현재 지점, height: 현재 지점의 높이, length: 등산로의 길이, chance: 봉우리를 깎을 수 있는 기회, visit: 방문지점\n while stack:\n i, j, height, length, chance, visit = stack.pop()\n if length > max_length:\n max_length = length\n for idx in range(4):\n # deepcopy를 이용한다. # 배열의 크기가 크지 않아 시간이 오래 걸리지 않음\n visit2 = [lst[:] for lst in visit]\n di, dj = delta[idx]\n ni, nj = i + di, j + dj\n # 현재 높이보다 낮고 배열 밖을 벗어나지 않으며 방문한 지점이 아니라면 경로에 추가한다.\n if 0 <= ni < n and 0 <= nj < n and arr[ni][nj] max_v:\n max_v = arr[i][j]\n # 시작점 리스트를 만들어준다.\n for i in range(n):\n for j in range(n):\n if arr[i][j] == max_v:\n start_lst.append((i,j))\n result = 0\n for start in start_lst:\n l = dfs(*start, k)\n if l > result:\n result = l\n print('#{} {}'.format(tc, result))\n\n","sub_path":"Algorithm/swea/[1949] 등산로 조성.py","file_name":"[1949] 등산로 조성.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"114520741","text":"import cv2\nimport numpy as np\n\ndatapath = \"../trains/\"\npos, neg = \"pos-\", \"neg-\"\nSAMPLES = 400\ndef path(cls,i):\n return \"%s%s%d.pgm\" % (datapath, cls, i)\n\ndef get_flann_matcher():\n flann_params = dict(algorithm = 1,trees = 5)\n return cv2.FlannBasedMatcher(flann_params,{})\n\ndef get_bow_extractor(extract,flann):\n return cv2.BOWImgDescriptorExtractor(extract,flann)\n\ndef get_extract_detect():\n return cv2.xfeatures2d.SIFT_create(),cv2.xfeatures2d.SIFT_create()\n\ndef extract_sift(img, extractor, detector):\n frame = cv2.imread(img, 0)\n return extractor.compute(frame, detector.detect(frame))[1]\n\ndef bow_features(img,extractor_bow,detector):\n return extractor_bow.compute(img,detector.detect(img))\n\ndef car_detector():\n\n detect,extract = get_extract_detect()\n flann = get_flann_matcher()\n print(\"building bowkmeanstrainer\")\n bow_kmeans_trainer = cv2.BOWKMeansTrainer(1000)\n extract_bow = get_bow_extractor(extract,flann)\n\n print(\"adding feature to trainer\")\n\n for i in range(SAMPLES):\n if i == 130:\n continue\n bow_kmeans_trainer.add(extract_sift(path(pos,i),extract,detect))\n bow_kmeans_trainer.add(extract_sift(path(neg,i),extract,detect))\n\n voc = bow_kmeans_trainer.cluster()\n extract_bow.setVocabulary(voc)\n\n traindata,trainlable = [],[]\n print(\"adding data to trainer\")\n\n for i in range(SAMPLES):\n if i == 130:\n continue\n traindata.extend(bow_features(cv2.imread(path(pos,i),0),extract_bow,detect))\n trainlable.append(1)\n traindata.extend(bow_features(cv2.imread(path(neg, i), 0), extract_bow, detect))\n trainlable.append(-1)\n\n svm = cv2.ml.SVM_create()\n svm.setType(cv2.ml.SVM_C_SVC)\n svm.setGamma(0.5)\n svm.setC(30)\n svm.setKernel(cv2.ml.SVM_RBF)\n\n svm.train(np.array(traindata),cv2.ml.ROW_SAMPLE,np.array(trainlable))\n\n return svm,extract_bow\n\n\n\n","sub_path":"第7章/car_detector/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"635029163","text":"\"\"\"\nAfter a hectic week at work, Mancunian and Liverbird decide to go on a fun weekend camping trip.\n As they were passing through a forest, they stumbled upon a \nunique tree of N nodes. Vertices are numbered from 1 to N.\n\nEach node of the tree is assigned a color (out of C possible colors). Being bored, they decide to work together\n (for a change) and test their reasoning skills. The tree is rooted at vertex 1. For each node, they want to find \n its closest ancestor having the same color.\n\nInput format\nThe first line contains two integers N and C denoting the number of vertices in the tree and the number of possible colors.\nThe second line contains integers. The integer denotes the parent of the vertex.\nThe third line contains N integers, denoting the colors of the vertices. Each color lies between 1 and C inclusive.\n\nOutput format\nPrint N space-separated integers. The integer is the vertex number of lowest ancestor of the node which has the\n same color. If there is no such ancestor, print 1 for that node.\n\nConstraints\nSAMPLE INPUT \n5 4\n1 1 3 3\n1 4 2 1 2\nSAMPLE OUTPUT \n-1 -1 -1 1 3\nExplanation\nVertices 1, 2 and 3 do not have any ancestors having the same color as them. The nearest required ancestors for \nvertices 4 and 5 are vertices 1 and 3 respectively.\n\"\"\"\nfrom sys import stdin , stdout\nn , c = map(int,stdin.readline().split())\nparent = list(map(int , stdin.readline().split()))\ncolor = list(map(int , stdin.readline().split()))\nparent = [-1 ,0] + parent\ncolor = [0] + color\nfor i in range(1,n+1):\n cur = color[i]\n node = parent[i]\n while True:\n if node == -1:\n stdout.write(\"-1 \")\n break\n if color[node] == cur:\n stdout.write(str(node) +\" \")\n break\n node = parent[node]\nstdout.write(\"\\n\")","sub_path":"MancunianAndColoredTree.py","file_name":"MancunianAndColoredTree.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56539355","text":"import gtk, gtk.glade, gobject\nimport sudoku\nfrom gtk_goodies import gconf_wrapper\nfrom defaults import *\nfrom gettext import gettext as _\nfrom gettext import ngettext\nimport threading\n\nclass GameGenerator (gconf_wrapper.GConfWrapper):\n\n glade_file = os.path.join(GLADE_DIR,'puzzle_generator.glade')\n\n initial_prefs = {'generate_target_easy':1,\n 'generate_target_medium':0,\n 'generate_target_hard':1,\n 'generate_target_veryHard':1,\n 'generate_endlessly':1,\n 'generate_for_target':0,\n 'number_of_sudokus_to_generate':10,\n }\n \n def __init__ (self, UI, gconf):\n self.ui = UI\n self.sudoku_tracker = self.ui.sudoku_tracker\n self.sudoku_maker = self.ui.sudoku_maker\n # Don't work in background...\n self.ui.stop_worker_thread()\n gconf_wrapper.GConfWrapper.__init__(self,gconf)\n self.glade = gtk.glade.XML(self.glade_file)\n self.generate_for_target_widgets = []\n for d in ['easy',\n 'medium',\n 'hard',\n 'veryHard']:\n widget_name = '%sCheckButton'%d\n widget = self.glade.get_widget(widget_name)\n label_widget_name = '%sLabel'%d\n setattr(self,label_widget_name,self.glade.get_widget(label_widget_name))\n setattr(self,widget_name,widget)\n gconf_setting = 'generate_target_%s'%d\n self.gconf_wrap_toggle(gconf_setting,widget)\n self.generate_for_target_widgets.append(widget)\n self.generateEndlesslyRadio = self.glade.get_widget('generateEndlesslyRadio')\n self.generateForTargetRadio = self.glade.get_widget('generateForTargetRadio')\n self.gconf_wrap_toggle('generate_endlessly',self.generateEndlesslyRadio)\n self.gconf_wrap_toggle('generate_for_target',self.generateForTargetRadio)\n self.generateEndlesslyRadio.connect('toggled',self.generate_method_changed_cb)\n self.newSudokusSpinButton = self.glade.get_widget('newSudokusSpinButton')\n self.gconf_wrap_adjustment('number_of_sudokus_to_generate',\n self.newSudokusSpinButton.get_adjustment()\n )\n self.generate_for_target_widgets.append(self.newSudokusSpinButton)\n self.generate_method_changed_cb()\n self.generateButton = self.glade.get_widget('generateButton')\n self.generateButton.connect('clicked',self.generate_cb)\n self.closeButton = self.glade.get_widget('closeButton')\n self.closeButton.connect('clicked',self.close_cb)\n self.pauseButton = self.glade.get_widget('pauseButton')\n self.pauseButton.connect('clicked',self.pause_cb)\n self.stopButton = self.glade.get_widget('stopButton')\n self.stopButton.connect('clicked',self.stop_cb)\n self.pauseButton.set_sensitive(False)\n self.stopButton.set_sensitive(False)\n self.prog = self.glade.get_widget('progressbar1')\n self.prog.set_show_text(True)\n self.working = False\n self.dialog = self.glade.get_widget('PuzzleGenerator')\n self.dialog.show_all()\n self.dialog.present()\n self.setup_base_status()\n\n def generate_method_changed_cb (self, *args):\n if not self.generateForTargetRadio.get_active():\n for w in self.generate_for_target_widgets:\n w.set_sensitive(False)\n else:\n for w in self.generate_for_target_widgets:\n w.set_sensitive(True)\n\n def generate_cb (self, *args):\n self.ngenerated = 0\n self.toward_target = 0\n self.pauseButton.set_sensitive(True)\n self.stopButton.set_sensitive(True)\n self.generateButton.set_sensitive(False)\n self.working = True\n self.paused = False\n self.prog.set_text(_('Working...'))\n gobject.timeout_add(100,self.update_status)\n self.worker = threading.Thread(target=lambda *args: self.sudoku_maker.work(limit=None,diff_min=self.get_diff_min(),diff_max=self.get_diff_max()))\n self.worker.start()\n\n def pause_cb (self, widg):\n if widg.get_active():\n self.sudoku_maker.pause()\n self.paused = True\n else:\n self.sudoku_maker.resume()\n self.prog.set_text(_('Working...'))\n self.paused = False\n\n def stop_cb (self, *args):\n self.sudoku_maker.stop()\n self.stopButton.set_sensitive(False)\n self.pauseButton.set_sensitive(False)\n self.pauseButton.set_active(False)\n self.generateButton.set_sensitive(True)\n self.working = False\n\n def close_cb (self, widg):\n if self.working:\n self.stop_cb()\n self.dialog.hide()\n self.dialog.destroy()\n\n def setup_base_status (self):\n \"\"\"Setup basic status.\n \"\"\"\n for puzz,diff in self.sudoku_tracker.list_new_puzzles():\n diffstr = diff.value_string()\n if diffstr == sudoku.DifficultyRating.easy:\n self.increment_label(self.easyLabel)\n elif diffstr == sudoku.DifficultyRating.medium:\n self.increment_label(self.mediumLabel)\n elif diffstr == sudoku.DifficultyRating.hard:\n self.increment_label(self.hardLabel)\n else:\n self.increment_label(self.veryHardLabel)\n\n def increment_label (self, lab, val=1):\n curtext = lab.get_text()\n if not curtext:\n newval = val\n else:\n curval = int(curtext.split()[0])\n newval = curval + val\n newtext = ngettext(\"%s puzzle\",\"%s puzzles\",newval)%newval\n lab.set_text(newtext)\n\n def update_status (self, *args):\n \"\"\"Update status of our progress bar and puzzle table.\n \"\"\"\n npuzzles = len(self.sudoku_maker.new_puzzles)\n if npuzzles > self.ngenerated:\n # updating gui...\n to_add = self.sudoku_maker.new_puzzles[self.ngenerated:]\n self.ngenerated=npuzzles\n for puzz,diff in to_add:\n diffstr = diff.value_string()\n if diffstr == sudoku.DifficultyRating.easy:\n self.increment_label(self.easyLabel)\n if (not self.generateForTargetRadio.get_active() or\n self.easyCheckButton.get_active()):\n self.toward_target += 1\n elif diffstr == sudoku.DifficultyRating.medium:\n self.increment_label(self.mediumLabel)\n if (not self.generateForTargetRadio.get_active() or\n self.mediumCheckButton.get_active()):\n self.toward_target += 1\n elif diffstr == sudoku.DifficultyRating.hard: \n self.increment_label(self.hardLabel)\n if (not self.generateForTargetRadio.get_active() or\n self.hardCheckButton.get_active()):\n self.toward_target += 1\n else:\n self.increment_label(self.veryHardLabel)\n if (not self.generateForTargetRadio.get_active() or\n self.veryHardCheckButton.get_active()):\n self.toward_target += 1\n self.update_progress_bar()\n if (self.generateForTargetRadio.get_active()\n and\n self.newSudokusSpinButton.get_value()==self.toward_target):\n self.stop_cb()\n return False\n if self.paused: self.prog.set_text(_('Paused'))\n elif self.generateEndlesslyRadio.get_active():\n self.prog.pulse()\n if not self.working: return False\n if hasattr(self.sudoku_maker,'new_generator') and self.sudoku_maker.new_generator.terminated:\n self.prog.set_text(_('Stopped'))\n self.stopButton.set_sensitive(False)\n self.pauseButton.set_sensitive(False)\n self.pauseButton.set_active(False)\n self.generateButton.set_sensitive(True)\n return False\n return True\n\n def update_progress_bar (self):\n if self.generateForTargetRadio.get_active():\n tot = int(self.newSudokusSpinButton.get_value())\n self.prog.set_percentage(\n float(self.toward_target)/tot\n )\n txt = _('Generated %s out of %s puzzles')%(self.toward_target,tot)\n else:\n self.prog.pulse()\n txt = _('Generated %s puzzles')%(self.toward_target)\n if self.paused: txt = txt + ' (' + _('Paused') + ')'\n self.prog.set_text(txt)\n\n def get_diff_min (self):\n if self.generateEndlesslyRadio.get_active(): return None\n if self.easyCheckButton.get_active(): return None\n if self.mediumCheckButton.get_active(): return sudoku.DifficultyRating.medium_range[0]\n if self.hardCheckButton.get_active(): return sudoku.DifficultyRating.hard_range[0]\n if self.veryHardCheckButton.get_active(): return sudoku.DifficultyRating.very_hard_range[0]\n\n def get_diff_max (self):\n if self.generateEndlesslyRadio.get_active(): return None\n if self.veryHardCheckButton.get_active(): return None\n if self.hardCheckButton.get_active(): return sudoku.DifficultyRating.hard_range[1]\n if self.mediumCheckButton.get_active(): return sudoku.DifficultyRating.medium_range[1]\n if self.easyCheckButton.get_active(): return sudoku.DifficultyRating.easy_range[1]\n","sub_path":"src/lib/sudoku_generator_gui.py","file_name":"sudoku_generator_gui.py","file_ext":"py","file_size_in_byte":9602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"637351303","text":"from common import ListNode\n\nclass Solution:\n def deleteNode(self, node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n \"\"\"\n p = node\n while True:\n p.val = p.next.val\n if not p.next.next:\n p.next = None\n break\n p = p.next\n \n return\n","sub_path":"python3/l0237_delete_node_in_a_linked_list.py","file_name":"l0237_delete_node_in_a_linked_list.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558850255","text":"from player import Player\r\nimport sys\r\nimport time\r\nimport os\r\nimport world\r\n# import speech # This module isn't working well yet\r\n\r\n\r\ndef play():\r\n player = Player()\r\n while True:\r\n room = world.tile_at(player.x, player.y)\r\n print(room.intro_text())\r\n action_input = get_player_command()\r\n if action_input in ['n', 'N']:\r\n print('Go North')\r\n player.move_north()\r\n elif action_input in ['s', 'S']:\r\n print('Go South')\r\n player.move_south()\r\n elif action_input in ['e', 'E']:\r\n print('Go East')\r\n player.move_east()\r\n elif action_input in ['w', 'W']:\r\n print('Go West')\r\n player.move_west()\r\n elif action_input in ['i', 'I']:\r\n player.print_inventory()\r\n elif action_input in ['c', 'C']:\r\n check = input('Which item do you want to examine?\\n>')\r\n for item in player.inventory:\r\n if check.capitalize() == item.name:\r\n player.examine_item(item)\r\n else:\r\n pass\r\n elif action_input in ['a', 'A']:\r\n player.attack()\r\n elif action_input in ['q', 'Q']:\r\n exit()\r\n elif action_input in ['h', 'H']:\r\n print('''\r\n Player Commands:\\n\r\n * N, n: Go North\\n\r\n * S, s: Go South\\n\r\n * E, e: Go East\\n\r\n * W, w: Go West\\n\r\n * A, a: Attack\\n\r\n * I, i: Display inventory\\n\r\n * C, c: Examine details of an item\\n\r\n * H, h: Help\\n\r\n * Q, q: Quit\r\n ''')\r\n else:\r\n print('Invalid action!')\r\n\r\ndef get_player_command():\r\n return input('Action\\n>')\r\n\r\ndef title_screen():\r\n # os.system('cls')\r\n print(open('assets/title.txt').read())\r\n print('\\t\\t\\t\\tEscape the City of Giants')\r\n time.sleep(2)\r\n print('\\nPress ENTER to continue')\r\n input()\r\n os.system('cls')\r\n start_menu()\r\n\r\n\r\ndef start_menu():\r\n while True:\r\n user_in = input('[S]tart\\n[Q]uit\\n[H]elp\\n>')\r\n if user_in.lower() == 's':\r\n play()\r\n elif user_in.lower() == 'q':\r\n exit()\r\n elif user_in.lower() == 'h':\r\n print('''\r\n Player Commands:\\n\r\n * N, n: Go North\\n\r\n * S, s: Go South\\n\r\n * E, e: Go East\\n\r\n * W, w: Go West\\n\r\n * I, i: Display inventory\\n\r\n * C, c: Examine details of an item\\n\r\n * H, h: Help\\n\r\n * Q, q: Quit\r\n ''')\r\n\r\n\r\ntitle_screen()\r\n","sub_path":"Protopolis/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"114066607","text":"import numpy as np\nimport cv2\nimport glob\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.utils.data import Dataset\nimport PIL.Image as Image\nimport os\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import transforms\nimport argparse\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nclass DoubleConv(nn.Module):\n \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.double_conv = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n nn.BatchNorm2d(out_channels),\n nn.ReLU(inplace=True)\n )\n\n def forward(self, x):\n return self.double_conv(x)\n\n\nclass Down(nn.Module):\n \"\"\"Downscaling with maxpool then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels):\n super().__init__()\n self.maxpool_conv = nn.Sequential(\n nn.MaxPool2d(2),\n DoubleConv(in_channels, out_channels)\n )\n\n def forward(self, x):\n return self.maxpool_conv(x)\n\n\nclass Up(nn.Module):\n \"\"\"Upscaling then double conv\"\"\"\n\n def __init__(self, in_channels, out_channels, bilinear=True):\n super().__init__()\n\n # if bilinear, use the normal convolutions to reduce the number of channels\n if bilinear:\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n else:\n self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2)\n\n self.conv = DoubleConv(in_channels, out_channels)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n # input is CHW\n diffY = x2.size()[2] - x1.size()[2]\n diffX = x2.size()[3] - x1.size()[3]\n\n x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n diffY // 2, diffY - diffY // 2])\n \n x = torch.cat([x2, x1], dim=1)\n return self.conv(x)\n\n\nclass OutConv(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(OutConv, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n\n def forward(self, x):\n return self.conv(x)\n \nclass UNet(nn.Module):\n def __init__(self, n_channels, n_classes, bilinear=True):\n super(UNet, self).__init__()\n self.n_channels = n_channels\n self.n_classes = n_classes\n self.bilinear = bilinear\n\n self.inc = DoubleConv(n_channels, 64)\n self.down1 = Down(64, 128)\n self.down2 = Down(128, 256)\n self.down3 = Down(256, 512)\n self.down4 = Down(512, 512)\n self.up1 = Up(1024, 256, bilinear)\n self.up2 = Up(512, 128, bilinear)\n self.up3 = Up(256, 64, bilinear)\n self.up4 = Up(128, 64, bilinear)\n self.outc = OutConv(64, n_classes)\n\n def forward(self, x):\n x1 = self.inc(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x = self.up1(x5, x4)\n x = self.up2(x, x3)\n x = self.up3(x, x2)\n x = self.up4(x, x1)\n logits = self.outc(x)\n return logits\n\n\ndef make_dataset_test(root):\n imgs=[]\n n=len(os.listdir(root))//2\n for i in range(1,21):\n if i <10:\n ind='0'+str(i)\n else:\n ind = str(i)\n img=os.path.join(root,ind+\"_test.tif\")\n mask=os.path.join(root,ind+\"_manual1.gif\")\n imgs.append((img,mask))\n return imgs\n\ndef make_dataset_train(root):\n imgs=[]\n n=len(os.listdir(root))//2\n for i in range(21,41):\n if i <10:\n ind='0'+str(i)\n else:\n ind = str(i)\n img=os.path.join(root,ind+\"_training.tif\")\n mask=os.path.join(root,ind+\"_manual1.gif\")\n imgs.append((img,mask))\n return imgs\n\nclass LiverDataset(Dataset):\n def __init__(self, root, path, transform=None, target_transform=None):\n if path == 'train':\n imgs = make_dataset_train(root)\n else:\n imgs = make_dataset_test(root)\n self.imgs = imgs\n self.transform = transform\n self.target_transform = target_transform\n def __getitem__(self, index):\n x_path, y_path = self.imgs[index]\n# .resize((1608,1068),Image.ANTIALIAS)\n img_x = Image.open(x_path).convert('RGB')\n img_y = Image.open(y_path).convert('L')\n if self.transform is not None:\n img_x = self.transform(img_x)\n if self.target_transform is not None:\n img_y = self.target_transform(img_y)\n return img_x, img_y\n\n def __len__(self):\n return len(self.imgs)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nx_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n])\ny_transforms = transforms.ToTensor()\n\ndef train_model(model, criterion, optimizer, dataload, num_epochs=21):\n epochloss = []\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 10)\n dt_size = len(dataload.dataset)\n epoch_loss = 0\n step = 0\n for x, y in dataload:\n step += 1\n inputs = x.to(device)\n labels = y.to(device)\n # zero the parameter gradients\n optimizer.zero_grad()\n # forward\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n epoch_loss += loss.item()\n print(\"%d/%d,train_loss:%0.3f\" % (step, (dt_size - 1) // dataload.batch_size + 1, loss.item()))\n print(\"epoch %d loss:%0.3f\" % (epoch, epoch_loss/step))\n epochloss.append(epoch_loss/step)\n torch.save(model.state_dict(), 'weights_%d.pth' % epoch)\n epochloss = np.array(epochloss)\n np.save('train_loss.npy',epochloss)\n return model\n\ndef train():\n model = UNet(3, 1).to(device)\n batch_size = 1\n criterion = nn.BCEWithLogitsLoss()\n optimizer=torch.optim.SGD(model.parameters(), lr=1e-3, momentum=0.99)\n liver_dataset = LiverDataset(\"/kaggle/input/train/train\",'train', transform=x_transforms,target_transform=y_transforms)\n dataloaders = DataLoader(liver_dataset, batch_size=batch_size, shuffle=True, num_workers=4)\n train_model(model, criterion, optimizer, dataloaders)\ndef test():\n model = UNet(3, 1)\n model.load_state_dict(torch.load('/kaggle/working/weights_39.pth',map_location='cpu'))\n liver_dataset = LiverDataset(\"/kaggle/input/test/test\", 'test', transform=x_transforms,target_transform=y_transforms)\n dataloaders = DataLoader(liver_dataset, batch_size=1)\n criterion = nn.BCEWithLogitsLoss()\n model.eval()\n plt.ion()\n imgs = []\n losses = []\n with torch.no_grad():\n for x, mask in dataloaders:\n y=model(x)\n loss = criterion(y, mask)\n losses.append(loss.item())\n print(loss.item())\n img_y=torch.squeeze(y).numpy()\n imgs.append(img_y)\n plt.imshow(img_y)\n plt.pause(0.01)\n plt.show()\n imgs = np.array(imgs)\n losses = np.array(losses)\n np.save('test_ex.npy',imgs)\n np.save('test_loss.npy',losses)\nif __name__ == '__main__':\n #参数解析\n train()\ntest()\nimport os\nos.listdir('/kaggle/input/train/train')","sub_path":"note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"299480080","text":"import os\nimport argparse\nfrom pathlib import Path\n\nimport detect\nfrom unvocabularize import unvocabularize\nfrom vocabulary import vocabulary\n\ndef convert_file_to_tokens(*, src=None, out=None, **kwargs):\n if not os.path.exists(out):\n os.makedirs(out)\n\n lst_files = []\n for _, _, files in os.walk(src):\n for filename in files:\n lst_files.append(filename)\n\n for idx, file in enumerate(lst_files):\n with open(str(src) + '/' + file, 'r') as f:\n tokens = detect.tokenize_file(f)\n vector = detect.vectorize_tokens(tokens)\n v = unvocabularize(vector)\n with open(str(out) + '/' + file + '.tks', 'w+') as p:\n p.write(v)\n print('file ' + file)\n\ndef add_common_args(parser):\n parser.add_argument('src', nargs='?', type=Path,\n default=Path('/dev/stdin'))\n parser.add_argument('out', nargs='?', type=Path,\n default=Path('/dev/stdin'))\n\nparser = argparse.ArgumentParser()\nadd_common_args(parser)\nparser.set_defaults(func=convert_file_to_tokens)\n\nif __name__ == '__main__':\n args = parser.parse_args()\n if args.func:\n args.func(**vars(args))\n else:\n parser.print_usage()\n exit(-1)\n","sub_path":"evaluation/convert_to_tokens.py","file_name":"convert_to_tokens.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"82946027","text":"# -*- coding: utf-8 -*-\n'''\nThis function takes in a date as a datetime object and the directory of ARM KAZR radar files.\nIt plots a basic reflectivity plot for the entered date quickly without using pcolor or pcolormesh.\n(pcolor took too long to run these large files)\nThe X-axis has incorrect values, but the grids are every hour for the 24 time period.\nReflectivity is filtered (masked) by the SNR. \n\n\nAuthor: Grant McKercher\n'''\n\nfrom scipy.io import netcdf\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nimport numpy.ma as ma\n\ndef plot_kazr(date,radar_dir):\n\n path = os.getcwd()\n\n [radar] = gather_radar_files(date,radar_dir)\n \n # Gather files\n os.chdir(radar_dir)\n f = netcdf.netcdf_file(radar, 'r')\n \n # Make Plot\n \n # Read in data\n rng = f.variables['range'].data\n refc = f.variables['reflectivity_copol'].data\n stnrc = f.variables['signal_to_noise_ratio_copol'].data\n # Masking Radar Attenuation\n refc = ma.masked_where((stnrc <= -14),refc)\n \n fig = plt.figure(figsize = [15,8])\n \n ax = fig.add_subplot(111)\n im = plt.imshow(refc.T,aspect=20,extent=[0,1000000,min(rng),max(rng)],origin='bottom')\n ax.set_title('SGP copolar reflectivity, masked SNR')\n # x axis\n xmajorLocator = MultipleLocator(41666.66666666667) \n ax.xaxis.set_major_locator(xmajorLocator)\n xmajorFormatter = FormatStrFormatter('%d')\n ax.xaxis.set_major_formatter(xmajorFormatter)\n\n ax.set_xlabel('Hours (UTC) - Grid by hour')\n\n # y axis\n ymajorLocator = MultipleLocator(2500)\n ax.yaxis.set_major_locator(ymajorLocator)\n ymajorFormatter = FormatStrFormatter('%d')\n ax.yaxis.set_major_formatter(ymajorFormatter)\n ax.set_ylabel('Height (m)')\n plt.grid()\n \n cb = plt.colorbar(ax=ax,mappable=im,aspect=20,orientation='vertical',shrink=0.55)\n cb.set_label(r'Reflectivity factor, $Z_e$ (dBZ)')\n\n f.close()","sub_path":"functions/plot_kazr.py","file_name":"plot_kazr.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"497407071","text":"import obmplib, turtle\nfrom tableMaker import Pashmak\n\nclass simulation:\n\n def __init__(self):\n self.tick = 0\n self.lasttick = 0\n self.ableworktime = 0\n self.bakerworktime = 0\n self.ableworking = -1\n self.bakerworking = -1\n self.queue = []\n self.pashmak = None\n self.history = []\n self.works = []\n self.ableworkingnow = None\n self.bakerworkingnow = None\n \n def initpashmak(self, a, b):\n self.pashmak = Pashmak(a, b)\n \n def nexttick(self):\n workername = ''\n while (True):\n if (self.ableworking > 0):\n self.ableworking -= 1\n if (self.ableworking == 0):\n self.ableworking = -1\n if (self.ableworkingnow):\n self.ableworkingnow.endtime = self.tick\n self.works.append(self.ableworkingnow)\n \n if (self.bakerworking > 0):\n self.bakerworking -= 1\n if (self.bakerworking == 0):\n self.bakerworking = -1\n if (self.bakerworkingnow):\n self.bakerworkingnow.endtime = self.tick\n self.works.append(self.bakerworkingnow)\n\n if (self.tick < self.lasttick):\n self.queue.extend(self.pashmak.queue(self.tick))\n \n if (len(self.queue) > 0 and self.ableworking == -1):\n self.ableworking = self.ableworktime\n self.ableworkingnow = self.queue.pop(0)\n self.ableworkingnow.starttime = self.tick\n self.ableworkingnow.servname = 'able'\n \n if (len(self.queue) > 0 and self.bakerworking == -1):\n self.bakerworking = self.bakerworktime\n self.bakerworkingnow = self.queue.pop(0)\n self.bakerworkingnow.starttime = self.tick\n self.bakerworkingnow.servname = 'baker'\n \n self.history.append((len(self.queue), self.ableworking, self.bakerworking))\n self.tick += 1\n\n if (self.tick > self.lasttick and len(self.queue) == 0 and self.ableworking == -1 and self.bakerworking == -1):\n break\n\ns = \"\"\n\nfor j in range(1, 51):\n sim = simulation()\n sim.lasttick = 10000\n sim.ableworktime = j\n sim.bakerworktime = 5\n\n sim.initpashmak(0,10)\n sim.nexttick()\n\n\n able = {}\n baker = {}\n\n hpot = {}\n hpot2 = {}\n\n #s = \"\"\n #s3 = \"\"\n\n for i in sim.works:\n b = i.endtime - i.queuetime\n #s += (str(b))\n #s += \"\\n\"\n #s3 += (str(i.starttime - i.queuetime))\n #s3 += \"\\n\"\n if (hpot.get(i.starttime - i.queuetime)):\n hpot[i.starttime - i.queuetime] += 1\n else:\n hpot[i.starttime - i.queuetime] = 1\n\n if (hpot2.get(i.endtime - i.queuetime)):\n hpot2[i.endtime - i.queuetime] += 1\n else:\n hpot2[i.endtime - i.queuetime] = 1\n \n \n if i.servname == 'able':\n b -= sim.ableworktime\n if b in able:\n able[b] += 1\n else:\n able[b] = 1\n else:\n b -= sim.bakerworktime\n if b in baker:\n baker[b] += 1\n else:\n baker[b] = 1\n t1 = 0\n t1s = 0\n for i in hpot:\n t1s += hpot[i]\n for i in hpot:\n t1 += hpot[i] * i / t1s\n\n t2 = 0\n t2s = 0\n for i in hpot2:\n t2s += hpot2[i]\n for i in hpot2:\n t2 += hpot2[i] * i / t2s\n\n s += str(j) + \"\\t\" + str(t1) + '\\t' + str(t2) + '\\n'\n \nf = open(\"q.txt\", 'w')\nf.write(s)\nf.close()\n##\n##f = open(\"s3.txt\", 'w')\n##f.write(s3)\n##f.close()\n##\n##s4 = \"\"\n##for i in hpot:\n## s4 += str(i) + '\\t' + str(hpot[i]) + '\\n'\n##\n##f = open(\"s4.txt\", 'w')\n##f.write(s4)\n##f.close()\n##\n##s7 = \"\"\n##for i in hpot2:\n## s7 += str(i) + '\\t' + str(hpot2[i]) + '\\n'\n##\n##f = open(\"s7.txt\", 'w')\n##f.write(s7)\n##f.close()\n##\n##\n##s2 = \"\"\n##\n##for i in sim.history:\n## kk = i[0]\n## if (i[1] != -1):\n## kk += 1\n## if (i[2] != -1):\n## kk += 1\n## s2 += str(kk) + \"\\n\"\n##\n##\n##\n##f = open(\"s2.txt\", 'w')\n##f.write(s2)\n##f.close()\n##\n### print(able)\n### print(baker)\n##\n##a = open('s5.txt', 'w')\n##for i in able:\n## a.write(\"%d\\t%d\\n\" % (i, able[i]))\n##a.close()\n##\n##a = open('s6.txt', 'w')\n##for i in baker:\n## a.write(\"%d\\t%d\\n\" % (i, baker[i]))\n##a.close()\n##\n### wn = turtle.Screen()\n### wn.delay(0)\n### wn.screensize(200, 200)\n### wn.setworldcoordinates(0, 0, 80, 80)\n### wn.exitonclick()\n##\n##\n##def makeUnderLine(u):\n## p = t.pos()\n## while t.pos()[0] > -320:\n## t.bk(5)\n## t.pu()\n## t.bk(5)\n## t.pd()\n##\n## t.write(str(u), align='left', font=('Times New Roman', 10))\n## t.pu()\n## t.goto(*p)\n## t.pd()\n##\n##t = turtle.Turtle()\n##turtle.delay(0)\n##t.speed(0)\n##t.hideturtle()\n##t.pensize(4)\n##t.pu()\n##t.goto(-300, -200)\n##t.pd()\n##t.fd(600)\n##t.pu()\n##t.goto(-300, -200)\n##t.pd()\n##t.goto(-300, +200)\n##t.pu()\n##t.pensize(2)\n##t.pencolor('red')\n##t.goto(-280, +180)\n##t.write(\"Able\", align='left', font=('Times New Roman',16))\n##t.goto(-300, -200)\n##t.pd()\n##\n##l1 = sorted(able.keys(), key=lambda x: x)\n##l11 = sorted(able.keys(), key=lambda x: able[x])\n##\n##l2 = sorted(baker.keys(), key=lambda x: x)\n##l22 = sorted(baker.keys(), key=lambda x: baker[x])\n##\n##d1 = 400 // max(able[l11[-1]], baker[l22[-1]])\n##d2 = 600 // max(l1[-1], l2[-1])\n##\n##for i in l1:\n## t.goto(i * d2 - 280, able[i] * d1 - 200)\n## # makeUnderLine(able[i])\n## t.write(str((able[i], i)), align='left', font=('Times New Roman', 10))\n##\n##t.pu()\n##t.pencolor('blue')\n##t.goto(-240, +180)\n##t.write(\"Baker\", align='left', font=('Times New Roman', 16))\n##t.goto(-300, -200)\n##t.pd()\n##\n##for i in l2:\n## t.goto(i * d2 - 280, baker[i] * d1 - 200)\n## #print(i, baker[i])\n## # makeUnderLine(baker[i])\n## t.write(str((baker[i], i)),align='left',font=('Times New Roman', 10))\n##\n##\n##turtle.done()\n","sub_path":"init2.py","file_name":"init2.py","file_ext":"py","file_size_in_byte":6092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"2302083","text":"import requests\nimport lxml.html\nimport time\n\n\ndef crawlRelatives(input_url,xpaths):\n wiki_prefix = 'https://en.wikipedia.org'\n mapped_urls = {}\n\n current_urls = [input_url]\n while len(mapped_urls.keys()) < 50:\n extracted_urls = []\n for curr_url in current_urls:\n if len(mapped_urls.keys()) >= 50:\n break\n time.sleep(1)\n res = requests.get(curr_url)\n doc = lxml.html.fromstring(res.content)\n\n for xpath in xpaths:\n if len(mapped_urls.keys()) >= 50:\n break\n new_urls = doc.xpath(xpath)\n for new_url in new_urls:\n if len(mapped_urls.keys()) >= 50:\n break\n if not (new_url.startswith('/wiki') or new_url.startswith(wiki_prefix)):\n continue\n full_url = wiki_prefix + new_url\n if full_url not in mapped_urls and full_url != input_url:\n extracted_urls.append(full_url)\n mapped_urls[full_url] = curr_url\n current_urls = extracted_urls\n\n list_of_pairs = []\n\n for key in mapped_urls.keys():\n list_of_pairs.append([mapped_urls[key], key])\n\n return list_of_pairs\n\n\n\nxpaths = [\"//tr[th='Mother']//@href[contains(.,'wiki')]\",\"//tr[th='Father']//@href[contains(.,'wiki')]\",\"//tr[th='Spouse']//@href[contains(.,'wiki')]\",\"//table[@class='wikitable']/tr/td/a/@href[contains(.,'wiki')]\",\"//tr[th='Family']//@href[contains(.,'wiki')]\",\"//tr[th='Issue']//@href[contains(.,'wiki')]\",\"//tr[th='Extended family']//@href[contains(.,'wiki')]\"]\nresult = crawlRelatives('https://en.wikipedia.org/wiki/Elizabeth_II',xpaths)\n\noutfile = open(\"Q2.elizabeth.txt\", \"w\")\nprint >> outfile, \"\\n\".join(i[0]+' , '+i[1] for i in result)\noutfile.close()","sub_path":"Q2.crawlRelatives.py","file_name":"Q2.crawlRelatives.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"27338821","text":"# 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 \n# \n# 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(\n# 一个节点也可以是它自己的祖先)。” \n# \n# 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] \n# \n# \n# \n# \n# \n# 示例 1: \n# \n# 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n# 输出: 3\n# 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。\n# \n# \n# 示例 2: \n# \n# 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n# 输出: 5\n# 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。\n# \n# \n# \n# \n# 说明: \n# \n# \n# 所有节点的值都是唯一的。 \n# p、q 为不同节点且均存在于给定的二叉树中。 \n# \n# Related Topics 树 \n# 👍 764 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n # 回溯算法: 后序遍历。找到p或q时,就将一层一层往上传递\n\n # 终止条件: 当前root为空,或者遇到p/q时,返回None或者p/q\n if not root or root == p or root == q: return root\n\n # 递归执行: 往左右子树遍历,得到返回来的值\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n\n # 对于当前root节点,它的左右子树返回来的left和right有4种情况\n # 1. l/r均为None,说明这个root不包含p/q,所以它返回None给上层\n # -> 从而所有非空,非p/q的节点,且不包含p/q的节点均向上返回None\n # 2&3. l和r其中有一个不是None,则返回另一个。\n # -> 两种情况:(以l为空为例)\n # 第一种: 右子树中包含p或q其中一个,从而返回来的是p或q节点,这种情况将会继续去找下一个\n # 第二种: 右子树中包含p和q,从而返回来的是p和q的公共祖先(在下面层中已经触及到了第4种情况了)\n if not left: return right\n if not right: return left\n\n # 4. 1/2/3均不满足,即l/r均不为空\n # -> 说明当前root节点的子左右树中分别包含了p和q,因此这个root为最近公共祖先\n return root\n \n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_03/[236]二叉树的最近公共祖先.py","file_name":"[236]二叉树的最近公共祖先.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"75630966","text":"#!/usr/bin/env python3\nimport base64\nimport paho.mqtt.client as mqtt\n\n\ntopic_num = {}\n\n# This is the Subscriber\ndanger = [\"train\"]\ndanger_items = [(\"topic/\"+i,0) for i in danger]\nprint(danger_items)\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n client.subscribe(danger_items)\n\ndef _on_message(client, userdata, msg):\n if msg.payload.decode() == \"Hello world!\":\n print(\"Yes!\")\n client.disconnect()\n\ndef on_message(client, obj, msg):\n # with open('/home/yicheng/python/test/new', 'wb') as fd:\n #fd.write(msg.payload)\n #print(msg)\n imgdata = base64.b64decode(msg.payload)\n\n top = msg.topic.split('/')[-1]\n if top in topic_num:\n topic_num[top] += 1\n else:\n topic_num[top] = 0\n\n filename = top + str(topic_num[top]) + '.jpg'\n with open(filename, 'wb') as f:\n f.write(imgdata)\n with open(\"latest.jpg\", 'wb') as f:\n f.write(imgdata)\n client.disconnect()\n\nwhile(True):\n\n client = mqtt.Client()\n client.connect(\"10.121.190.108\",1883,60)\n client.on_connect = on_connect\n #///////////////////////////////////////////////////\n client.on_message = on_message\n client.loop_forever()\n","sub_path":"MQTT/train/base64_pic_recieve_tran.py","file_name":"base64_pic_recieve_tran.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461886644","text":"if __name__ == '__main__':\n import sys, os\n sys.path.insert(0, os.path.abspath('./models'))\n\n from torch.utils.data import DataLoader\n from data import PascalVOCClassification\n from vgg_gap import vgg\n\n import torch\n import torch.optim as optim\n from torch.optim import lr_scheduler\n import numpy as np\n import torchvision\n from torchvision import datasets, models, transforms\n import matplotlib.pyplot as plt\n import time\n import os\n import copy\n\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # Set up dataloader\n pascal_train = PascalVOCClassification(source='train')\n pascal_val = PascalVOCClassification(source='val')\n\n dataloaders = {\n 'train': DataLoader(pascal_train, batch_size=16, shuffle=True, num_workers=6),\n 'val': DataLoader(pascal_val, batch_size=16, shuffle=False, num_workers=6)\n }\n\n def train_model(model, criterion, optimizer, scheduler, num_epochs=25):\n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train()\n else:\n model.eval()\n\n running_loss = 0.0\n running_corrects = 0\n\n count = 0\n for inputs, labels in dataloaders[phase]:\n count += 1\n\n inputs = inputs.permute(0, 3, 1, 2)\n inputs = inputs.to(device).float()\n labels = labels.to(device).float()\n\n optimizer.zero_grad()\n\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n loss = criterion(outputs, labels)\n\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n _, preds = torch.max(outputs, 1)\n _, labels_pred = torch.max(labels, 1)\n\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels_pred)\n\n epoch_loss = running_loss / count\n epoch_acc = running_corrects.double() / count\n \n print('{} batch: {} Loss: {:.4f} Acc: {:.4f}.............'.format(phase, count, epoch_loss, epoch_acc), end='\\r')\n\n if phase == 'train':\n scheduler.step()\n\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_model_wts = copy.deepcopy(model.state_dict())\n torch.save(model.state_dict(), './checkpoints/vgg_gap.pt')\n\n vgg.to(device)\n\n optimizer = torch.optim.Adam(vgg.parameters(), lr=0.0001)\n scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)\n train_model(vgg, torch.nn.BCELoss(), optimizer, scheduler)","sub_path":"classification/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"240663491","text":"import cv2\nimport numpy as np\n\n\ndef crop(file_name):\n \n mser = cv2.MSER_create()\n img = cv2.imread(file_name)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n vis = img.copy()\n rectImg = img.copy()\n regions, _ = mser.detectRegions(gray)\n hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]\n \n combinedContour = np.vstack(cnt for cnt in hulls)\n combinedContour = np.array(combinedContour)\n \n hull = cv2.convexHull(combinedContour)\n cv2.drawContours(vis,[hull],-1,(0,255,0),2) \n cv2.imshow('img', vis)\n cv2.waitKey(0)\n \n rect = cv2.minAreaRect(hull)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n cv2.drawContours(rectImg,[box],-1,(0,0,255),2)\n cv2.imshow('rectImg', rectImg)\n cv2.waitKey(0)\n \n mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)\n cv2.drawContours(mask,[box],-1,(255,255,255),-1) \n \n text_only = cv2.bitwise_and(img, img, mask=mask)\n cv2.imshow('text_only', text_only)\n cv2.waitKey(0)\n \n res = np.hstack((img,vis))\n res1 = np.hstack((rectImg,text_only))\n \n result = np.vstack((res,res1))\n cv2.imshow('result', result)\n cv2.waitKey(0)\n \n cv2.imwrite(\"data1_crop.jpg\",result)\n\nfile_name = 'data1.png'\ncrop(file_name) ","sub_path":"imageEnhance/CropText.py","file_name":"CropText.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"635950069","text":"choice = \"-\"\navailable_parts= [\"Monitor\",\n \"Keyboard\",\n \"Mouse\",\n \"SSD\",\n \"Optical Drive\",\n \"Pendrive\",\n \"Exit\" \n ]\nselected_choices=[]\navailable_choices=[str(i) for i in range(1,len(available_parts)+1)]\nprint(available_choices)\n\nwhile choice!=\"0\":\n if choice in available_choices:\n print(\"Adding {} \".format(choice))\n index=int(choice)-1\n selected_choices.append(available_parts[index])\n elif choice=='False':\n break\n\n else:\n print(\"Coose from the above list\")\n for index, item in enumerate(available_parts):\n print(\"{}: {}\".format(index+1,item))\n choice=input()\nelse:\n print(\"Have a nice day :)\" )\nprint(selected_choices)\n \n","sub_path":"List_comp.py","file_name":"List_comp.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"43699997","text":"fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n\ndef f2c(c):\n\tcDec = 0\n\tfor i in range(0,10):\n\t\tif c[i] == '1':\n\t\t\tcDec += fib[10-i]\n\treturn chr(cDec)\n\n\nflagEnc = open('flag.enc','r').read().split()\nflag = ''\nfor c in flagEnc:\n\tflag += f2c(c)\nprint(flag)","sub_path":"corCTF/fibinary/dec.py","file_name":"dec.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528564352","text":"#!/usr/bin/env python35\n# coding:utf-8\n\n'''\nCreate by Liush at 2017/02/07\n'''\n\nimport socket\nimport subprocess\n\n#HOST = '192.168.1.55'\n#PORT = 10086\n#SK = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n#SK.bind((HOST,PORT)) # 在 AF_INET 下,地址以元组的形式表示\n#SK.listen(5)\n\n\n# eg1: 客户端使用 shell 命令请求服务端\n\n#while True:\n # print(SK.accept())\n # (, ('192.168.1.55', 23698))\n# conn,addr = SK.accept()\n# while True:\n# #conn.recv() 接受客户端内容,接收到的是 bytes 类型数据。str(conn.recv(10240), encoding='utf-8') 用 'utf-8' 进行解码\n# data = str(conn.recv(10240),encoding='utf-8') \n# cmd_status,cmd_result = subprocess.getstatusoutput(data)\n# if len(cmd_result.strip()) == 0:\n# conn.sendall(bytes('Done', encoding='utf-8'))\n# else:\n# # 发送内容必须是 bytes 类型数据,bytes(cmd_result, encoding='utf-8')用 'utf-8' 进行编码\n# conn.sendall(bytes(cmd_result, encoding='utf-8')) \n#conn.close()\n\n\n# eg2: 简单实现客户端与服务端对话\n\n#while True:\n# Info = SK.accept()\n# print('客户端信息 : ',str(Info[1]))\n# while True:\n# r_data = str(Info[0].recv(1024),encoding='utf-8')\n# print('接收内容 : ',r_data)\n# if r_data == 'exit':break\n \n# s_data = input('Please input Send_Message : ')\n# Info[0].sendall(bytes(s_data, encoding='utf-8'))\n#Info[0].close()\n \n\n# eg3: 实现多进程\n\n#import socketserver\n#class MyServer(socketserver.BaseRequestHandler):\n# def handle(self):\n# while True:\n# conn = self.request\n# addr = self.client_address\n# print('客户端信息 : ',addr)\n# while True:\n# r_data = str(conn.recv(1024), encoding='utf-8')\n# print('接收内容 : ',r_data)\n# if r_data == 'exit':break\n \n# s_data = bytes(input('Please input Send_Message : '), encoding='utf-8')\n# conn.sendall(s_data)\n# conn.close()\n\n#if __name__ == '__main__':\n# server = socketserver.ThreadingTCPServer((\"192.168.1.55\", 10088), MyServer)\n# server.serve_forever()\n\n# eg4: 传输文件\nimport socketserver\nimport os\n\nclass MyServer(socketserver.BaseRequestHandler):\n def handle(self):\n BasePath = \"/home/liush\"\n Conn = self.request\n print(\"Connected by \",self.client_address)\n while True:\n r_data = Conn.recv(1024).decode('utf-8')\n cmd,file_name,file_size = r_data.split('|')\n r_size = 0\n FileDir = os.path.join(BasePath,file_name)\n \n with open(FileDir,'w') as F:\n Flag = True\n while Flag:\n if int(file_size) > r_size:\n Data = Conn.recv(1024).decode('utf-8')\n r_size += len(Data)\n else:\n r_size = 0\n Flag = False\n F.write(Data)\n print(\"Done\")\n\nif __name__ == '__main__':\n Server = socketserver.ThreadingTCPServer(('192.168.1.55',10088),MyServer)\n Server.serve_forever()\n\n","sub_path":"module/Socket/Socket_Server.py","file_name":"Socket_Server.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"50382560","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport scipy as sp\nimport scipy.optimize\n\n# 按照 MWR 方式计算年化收益率\n# example:\n# 10000元存了2个月,100000元存了1个月,最终变成了90000元,\n# 算出来年化收益率-0.89162962\n# cfDict = {'a':10000, 'b':100000, 'c':-90000}\n# wDict = {'a':2.0/12.0, 'b':1.0/12.0, 'c':0}\n# return -0.89162962\ndef calMWR(cfDict, tDict):\n '''用于计算MWR'''\n def f(r):\n fvLst = []\n for dt in tDict:\n t = tDict[dt]\n cf = cfDict[dt]\n # print(t, cf)\n fvLst.append(cf * np.exp(r*t))\n v = sum(fvLst)\n return v\n\n guess = 0.01\n x0 = guess\n sol = sp.optimize.root(f, x0, method='lm')\n return np.exp(sol.x) - 1, sol.success\n","sub_path":"scipy/mwr.py","file_name":"mwr.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"421943226","text":"import os\nimport unittest\nimport sys\n\nfrom fontanelle.client import App, main\nfrom fontanelle.region import Region\nfrom fontanelle.walker import SoftRegionFinder\n\n\nclass TestFontanelle(unittest.TestCase):\n\n def test_app(self):\n\n os.makedirs('tmp', exist_ok=True)\n\n app = App()\n\n app.run(['-i', 'tests/test_data/deletion.bam', '-o', 'tmp/deletion.bed'])\n app.run(['-i', 'tests/test_data/insertion_and_deletion.bam', '-o', 'tmp/insertion_and_deletion.bed'])\n\n with open('tmp/deletion.bed') as f:\n self.assertEqual(f.readlines(), ['chr2\\t47799941\\t47800001\\n'])\n\n with open('tmp/insertion_and_deletion.bed') as f:\n self.assertEqual(f.readlines(), ['chr2\\t47799732\\t47799778\\n', 'chr2\\t47799942\\t47800001\\n'])\n\n sys.argv = ['fontanelle', '-i', 'tests/test_data/deletion.bam', '-o', 'tmp/main_deletion.bed']\n main()\n with open('tmp/main_deletion.bed') as f:\n self.assertEqual(f.readlines(), ['chr2\\t47799941\\t47800001\\n'])\n\n def test_fontanelle_one_region(self):\n\n soft_region_finder = SoftRegionFinder(bam_file='tests/test_data/deletion.bam')\n\n soft_region_finder.depth_cutoff = 30\n soft_region_finder.soft_fraction_cutoff = 0.2\n soft_region_finder.minimum_region_length = 10\n\n regions = list(soft_region_finder.regions())\n\n self.assertEqual(len(regions), 1)\n\n self.assertEqual(regions[0].chromosome, 'chr2')\n self.assertEqual(regions[0].start, 47799942)\n self.assertEqual(regions[0].end, 47800001)\n\n def test_fontanelle_two_regions(self):\n\n soft_region_finder = SoftRegionFinder(bam_file='tests/test_data/insertion_and_deletion.bam')\n\n soft_region_finder.depth_cutoff = 30\n soft_region_finder.soft_fraction_cutoff = 0.1\n soft_region_finder.minimum_region_length = 10\n\n regions = list(soft_region_finder.regions())\n\n self.assertEqual(len(regions), 2)\n\n self.assertEqual(regions[0].chromosome, 'chr2')\n self.assertEqual(regions[0].start, 47799714)\n self.assertEqual(regions[0].end, 47799795)\n\n self.assertEqual(regions[1].chromosome, 'chr2')\n self.assertEqual(regions[1].start, 47799943)\n self.assertEqual(regions[1].end, 47800001)\n\n def test_region_class(self):\n\n self.assertEqual(Region(chromosome='chr1', start=1000, end=1000).length(), 1)\n self.assertEqual(Region(chromosome='chr1', start=1000, end=2000).length(), 1001)\n\n def set_non_integer_start():\n region = Region()\n region.start = 'a'\n\n def set_negative_start():\n region = Region()\n region.start = -1\n\n def set_start_after_end():\n region = Region()\n region.end = 1000\n region.start = 2000\n\n def set_non_integer_end():\n region = Region()\n region.end = 'z'\n\n def set_negative_end():\n region = Region()\n region.end = -1\n\n def set_end_before_start():\n region = Region()\n region.start = 2000\n region.end = 1000\n\n self.assertRaises(Exception, set_non_integer_start)\n self.assertRaises(Exception, set_negative_start)\n self.assertRaises(Exception, set_start_after_end)\n\n self.assertRaises(Exception, set_non_integer_end)\n self.assertRaises(Exception, set_negative_end)\n self.assertRaises(Exception, set_end_before_start)\n","sub_path":"tests/test_fontanelle.py","file_name":"test_fontanelle.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"329345073","text":"from django.urls import path,include\nfrom .import views\n\napp_name='user'\nurlpatterns = [\n path('home/',views.home),\n path('myprofile/',views.myprofile)\n #path('update_pro//',views.update_pro,name='update_pro')\n\n]\n","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"343731078","text":"from rest_framework import serializers\nfrom courses.models import Course, Contact, Branch\n\n\nclass ContactsSerializer(serializers.ModelSerializer):\n class Meta:\n model = Contact\n fields = ('value',)\n\n\nclass BranchesSerializer(serializers.ModelSerializer):\n class Meta:\n model = Branch\n fields = ('latitude', 'longitude', 'addres',)\n\n\nclass CourseDetailSerializer(serializers.ModelSerializer):\n contacts = ContactsSerializer(many=True)\n branches = BranchesSerializer(many=True)\n\n class Meta:\n model = Course\n fields = ('id', 'name', 'description', 'category', 'contacts', 'branches',)\n\n def create(self, validated_data):\n contacts = validated_data.pop('contacts')\n branches = validated_data.pop('branches')\n\n course = Course.objects.create(**validated_data)\n\n for contact in contacts:\n Contact.objects.create(course=course, **contact)\n\n for branch in branches:\n Branch.objects.create(course=course, **branch)\n\n return course\n\n","sub_path":"courses/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"577365427","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayTradeOrderSettleQueryModel(object):\n\n def __init__(self):\n self._out_request_no = None\n self._settle_no = None\n self._trade_no = None\n\n @property\n def out_request_no(self):\n return self._out_request_no\n\n @out_request_no.setter\n def out_request_no(self, value):\n self._out_request_no = value\n @property\n def settle_no(self):\n return self._settle_no\n\n @settle_no.setter\n def settle_no(self, value):\n self._settle_no = value\n @property\n def trade_no(self):\n return self._trade_no\n\n @trade_no.setter\n def trade_no(self, value):\n self._trade_no = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.out_request_no:\n if hasattr(self.out_request_no, 'to_alipay_dict'):\n params['out_request_no'] = self.out_request_no.to_alipay_dict()\n else:\n params['out_request_no'] = self.out_request_no\n if self.settle_no:\n if hasattr(self.settle_no, 'to_alipay_dict'):\n params['settle_no'] = self.settle_no.to_alipay_dict()\n else:\n params['settle_no'] = self.settle_no\n if self.trade_no:\n if hasattr(self.trade_no, 'to_alipay_dict'):\n params['trade_no'] = self.trade_no.to_alipay_dict()\n else:\n params['trade_no'] = self.trade_no\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayTradeOrderSettleQueryModel()\n if 'out_request_no' in d:\n o.out_request_no = d['out_request_no']\n if 'settle_no' in d:\n o.settle_no = d['settle_no']\n if 'trade_no' in d:\n o.trade_no = d['trade_no']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayTradeOrderSettleQueryModel.py","file_name":"AlipayTradeOrderSettleQueryModel.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"70735410","text":"today = 2021\nreqTime = 0\nage = 0\nwhile (True):\n ageOrYob = int(input(\"Enter your age or year of birth\"))\n\n if ageOrYob < 150 and ageOrYob > 0:\n reqTime = 100 - ageOrYob\n print(f\"You will be 100 years old in year {today + reqTime} or we can say in {reqTime} years\")\n break\n elif ageOrYob > 150 and ageOrYob <= 2021:\n age = today - ageOrYob\n reqTime = 100 - age\n print(f\"You will be 100 years old in year {today + reqTime} or we can say in {reqTime} years\")\n break\n else:\n print(\"Wrong age or year of birth entered\")\n continue\n","sub_path":"whenyouwillreach100.py","file_name":"whenyouwillreach100.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"606485268","text":"import drugs\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nimport numpy as np\r\n\r\nlist_of_report = drugs.get_reports()\r\n\r\ndef makeAvg(list):\r\n sum = 0\r\n for x in range(len(list)):\r\n sum += list[x]\r\n average = sum/len(list)\r\n return average\r\n\r\nmari = []\r\nageRange26mari = []\r\nfor n in list_of_report:\r\n ageRange26mari.append(n[\"Totals\"][\"Marijuana\"][\"Used Past Month\"][\"26+\"])\r\navg1 = makeAvg(ageRange26mari)\r\nmari.append(avg1)\r\n\r\nageRange1825mari = []\r\nfor n in list_of_report:\r\n ageRange1825mari.append(n[\"Totals\"][\"Marijuana\"][\"Used Past Month\"][\"18-25\"])\r\navg2 = makeAvg(ageRange1825mari)\r\nmari.append(avg2)\r\n\r\nageRange1217mari = []\r\nfor n in list_of_report:\r\n ageRange1217mari.append(n[\"Totals\"][\"Marijuana\"][\"Used Past Month\"][\"12-17\"])\r\navg3 = makeAvg(ageRange1217mari)\r\nmari.append(avg3)\r\n\r\nprint(\"marijuana use in past month, ages 26+, 18-25, 12-17 respectively: \" + str(mari))\r\n\r\n\r\nalc = []\r\nageRange26alc = []\r\nfor n in list_of_report:\r\n ageRange26alc.append(n[\"Totals\"][\"Alcohol\"][\"Use Past Month\"][\"26+\"])\r\navg4 = makeAvg(ageRange26alc)\r\nalc.append(avg4)\r\n\r\nageRange1825alc = []\r\nfor n in list_of_report:\r\n ageRange1825alc.append(n[\"Totals\"][\"Alcohol\"][\"Use Past Month\"][\"18-25\"])\r\navg5 = makeAvg(ageRange1825alc)\r\nalc.append(avg5)\r\n\r\nageRange1217alc = []\r\nfor n in list_of_report:\r\n ageRange1217alc.append(n[\"Totals\"][\"Alcohol\"][\"Use Past Month\"][\"12-17\"])\r\navg6 = makeAvg(ageRange1217alc)\r\nalc.append(avg6)\r\n\r\nprint(\"alcohol use in past month, ages 26+, 18-25, 12-17 respectively: \" + str(alc))\r\n\r\n\r\ntob = []\r\nageRange26tob = []\r\nfor n in list_of_report:\r\n ageRange26tob.append(n[\"Totals\"][\"Tobacco\"][\"Use Past Month\"][\"26+\"])\r\navg7 = makeAvg(ageRange26tob)\r\ntob.append(avg7)\r\n\r\nageRange1825tob = []\r\nfor n in list_of_report:\r\n ageRange1825tob.append(n[\"Totals\"][\"Tobacco\"][\"Use Past Month\"][\"18-25\"])\r\navg8 = makeAvg(ageRange1825tob)\r\ntob.append(avg8)\r\n\r\nageRange1217tob = []\r\nfor n in list_of_report:\r\n ageRange1217tob.append(n[\"Totals\"][\"Tobacco\"][\"Use Past Month\"][\"12-17\"])\r\navg9 = makeAvg(ageRange1217tob)\r\ntob.append(avg9)\r\n\r\nprint(\"tobacco use in past month, ages 26+, 18-25, 12-17 respectively: \" + str(tob))\r\n\r\n\r\nill= []\r\nageRange26ill = []\r\nfor n in list_of_report:\r\n ageRange26ill.append(n[\"Totals\"][\"Illicit Drugs\"][\"Used Past Month\"][\"26+\"])\r\navg10 = makeAvg(ageRange26ill)\r\nill.append(avg10)\r\n\r\nageRange1825ill = []\r\nfor n in list_of_report:\r\n ageRange1825ill.append(n[\"Totals\"][\"Illicit Drugs\"][\"Used Past Month\"][\"18-25\"])\r\navg11 = makeAvg(ageRange1825ill)\r\nill.append(avg11)\r\n\r\nageRange1217ill = []\r\nfor n in list_of_report:\r\n ageRange1217ill.append(n[\"Totals\"][\"Illicit Drugs\"][\"Used Past Month\"][\"12-17\"])\r\navg12 = makeAvg(ageRange1217ill)\r\nill.append(avg12)\r\n\r\nprint(\"illicit drug use in past month, ages 26+, 18-25, 12-17 respectively: \" + str(ill))\r\n\r\ntotal = [mari, alc, tob, ill]\r\n\r\n\r\n\r\nnp.random.seed(0)\r\n\r\nn_bins = 4\r\nx = [[avg1], [avg2], [avg3], [avg4], [avg5], [avg6], [avg7], [avg8], [avg9], [avg10], [avg11], [avg12]]\r\n\r\n#fig, axes = plt.subplots(nrows=2, ncols=2)\r\n#ax0, ax1, ax2, ax3 = axes.flatten()\r\n\r\ncolors = ['red', 'tan', 'lime', 'red', 'tan', 'lime', 'red', 'tan', 'lime', 'red', 'tan', 'lime']\r\nage = [\"12-17\", \"18-25\", \"26+\"]\r\nplt.hist(x, n_bins, histtype='bar', color=colors, label=age, orientation = 'horizontal')\r\nplt.legend(prop={'size': 5})\r\nplt.title('pls help')\r\nplt.axis([0, 2, 0, 200000])\r\n\r\nplt.show()\r\n","sub_path":"seedrug.py","file_name":"seedrug.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"637581064","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.keras.engine.data_adapter import train_validation_split\nfrom sklearn.model_selection import train_test_split\n\n#1. 데이터\nx = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])\ny = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13])\n\n# train_test_split으로 만들어라\nx_train, x_ren, y_train, y_ren = train_test_split(x, y, train_size=0.6)\nx_val, x_test, y_val, y_test = train_test_split(x_ren, y_ren, test_size=0.5)\n\n# x_train = np.array([1,2,3,4,5,6,7]) # 훈련, 공부하는 거 \n# y_train = np.array([1,2,3,4,5,6,7])\n \n# x_test = np.array([8,9,10]) # 평가하는 거\n# y_test = np.array([8,9,10])\n# x_val = np.array([11,12,13])\n# y_val = np.array([11,12,13])\n\n# #2. 모델 구성\nmodel = Sequential()\nmodel.add(Dense(5, input_dim=1)) #첫번째 hidden layer가 노드가 5개라면, input은 1개.\nmodel.add(Dense(4))\nmodel.add(Dense(3))\nmodel.add(Dense(1))\n\n# #3. 컴파일, 훈련\nmodel.compile(loss='mse', optimizer='adam') # 컴퓨터가 이해하도록 컴파일\n\nmodel.fit(x_train, y_train, epochs=1000, batch_size=1, validation_data=(x_val, y_val)) # 훈련시키는 fit에서 검증을 하게 된다.\n\n# #4. 평가, 예측\nloss = model.evaluate(x_test, y_test)\nprint('loss : ', loss)\n\ny_predict = model.predict([11])\nprint('11의 예측값 : ', y_predict)\n\n# # plt.scatter(x, y)\n# plt.plot(x, y_predict, color='red')\n# plt.show()","sub_path":"keras10_validation3_train_test.py","file_name":"keras10_validation3_train_test.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"437236480","text":"import dash_bootstrap_components as dbc\nimport dash\nimport dash_core_components as dcc\n\napp = dash.Dash(\n external_stylesheets=[dbc.themes.BOOTSTRAP]\n)\n\napp.layout = dbc.Container([\n dbc.Alert(\"Hello Bootstrap!\", color=\"success\"),\n dcc.Slider(id=\"Q1\",marks ={\n 0: '0 °F',\n 3: '3 °F',\n 5: '5 °F',\n 7.65: '7.65 °F',\n 10: '10 °F'\n }, ),\n]\n)\n\nif __name__ == \"__main__\":\n app.run_server(debug=True,port=8080)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567327118","text":"from datetime import datetime\nfrom tecton import TemporalAggregateFeaturePackage, FeatureAggregation, sql_transformation, MaterializationConfig\nfrom feature_repo.shared import data_sources, entities\n\n@sql_transformation(inputs=data_sources.ad_impressions_stream)\ndef user_ad_impression_counts_transformer(input_df):\n return f\"\"\"\n select\n user_uuid,\n ad_id,\n 1 as impression,\n timestamp\n from\n {input_df}\n \"\"\"\n\n\nuser_ad_impression_counts = TemporalAggregateFeaturePackage(\n name=\"user_ad_impression_counts\",\n description=\"[Stream Feature] The number of times a given user has been shown a given ad over various time windows\",\n entities=[entities.user_entity, entities.ad_entity],\n transformation=user_ad_impression_counts_transformer,\n aggregation_slide_period=\"1h\",\n aggregations=[FeatureAggregation(column=\"impression\", function=\"count\", time_windows=[\"1h\", \"12h\", \"24h\",\"72h\",\"168h\"])],\n materialization=MaterializationConfig(\n online_enabled=True,\n offline_enabled=True,\n feature_start_time=datetime(2020, 6, 1),\n ),\n family='ad_serving',\n tags={'release': 'development'},\n owner=\"jay@tecton.ai\"\n)\n","sub_path":"feature_store/feature_repo/shared/features/user_ad_impression_counts.py","file_name":"user_ad_impression_counts.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"270110325","text":"from types import SimpleNamespace\nfrom typing import List, Optional\n\nfrom dt_shell import DTCommandAbs, dtslogger, DTShell, __version__ as shell_version\n\nimport argparse\nimport pathlib\nimport json\nimport os\nimport shutil\nimport subprocess\nimport time\nimport docker\nimport socket\nimport getpass\nfrom datetime import datetime\n\nfrom utils.cli_utils import ask_confirmation\nfrom utils.duckietown_utils import get_distro_version\nfrom utils.misc_utils import human_time\n\nfrom disk_image.create.constants import (\n PARTITION_MOUNTPOINT,\n FILE_PLACEHOLDER_SIGNATURE,\n TMP_WORKDIR,\n DISK_IMAGE_STATS_LOCATION,\n DOCKER_IMAGE_TEMPLATE,\n MODULES_TO_LOAD,\n DATA_STORAGE_DISK_IMAGE_DIR,\n AUTOBOOT_STACKS_DIR,\n DEFAULT_STACK,\n)\n\nfrom disk_image.create.utils import (\n VirtualSDCard,\n check_cli_tools,\n pull_docker_image,\n disk_template_partitions,\n disk_template_objects,\n find_placeholders_on_disk,\n get_file_first_line,\n get_file_length,\n run_cmd,\n run_cmd_in_partition,\n validator_autoboot_stack,\n validator_yaml_syntax,\n transfer_file,\n replace_in_file,\n list_files,\n copy_file,\n get_validator_fcn,\n)\n\n\n# NOTE: -----------------------------------\n# The input image is ubuntu 20.04.2, it was downloaded, flashed to an SD card and:\n# - password was set to `quackquack`, user remained `ubuntu`\n# - cmd: `sudo apt update`\n# - cmd: `sudo apt full-upgrade`\n# - cmd: `sudo apt install rsync docker.io docker-compose cloud-guest-utils inotify-tools`\n# - cmd: `sudo apt autoremove`\n# SD card was then dumped into an .img file and uploaded to S3\n# -----------------------------------------\n\n\n# TODO:\n# - fix camera\n#\n#\n\nDISK_IMAGE_PARTITION_TABLE = {\"system-boot\": 1, \"writeable\": 2}\nROOT_PARTITION = \"writeable\"\nDISK_IMAGE_SIZE_GB = 10\nDISK_IMAGE_VERSION = \"2.0.0\"\nUBUNTU_VERSION = \"20.04.2\"\nDEVICE_ARCH = \"arm64v8\"\nUBUNTU_DISK_IMAGE_NAME = f\"ubuntu-rpi-v{UBUNTU_VERSION}\"\nINPUT_DISK_IMAGE_URL = (\n f\"https://duckietown-public-storage.s3.amazonaws.com/disk_image/disk_template/\"\n f\"{UBUNTU_DISK_IMAGE_NAME}.zip\"\n)\nTEMPLATE_FILE_VALIDATOR = {\n \"APP:/data/autoboot/*.yaml\": lambda *a, **kwa: validator_autoboot_stack(*a, **kwa),\n \"APP:/data/config/calibrations/*/default.yaml\": lambda *a, **kwa: validator_yaml_syntax(*a, **kwa),\n}\nCOMMAND_DIR = os.path.dirname(os.path.abspath(__file__))\nDISK_TEMPLATE_DIR = os.path.join(COMMAND_DIR, \"disk_template\")\nSTACKS_DIR = os.path.join(COMMAND_DIR, \"..\", \"..\", \"..\", \"stack\", \"stacks\", DEFAULT_STACK)\nSUPPORTED_STEPS: List[Optional[str]] = [\n \"download\",\n \"create\",\n \"mount\",\n \"resize\",\n \"upgrade\",\n \"docker\",\n \"setup\",\n \"finalize\",\n \"unmount\",\n \"compress\",\n]\nMANDATORY_STEPS = [\"create\", \"mount\", \"unmount\"]\n\nAPT_PACKAGES_TO_INSTALL = [\n \"rsync\",\n \"nano\",\n \"htop\",\n \"i2c-tools\",\n \"libraspberrypi-bin\",\n \"docker.io\",\n \"avahi-daemon\",\n \"libnss-mdns\",\n \"docker-compose\",\n # provides the command `growpart`, used to resize the root partition at first boot\n \"cloud-guest-utils\",\n # provides the command `inotifywait`, used to monitor inode events on trigger sockets\n \"inotify-tools\",\n]\nAPT_PACKAGES_TO_HOLD = [\n # list here packages that cannot be updated through `chroot`\n \"initramfs-tools\"\n]\n\n\nclass DTCommand(DTCommandAbs):\n\n help = \"Prepares an .img disk file for a Raspberry Pi\"\n\n @staticmethod\n def command(shell: DTShell, args, **kwargs):\n parser = argparse.ArgumentParser()\n # define parser arguments\n parser.add_argument(\n \"--steps\",\n type=str,\n default=\",\".join(SUPPORTED_STEPS),\n help=\"List of steps to perform (comma-separated)\",\n )\n parser.add_argument(\n \"--no-steps\", type=str, default=\"\", help=\"List of steps to skip (comma-separated)\"\n )\n parser.add_argument(\n \"-o\", \"--output\", type=str, default=None, help=\"The destination directory for the output files\"\n )\n parser.add_argument(\n \"--no-cache\",\n default=False,\n action=\"store_true\",\n help=\"Whether to use previously downloaded base ISO image/zip archive (download step)\",\n )\n parser.add_argument(\n \"--workdir\", type=str, default=TMP_WORKDIR, help=\"(Optional) temporary working directory to use\"\n )\n parser.add_argument(\n \"--cache-target\",\n type=str,\n default=None,\n help=\"Target (cached) step to start from\",\n )\n parser.add_argument(\n \"--cache-record\",\n type=str,\n default=None,\n help=\"Step to cache\",\n )\n parser.add_argument(\n \"--continue\",\n dest=\"do_continue\",\n default=False,\n action=\"store_true\",\n help=\"Continue with the current artefact, do not overwrite (experts only)\",\n )\n parser.add_argument(\n \"--push\",\n default=False,\n action=\"store_true\",\n help=\"Whether to push the final compressed image to the Duckietown Cloud Storage\",\n )\n # parse arguments\n parsed = parser.parse_args(args=args)\n stime = time.time()\n # check given steps\n f = lambda s: len(s) > 0\n parsed.steps = parsed.steps.split(\",\")\n parsed.steps = list(filter(f, parsed.steps))\n non_supported_steps = set(parsed.steps).difference(set(SUPPORTED_STEPS))\n if len(non_supported_steps):\n dtslogger.error(f\"These steps are not supported: {non_supported_steps}\")\n return\n # check given steps (to skip)\n parsed.no_steps = parsed.no_steps.split(\",\")\n parsed.no_steps = list(filter(f, parsed.no_steps))\n non_supported_steps = set(parsed.no_steps).difference(set(SUPPORTED_STEPS))\n if len(non_supported_steps):\n dtslogger.error(f\"These steps are not supported: {non_supported_steps}\")\n return\n # remove skipped steps\n if len(parsed.no_steps) > 0:\n skipped = set(parsed.steps).intersection(set(parsed.no_steps))\n parsed.steps = set(parsed.steps).difference(skipped)\n dtslogger.info(f\"Skipping steps: [{', '.join(skipped)}]\")\n # check steps caching\n if parsed.cache_target not in [None] + SUPPORTED_STEPS:\n dtslogger.error(f\"Unknown step `{parsed.cache_target}`\")\n return\n if parsed.cache_record not in [None] + SUPPORTED_STEPS:\n dtslogger.error(f\"Unknown step `{parsed.cache_record}`\")\n return\n # check dependencies\n check_cli_tools()\n # make sure the token is set\n # noinspection PyBroadException\n try:\n shell.get_dt1_token()\n except Exception:\n dtslogger.error(\n \"You have not set a token for this shell.\\n\"\n \"You can get a token from the following URL,\\n\\n\"\n \"\\thttps://www.duckietown.org/site/your-token \\n\\n\"\n \"and set it using the following command,\\n\\n\"\n \"\\tdts tok set\\n\"\n )\n return\n # check if the output directory exists, create it if it does not\n if parsed.output is None:\n parsed.output = os.getcwd()\n if not os.path.exists(parsed.output):\n os.makedirs(parsed.output)\n # define output file template\n in_file_path = lambda ex: os.path.join(parsed.workdir, f\"{UBUNTU_DISK_IMAGE_NAME}.{ex}\")\n input_image_name = pathlib.Path(in_file_path(\"img\")).stem\n output_image_name = input_image_name.replace(UBUNTU_VERSION, DISK_IMAGE_VERSION)\n out_file_name = lambda ex: f\"dt-{output_image_name}.{ex}\"\n out_file_path = lambda ex: os.path.join(parsed.output, out_file_name(ex))\n cached_step_file_path = lambda step, ex: os.path.join(\n parsed.output, \"cache\", out_file_name(ex) + f\".{step}\"\n )\n # get version\n distro = get_distro_version(shell)\n # create a virtual SD card object\n sd_card = VirtualSDCard(out_file_path(\"img\"), DISK_IMAGE_PARTITION_TABLE)\n # this is the surgey plan that will be performed by the init_sd_card command\n surgery_plan = []\n # define disk image origin\n disk_image_origin = in_file_path(\"img\")\n using_cached_step = False\n # this holds the stats that will be stored in /data/stats/disk_image/build.json\n stats = {\n \"steps\": {step: bool(step in parsed.steps) for step in SUPPORTED_STEPS},\n \"version\": DISK_IMAGE_VERSION,\n \"input_name\": input_image_name,\n \"input_url\": INPUT_DISK_IMAGE_URL,\n \"base_type\": \"Ubuntu\",\n \"base_version\": UBUNTU_VERSION,\n \"environment\": {\n \"hostname\": socket.gethostname(),\n \"user\": getpass.getuser(),\n \"shell_version\": shell_version,\n \"commands_version\": shell.get_commands_version(),\n },\n \"modules\": [\n DOCKER_IMAGE_TEMPLATE(\n owner=module[\"owner\"],\n module=module[\"module\"],\n version=distro,\n tag=module[\"tag\"] if \"tag\" in module else None,\n arch=DEVICE_ARCH,\n )\n for module in MODULES_TO_LOAD\n ],\n \"template\": {\"directories\": [], \"files\": []},\n \"disk_size_gb\": DISK_IMAGE_SIZE_GB,\n \"stamp\": time.time(),\n \"stamp_human\": datetime.now().isoformat(),\n }\n\n # create caching function\n def cache_step(step):\n if step != parsed.cache_record:\n return\n # cache step\n dtslogger.info(f\"Caching step '{step}'...\")\n cache_file_path = cached_step_file_path(step, \"img\")\n copy_file(out_file_path(\"img\"), cache_file_path)\n dtslogger.info(f\"Step '{step}' cached.\")\n\n # use cached step\n if parsed.cache_target is not None:\n disk_image_origin = cached_step_file_path(parsed.cache_target, \"img\")\n if not os.path.isfile(disk_image_origin):\n dtslogger.error(f\"No cached artifact found for step `{parsed.cache_target}`\")\n return\n for step in SUPPORTED_STEPS[: SUPPORTED_STEPS.index(parsed.cache_target) + 1]:\n if step in MANDATORY_STEPS:\n continue\n parsed.steps.remove(step)\n using_cached_step = True\n\n # ---\n print()\n dtslogger.info(f\"Steps to perform: {[s for s in SUPPORTED_STEPS if s in parsed.steps]}\")\n #\n # STEPS:\n #\n # ------>\n # Step: download\n if \"download\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: download\")\n # clear cache (if requested)\n if parsed.no_cache:\n dtslogger.info(\"Clearing cache\")\n if os.path.exists(parsed.workdir):\n if parsed.workdir != TMP_WORKDIR:\n dtslogger.warn(\n \"A custom working directory is being used. The flag \"\n \"--no-cache does not have an effect in this case.\"\n )\n else:\n shutil.rmtree(parsed.workdir)\n # create temporary dir\n run_cmd([\"mkdir\", \"-p\", parsed.workdir])\n # download zip (if necessary)\n dtslogger.info(\"Looking for ZIP image file...\")\n if not os.path.isfile(in_file_path(\"zip\")):\n dtslogger.info(\"Downloading ZIP image...\")\n shell.include.data.get.command(\n shell,\n [],\n parsed=SimpleNamespace(\n file=[in_file_path(\"zip\")],\n object=[\n os.path.join(\n DATA_STORAGE_DISK_IMAGE_DIR, \"disk_template\", f\"{UBUNTU_DISK_IMAGE_NAME}.zip\"\n )\n ],\n space=\"public\",\n ),\n )\n else:\n dtslogger.info(f\"Reusing cached ZIP image file [{in_file_path('zip')}].\")\n # unzip (if necessary)\n if not os.path.isfile(in_file_path(\"img\")):\n dtslogger.info(\"Extracting ZIP image...\")\n try:\n run_cmd([\"unzip\", in_file_path(\"zip\"), \"-d\", parsed.workdir])\n except KeyboardInterrupt as e:\n dtslogger.info(\"Cleaning up...\")\n run_cmd([\"rm\", \"-f\", in_file_path(\"img\")])\n raise e\n else:\n dtslogger.info(f\"Reusing cached DISK image file [{in_file_path('img')}].\")\n # ---\n cache_step(\"download\")\n dtslogger.info(\"Step END: download\\n\")\n # Step: download\n # <------\n #\n # ------>\n # Step: create\n if \"create\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: create\")\n # check if the destination image already exists\n if os.path.exists(out_file_path(\"img\")):\n msg = (\n f\"The destination file {out_file_path('img')} already exists. \"\n f\"If you proceed, the file will be overwritten.\"\n )\n granted = ask_confirmation(msg)\n if not granted:\n dtslogger.info(\"Aborting.\")\n return\n # create empty disk image\n if not using_cached_step:\n dtslogger.info(f\"Creating empty disk image [{out_file_path('img')}]\")\n run_cmd(\n [\n \"dd\",\n \"if=/dev/zero\",\n f\"of={out_file_path('img')}\",\n f\"bs={1024 * 1024}\",\n f\"count={1024 * DISK_IMAGE_SIZE_GB}\",\n ]\n )\n dtslogger.info(\"Empty disk image created!\")\n # make copy of the disk image\n dtslogger.info(f\"Copying [{disk_image_origin}] -> [{out_file_path('img')}]\")\n run_cmd(\n [\n \"dd\",\n f\"if={disk_image_origin}\",\n f\"of={out_file_path('img')}\",\n f\"bs={1024 * 1024}\",\n \"\" if using_cached_step else \"conv=notrunc\",\n ]\n )\n # flush buffer\n dtslogger.info(\"Flushing I/O buffer...\")\n run_cmd([\"sync\"])\n # ---\n cache_step(\"create\")\n dtslogger.info(\"Step END: create\\n\")\n # Step: create\n # <------\n #\n # ------>\n # Step: mount\n if \"mount\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: mount\")\n # check if the destination image is already mounted\n loopdev = VirtualSDCard.find_loopdev(out_file_path(\"img\"))\n sd_card.set_loopdev(loopdev)\n if loopdev:\n dtslogger.warn(\n f\"The destination file {out_file_path('img')} already exists \"\n f\"and is mounted to {sd_card.loopdev}, skipping the 'mount' step.\"\n )\n else:\n # mount disk image\n dtslogger.info(f\"Mounting {out_file_path('img')}...\")\n sd_card.mount()\n dtslogger.info(f\"Disk {out_file_path('img')} successfully mounted \" f\"on {sd_card.loopdev}\")\n # ---\n cache_step(\"mount\")\n dtslogger.info(\"Step END: mount\\n\")\n # Step: mount\n # <------\n #\n # ------>\n # Step: resize\n if \"resize\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: resize\")\n # make sure that the disk is mounted\n if not sd_card.is_mounted():\n dtslogger.error(f\"The disk {out_file_path('img')} is not mounted.\")\n return\n # get root partition id\n root_device = sd_card.partition_device(ROOT_PARTITION)\n # resize root partition to take the entire disk\n run_cmd(\n [\n \"sudo\",\n \"parted\",\n \"-s\",\n sd_card.loopdev,\n \"resizepart\",\n str(DISK_IMAGE_PARTITION_TABLE[ROOT_PARTITION]),\n \"100%\",\n ]\n )\n # force driver to reload file size\n run_cmd([\"sudo\", \"losetup\", \"-c\", sd_card.loopdev])\n # show info about disk\n dtslogger.debug(\"\\n\" + run_cmd([\"sudo\", \"fdisk\", \"-l\", sd_card.loopdev], True))\n # fix file system\n run_cmd([\"sudo\", \"e2fsck\", \"-y\", \"-f\", root_device])\n # resize file system\n run_cmd([\"sudo\", \"resize2fs\", root_device])\n # ---\n cache_step(\"resize\")\n dtslogger.info(\"Step END: resize\\n\")\n # Step: resize\n # <------\n #\n # ------>\n # Step: upgrade\n if \"upgrade\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: upgrade\")\n # from this point on, if anything weird happens, unmount the disk\n try:\n # make sure that the disk is mounted\n if not sd_card.is_mounted():\n dtslogger.error(f\"The disk {out_file_path('img')} is not mounted.\")\n return\n # check if the root disk device exists\n root_partition_disk = sd_card.partition_device(ROOT_PARTITION)\n if not os.path.exists(root_partition_disk):\n raise ValueError(f\"Disk device {root_partition_disk} not found\")\n # mount `root` partition\n sd_card.mount_partition(ROOT_PARTITION)\n # from this point on, if anything weird happens, unmount the `root` disk\n try:\n # copy QEMU, resolvconf\n _transfer_file(ROOT_PARTITION, [\"usr\", \"bin\", \"qemu-aarch64-static\"])\n _transfer_file(ROOT_PARTITION, [\"run\", \"systemd\", \"resolve\", \"stub-resolv.conf\"])\n # mount /dev from the host\n _dev = os.path.join(PARTITION_MOUNTPOINT(ROOT_PARTITION), \"dev\")\n run_cmd([\"sudo\", \"mount\", \"--bind\", \"/dev\", _dev])\n # configure the kernel for QEMU\n run_cmd(\n [\n \"docker\",\n \"run\",\n \"--rm\",\n \"--privileged\",\n \"multiarch/qemu-user-static:register\",\n \"--reset\",\n ]\n )\n # try running a simple echo from the new chroot, if an error occurs, we need\n # to check the QEMU configuration\n try:\n output = run_cmd_in_partition(\n ROOT_PARTITION, 'echo \"Hello from an ARM chroot\"', get_output=True\n )\n if \"Exec format error\" in output:\n raise Exception(\"Exec format error\")\n except (BaseException, subprocess.CalledProcessError) as e:\n dtslogger.error(\n \"An error occurred while trying to run an ARM binary \"\n \"from the temporary chroot.\\n\"\n \"This usually indicates a misconfiguration of QEMU \"\n \"on the host.\\n\"\n \"Please, make sure that you have the packages \"\n \"'qemu-user-static' and 'binfmt-support' installed \"\n \"via APT.\\n\\n\"\n \"The full error is:\\n\\t%s\" % str(e)\n )\n exit(2)\n # compile list of packages to hold\n to_hold = \" \".join(APT_PACKAGES_TO_HOLD)\n # from this point on, if anything weird happens, unmount the `root` disk\n try:\n # run full-upgrade on the new root\n run_cmd_in_partition(\n ROOT_PARTITION,\n \"apt update && \"\n + (f\"apt-mark hold {to_hold}\" if len(to_hold) else \":\")\n + \" && \"\n + \"apt --yes --force-yes --no-install-recommends\"\n ' -o Dpkg::Options::=\"--force-confdef\"'\n ' -o Dpkg::Options::=\"--force-confold\"'\n \" full-upgrade && \" + (f\"apt-mark unhold {to_hold}\" if len(to_hold) else \":\"),\n )\n # install packages\n if APT_PACKAGES_TO_INSTALL:\n pkgs = \" \".join(APT_PACKAGES_TO_INSTALL)\n run_cmd_in_partition(\n ROOT_PARTITION,\n \"DEBIAN_FRONTEND=noninteractive \"\n f\"apt install --yes --force-yes --no-install-recommends {pkgs}\",\n )\n # clean packages\n run_cmd_in_partition(\n ROOT_PARTITION,\n f\"apt autoremove --yes\",\n )\n except Exception as e:\n raise e\n # unomunt bind /dev\n run_cmd([\"sudo\", \"umount\", _dev])\n except Exception as e:\n sd_card.umount_partition(ROOT_PARTITION)\n raise e\n # unmount ROOT_PARTITION\n sd_card.umount_partition(ROOT_PARTITION)\n # ---\n except Exception as e:\n sd_card.umount()\n raise e\n # ---\n cache_step(\"upgrade\")\n dtslogger.info(\"Step END: upgrade\\n\")\n # Step: upgrade\n # <------\n #\n # ------>\n # Step: docker\n if \"docker\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: docker\")\n # from this point on, if anything weird happens, unmount the disk\n try:\n # make sure that the disk is mounted\n if not sd_card.is_mounted():\n dtslogger.error(f\"The disk {out_file_path('img')} is not mounted.\")\n return\n # check if the corresponding disk device exists\n partition_disk = sd_card.partition_device(ROOT_PARTITION)\n if not os.path.exists(partition_disk):\n raise ValueError(f\"Disk device {partition_disk} not found\")\n # mount device\n sd_card.mount_partition(ROOT_PARTITION)\n # get local docker client\n local_docker = docker.from_env()\n # pull dind image\n pull_docker_image(local_docker, \"docker:dind\")\n # run auxiliary Docker engine\n remote_docker_dir = os.path.join(PARTITION_MOUNTPOINT(ROOT_PARTITION), \"var\", \"lib\", \"docker\")\n remote_docker_engine_container = local_docker.containers.run(\n image=\"docker:dind\",\n detach=True,\n remove=True,\n auto_remove=True,\n publish_all_ports=True,\n privileged=True,\n name=\"dts-disk-image-aux-docker\",\n volumes={remote_docker_dir: {\"bind\": \"/var/lib/docker\", \"mode\": \"rw\"}},\n entrypoint=[\"dockerd\", \"--host=tcp://0.0.0.0:2375\", \"--bridge=none\"],\n )\n dtslogger.info(\"Waiting 20 seconds for DIND to start...\")\n time.sleep(20)\n # get IP address of the container\n container_info = local_docker.api.inspect_container(\"dts-disk-image-aux-docker\")\n container_ip = container_info[\"NetworkSettings\"][\"IPAddress\"]\n # create remote docker client\n endpoint_url = f\"tcp://{container_ip}:2375\"\n dtslogger.info(f\"DIND should now be up, using endpoint URL `{endpoint_url}`.\")\n remote_docker = docker.DockerClient(base_url=endpoint_url)\n # from this point on, if anything weird happens, stop container and unmount disk\n try:\n dtslogger.info(\"Transferring Docker images...\")\n # pull images inside the disk image\n for module in MODULES_TO_LOAD:\n image = DOCKER_IMAGE_TEMPLATE(\n owner=module[\"owner\"],\n module=module[\"module\"],\n version=distro,\n tag=module[\"tag\"] if \"tag\" in module else None,\n arch=DEVICE_ARCH,\n )\n pull_docker_image(remote_docker, image)\n # ---\n dtslogger.info(\"Docker images successfully transferred!\")\n except Exception as e:\n # unmount disk\n sd_card.umount()\n raise e\n finally:\n # stop container\n remote_docker_engine_container.stop()\n # unmount partition\n sd_card.umount_partition(ROOT_PARTITION)\n # ---\n except Exception as e:\n # unmount disk\n sd_card.umount()\n raise e\n # ---\n cache_step(\"docker\")\n dtslogger.info(\"Step END: docker\\n\")\n # Step: docker\n # <------\n #\n # ------>\n # Step: setup\n if \"setup\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: setup\")\n # from this point on, if anything weird happens, unmount the disk\n try:\n # make sure that the disk is mounted\n if not sd_card.is_mounted():\n dtslogger.error(f\"The disk {out_file_path('img')} is not mounted.\")\n return\n # find partitions to update\n partitions = disk_template_partitions(DISK_TEMPLATE_DIR)\n # put template objects inside the stats object\n for partition in partitions:\n stats[\"template\"][\"directories\"] = list(\n map(\n lambda u: u[\"relative\"],\n disk_template_objects(DISK_TEMPLATE_DIR, partition, \"directory\"),\n )\n )\n stats[\"template\"][\"files\"] = list(\n map(\n lambda u: u[\"relative\"],\n disk_template_objects(DISK_TEMPLATE_DIR, partition, \"file\"),\n )\n )\n # make sure that all the partitions are there\n for partition in partitions:\n # check if the partition defined in the disk_template dir exists\n if partition not in DISK_IMAGE_PARTITION_TABLE:\n raise ValueError(f\"Partition {partition} not declared in partition table\")\n # check if the corresponding disk device exists\n partition_disk = sd_card.partition_device(partition)\n if not os.path.exists(partition_disk):\n raise ValueError(f\"Disk device {partition_disk} not found\")\n # mount device\n sd_card.mount_partition(partition)\n # from this point on, if anything weird happens, unmount the disk\n try:\n dtslogger.info(f'Updating partition \"{partition}\":')\n # create directory structure from disk template\n dirs = disk_template_objects(DISK_TEMPLATE_DIR, partition, \"directory\")\n for update in dirs:\n dtslogger.info(f\"- Creating directory [{update['relative']}]\")\n # create destination\n run_cmd([\"sudo\", \"mkdir\", \"-p\", update[\"destination\"]])\n # copy stacks (APP only)\n if partition == ROOT_PARTITION:\n for stack in list_files(STACKS_DIR, \"yaml\"):\n origin = os.path.join(STACKS_DIR, stack)\n destination = os.path.join(\n PARTITION_MOUNTPOINT(partition), AUTOBOOT_STACKS_DIR.lstrip(\"/\"), stack\n )\n relative = os.path.join(AUTOBOOT_STACKS_DIR, stack)\n # validate file\n validator = _get_validator_fcn(partition, relative)\n if validator:\n dtslogger.debug(f\"Validating file {relative}...\")\n validator(shell, origin, relative, arch=DEVICE_ARCH)\n # create or modify file\n effect = \"MODIFY\" if os.path.exists(destination) else \"NEW\"\n dtslogger.info(f\"- Updating file ({effect}) [{relative}]\")\n # copy new file\n run_cmd([\"sudo\", \"cp\", origin, destination])\n # add architecture as default value in the stack file\n dtslogger.debug(\n \"- Replacing '{ARCH}' with '{ARCH:-%s}' in %s\"\n % (DEVICE_ARCH, destination)\n )\n replace_in_file(\"{ARCH}\", \"{ARCH:-%s}\" % DEVICE_ARCH, destination)\n # apply changes from disk_template\n files = disk_template_objects(DISK_TEMPLATE_DIR, partition, \"file\")\n for update in files:\n # validate file\n validator = _get_validator_fcn(partition, update[\"relative\"])\n if validator:\n dtslogger.debug(f\"Validating file {update['relative']}...\")\n validator(shell, update[\"origin\"], update[\"relative\"], arch=DEVICE_ARCH)\n # create or modify file\n effect = \"MODIFY\" if os.path.exists(update[\"destination\"]) else \"NEW\"\n dtslogger.info(f\"- Updating file ({effect}) [{update['relative']}]\")\n # copy new file\n run_cmd([\"sudo\", \"cp\", update[\"origin\"], update[\"destination\"]])\n # get first line of file\n file_first_line = get_file_first_line(update[\"destination\"])\n # only files containing a known placeholder will be part of the surgery\n if file_first_line.startswith(FILE_PLACEHOLDER_SIGNATURE):\n placeholder = file_first_line[len(FILE_PLACEHOLDER_SIGNATURE) :]\n # get stats about file\n real_bytes, max_bytes = get_file_length(update[\"destination\"])\n # saturate file so that it occupies the entire pagefile\n run_cmd([\"sudo\", \"truncate\", f\"--size={max_bytes}\", update[\"destination\"]])\n # store preliminary info about the surgery\n surgery_plan.append(\n {\n \"partition\": partition,\n \"partition_id\": DISK_IMAGE_PARTITION_TABLE[partition],\n \"path\": update[\"relative\"],\n \"placeholder\": placeholder,\n \"offset_bytes\": None,\n \"used_bytes\": real_bytes,\n \"length_bytes\": max_bytes,\n }\n )\n # special handling of the ROOT partition\n if partition == ROOT_PARTITION:\n # store stats before closing the [root] partition\n stats_filepath = os.path.join(\n PARTITION_MOUNTPOINT(partition), DISK_IMAGE_STATS_LOCATION\n )\n with open(out_file_path(\"stats\"), \"wt\") as fout:\n json.dump(stats, fout, indent=4, sort_keys=True)\n run_cmd([\"sudo\", \"cp\", out_file_path(\"stats\"), stats_filepath])\n # setup services\n run_cmd_in_partition(\n ROOT_PARTITION,\n \"ln\"\n \" -s -f\"\n \" /etc/systemd/system/dt_init.service\"\n \" /etc/systemd/system/multi-user.target.wants/dt_init.service\",\n )\n # flush I/O buffer\n dtslogger.info(\"Flushing I/O buffer...\")\n run_cmd([\"sync\"])\n # ---\n dtslogger.info(f\"Partition {partition} updated!\")\n except Exception as e:\n sd_card.umount_partition(partition)\n raise e\n # umount partition\n sd_card.umount_partition(partition)\n # ---\n except Exception as e:\n sd_card.umount()\n raise e\n # finalize surgery plan\n dtslogger.info(\"Locating files for surgery in the disk image...\")\n placeholders = find_placeholders_on_disk(out_file_path(\"img\"))\n for i in range(len(surgery_plan)):\n full_placeholder = f\"{FILE_PLACEHOLDER_SIGNATURE}{surgery_plan[i]['placeholder']}\"\n # check if the placeholder was found\n if full_placeholder not in placeholders:\n raise ValueError(\n f'The string \"{full_placeholder}\" '\n f\"was not found in the disk image {out_file_path('img')}\"\n )\n # update surgery plan\n surgery_plan[i][\"offset_bytes\"] = placeholders[full_placeholder]\n dtslogger.info(\"All files located successfully!\")\n # ---\n cache_step(\"setup\")\n dtslogger.info(\"Step END: setup\\n\")\n # Step: setup\n # <------\n #\n # ------>\n # Step: finalize\n if \"finalize\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: finalize\")\n # compute image sha256\n dtslogger.info(f\"Computing SHA256 checksum of {out_file_path('img')}...\")\n disk_image_sha256 = sd_card.disk_image_sha()\n dtslogger.info(f\"SHA256: {disk_image_sha256}\")\n # store surgery plan and other info\n dtslogger.info(f\"Storing metadata in {out_file_path('json')}...\")\n metadata = {\n \"version\": DISK_IMAGE_VERSION,\n \"disk_image\": os.path.basename(out_file_path(\"img\")),\n \"sha256\": disk_image_sha256,\n \"surgery_plan\": surgery_plan,\n }\n with open(out_file_path(\"json\"), \"wt\") as fout:\n json.dump(metadata, fout, indent=4, sort_keys=True)\n dtslogger.info(\"Done!\")\n # ---\n cache_step(\"finalize\")\n dtslogger.info(\"Step END: finalize\\n\")\n # Step: finalize\n # <------\n #\n # ------>\n # Step: unmount\n if \"unmount\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: unmount\")\n sd_card.umount()\n cache_step(\"unmount\")\n dtslogger.info(\"Step END: unmount\\n\")\n # Step: unmount\n # <------\n #\n # ------>\n # Step: compress\n if \"compress\" in parsed.steps:\n dtslogger.info(\"Step BEGIN: compress\")\n dtslogger.info(\"Compressing disk image...\")\n run_cmd([\"zip\", \"-j\", out_file_path(\"zip\"), out_file_path(\"img\"), out_file_path(\"json\")])\n dtslogger.info(\"Done!\")\n cache_step(\"compress\")\n dtslogger.info(\"Step END: compress\\n\")\n # Step: compress\n # <------\n #\n # ------>\n # Step: push\n if parsed.push:\n if \"compress\" not in parsed.steps:\n dtslogger.warning(\"The step 'compress' was not performed. No artifacts to push.\")\n return\n dtslogger.info(\"Step BEGIN: push\")\n dtslogger.info(\"Pushing disk image...\")\n shell.include.data.push.command(\n shell,\n [],\n parsed=SimpleNamespace(\n file=[out_file_path(\"zip\")],\n object=[os.path.join(DATA_STORAGE_DISK_IMAGE_DIR, out_file_name(\"zip\"))],\n space=\"public\",\n ),\n )\n dtslogger.info(\"Done!\")\n dtslogger.info(\"Step END: push\\n\")\n # Step: push\n # <------\n dtslogger.info(f\"Completed in {human_time(time.time() - stime)}\")\n\n @staticmethod\n def complete(shell, word, line):\n return []\n\n\ndef _get_validator_fcn(partition, path):\n return get_validator_fcn(TEMPLATE_FILE_VALIDATOR, partition, path)\n\n\ndef _transfer_file(partition, location):\n return transfer_file(DISK_TEMPLATE_DIR, partition, location)\n","sub_path":"disk_image/create/raspberry_pi_arm64v8/private_command.py","file_name":"private_command.py","file_ext":"py","file_size_in_byte":38525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"650461339","text":"import numpy as np\nimport scipy.special\nimport scipy.stats as sc\nimport scipy\n\nimport numdifftools as ndt # to comput the Hessian matrix\n\n# Jake VanderPlas package to fit a bivariate normal\nfrom fit_bivariate_gaussian_astroML import *\n\n#=============================================================================== \n# Generic thermodynamic functions\n#=============================================================================== \n\ndef pact_log(IPTG, ea, ei, epsilon):\n '''\n Returns the probability of a repressor being active as described by the MWC\n model.\n Parameter\n ---------\n IPTG : array-like.\n concentrations of inducer on which to evaluate the function\n ea, ei : float.\n minus log of the dissociation constants of the active and the inactive \n states respectively\n epsilon : float.\n energy difference between the active and the inactive state\n Returns\n -------\n pact : float.\n probability of a repressor of being in the active state. Active state is\n defined as the state that can bind to the DNA.\n '''\n pact = (1 + IPTG * np.exp(ea))**2 / \\\n ((1 + IPTG * np.exp(ea))**2 + np.exp(-epsilon) * (1 + IPTG * np.exp(ei))**2)\n return pact\n\n#=============================================================================== \n\ndef fold_change_log(IPTG, ea, ei, epsilon, R, epsilon_r):\n '''\n Returns the gene expression fold change according to the thermodynamic model\n with the extension that takes into account the effect of the inducer.\n Parameter\n ---------\n IPTG : array-like.\n concentrations of inducer on which to evaluate the function\n ea, ei : float.\n minus log of the dissociation constants of the active and the inactive \n states respectively\n epsilon : float.\n energy difference between the active and the inactive state\n R : array-like.\n repressor copy number for each of the strains. The length of this array\n should be equal to the IPTG array. If only one value of the repressor is\n given it is asssume that all the data points should be evaluated with\n the same repressor copy number\n epsilon_r : array-like\n repressor binding energy. The length of this array\n should be equal to the IPTG array. If only one value of the binding\n energy is given it is asssume that all the data points \n should be evaluated with the same repressor copy number\n \n Returns\n -------\n fold-change : float.\n gene expression fold change as dictated by the thermodynamic model.\n '''\n return 1 / (1 + 2 * R / 5E6 * pact_log(IPTG, ea, ei, epsilon) * \\\n (1 + np.exp(-epsilon)) * np.exp(-epsilon_r))\n\n#=============================================================================== \n# Non-linear regression\n#=============================================================================== \n\ndef log_post(param, indep_var, dep_var, epsilon=4.5):\n '''\n Computes the log posterior for a single set of parameters.\n Parameters\n ----------\n param : array-like.\n param[0] = epsilon_a\n ]aram[1] = epsilon_i\n indep_var : n x 3 array.\n series of independent variables to compute the theoretical fold-change.\n 1st column : IPTG concentration\n 2nd column : repressor copy number\n 3rd column : repressor binding energy\n dep_var : array-like\n dependent variable, i.e. experimental fold-change. Then length of this\n array should be the same as the number of rows in indep_var.\n \n Returns\n -------\n log_post : float.\n the log posterior probability\n '''\n # unpack parameters\n ea, ei = param\n \n # unpack independent variables\n IPTG, R, epsilon_r = indep_var[:, 0], indep_var[:, 1], indep_var[:, 2]\n \n # compute the theoretical fold-change\n fc_theory = fold_change_log(IPTG, ea, ei, epsilon, R, epsilon_r)\n \n # return the log posterior\n return -len(dep_var) / 2 * np.log(np.sum((dep_var - fc_theory)**2))\n\n#=============================================================================== \n\ndef resid(param, indep_var, dep_var, epsilon=4.5):\n '''\n Residuals for the theoretical fold change.\n \n Parameters\n ----------\n param : array-like.\n param[0] = epsilon_a\n param[1] = epsilon_i\n indep_var : n x 3 array.\n series of independent variables to compute the theoretical fold-change.\n 1st column : IPTG concentration\n 2nd column : repressor copy number\n 3rd column : repressor binding energy\n dep_var : array-like\n dependent variable, i.e. experimental fold-change. Then length of this\n array should be the same as the number of rows in indep_var.\n \n Returns\n -------\n fold-change_exp - fold-change_theory\n '''\n # unpack parameters\n ea, ei = param\n \n # unpack independent variables\n IPTG, R, epsilon_r = indep_var[:, 0], indep_var[:, 1], indep_var[:, 2]\n \n # compute the theoretical fold-change\n fc_theory = fold_change_log(IPTG, ea, ei, epsilon, R, epsilon_r)\n \n # return the log posterior\n return dep_var - fc_theory\n\n#=============================================================================== \n\ndef non_lin_reg_mwc(df, p0,\n indep_var=['IPTG_uM', 'repressors', 'binding_energy'],\n dep_var='fold_change_A', epsilon=4.5, diss_const=False):\n '''\n Performs a non-linear regression on the lacI IPTG titration data assuming\n Gaussian errors with constant variance. Returns the parameters \n e_A == -ln(K_A)\n e_I == -ln(K_I)\n and it's corresponding error bars by approximating the posterior distribution\n as Gaussian.\n Parameters\n ----------\n df : DataFrame.\n DataFrame containing all the titration information. It should at minimum\n contain the IPTG concentration used, the repressor copy number for each\n strain and the binding energy of such strain as the independent variables\n and obviously the gene expression fold-change as the dependent variable.\n p0 : array-like (length = 2).\n Initial guess for the parameter values. The first entry is the guess for\n e_A == -ln(K_A) and the second is the initial guess for e_I == -ln(K_I).\n indep_var : array-like (length = 3).\n Array of length 3 with the name of the DataFrame columns that contain\n the following parameters:\n 1) IPTG concentration\n 2) repressor copy number\n 3) repressor binding energy to the operator\n dep_var : str.\n Name of the DataFrame column containing the gene expression fold-change.\n epsilon : float.\n Value of the allosteric parameter, i.e. the energy difference between\n the active and the inactive state.\n diss_const : bool.\n Indicates if the dissociation constants should be returned instead of\n the e_A and e_I parameteres.\n Returns\n -------\n if diss_const == True:\n e_A : MAP for the e_A parameter.\n de_A : error bar on the e_A parameter\n e_I : MAP for the e_I parameter.\n de_I : error bar on the e_I parameter\n else:\n K_A : MAP for the K_A parameter.\n dK_A : error bar on the K_A parameter\n K_I : MAP for the K_I parameter.\n dK_I : error bar on the K_I parameter\n '''\n df_indep = df[indep_var]\n df_dep = df[dep_var]\n \n # Extra arguments given as tuple \n args = (df_indep.values, df_dep.values, epsilon)\n\n # Compute the MAP \n popt, _ = scipy.optimize.leastsq(resid, p0, args=args)\n\n # Extract the values\n ea, ei = popt\n \n # Instantiate a numdifftools Hessian object for the log posterior\n hes_fun = ndt.Hessian(log_post)\n\n # Compute the Hessian at the map\n hes = hes_fun(popt, df_indep.values, df_dep.values)\n \n # Compute the covariance matrix\n cov = -np.linalg.inv(hes) \n\n if diss_const:\n # Get the values for the dissociation constants and their \n # respective error bars\n Ka = np.exp(-ea)\n Ki = np.exp(-ei)\n deltaKa = np.sqrt(cov[0,0]) * Ka\n deltaKi = np.sqrt(cov[1,1]) * Ki \n return Ka, deltaKa, Ki, deltaKi\n else:\n return ea, cov[0,0], ei, cov[1,1]\n\n#=============================================================================== \n# datashader scatter plots\n#=============================================================================== \n# Datashader to plot lots of datapoints\n\n'''Deleted this section to run processing.py'''\n\n#=============================================================================== \n\ndef ds_plot(df, x_col, y_col, log=False):\n if log:\n data = np.log10(df[[x_col, y_col]])\n else:\n data = df[[x_col, y_col]]\n p = base_plot(data, x_col, y_col)\n pipeline = ds.Pipeline(data, ds.Point(x_col, y_col))\n return p, pipeline\n\n#=============================================================================== \n# Automatic gating of the flow cytometry data\n#=============================================================================== \n\ndef fit_2D_gaussian(df, x_val='FSC-A', y_val='SSC-A', log=False):\n '''\n This function hacks astroML fit_bivariate_normal to return the mean and\n covariance matrix when fitting a 2D gaussian fuction to the data contained\n in the x_vall and y_val columns of the DataFrame df.\n Parameters\n ----------\n df : DataFrame.\n dataframe containing the data from which to fit the distribution\n x_val, y_val : str.\n name of the dataframe columns to be used in the function\n log : bool.\n indicate if the log of the data should be use for the fit or not\n \n Returns\n -------\n mu : tuple.\n (x, y) location of the best-fit bivariate normal\n cov : 2 x 2 array\n covariance matrix.\n cov[0, 0] = variance of the x_val column\n cov[1, 1] = variance of the y_val column\n cov[0, 1] = cov[1, 0] = covariance of the data\n '''\n if log:\n x = np.log10(df[x_val])\n y = np.log10(df[y_val])\n else:\n x = df[x_val]\n y = df[y_val]\n \n # Fit the 2D Gaussian distribution using atroML function\n mu, sigma_1, sigma_2, alpha = fit_bivariate_normal(x, y, robust=True)\n\n # compute covariance matrix from the standar deviations and the angle\n # that the fit_bivariate_normal function returns\n sigma_xx = ((sigma_1 * np.cos(alpha)) ** 2\n + (sigma_2 * np.sin(alpha)) ** 2)\n sigma_yy = ((sigma_1 * np.sin(alpha)) ** 2\n + (sigma_2 * np.cos(alpha)) ** 2)\n sigma_xy = (sigma_1 ** 2 - sigma_2 ** 2) * np.sin(alpha) * np.cos(alpha)\n \n # put elements of the covariance matrix into an actual matrix\n cov = np.array([[sigma_xx, sigma_xy], [sigma_xy, sigma_yy]])\n \n return mu, cov\n\n#=============================================================================== \n\ndef gauss_interval(df, mu, cov, x_val='FSC-A', y_val='SSC-A', log=False):\n '''\n Computes the of the statistic\n for each of the elements in df columns x_val and y_val.\n \n Parameters\n ----------\n df : DataFrame.\n dataframe containing the data from which to fit the distribution\n mu : array-like.\n (x, y) location of bivariate normal\n cov : 2 x 2 array\n covariance matrix\n x_val, y_val : str.\n name of the dataframe columns to be used in the function\n log : bool.\n indicate if the log of the data should be use for the fit or not \n \n Returns\n -------\n statistic_gauss : array-like.\n array containing the result of the linear algebra operation:\n \n '''\n # Determine that the covariance matrix is not singular\n det = np.linalg.det(cov)\n if det == 0:\n raise NameError(\"The covariance matrix can't be singular\")\n \n # Compute the vector x defined as [[x - mu_x], [y - mu_y]]\n if log: \n x_vect = np.log10(np.array(df[[x_val, y_val]]))\n else:\n x_vect = np.array(df[[x_val, y_val]])\n x_vect[:, 0] = x_vect[:, 0] - mu[0]\n x_vect[:, 1] = x_vect[:, 1] - mu[1]\n \n # compute the inverse of the covariance matrix\n inv_sigma = np.linalg.inv(cov)\n \n # compute the operation\n interval_array = np.zeros(len(df))\n for i, x in enumerate(x_vect):\n interval_array[i] = np.dot(np.dot(x, inv_sigma), x.T)\n \n return interval_array\n\n#=============================================================================== \n\ndef auto_gauss_gate(df, alpha, x_val='FSC-A', y_val='SSC-A', log=False,\n verbose=False):\n '''\n Function that applies an \"unsupervised bivariate Gaussian gate\" to the data\n over the channels x_val and y_val.\n \n Parameters\n ----------\n df : DataFrame.\n dataframe containing the data from which to fit the distribution\n alpha : float. [0, 1]\n fraction of data aimed to keep. Used to compute the chi^2 quantile function\n x_val, y_val : str.\n name of the dataframe columns to be used in the function\n log : bool.\n indicate if the log of the data should be use for the fit or not \n verbose : bool.\n indicate if the percentage of data kept should be print\n Returns\n -------\n df_thresh : DataFrame\n Pandas data frame to which the automatic gate was applied.\n '''\n data = df[[x_val, y_val]]\n # Fit the bivariate Gaussian distribution\n mu, cov = fit_2D_gaussian(data, log=log)\n\n # Compute the statistic for each of the pair of log scattering data\n interval_array = gauss_interval(data, mu, cov, log=log)\n \n # Find which data points fall inside the interval\n idx = interval_array <= scipy.stats.chi2.ppf(alpha, 2)\n\n # print the percentage of data kept\n if verbose:\n print('''\n with parameter alpha={0:0.2f}, percentage of data kept = {1:0.2f}\n '''.format(alpha, np.sum(idx) / len(df)))\n\n return df[idx]\n","sub_path":"code/analysis/mwc_induction_utils_processing.py","file_name":"mwc_induction_utils_processing.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347597983","text":"import pymongo\nfrom pymongo import MongoClient\nimport DemoBot.config as config\nimport re\n\ndef init_nosql():\n print('Check MongoDB collection...', end = '')\n client = MongoClient(config.mongo_connection)\n db = client['bot']\n articlies = db.articles\n \n if articlies.count() == 0:\n article = { \"Object\" : \"Шуховская башня\", \"Desc\": \"\"\" \n Шу́ховская ба́шня на Оке́ — единственная в мире гиперболоидная многосекционная опора линии\n электропередачи, выполненная в виде несущей сетчатой оболочки. Высота 128 м. \n Расположена примерно в 12 км от города Дзержинск на левом берегу Оки, за посёлком Дачный\n \"\"\",\n \"tags\" : [\"башня\", \"ЛЭП\"] }\n articlies.insert_one(article)\n article = { \"Object\" : \"Спасская башня\", \"Desc\": \"\"\"\n Спа́сская ба́шня (Фро́ловская, Фло́ровская, Фролола́врская, Иерусали́мские воро́та) — \n проездная башня Московского Кремля, выходящая на Красную площадь. \n Построена в 1491 году архитектором Пьетро Солари\n \"\"\",\n \"tags\" : [\"башня\"] \n }\n articlies.insert_one(article)\n article = { \"Object\" : \"Линия электропередачи\", \"Desc\" : \"\"\"\n Ли́ния электропереда́чи (ЛЭП) — один из компонентов электрической сети, система энергетического\n оборудования, предназначенная для передачи электроэнергии посредством электрического тока.\n Также электрическая линия в составе такой системы, выходящая за пределы электростанции или \n подстанции\n \"\"\",\n \"tags\" : [\"ЛЭП\"]}\n articlies.insert_one(article)\n print('collection created!')\n else:\n print('collection exists!')\n\ndef search(message):\n result = ''\n keyword = re.split(r'[ ]',message)\n \n client = MongoClient(config.mongo_connection)\n db = client['bot']\n articlies = db.articles\n rows = articlies.find( {\"tags\": {\"$in\" : keyword[1:]}})\n for c in rows:\n result += \"{}\\nОписание:\\n {}\\n\".format(c['Object'],c['Desc'])\n return result","sub_path":"Code/Module 9/Exercises/business_service/nosql_db.py","file_name":"nosql_db.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"20515827","text":"#!/usr/bin/env python\n\nimport sys\n\nlines = list(map(lambda w:w.split(','), open(sys.argv[1], \"r\").read().split('\\n')))\n\nwire1 = lines[0]\nwire2 = lines[1]\n\ndef find_coords(wire):\n x_curr, y_curr, x_dest, y_dest = 0, 0, 0, 0\n direction = (0,0)\n points = {}\n steps = 0\n for move in wire:\n units = int(move[1:])\n if move[0] == \"R\":\n x_dest += units\n direction = (1,0)\n elif move[0] == \"L\":\n x_dest -= units\n direction = (-1,0)\n elif move[0] == \"U\":\n y_dest += units\n direction = (0,1)\n elif move[0] == \"D\":\n y_dest -= units\n direction = (0,-1)\n\n while x_curr != x_dest or y_curr != y_dest:\n if (x_curr, y_curr) not in points:\n points[(x_curr, y_curr)] = steps\n x_curr += direction[0]\n y_curr += direction[1]\n steps += 1\n\n return points\n\nwire1_coords = find_coords(wire1)\nwire2_coords = find_coords(wire2)\n\nintersection_points = (set(wire1_coords.keys()) & set(wire2_coords.keys())).difference({(0,0)})\n\nintersections = list(map(lambda x: wire1_coords[x] + wire2_coords[x], intersection_points))\n\nprint(min(intersections))","sub_path":"day-03/python/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"149280140","text":"class Point(object):\n def __init__(self, x, y):\n self.x, self.y = x, y\n\n\nclass Vector(object):\n def __init__(self, start_point, end_point):\n self.start, self.end = start_point, end_point\n self.x = end_point.x - start_point.x\n self.y = end_point.y - start_point.y\n\ndef negative(vector):\n \"\"\"negative\"\"\"\n return Vector(vector.end, vector.start)\n\ndef vector_product(vectorA, vectorB):\n \"\"\"calculate x_1 * y_2 - x_2 * y_1\"\"\"\n return vectorA.x * vectorB.y - vectorB.x * vectorA.y\n\ndef is_intersected(A, B, C, D):\n \"\"\"A, B, C, D is point class type\"\"\"\n AC = Vector(A, C)\n AD = Vector(A, D)\n BC = Vector(B, C)\n BD = Vector(B, D)\n CA = negative(AC)\n CB = negative(BC)\n DA = negative(AD)\n DB = negative(BD)\n\n return (vector_product(AC, AD) * vector_product(BC, BD) <= ZERO) \\\n and (vector_product(CA, CB) * vector_product(DA, DB) <= ZERO)\n\ndef ArraySwapLocation(bboxes):\n \"\"\"\n if two lines is intersected, swap two points localization\n :param bboxes:\n :return:\n \"\"\"\n bboxes_modify = copy.deepcopy(bboxes[0])\n for i in range(1, 1 + num_classes):\n box = bboxes[0][i]\n flag = []\n if box.shape[0] == 0:\n continue\n for idx, box_s in enumerate(box):\n A = Point(box_s[2], box_s[3])\n B = Point(box_s[8], box_s[9])\n C = Point(box_s[4], box_s[5])\n D = Point(box_s[6], box_s[7])\n if is_intersected(A, B, C, D):\n flag.append(idx)\n if len(flag) == 0:\n continue\n box_tmp = box[np.array(flag)]\n # print('modify {}'.format(box_tmp[:,8]))\n for j, idx in enumerate(flag):\n bboxes_modify[i][idx][6] = box_tmp[j][8]\n bboxes_modify[i][idx][8] = box_tmp[j][6]\n bboxes_modify[i][idx][7] = box_tmp[j][9]\n bboxes_modify[i][idx][9] = box_tmp[j][7]\n return bboxes_modify\n","sub_path":"dota_kit/JudgeIntersected.py","file_name":"JudgeIntersected.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425601926","text":"import datetime as dt\nimport requests\nfrom api_key import *\n\n\n\ndef wu_history_url(city, state, day):\n # must use correct capitalization for city/state (City, ST)\n # YYYYMMDD\n url = 'http://api.wunderground.com/api/' + wu_api_key + '/history_' + day + '/q/' + state + '/' + city + '.json'\n\n return url\n\n\ndef wu_forecast_url(city, state):\n url = 'http://api.wunderground.com/api/' + wu_api_key + '/forecast/q/' + state + '/' + city + '.json'\n\n return url\n\n\ndef date_gen(year, start_month, start_day, end_month, end_day):\n d1 = dt.date(year, start_month, start_day)\n d2 = dt.date(year, end_month, end_day)\n delta = d2 - d1\n # generate list of all dates in sepcified date range\n unformatted_dates = [str(d1 + dt.timedelta(days=i)) for i in range(delta.days + 1)]\n # remove hyphens so dates can be inserted into url\n formatted_dates = [x.replace('-', '') for x in unformatted_dates]\n\n return formatted_dates\n\n\ndef date_format(x):\n year = x[0:4]\n if x[4] == '0':\n month = x[5]\n else:\n month = x[4:6]\n\n if x[6] == '0':\n day = x[7]\n else:\n day = x[6:8]\n new_date = '{}/{}/{}'.format(month, day, year)\n return new_date\n\ndef wu_actual_observations(city, state, focus_day):\n weather_data = (requests.get(wu_history_url(city, state, focus_day))).json()\n # access the observed max and min temps using dict keys and list indices\n max_temp = weather_data['history']['dailysummary'][0]['maxtempi']\n min_temp = weather_data['history']['dailysummary'][0]['mintempi']\n precip = weather_data['history']['dailysummary'][0]['precipi']\n # need to replace T (trace) in precip with 0 for stat comparison\n\n\n #formate the date to be able to easily compare the resultant with the three_day_forecast csv\n proper_date = date_format(focus_day)\n\n return proper_date, max_temp, min_temp, precip\n\n\n\ndef wu_three_day_forecast(city, state):\n today = dt.date.today()\n this_day = str(today + dt.timedelta(days=2))\n location_data = (requests.get(wu_forecast_url(city, state))).json()\n high = location_data['forecast']['simpleforecast']['forecastday'][2]['high']['fahrenheit']\n low = location_data['forecast']['simpleforecast']['forecastday'][2]['low']['fahrenheit']\n precip = location_data['forecast']['simpleforecast']['forecastday'][2]['qpf_allday']['in']\n\n return this_day, high, low, precip\n\n\n\n\n\n\n\n\n","sub_path":"wu_utilities.py","file_name":"wu_utilities.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"160320936","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport logging\nimport os\nimport configparser\nimport pandas as pd\nfrom datetime import datetime\nfrom EmailSender import EmailSender\n\nstart_time = datetime.now()\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(level=logging.INFO)\nlog_file = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'log.log')\nf_handler = logging.FileHandler(log_file)\nf_handler.setLevel(logging.INFO)\nformatter = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S')\nf_handler.setFormatter(formatter)\nlogger.addHandler(f_handler)\ns_handler = logging.StreamHandler()\ns_handler.setLevel(logging.DEBUG)\nlogger.addHandler(s_handler)\n\nconf = configparser.ConfigParser()\nconf_file = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'config_pg_hsm_w.ini')\nconf.read(conf_file, encoding='utf-8')\n\nemail = {\n 'user': conf.get('email', 'user'),\n 'password': conf.get('email', 'password'),\n 'host': conf.get('email', 'host'),\n 'port': conf.getint('email', 'port'),\n}\n\nto = conf.get('email', 'to').split()\nmonth = conf.get('pg_hsm', 'month')\n\n\ndef main():\n category = ['hair', 'pcc', 'laundry', 'oral', 'fem', 'baby', 'skin', 'br']\n report_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), ('pg_hsm_report_' + month + '.xlsx'))\n writer = pd.ExcelWriter(report_path)\n report_file = []\n report_data = []\n report_data_number = []\n for i in range(8):\n report_file.append(os.path.join(os.path.dirname(os.path.realpath('__file__')),\n ('pg_hsm_report_' + category[i] + '_' + month + '.xlsx')))\n report_data.append(pd.read_excel(report_file[i], category[i]))\n for k in report_data[i].columns:\n if '_pic' in k:\n report_data[i][k] = report_data[i][k].map(lambda x: '' if pd.isna(x) else '=' + x)\n report_data[i].to_excel(writer, category[i], index=False)\n report_data_number.append(pd.read_excel(report_file[i], category[i] + '_number'))\n report_data_number[i].to_excel(writer, category[i] + '_number', index=False)\n os.remove(report_file[i])\n writer.close()\n subject = 'P&G_HSM_Report_' + month + '_' + datetime.now().strftime('%Y-%m-%d')\n contents = ['附件中为' + month + '全部数据及需检查的数据', ]\n attachments = [report_path]\n with EmailSender(**email) as email_sender:\n email_sender.send_email(to=to, subject=subject, contents=contents, attachments=attachments)\n\n\nif __name__ == '__main__':\n main()\n end_time = datetime.now()\n logger.info('time_consumed: %s' % (end_time-start_time))\n","sub_path":"BI_ETL/pg_hsm_w_mail.py","file_name":"pg_hsm_w_mail.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264392318","text":"import os, os.path, sys , datetime\n\nfor x in sys.argv[1:]:\n folderpath = str(x) \n for root, _, files in os.walk(folderpath, topdown=False):\n for f in files:\n fullpath = os.path.join(root, f) ##Combines the directory & filename, assigns to variable\n file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(fullpath))\n if datetime.datetime.now() - file_modified > datetime.timedelta(hours=1):\n os.remove(fullpath)\n","sub_path":"franklyapi/delete_old_files.py","file_name":"delete_old_files.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"127748908","text":"from turtle import *\r\n#impostazioni\r\npencolor(\"white\")\r\nshape(\"turtle\")\r\nspeed(10)\r\npensize(4)\r\nScreen ().bgcolor(\"turquoise\")\r\n\r\n#usiamo le funzioni\r\ndef forma():\r\n right(25)\r\n forward(50)\r\n backward(50)\r\n left(50)\r\n forward(50)\r\n backward(50)\r\n right(25)\r\n\r\ndef fiocco():\r\n for i in range(0,4):\r\n forward(30)\r\n forma()\r\n backward(120)\r\n \r\ni=0\r\nwhile i<8:\r\n fiocco()\r\n right(45)\r\n i=i+1\r\n","sub_path":"fiocco.py","file_name":"fiocco.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"628289757","text":"from sys import stdin\nfrom collections import deque\n\n\ndef bash(target, buttons):\n # print(\"target: {} | buttons: {}\".format(target, buttons))\n min_possible = (0, float('inf'))\n q = deque()\n seen = set()\n q.append((0,0))\n while q:\n dist, current = q.popleft()\n dist += 1\n for i in buttons:\n pressed = current\n pressed += i\n if pressed >= target and min_possible[1] >= pressed:\n min_possible = ((dist, pressed-target))\n if pressed in seen: continue\n else: seen.add(pressed)\n if pressed <= 0: continue\n elif pressed > 3600: \n pressed = 3600\n q.append((dist, pressed))\n elif pressed == target:\n return (dist, pressed - pressed)\n else: q.append((dist, pressed))\n return min_possible\n\n\nn = int(input())\nfor i in range(n):\n amt, target = stdin.readline().split()\n buttons = {int(i) for i in stdin.readline().split()}\n dist, remainder = (bash(int(target), buttons))\n print(dist, remainder)\n","sub_path":"wip/button_bashing.py","file_name":"button_bashing.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"327953909","text":"\r\nclass RoadModel(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.image_model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', \r\n pretrained=False)\r\n self.fc1 = nn.Linear(6000, 2500)\r\n self.ups1 = nn.Upsample(size=100, mode='bilinear')\r\n self.deconv1 = nn.ConvTranspose2d(in_channels=1, out_channels=32, \r\n kernel_size=3, stride=1, padding=1)\r\n self.ups2 = nn.Upsample(size=200, mode='bilinear')\r\n self.deconv2 = nn.ConvTranspose2d(in_channels=32, out_channels=16, \r\n kernel_size=3, stride=1, padding=1)\r\n self.ups3 = nn.Upsample(size=400, mode='bilinear')\r\n self.deconv3 = nn.ConvTranspose2d(in_channels=16, out_channels=4, \r\n kernel_size=3, stride=1, padding=1)\r\n self.ups4 = nn.Upsample(size=800, mode='bilinear')\r\n self.deconv4 = nn.ConvTranspose2d(in_channels=4, out_channels=1, \r\n kernel_size=3, stride=1, padding=1)\r\n \r\n \r\n def forward(self, x):\r\n features = []\r\n for im in x:\r\n features.append(self.image_model(im))\r\n x = torch.cat(features, dim=1)\r\n x = self.fc1(x)\r\n # x = F.relu(x)\r\n x = x.reshape([-1, 1, 50, 50])\r\n x = self.ups1(x)\r\n x = self.deconv1(x)\r\n x = F.relu(x)\r\n x = self.ups2(x)\r\n x = self.deconv2(x)\r\n x = F.relu(x)\r\n x = self.ups3(x)\r\n x = self.deconv3(x)\r\n x = F.relu(x)\r\n x = self.ups4(x)\r\n x = self.deconv4(x)\r\n return F.sigmoid(x)\r\n","sub_path":"test_v1/model_file.py","file_name":"model_file.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508377955","text":"#! python3\r\n# -*- encoding: utf-8 -*-\r\n'''\r\nCurrent module: demo.views.simple.views\r\n\r\nRough version history:\r\nv1.0 Original version to use\r\n\r\n********************************************************************\r\n @AUTHOR: Administrator-Bruce Luo(罗科峰)\r\n MAIL: lkf20031988@163.com\r\n RCS: demo.views.simple.views,v 1.0 2019年2月20日\r\n FROM: 2019年2月20日\r\n********************************************************************\r\n\r\n======================================================================\r\n\r\nUI and Web Http automation frame for python.\r\n\r\n'''\r\n\r\nfrom flask import request, jsonify\r\nfrom flask_demo.demo.views.simple import simple\r\n\r\n\r\n_msg = {\"status\":\"ok\", \"result\":\"\", \"msg\":\"\"}\r\n\r\n@simple.route('add', methods=[\"GET\"])\r\ndef add_get():\r\n # GET /add?x=1&y=2\r\n param = dict(request.args.items())\r\n \r\n try:\r\n _msg[\"result\"] = int(param.get('x')) + int(param.get('y')) \r\n except Exception as e:\r\n _msg[\"status\"] = \"error\"\r\n _msg[\"msg\"] = str(e)\r\n return jsonify(_msg)\r\n\r\n@simple.route('add', methods=[\"POST\"])\r\ndef add_post():\r\n # POST /add \r\n j_param = request.json if request.data else request.form.to_dict() \r\n \r\n try:\r\n _msg[\"result\"] = int(j_param.get('x')) + int(j_param.get('y')) \r\n except Exception as e:\r\n _msg[\"status\"] = \"error\"\r\n _msg[\"msg\"] = str(e)\r\n return jsonify(_msg)\r\n","sub_path":"flask_demo/demo/views/simple/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"463198760","text":"# enable debug?\ndebug = True\n# what's my environment?\n# a unique id, e.g. networkname, project related to, you get the idea\nenvironment = 'prod'\n# checks array\n# check ttl should always be way longer than executing the check takes!\nchecks = [\n {'name': 'uptime', 'ttl': 60, 'warn': 120, 'crit': 365},\n {'name': 'load5', 'ttl': 60, 'warn': 2.0, 'crit': 3.0},\n {'name': 'dfavg', 'ttl': 60, 'warn': 80, 'crit': 90},\n {'name': 'mem', 'ttl': 60, 'warn': 80, 'crit': 90},\n]\n# check states path\nstates_path = 'states/'\n","sub_path":"setting.example.py","file_name":"setting.example.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"305671451","text":"# Copyright (c) 2003-2015 by Mike Jarvis\n#\n# TreeCorr is free software: redistribution and use in source and binary forms,\n# with or without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions, and the disclaimer given in the accompanying LICENSE\n# file.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions, and the disclaimer given in the documentation\n# and/or other materials provided with the distribution.\n\nfrom __future__ import print_function\nimport numpy\nimport treecorr\nimport os\nimport fitsio\n\nfrom test_helper import get_script_name\n\ndef test_ggg():\n # Use gamma_t(r) = gamma0 r^2/r0^2 exp(-r^2/2r0^2)\n # i.e. gamma(r) = -gamma0 exp(-r^2/2r0^2) (x+iy)^2 / r0^2\n #\n # Rather than go through the bispectrum, I found it easier to just directly do the\n # integral:\n #\n # Gamma0 = int(int( g(x+x1,y+y1) g(x+x2,y+y2) g(x-x1-x2,y-y1-y2) (x1-Iy1)^2/(x1^2+y1^2)\n # (x2-Iy2)^2/(x2^2+y2^2) (x1+x2-I(y1+y2))^2/((x1+x2)^2+(y1+y2)^2)))\n #\n # where the positions are measured relative to the centroid (x,y).\n # If we call the positions relative to the centroid:\n # q1 = x1 + I y1\n # q2 = x2 + I y2\n # q3 = -(x1+x2) - I (y1+y2)\n # then the result comes out as\n #\n # Gamma0 = -2/3 gamma0^3/L^2r0^4 Pi |q1|^2 |q2|^2 |q3|^2 exp(-(|q1|^2+|q2|^2+|q3|^2)/2r0^2)\n #\n # The other three are a bit more complicated.\n #\n # Gamma1 = int(int( g(x+x1,y+y1)* g(x+x2,y+y2) g(x-x1-x2,y-y1-y2) (x1+Iy1)^2/(x1^2+y1^2)\n # (x2-Iy2)^2/(x2^2+y2^2) (x1+x2-I(y1+y2))^2/((x1+x2)^2+(y1+y2)^2)))\n #\n # = -2/3 gamma0^3/L^2r0^4 Pi exp(-(|q1|^2+|q2|^2+|q3|^2)/2r0^2) *\n # ( |q1|^2 |q2|^2 |q3|^2 - 8/3 r0^2 q1^2 q2* q3*\n # + 8/9 r0^4 (q1^2 q2*^2 q3*^2)/(|q1|^2 |q2|^2 |q3|^2) (2q1^2-q2^2-q3^2) )\n #\n # Gamm2 and Gamma3 are found from cyclic rotations of q1,q2,q3.\n\n gamma0 = 0.05\n r0 = 10.\n if __name__ == '__main__':\n ngal = 200000\n L = 30.*r0 # Not infinity, so this introduces some error. Our integrals were to infinity.\n req_factor = 1\n else:\n # Looser tests from nosetests that don't take so long to run.\n ngal = 10000\n L = 10.*r0\n req_factor = 5\n numpy.random.seed(8675309)\n x = (numpy.random.random_sample(ngal)-0.5) * L\n y = (numpy.random.random_sample(ngal)-0.5) * L\n r2 = (x**2 + y**2)/r0**2\n g1 = -gamma0 * numpy.exp(-r2/2.) * (x**2-y**2)/r0**2\n g2 = -gamma0 * numpy.exp(-r2/2.) * (2.*x*y)/r0**2\n\n min_sep = 11.\n max_sep = 15.\n nbins = 3\n min_u = 0.7\n max_u = 1.0\n nubins = 3\n min_v = -0.1\n max_v = 0.3\n nvbins = 4\n\n cat = treecorr.Catalog(x=x, y=y, g1=g1, g2=g2, x_units='arcmin', y_units='arcmin')\n ggg = treecorr.GGGCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v,\n nubins=nubins, nvbins=nvbins,\n sep_units='arcmin', verbose=1)\n ggg.process(cat)\n\n # log() != , but it should be close:\n #print('meanlogd1 - log(meand1) = ',ggg.meanlogd1 - numpy.log(ggg.meand1))\n #print('meanlogd2 - log(meand2) = ',ggg.meanlogd2 - numpy.log(ggg.meand2))\n #print('meanlogd3 - log(meand3) = ',ggg.meanlogd3 - numpy.log(ggg.meand3))\n #print('meanlogd3 - meanlogd2 - log(meanu) = ',ggg.meanlogd3 - ggg.meanlogd2 - numpy.log(ggg.meanu))\n #print('log(meand1-meand2) - meanlogd3 - log(meanv) = ',numpy.log(ggg.meand1-ggg.meand2) - ggg.meanlogd3 - numpy.log(numpy.abs(ggg.meanv)))\n numpy.testing.assert_almost_equal(ggg.meanlogd1, numpy.log(ggg.meand1), decimal=3)\n numpy.testing.assert_almost_equal(ggg.meanlogd2, numpy.log(ggg.meand2), decimal=3)\n numpy.testing.assert_almost_equal(ggg.meanlogd3, numpy.log(ggg.meand3), decimal=3)\n numpy.testing.assert_almost_equal(ggg.meanlogd3-ggg.meanlogd2, numpy.log(ggg.meanu), decimal=3)\n numpy.testing.assert_almost_equal(numpy.log(ggg.meand1-ggg.meand2)-ggg.meanlogd3,\n numpy.log(numpy.abs(ggg.meanv)), decimal=3)\n\n d1 = ggg.meand1\n d2 = ggg.meand2\n d3 = ggg.meand3\n #print('rnom = ',numpy.exp(ggg.logr))\n #print('unom = ',ggg.u)\n #print('vnom = ',ggg.v)\n #print('d1 = ',d1)\n #print('d2 = ',d2)\n #print('d3 = ',d3)\n\n # For q1,q2,q3, we can choose an orientation where c1 is at the origin, and d2 is horizontal.\n # Then let s be the \"complex vector\" from c1 to c3, which is just real.\n s = d2\n # And let t be from c1 to c2. t = |t| e^Iphi\n # |t| = d3\n # cos(phi) = (d2^2+d3^2-d1^2)/(2d2 d3)\n # |t| cos(phi) = (d2^2+d3^2-d1^2)/2d2\n # |t| sin(phi) = sqrt(|t|^2 - (|t|cos(phi))^2)\n tx = (d2**2 + d3**2 - d1**2)/(2.*d2)\n ty = numpy.sqrt(d3**2 - tx**2)\n # As arranged, if ty > 0, points 1,2,3 are clockwise, which is negative v.\n # So for bins with positive v, we need to flip the direction of ty.\n ty[ggg.meanv > 0] *= -1.\n t = tx + 1j * ty\n\n q1 = (s + t)/3.\n q2 = q1 - t\n q3 = q1 - s\n nq1 = numpy.abs(q1)**2\n nq2 = numpy.abs(q2)**2\n nq3 = numpy.abs(q3)**2\n #print('q1 = ',q1)\n #print('q2 = ',q2)\n #print('q3 = ',q3)\n\n # The L^2 term in the denominator of true_zeta is the area over which the integral is done.\n # Since the centers of the triangles don't go to the edge of the box, we approximate the\n # correct area by subtracting off 2*mean(qi) from L, which should give a slightly better\n # estimate of the correct area to use here. (We used 2d2 for the kkk calculation, but this\n # is probably a slightly better estimate of the distance the triangles can get to the edges.)\n L = L - 2.*(q1 + q2 + q3)/3.\n\n # Gamma0 = -2/3 gamma0^3/L^2r0^4 Pi |q1|^2 |q2|^2 |q3|^2 exp(-(|q1|^2+|q2|^2+|q3|^2)/2r0^2)\n true_gam0 = ((-2.*numpy.pi * gamma0**3)/(3. * L**2 * r0**4) *\n numpy.exp(-(nq1+nq2+nq3)/(2.*r0**2)) * (nq1*nq2*nq3) )\n\n # Gamma1 = -2/3 gamma0^3/L^2r0^4 Pi exp(-(|q1|^2+|q2|^2+|q3|^2)/2r0^2) *\n # ( |q1|^2 |q2|^2 |q3|^2 - 8/3 r0^2 q1^2 q2* q3*\n # + 8/9 r0^4 (q1^2 q2*^2 q3*^2)/(|q1|^2 |q2|^2 |q3|^2) (2q1^2-q2^2-q3^2) )\n true_gam1 = ((-2.*numpy.pi * gamma0**3)/(3. * L**2 * r0**4) *\n numpy.exp(-(nq1+nq2+nq3)/(2.*r0**2)) *\n (nq1*nq2*nq3 - 8./3. * r0**2 * q1**2*nq2*nq3/(q2*q3)\n + (8./9. * r0**4 * (q1**2 * nq2 * nq3)/(nq1 * q2**2 * q3**2) *\n (2.*q1**2 - q2**2 - q3**2)) ))\n\n true_gam2 = ((-2.*numpy.pi * gamma0**3)/(3. * L**2 * r0**4) *\n numpy.exp(-(nq1+nq2+nq3)/(2.*r0**2)) *\n (nq1*nq2*nq3 - 8./3. * r0**2 * nq1*q2**2*nq3/(q1*q3)\n + (8./9. * r0**4 * (nq1 * q2**2 * nq3)/(q1**2 * nq2 * q3**2) *\n (2.*q2**2 - q1**2 - q3**2)) ))\n\n true_gam3 = ((-2.*numpy.pi * gamma0**3)/(3. * L**2 * r0**4) *\n numpy.exp(-(nq1+nq2+nq3)/(2.*r0**2)) *\n (nq1*nq2*nq3 - 8./3. * r0**2 * nq1*nq2*q3**2/(q1*q2)\n + (8./9. * r0**4 * (nq1 * nq2 * q3**2)/(q1**2 * q2**2 * nq3) *\n (2.*q3**2 - q1**2 - q2**2)) ))\n\n #print('ntri = ',ggg.ntri)\n print('gam0 = ',ggg.gam0)\n print('true_gam0 = ',true_gam0)\n #print('ratio = ',ggg.gam0 / true_gam0)\n #print('diff = ',ggg.gam0 - true_gam0)\n print('max rel diff = ',numpy.max(numpy.abs((ggg.gam0 - true_gam0)/true_gam0)))\n # The Gamma0 term is a bit worse than the others. The accurracy improves as I increase the\n # number of objects, so I think it's just because of the smallish number of galaxies being\n # not super accurate.\n assert numpy.max(numpy.abs((ggg.gam0 - true_gam0)/true_gam0))/req_factor < 0.2\n numpy.testing.assert_almost_equal(numpy.log(numpy.abs(ggg.gam0))/2./req_factor,\n numpy.log(numpy.abs(true_gam0))/2./req_factor, decimal=1)\n\n print('gam1 = ',ggg.gam1)\n print('true_gam1 = ',true_gam1)\n #print('ratio = ',ggg.gam1 / true_gam1)\n #print('diff = ',ggg.gam1 - true_gam1)\n print('max rel diff = ',numpy.max(numpy.abs((ggg.gam1 - true_gam1)/true_gam1)))\n assert numpy.max(numpy.abs((ggg.gam1 - true_gam1)/true_gam1))/req_factor < 0.1\n numpy.testing.assert_almost_equal(numpy.log(numpy.abs(ggg.gam1))/req_factor,\n numpy.log(numpy.abs(true_gam1))/req_factor, decimal=1)\n\n #print('gam2 = ',ggg.gam2)\n #print('true_gam2 = ',true_gam2)\n #print('ratio = ',ggg.gam2 / true_gam2)\n #print('diff = ',ggg.gam2 - true_gam2)\n #print('max rel diff = ',numpy.max(numpy.abs((ggg.gam2 - true_gam2)/true_gam2)))\n assert numpy.max(numpy.abs((ggg.gam2 - true_gam2)/true_gam2))/req_factor < 0.1\n numpy.testing.assert_almost_equal(numpy.log(numpy.abs(ggg.gam2))/req_factor,\n numpy.log(numpy.abs(true_gam2))/req_factor, decimal=1)\n\n #print('gam3 = ',ggg.gam3)\n #print('true_gam3 = ',true_gam3)\n #print('ratio = ',ggg.gam3 / true_gam3)\n #print('diff = ',ggg.gam3 - true_gam3)\n #print('max rel diff = ',numpy.max(numpy.abs((ggg.gam3 - true_gam3)/true_gam3)))\n assert numpy.max(numpy.abs((ggg.gam3 - true_gam3)/true_gam3))/req_factor < 0.1\n numpy.testing.assert_almost_equal(numpy.log(numpy.abs(ggg.gam3))/req_factor,\n numpy.log(numpy.abs(true_gam3))/req_factor, decimal=1)\n\n # Check that we get the same result using the corr3 executable:\n if __name__ == '__main__':\n cat.write(os.path.join('data','ggg_data.dat'))\n import subprocess\n corr3_exe = get_script_name('corr3')\n p = subprocess.Popen( [corr3_exe,\"ggg.yaml\"] )\n p.communicate()\n corr3_output = numpy.genfromtxt(os.path.join('output','ggg.out'), names=True)\n #print('gam0r = ',ggg.gam0.real)\n #print('from corr3 output = ',corr3_output['gam0r'])\n #print('ratio = ',corr3_output['gam0r']/ggg.gam0r.flatten())\n #print('diff = ',corr3_output['gam0r']-ggg.gam0r.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam0r']/ggg.gam0r.flatten(), 1., decimal=3)\n #print('gam0i = ',ggg.gam0.imag)\n #print('from corr3 output = ',corr3_output['gam0i'])\n #print('ratio = ',corr3_output['gam0i']/ggg.gam0i.flatten())\n #print('diff = ',corr3_output['gam0i']-ggg.gam0i.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam0i']/ggg.gam0i.flatten(), 1., decimal=3)\n #print('gam1r = ',ggg.gam1.real)\n #print('from corr3 output = ',corr3_output['gam1r'])\n #print('ratio = ',corr3_output['gam1r']/ggg.gam1r.flatten())\n #print('diff = ',corr3_output['gam1r']-ggg.gam1r.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam1r']/ggg.gam1r.flatten(), 1., decimal=3)\n #print('gam1i = ',ggg.gam1.imag)\n #print('from corr3 output = ',corr3_output['gam1i'])\n #print('ratio = ',corr3_output['gam1i']/ggg.gam1i.flatten())\n #print('diff = ',corr3_output['gam1i']-ggg.gam1i.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam1i']/ggg.gam1i.flatten(), 1., decimal=3)\n #print('gam2r = ',ggg.gam2.real)\n #print('from corr3 output = ',corr3_output['gam2r'])\n #print('ratio = ',corr3_output['gam2r']/ggg.gam2r.flatten())\n #print('diff = ',corr3_output['gam2r']-ggg.gam2r.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam2r']/ggg.gam2r.flatten(), 1., decimal=3)\n #print('gam2i = ',ggg.gam2.imag)\n #print('from corr3 output = ',corr3_output['gam2i'])\n #print('ratio = ',corr3_output['gam2i']/ggg.gam2i.flatten())\n #print('diff = ',corr3_output['gam2i']-ggg.gam2i.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam2i']/ggg.gam2i.flatten(), 1., decimal=3)\n #print('gam3r = ',ggg.gam3.real)\n #print('from corr3 output = ',corr3_output['gam3r'])\n #print('ratio = ',corr3_output['gam3r']/ggg.gam3r.flatten())\n #print('diff = ',corr3_output['gam3r']-ggg.gam3r.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam3r']/ggg.gam3r.flatten(), 1., decimal=3)\n #print('gam3i = ',ggg.gam3.imag)\n #print('from corr3 output = ',corr3_output['gam3i'])\n #print('ratio = ',corr3_output['gam3i']/ggg.gam3i.flatten())\n #print('diff = ',corr3_output['gam3i']-ggg.gam3i.flatten())\n numpy.testing.assert_almost_equal(corr3_output['gam3i']/ggg.gam3i.flatten(), 1., decimal=3)\n\n # Check the fits write option\n out_file_name1 = os.path.join('output','ggg_out1.fits')\n ggg.write(out_file_name1)\n data = fitsio.read(out_file_name1)\n numpy.testing.assert_almost_equal(data['R_nom'], numpy.exp(ggg.logr).flatten())\n numpy.testing.assert_almost_equal(data['u_nom'], ggg.u.flatten())\n numpy.testing.assert_almost_equal(data['v_nom'], ggg.v.flatten())\n numpy.testing.assert_almost_equal(data['meand1'], ggg.meand1.flatten())\n numpy.testing.assert_almost_equal(data['meanlogd1'], ggg.meanlogd1.flatten())\n numpy.testing.assert_almost_equal(data['meand2'], ggg.meand2.flatten())\n numpy.testing.assert_almost_equal(data['meanlogd2'], ggg.meanlogd2.flatten())\n numpy.testing.assert_almost_equal(data['meand3'], ggg.meand3.flatten())\n numpy.testing.assert_almost_equal(data['meanlogd3'], ggg.meanlogd3.flatten())\n numpy.testing.assert_almost_equal(data['meanu'], ggg.meanu.flatten())\n numpy.testing.assert_almost_equal(data['meanv'], ggg.meanv.flatten())\n numpy.testing.assert_almost_equal(data['gam0r'], ggg.gam0.real.flatten())\n numpy.testing.assert_almost_equal(data['gam1r'], ggg.gam1.real.flatten())\n numpy.testing.assert_almost_equal(data['gam2r'], ggg.gam2.real.flatten())\n numpy.testing.assert_almost_equal(data['gam3r'], ggg.gam3.real.flatten())\n numpy.testing.assert_almost_equal(data['gam0i'], ggg.gam0.imag.flatten())\n numpy.testing.assert_almost_equal(data['gam1i'], ggg.gam1.imag.flatten())\n numpy.testing.assert_almost_equal(data['gam2i'], ggg.gam2.imag.flatten())\n numpy.testing.assert_almost_equal(data['gam3i'], ggg.gam3.imag.flatten())\n numpy.testing.assert_almost_equal(data['sigma_gam'], numpy.sqrt(ggg.vargam.flatten()))\n numpy.testing.assert_almost_equal(data['weight'], ggg.weight.flatten())\n numpy.testing.assert_almost_equal(data['ntri'], ggg.ntri.flatten())\n\n # Check the read function\n # Note: These don't need the flatten. The read function should reshape them to the right shape.\n ggg2 = treecorr.GGGCorrelation(min_sep=min_sep, max_sep=max_sep, nbins=nbins,\n min_u=min_u, max_u=max_u, min_v=min_v, max_v=max_v,\n nubins=nubins, nvbins=nvbins,\n sep_units='arcmin', verbose=1)\n ggg2.read(out_file_name1)\n numpy.testing.assert_almost_equal(ggg2.logr, ggg.logr)\n numpy.testing.assert_almost_equal(ggg2.u, ggg.u)\n numpy.testing.assert_almost_equal(ggg2.v, ggg.v)\n numpy.testing.assert_almost_equal(ggg2.meand1, ggg.meand1)\n numpy.testing.assert_almost_equal(ggg2.meanlogd1, ggg.meanlogd1)\n numpy.testing.assert_almost_equal(ggg2.meand2, ggg.meand2)\n numpy.testing.assert_almost_equal(ggg2.meanlogd2, ggg.meanlogd2)\n numpy.testing.assert_almost_equal(ggg2.meand3, ggg.meand3)\n numpy.testing.assert_almost_equal(ggg2.meanlogd3, ggg.meanlogd3)\n numpy.testing.assert_almost_equal(ggg2.meanu, ggg.meanu)\n numpy.testing.assert_almost_equal(ggg2.meanv, ggg.meanv)\n numpy.testing.assert_almost_equal(ggg2.gam0, ggg.gam0)\n numpy.testing.assert_almost_equal(ggg2.gam1, ggg.gam1)\n numpy.testing.assert_almost_equal(ggg2.gam2, ggg.gam2)\n numpy.testing.assert_almost_equal(ggg2.gam3, ggg.gam3)\n numpy.testing.assert_almost_equal(ggg2.vargam, ggg.vargam)\n numpy.testing.assert_almost_equal(ggg2.weight, ggg.weight)\n numpy.testing.assert_almost_equal(ggg2.ntri, ggg.ntri)\n\nif __name__ == '__main__':\n test_ggg()\n","sub_path":"tests/test_ggg.py","file_name":"test_ggg.py","file_ext":"py","file_size_in_byte":16251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"312083260","text":"import socket\r\n\r\n# create socket TCP/IP\r\ns = socket.socket()\r\n\r\n# get ip address\r\nip_address = socket.gethostbyname(socket.gethostname())\r\n\r\n# bind ip address port 12345\r\ns.bind((ip_address, 12345))\r\n\r\n# listen connections\r\ns.listen(3)\r\n\r\n# print ip address\r\nprint('Server ip address: ' + ip_address)\r\n\r\nwhile True:\r\n # waiting connection establishment\r\n print('waiting for a connection')\r\n connection, client_address = s.accept()\r\n\r\n try:\r\n # show connected client\r\n print('connected from: ', client_address)\r\n\r\n # sending acknowledgement to client that you are connected\r\n connection.send(str('Now you are connected').encode('utf-8'))\r\n\r\n # receiving msg\r\n while True:\r\n data = connection.recv(1024).decode('utf-8')\r\n if data:\r\n # message from client\r\n print(list(client_address)[0], end='')\r\n print(': %s' % data)\r\n\r\n # Enter your message to send to client\r\n # new_data = str(input('You: ')).encode('utf-8')\r\n # connection.send(new_data)\r\n finally:\r\n # close connection\r\n connection.close()\r\n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"116641206","text":"from db import DB\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom datetime import datetime\napp = Flask(__name__)\n\ndb = DB()\ndb.seed()\n\n@app.route('/')\ndef index():\n page = request.args.get('page', 0, int)\n entries = [(e[0], datetime.strptime(e[1], \"%Y-%m-%d %H:%M:%S.%f\").strftime(\"%X %d. %m. %Y\"), e[2]) for e in db.get_entries(page, 20)]\n pages = int(db.count_entries()[0]/20)\n return render_template(\"index.html\", entries=entries, pages=pages, page=page)\n\n@app.route('/add', methods=['POST'])\ndef add():\n db.add_entry(datetime.now())\n return ('', 200)\n\n@app.route('/read', methods=['POST'])\ndef read():\n id = request.args.get('id')\n page = request.args.get('page')\n try:\n id = int(id)\n except:\n abort(400)\n db.mark_read(id)\n return redirect(url_for('index', page=page))\n\n@app.route('/unread', methods=['POST'])\ndef unread():\n id = request.args.get('id')\n page = request.args.get('page')\n try:\n id = int(id)\n except:\n abort(400)\n db.mark_unread(id)\n return redirect(url_for('index', page=page))\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"28737402","text":"# import requests\n# import json\n# import pprint\n# url = 'http://musicapi.leanapp.cn/playlist/detail?id=3199698721'\n# headers = {\n# 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11',\n# 'Referer': 'http://musicapi.leanapp.cn/'\n# }\n# url2 = 'https://music.163.com/#/song?id='\n# html = requests.get(url).text\n# data = json.loads(html)\n# # print(data)\n# #让我们来爬个虫好吗\n# music = data['playlist']['tracks']\n# #for cloudmusic in music:\n# # title = cloudmusic['name']\n# # description = cloudmusic['name']\n# # img = cloudmusic['al']['picUrl']\n# # url = cloudmusic['id']\n# # 爬你妈,给爷爬,敲代码要暴躁\n# for cl in music:\n# print(cl['name'])\n# url = \"https://music.163.com/#/song?id=\"\n# id = cl['id']\n# print(url,id)\n# # pprint.pprint(title)\n# # encoding=utf8\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\nheaders = {\n 'Referer': 'http://music.163.com/',\n 'Host': 'music.163.com',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n}\nplay_url = 'http://music.163.com/playlist?id=3199698721'\ns = requests.session()\nresponse = s.get(play_url, headers=headers).content\ns = BeautifulSoup(response, 'lxml')\nmain = s.find('ul', {'class': 'f-hide'})\nurl = '
    '\nfor music in main.find_all('a'):\n print('{}{}{}{}{}'.format(url,str(music['href']),url2,music.text,''))","sub_path":"list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"189969524","text":"# В школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики.\n\n\n# Т.е. Учитель Иванов может преподавать математику у 5А и 6Б,\n# но больше математику не м��жет преподавать никто другой.\n#\nfrom collections import namedtuple\n\nclass Student:\n\n def __init__(self):\n self.student = [\"Egor Petrov\", \"Vasya Pupochkin\", \"Vladimir Petushkov\", \"Lamila Kostileva\", \"Lena Glubokova\"]\n self.parents_father = [\"Timur Petrov\", \"Gosha Pupochkin\", \"Vladislav Petushkov\", \"Kolya Kostilev\",\n \"Sergei Glubokov\"]\n self.parents_mather = [\"Olga Petrova\", \"Elena Pupochkina\", \"Sveta Petushkova\", \"Katerina Kostileva\",\n \"Nina Glubokova\"]\n # self.student_id = student_id\n\n \"\"\"Ученики , # У каждого ученика есть два Родителя(мама и папа).\n Родители\"\"\" # 4. Узнать ФИО родителей указанного ученика\n\n def get_student_all(self):\n return self.student\n\n def get_parents_father(self):\n return self.parents_father\n\n def get_parents_mather(self):\n return self.parents_mather\n\n def get_student_parents_FIO(self, student_id):\n # print(type(self.parents_father))\n # x = [y.split(\" \")[1] for y in self.parents_father]\n # print(x)\n mom = 0\n pop = 0\n if student_id in self.student:\n if student_id.split(\" \")[1] in [x.split(\" \")[1] for x in self.parents_father] or student_id.split(\" \")[1][0: -1] in [l.split(\" \")[1] for l in self.parents_father] or student_id.split(\" \")[1][0: -2] in [s.split(\" \")[1] for s in self.parents_father] and student_id.split(\" \")[1] in [y.split(\" \")[1][0:-1] for y in self.parents_mather] or student_id.split(\" \")[1] in [n.split(\" \")[1][0:-2] for n in self.parents_mather]:\n for i in range(len(self.parents_father)):\n if self.parents_father[i].split(\" \")[1] == student_id.split(\" \")[1] or self.parents_father[i].split(\" \")[1] == student_id.split(\" \")[1][0:-1] or self.parents_father[i].split(\" \")[1] == student_id.split(\" \")[1][0:-2]:\n pop = self.parents_father[i]\n\n for i in range(len(self.parents_mather)):\n if self.parents_mather[i].split(\" \")[1][0:-1] == student_id.split(\" \")[1] or self.parents_mather[i].split(\" \")[1][0:-1] == student_id.split(\" \")[1][0:-2] or self.parents_mather[i].split(\" \")[1][0:-1] == student_id.split(\" \")[1] or self.parents_mather[i].split(\" \")[1] == student_id.split(\" \")[1]:\n mom = self.parents_mather[i]\n\n return (f\"Родители студента {student_id} Папа:{pop} Мама:{mom}\")\n return False\n\nclass School(Student):\n\n def __init__(self): # student, parents_father, parents_mather\n # self.classtype = classtype\n # \"Классы\" В школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики.\n # self.class_5A = list()\n # self.class_5B = list()\n # self.class_5C = list()\n # self.class_6A = list()\n # self.class_6B = list()\n\n self.class_of_school = [\"5A\", \"5B\", \"5C\", \"6A\", \"6B\"]\n # \"Учителя\"\n self.teacher = [\"Anrdey Kolesnikov\", \"Vladimir Gorelov\", \"Vitaliy Putin\", \"Kentavr Kolbasinov\"]\n # \"Занятия\"\n self.lesson = [\"Math\", \"Physics\", \"Madhouse\"]\n # 'Описание\"\n Student.__init__(self)\n # 1. Получить полный список всех классов школы\n self.dict_klass_in_student = {self.student[0]: self.class_of_school[0],\n self.student[1]: self.class_of_school[1],\n self.student[2]: self.class_of_school[2],\n self.student[3]: self.class_of_school[3],\n self.student[4]: self.class_of_school[4],\n }\n # Массивы для записи уроков в классы\n\n\n\n # Словари для связок. Пример учитель(key) > урок(value)\n self.dict_teacher_lesson = dict()\n self.dict_klass_on_teacher = dict()\n self.dict_klass_in_lesson = dict()\n\n # 2. Получить список всех учеников в указанном классе\n\n\n\n def get_all_class_of_school(self):\n return self.dict_klass_in_student\n # Получить все классы школы\n def get_class_of_school(self):\n return self.class_of_school\n\n def get_teacher_all(self):\n return self.teacher\n\n def del_class_of_school(self, classtype):\n return self.class_of_school.remove(classtype)\n\n def add_class_of_school(self, classtype):\n return self.class_of_school.append(classtype)\n\n def add_teacher_lesson(self, teacher_usr, lesson_usr):\n if teacher_usr in self.teacher and lesson_usr in self.lesson:\n #Учитель Иванов может преподавать математику у 5А и 6Б, но больше математику не может преподавать никто друго\n if not teacher_usr in self.dict_teacher_lesson:\n self.dict_teacher_lesson[teacher_usr] = lesson_usr\n return True\n return False\n\n def add_klass_teacher(self, teacher_usr, klass_usr):\n if teacher_usr in self.teacher and klass_usr in self.class_of_school:\n if not self.dict_klass_on_teacher.get(teacher_usr) == klass_usr:\n\n self.dict_klass_on_teacher[klass_usr] = teacher_usr\n return True\n return False\n\n def add_klass_in_lesson(self, klass_usr, lesson_usr):\n if klass_usr in self.class_of_school and lesson_usr in self.lesson:\n if not self.dict_klass_in_lesson.get(klass_usr) == lesson_usr:\n tmp = list()\n if self.dict_klass_in_lesson.get(klass_usr) != None:\n for item in self.dict_klass_in_lesson.get(klass_usr):\n tmp.append(item)\n tmp.append(lesson_usr)\n else:\n tmp.append(lesson_usr)\n self.dict_klass_in_lesson[klass_usr] = tmp\n return self.dict_klass_in_lesson\n return False\n\n def schooll_grid(self, student_id): # (Ученик --> Класс --> Учителя --> Предметы)\n a = list()\n a.append(student_id)\n a.append(self.dict_klass_in_student.get(student_id))\n a.append(self.dict_klass_on_teacher.get(self.dict_klass_in_student.get(student_id)))\n a.append(self.dict_klass_in_lesson.get(self.dict_klass_in_student.get(student_id)))\n return a\n\n# -------Main------\n# 5. Получить список всех Учителей, преподающих в указанном классе\na = \"Lamila Kostileva\"\nstud = Student()\nx = School()\n\n# add add_teacher_lesson\nx.add_teacher_lesson(\"Anrdey Kolesnikov\", \"Madhouse\")\nx.add_teacher_lesson(\"Vladimir Gorelov\", \"Math\")\nx.add_teacher_lesson(\"Vitaliy Putin\", \"Physics\")\n\n# add_klass_in_lesson\nx.add_klass_in_lesson(\"5A\", \"Math\")\nx.add_klass_in_lesson(\"5A\", \"Physics\")\nx.add_klass_in_lesson(\"5A\", \"Madhouse\")\nx.add_klass_teacher(\"Anrdey Kolesnikov\", \"5A\")\n\n# add_klass_in_lesson\nx.add_klass_in_lesson(\"5B\", \"Math\")\nx.add_klass_in_lesson(\"5B\", \"Madhouse\")\nx.add_klass_teacher(\"Kentavr Kolbasinov\", \"5B\")\n\n\n# Tod\nprint(x.schooll_grid('Vasya Pupochkin'))","sub_path":"Normal.py","file_name":"Normal.py","file_ext":"py","file_size_in_byte":7756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"14302012","text":"#!/usr/local/bin/python3\n\n# Input: .\n# Output: or \n# argv[1] a key i.e. V1#V2\n# argv[2] a file containing a list of 0's and 1's\n\nimport sys\n\nkey = sys.argv[1]\nfilename = sys.argv[2]\ncount1 = 0\ncount0 = 0\n\ncandidates = key.split(\"#\")\nA = candidates[0]\nB = candidates[1]\n\n# Count the number of 0s and number of 1s\nwith open(filename, \"r\") as file:\n for line in file:\n line = line.strip()\n if len(line) > 0:\n if line == \"1\":\n count1 += 1\n elif line == \"0\":\n count0 += 1\n\nif count1 > count0: # if more 1s than 0s, output (A,B) // A dominates B\n print(A + \",\" + B)\nelse:\n print(B + \",\" + A) # B dominates A\n","sub_path":"app/win_juice1.py","file_name":"win_juice1.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"353087788","text":"import json\nfrom Helpers.HelpOperations import delete, add, printAll, saveBooks, find, count\n\n\ndef run(command, listOfbooks, params):\n #while(True):\n #print(\"Введите команду\")\n #command = input()\n #if command == \"start\":\n json_data = open(\"C:\\\\Users\\\\User\\\\PycharmProjects\\\\LibaryPython\\\\books.json\") # Загружаем файл\n d = json.load(json_data)\n listOfbooks = d[\"books\"]\n print(\"Поступившая комманда: \", command)\n if command == \"print all\" or command == \"1\":\n msg = printAll(listOfbooks) # Напечатать информацию о книге\n return msg\n elif command == \"add\":\n listOfbooks = add(listOfbooks, params)#Добавить книгу. Для описания функции. Смотреть соответствующий файл\n saveBooks(listOfbooks)\n return \"add completed. Input print all to see.\"\n elif command == \"delete\":\n msg = delete(listOfbooks, params)#Удалить книгу. Для описание функции. Смотреть соответсвующий файл\n return msg\n elif command == \"find\":\n print(\"appJson: find book\")\n msg = find(listOfbooks, params)# Найти книгу по имени\n return msg\n elif command == \"save\" or command == \"8\":\n saveBooks(listOfbooks)# Сохранить изменения в книгах\n return \"save completed\"\n elif command == \"exit\":\n print(\"appJson: Завершаю программу\")\n saveBooks(listOfbooks)\n return listOfbooks\n elif command == \"count\" or command == \"7\":\n cnt = count(listOfbooks)\n return cnt\n else :\n print(\"appJson: Нет такой команды\")\n return \"no such command\"\n\n\n","sub_path":"appJson.py","file_name":"appJson.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"457160789","text":"import cv2\nimport time\nfrom multiprocessing import Queue\nimport numpy as np\n\nFMT = '%Y-%m-%d %H:%M:%S'\n\ndef scan(target):\n cap = cv2.VideoCapture(0)\n\n while cap.isOpened():\n ret, img = cap.read()\n if ret:\n turn = ball(img)\n print(time.strftime(FMT), 'put', turn)\n target.put(turn, block=True, timeout=None)\n time.sleep(0.25)\n \"\"\"cv2.imshow('Image', img)\n key = cv2.waitKey(1) & 0xFF\n if key == ord('q'):\n break\"\"\"\n\n \ndef ball(img):\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n #low_range = np.array([20, 50, 100], dtype=np.uint8)\n #high_range = np.array([40, 255, 200], dtype=np.uint8)\n low_range = np.array([0, 50, 100], dtype=np.uint8)\n high_range = np.array([10, 255, 255], dtype=np.uint8)\n clr_range1 = cv2.inRange(hsv, low_range, high_range)\n low_range = np.array([170, 50, 100], dtype=np.uint8)\n high_range = np.array([180, 255, 255], dtype=np.uint8)\n clr_range2 = cv2.inRange(hsv, low_range, high_range)\n clr_range = clr_range1 + clr_range2\n #cv2.imshow('hsv', clr_range); cv2.waitKey(0)\n \n circles = cv2.HoughCircles(clr_range, cv2.HOUGH_GRADIENT, 1, 100,\n param1=150, param2=15, minRadius=5, maxRadius=150)\n if circles is not None:\n #print(len(circles))\n circles = np.uint16(np.around(circles))\n for i in circles[0,:]:\n cv2.circle(img, (i[0], i[1]), i[2], (0, 0, 255), 2)\n break\n else:\n return 'tank_turn'\n return 'left' if i[0] > 320 else 'right'\n\ndef human(img):\n hog = cv2.HOGDescriptor()\n hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n (rects, weights) = hog.detectMultiScale(gray, winstride=(4, 4),\n padding=(8, 8), scale=(1.05))\n for (x, y , w, h) in rects:\n cv2.rectangle(img, (x,y), (x + w, y + h), (255, 0, 0), 2)\n break\n\ndef face(img):\n face_cascade = cv2.CascadeClassifier('/path/to/cv2/data/haarcascade_frontalface_default.xml')\n eye_cascade = cv2.CascadeClassifier('/path/to/cv2/data/haarcascade_eye.xml')\n \n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n \n for (x, y, w, h) in faces:\n face = cv2.rectangle(img, (x,y), (x + w, y + h), (0, 255, 0), 2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n eyes = eye_cascade.detectMultiScale(roi_gray)\n for (ex, ey, ew, eh) in eyes:\n cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)\n\n \nif __name__ == '__main__':\n target = Queue()\n scan(target)","sub_path":"Tank/Vision.py","file_name":"Vision.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"509298004","text":"# This script trains a keras model for human driver behavioral cloning.\n# Input: camera image, Output: steering wheel angle.\n# April 22nd, 2018, By S.CHEN\n\n# Imports\nimport numpy as np\nimport os, cv2, csv, keras, sklearn\nfrom datetime import datetime\n\nclass SetParams(object):\n '''\n Group all (hyper)parameters.\n '''\n def __init__(self):\n # data params\n self.logfile = './data/driving_log.csv'\n self.input_shape = (160, 320, 3) \n self.crop_region = ((60,25), (0,0))\n self.use_augmented_data = True\n \n # training parmas\n self.training_flag = True\n self.batch_size = 256\n self.optimizer = 'adam'\n self.learning_rate = 0.01\n self.lr_decay_step = 20\n self.regularizer_val = 0.001\n self.dropout_rate = 0.1\n self.num_epochs = 100\n\n # checkpoint params\n self.weights_dir = './weights'\n self.continued_training = False\n self.ckpt_file = './weights/ckpt.h5'\n\nclass LoadData(object):\n '''\n Load train(dev) data\n '''\n def __init__(self, params):\n self.logfile = params.logfile\n self.samples = []\n self.train_samples = []\n self.validation_samples = []\n self.use_augmented_data = params.use_augmented_data\n \n # Get training data from log file\n self.get_samples()\n\n # Split train/dev set\n self.split_data()\n \n # Compute number of batches\n self.num_train_batches = len(self.train_samples) // params.batch_size\n self.num_validation_batches = len(self.validation_samples) // params.batch_size\n \n # Compute standard variation of steering angle (to be used as correction value)\n self.compute_angle_correction()\n\n def get_samples(self):\n '''Get data from log file'''\n with open(self.logfile) as f:\n reader = csv.reader(f)\n next(reader) # Skip header\n for line in reader:\n self.samples.append(line)\n\n def compute_angle_correction(self):\n '''Compute std value of steering angles, and use it as correction angle'''\n angles = []\n with open(self.logfile) as f:\n reader = csv.reader(f)\n next(reader) # Skip header\n for line in reader:\n angles.append(float(line[3]))\n correction = np.std(angles)\n self.angle_correction = max(correction, 0.01)\n print('Angle correction used in data augmentation is {:.4f}'.format(self.angle_correction))\n \n def split_data(self):\n '''\n Split data set to train/dev set\n '''\n from sklearn.model_selection import train_test_split\n self.train_samples, self.validation_samples = train_test_split(self.samples, test_size=0.2)\n\n def data_augmentation(self, batch_sample, train_flag):\n '''\n Apply data augmentation on input image, and change target value accordingly\n '''\n img_dir = 'data/IMG/'\n splitter = '/'\n # When no augmented data are to be used, load the central image only\n if (train_flag == False) or (self.use_augmented_data == False):\n name = img_dir + batch_sample[0].split(splitter)[-1]\n img = cv2.imread(name)\n angle = float(batch_sample[3])\n else: # In case of using augmented data:\n #print('correction angle: {:.4f}'.format(self.angle_correction))\n angle = float(batch_sample[3]) # Get the steering angle\n augmentation_ratio = 0.5 # Set augmentation ratio\n if(np.random.uniform() > 0.5):\n img_name = img_dir + batch_sample[0].split(splitter)[-1]\n img = cv2.imread(img_name)\n if (np.random.uniform() > 0.5): # Half of time use its flipped version\n img = cv2.flip(img, flipCode=1)\n angle = -angle\n elif(np.random.uniform() > 0.5): # Use left image\n img_name = img_dir + batch_sample[1].split(splitter)[-1]\n img = cv2.imread(img_name)\n angle += self.angle_correction # apply angle correction\n else: # Use right image\n img_name = img_dir + batch_sample[2].split(splitter)[-1]\n img = cv2.imread(img_name)\n angle -= self.angle_correction # apply angle correction\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR image to RGB\n return img, angle\n\n def generator(self, samples, batch_size, train_flag):\n '''Generate mini-batch data for training'''\n num_samples = len(samples)\n while True:\n np.random.shuffle(samples) # Shuffle data for each epoch\n for offset in range(0, num_samples, batch_size): # Yield mini-batchs\n batch_samples = self.samples[offset:offset+batch_size]\n images = []\n angles = []\n for sample in batch_samples:\n # Perform data augmentation on training samples\n img, angle = self.data_augmentation(sample, train_flag) \n images.append(img)\n angles.append(angle)\n X = np.array(images)\n y = np.array(angles)\n yield sklearn.utils.shuffle(X, y)\n \ndef behavior_clone_model(params):\n '''\n Create keras model to predict steering angle given camera image\n '''\n from keras.models import Sequential\n from keras.layers import Flatten, Dense, Dropout, Activation, Input, Lambda, Cropping2D\n from keras.layers.convolutional import Conv2D, MaxPooling2D\n from keras.layers.normalization import BatchNormalization\n from keras import regularizers\n from keras.layers import Lambda\n model = Sequential()\n \n # Crop out RoI\n model.add(Cropping2D(cropping=params.crop_region, input_shape=params.input_shape))\n \n # Whitening input\n model.add(Lambda(lambda x: x / 255.0 - 0.5))\n \n # conv1 --> batch_norm1 --> relu1 --> pool1\n # Stride more along horizental axis to compensate vertical depth compression\n model.add(Conv2D(24, (5,5), strides=(2,4), kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n model.add(BatchNormalization())\n model.add(Activation('relu', name='relu_1'))\n model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), name='pool_1'))\n \n # conv2 --> batch_norm2 --> relu2 --> pool2\n model.add(Conv2D(32, (3,3), padding='same', kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n model.add(BatchNormalization())\n model.add(Activation('relu', name='relu_2'))\n model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), name='pool_2')) \n\n # conv3 --> batch_norm3 --> relu3 --> pool3\n model.add(Conv2D(48, (3,3), padding='same', kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n model.add(BatchNormalization())\n model.add(Activation('relu', name='relu_3'))\n model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), name='pool_3')) \n\n # conv4, convolve activation map into vector (to conect 1x1 convlution)\n model.add(Conv2D(64, (3,9), kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n model.add(BatchNormalization())\n model.add(Activation('relu', name='relu_4'))\n \n # Dropout 4\n model.add(Dropout(params.dropout_rate, name='dropout_4'))\n\n # Conv5\n model.add(Conv2D(16, (1,1), kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n model.add(BatchNormalization())\n model.add(Activation('relu', name='relu_6'))\n\n # Conv6: output steering angle value\n model.add(Conv2D(1, (1,1), kernel_regularizer = regularizers.l1_l2(params.regularizer_val)))\n \n # Reshape to scalar\n model.add(keras.layers.Reshape((1,)))\n\n # View graph layout\n model.summary()\n return model\n\ndef compile_model(model, params):\n '''\n Set training optimizer and compile model\n '''\n opt = keras.optimizers.Adam(lr=params.learning_rate)\n model.compile(loss='mse', optimizer=opt)\n\ndef show_training(train_history):\n '''\n Visualize training and validation process\n '''\n import matplotlib.pyplot as plt\n print(train_history.history.keys())\n plt.plot(train_history.history['loss'])\n plt.plot(train_history.history['val_loss'])\n plt.title('model mean squared error loss')\n plt.ylabel('mean squared error loss')\n plt.xlabel('epoch')\n plt.legend(['training set', 'validation set'], loc='upper right')\n plt.show()\n plt.savefig('training_process.png', bbox_inches='tight')\n \ndef train_model(model, train_data, params):\n '''\n Train/validate model on training/validation data, and save model \n '''\n # Generator for train/dev set\n train_generator = train_data.generator(train_data.train_samples, \n params.batch_size, \n True)\n validation_generator = train_data.generator(train_data.validation_samples, \n params.batch_size, \n False) # Set train_flag to False, which disables data augmentation.\n\n # Prepare to save\n if not os.path.isdir(params.weights_dir): os.mkdir(params.weights_dir)\n \n # Load checkpoint file if in continued training\n if params.continued_training == True:\n assert os.path.exists(params.ckpt_file)\n model.load_weights(params.ckpt_file, by_name=True)\n\n # Define learning rate schedule\n # Linear lr decay\n lr_schedule = lambda x : params.learning_rate / (10.**(x//params.lr_decay_step))\n ## Ploy lr decay \n #lr_schedule = lambda x : params.learning_rate * (1.0-x/params.num_epochs)**0.9\n lr_schedule_callback = keras.callbacks.LearningRateScheduler(lr_schedule, verbose=1)\n ckpt_name = params.weights_dir + '/' + '{val_loss:.4f}_{epoch:03d}.h5'\n save_model_callback = keras.callbacks.ModelCheckpoint(ckpt_name,\n monitor='val_loss', \n verbose=0, \n save_best_only=False, \n save_weights_only=False, \n mode='auto', \n period=1)\n callbacks = [lr_schedule_callback, save_model_callback]\n\n # Train the model\n if params.training_flag == True:\n train_history = model.fit_generator(train_generator,\n steps_per_epoch = train_data.num_train_batches,\n\t \t\t\t\t validation_data = validation_generator, \n\t \t\t\t\t validation_steps = train_data.num_validation_batches,\n\t \t\t\t\t epochs = params.num_epochs, \n\t \t\t\t\t verbose = 1,\n callbacks = callbacks)\n\n # Visualization training process\n show_training(train_history)\n \n # Save trained model\n model.save('{}.h5'.format(datetime.now().strftime(\"%m_%d_%H_%M\")))\n \ndef main():\n # Set all training parameters\n params = SetParams()\n\n # Load training data\n train_data = LoadData(params)\n \n # Create model\n model = behavior_clone_model(params)\n\n # Compile model\n compile_model(model, params)\n\n # Train/validate and save model\n train_model(model, train_data, params)\n\nif __name__ == '__main__':\n main()","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"635127877","text":"import algorithm.Struct_Start\nfrom django.forms.models import model_to_dict\nfrom books import models\nimport datetime\n\n# Determine the phrase is overlap or not\n# If overlap, we can assume this number is belong to one column\ndef overlap(pos1, pos2):\n if pos1[0] > pos2[0] and (pos2[0] + pos2[0] > pos1[0]):\n return True\n elif pos2[0] > pos1[0] and (pos1[0] + pos1[2] > pos2[0]):\n return True\n return False\n\n# Determine whether word is a useful number or not\n# This function is part of txt pre-processing\ndef numpossible(word):\n i = 0\n if len(word) == 1:\n return True\n for c in word:\n if c.isdigit() and i <= 4:\n try:\n f = float(word[i:])\n return True\n except ValueError:\n return False\n else:\n i = i + 1\n return False\n\n# Input one sentence. According different rules, this function can classify sentences\n# Type -1: Sentence may from paragraph which we don't care\n# String: this line is belong to a certain type\n# Type 0: It is part of spreadsheet and we don't know the type of this line\n# Type 1: Contains all number and number is belong to years\n# Type 2: Contains all number and number isn't belong to years\ndef identify(trie, line, years):\n count = 0\n length = len(line)\n type = trie.searchWord(line[0])\n if type != -1:\n return type\n subtype = models.Synonym.objects.filter(word_from_fin__istartswith=line[0]).order_by(\"count\")\n if len(subtype) != 0:\n return subtype[0].property\n for word in line:\n if numpossible(word):\n count = count + 1\n if count == length and not line[len(line)-1] in years:\n return 2\n elif count == length:\n return 1\n elif count == length - 1 and count != 0 and not numpossible(line[0]):\n return 0\n return -1\n\n# Output the finial outcome\ndef targetNum(trie, excel):\n now = datetime.datetime.now().year\n years = set()\n # Input year information\n for i in range(0, 5):\n years.add(str(now-i))\n years.add(str(now-i)[-2:])\n data = dict()\n # Memorize the tile\n title = list()\n titleloca = list()\n # Memorize type information\n stack = list()\n for i in range(0, len(excel), 2):\n tap = identify(trie, excel[i], years)\n if tap == -1:\n title = excel[i]\n titlepos = excel[i + 1]\n stack = list()\n elif isinstance(tap, str):\n temp = list()\n if tap in data:\n temp = data[tap]\n temp.append(excel[i])\n data[tap] = temp\n if len(stack) > 0 and stack[len(stack)-1] == tap:\n continue\n else:\n stack.append(tap)\n elif tap == 0:\n if len(stack) != 0:\n last = stack[len(stack)-1]\n data[last].append(excel[i])\n else:\n if not \"Other\" in data:\n data[\"Other\"] = list()\n data[\"Other\"].append(excel[i])\n elif tap == 1:\n title = excel[i]\n titlepos = excel[i+1]\n stack = list()\n elif tap == 2:\n if len(stack) != 0:\n last = stack.pop()\n data[last].append(excel[i])\n return data","sub_path":"backend/algorithm/Target.py","file_name":"Target.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"308653866","text":"from tkinter import*\nNUMS={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15,'G':16,'H':17,'I':18,'J':19,'K':20,'L':21,\n 'M':22,'N':23,'O':24,'P':25,'Q':26,'R':27,'S':28,'T':29,'U':30,'V':31,'W':32,\n 'X':33,'Y':34,'Z':35}\nNEW_D = {value: key for key, value in NUMS.items()}\nclass Application(Frame):\n def __init__(self, master):\n super().__init__(master)\n self.grid()\n self.create_widgets()\n def create_widgets(self):\n self.inst_lbl=Label(self,text='Введите Символ:')\n self.inst_lbl.grid(row = 0, column = 0, sticky = W )\n self.pw_ent=Entry(self)\n self.pw_ent.grid(row = 0, column = 1, sticky =W)\n self.bttn=Button(self, text ='Показать ord', command =self.count)\n self.bttn.grid(row=0,column=2)\n self.txt=Text(self,width = 20, height = 1, wrap = WORD)\n self.txt.grid(row=0,column=3,sticky=W)\n def count(self):\n sym=self.pw_ent.get()\n try:\n ans=ord(sym)\n except:\n ans='Некорректный ввод'\n self.text(ans)\n def text(self,txt):\n message=txt\n self.txt.delete(0.0, END)\n self.txt.insert(0.0, message)\n# основная часть\nroot=Tk()\nroot.title('Мини-конвертер')\nroot.geometry('475x25')\napp=Application(root)\nroot.mainloop()","sub_path":"Others/ORD.py","file_name":"ORD.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"524810823","text":"\"\"\"go_coup URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom . import views\n\napp_name = 'user'\nLOGIN_URL = 'login'\nLOGOUT_URL = 'logout'\nLOGIN_REDIRECT_URL = 'home'\nSOCIAL_AUTH_FACEBOOK_KEY = '504951239878757' # App ID\nSOCIAL_AUTH_FACEBOOK_SECRET = 'd6e8030eb8a53f82a34c169139993bd4' # App Secret\n\nurlpatterns = [\n url(r'^register/$', views.customerRegister, name='customer-register'),\n url(r'^store-register/$', views.storeRegister, name='store-register'),\n url(r'^login/$',views.singin, name='login'),\n url(r'^logout/$',views.signout, name='logout'),\n url(r'^tempprofile/$',views.profile, name='profile'),\n url(r'^profile/$',views.customerProfile, name='customer-profile'),\n url(r'^coupon/$',views.customerCoupon, name='customer-coupon'),\n url(r'^wallet/$',views.customerWallet, name='customer-wallet'),\n url(r'^customertest/$',views.customertest, name='customertest'),\n url(r'^storetest/$',views.storetest, name='storetest'),\n url(r'^setting/$',views.customerSetting, name='customer-setting'),\n]\n","sub_path":"web/usermanage/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"335402418","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import Warning\nfrom odoo.exceptions import UserError, RedirectWarning, ValidationError\n\n\nclass payment_plan_wizard(models.TransientModel):\n _name = 'payment.plan.wizard'\n\n name = fields.Char(string=\"Name\")\n owner = fields.Many2one('res.users', string='Requested By', default=lambda self: self.env.user)\n payment_date = fields.Date('Payment Date')\n memo = fields.Char('Memo')\n amount_total = fields.Float(string=\"Total\",compute=\"get_total\")\n\n payment_line_ids = fields.One2many('payment.plan.line', 'payment_id', string=\"Plan\")\n\n @api.depends('payment_line_ids.total')\n def get_total(self):\n total = 0\n for line in self.payment_line_ids:\n total += line.total\n\n self.amount_total = total\n\n @api.model\n def default_get(self, vals):\n res = super(payment_plan_wizard, self).default_get(vals)\n payment_paid = self.env['account.invoice'].search([('state','in',['paid']),('id','in',self._context.get('active_ids'))])\n if payment_paid:\n raise Warning('Paid bill cannot be processed.')\n\n else:\n payment_line = self.env['account.invoice'].browse(self._context.get('active_ids'))\n payment = []\n for bill in payment_line:\n dict = (0,0, {\n 'partner_id': bill.partner_id.id,\n 'date': bill.date_invoice,\n 'number': bill.number,\n 'reference': bill.reference,\n 'due_date': bill.date_due,\n 'source_doc': bill.origin,\n 'total': bill.amount_total,\n })\n payment.append(dict)\n res.update({'payment_line_ids' :payment})\n return res\n\n @api.multi\n def create_payment_line(self):\n payment_model = self.env['payment.plan']\n order_list = []\n for order in self:\n for line in order.payment_line_ids:\n order_list.append((0,0,{\n 'partner_id':line.partner_id.id,\n 'date':line.date,\n 'number':line.number,\n 'reference':line.reference,\n 'due_date':line.due_date,\n 'source_doc':line.source_doc,\n 'total':line.total,\n }))\n\n payment = payment_model.create({\n 'owner':order.owner.id,\n 'payment_date':order.payment_date,\n 'memo':order.memo,\n 'plan_line_ids':order_list\n })\n \n if payment:\n self.payment_plan_id = payment.id\n\n res = {\n 'name':'Payment Plan',\n 'view_type':'form',\n 'view_mode':'form',\n 'res_model':'payment.plan',\n 'type':'ir.actions.act_window',\n 'target':'current',\n 'context':{},\n }\n\n if self.payment_plan_id:\n res['res_id'] = payment.id\n return res\n \n\nclass payment_plan_line(models.TransientModel):\n _name = 'payment.plan.line'\n\n payment_id = fields.Many2one('payment.plan.wizard', string=\"Payment\")\n\n partner_id = fields.Many2one('res.partner', 'Vendor')\n date = fields.Date('Bill Date')\n number = fields.Char('Number')\n reference = fields.Char('Vendor Reference')\n due_date = fields.Date('Due Date')\n source_doc = fields.Char('Source Document')\n total = fields.Float('Total')","sub_path":"payment_plan/wizard/generate_payment_wizard.py","file_name":"generate_payment_wizard.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"370549635","text":"import os\nimport re\nimport pandas as pd\n\na = {'Image Name': [],\n 'PID' : [],\n 'Session Name': [],\n 'Session#': [],\n 'Mem Usage': []\n }\n\nwith os.popen('tasklist','r') as f:\n for i,line in enumerate(f):\n t = re.split(r'\\s\\s+|\\t',line.rstrip())\n if len(t) > 3 and i > 1:\n a['Image Name'] += [t.pop(0)]\n s = t.pop(0)\n s = s.split()\n a['PID'] += [s.pop(0)]\n a['Session Name'] += [s.pop(0)]\n a['Session#'] += [t.pop(0)]\n a['Mem Usage'] += [t.pop(0)]\n\n\n\nprint(pd.DataFrame.from_dict(a))\n","sub_path":"retask.py","file_name":"retask.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"336771103","text":"import tinydb\nimport sys\nfrom downloader import downloader\n\ndef select():\n action = { '1': 'new download',\n '2': 'continue download',\n '3': 'show status'}\n\n for i in action:\n print(\"[\" + i + \"] \" + action.get(i))\n print(\"\")\n print(\"Action: \", end='')\n choose = input()\n\n if choose not in action.keys():\n choose = '0'\n return choose\n\nif __name__ == '__main__':\n d = downloader()\n choose = select()\n\n if choose == '1':\n print(\"Enter URL: \")\n url = input()\n d.new_download(url)\n elif choose == '2':\n d.status()\n print(\"Enter PID: \", end='')\n pid = input()\n info = d.database.search(tinydb.where('pid') == int(pid))\n if not info:\n raise Exception(\"Wrong pid\")\n d.cont_download(info[0])\n elif choose == '3':\n print(\"Status\")\n d.status()\n elif choose == '0':\n print(\"Exit\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"210379523","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Library for handling the model agnostic TensorFlow graph.\n\nIn particular, the class defined creates a graph with placeholders for\nfeeding in FeaturesPredictionsLabels and calculating metrics via metric\ncallbacks., Some care must be given when creating the input placeholders\nand the feedlist as they match. To achieve this, the graph is created with\nan example FPL to determine FPL feed structure.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Standard __future__ imports\nfrom __future__ import print_function\n\nimport datetime\n# Standard Imports\nimport apache_beam as beam\nimport tensorflow as tf\n\nfrom tensorflow_model_analysis import constants\nfrom tensorflow_model_analysis import types\nfrom tensorflow_model_analysis.eval_metrics_graph import eval_metrics_graph\nfrom tensorflow_model_analysis.eval_saved_model import encoding\nfrom tensorflow_model_analysis.eval_saved_model import util\n\nfrom typing import Any, Generator, List, Optional, Text, Tuple # pytype: disable=not-supported-yet\n\n\ndef make_construct_fn( # pylint: disable=invalid-name\n add_metrics_callbacks: Optional[List[types.AddMetricsCallbackType]],\n fpl_feed_config: eval_metrics_graph.FPLFeedConfig):\n \"\"\"Returns a construct fn for constructing the model agnostic eval graph.\"\"\"\n\n def construct_fn(model_load_seconds: beam.metrics.metricbase.Distribution):\n \"\"\"Thin wrapper for the actual construct to allow for metrics.\"\"\"\n\n def construct(): # pylint: disable=invalid-name\n \"\"\"Function for constructing a model agnostic eval graph.\"\"\"\n start_time = datetime.datetime.now()\n model_agnostic_eval = ModelAgnosticEvaluateGraph(add_metrics_callbacks,\n fpl_feed_config)\n end_time = datetime.datetime.now()\n model_load_seconds.update(int((end_time - start_time).total_seconds()))\n return model_agnostic_eval\n\n return construct\n\n return construct_fn\n\n\nclass ModelAgnosticEvaluateGraph(eval_metrics_graph.EvalMetricsGraph):\n \"\"\"Class handler for using a ModelAgnosticEvaluation graph.\"\"\"\n\n def __init__(self, add_metrics_callbacks: List[types.AddMetricsCallbackType],\n fpl_feed_config: eval_metrics_graph.FPLFeedConfig):\n # Note that we do not actually initialize the graph here. The reason is we\n # wait until we get the first FeaturesPredictionsLabels to get\n # how the graph is to be constructed. Otherwise, we will need define a\n # config.\n self._add_metrics_callbacks = add_metrics_callbacks\n self._fpl_feed_config = fpl_feed_config\n super(ModelAgnosticEvaluateGraph, self).__init__()\n\n def _construct_graph(self):\n \"\"\"Creates a graph which we instantiate FPL infeed and metric ops.\"\"\"\n with self._graph.as_default():\n # Create the infeed ops.\n self._create_infeed_ops()\n self.register_add_metric_callbacks(self._add_metrics_callbacks)\n\n def _iterate_fpl_maps_in_canonical_order(\n self\n ) -> Generator[Tuple[Text, types.FPLKeyType, types.TensorType], None, None]:\n for key, value in sorted(self._fpl_feed_config.features.items()):\n yield 'features', key, value # pytype: disable=bad-return-type\n for key, value in sorted(self._fpl_feed_config.predictions.items()):\n yield 'predictions', key, value # pytype: disable=bad-return-type\n for key, value in sorted(self._fpl_feed_config.labels.items()):\n yield 'labels', key, value # pytype: disable=bad-return-type\n\n def _create_placeholder(self, fpl_feed: Tuple[Text, Any]):\n \"\"\"Generates a placeholder op given the input fetched_tensor_value.\"\"\"\n # numpy array for dense Tensor, SparseTensorValue for SparseTensor\n (tensor_type, dtype) = fpl_feed\n if tensor_type == constants.PLACEHOLDER:\n return tf.compat.v1.placeholder(dtype=dtype)\n return tf.compat.v1.sparse_placeholder(dtype=dtype)\n\n def _create_infeed_ops(self):\n \"\"\"Instantiates the infeed ops to read in FPLs.\n\n This method generates the input placeholder ops given an example\n FPL. The ordering of the infeed ops should match the ordering of the\n feed list. In our case, we traverse the FPLs in the same manner:\n Features->Predictions->Labels.\n\n Returns:\n features_dict: The dictionary key to feature tensors as generated\n by our placeholder infeed.\n predictions_list_or_dict: The dictionary key to predictions tensors or\n list as generated by our placeholder infeed. Note that in the case\n the prediction key is \"__predictions\", this is special cased to a list.\n labels_list_or_dict: The dictionary key to labels tensors or\n list as generated by our placeholder infeed. Note that in the case\n the labels key is \"__labels\", this is special cased to a list.\n feed_list: The overall list of combined input tensor feeds.\n \"\"\"\n\n # Create a feedlist based on the following order:\n # Features, Predictions, Labels\n # Within each, use the sorted ordering of the keys. Note that\n # this needs to match the ordering in the function\n # _create_feed_for_features_predictions_labels_list\n feed_list = []\n feed_list_keys = []\n\n for which_map, key, value in self._iterate_fpl_maps_in_canonical_order():\n placeholder = self._create_placeholder(value)\n getattr(self, '_' + which_map + '_map')[key] = {\n encoding.NODE_SUFFIX: placeholder\n }\n feed_list.append(placeholder)\n feed_list_keys.append((which_map, key))\n\n self._perform_metrics_update_fn_feed_list = feed_list\n # We also keep the associated keys for better error messages.\n self._perform_metrics_update_fn_feed_list_keys = feed_list_keys\n\n def _create_feed_for_features_predictions_labels_list(\n self,\n features_predictions_labels_list: List[types.FeaturesPredictionsLabels]\n ) -> List[types.TensorValue]:\n \"\"\"Create feed list for a list of FeaturesPredictionsLabels.\"\"\"\n\n # Feed in the tensors in the following order:\n # Features -> Predictions -> Labels and using the standard key ordering\n # within each bucket. This should match the placeholder definitions when\n # generating the graph.\n # Note that we need to merge all examples into one Tensor before feeding.\n tensor_feed = []\n\n for which_map, key, _ in self._iterate_fpl_maps_in_canonical_order():\n tensor_feed.append(\n util.merge_tensor_values([\n getattr(fpl, which_map)[key][encoding.NODE_SUFFIX]\n for fpl in features_predictions_labels_list # pytype: disable=wrong-arg-types\n ]))\n\n return tensor_feed\n","sub_path":"tensorflow_model_analysis/model_agnostic_eval/model_agnostic_evaluate_graph.py","file_name":"model_agnostic_evaluate_graph.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"174038577","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^login/$', views.ChatLoginView.as_view(), name='login_view'),\n url(r'^logout/$', views.ChatLogoutView.as_view(), name='logout'),\n url(r'^signup/$', views.SignUpView.as_view(), name='signup_view'),\n url(r'^info/$', views.UserInfoView.as_view(), name='user_info'),\n]\n","sub_path":"authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"154754204","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# authors: Dat Chu \n# Dominik Mayer \n# John Tyree\n# Optional Dependency\n# - aplay to play a sound of your choice\n\nimport argparse\nimport os\nimport subprocess\nimport sys\nimport time\n\nfrom math import floor\n\n# ———————————————————————————— CONFIGURATIONS ————————————————————————————\n\n# Files and Folders\npymodoro_directory = os.path.expanduser(os.path.dirname(__file__))\nsession_file = os.path.expanduser('~/.config/pymodoro/pomodoro_session')\nstart_script = os.path.expanduser('~/.local/bin/focus_time_start.sh')\nstop_script = os.path.expanduser('~/.local/bin/focus_time_stop.sh')\n\n# Times\nsession_duration_in_seconds = 25 * 60 + 1\nbreak_duration_in_seconds = 5 * 60\nupdate_interval_in_seconds = 1\n\n# Progress Bar\ntotal_number_of_marks = 10\nsession_full_mark_character = '#'\nbreak_full_mark_character = '|'\nempty_mark_character = '·'\nleft_to_right = False\n\n# Prefixes\nbreak_prefix = 'B'\nbreak_suffix = ''\npomodoro_prefix = 'P'\npomodoro_suffix = ''\n\n# Sound\nenable_sound = True\nenable_tick_sound = False\nsession_sound_file_config = 'dings.ogg'\nbreak_sound_file_config = 'rimshot.wav'\ntick_sound_file_config = 'klack.wav'\n\n# —————————————————————————— END CONFIGURATIONS ———————————————————————————\n\n# constant inferred from configurations\nsession_sound_file = os.path.join(pymodoro_directory,\n session_sound_file_config)\nbreak_sound_file = os.path.join(pymodoro_directory,\n break_sound_file_config)\ntick_sound_file = os.path.join(pymodoro_directory,\n tick_sound_file_config)\n\n# variables\nlast_start_time = 0\n\n\ndef set_configuration_from_arguments(args):\n global session_duration_in_seconds\n global break_duration_in_seconds\n global update_interval_in_seconds\n global total_number_of_marks\n global session_full_mark_character\n global break_full_mark_character\n global empty_mark_character\n global session_file\n global session_sound_file\n global break_sound_file\n global tick_sound_file\n global enable_sound\n global enable_tick_sound\n global left_to_right\n global break_prefix\n global break_suffix\n global pomodoro_prefix\n global pomodoro_suffix\n\n if args.session_duration is not None:\n if args.durations_in_seconds:\n session_duration_in_seconds = args.session_duration\n else:\n session_duration_in_seconds = args.session_duration * 60\n if args.break_duration is not None:\n if args.durations_in_seconds:\n break_duration_in_seconds = args.break_duration\n else:\n break_duration_in_seconds = args.break_duration * 60\n if args.update_interval_in_seconds is not None:\n update_interval_in_seconds = args.update_interval_in_seconds\n if args.total_number_of_marks is not None:\n total_number_of_marks = args.total_number_of_marks\n if args.session_full_mark_character is not None:\n session_full_mark_character = args.session_full_mark_character\n if args.break_full_mark_character is not None:\n break_full_mark_character = args.break_full_mark_character\n if args.empty_mark_character is not None:\n empty_mark_character = args.empty_mark_character\n if args.session_file is not None:\n session_file = args.session_file\n if args.session_sound_file is not None:\n session_sound_file = args.session_sound_file\n if args.break_sound_file is not None:\n break_sound_file = args.break_sound_file\n if args.tick_sound_file:\n tick_sound_file = args.tick_sound_file\n if args.silent: # Always boolean\n enable_sound = False\n if args.tick:\n enable_tick_sound = True\n if args.left_to_right:\n left_to_right = True\n if args.no_break:\n break_duration_in_seconds = 0\n if args.break_prefix:\n break_prefix = args.break_prefix\n if args.break_suffix:\n break_suffix = args.break_suffix\n if args.pomodoro_prefix:\n pomodoro_prefix = args.pomodoro_prefix\n if args.pomodoro_suffix:\n pomodoro_suffix = args.pomodoro_suffix\n\n\ndef get_seconds_left():\n if os.path.exists(session_file):\n global last_start_time\n start_time = os.path.getmtime(session_file)\n if last_start_time != start_time:\n last_start_time = start_time\n setup_new_timer()\n return floor(session_duration_in_seconds - time.time() + start_time)\n else:\n return\n\n\ndef setup_new_timer():\n options = read_session_file()\n if len(options) > 0:\n set_session_duration(options[0])\n if len(options) > 1:\n set_break_duration(options[1])\n try:\n subprocess.call([start_script])\n except OSError as e:\n print(\"Unable to run start script {}\".format(e))\n\n\ndef read_session_file():\n f = open(session_file)\n content = f.readline()\n f.close()\n return content.rsplit()\n\n\ndef set_session_duration(session_duration_as_string):\n global session_duration_in_seconds\n session_duration_as_integer = convert_string_to_int(\n session_duration_as_string)\n if session_duration_as_integer != -1:\n session_duration_in_seconds = session_duration_as_integer\n\n\ndef convert_string_to_int(string):\n if not string.isdigit():\n #print(\"Session File may only contain digits!\")\n return -1\n else:\n return int(string)\n\n\ndef set_break_duration(break_duration_as_string):\n global break_duration_in_seconds\n break_duration_as_integer = convert_string_to_int(break_duration_as_string)\n if break_duration_as_integer != -1:\n break_duration_in_seconds = break_duration_as_integer * 60\n\n\ndef print_session_output(seconds_left):\n print_output(pomodoro_prefix,\n session_duration_in_seconds,\n seconds_left,\n session_full_mark_character,\n pomodoro_suffix)\n\n\ndef print_break_output(seconds_left):\n break_seconds_left = get_break_seconds_left(seconds_left)\n print_output(break_prefix,\n break_duration_in_seconds,\n break_seconds_left,\n break_full_mark_character,\n break_suffix)\n\n\ndef get_break_seconds_left(seconds):\n return break_duration_in_seconds + seconds\n\n\ndef print_output(description, duration_in_seconds, seconds,\n full_mark_character, suffix):\n minutes = get_minutes(seconds)\n output_seconds = get_output_seconds(seconds)\n progress_bar = print_progress_bar(\n duration_in_seconds, seconds, full_mark_character)\n output = description + \"{} {:02d}:{:02d}\".format(\n progress_bar, minutes, output_seconds)\n sys.stdout.write(wrap(output)+\"\\n\")\n\n\ndef wrap(string, color=None):\n if color is not None:\n return \"%s\" % (color, string)\n else:\n return string\n\n\ndef get_minutes(seconds):\n return int(seconds / 60)\n\n\ndef get_output_seconds(seconds):\n minutes = get_minutes(seconds)\n return int(seconds - minutes * 60)\n\n\ndef print_progress_bar(duration_in_seconds, seconds, full_mark_character):\n if total_number_of_marks != 0:\n seconds_per_mark = (duration_in_seconds / total_number_of_marks)\n number_of_full_marks = int(round(seconds / seconds_per_mark))\n # Reverse the display order\n if left_to_right:\n number_of_full_marks = total_number_of_marks - number_of_full_marks\n full_marks = print_full_marks(number_of_full_marks,\n full_mark_character)\n empty_marks = print_empty_marks(\n total_number_of_marks - number_of_full_marks)\n output = \" \" + full_marks + empty_marks\n else:\n output = \"\"\n return output\n\n\ndef print_full_marks(number_of_full_marks, full_mark_character):\n return full_mark_character * number_of_full_marks\n\n\ndef print_empty_marks(number_of_empty_marks):\n return empty_mark_character * number_of_empty_marks\n\n\ndef print_break_output_hours(seconds):\n seconds = -seconds\n minutes = get_minutes(seconds)\n output_minutes = get_output_minutes(seconds)\n hours = get_hours(seconds)\n output_seconds = get_output_seconds(seconds)\n if break_duration_in_seconds < seconds:\n color = \"red\"\n else:\n color = None\n if minutes < 60:\n output = \"B %02d:%02d min\" % (minutes, output_seconds)\n elif hours < 24:\n output = \"B %02d:%02d h\" % (hours, output_minutes)\n else:\n days = int(hours/24)\n output_hours = hours - days * 24\n output = \"B %02d d %02d h\" % (days, output_hours)\n sys.stdout.write(wrap(output, color)+\"\\n\")\n\n\ndef get_hours(seconds):\n return int(seconds / 3600)\n\n\ndef get_output_minutes(seconds):\n hours = get_hours(seconds)\n minutes = get_minutes(seconds)\n return int(minutes - hours * 60)\n\n\ndef play_sound(sound_file):\n if enable_sound and sound_file:\n try:\n subprocess.Popen(['play', '-q', sound_file])\n except OSError:\n try:\n subprocess.Popen(['mplayer', sound_file])\n except OSError:\n notify([\"Error'd playing sound\"])\n\n\ndef notify_end_of_session():\n notify([\"-i\", \"face-tired\", \"Worked enough.\", \"Time for a break!\"],\n audio=session_sound_file,\n script=stop_script)\n\n\ndef notify_end_of_break():\n notify([\"-i\", \"face-glasses\", \"Break is over.\", \"Back to work!\"],\n audio=break_sound_file,\n script=start_script)\n\n\ndef notify(data, audio=None, script=None):\n strings = list(data)\n cmd = ['notify-send'] + strings\n try:\n subprocess.Popen(cmd)\n play_sound(audio)\n if script is not None:\n subprocess.call([script])\n except OSError as e:\n print(\"Unable to notify {}\".format(e))\n\n\ndef main():\n # Parse command line arguments\n global session_file\n global notify_after_session\n global notify_after_break\n global tick_sound_file\n global enable_tick_sound\n global pomodoro_prefix\n global pomodoro_suffix\n\n parser = argparse.ArgumentParser(\n description='Create a textual Pomodoro display.')\n\n parser.add_argument(\n '-s', '--seconds', action='store_true',\n help='Changes format of input times from minutes to seconds.',\n dest='durations_in_seconds')\n parser.add_argument(\n '-d', '--session', action='store', nargs='?', type=int,\n help='Pomodoro duration in minutes (default: 25).',\n metavar='POMODORO DURATION', dest=\"session_duration\")\n parser.add_argument(\n 'break_duration', action='store', nargs='?', type=int,\n help='Break duration in minutes (default: 5).',\n metavar='BREAK DURATION')\n parser.add_argument(\n '-f', '--file', action='store',\n help='Pomodoro session file (default: ~/.config/pymodoro/pomodoro_session).',\n metavar='PATH', dest='session_file')\n parser.add_argument(\n '-n', '--no-break', action='store_true',\n help='No break sound.', dest='no_break')\n parser.add_argument(\n '-i', '--interval', action='store', type=int,\n help='Update interval in seconds (default: 1).',\n metavar='DURATION', dest='update_interval_in_seconds')\n parser.add_argument(\n '-l', '--length', action='store', type=int,\n help='Bar length in characters (default: 10).',\n metavar='INT', dest='total_number_of_marks')\n\n parser.add_argument(\n '-p', '--pomodoro', action='store',\n help='Pomodoro full mark characters (default: #).',\n metavar='CHARACTER', dest='session_full_mark_character')\n parser.add_argument(\n '-b', '--break', action='store',\n help='Break full mark characters (default: |).',\n metavar='CHARACTER', dest='break_full_mark_character')\n parser.add_argument(\n '-e', '--empty', action='store',\n help='Empty mark characters (default: ·).',\n metavar='CHARACTER', dest='empty_mark_character')\n\n parser.add_argument(\n '-sp', '--pomodoro-sound', action='store',\n help='Pomodoro end sound file (default: nokiaring.wav).',\n metavar='PATH', dest='session_sound_file')\n parser.add_argument(\n '-sb', '--break-sound', action='store',\n help='Break end sound file (default: rimshot.wav).',\n metavar='PATH', dest='break_sound_file')\n parser.add_argument(\n '-st', '--tick-sound', action='store',\n help='Ticking sound file (default: klack.wav).',\n metavar='PATH', dest='tick_sound_file')\n parser.add_argument(\n '-si', '--silent', action='store_true',\n help='Play no end sounds', dest='silent')\n parser.add_argument(\n '-t', '--tick', action='store_true',\n help='Play tick sound at every interval', dest='tick')\n parser.add_argument(\n '-ltr', '--left-to-right', action='store_true',\n help='Display markers from left to right'\n ' (incrementing marker instead of decrementing)',\n dest='left_to_right')\n parser.add_argument(\n '-bp', '--break-prefix', action='store',\n help='String to display before, when we are in a break. '\n ' Default to \"B\". Can be used to format display for dzen.',\n metavar='BREAK PREFIX', dest='break_prefix')\n parser.add_argument(\n '-bs', '--break-suffix', action='store',\n help='String to display after, when we are in a break.'\n ' Default to \"\". Can be used to format display for dzen.',\n metavar='BREAK SUFFIX', dest='break_suffix')\n parser.add_argument(\n '-pp', '--pomodoro-prefix', action='store',\n help='String to display before, when we are in a pomodoro.'\n ' Default to \"B\". Can be used to format display for dzen.',\n metavar='POMODORO PREFIX', dest='pomodoro_prefix')\n parser.add_argument(\n '-ps', '--pomodoro-suffix', action='store',\n help='String to display after, when we are in a pomodoro.'\n ' Default to \"\". Can be used to format display for dzen.',\n metavar='POMODORO SUFFIX', dest='pomodoro_suffix')\n\n args = parser.parse_args()\n set_configuration_from_arguments(args)\n session_file = os.path.expanduser(session_file)\n\n# sanity check\n if not os.path.exists(session_sound_file):\n print(\"Error: Cannot find sound file %s\" % session_sound_file)\n if not os.path.exists(break_sound_file):\n print(\"Error: Cannot find sound file %s\" % break_sound_file)\n if not os.path.exists(tick_sound_file):\n print(\"Error: Cannot find sound file %s\" % tick_sound_file)\n\n# Repeat printing the status of our session\n seconds_left = get_seconds_left()\n notify_after_session = True\n notify_after_break = break_duration_in_seconds != 0\n while True:\n if seconds_left is None:\n # No session is active\n sys.stdout.write(\"%s —%s\\n\" % (pomodoro_prefix, pomodoro_suffix))\n elif 0 < seconds_left:\n # We're counting down to the end of work session\n print_session_output(seconds_left)\n notify_after_session = True\n if enable_tick_sound:\n play_sound(tick_sound_file)\n elif -break_duration_in_seconds <= seconds_left <= 0:\n # We're counting down to the end of break\n if notify_after_session:\n notify_end_of_session()\n notify_after_session = False\n print_break_output(seconds_left)\n notify_after_break = break_duration_in_seconds != 0\n else:\n if -seconds_left <= break_duration_in_seconds:\n print_break_output(seconds_left)\n else:\n # Break has ended\n print_break_output_hours(seconds_left)\n if notify_after_break:\n notify_end_of_break()\n notify_after_break = False\n\n sys.stdout.flush()\n\n time.sleep(update_interval_in_seconds)\n\n seconds_left = get_seconds_left()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pymodoro.py","file_name":"pymodoro.py","file_ext":"py","file_size_in_byte":16299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"239697488","text":"import math\r\n\r\ndef main():\r\n i = 0\r\n while True:\r\n try:\r\n t = input()\r\n if i != 0: # Skip first line\r\n print(\"Case #{}:\".format(i))\r\n coin(t)\r\n except EOFError:\r\n break\r\n i += 1\r\n\r\n\r\ndef parse_coin(s):\r\n return (int(x) for x in s.rstrip().split(\" \"))\r\n\r\n\r\ndef coin(c):\r\n (n, j) = parse_coin(c)\r\n coin_gen = generate_coin_candidates(n)\r\n\r\n good_coins = []\r\n\r\n while len(good_coins) < j:\r\n candidate = next(coin_gen)\r\n divisors = get_divisors(candidate)\r\n if divisors is not None:\r\n good_coins.append((candidate, divisors))\r\n\r\n for cn, divs in good_coins:\r\n print(\"{} {}\".format(cn, \" \".join([str(x) for x in divs])))\r\n\r\n\r\ndef generate_coin_candidates(n):\r\n num = 2**(n-1) + 1\r\n while num < 2**n:\r\n yield bin(num)[2:]\r\n num += 2\r\n\r\n\r\ndef get_divisors(c):\r\n divisors = []\r\n for base in range(2, 11):\r\n num = interpret_in_base(c, base)\r\n d = first_divisor(num)\r\n if d is not None:\r\n divisors.append(d)\r\n else:\r\n return None\r\n\r\n return divisors\r\n\r\n\r\ndef first_divisor(num):\r\n for i in range(2, int(math.sqrt(num)) + 1):\r\n if num % i == 0:\r\n return i\r\n\r\n return None\r\n\r\n\r\ndef interpret_in_base(c, base):\r\n # print(\"interpret_in_base: c{}, base{}\".format(c, base))\r\n total = 0\r\n digits = list(c)\r\n for i, x in enumerate(reversed(digits)):\r\n # print(\"i{}, x{}\".format(i, x))\r\n if int(x) == 1:\r\n total += base**i\r\n return total\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"codes/CodeJamCrawler/16_0_3/leesunny/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"280149604","text":"import numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.optimizers import SGD\nfrom keras.utils import to_categorical\nimport pprint, pickle\nimport matplotlib.pyplot as plt\nfrom get_parameters import *\nfrom keras import regularizers\n\n#################\n##Training Data##\n#################\nall_matrices=[]\ncos_matrix=[]\nsin_matrix=[]\nvortices=[] # list of winding numbers of central element\nfor r in range(10000):\n all_matrices.append(np.random.rand(3,3))\n vortices.append((get_vorticity_configuration(all_matrices[-1]))[1,1])\n cos_matrix.append(np.cos(2*np.pi*all_matrices[-1].reshape(9,)))\n sin_matrix.append(np.sin(2*np.pi*all_matrices[-1].reshape(9,)))\nall_matrices=np.array(all_matrices)\nvortices=np.array(vortices)\ncos_matrix=np.array(cos_matrix)\nsin_matrix=np.array(sin_matrix)\n\ntrain_data=np.concatenate((cos_matrix,sin_matrix),axis=1)\ntrain_ground_truth=train_data+0\n\n#############\n##Test Data##\n#############\nall_test_matrices=[]\ncos_test_matrix=[]\nsin_test_matrix=[]\nvortices_test=[] # list of winding numbers of central element\nfor r in range(1000):\n all_test_matrices.append(np.random.rand(3,3))\n vortices_test.append((get_vorticity_configuration(all_test_matrices[-1]))[1,1])\n cos_test_matrix.append(np.cos(2*np.pi*all_test_matrices[-1].reshape(9,)))\n sin_test_matrix.append(np.sin(2*np.pi*all_test_matrices[-1].reshape(9,)))\nall_test_matrices=np.array(all_test_matrices)\nvortices_test=np.array(vortices_test)\ncos_test_matrix=np.array(cos_test_matrix)\nsin_test_matrix=np.array(sin_test_matrix)\n\ntest_data=np.concatenate((cos_test_matrix,sin_test_matrix),axis=1)\ntest_ground_truth=test_data+0\n\n###############\n##Keras model##\n###############\nepochs=50\nmodel = Sequential()\nmodel.add(Dense(30,activation='sigmoid',input_shape=(18,)))\nmodel.add(Dense(20,activation='sigmoid'))\nmodel.add(Dense(9,activation='sigmoid',activity_regularizer=regularizers.l1(1))) # bottleneck layer\nmodel.add(Dense(20,activation='sigmoid'))\nmodel.add(Dense(30,activation='sigmoid'))\nmodel.add(Dense(18,activation='linear'))\n\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\nmodel.compile(loss='mean_squared_error', optimizer=sgd,metrics=['mean_squared_error'])\nmodel_train=model.fit(train_data, train_ground_truth, batch_size=32, epochs=epochs,validation_data=(test_data, test_ground_truth))\n\n##############################################\n##Evaluating the model (based on loss trend)##\n##############################################\nloss = model_train.history['loss']\nval_loss=model_train.history['val_loss']\nepochs = range(epochs)\nplt.figure()\nplt.plot(epochs[1:], loss[1:], 'bo', label='Training loss')\nplt.plot(epochs[1:], val_loss[1:], 'b', label='Validation loss')\nplt.title('Training and validation loss')\nplt.legend()\nplt.show()\n\n##############################################################################\n##Evaluating the model (across different values of regularization parameter)##\n##############################################################################\nscore = model.evaluate(test_data, test_ground_truth, batch_size=32)\nprint(score)\n\n\t\n\n","sub_path":"Aug11/sparse_autoencoder.py","file_name":"sparse_autoencoder.py","file_ext":"py","file_size_in_byte":3230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"456791492","text":"import numpy as np\nimport math\n\ndef order_3(d333,R):\n\t#rotates a 3x3x3 matrix according to some rotation matrix R\n\tarrSize = d333.shape\n\tpostRot = np.zeros((arrSize[0],arrSize[1],3,3,3))\n\n\tfor grain in range(arrSize[0]):\n\t\tfor direc in range(arrSize[1]):\n\t\t\tfor i in range(3):\n\t\t\t\tfor j in range(3):\n\t\t\t\t\tfor k in range(3):\n\t\t\t\t\t\tfor m in range(3):\n\t\t\t\t\t\t\tfor n in range(3):\n\t\t\t\t\t\t\t\tfor o in range(3):\n\t\t\t\t\t\t\t\t\ttoPut = postRot[grain,direc,i,j,k] + R[grain,direc,i,m] * R[grain,direc,j,n] * R[grain,direc,k,o] * d333[grain,direc,m,n,o]\n\t\t\t\t\t\t\t\t\tpostRot[grain,direc,i,j,k] = toPut\n\treturn postRot\n\ndef order_4(C3333,R):\n\t#rotates a 3x3x3x3 matrix according to some rotation matrix R\n\tarrSize = C3333.shape\n\tpostRot = np.zeros((arrSize[0],arrSize[1],3,3,3,3))\n\n\tfor grain in range(arrSize[0]):\n\t\tfor direc in range(arrSize[1]):\n\t\t\tfor i in range(3):\n\t\t\t\tfor j in range(3):\n\t\t\t\t\tfor k in range(3):\n\t\t\t\t\t\tfor l in range(3):\n\t\t\t\t\t\t\tfor m in range(3):\n\t\t\t\t\t\t\t\tfor n in range(3):\n\t\t\t\t\t\t\t\t\tfor o in range(3):\n\t\t\t\t\t\t\t\t\t\tfor p in range(3):\n\t\t\t\t\t\t\t\t\t\t\ttoPut = postRot[grain,direc,i,j,k,l] + R[grain,direc,i,m] * R[grain,direc,j,n] * R[grain,direc,k,o] * R[grain,direc,l,p] * C3333[grain,direc,m,n,o,p]\n\t\t\t\t\t\t\t\t\t\t\tpostRot[grain,direc,i,j,k,l] = toPut\n\treturn postRot\n\ndef matrot(angles):\n\t#constructs a 3x3 orientation matrix from a 3x1 (xyz) angle vector\n c1=math.cos(angles[0]);\n s1=math.sin(angles[0]);\n c2=math.cos(angles[1]);\n s2=math.sin(angles[1]);\n c3=math.cos(angles[2]);\n s3=math.sin(angles[2]);\n\n A_rot = np.zeros((3,3))\n A_rot[0,0] = c1*c3 - s1*c2*s3\n A_rot[0,1] = -c1*s3 - c2*c3*s1\n A_rot[0,2] = s1*s2\n A_rot[1,0] = c3*s1 + c1*c2*s3\n A_rot[1,1] = c1*c2*c3 - s1*s3\n A_rot[1,2] = -c1*s2\n A_rot[2,0] = s2*s3\n A_rot[2,1] = c3*s2\n A_rot[2,2] = c2\n \n return A_rot\n\n","sub_path":"python/pySlurm/distributed/util_functions/rotations.py","file_name":"rotations.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544617539","text":"#!/usr/bin/env python\n\"\"\"REL_DB implementation of hunts.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom grr_response_core.lib import rdfvalue\nfrom grr_response_core.lib import registry\nfrom grr_response_server import access_control\nfrom grr_response_server import data_store\nfrom grr_response_server import db\nfrom grr_response_server import flow\nfrom grr_response_server import foreman_rules\nfrom grr_response_server import notification\nfrom grr_response_server.aff4_objects import users as aff4_users\nfrom grr_response_server.rdfvalues import flow_objects as rdf_flow_objects\nfrom grr_response_server.rdfvalues import hunt_objects as rdf_hunt_objects\nfrom grr_response_server.rdfvalues import objects as rdf_objects\n\nMIN_CLIENTS_FOR_AVERAGE_THRESHOLDS = 1000\n\n\nclass Error(Exception):\n pass\n\n\nclass UnknownHuntTypeError(Error):\n pass\n\n\nclass OnlyPausedHuntCanBeModifiedError(Error):\n\n def __init__(self, hunt_obj):\n super(OnlyPausedHuntCanBeModifiedError,\n self).__init__(\"Hunt %s can't be modified since it's in state %s.\" %\n (hunt_obj.hunt_id, hunt_obj.hunt_state))\n\n\nclass OnlyPausedHuntCanBeStartedError(Error):\n\n def __init__(self, hunt_obj):\n super(OnlyPausedHuntCanBeStartedError,\n self).__init__(\"Hunt %s can't be started since it's in state %s.\" %\n (hunt_obj.hunt_id, hunt_obj.hunt_state))\n\n\nclass OnlyStartedHuntCanBePausedError(Error):\n\n def __init__(self, hunt_obj):\n super(OnlyStartedHuntCanBePausedError,\n self).__init__(\"Hunt %s can't be paused since it's in state %s.\" %\n (hunt_obj.hunt_id, hunt_obj.hunt_state))\n\n\nclass OnlyStartedOrPausedHuntCanBeStoppedError(Error):\n\n def __init__(self, hunt_obj):\n super(OnlyStartedOrPausedHuntCanBeStoppedError,\n self).__init__(\"Hunt %s can't be stopped since it's in state %s.\" %\n (hunt_obj.hunt_id, hunt_obj.hunt_state))\n\n\ndef IsLegacyHunt(hunt_id):\n return hunt_id.startswith(\"H:\")\n\n\ndef StopHuntIfAverageLimitsExceeded(hunt_obj):\n \"\"\"Stops the hunt if average limites are exceeded.\"\"\"\n\n # Do nothing if the hunt is already stopped.\n if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntState.STOPPED:\n return hunt_obj\n\n total_clients = (\n hunt_obj.num_successful_clients + hunt_obj.num_failed_clients +\n hunt_obj.num_crashed_clients)\n\n if total_clients < MIN_CLIENTS_FOR_AVERAGE_THRESHOLDS:\n return hunt_obj\n\n # Check average per-client results count limit.\n if hunt_obj.avg_results_per_client_limit:\n avg_results_per_client = (hunt_obj.num_results / total_clients)\n if avg_results_per_client > hunt_obj.avg_results_per_client_limit:\n # Stop the hunt since we get too many results per client.\n reason = (\"Hunt %s reached the average results per client \"\n \"limit of %d and was stopped.\") % (\n hunt_obj.hunt_id, hunt_obj.avg_results_per_client_limit)\n return StopHunt(hunt_obj.hunt_id, reason=reason)\n\n # Check average per-client CPU seconds limit.\n if hunt_obj.avg_cpu_seconds_per_client_limit:\n avg_cpu_seconds_per_client = (\n (hunt_obj.client_resources_stats.user_cpu_stats.sum +\n hunt_obj.client_resources_stats.system_cpu_stats.sum) / total_clients)\n if avg_cpu_seconds_per_client > hunt_obj.avg_cpu_seconds_per_client_limit:\n # Stop the hunt since we use too many CPUs per client.\n reason = (\"Hunt %s reached the average CPU seconds per client \"\n \"limit of %d and was stopped.\") % (\n hunt_obj.hunt_id, hunt_obj.avg_cpu_seconds_per_client_limit)\n return StopHunt(hunt_obj.hunt_id, reason=reason)\n\n # Check average per-client network bytes limit.\n if hunt_obj.avg_network_bytes_per_client_limit:\n avg_network_bytes_per_client = (\n hunt_obj.client_resources_stats.network_bytes_sent_stats.sum /\n total_clients)\n if (avg_network_bytes_per_client >\n hunt_obj.avg_network_bytes_per_client_limit):\n # Stop the hunt since we use too many network bytes sent\n # per client.\n reason = (\"Hunt %s reached the average network bytes per client \"\n \"limit of %d and was stopped.\") % (\n hunt_obj.hunt_id,\n hunt_obj.avg_network_bytes_per_client_limit)\n return StopHunt(hunt_obj.hunt_id, reason=reason)\n\n return hunt_obj\n\n\ndef CompleteHuntIfExpirationTimeReached(hunt_obj):\n \"\"\"Marks the hunt as complete if it's past its expiry time.\"\"\"\n\n if (hunt_obj.hunt_state not in [\n rdf_hunt_objects.Hunt.HuntState.STOPPED,\n rdf_hunt_objects.Hunt.HuntState.COMPLETED\n ] and hunt_obj.expiry_time < rdfvalue.RDFDatetime.Now()):\n StopHunt(hunt_obj.hunt_id, reason=\"Hunt completed.\")\n\n def UpdateFn(h):\n h.hunt_state = h.HuntState.COMPLETED\n return h\n\n return data_store.REL_DB.UpdateHuntObject(hunt_obj.hunt_id, UpdateFn)\n\n return hunt_obj\n\n\ndef CreateAndStartHunt(flow_name, flow_args, creator, **kwargs):\n \"\"\"Creates and starts a new hunt.\"\"\"\n\n hunt_args = rdf_hunt_objects.HuntArguments(\n hunt_type=rdf_hunt_objects.HuntArguments.HuntType.STANDARD,\n standard=rdf_hunt_objects.HuntArgumentsStandard(\n flow_name=flow_name, flow_args=flow_args))\n\n hunt_obj = rdf_hunt_objects.Hunt(creator=creator, args=hunt_args, **kwargs)\n data_store.REL_DB.WriteHuntObject(hunt_obj)\n\n StartHunt(hunt_obj.hunt_id)\n\n\ndef StartHunt(hunt_id):\n \"\"\"Starts a hunt with a given id.\"\"\"\n\n hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)\n output_plugins_states = None\n if hunt_obj.output_plugins and not hunt_obj.output_plugins_states:\n output_plugins_states = flow.GetOutputPluginStates(\n hunt_obj.output_plugins,\n source=\"hunts/%s\" % hunt_obj.hunt_id,\n token=access_control.ACLToken(username=hunt_obj.creator))\n for ops in output_plugins_states:\n ops.plugin_state[\"success_count\"] = 0\n ops.plugin_state[\"error_count\"] = 0\n\n def UpdateFn(h):\n \"\"\"Updates given hunt in a transaction.\"\"\"\n\n if h.hunt_state != h.HuntState.PAUSED:\n raise OnlyPausedHuntCanBeStartedError(h)\n\n if (output_plugins_states is not None and\n not hunt_obj.output_plugins_states):\n h.output_plugins_states = output_plugins_states\n h.hunt_state = h.HuntState.STARTED\n h.hunt_state_comment = None\n h.next_client_due = rdfvalue.RDFDatetime.Now()\n return h\n\n hunt_obj = data_store.REL_DB.UpdateHuntObject(hunt_id, UpdateFn)\n if hunt_obj.hunt_state != hunt_obj.HuntState.STARTED:\n return\n\n foreman_condition = foreman_rules.ForemanCondition(\n creation_time=rdfvalue.RDFDatetime.Now(),\n expiration_time=hunt_obj.expiry_time,\n description=\"Hunt %s %s\" % (hunt_obj.hunt_id, hunt_obj.args.hunt_type),\n client_rule_set=hunt_obj.client_rule_set,\n hunt_id=hunt_obj.hunt_id)\n\n # Make sure the rule makes sense.\n foreman_condition.Validate()\n\n data_store.REL_DB.WriteForemanRule(foreman_condition)\n\n return hunt_obj\n\n\ndef PauseHunt(hunt_id, reason=None):\n \"\"\"Pauses a hunt with a given id.\"\"\"\n\n def UpdateFn(h):\n if h.hunt_state != h.HuntState.STARTED:\n raise OnlyStartedHuntCanBePausedError(h)\n\n h.hunt_state = h.HuntState.PAUSED\n if reason is not None:\n h.hunt_state_comment = reason\n else:\n h.hunt_state_comment = None\n return h\n\n hunt_obj = data_store.REL_DB.UpdateHuntObject(hunt_id, UpdateFn)\n if hunt_obj.hunt_state == hunt_obj.HuntState.PAUSED:\n data_store.REL_DB.RemoveForemanRule(hunt_id=hunt_obj.hunt_id)\n\n return hunt_obj\n\n\ndef StopHunt(hunt_id, reason=None):\n \"\"\"Stops a hunt with a given id.\"\"\"\n\n def UpdateFn(h):\n if h.hunt_state not in [h.HuntState.STARTED, h.HuntState.PAUSED]:\n raise OnlyStartedOrPausedHuntCanBeStoppedError(h)\n\n h.hunt_state = h.HuntState.STOPPED\n if reason is not None:\n h.hunt_state_comment = reason\n return h\n\n # If the hunt was not started or paused, the exception from UpdateFn is\n # guaranteed to be propagated by UpdateHuntObject implementation.\n hunt_obj = data_store.REL_DB.UpdateHuntObject(hunt_id, UpdateFn)\n data_store.REL_DB.RemoveForemanRule(hunt_id=hunt_obj.hunt_id)\n\n flows = data_store.REL_DB.ReadHuntFlows(hunt_obj.hunt_id, 0, db.MAX_COUNT)\n data_store.REL_DB.UpdateFlows(\n [(f.client_id, f.flow_id) for f in flows],\n pending_termination=rdf_flow_objects.PendingFlowTermination(\n reason=\"Parent hunt stopped.\"))\n\n if (reason is not None and\n hunt_obj.creator not in aff4_users.GRRUser.SYSTEM_USERS):\n notification.Notify(\n hunt_obj.creator, rdf_objects.UserNotification.Type.TYPE_HUNT_STOPPED,\n reason,\n rdf_objects.ObjectReference(\n reference_type=rdf_objects.ObjectReference.Type.HUNT,\n hunt=rdf_objects.HuntReference(hunt_id=hunt_obj.hunt_id)))\n\n return hunt_obj\n\n\ndef UpdateHunt(hunt_id, client_limit=None, client_rate=None, expiry_time=None):\n \"\"\"Updates a hunt (it must be paused to be updated).\"\"\"\n\n def UpdateFn(hunt_obj):\n \"\"\"Update callback used by UpdateHuntObject.\"\"\"\n\n if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED:\n raise OnlyPausedHuntCanBeModifiedError(hunt_obj)\n\n if client_limit is not None:\n hunt_obj.client_limit = client_limit\n\n if client_rate is not None:\n hunt_obj.client_rate = client_rate\n\n if expiry_time is not None:\n hunt_obj.expiry_time = expiry_time\n\n return hunt_obj\n\n return data_store.REL_DB.UpdateHuntObject(hunt_id, UpdateFn)\n\n\ndef StartHuntFlowOnClient(client_id, hunt_id):\n \"\"\"Starts a flow corresponding to a given hunt on a given client.\"\"\"\n\n hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)\n hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj)\n # There may be a little race between foreman rules being removed and\n # foreman scheduling a client on an (already) paused hunt. Making sure\n # we don't lose clients in such a race by accepting clients for paused\n # hunts.\n if not rdf_hunt_objects.IsHuntSuitableForFlowProcessing(hunt_obj.hunt_state):\n return\n\n if hunt_obj.args.hunt_type == hunt_obj.args.HuntType.STANDARD:\n hunt_args = hunt_obj.args.standard\n\n def UpdateFn(h):\n # h.num_clients > 0 check ensures that first client will be scheduled\n # immediately and not 60.0 / h.client_rate seconds after the hunt is\n # started.\n if h.client_rate > 0 and h.num_clients > 0:\n h.next_client_due = h.next_client_due + 60.0 / h.client_rate\n h.num_clients += 1\n return h\n\n hunt_obj = data_store.REL_DB.UpdateHuntObject(hunt_id, UpdateFn)\n start_at = hunt_obj.next_client_due if hunt_obj.client_rate > 0 else None\n\n flow_cls = registry.FlowRegistry.FlowClassByName(hunt_args.flow_name)\n flow_args = hunt_args.flow_args if hunt_args.HasField(\"flow_args\") else None\n flow.StartFlow(\n client_id=client_id,\n creator=hunt_obj.creator,\n cpu_limit=hunt_obj.per_client_cpu_limit,\n network_bytes_limit=hunt_obj.per_client_network_bytes_limit,\n flow_cls=flow_cls,\n flow_args=flow_args,\n start_at=start_at,\n parent_hunt_id=hunt_id)\n\n if hunt_obj.client_limit and hunt_obj.num_clients >= hunt_obj.client_limit:\n PauseHunt(hunt_obj.hunt_id)\n\n elif hunt_obj.args.hunt_type == hunt_obj.args.HuntType.VARIABLE:\n raise NotImplementedError()\n else:\n raise UnknownHuntTypeError(\"Can't determine hunt type when starting \"\n \"hunt %s on client %s.\" % (client_id, hunt_id))\n","sub_path":"grr/server/grr_response_server/hunt.py","file_name":"hunt.py","file_ext":"py","file_size_in_byte":11524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"130356118","text":"#scrapes images from r/CustomHearthstone\nimport requests, shutil, os\n\n# First check for internet connection.\nurl = r\"http://www.google.com/\"\ntry:\n g = requests.get(url,timeout=5)\nexcept requests.ConnectionError:\n print(\"No Internet!\")\n \nprint(\"@Mark's Image Scraper!\")\nos.chdir(r'C:\\Users\\asus x550l\\desktop')\nfolder = (r'.\\Custom Cards')\nif not os.path.exists(folder):\n os.makedirs(folder)\nos.chdir(r'.\\Custom Cards')\nmain_url = \"https://www.reddit.com/r/customhearthstone/.json\"\nr = requests.get(main_url,headers={'User-agent':'chikorita'})\nd = r.json()\nn = 0\nfor item in d['data']['children']:\n n += 1\n if 'preview' in item['data']:\n sub_url = item['data']['preview']['images'][0]['source']['url']\n img_r = requests.get(sub_url,stream=True)\n print(sub_url)\n if img_r.status_code == 200:\n with open(str(n)+\".jpg\",'wb') as img_f:\n shutil.copyfileobj(img_r.raw,img_f)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"565519350","text":"\"\"\"\r\n File:EM.py\r\n Name:孙新梦\r\n ID:18340149\r\n TASK:用EM算法对Iris数据集进行分类,\r\n 输出γ,μ,Σ,可视化输出分类\r\n\"\"\"\r\nimport math\r\nimport numpy as np\r\nfrom copy import deepcopy as cp\r\n\r\n\r\ndef readData():\r\n data = []\r\n lable = []\r\n with open('iris.data', 'r') as f:\r\n flag = 0\r\n for line in f.readlines():\r\n now_line = line.split(',')\r\n data.append(list(map(lambda x: float(x), now_line[:-1])))\r\n lable.append(line[-1])\r\n return data, lable\r\n\r\n\r\ndef gaussion(inputs, miu, sigma):\r\n D = len(miu)\r\n\r\n m = [inputs[i] - miu[i] for i in range(D)]\r\n minus = np.array(m)\r\n\r\n return 1 / (math.sqrt(math.pow(2 * math.pi, D) * np.linalg.det(sigma)) ) * math.exp(\r\n -0.5 * (minus.reshape(1, D)).dot(np.linalg.inv(sigma)).dot(minus.reshape(D, 1)))\r\n\r\n\r\ndef get_init(data, K, dim):\r\n N = len(data)\r\n mask = np.random.permutation(N)[:K]\r\n miu = cp(data[mask])\r\n sigma = np.array([np.zeros((dim, dim)) for i in range(K)])\r\n\r\n for i in range(K):\r\n for j in range(dim):\r\n sigma[i, j, j] = np.random.rand()\r\n # sigma = np.array([np.identity(dim) for i in range(K)])\r\n\r\n pi = np.ones(K) / K\r\n return pi, miu, sigma\r\n\r\n\r\ndef EM(data, K, dim):\r\n # initialization\r\n pi, miu, sigma = get_init(data, K, dim)\r\n\r\n N = len(data)\r\n # N*K的一个矩阵——shape参数,行数表示哪一个样例,列数表示是哪一类的概率\r\n gamma = np.ndarray((N, K))\r\n\r\n # 10次迭代\r\n for epoch in range(10):\r\n print(\"\\n-----第 \", epoch, \" 次迭代-----\")\r\n print(\"μ = \", miu)\r\n print(\"Σ = \", sigma)\r\n print(\"Π = \", pi)\r\n\r\n # E step\r\n for n in range(N):\r\n fenmu = 0\r\n for k in range(K):\r\n val = pi[k] * gaussion(data[n], miu[k], sigma[k])\r\n gamma[n, k] = val\r\n fenmu += val\r\n gamma[n] /= fenmu\r\n\r\n # M step\r\n Nk = gamma.sum(0)\r\n pi = Nk / N\r\n for k in range(K):\r\n temp = np.zeros(miu[k].shape)\r\n for n in range(N):\r\n temp += gamma[n, k] * data[n]\r\n miu[k] = temp / Nk[k]\r\n\r\n temp = np.zeros(sigma[k].shape)\r\n for n in range(N):\r\n temp += gamma[n, k] * ((data[n] - miu[k]).reshape(data[n].size, 1)).dot(\r\n (data[n] - miu[k]).reshape(1, data[n].size))\r\n sigma[k] += temp / Nk[k]\r\n\r\n print(\"\\n\\n*****分类*****\")\r\n for n in range(N):\r\n the_class = np.argmax(gamma[n])\r\n print(\"第 \", n, \" 条,分类为:第 \", the_class, \" 类\")\r\n\r\n\r\n# name = ['']\r\nif __name__ == '__main__':\r\n K = 3\r\n data, lable = readData()\r\n data = np.array(data)\r\n # dimension = 4\r\n EM(data, K, 4)\r\n","sub_path":"作业/AI实验与项目/E12/EM.py","file_name":"EM.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"139157276","text":"import math\n\n\ndef round_half_up(n, decimals=0):\n multiplier = 10 ** decimals\n return math.floor(n * multiplier + 0.5) / multiplier\n\n\ncases = int(input())\n\nfor _ in range(cases):\n rate, balance, monthly = tuple(map(float, input().split(\" \")))\n\n balance = int(round_half_up(balance * 100))\n monthly = int(round_half_up(monthly * 100))\n\n multiplier = 1 + rate / 100\n months = 0\n while balance > 0 and months <= 1200:\n balance *= multiplier\n balance = round_half_up(balance)\n balance -= monthly\n balance = round_half_up(balance)\n months += 1\n if months == 1201:\n print(\"impossible\")\n else:\n print(months)\n","sub_path":"Kattis/credit-card-payment/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"235817893","text":"from openerp.osv import osv, fields\n\nclass supplier(osv.osv):\n _inherit = 'res.partner'\n \n _columns = {\n 'stock_feed_enabled': fields.boolean(\n 'Enable Stock Feed Integration',\n help=\"Use supplier quantity supplied via stock feed instead of normal backorder limit\"\n ),\n 'stock_feed_threshold': fields.integer(\n 'Stock Feed Threshold',\n help=\"Set the stock quantity of products to 0 when importing stock quantities through the supplier feed and the value given is less or equal to the treshold\"\n ),\n 'flag_skus_out_of_stock': fields.boolean(\n 'Clear stock if missing from supplier feed',\n help=\"Set products as out of stock if they are not included in the supplier integration feed\"\n )\n }\n","sub_path":"connector_bots_stock_integration/supplier_stock_integration.py","file_name":"supplier_stock_integration.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430927416","text":"import os\nimport warnings\n\n\ndef tsv_line(*args):\n return '\\t'.join(map(str, args)) + '\\n'\n\n\nclass InformationLogger(object):\n def __init__(self, log_folder, mode):\n # List of metrics names\n self.metrics = ['loss']\n self.metrics_classwise = []\n if mode == 'val' or mode == 'tst':\n self.metrics += ['iou']\n self.metrics_classwise += ['precision', 'recall', 'fscore']\n\n # Dicts of logs\n def open_log(metric_name, fmt_str=\"metric_{}_{}.log\"):\n filename = fmt_str.format(mode, metric_name)\n return open(os.path.join(log_folder, filename), \"a\", buffering=1)\n self.metric_values = {m: open_log(m) for m in self.metrics}\n self.class_scores = {m: open_log(m, fmt_str=\"metric_classwise_{}_{}.log\") for m in self.metrics_classwise}\n self.averaged_scores = {m: open_log(m, fmt_str=\"metric_{}_{}_averaged.log\") for m in self.metrics_classwise}\n\n def add_values(self, info, epoch, ignore: list = None):\n \"\"\"Add new information to the logs.\"\"\"\n\n ignore = [] if ignore is None else ignore\n\n for composite_name, value in info.items():\n tokens = composite_name.split('_')\n if len(tokens) == 1:\n # Ordinary metric (non-classwise); e.g. loss, iou, precision\n name = composite_name\n if name in ignore:\n continue\n elif name in self.metrics:\n self.metric_values[name].write(tsv_line(epoch, value.avg))\n elif name in self.metrics_classwise: # Metrics averaged over classes\n self.averaged_scores[name].write(tsv_line(epoch, value.avg))\n else:\n warnings.warn(f'Unknown metric {name}')\n elif len(tokens) == 2:\n # Classwise metric; e.g. precision_0, recall_1\n name, class_idx = tokens\n if name in ignore:\n continue\n elif name in self.metrics_classwise:\n self.class_scores[name].write(tsv_line(epoch, class_idx, value.avg))\n else:\n warnings.warn(f'Unknown metric {name}')\n\n\ndef save_logs_to_bucket(bucket, bucket_output_path, output_path, now, batch_metrics=None):\n if batch_metrics is not None:\n list_log_file = ['metric_val_fscore_averaged', 'metric_val_fscore', 'metric_val_iou',\n 'metric_val_precision_averaged', 'metric_val_precision', 'metric_val_recall_averaged',\n 'metric_val_recall']\n else:\n list_log_file = ['metric_trn_loss', 'metric_val_loss']\n for i in list_log_file:\n if bucket_output_path:\n log_file = os.path.join(output_path, f\"{i}.log\")\n bucket.upload_file(log_file, os.path.join(bucket_output_path, f\"Logs/{now}_{i}.log\"))\n else:\n log_file = os.path.join(output_path, f\"{i}.log\")\n bucket.upload_file(log_file, f\"Logs/{now}_{i}.log\")\n bucket.upload_file(\"output.txt\", os.path.join(bucket_output_path, f\"Logs/{now}_output.txt\"))\n","sub_path":"utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"631178855","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Newville/Codes/xraylarch/tests/test_symbol_callbacks.py\n# Compiled at: 2017-04-05 21:43:24\nfrom larch import Interpreter\nlinp = Interpreter()\n\ndef onVarChange(group=None, symbolname=None, value=None, **kws):\n print ('var changed ', group, symbolname, value, kws)\n\n\nlinp('x = 100.0')\nlinp.symtable.add_callback('x', onVarChange)\nlinp.symtable.set_symbol('x', 30)\nlinp.symtable.set_symbol('x', 'a string')\nlinp('x = arange(7)')","sub_path":"pycfiles/xraylarch-0.9.47.tar/test_symbol_callbacks.py","file_name":"test_symbol_callbacks.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"544546266","text":"import ups_pb2\nimport amz_ups_pb2\nimport psycopg2\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\nimport random\nimport time\nimport smtplib\nfrom send_recv_message import send_message, recv_message\nfrom fill_message import fill_deliveries, fill_pickups\nfrom fill_message import fill_created_shipments, fill_arrived, fill_load_confirm\nfrom fill_message import fill_query_results, fill_delivered\n\n\n# global mutex lock\nmutex = threading.Lock()\n# set simspeed from 150000 to 250000 for visualize capture\nsimspeed = 300000\npackage_limit = 1\ndb_host = \"vcm-3838.vm.duke.edu\"\ndb_port = \"6666\"\n\n\n# ----------------------------------------------------------------------------------\n\"\"\" 1. Amazon messages handlers \"\"\"\n# ----------------------------------------------------------------------------------\n\n\n# handle gopickups(whid, dst_x, dst_y, packageid) message from Amazon\ndef handle_gopickups(world_id, amazon_conn, world_conn, amazon_msg):\n print(\"handle Amazon's gopickups\")\n # first connect to the database shared with web app\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n command = ups_pb2.UCommands()\n command.simspeed = simspeed\n message = amz_ups_pb2.UAMessages()\n\n # 1. assign an available truck\n # TODO: may need to limit the max number of gopickups messages\n tracking_number = []\n i = 0\n # 1. generate shipments and tracking_number, response Amazon\n for gopickups in amazon_msg.gopickups:\n print(\"for gopickups in amazon_msg.gopickups\")\n while 1:\n random.seed()\n tracking_number.append(random.randint(100000000, 999999999))\n # first check if the generated tracking number has already been used\n print(\"1\")\n db_cur.execute(\"select count(*) from ups_frontend_tracking_number\"\n \" where worldid = '\" + str(world_id) +\n \"' and tracking_number = '\" +\n str(tracking_number[i]) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n # if tracking_number generated has not been used, use it\n if row[0] == 0:\n # update ups_frontend_tracking_number table\n print(\"2\")\n db_cur.execute(\"insert into ups_frontend_tracking_number \"\n \"(worldid, tracking_number) values ('\" +\n str(world_id) + \"', '\" +\n str(tracking_number[i]) + \"')\")\n\n break\n # if tracking_number generated has been used, try again\n else:\n pass\n # get username, may need to coordinate with Amazon to set a valid one\n username = gopickups.userid\n print(\"3\")\n db_cur.execute(\"select count(*) from auth_user where username = '\" +\n username + \"'\")\n rows = db_cur.fetchall()\n\n if not rows[0]:\n # if username does not exist, set username as \"nobody\"\n username = \"nobody\"\n else:\n # if username does not match with position_x and position_y\n print(\"4\")\n db_cur.execute(\"select pos_x, pos_y from ups_frontend_accounts \"\n \"where ups_account='\" + username + \"'\")\n rows = db_cur.fetchall()\n if rows:\n row = rows[0]\n # if validation passed, keep username unchanged\n if gopickups.dst_x == int(row[0]) and gopickups.dst_y == int(row[1]):\n pass\n else:\n username = \"nobody\"\n # TODO: may need to response Amazon with error message or ignore\n else:\n username = \"nobody\"\n # add package info to database, status is created shipment\n print(\"5\")\n db_cur.execute(\"insert into ups_frontend_package \"\n \"(username, trackingid, status, position_x, \"\n \"position_y, packageid, worldid) values ('\" +\n username + \"', '\" + str(tracking_number[i]) +\n \"', 'C', '\" + str(gopickups.dst_x) + \"', '\" +\n str(gopickups.dst_y) + \"', '\" +\n str(gopickups.packageid) + \"', '\" +\n str(world_id) + \"')\")\n\n # record the time of shipment creation\n print(\"6\")\n db_cur.execute(\"insert into ups_frontend_time \"\n \"(worldid, trackingid, c_time, packageid) values ('\" +\n str(world_id) + \"', '\" + str(tracking_number[i]) + \"', '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) +\n \"', '\" + str(gopickups.packageid) + \"')\")\n\n # update item info, store each item into database\n for things in gopickups.things:\n print(\"7\")\n db_cur.execute(\"insert into ups_frontend_item \"\n \"(worldid, trackingid, iteminfo, count) values ('\" +\n str(world_id) + \"', '\" + str(tracking_number[i]) + \"', '\"\n + things.description + \"', '\" + str(things.count) + \"')\")\n\n # TODO: inform user when package is delivered\n # get username from database using packageid and worldid\n print(\"8\")\n db_cur.execute(\"select username from ups_frontend_package where worldid='\" +\n str(world_id) + \"' and packageid = '\" +\n str(gopickups.packageid) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n username = row[0]\n # get user's email address using username\n print(\"9\")\n db_cur.execute(\"select email from auth_user where username = '\" +\n username + \"'\")\n rows = db_cur.fetchall()\n if rows:\n row = rows[0]\n receiver = row[0]\n # fill and send email to inform user\n host = \"smtp.gmail.com\"\n port = 465\n sender = \"youlyu25@gmail.com\"\n pwd = \"abc12345678!\" # not a good practice though...\n s = smtplib.SMTP_SSL(host, port)\n s.login(sender, pwd)\n s.sendmail(sender, receiver, \"Hello \" + username + \" !\\n\\nThis is UPS! \"\n \"Your package's shipment has been successfully created! \"\n \"The tracking number is: \" + str(tracking_number[i]))\n \n message = fill_created_shipments(message,\n tracking_number[i], gopickups.packageid)\n i = i + 1\n db_conn.commit()\n # send createdShipments message to Amazon, indicating the dispatch of truck\n send_message(amazon_conn, message)\n print(\"sent createdShipments message to Amazon\")\n\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n i = 0\n for gopickups in amazon_msg.gopickups:\n truckid = 0\n # 2. assign truck to pickup package\n while 1:\n # 2.1 check if any truck is available from database\n # mutex.acquire()\n # 2.1.1 first check if there is any truck with status \"loaded\"\n db_cur.execute(\"select truckid, package_num from ups_frontend_truck \"\n \"where status = 'L' and worldid = '\" +\n str(world_id) + \"' order by truckid asc\")\n rows = db_cur.fetchall()\n # if there is a truck with status \"loaded\"\n if rows:\n row = rows[0]\n truckid = int(row[0])\n print(\"loaded truck \" + str(truckid) + \" found\")\n # update truck status\n db_cur.execute(\"update ups_frontend_truck set status = 'E'\"\n \" where truckid = '\" + str(truckid) +\n \"' and worldid = '\" + str(world_id) + \"'\")\n # mutex.release()\n break\n\n # 2.1.2 if there is no truck with status \"loaded\", assign an \"idle\" one\n else:\n db_cur.execute(\"select truckid, package_num from ups_frontend_truck \"\n \"where status = 'I' and worldid = '\" +\n str(world_id) + \"' order by truckid asc\")\n rows = db_cur.fetchall()\n if rows:\n row = rows[0]\n truckid = int(row[0])\n print(\"idle truck \" + str(truckid) + \" found\")\n # update truck status\n db_cur.execute(\"update ups_frontend_truck set status = 'E'\"\n \" where truckid = '\" + str(truckid) +\n \"' and worldid = '\" + str(world_id) + \"'\")\n # mutex.release()\n break\n # if there is not, keep waiting until there is an available one\n else:\n print(\"no available truck\")\n # mutex.release()\n # 3. update package info into database since a truck is assigned\n db_cur.execute(\"update ups_frontend_package set status = 'E', \"\n \"truckid = '\" + str(truckid) + \"' where \"\n \"trackingid = '\" + str(tracking_number[i]) +\n \"' and worldid = '\" + str(world_id) + \"'\")\n\n # EXTRA TODO: the user may be able to confirm reception?\n # 4. record the starting time of pickup\n db_cur.execute(\"update ups_frontend_time set e_time = '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) +\n \"' where worldid = '\" + str(world_id) +\n \"' and trackingid = '\" + str(tracking_number[i]) + \"'\")\n\n # 5. fill command and message for world and Amazon\n command = fill_pickups(command, truckid, gopickups.whid)\n i = i + 1\n\n db_conn.commit()\n # send command to the world to dispatch truck for picking up\n send_message(world_conn, command)\n print(\"sent pickups command to world\")\n return\n# ----------------------------------------------------------------------------------\n\n\n# handle loaded(packageid) from Amazon\ndef handle_loaded(world_id, amazon_conn, world_conn, amazon_msg):\n print(\"handle loaded\")\n # first connect to the database shared with web app\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n command = ups_pb2.UCommands()\n command.simspeed = simspeed\n message = amz_ups_pb2.UAMessages()\n\n for loaded in amazon_msg.loaded:\n packageid = loaded.packageid\n # TODO: may need to get truckid from database if no truckid info is provided\n db_cur.execute(\"select truckid from ups_frontend_package where \"\n \"worldid = '\" + str(world_id) + \"' and packageid = '\" +\n str(packageid) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n truckid = int(row[0])\n print(\"truckid = \", truckid)\n # truckid = loaded.truckid\n deliveries = command.deliveries.add()\n deliveries.truckid = truckid\n\n # 1.1 update truck's package_num info\n db_cur.execute(\"select package_num from ups_frontend_truck where worldid='\"\n + str(world_id) + \"' and truckid = '\" + str(truckid) + \"'\")\n print(\"2\")\n rows = db_cur.fetchall()\n package_num = 0\n if rows:\n row = rows[0]\n package_num = int(row[0])\n package_num = package_num + 1\n db_cur.execute(\"update ups_frontend_truck set package_num = '\" +\n str(package_num) + \"' where truckid = '\" + str(truckid) +\n \"' and worldid = '\" + str(world_id) + \"'\")\n\n # 1.2 update package info\n db_cur.execute(\"update ups_frontend_package set status = 'L' where \"\n \"worldid = '\" + str(world_id) + \"' and packageid = '\" +\n str(packageid) + \"'\")\n print(\"3\")\n # update loaded time of package\n db_cur.execute(\"update ups_frontend_time set l_time = '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) +\n \"' where worldid = '\" + str(world_id) +\n \"' and packageid = '\" + str(packageid) + \"'\")\n print(\"4\")\n\n # 2. check if truck has loaded enough packages\n # if enough packages, send truck for delivery, status is \"O\"\n if package_num >= package_limit:\n # update truck's status to \"O\"\n db_cur.execute(\"update ups_frontend_truck set status = 'O' where \"\n \"worldid = '\" + str(world_id) +\n \"' and truckid = '\" + str(truckid) + \"'\")\n print(\"5.0\")\n # get coordinates from database using truckid\n db_cur.execute(\"select packageid, position_x, position_y from \"\n \"ups_frontend_package where worldid = '\" +\n str(world_id) + \"' and truckid = '\" +\n str(truckid) + \"' and status = 'L'\")\n rows = db_cur.fetchall()\n print(\"5.1\")\n # fill deliveries command\n for row in rows:\n packages = deliveries.packages.add()\n packages.packageid = int(row[0])\n packages.x = int(row[1])\n packages.y = int(row[2])\n # set the status of these packages to \"O\"\n db_cur.execute(\"update ups_frontend_package set status = 'O' where \"\n \"worldid = '\" + str(world_id) + \"' and packageid = '\"\n + str(packages.packageid) + \"'\")\n print(\"5.2\")\n # update out for delivery time of package\n db_cur.execute(\"update ups_frontend_time set o_time = '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n + \"' where worldid = '\" + str(world_id) +\n \"' and packageid='\" + str(packages.packageid) + \"'\")\n\n # not enough packages, status is \"L\"\n else:\n db_cur.execute(\"update ups_frontend_truck set status = 'L' where \"\n \"worldid = '\" + str(world_id) +\n \"' and truckid = '\" + str(truckid) + \"'\")\n print(\"6\")\n message = fill_load_confirm(message, loaded.packageid)\n print(\"7\")\n db_conn.commit()\n # send command to the world to deliver the packages indicated by packageids\n send_message(world_conn, command)\n # send loadConfirm message to Amazon\n send_message(amazon_conn, message)\n return\n# ----------------------------------------------------------------------------------\n\n\n# handle queries(tracking_number) message from Amazon\ndef handle_queries(world_id, amazon_conn, world_conn, amazon_msg):\n print(\"handle queries\")\n # first connect to the database shared with web app\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n # Amazon send queries to track packages\n message = amz_ups_pb2.UAMessages()\n for queries in amazon_msg.queries:\n # TODO: get truck status from DB using tracking_number\n db_cur.execute(\"select status from ups_frontend_package where \"\n \"worldid = '\" + str(world_id) + \"' and trackingid = '\" +\n str(queries.tracking_number) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n status = row[0]\n # fill queryResults message\n message = fill_query_results(message, queries.tracking_number, status)\n # send message to Amazon indicating the status of truck/package\n send_message(amazon_conn, message)\n return\n# ----------------------------------------------------------------------------------\n\n\n# ----------------------------------------------------------------------------------\n\"\"\" 2. world messages handlers \"\"\"\n# ----------------------------------------------------------------------------------\n\n\n# handle completions(truckid, x, y) message from world\ndef handle_completions(world_id, amazon_conn, world_conn, world_msg):\n print(\"handle completions\")\n # first connect to the database shared with web app\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n # determine if the truck has finished all the deliveries\n # or it reaches the warehouse by checking the current status\n # of the truck stored in the database\n for completions in world_msg.completions:\n message = amz_ups_pb2.UAMessages()\n # check truck's current status\n # if 'O', then it has finished all the deliveries\n print(\"a\")\n db_cur.execute(\"select status from ups_frontend_truck where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(completions.truckid) + \"'\")\n rows = db_cur.fetchall()\n # db_conn.commit()\n # db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n # \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n # db_cur = db_conn.cursor()\n row = rows[0]\n truck_status = row[0]\n # the truck has finished all its tasks, it is now idle\n if truck_status is \"O\":\n print(\"b\")\n # update the status of truck to idle in the database\n print(\"update ups_frontend_truck set status = 'I', \"\\\n \"package_num = '0' where \"\\\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(completions.truckid) + \"'\")\n db_cur.execute(\"update ups_frontend_truck set status = 'I', \"\n \"package_num = '0' where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(completions.truckid) + \"'\")\n print(\"bbb\")\n # else if en route, it just reaches the warehouse\n elif truck_status is \"E\":\n print(\"c\")\n # update the status of truck\n db_cur.execute(\"update ups_frontend_truck set status = 'W' where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(completions.truckid) + \"'\")\n # TODO: get packageid from DB using truckid in completions\n db_cur.execute(\"select packageid from ups_frontend_package where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(completions.truckid) + \"' and status = 'E'\")\n rows = db_cur.fetchall()\n row = rows[0]\n packageid = int(row[0])\n message = fill_arrived(message, packageid, completions.truckid)\n # the truck reaches warehouse, notify Amazon with arrived message\n send_message(amazon_conn, message)\n print(\"d\")\n # update status of package\n db_cur.execute(\"update ups_frontend_package set status = 'W' where \"\n \"packageid = '\" + str(packageid) +\n \"' and worldid = '\" + str(world_id) + \"'\")\n print(\"e\")\n # update status of waiting for load time\n db_cur.execute(\"update ups_frontend_time set w_time = '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) +\n \"' where worldid = '\" + str(world_id) +\n \"' and packageid = '\" + str(packageid) + \"'\")\n print(\"f\")\n db_conn.commit()\n return\n# ----------------------------------------------------------------------------------\n\n\n# handle delivered(truckid, packageid) message from world\ndef handle_delivered(world_id, amazon_conn, world_conn, world_msg):\n print(\"handle delivered\")\n # first connect to the database shared with web app\n db_conn = psycopg2.connect(\"dbname='postgres' user='postgres'\"\n \"host='\" + db_host + \"' port='\" + db_port + \"'\")\n db_cur = db_conn.cursor()\n # a certain package has been delivered\n message = amz_ups_pb2.UAMessages()\n for delivered in world_msg.delivered:\n # find tracking_number in the database using packageid\n print(\"v\")\n db_cur.execute(\"select trackingid from ups_frontend_package where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(delivered.truckid) + \"' and packageid = '\" +\n str(delivered.packageid) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n tracking_number = int(row[0])\n # update the status of package to delivered\n print(\"z\")\n db_cur.execute(\"update ups_frontend_package set status = 'D' where \"\n \"worldid = '\" + str(world_id) + \"' and trackingid = '\" +\n str(tracking_number) + \"'\")\n # update delivered time\n print(\"x\")\n db_cur.execute(\"update ups_frontend_time set d_time = '\" +\n time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) +\n \"' where worldid = '\" + str(world_id) +\n \"' and trackingid = '\" + str(tracking_number) + \"'\")\n # decrement truck's package_num as one package has been delivered\n print(\"c\")\n db_cur.execute(\"select package_num from ups_frontend_truck where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(delivered.truckid) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n package_num = int(row[0])\n package_num = package_num - 1\n print(\"r\")\n db_cur.execute(\"update ups_frontend_truck set package_num = '\" +\n str(package_num) + \"' where \"\n \"worldid = '\" + str(world_id) + \"' and truckid = '\" +\n str(delivered.truckid) + \"'\")\n\n # TODO: inform user when package is delivered\n # get username from database using packageid and worldid\n print(\"e\")\n db_cur.execute(\"select username, position_x, position_y from \"\n \"ups_frontend_package where worldid = '\" +\n str(world_id) + \"' and packageid = '\" +\n str(delivered.packageid) + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n username = row[0]\n if username == \"nobody\":\n print(\"package is stored as nobody's package\")\n pass\n else:\n x = row[1]\n y = row[2]\n # get user's email address using username\n db_cur.execute(\"select email from auth_user where username = '\" +\n username + \"'\")\n rows = db_cur.fetchall()\n row = rows[0]\n receiver = row[0]\n # fill and send email to inform user\n host = \"smtp.gmail.com\"\n port = 465\n sender = \"youlyu25@gmail.com\"\n pwd = \"abc12345678!\" # not a good practice though...\n s = smtplib.SMTP_SSL(host, port)\n s.login(sender, pwd)\n s.sendmail(sender, receiver, \"Hello \" + username + \" !\\n\\nThis is UPS! \"\n \"Your package has been successfully delivered to (\" +\n x + \", \" + y + \") !\")\n print(\"q\")\n message = fill_delivered(message, delivered.packageid)\n print(\"!\")\n db_conn.commit()\n # send message to Amazon to notify that a package's delivery is complete\n send_message(amazon_conn, message)\n\n# ----------------------------------------------------------------------------------\n\n\n# ----------------------------------------------------------------------------------\n\"\"\" 3. Amazon and world message main handlers \"\"\"\n# ----------------------------------------------------------------------------------\n\n\n# parse message from Amazon and make corresponding operations\ndef handle_amazon_msg(world_id, amazon_conn, world_conn, amazon_msg):\n print(\"handle_amazon_msg\\n\", amazon_msg)\n \"\"\"\n there are three possible messages sent from Amazon:\n GoPickUp gopickups\n LoadSuccess loaded\n GetDeliveryStatus queries\n parse the message and determine which operation to make\n \"\"\"\n # TODO: how should UPS handle error in amazon_msg?\n # TODO: may need to coordinate a set of uniform error messages\n # if error:\n if len(amazon_msg.gopickups):\n handle_gopickups(world_id, amazon_conn, world_conn, amazon_msg)\n if len(amazon_msg.loaded):\n handle_loaded(world_id, amazon_conn, world_conn, amazon_msg)\n if len(amazon_msg.queries):\n handle_queries(world_id, amazon_conn, world_conn, amazon_msg)\n return\n\n\n# parse message from Amazon and make corresponding operations\ndef handle_world_msg(world_id, amazon_conn, world_conn, world_msg):\n print(\"handle_world_msg\\n\", world_msg)\n \"\"\"\n there are two possible messages sent from the world:\n UFinished completions\n UDeliveryMade delivered\n parse the message and determine which operations to make\n \"\"\"\n # TODO: how should UPS handle error in world_msg?\n # TODO: try to check all the error information\n # if error:\n if len(world_msg.completions):\n handle_completions(world_id, amazon_conn, world_conn, world_msg)\n if len(world_msg.delivered):\n handle_delivered(world_id, amazon_conn, world_conn, world_msg)\n return\n\n\n# ----------------------------------------------------------------------------------\n\"\"\" 4. Amazon and world message receiving threads \"\"\"\n# ----------------------------------------------------------------------------------\n\n\n# receive messages from Amazon\ndef recv_amazon_msg(world_id, amazon_conn, world_conn):\n print(\"recv_amazon_msg\")\n # create a thread pool to handle received messages\n num_threads = 5\n # pool = threadpool.ThreadPool(num_threads)\n pool = ThreadPoolExecutor(num_threads)\n while 1:\n # receive a message from Amazon and assign a thread to handle it\n amazon_msg = recv_message(amazon_conn, amz_ups_pb2.AUMessages)\n pool.submit(handle_amazon_msg, world_id, amazon_conn, world_conn, amazon_msg)\n# ----------------------------------------------------------------------------------\n\n\n# receive messages from world\ndef recv_world_msg(world_id, amazon_conn, world_conn):\n print(\"recv_world_msg\")\n # create a thread pool to handle received messages\n num_threads = 5\n pool = ThreadPoolExecutor(num_threads)\n while 1:\n # receive a message from Amazon and assign a thread to handle it\n world_msg = recv_message(world_conn, ups_pb2.UResponses)\n pool.submit(handle_world_msg, world_id, amazon_conn, world_conn, world_msg)\n","sub_path":"ups_Docker/handle_msg_backup.py","file_name":"handle_msg_backup.py","file_ext":"py","file_size_in_byte":27434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"254407895","text":"#!/usr/bin/env python\nfrom functools import lru_cache\n\n@lru_cache(1000)\ndef add(x, y):\n print(\"Hello from add\")\n return x + y\n\n\nfor i in range(30):\n print(add(5, 10))\n\nprint(add.cache_info())\n\n","sub_path":"mathwhiz.py","file_name":"mathwhiz.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"11006158","text":"# For compatibility with newer versions\ntry:\n config.load_autoconfig(False)\nexcept:\n pass\n\nc.aliases = {\n 'w': 'session-save',\n 'q': 'quit',\n 'wq': 'quit --save',\n}\n\nc.backend = 'webengine'\n\nc.completion.delay = 1000\nc.completion.web_history.exclude = [\n # Exclude searches from completion\n # Doesn't regenerate automatically, see: https://github.com/qutebrowser/qutebrowser/issues/5868\n # Can be regenerated manually with\n # sqlite3 ~/.local/share/qutebrowser/history.sqlite 'update CompletionMetaInfo set value=1 where key=\"force_rebuild\"'\n '*://duckduckgo.com/*',\n '*://www.google.com/*',\n]\n\nc.confirm_quit = [\"multiple-tabs\", \"downloads\"]\n\nc.content.headers.accept_language = 'es-VE,es'\n\nc.editor.command = ['st', '-e', 'nvim', '{file}', '-c', 'normal {line}G{column0}l']\n\nc.fonts.default_size = '9pt'\nc.fonts.web.family.sans_serif = 'Liberation Sans'\nc.fonts.web.family.standard = 'Liberation Sans'\nc.fonts.web.size.default = 15\n\nc.hints.border = '1px solid #6b7089'\nc.hints.chars = 'asdfghjkl'\nc.hints.mode = 'letter'\n# Reddit expando\nc.hints.selectors['expando'] = ['.expando-button']\n# Reddit and Hacker News comment toggles\nc.hints.selectors['comment'] = ['.expand', '.togg']\nc.hints.selectors['any'] = ['*']\nc.hints.uppercase = True\n\nc.qt.low_end_device_mode = 'always'\n\nc.scrolling.smooth = False\n\nc.session.lazy_restore = True\n\nc.statusbar.position = 'bottom'\nc.statusbar.show = 'always'\n\nc.tabs.background = True\nc.tabs.indicator.padding = {\n 'top': 2,\n 'bottom': 2,\n 'left': 0,\n 'right': 4\n}\nc.tabs.indicator.width = 2\nc.tabs.last_close = 'default-page'\nc.tabs.mousewheel_switching = False\nc.tabs.padding = {\n 'top': 0,\n 'bottom': 0,\n 'left': 4,\n 'right': 4\n}\nc.tabs.position = 'top'\nc.tabs.show = 'multiple'\nc.tabs.title.alignment = 'left'\nc.tabs.title.format = '{audio}{index}: {current_title}'\nc.tabs.width = '5%'\n\nc.url.default_page = '~/any/startpage/index.html'\nc.url.searchengines = {\n 'DEFAULT': 'https://duckduckgo.com/?q={}',\n 'd': 'https://duckduckgo.com/?q={}',\n 'aw': 'https://wiki.archlinux.org/?search={}',\n 'w': 'https://es.wikipedia.org/?search={}',\n 'ew': 'https://en.wikipedia.org/?search={}',\n 'g': 'https://www.google.com/search?&q={}',\n # Go to given subreddit\n 'sr': 'https://www.reddit.com/r/{unquoted}',\n 'r': 'https://www.reddit.com/search?q={}',\n 'ru': 'https://www.reddit.com/user/{unquoted}',\n 'yt': 'https://www.youtube.com/results?search_query={}',\n 'gh': 'https://github.com/search?q={}',\n 'ud': 'https://www.urbandictionary.com/define.php?term={}',\n 'kym': 'https://knowyourmeme.com/search?q={}',\n 'cpp': 'https://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search={}',\n 'iv': 'https://invidious.snopyta.org/search?q={}',\n 'fd': 'https://search.f-droid.org/?q={}',\n 'nt': 'https://nitter.net/search?q={}',\n # Nitter handle\n 'nth': 'https://nitter.net/{unquoted}',\n # Jump to github repo or user\n 'ghr': 'https://github.com/{unquoted}',\n 'wf': 'https://www.wolframalpha.com/input/?i={}'\n}\nc.url.start_pages = '~/any/startpage/index.html'\n\n# Disable mouse wheel zoom\nc.zoom.mouse_divider = 0\n\ntab_rotate = [\n 'config-cycle tabs.position top right',\n 'config-cycle tabs.title.format \"{audio}{index}: {current_title}\" \"{aligned_index}\"',\n 'config-cycle tabs.title.alignment left center',\n 'set tabs.position?',\n]\n\ntab_show_cycle = [\n 'config-cycle tabs.show multiple switching never',\n 'set tabs.show?',\n]\n\nbar_show_toggle = [\n 'config-cycle statusbar.show never always',\n 'set statusbar.show?',\n]\n\ndef join_commands(command_list):\n return ' ;; '.join(command_list)\n\nconfig.bind('xr', join_commands(tab_rotate))\nconfig.bind('xt', join_commands(tab_show_cycle))\nconfig.bind('xb', join_commands(bar_show_toggle))\nconfig.bind(';e', 'hint expando')\nconfig.bind(';E', 'hint --rapid expando')\nconfig.bind(';c', 'hint comment')\nconfig.bind(';C', 'hint --rapid comment')\n\nconfig.source(\"colors.py\")\n","sub_path":".config/qutebrowser/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560563559","text":"\n\nfrom xai.brain.wordbase.nouns._audience import _AUDIENCE\n\n#calss header\nclass _AUDIENCES(_AUDIENCE, ):\n\tdef __init__(self,): \n\t\t_AUDIENCE.__init__(self)\n\t\tself.name = \"AUDIENCES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"audience\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_audiences.py","file_name":"_audiences.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"154868278","text":"'''\nCreated on 11 oct. 2016\n\n@author: tewdewildt\n'''\n\nimport logging\nimport gensim\nfrom gensim import corpora, models, similarities\nfrom pprint import pprint\nfrom nltk.stem.porter import PorterStemmer\nfrom stop_words import get_stop_words\nimport os\nimport matplotlib.font_manager\nimport matplotlib.pyplot as plt\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nfrom scipy.spatial.distance import pdist, squareform\n\nmatplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')\n\n\nen_stop = get_stop_words('en')\np_stemmer = PorterStemmer()\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.CRITICAL)\n\nlda = models.LdaModel.load('../Save/modelLDA.lda')\ndictionary = corpora.Dictionary.load('../Save/scopus_list.dict')\ncorpus_tfidf = corpora.MmCorpus('../Save/scopus_corpus.mm')\n\n''' Find word lists '''\nn_topics = 10\nFind_word_lists = False\nif Find_word_lists == True:\n for i in range(1, n_topics):\n temp = lda.show_topic(i, 5)\n terms = []\n for term in temp:\n terms.append(term)\n print(\"Top 10 terms for topic #\" + str(i) + \": \"+ \", \".join([i[0] for i in terms]))\n\n''' Make word clouds '''\n\nMake_word_clouds = False\nif Make_word_clouds == True:\n for i in range(1, n_topics):\n temp = lda.show_topic(i, 5)\n terms = []\n for term in temp:\n terms.append(term)\n from os import path\n from wordcloud import WordCloud\n \n def terms_to_wordcounts(terms, multiplier=1000):\n return \" \".join([\" \".join(int(multiplier*i[1]) * [i[0]]) for i in terms])\n #font_path = os.environ.get(\"FONT_PATH\", \"/Library/Fonts/Times New Roman.ttf\")\n font_path = \"times.ttf\"\n wordcloud = WordCloud(font_path, background_color='white').generate(terms_to_wordcounts(terms))\n \n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.show()\n\n''' Topic-words vectors: topics vs. words and PCA'''\n\nTopic_words_vectors_PCA_Topics= True\nTopic_words_vectors_PCA_Words= False\n\nfrom sklearn.feature_extraction import DictVectorizer\n \ndef topics_to_vectorspace(n_topics, n_words=200):\n rows = []\n for i in xrange(n_topics):\n temp = lda.show_topic(i, n_words)\n row = dict(((i[0],i[1]) for i in temp))\n rows.append(row)\n \n return rows \n \nvec = DictVectorizer()\n \nX = vec.fit_transform(topics_to_vectorspace(n_topics))\nX.shape\n# (40, 2457)\n\nif Topic_words_vectors_PCA_Topics==True:\n from sklearn.decomposition import PCA\n \n pca = PCA(n_components=2)\n \n X_pca = pca.fit(X.toarray()).transform(X.toarray())\n \n plt.figure()\n for i in xrange(X_pca.shape[0]):\n plt.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)\n plt.text(X_pca[i, 0], X_pca[i, 1], s=' ' + str(i)) \n \n plt.title('PCA Topics of keywords: energy and values')\n #plt.savefig(\"pca_topic\")\n \n #plt.show()\n\n\nif Topic_words_vectors_PCA_Words==True:\n X_pca = pca.fit(X.T.toarray()).transform(X.T.toarray())\n \n plt.figure()\n for i, n in enumerate(vec.get_feature_names()):\n plt.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)\n plt.text(X_pca[i, 0], X_pca[i, 1], s=' ' + n, fontsize=8)\n \n plt.title('PCA Words of keywords: energy and values')\n plt.show()\n\n''' hierarchical clustering '''\n \nhierarchical_clustering = False\nif hierarchical_clustering == True: \n \n \n plt.figure(figsize=(12,6))\n R = dendrogram(linkage(X_pca))\n plt.show()\n\n\n\n''' Correlation matrix '''\n\ncorrelation_matrix = False\nif correlation_matrix == True:\n \n \n cor = squareform(pdist(X.toarray(), metric=\"euclidean\"))\n \n plt.figure(figsize=(12,6))\n R = dendrogram(linkage(cor))\n plt.show()\n\n''' Network '''\n\nnetwork = True\nif network == True:\n import networkx as nx\n\n from sklearn.pipeline import make_pipeline\n from sklearn.preprocessing import Normalizer\n \n pca_norm = make_pipeline(PCA(n_components=20), Normalizer(copy=False))\n \n X_pca_norm = pca_norm.fit(X.toarray()).transform(X.toarray())\n \n cor = squareform(pdist(X_pca_norm, metric=\"euclidean\"))\n \n G = nx.Graph()\n \n for i in xrange(cor.shape[0]):\n for j in xrange(cor.shape[1]):\n if i == j:\n G.add_edge(i, j, {\"weight\":0})\n else:\n G.add_edge(i, j, {\"weight\":1.0/cor[i,j]})\n \n edges = [(i, j) for i, j, w in G.edges(data=True) if w['weight'] > .8]\n edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])\n \n #pos = nx.graphviz_layout(G, prog=\"twopi\") # twopi, neato, circo\n pos = nx.spring_layout(G)\n \n nx.draw_networkx_nodes(G, pos, node_size=100, alpha=.5)\n nx.draw_networkx_edges(G, pos, edgelist=edges, width=1)\n #nx.draw_networkx_edge_labels(G, pos ,edge_labels=edge_weight)\n nx.draw_networkx_labels(G, pos, font_size=8, font_family='sans-serif')\n \n plt.show()\n\n\n\n\n\n\n","sub_path":"LDA/lda_gensim_visualization.py","file_name":"lda_gensim_visualization.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466847673","text":"import scrapy\nfrom MultiPosting.items import OfferItem\nfrom MultiPosting.items import writeOfferItemHeaderRowCSV\nimport json\nimport csv\n\n# First version OfferSpider, starting directly from the feeding URL.\n# This one is better suited for sites that are going to be updated often, and have a stable feeding URL.\n# Plus: It can only broke if the feeding URL is changed, or if the feeding method/format is.\n# Weak points:\n# -Feeding URL change\n# -Feeding format change\n# -Feeding method change\n\n# Changes to do : Try using defined CSV writers from scrapy if possible\n# Adding a method for the JSON offer to item utf8 encoding\n\nclass OfferSpider(scrapy.Spider):\n\tname = \"offer\"\n\tallowed_domains = [\"multiposting.fr\"]\n\tstart_urls = [\n\t\t\"http://multiposting.fr/fr/get-job-list\"\n\t]\n\n\t# Response.body is loaded with json.loads\n\t# if extracted data exist:\n\t# a csv.writer is instantiated\n\t# header row containing column names is writen to offer.csv\n\t# each offer contained in the loaded JSON file is:\n\t# encoded to utf8 standard and stocked in an OfferItem\n\t# (((which is not really used here, but would permit to export\n\t# to different formats/files/database, and helps to keep the code clear)))\n\t# writen attribute by attribute to offer.csv as a single row.\n\n\tdef parse(self, response):\n\t\tdata = json.loads(response.body)\n\t\tif data and data['offers'] and len(data['offers']) != 0:\n\t\t\tc = csv.writer(open(\"offers.csv\", \"wb\"))\n\t\t\twriteOfferItemHeaderRowCSV(c)\n\t\t\tfor offer in data['offers']:\n\t\t\t\titem = OfferItem()\n\t\t\t\titem['offer'] = offer['id']\n\t\t\t\titem['title'] = offer['title'].encode('utf8')\n\t\t\t\titem['country']= offer['country'].encode('utf8')\n\t\t\t\titem['location_name']= offer['city'].encode('utf8')\n\t\t\t\titem['postal_code']= offer['postal_code'].encode('utf8')\n\t\t\t\titem['education_level']= offer['study_level'].encode('utf8')\n\t\t\t\titem['experience_level']= offer['experience'].encode('utf8')\n\t\t\t\titem['contract_type']= offer['contract_type'].encode('utf8')\n\t\t\t\titem['job_description']= offer['description'].encode('utf8')\n\t\t\t\titem['profile_description']= offer['requested_profile'].encode('utf8')\n\t\t\t\titem.writeRowCSV(c)\n","sub_path":"MultiPosting/spiders/item_spider.py","file_name":"item_spider.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"425702423","text":"# Copyright 2015 Spanish National Research Council\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nimport copy\nimport json\nimport shlex\n\nfrom six.moves import urllib\n\nfrom ooi import exception\n\n\n_MEDIA_TYPE_MAP = collections.OrderedDict([\n ('text/plain', 'text'),\n ('text/occi', 'header'),\n ('application/occi+json', 'json'),\n])\n\n\ndef _quoted_split(s, separator=',', quotes='\"'):\n \"\"\"Splits a string considering quotes.\n\n e.g. _quoted_split('a,\"b,c\",d') -> ['a', '\"b,c\"', 'd']\n \"\"\"\n splits = []\n partial = []\n in_quote = None\n for c in s:\n if in_quote:\n if c == in_quote:\n in_quote = None\n else:\n if c in quotes:\n in_quote = c\n if not in_quote and c in separator:\n if partial:\n splits.append(''.join(partial))\n partial = []\n else:\n partial.append(c)\n if partial:\n splits.append(''.join(partial))\n return splits\n\n\ndef _split_unquote(s, separator=\"=\"):\n \"\"\"Splits a string considering quotes and removing them in the result.\n\n e.g. _split_unquote('a=\"b=d\"') -> ['a', 'b=d']\n \"\"\"\n lex = shlex.shlex(s, posix=True)\n lex.commenters = \"\"\n lex.whitespace = separator\n lex.whitespace_split = True\n return list(lex)\n\n\nclass BaseParser(object):\n def __init__(self, headers, body):\n self.headers = headers\n self.body = body\n\n def parse(self):\n raise NotImplemented\n\n\nclass TextParser(BaseParser):\n def parse_categories(self, headers):\n kind = action = None\n mixins = collections.Counter()\n schemes = collections.defaultdict(list)\n try:\n categories = headers[\"Category\"]\n except KeyError:\n raise exception.OCCIInvalidSchema(\"No categories\")\n for ctg in _quoted_split(categories):\n ll = _quoted_split(ctg, \"; \")\n d = {\"term\": ll[0]} # assumes 1st element => term's value\n try:\n d.update(dict([_split_unquote(i) for i in ll[1:]]))\n except ValueError:\n raise exception.OCCIInvalidSchema(\"Unable to parse category\")\n ctg_class = d.get(\"class\", None)\n ctg_type = '%(scheme)s%(term)s' % d\n if ctg_class == \"kind\":\n if kind is not None:\n raise exception.OCCIInvalidSchema(\"Duplicated Kind\")\n kind = ctg_type\n elif ctg_class == \"action\":\n if action is not None:\n raise exception.OCCIInvalidSchema(\"Duplicated action\")\n action = ctg_type\n elif ctg_class == \"mixin\":\n mixins[ctg_type] += 1\n schemes[d[\"scheme\"]].append(d[\"term\"])\n if action and kind:\n raise exception.OCCIInvalidSchema(\"Action and kind together?\")\n return {\n \"category\": kind or action,\n \"mixins\": mixins,\n \"schemes\": schemes,\n }\n\n def parse_attribute_value(self, value):\n v = value.strip()\n # quoted: string or bool\n if v[0] == '\"':\n v = v.strip('\"')\n if v == \"true\":\n return True\n elif v == \"false\":\n return False\n else:\n return v\n # unquoted: number or enum-val\n try:\n return int(v)\n except ValueError:\n try:\n return float(v)\n except ValueError:\n return v\n\n def parse_attributes(self, headers):\n attrs = {}\n try:\n header_attrs = headers[\"X-OCCI-Attribute\"]\n for attr in _quoted_split(header_attrs):\n try:\n n, v = attr.split(\"=\", 1)\n attrs[n.strip()] = self.parse_attribute_value(v)\n except ValueError:\n raise exception.OCCIInvalidSchema(\"Unable to parse\")\n except KeyError:\n pass\n return attrs\n\n def parse_links(self, headers):\n links = collections.defaultdict(list)\n try:\n header_links = headers[\"Link\"]\n except KeyError:\n return links\n for link in _quoted_split(header_links):\n ll = _quoted_split(link, \"; \")\n # remove the \"<\" and \">\"\n if ll[0][1] != \"<\" and ll[0][-1] != \">\":\n raise exception.OCCIInvalidSchema(\"Unable to parse link\")\n link_id = ll[0][1:-1]\n target_location = None\n target_kind = None\n attrs = {}\n try:\n for attr in ll[1:]:\n n, v = attr.split(\"=\", 1)\n n = n.strip().strip('\"')\n v = self.parse_attribute_value(v)\n if n == \"rel\":\n target_kind = v\n continue\n elif n == \"occi.core.target\":\n target_location = v\n continue\n attrs[n] = v\n except ValueError:\n raise exception.OCCIInvalidSchema(\"Unable to parse link\")\n if not (target_kind and target_location):\n raise exception.OCCIInvalidSchema(\"Unable to parse link\")\n links[target_kind].append({\n \"target\": target_location,\n \"attributes\": attrs,\n \"id\": link_id,\n })\n return links\n\n def _convert_to_headers(self):\n if not self.body:\n raise exception.OCCIInvalidSchema(\"No schema found\")\n hdrs = collections.defaultdict(list)\n for l in self.body.splitlines():\n hdr, content = l.split(\":\", 1)\n hdrs[hdr].append(content)\n return {hdr: ','.join(hdrs[hdr]) for hdr in hdrs}\n\n def _parse(self, headers):\n obj = self.parse_categories(headers)\n obj['attributes'] = self.parse_attributes(headers)\n obj['links'] = self.parse_links(headers)\n return obj\n\n def parse(self):\n return self._parse(self._convert_to_headers())\n\n\nclass HeaderParser(TextParser):\n def parse(self):\n return self._parse(self.headers)\n\n\nclass JsonParser(BaseParser):\n def parse_categories(self, obj):\n kind = action = None\n mixins = collections.Counter()\n schemes = collections.defaultdict(list)\n if \"kind\" in obj:\n sch, term = urllib.parse.urldefrag(obj[\"kind\"])\n schemes[sch + \"#\"].append(term)\n kind = obj[\"kind\"]\n for m in obj.get(\"mixins\", []):\n mixins[m] += 1\n sch, term = urllib.parse.urldefrag(m)\n schemes[sch + \"#\"].append(term)\n if \"action\" in obj:\n action = obj[\"action\"]\n sch, term = urllib.parse.urldefrag(obj[\"action\"])\n schemes[sch + \"#\"].append(term)\n if action and kind:\n raise exception.OCCIInvalidSchema(\"Action and kind together?\")\n return {\n \"category\": kind or action,\n \"mixins\": mixins,\n \"schemes\": schemes,\n }\n\n def parse_attributes(self, obj):\n if \"attributes\" in obj:\n return copy.copy(obj[\"attributes\"])\n return {}\n\n def parse_links(self, obj):\n links = collections.defaultdict(list)\n for l in obj.get(\"links\", []):\n try:\n d = {\n \"target\": l[\"target\"][\"location\"],\n \"attributes\": copy.copy(l.get(\"attributes\", {})),\n }\n if \"id\" in l:\n d[\"id\"] = l[\"id\"]\n links[l[\"target\"][\"kind\"]].append(d)\n except KeyError:\n raise exception.OCCIInvalidSchema(\"Unable to parse link\")\n return links\n\n def parse(self):\n try:\n obj = json.loads(self.body or \"\")\n except ValueError:\n raise exception.OCCIInvalidSchema(\"Unable to parse JSON\")\n r = self.parse_categories(obj)\n r['attributes'] = self.parse_attributes(obj)\n r['links'] = self.parse_links(obj)\n return r\n\n\n_PARSERS_MAP = {\n \"text\": TextParser,\n \"header\": HeaderParser,\n \"json\": JsonParser,\n}\n\n\ndef get_media_map():\n return _MEDIA_TYPE_MAP\n\n\ndef get_default_parsers():\n return _PARSERS_MAP\n\n\ndef get_supported_content_types():\n return _MEDIA_TYPE_MAP.keys()\n","sub_path":"ooi/wsgi/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":8906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"592030958","text":"\"\"\"\nThe helpers classes/function of the Ultimate-Hosts-Blacklist project.\n\nProvide the helpers we use for list manipulation.\n\nLicense:\n::\n\n\n MIT License\n\n Copyright (c) 2019, 2020, 2021 Ultimate-Hosts-Blacklist\n Copyright (c) 2019, 2020, 2021 Nissar Chababy\n Copyright (c) 2019, 2020, 2021 Mitchell Krog\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\"\"\"\n\n\nclass List: # pylint: disable=too-few-public-methods, bad-continuation\n \"\"\"\n List manipulation.\n\n :param main_list: The list we are working with.\n :type main_list: list\n \"\"\"\n\n def __init__(self, main_list=None):\n if main_list is None: # pragma: no cover\n self.main_list = []\n else:\n self.main_list = main_list\n\n def format(self, delete_empty=False):\n \"\"\"\n Return a well formated list. Basicaly, it's sort a list and remove duplicate.\n\n :param delete_empty: Tell us if we have to remove all empty element of the list.\n :type delte_empty: bool\n \"\"\"\n\n try:\n formatted = sorted(list(set(self.main_list)), key=str.lower)\n\n if delete_empty and formatted and not formatted[0]:\n return formatted[1:]\n return formatted\n except TypeError: # pragma: no cover\n return self.main_list\n\n def delete_none_element(self):\n \"\"\"\n Delete all None type elements.\n \"\"\"\n\n return [x for x in self.main_list if x]\n\n def merge(self, to_merge, strict=True):\n \"\"\"\n Merge to_merge into the given main list.\n\n :param list to_merge: The list to merge.\n\n :param bool strict:\n Tell us if we have to respect index (:code:`True`)\n or not (:code:`False`).\n\n :return: The merged list.\n :rtype: list\n \"\"\"\n\n from ultimate_hosts_blacklist.helpers.dict import Dict\n\n # We initiate a variable which will save the\n # result\n result = []\n\n if strict:\n # We are in strict mode.\n\n for index, element in enumerate(to_merge):\n # We loop through each element of the list to merge\n # to the main dict.\n\n try:\n if isinstance(element, dict) and isinstance(\n self.main_list[index], dict\n ):\n # The currently read element is a dict.\n\n # We merge its content into the main dict\n # and append into the result.\n result.append(Dict(self.main_list[index]).merge(element))\n elif isinstance(element, list) and isinstance(\n self.main_list[index], list\n ):\n # The currently read element is a list.\n\n # We loop through this method.\n result.append(List(self.main_list[index]).merge(element))\n else:\n # The currently read element is not a list\n # nor a dict.\n\n # We append the element to the result.\n result.append(element)\n except IndexError: # pragma: no cover\n # The index does not exist.\n # Which means that for example one list is bigger\n # than the other one.\n\n # We append the element to the result.\n result.append(element)\n else:\n # We are not is strict mode.\n\n # We initiate the result with the main list.\n result = self.main_list\n\n for element in to_merge:\n # We loop through the element to merge.\n\n if element not in result:\n # The currently read element is not\n # in the result.\n\n # We append it to the result\n result.append(element)\n\n # We return the result.\n return result\n","sub_path":"ultimate_hosts_blacklist/helpers/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"428509885","text":"# Cоздать приложение Телефонная книга. В телефонную книгу (PhoneBook) надо добавлять контакты(Contact)\n\n# 1. Класс Contact имеет следующие поля:\n# Имя, фамилия, телефонный номер - обязательные поля;\n# Избранный контакт - необязательное поле. По умолчанию False;\n# Дополнительная инфор��ация(email, список дополнительных номеров, ссылки на соцсети) - необходимо использовать *args, **kwargs.\n\n# 2. Класс PhoneBook:\n# Название телефонной книги - обязательное поле;\n# Телефонная книга должна работать с классами Contact.\n\nclass Contact():\n\n def __init__(self, name, surname, phone_num, favourite=False, *args, **kwargs):\n self.name = name\n self.surname = surname\n self.phone_num = phone_num\n self.args = args\n self.kwargs = kwargs\n self.favourite = favourite\n if self.favourite is False:\n self.favourite_status = 'нет'\n else:\n self.favourite_status = 'да'\n\n def __str__(self):\n\n self.contact_str = 'Имя: ' + self.name + '\\n' + 'Фамилия: ' + self.surname + '\\n' + 'Телефон: ' + self.phone_num + '\\n' + 'В избранных: ' + self.favourite_status + '\\n'\n\n if self.args:\n for i in self.args:\n self.contact_str += 'Дополнительный номер: ' + i\n\n if self.kwargs:\n self.contact_str += 'Дополнительная информация:\\n'\n for key,value in self.kwargs.items():\n self.contact_str += '\\t' + key + ': ' + value + '\\n'\n\n return self.contact_str\n\nclass PhoneBook():\n\n def __init__(self, name):\n self.name = name\n self.contact_list = list()\n\n # показать все контакты телефонной книги\n def show_all_contacts(self):\n for contact in self.contact_list:\n print(contact)\n\n # добавить контакт в телефонную книги\n def add_contact(self, name, surname, phone_num,*args, **kwargs):\n self.contact_list.append(Contact(name, surname, phone_num,*args, **kwargs))\n print(f'Контакт {name} был добавлен')\n\n # удалить контакт по номеру из телефонной книги\n def delete_contact(self, phone_num):\n for contact in self.contact_list:\n if phone_num in contact.phone_num:\n self.contact_list.remove(contact)\n print(f'Контакт {contact.name} с номером {contact.phone_num} был удален\\n')\n\n # вывести избранные контакты из телефонной книги\n def get_favourite(self):\n print('Избранные номера:')\n for contact in self.contact_list:\n if contact.favourite is True:\n print(f'\\t{contact.phone_num}')\n\n # поиск контакта по имени и фамилии из телефонной книги\n def get_contact(self, name, surname):\n for contact in self.contact_list:\n if contact.name == name and contact.surname == surname:\n print(f'По вашему запросу был найден контакт:\\n{contact}')\n\nMila_PhoneBook = PhoneBook('Мила') # создать телефонную книга Мила\nMira_PhoneBook = PhoneBook('Мира') # создать телефонную книга Мира\n\n# добавить контакт в телефонную книгу Мила (закоменченные строчки после функции можно использовать вместо этой функции)\ndef add_contact(phone_book):\n name = input('Введите имя: ')\n surname = input('Введите фамилию: ')\n phone_num = input('Введите телефонный номер: ')\n favourite = input('Добавить номер в избранные контакты?(да/нет): ')\n phone_book.add_contact(name, surname, phone_num)\nadd_contact(Mila_PhoneBook)\n# Mila_PhoneBook.add_contact('Jhon', 'Smith', '+71234567809', telegram='@jhony', email='jhony@smith.com')\n# Mila_PhoneBook.add_contact('Denis', 'Kaurow', '+75764523534', instagram='@denuska', email='denuska@gmail.com')\n# Mila_PhoneBook.add_contact('Maria', 'Ankushina', '+79198648764', slack='@ankuuusha', email='denuska@gmail.com')\n\n# показать все контакты телефонной книги Мила (закоменченные строчки после функции можно использовать вместо этой функции)\ndef show_all_contacts(phone_book):\n phone_book.show_all_contacts()\nshow_all_contacts(Mila_PhoneBook)\n# Mila_PhoneBook.show_all_contacts()\n\n# удалить контакт по номеру из телефонной книги Мила (закоменченные строчки после функции можно использовать вместо этой функции)\ndef delete_contact(phone_book):\n phone_num = str(input('Введите номер телефона контакта, которого хотите удалить (начиная с +7): '))\n phone_book.delete_contact(phone_num)\ndelete_contact(Mila_PhoneBook)\n# Mila_PhoneBook.delete_contact('+71234567809')\n\n# вывести избранные контакты из телефонной книги Мила (закоменченные строчки после функции можно использовать вместо этой функции)\ndef get_favourite(phone_book):\n phone_book.get_favourite()\nget_favourite(Mila_PhoneBook)\n# Mila_PhoneBook.get_favourite()\n\n# поиск контакта по имени и фамилии из телефонной книги Мила (закоменченные строчки после функции можно использовать вместо этой функции)\ndef get_contact(phone_book):\n name = input('Введите имя контакта, которого хотите посмотреть: ')\n surname = input('Введите фамилию контакта, которого хотите посмотреть: ')\n phone_book.get_contact(name, surname)\nget_contact(Mila_PhoneBook)\n# Mila_PhoneBook.get_contact('Denis', 'Kaurow')\n\n","sub_path":"Продвинутый Python/3. Function 2.0 args, kwargs (Работа с Классами)/main(Вариант сложнее, из классов делать готовые функции, более подходит для использования).py","file_name":"main(Вариант сложнее, из классов делать готовые функции, более подходит для использования).py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"290853464","text":"#from datetime import datetime\n\nfrom django.db import models\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation\nfrom django.contrib.auth.models import User\n#from django.utils import timezone\n\n#from .managers import ScoreManager\n\n# Create your models here.\n\n'''\nDeze rating app maakt gebruik van het contenttypes framework van django. We willen immers een stem kunnen \nuitbrengen op verschillende django modellen, dus hebben we generic relations nodig.\n\nMomenteel is de implementatie gebaseerd op: https://github.com/pinax/pinax-ratings/blob/master/pinax/ratings/models.py \n'''\n\n\nclass BaseContentTypesModel(models.Model):\n\t'''\n\tAbstracte klasse voor modellen die gebruik maken van het contenttypes framework\n\t'''\n\n\tcontent_type = models.ForeignKey(ContentType, verbose_name='content type', related_name='content_type_set_for_%(class)s')\n\tobject_id = models.PositiveIntegerField(db_index=True) # default name voor GenericForeignKey relaties in contenttypes\n\tcontent_object = GenericForeignKey('content_type', 'object_id')\n\n\tclass Meta:\n\t\tabstract=True\n\n\nclass Vote(BaseContentTypesModel):\n\t'''\n\tEen Vote object is een stem uitgebracht door een gebruiker op een te beoordelen model. Een gebruiker kan \n\tslechts 1 stem uitbrengen op een bepaald model.\n\t'''\n\n\tuser = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='votes')\n\ttimestamp = models.DateTimeField(auto_now_add=True, editable=False)\n\tscore = models.PositiveIntegerField(default=0) # Enkel positieve getallen worden ondersteund in deze app\n\t#date_changed = models.DateTimeField(default=datetime.now(), editable=False)\n\n\toverall_rating = models.ForeignKey('Score', null=True, related_name='votes')\t# foreignkey naar Score, een Score bestaat uit een aantal Votes\n\n\n\tclass Meta:\n\t\tunique_together = ('content_type', 'object_id', 'user')\n\n\tdef __str__(self):\n\t\treturn '%s gaf een score van %s op %s' % (self.user, self.score, self.content_object)\n\n\t# Huidige implementatie doets niets!\n\tdef save(self, *args, **kwargs):\n\t\t#self.date_changed = datetime.now()\n\t\tsuper(Vote, self).save(*args, **kwargs)\n\n\t@classmethod\n\tdef vote(cls, rating, user, score):\n\t\tct = ContentType.objects.get_for_model(rating)\n\n\t\tnew = cls.objects.create(\n\t\t\tcontent_type=ct,\n\t\t\tobject_id=rating.pk,\n\t\t\tuser=user,\n\t\t\trating=score\n\t\t)\n\n\t\toverall_score, is_created = Score.objects.get_or_create(\n\t\t\tobject_id=new.pk,\n\t\t\tcontent_type=ct,\n\t\t)\n\n\t\tnew.overall_rating = overall_score.update(score) # returns updated score\n\t\tnew.save()\t\n\n\t\ttotal_score = overall_score.total_score\n\t\tnum_votes = overall_score.num_votes\n\n\t\treturn (total_score, num_votes) #retourneer totale score en aantal stemmen om UI te updaten\n\n\n\nclass Score(BaseContentTypesModel):\n\t'''\n\tDe score voor een object wordt bepaald door de uitgebrachte stemmen op dat object. \n\tScore.votes is een FK relatie vanuit het Vote model\n\t'''\n\n\ttotal_score = models.PositiveIntegerField(null=True) \n\tnum_votes = models.PositiveIntegerField(default=0)\n\n\n\tclass Meta:\n\t\tunique_together = ('content_type', 'object_id', )\n\n\tdef __str__(self):\n\t\treturn '%s heeft een score van %s, behaald door %s stemmen' % (self.content_object, self.score, self.votes)\n\n\tdef update(self, score):\n\n\t\tnum_votes = num_votes + 1\n\t\ttotal_score = total_score + score\n\t\tself.save()\n\n\t\treturn self.score\n\n\t@property\n\tdef score(self):\n\n\t\tscore = float(total_score/num_votes)\n\n\t\treturn score\n\nclass RatedModelMixin(models.Model):\n\t'''\n\tDeze mixin klasse voegt de rating functionaliteit toe aan het model waarbij je de mixin implementeert\n\t'''\n\n\trating_scores = GenericRelation(Score)\n\trating_votes = GenericRelation(Vote)\n\n\tclass Meta:\n\t\tabstract = True\n","sub_path":"ratings/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"200087063","text":"import random\n\nst = ''\nset = []\nfor i in range(1111, 6667):\n st = str(i)\n if '0' not in st and '7' not in st and '8' not in st and '9' not in st:\n set.append(st)\n\ndef spelregels():\n \"'Deze functie heb ik om het wat meer op een spel te laten lijken, hierin kun je de spelregels krijgen als je het spel nog nooit hebt gespeeld.'\"\n gespeeld = input('Heb je dit spel al een keer gespeeld [Y/N]: ').lower()\n if 'n' == gespeeld:\n regels = '---SPELREGELS---' + \\\n '\\n' + \\\n 'Er zijn 6 verschillen getallen waar je uit kunt kiezen, 1 t/m 6.' + \\\n '\\n' + \\\n 'Je hebt 10 beurten om het goed te raden, haal je ndit niet heb je verloren.' + \\\n '\\n' + \\\n 'Zodra een getal op de goede plek staat en het goede getal is komt er een zwart pinnetje te staan.' + \\\n '\\n' + \\\n 'Zodra een getal niet op de goede plek staat, maar als het getal wel in de code voorkomt ' + \\\n 'krijg je een wit pinnetje erbij.' + \\\n '\\n' + \\\n 'Als je de code hebt geraden heb je gewonnen.' + \\\n '\\n' + \\\n 'Hoe minder pogingen je er over doet, hoe beter je bent.' + \\\n '\\n' + \\\n 'Van de feedback is het eerste getal de zwarte pion en het tweede getal de witte pion. ' + \\\n '\\n' + \\\n 'Bijv: 1, 2. Dit betekent 1 zwarte pion en 2 witte pionnen.' + \\\n '\\n'\n print(regels)\n gamemode()\n elif 'y' == gespeeld:\n print('\\n')\n gamemode()\n else:\n print('Dit is geen geldige optie, probeer het opnieuw.' + '\\n')\n spelregels()\n\n\ndef gamemode():\n \"'In deze functie kies ik of ik de code wil raden of de computer de code wil laten raden.'\"\n pogingen = 0\n modus = input('Wil je de code maken of breken: ').lower()\n if 'breken' in modus:\n print('De te raden getallen zijn: ' + '1 t/m 6. ')\n code = []\n code_breken(pogingen, code)\n elif 'maken' in modus:\n pc_raden(pogingen, set)\n else:\n print('dat is geen bestaande gamemode, probeer het opnieuw')\n gamemode()\n\n\ndef inp():\n \"'In deze functie voer ik in wat mijn gok is of wat de code moet zijn.'\"\n poging = ''\n while poging not in set:\n poging = input('Wat is de code: ')\n poging = poging.strip()\n if poging not in set:\n print('Deze codecombinatie bestaat niet, probeer het opnieuw.')\n return poging\n\n\ndef code_breken(pogingen, codes):\n \"'In deze functie raad ik zelf de code.'\"\n if len(codes) < 4:\n codes = random.choice(set)\n print('Je hebt nog ' + str(10 - pogingen) + ' pogingen over.')\n pogingen += 1\n\n poging = inp()\n\n if poging == codes:\n print('Gefeliciteerd je hebt het goed geraden')\n print('Je hebt het in ' + str(pogingen) + ' poging gehaald.' + '\\n')\n gamemode()\n else:\n terugslag = feedback(codes, poging)\n print('Feedback: ' + str(terugslag))\n\n if pogingen == 10:\n print('Helaas je hebt de code niet kunnen kraken in 10 pogingen')\n print('De code was ' + str(codes) + '\\n')\n gamemode()\n else:\n code_breken(pogingen, codes)\n\n#bron: 'YET ANOTHER MASTERMIND STRATEGY from Barteld Kooi, Department of Philosophy, University of Groningen, The Netherlands\ndef pc_raden(pogingen, set):\n \"'In deze functie staat het worst case strategy algorithme.'\"\n eigencode = inp()\n\n\n while len(set) > 0:\n uitkomsten = ['0, 0', '0, 1', '0, 2', '0, 3', '0, 4', '1, 0', '1, 1', '1, 2', '1, 3', '2, 0', '2, 1', '2, 2',\n '3, 0', '4, 0']\n\n worst_case = '1000'\n combo = 'hu'\n\n for i in set:\n tussen = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n for x in set:\n comment = feedback(str(i), str(x))\n for y in range(0, len(uitkomsten)):\n if uitkomsten[y] == comment:\n tussen[y] += 1\n if max(tussen) < int(worst_case):\n worst_case = max(tussen)\n combo = i\n guess = combo\n pogingen += 1\n print('gok ' + str(pogingen) + ': ' + str(guess))\n if guess == eigencode:\n break\n reflectie = feedback(eigencode, guess)\n\n memorie = []\n for i in set:\n if feedback(guess, i) == reflectie:\n memorie.append(i)\n set = memorie\n if pogingen > 10:\n print('Gefeliciteerd de computer heeft het niet binnen 10 pogingen geraden!')\n\n print('De computer heeft er ' + str(pogingen) + ' over gedaan' + '\\n')\n else:\n print('Helaas, de computer heeft het in ' + str(pogingen) + ' pogingen geraden!' + '\\n')\n gamemode()\n\n#Deze functie is deels in samenwerking met Brandon Betz\ndef feedback(code, poging):\n \"'In deze functie geef ik hoeveel zwarte pionnen en hoeveel witte pionnen er terugkomen bij de vergelijking van de 2 parameters.'\"\n temp = []\n feedback = []\n for i in range(0, len(poging)):\n if poging[i] == code[i]:\n e = str(poging[i]) + ':' + 'zwart'\n temp.append(e)\n feedback.append('zwart')\n for i in range(0, len(poging)):\n if poging[i] in code:\n d = str(poging[i]) + ':' + 'wit'\n if d not in temp and temp.count(str(poging[i]) + ':' + 'zwart') < code.count(poging[i]) and temp.count(str(poging[i]) + ':' + 'zwart') < poging.count(poging[i]):\n temp.append(d)\n feedback.append('wit')\n return str(feedback.count('zwart')) + ', ' + str(feedback.count('wit'))\n\nspelregels()","sub_path":"Mastering mastermind/worst_case.py","file_name":"worst_case.py","file_ext":"py","file_size_in_byte":5819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"535924457","text":"__author__ = 'isaac'\n\nfrom flask import Flask\nimport controller,controllerServer\n\napp = Flask(__name__)\napp.secret_key = 'some_secret'\napp.add_url_rule('/',view_func = controller.index)\napp.add_url_rule('/linkedcities',view_func = controller.linkedCities)\n\n#backend\napp.add_url_rule('/citiesinfo',view_func=controllerServer.queryCitiesInfo)","sub_path":"pwiki/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"258333792","text":"\nfrom __future__ import division\nfrom numpy import *\nfrom math import *\nfrom numpy import linalg as la \nimport numpy as np\nfrom cmath import *\nfrom pyx import *\nfrom pyx.graph import axis\n\n\n\nV=0.9\t\t#Potential v_gate\nn=5\t\t\t#Wie viele Potentiale hintereinander?\nt=0.8\t\t\t#Hoppingparameter der linken und rechten Seite\n\nbl=2\nbr=3\n\nVolt=-5\nVoltloop=51\nVoltstep=0.2\n\nstep=1000\t\t#in wie vielen Schritten soll das Integral gerechnet werden\n\n\nkstep=pi/step\n\npot=[0]*(n+1)\t\t\t\t#Liste generieren\n\nstrom=open(\"landauerstrom.dat\", \"w\")\n\nfor zzz in range(Voltloop):\n\n\n\tul=float(Volt)/float(2)\n\tur=-float(Volt)/float(2)\n\n\n\tk=0.00000000001\n\tj0=0\n\tje0=0\n\n\tfor kloop in range(step):\n\n\t\t\n\t\tE=-2*cos(k)\t\t\t\t#Energie berechnen\n\n\n\t\tfl=1/(exp(bl*(E-ul))+1)\n\t\tfr=1/(exp(br*(E-ur))+1)\n\n\n\t\t#Gleichungssystem loesen\n\n\n\t\tif n>1:\t\t\t\t\t#fuer mehr als ein Platz mit Potential in der Mitte\n\n\t\t\tpot[n]=-(E*exp(1j*k)+exp(2*1j*k))/(t)\n\t\t\t\n\n\t\t\tpot[n-1]=-((E-V)*pot[n]+t*exp(1j*k))\n\n\n\t\t\tfor m in range(n-2):\t\t#Schleife fuer die Potentiale\n\t\t\t\tpot[n-2-m]=-((E-V)*pot[n-1-m]+pot[n-m])\n\n\t\t\ta=(t*pot[1]-(E+exp(1j*k))*((E-V)*pot[1]+pot[2])/t)/(1-exp(-2*1j*k))\n\n\n\n\t\tif n==1:\t\t\t\t#Fuer den Fall, dass nur ein Potential in der Mitte platziert ist\n\t\t\tpot[0]=t*exp(1j*k)\n\n\t\t\tpot[1]=-(E*exp(1j*k)+exp(2*1j*k))/(t)\n\t\t\t\n\t\t\ta=(t*pot[1]-(E+exp(1j*k))*((E-V)*pot[1]+pot[0])/t)/(1-exp(-2*1j*k))\n\n\t\tT=1/(abs(a)**2)\n\t\tT=T.real\t\n\t\t\t\t\n\t\t#Damit ist das Glechungssystem geloest\n\t\t\n\n\n\n\t\tj=(1/pi)*sin(k)*T*(fl-fr)*kstep\n\t\tje=(1/pi)*E*sin(k)*T*(fl-fr)*kstep\n\t\t\n\t\tj0=j0+j\n\t\tje0=je0+je\n\n\t\tk=k+kstep\t\n\n\n\tstrom.write(\"%s\\t%s\\t%s\\n\"%(Volt,j0.real,je0.real))\n\tVolt=Volt+Voltstep\n\n\nstrom.close()\n\ncolors1 = [color.rgb.red] #Definieren von Farben und den Eigenschaften der Linien\ncolors2 = [color.rgb.blue]\ncolors3 = [color.rgb.black]\ncolors4 = [color.rgb.green]\nsymbols = [graph.style._diamondsymbol]\n\nline1 = graph.style.line(lineattrs=[attr.changelist(colors1), attr.changelist([style.linestyle.solid])])\nline2 = graph.style.line(lineattrs=[attr.changelist(colors2), attr.changelist([style.linestyle.dashdotted])])\nline3 = graph.style.line(lineattrs=[attr.changelist(colors3), attr.changelist([style.linestyle.solid])])\nline4 = graph.style.line(lineattrs=[attr.changelist(colors4), attr.changelist([style.linestyle.dashdotted])])\n\n\ng = graph.graphxy(width=12, key=graph.key.key(pos=\"br\", dist=0.1), x=graph.axis.lin(title=r\"Zeit $t$\"), y=graph.axis.lin(title=r\"AHA\"))\n\n\n\nf = graph.graphxy(width=12,key=graph.key.key(pos=\"br\", dist=0.1), x=graph.axis.lin(title=r\"Spannung $V$\"), y=graph.axis.lin(title=r\"statischer Strom $j$\") ) #Plotten der Stroeme zwischen dem linken und zentralen System\nf.plot(graph.data.file(\"landauerstrom.dat\", x=1, y=2, title=r\"statischer Strom\"),styles=[line1])\n#f.plot(graph.data.file(\"statstrom.dat\", x=1, y=3, title=r\"rechter statischer Strom\"),styles=[line3])\n#f.plot(graph.data.file(\"statstrom.dat\", x=1, y=4, title=r\"Mittelwert\"),styles=[line3])\nf.text(g.width/2.0,g.height+0.5,\"Statischen Stroeme in Abhaengigkeit mit der Spannung (LANDAUER)\",\n\t[text.halign.center, text.valign.bottom, text.size.Large])\n\nf.writePDFfile(\"landauerstrom\")\n\n","sub_path":"python/projarb/landauer.py","file_name":"landauer.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"188526272","text":"from django.test import TestCase\nfrom django.test.client import Client\nfrom django_any import any_model\nfrom models import models\nfrom forms import forms\n\ndef model_to_dict(model):\n opt = model._meta\n mdict = {}\n for field in opt.fields:\n if field.name != 'id':\n mdict[field.name] = field.value_from_object(model)\n return mdict\n\n# Models test\nclass ModelsTestCase(TestCase):\n def test_add_data(self):\n for key in models:\n data = any_model(models[key])\n for field in data._meta.fields:\n if field.name != 'id':\n self.assertEquals(bool(getattr(data, field.name)), True)\n\n# Client tests\nclass ClientTestCase(TestCase):\n def setUp(self):\n self.data = {}\n for key in models:\n self.data[key] = any_model(models[key])\n\n def test_index_page(self):\n c = Client()\n resp = c.get('/')\n self.assertEquals(resp.status_code, 200)\n\n def test_tree_view(self):\n c = Client()\n resp = c.get('/tree/')\n self.assertEquals(resp.status_code, 200)\n\n def test_manage_json(self):\n c = Client()\n for key in self.data:\n resp = c.get('/manage/json/' + key)\n self.assertEquals(resp.status_code, 301)\n\n def test_add_item(self):\n c = Client()\n for key in self.data:\n form = forms[key](instance=self.data[key])\n resp = c.post('/manage/add_item/' + key, {'form': form})\n self.assertEquals(resp.status_code, 301)\n\n def test_edit_item(self):\n c = Client()\n for key in self.data:\n form = forms[key](instance=self.data[key])\n resp = c.post('/manage/edit_item/' + key + '/' + str(self.data[key].id), {'form': form})\n self.assertEquals(resp.status_code, 301)","sub_path":"test_project/core/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"399166942","text":"import sys\nimport socket\nimport argparse\nimport threading\nimport subprocess\n\ndef run_command(command):\n #换行\n command = command.rstrip()\n print(\"command: %s\"%command)\n\n #运行命令并将输出返回\n try:\n output = subprocess.check_output(command,stderr=subprocess.STDOUT, shell = True)\n except:\n output = \"Failed to execute command.\\r\\n\"\n\n print(\"output: %s\"%output)\n\n return output\n\ndef client_handler(client_socket,addr,des,exe,cmd):\n print(\"Accept new connection from %s:%s\" % addr)\n if des:\n #读取所有的字符并写下目标\n client_socket.send(b\"Welcome\\n\");\n file_buffer = \"\"\n #持续读取数据直到没有符合的数据\n \n while True:\n data = client_socket.recv(1024).decode()\n print(\"write data: %s\"%data)\n if data == \"exit\":\n break\n else:\n file_buffer += data\n file_buffer += \"\\n\"\n client_socket.send(b\"Continue\\n\");\n\n #现在将接收的数据写出来\n try:\n f = open(des,\"wb\")\n f.write(file_buffer.encode())\n f.close()\n\n client_socket.send((\"Successful saved file in: %s\"%des).encode())\n\n except:\n client_socket.send((\"Failed to save file in: %s\"%des).encode())\n\n #执行一个shell命令\n if exe:\n output = run_command(exe)\n\n client_socket.send(output.encode())\n if cmd:\n print(\"here\")\n client_socket.send(b\"\")\n while True:\n data = client_socket.recv(1024).decode()\n print(\"receive data %s\" %data)\n if(data == \"exit\"):\n client_socket.send(b\"Good Bye!\")\n break\n else:\n output = run_command(data)\n client_socket.send(output)\n client_socket.close()\n print(\"Connection from %s:%s is closed.\" % addr)\n\ndef client_sender(host,port):\n try:\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n s.connect((host,port))\n print(s.recv(2048).decode())\n while True:\n data = input()\n if not data:\n continue\n s.send(data.encode())\n print(s.recv(2048).decode())\n if data == \"exit\":\n break\n s.close()\n except:\n print(\"[*] exception Exiting.\")\n\n\n\ndef server_loop(host,port,des,exe,cmd):\n if not host:\n host = \"0.0.0.0\"\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((host,port))\n\n server.listen(5)\n while True:\n client_socket, addr = server.accept()\n t = threading.Thread(target = client_handler,args=(client_socket,addr,des,exe,cmd))\n t.start()\n\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-t\", \"--target\", dest=\"target_host\", type=str,help = \"target host\")\n parser.add_argument(\"-p\", \"--port\", dest=\"port\", type = int,help = \"target port\")\n parser.add_argument(\"-l\", \"--listen\", action=\"store_true\", help = \"listen on [host]:[port] for incomming connection\")\n parser.add_argument(\"-e\", \"--execute\", dest=\"execute\",help = \"execute a given file\",type = str)\n parser.add_argument(\"-u\", \"--upload\", dest=\"upload\", help = \"upload destination\",type = str)\n parser.add_argument(\"-c\", \"--command\", action=\"store_true\", help = \"run a shell\")\n args = parser.parse_args()\n if args.target_host:\n print(\"target host: %s\" % args.target_host)\n if args.port:\n print(\"target port: %s\" % args.port)\n if args.listen:\n print(\"listening\")\n if args.execute:\n print(\"execute: %s\"%args.execute)\n if args.upload:\n print(\"upload: %s\" %args.upload)\n if args.command:\n print(\"command\")\n\n\n ## 模仿netcat从标准输入中读取数据,并通过网络发送数据\n if not args.listen and len(args.target_host) and args.port > 0:\n #从命令行读取内存数据\n #这里将阻塞,所以不再向标准输入发送数据时发送CTRL-D\n\n #发送数据\n client_sender(args.target_host,args.port)\n\n ##开始监听并准备上传文件、执行命令\n #放置一个反弹shell\n #取决于上面的命令行选项\n if args.listen:\n server_loop(args.target_host, args.port, args.upload, args.execute, args.command)\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"network/netcat.py","file_name":"netcat.py","file_ext":"py","file_size_in_byte":4427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"42198826","text":"# Challenge 021\r\n\r\n\"\"\" Ask the user to enter their first name and then ask them to enter their surname. Join them together\r\nwith a space between and display the name and the length of whole name. \"\"\"\r\n\r\nfirst_name = input('What is your name?\\n>> ').title()\r\n\r\nsurname = input('What is your surname?\\n>> ').title()\r\n\r\nname = first_name + \" \" + surname \r\n\r\nprint(F'{name}')\r\n\r\nprint(len(name))\r\n","sub_path":"ex021.py","file_name":"ex021.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372238359","text":"from CRABClient.UserUtilities import config\nconfig = config()\n\nconfig.General.requestName = 'Analysis_SingleMuon_UL2018C_wProbQ'\nconfig.General.workArea = 'crab_projects'\nconfig.General.transferOutputs = True\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'HSCParticleProducerAnalyzer_cfg.py'\nconfig.JobType.allowUndistributedCMSSW = True\n\nconfig.JobType.inputFiles = ['SUSYBSMAnalysis/HSCP/data/Data13TeVGains_v2.root','SUSYBSMAnalysis/HSCP/data/dEdxTemplate_harm2_SO_in_noC_CCC_MG_2017B.root','SUSYBSMAnalysis/HSCP/data/CMS_GeomTree.root','SUSYBSMAnalysis/HSCP/data/MuonTimeOffset.txt']\n\nconfig.Data.inputDataset = '/SingleMuon/tvami-crab_PrivateReAOD_2018_SingleMuon_AOD_v1-f31fbc775312df6a6c2c9ecba57d4788/USER'\nconfig.Data.inputDBS = 'phys03'\n #config.Data.splitting = 'Automatic'\n #config.Data.splitting = 'LumiBased'\n #config.Data.unitsPerJob = 1 #20\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 1\n\n #config.Data.lumiMask = 'https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions17/13TeV/Legacy_2017/Cert_294927-306462_13TeV_UL2017_Collisions17_GoldenJSON.txt'\n #config.Data.lumiMask = '/afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions17/13TeV/Legacy_2017/Cert_294927-306462_13TeV_UL2017_Collisions17_GoldenJSON.txt'\n #config.Data.lumiMask = '/afs/cern.ch/work/d/dapparu/private/thesis/hscp/CMSSW_10_6_20/src/SUSYBSMAnalysis/crab_projects/crab_EDMProd_MET_UL2017B_297047_297484/results/processedLumis.json'\n\n #config.Data.runRange = '299368-300284'\n #config.Data.runRange = '297047-306462'\n\nconfig.Data.publication = False\nconfig.Data.outputDatasetTag = config.General.requestName\nconfig.Data.outLFNDirBase = '/store/user/tvami/HSCP'\n\nconfig.Site.storageSite = 'T2_HU_Budapest'\n","sub_path":"configs/4crabWprobQ.py","file_name":"4crabWprobQ.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"58761614","text":"import datetime\r\nimport mysql.connector\r\nfrom mysql.connector import Error\r\nimport elo\r\n\r\n\r\nclass Player(object):\r\n def __init__(self, rank, name, elo_rank):\r\n self.rank = rank\r\n self.name = name\r\n self.elo = elo_rank\r\n\r\n\r\nclass game_history(object):\r\n def __init__(self, opponent, score, elo_rank, date):\r\n self.opponent = opponent\r\n self.score = score\r\n self.elo = elo_rank\r\n self.date = date\r\n\r\n\r\ndef create_connection(db_file):\r\n \"\"\" create a database connection to the SQLite database\r\n specified by the db_file\r\n :param db_file: database file\r\n :return: Connection object or None\r\n \"\"\"\r\n try:\r\n conn = mysql.connector.connect(user='root', database=db_file, password='easy')\r\n if conn.is_connected():\r\n print('Connected to MySQL database')\r\n return conn\r\n\r\n except Error as e:\r\n print(e)\r\n\r\n return None\r\n\r\n\r\ndef add_new_user(conn, userNameIn, passwordIn):\r\n cur = conn.cursor()\r\n\r\n # check if user name is not taken\r\n cur.execute(\"SELECT player_name FROM users \\\r\n WHERE player_name='%s'\" % userNameIn)\r\n is_user_name_already_in_db = cur.fetchone()\r\n if is_user_name_already_in_db:\r\n print('User name: ', userNameIn, 'already existing, select another one')\r\n else:\r\n try:\r\n cur.execute(\"INSERT INTO users \\\r\n SET player_name='%s', password='%s'\" % (userNameIn, passwordIn))\r\n conn.commit()\r\n except Error as error:\r\n print(error)\r\n\r\n\r\ndef display_user_list(conn):\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT * FROM users\")\r\n rows = cursor.fetchall()\r\n\r\n print('Total Row(s):', cursor.rowcount)\r\n for row in rows:\r\n print(row)\r\n\r\n\r\ndef update_elo(conn, user_id, opponent_name, did_the_user_win):\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT elo FROM users WHERE \\\r\n player_name = '%s'\" % opponent_name)\r\n opponent_elo = cursor.fetchone()\r\n cursor.execute(\"SELECT elo FROM users WHERE \\\r\n id_usr = '%d'\" % user_id)\r\n user_elo = cursor.fetchone()\r\n\r\n expected_score = elo.expected(int(user_elo[0]), int(opponent_elo[0]))\r\n\r\n if did_the_user_win == 1:\r\n score = 1\r\n score_opponent = 0\r\n else:\r\n score = 0\r\n score_opponent = 1\r\n\r\n # update user elo\r\n updated_user_elo = round(elo.elo(int(user_elo[0]), expected_score, score, k=32))\r\n # update opponent elo, his expected score is 1 - expected_score\r\n updated_opponent_elo = round(elo.elo(int(opponent_elo[0]), 1 - expected_score, score_opponent, k=32))\r\n\r\n return updated_user_elo, updated_opponent_elo\r\n\r\n\r\ndef game_result_input(conn, user_id, opponent_name, did_the_user_win):\r\n cursor = conn.cursor()\r\n\r\n # update elo of the user and opponent\r\n updated_elo = update_elo(conn, user_id, opponent_name, did_the_user_win)\r\n\r\n if did_the_user_win == 1:\r\n score = 'W'\r\n score_opponent = 'L'\r\n else:\r\n score = 'L'\r\n score_opponent = 'W'\r\n\r\n now = datetime.datetime.now()\r\n # Add a row in user game_history\r\n cursor.execute(\"INSERT INTO game_history \\\r\n SET opponent='%s', id_usr='%d', score='%s', elo='%d', date='%s'\"\r\n % (opponent_name, user_id, score, updated_elo[0], now))\r\n # update user profile\r\n cursor.execute(\"Update users \\\r\n SET elo='%d' WHERE id_usr='%d'\"\r\n % (updated_elo[0], user_id))\r\n\r\n # Add a row in opponent game_history\r\n cursor.execute(\"INSERT INTO game_history \\\r\n SET opponent='%s', id_usr='%d', score='%s', elo='%d', date='%s'\"\r\n % (get_player_name_from_usr_id(conn, user_id), get_id_usr_from_player_name(conn, opponent_name),\r\n score_opponent, updated_elo[1], now))\r\n # update elo of the opponent\r\n cursor.execute(\"Update users \\\r\n SET elo='%d' WHERE player_name='%s'\"\r\n % (updated_elo[1], opponent_name))\r\n conn.commit()\r\n\r\n\r\ndef display_user_game_history(conn, user_id):\r\n cursor = conn.cursor()\r\n\r\n cursor.execute(\"SELECT opponent FROM game_history WHERE id_usr='%d' ORDER by date DESC\"\r\n % user_id)\r\n opponent = cursor.fetchall()\r\n cursor.execute(\"SELECT score FROM game_history WHERE id_usr='%d' ORDER by date DESC\"\r\n % user_id)\r\n score = cursor.fetchall()\r\n cursor.execute(\"SELECT elo FROM game_history WHERE id_usr='%d' ORDER by date DESC\"\r\n % user_id)\r\n elo_rank = cursor.fetchall()\r\n cursor.execute(\"SELECT date FROM game_history WHERE id_usr='%d' ORDER by date DESC\"\r\n % user_id)\r\n date = cursor.fetchall()\r\n\r\n cursor.execute(\"SELECT COUNT(id) FROM game_history WHERE id_usr='%d'\" % user_id)\r\n number_of_game = cursor.fetchone()[0]\r\n\r\n game_history_list = []\r\n for idx_game in range(number_of_game):\r\n game_history_list.append(game_history(opponent[idx_game][0], score[idx_game][0],\r\n elo_rank[idx_game][0], date[idx_game][0]))\r\n return game_history_list\r\n\r\n\r\ndef get_player_name_from_usr_id(conn, user_id):\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT player_name FROM users WHERE id_usr='%d'\"\r\n % user_id)\r\n user_name = cursor.fetchone()\r\n return user_name[0]\r\n\r\n\r\ndef get_id_usr_from_player_name(conn, player_name):\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT id_usr FROM users WHERE player_name ='%s'\"\r\n % player_name)\r\n opponent_id_usr = cursor.fetchone()\r\n return opponent_id_usr[0]\r\n\r\n\r\ndef get_all_users_and_elo(conn, logged_in_user_name):\r\n\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT COUNT(player_name) from users\")\r\n number_of_users = cursor.fetchone()[0]\r\n\r\n cursor.execute(\"SELECT player_name FROM users ORDER BY elo DESC\")\r\n Player_name = cursor.fetchall()\r\n cursor.execute(\"SELECT elo FROM users ORDER BY elo DESC\")\r\n Player_elo = cursor.fetchall()\r\n\r\n\r\n Player_list = []\r\n for nb_users in range(number_of_users):\r\n Player_list.append(Player(nb_users+1, Player_name[nb_users][0], Player_elo[nb_users][0]))\r\n\r\n return Player_list\r\n\r\n\r\ndef get_all_users_alph_order(conn, logged_in_user_name):\r\n\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT COUNT(player_name) from users \\\r\n WHERE player_name not like '%s'\" % logged_in_user_name)\r\n number_of_users = cursor.fetchone()[0]\r\n\r\n cursor.execute(\"select player_name from users WHERE\\\r\n player_name NOT LIKE '%s' ORDER BY player_name ASC\" % logged_in_user_name)\r\n Player_name = cursor.fetchall()\r\n cursor.execute(\"select player_name from users WHERE\\\r\n player_name NOT LIKE '%s' ORDER BY player_name ASC\" % logged_in_user_name)\r\n Player_elo = cursor.fetchall()\r\n\r\n\r\n Player_list = []\r\n for nb_users in range(number_of_users):\r\n Player_list.append(Player(nb_users + 1, Player_name[nb_users][0], Player_elo[nb_users][0]))\r\n\r\n return Player_list\r\n\r\n\r\ndef main():\r\n database = 'tischtenniz'\r\n\r\n testNewUser = 'Shinji'\r\n testNewPass = 'iLoveCheeseNaN'\r\n testNewUser1 = 'a'\r\n testNewPass1 = 'iLoveCheeseNaN'\r\n opponent_name = 'Shinji'\r\n did_the_user_win = 1\r\n user_id = 1\r\n\r\n # create a database connection\r\n conn = create_connection(database)\r\n Player_list = get_all_users(conn)\r\n display_user_game_history(conn, 12)\r\n return Player_list\r\n '''\r\n # input a new user\r\n add_new_user(conn, testNewUser, testNewPass)\r\n add_new_user(conn, testNewUser1, testNewPass1)\r\n\r\n # display full user list\r\n display_user_list(conn)\r\n\r\n ############################ ENTER GAME SCORE SECTION ###############################\r\n\r\n # input a new game resut\r\n game_result_input(conn, user_id, opponent_name, did_the_user_win)\r\n\r\n # display user history\r\n display_user_game_history(conn, user_id)\r\n'''\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"TischtenniZ/database_interface.py","file_name":"database_interface.py","file_ext":"py","file_size_in_byte":8103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"27016548","text":"\"\"\"\nCode to sort elements of dictionary by key and values\n\"\"\"\nimport collections\n\n# Lambda is one line anonymous function\ndef add_num(num1, num2):\n \"\"\"\n Adding two numbers\n :param num1:\n :param num2:\n :return:\n \"\"\"\n return num1 + num2\n\nsum_of_two_num = add_num(2, 3)\nprint(sum_of_two_num)\n\n# Lambda can be used here. Before : is arguments and after is the expression which is\n# evaluated and returned\nlamba_fun = lambda num1, num2: num1 + num2\nsum_of_two_num_using_lambda = lamba_fun(2, 3)\nprint(sum_of_two_num_using_lambda)\n\nrandom_dict = {'z': 8, 'a': 44, 'b': 88, 'e': 22, 'c': 909, 'd': 9}\n\n# Code to sort this dictionary based on key's value\n# Here lambda key_value: key_value[1] is the function assigned to key, based on\n# which dict will be sorted\nsorted_dict = sorted(random_dict.items(), key=lambda key_value: key_value[1])\nprint(collections.OrderedDict(sorted_dict))\n\n# Now sort based on key\nsorted_dict = sorted(random_dict.items(), key=lambda key_value: key_value[0])\nprint(collections.OrderedDict(sorted_dict))\n\n# Get key with lowest value\nmin_value_key = min(random_dict.items(), key=lambda key_value: key_value[1])\nprint(min_value_key)\n\n","sub_path":"python_code_samples/dict_sorting_and_lambda/dict_sort_and_lambda.py","file_name":"dict_sort_and_lambda.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124902170","text":"#!/usr/bin/env python\n\n# This file is inteded for the usage of the Thayer School of Engineering and the US Biathlon Team.\n# Within is outlined a data collection interface that utilizes the Raspberry Pi and a couple of Python open-source libraries.\n# Special thanks to the creators of paramiko and pyqtgraph, without them this project wouldn't have been possible.\n#\n# All code written by George Hito.\n# Currently only functional on OSX.\n\nimport signal\nimport time\nimport base64\nimport getpass\nimport os\nimport socket\nimport sys\nimport traceback\nimport errno\nfrom datetime import datetime\nfrom timeout import timeout\nfrom paramiko.py3compat import input\nfrom paramiko.py3compat import u\n\n# paramiko for ssh\nimport paramiko\ntry:\n import termios\n import tty\n has_termios = True\nexcept ImportError:\n has_termios = False\n\n# plotting and GUI\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom pyqtgraph.Qt import QtGui, QtCore, QtWidgets\nimport numpy as np\nimport pyqtgraph as pg\nglobal curve1, curve2, app\n\n# opencv for laser tracking\nimport cv2\nfrom processframe import ProcessFrame\n\n# set adc values as globals\n# these are lists that have each new value appended to them\nglobal adc_value1, adc_value2, ptr\nadc_value1 = [0]\nadc_value2 = [0]\nptr = 0\n\n# other globals for usage to start/stop actions in other threads\nglobal run_started\nrun_started = False\n\n# worker class for multithreading\nclass Worker(QRunnable):\n\tdef __init__(self, fn, *args, **kwargs):\n\t\tsuper(Worker, self).__init__()\n\t\tself.fn = fn\n\t\tself.args = args\n\t\tself.kwargs = kwargs\n\n\t@pyqtSlot()\n\tdef run(self):\n\t\t'''\n\t\tInitialise the runner function with passed self.args, self.kwargs.\n\t\t'''\n\t\tself.fn(*self.args, **self.kwargs)\n\n# wrapper for threadpool\nclass WorkerPool():\n\tdef __init__(self, *args, **kwargs):\n\t\tself.threadpool = QThreadPool()\n\n# connect to pi\ndef connectPi():\n\tglobal adc_value1, adc_value2, ptr, run_started, client, wifi\n\n\t# # first check if biathlon_rifle is current network\n\t# if \"biathlon_rifle\" in subprocess.check_output(\"iwgetid -r\"):\n\t# \tprint(\"Connected to rifle!\")\n\t# else:\n\t# \tprint(\"Please connect to the rifle.\")\n\t# \tsys.exit(1)\n\n\n\t# setup logging\n\tparamiko.util.log_to_file('demo_simple.log')\n\n\t# check if the biathlon rifle is within range\n\timport objc\n\n\tobjc.loadBundle('CoreWLAN',\n\t\t\t\tbundle_path = '/System/Library/Frameworks/CoreWLAN.framework',\n\t\t\t\tmodule_globals = globals())\n\n\tiface = CWInterface.interface()\n\n\tnetworks, error = iface.scanForNetworksWithName_error_('biathlon_rifle', None)\n\t\n\t# if no error, biathlon rifle is nearby\n\t# if str(error) == 'None':\n\t# \tprint('Biathlon rifle is nearby.')\n\t# else:\n\t# \tprint('Biathlon rifle is not nearby, please try and get closer to connect.')\n\t# \tsys.exit(2)\n\n\t# returns list of nearby networks\n\tnetwork_list = os.popen(\"/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport --scan | awk '{print $1}'\")\n\n\t# is rifle nearby? initialize to false.\n\trifle_nearby = False\n\n\twhile 1:\n\t\tline = network_list.readline()\n\t\tif line == 'biathlon_rifle\\n':\n\t\t\trifle_nearby = True\n\t\tif not line: \n\t\t\tbreak\n\n\t# if rifle is nearby, proceed\n\tif rifle_nearby == True:\n\t\tprint('Biathlon rifle is nearby.')\n\telse:\n\t\tprint('Biathlon rifle is not nearby, please try and get closer to connect.')\n\t\tsys.exit(2)\n\n\n\tnetwork = networks.anyObject()\n\n\t# if not currently connected to rifle, try to connect to it\n\t# returns currently connected wifi network\n\tcurrent_network = os.popen(\"/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk '/ SSID/ {print substr($0, index($0, $2))}'\")\n\t\n\t# check if we are currently connected to rifle, if not then try to connect to it\n\tconnected_to_rifle = False\n\twhile 1:\n\t\tline = current_network.readline()\n\t\tif line == 'biathlon_rifle\\n':\n\t\t\tconnected_to_rifle = True\n\t\tif not line: \n\t\t\tbreak\n\n\tif connected_to_rifle == False:\n\t\t# if no error, successfully connected to rifle\n\t\tsuccess, error = iface.associateToNetwork_password_error_(network, 'biathlon', None)\n\t\tif str(error) == 'None':\n\t\t\tprint('Successfully connected to rifle!')\n\t\telse:\n\t\t\tprint('Unable to connnect to rifle')\n\t\t\tsys.exit(2)\n\telse:\n\t\tprint('Already connected to rifle!')\n\t\n\n\n\t# Paramiko client configuration\n\tUseGSSAPI = paramiko.GSS_AUTH_AVAILABLE # enable \"gssapi-with-mic\" authentication, if supported by your python installation\n\tDoGSSAPIKeyExchange = paramiko.GSS_AUTH_AVAILABLE # enable \"gssapi-kex\" key exchange, if supported by your python installation\n\t# UseGSSAPI = False\n\t# DoGSSAPIKeyExchange = False\n\n\t# adc_value initialized for two channels\n\tadc_value1_temp = 0\n\tadc_value2_temp = 0\n\ttime = 0\n\n\t# now, connect and use paramiko Client to negotiate SSH2 across the connection\n\ttry:\n\t\t# get hostname\n\t\tusername = 'pi'\n\t\tpassword = 'biathlon'\n\t\thostname = '192.168.4.1'\n\t\tport = 22\n\t\t\n\t\tclient = paramiko.SSHClient()\n\t\tclient.load_system_host_keys()\n\t\tclient.set_missing_host_key_policy(paramiko.WarningPolicy())\n\t\tprint('*** Starting ssh...')\n\t\tif not UseGSSAPI and not DoGSSAPIKeyExchange:\n\t\t\tclient.connect(hostname, port, username, password)\n\t\telse:\n\t\t\ttry:\n\n\t\t\t\tclient.connect(hostname, port, username, gss_auth=UseGSSAPI,\n\t\t\t\t\tgss_kex=DoGSSAPIKeyExchange)\n\t\t\texcept Exception:\n\t\t\t\t# traceback.print_exc()\n\t\t\t\tpassword = getpass.getpass('Password for %s@%s: ' % (username, hostname))\n\t\t\t\tclient.connect(hostname, port, username, password)\n\n\t\tchan = client.invoke_shell()\n\t\t# print(repr(client.get_transport()))\n\t\tprint('*** Successfully started ssh!')\n\t\trun_started = True\n\n\t\t# send relevant messages to start adc reading and print to terminal\n\t\t# in the future this will be synchronized with animated graph\n\t\timport select\n\n\t\toldtty = termios.tcgetattr(sys.stdin)\n\t\ttry:\n\t\t\ttty.setraw(sys.stdin.fileno())\n\t\t\ttty.setcbreak(sys.stdin.fileno())\n\t\t\tchan.settimeout(0.0)\n\t\t\t# send command to Pi to trigger data collection and gather the results through ssh\n\t\t\tchan.send('python ~/biathlon/demo_readvoltage.py\\n')\n\t\t\twhile True:\n\t\t\t\tr, w, e = select.select([chan, sys.stdin], [], [])\n\t\t\t\tif chan in r:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tx = u(chan.recv(1024))\n\t\t\t\t\t\tif len(x) == 0:\n\t\t\t\t\t\t\tsys.stdout.write('\\r\\n*** EOF\\r\\n')\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t# save numbers once they start coming in, we assume both sensors are always connected\n\t\t\t\t\t\t# first check to see if both sensors are attached\n\t\t\t\t\t\t# zero attached\n\t\t\t\t\t\t# if len(x.split(' ')) == 2:\n\t\t\t\t\t\t# \tprint('No sensors attached!')\n\t\t\t\t\t\t# only one attached\n\t\t\t\t\t\tif len(x.split(' ')) == 3:\n\t\t\t\t\t\t\t# check which one is attached\n\t\t\t\t\t\t\tif x[:3] == 'Ch1':\n\t\t\t\t\t\t\t\tadc_value1_temp = float(x.split(' ')[1])\n\t\t\t\t\t\t\t\tadc_value1.append(adc_value1_temp)\n\t\t\t\t\t\t\telif x[:3] == 'Ch2':\n\t\t\t\t\t\t\t\tadc_value2_temp = float(x.split(' ')[1])\n\t\t\t\t\t\t\t\tadc_value2.append(adc_value2_temp)\n\t\t\t\t\t\t\tptr += 1\n\t\t\t\t\t\t\tprint(x + '\\r')\n\n\t\t\t\t\t\t# both attached\n\t\t\t\t\t\telif len(x.split(' ')) == 4:\n\t\t\t\t\t\t\tadc_value1_temp = float(x.split(' ')[1])\n\t\t\t\t\t\t\tadc_value1.append(adc_value1_temp)\n\t\t\t\t\t\t\tadc_value2_temp = float(x.split(' ')[3])\n\t\t\t\t\t\t\tadc_value2.append(adc_value2_temp)\n\t\t\t\t\t\t\tptr += 1\n\t\t\t\t\t\t\tprint(x + '\\r')\t\t\t\t\t\t\n\n\t\t\t\t\texcept socket.timeout:\n\t\t\t\t\t\tpass\n\t\t\t\tif sys.stdin in r:\n\t\t\t\t\tx = sys.stdin.read(1)\n\t\t\t\t\tif len(x) == 0:\n\t\t\t\t\t break\n\t\t\t\t\tchan.send(x)\n\t\t\t\t\tchan.close()\n\t\t\t\t\tclient.close()\n\n\t\tfinally:\n\t\t\ttermios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)\n\texcept Exception as e:\n\t\tprint('*** Caught exception: %s: %s' % (e.__class__, e))\n\t\ttraceback.print_exc()\n\t\ttry:\n\t\t\tclient.close()\n\t\texcept:\n\t\t\tpass\n\t\tsys.exit(1)\n\n# main graphics window\nclass MainWindow(QMainWindow):\n\tglobal window\n\tkeyPressed = QtCore.pyqtSignal()\n\tdef __init__(self, parent=None):\n\t\tsuper(MainWindow, self).__init__(parent)\n\t\tself.initUI()\n\n\tdef setFrame(self,frame):\n\t\tpixmap = QPixmap.fromImage(frame)\n\t\tself.label.setPixmap(pixmap)\n\t\n\tdef initUI(self):\n\t\tglobal app, adc1, adc2, curve1, curve2, ptr, window, video\n\n\t\t# define a top-level widget to hold everything\n\t\twindow = pg.GraphicsLayoutWidget()\n\t\twindow.setWindowTitle('Biathlon Team Data Processing')\n\n\t\t# init graphs in widget\n\t\tadc1 = window.addPlot(row=0,col=0,title=\"Hall Effect Sensor Voltage vs Time\", \n\t\t\tlabels={'left': 'Voltage (V)', 'bottom': 'Time (seconds)'})\n\t\tadc2 = window.addPlot(row=0,col=1,title=\"Force Sensor Voltage vs Time\",\n\t\t\tlabels={'left': 'Voltage (V)', 'bottom': 'Time (seconds)'})\n\n\t\t# antialiasing for better plots\n\t\tpg.setConfigOptions(antialias=True)\n\n\t\t# set downsampling and clipping to reduce drawing load\n\t\tadc1.setDownsampling(mode='peak')\n\t\tadc2.setDownsampling(mode='peak')\n\t\tadc1.setClipToView(True)\n\t\tadc2.setClipToView(True)\n\n\t\tadc1.setRange(xRange=[-100, 10], yRange=[-1,5])\n\t\tadc1.setLimits(xMax=10, yMax=5, yMin=-1)\n\t\tadc2.setRange(xRange=[-100, 10], yRange=[-1,5])\n\t\tadc2.setLimits(xMax=10, yMax=5, yMin=-1)\n\n\t\tcurve1 = adc1.plot(pen='y')\n\t\tcurve2 = adc2.plot(pen='y')\n\n\tdef beginGraphics(self):\n\t\tglobal app, adc1, adc2, curve1, curve2, ptr, window\n\n\t\t# updates plots in real-time and keeps the most recent values the focus\n\t\tdef update():\n\t\t\tglobal curve1, curve2, adc_value1, adc_value2, ptr\n\t\t\tcurve1.setData(adc_value1[:ptr])\n\t\t\tcurve1.setPos(-ptr, 0)\n\t\t\tcurve2.setData(adc_value2[:ptr])\n\t\t\tcurve2.setPos(-ptr, 0)\n\n\t\ttimer = QtCore.QTimer()\n\t\ttimer.timeout.connect(update)\n\t\ttimer.start(50)\n\n\t\t# Display the widget as a new window\n\t\twindow.show()\n\n\t\t# start the QT event loop\n\t\tapp.exec_()\n\n\tdef keyPressEvent(self, event):\n\t\tself.keyPressed.emit()\n\t\tif event.key() == Qt.Key_Escape:\n\t\t\tself.close()\n\n# handle ctrl+c elegantly\ndef sigint_handler(*args):\n \"\"\"Handler for the SIGINT signal.\"\"\"\n sys.stderr.write('\\r')\n QtGui.QApplication.quit()\n\n# use openCV to track a laser in a video stream\n# class Video_display(QMainWindow):\n# def __init__(self, parent=None):\n# super(Second, self).__init__(parent)\n# def video_thread():\n# \tglobal video_frame\n# \tcam = cv2.VideoCapture(0)\n\n# \twhile True:\n# \t\tret_val, img = cam.read()\n# \t\tcv2.imshow(\"my webcam\", img)\n\t\n\nclass Capture():\n\tdef __init__(self):\n\t\tself.capturing = False\n\t\t# CHANGE THIS TO SWITCH BETWEEN WEBCAM AND USB CAMERA\n\t\tself.c = cv2.VideoCapture(0)\n\n\tdef startCapture(self):\n\t\tprint(\"pressed start\")\n\t\tself.capturing = True\n\t\tcap = self.c\n\t\t# captures video and processes for laser point\n\t\tpf = ProcessFrame()\n\t\twhile(self.capturing):\n\t\t\tret, frame = cap.read()\n\n\t\t\tif ret == True:\n\t\t\t\t# Find the laser\n\t\t\t\tcenter = pf.find_laser(frame)\n\n\t\t\t\t# Find the targets\n\t\t\t\tcircles = pf.find_targets(frame)\n\n\t\t\t\t# check if found, if not then stop capture\n\t\t\t\tif circles is None:\n\t\t\t\t\tprint(\"No targets found.\")\n\t\t\t\t\tself.capturing = False\n\t\t\t\t\tbreak\n\n\t\t\t\t# Draw circles\n\t\t\t\tcircles = np.uint16(np.around(circles))\n\t\t\t\tfor i in circles[0,:]:\n\t\t\t\t\tcv2.circle(frame,(i[0],i[1]),i[2],(0,255,0),2) # Draw the outer circle\n\t\t\t\t\tcv2.circle(frame,(i[0],i[1]),2,(0,0,255),3) # Draw the center\n\n\t\t\t\t# Draw laser\n\t\t\t\tcv2.circle(frame, center, 6, (0, 255, 0), -1)\n\n\t\t\t\t# display to user\n\t\t\t\tcv2.namedWindow('Frame',cv2.WINDOW_AUTOSIZE)\n\t\t\t\tframe = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5) \n\t\t\t\tcv2.imshow('Frame', frame)\n\n\t\t\t\tif cv2.waitKey(25) & 0xFF == ord('q'): # Exit by pressing Q\n\t\t\t\t\tbreak\n\t\tcv2.destroyAllWindows()\n\n\tdef endCapture(self):\n\t\tprint (\"pressed End\")\n\t\tself.capturing = False\n\t\t# cv2.destroyAllWindows()\n\n\tdef quitCapture(self):\n\t\tprint (\"pressed Quit\")\n\t\tcap = self.c\n\t\tcv2.destroyAllWindows()\n\t\tcap.release()\n\t\tQtCore.QCoreApplication.quit()\n\nclass VideoWindow(QtWidgets.QWidget):\n\tdef __init__(self):\n\t\tQtWidgets.QWidget.__init__(self)\n\t\tself.setWindowTitle('Control Panel')\n\n\t\tself.capture = Capture()\n\t\tself.start_button = QtGui.QPushButton('Start',self)\n\t\tself.start_button.clicked.connect(self.capture.startCapture)\n\n\t\tself.end_button = QtGui.QPushButton('End',self)\n\t\tself.end_button.clicked.connect(self.capture.endCapture)\n\n\t\tself.quit_button = QtGui.QPushButton('Quit',self)\n\t\tself.quit_button.clicked.connect(self.capture.quitCapture)\n\n\t\tvbox = QtGui.QVBoxLayout(self)\n\t\tvbox.addWidget(self.start_button)\n\t\tvbox.addWidget(self.end_button)\n\t\tvbox.addWidget(self.quit_button)\n\n\t\tself.setLayout(vbox)\n\t\tself.setGeometry(100,100,200,200)\n\t\tself.show()\n\n\ndef main():\n\tglobal adc_value1, adc_value2, app\n\n\t# set up QT\n\tapp = QtGui.QApplication(sys.argv)\n\n\t# get current time to the microsecond, this will be used for syncing with pi\n\tstartTime = datetime.now()\n\tprint(startTime)\n\n\t# multithread graphics, video, and pi connections\n\twp = WorkerPool()\n\n\tdataWorker = Worker(connectPi)\n\twp.threadpool.start(dataWorker)\n\n\tmainwindow = MainWindow()\n\tvideo = VideoWindow()\n\n\t# handle ctrl+c\n\tsignal.signal(signal.SIGINT, sigint_handler)\n\ttimer = QTimer()\n\ttimer.start(50) # You may change this if you wish.\n\ttimer.timeout.connect(lambda: None) # Let the interpreter run each 50 ms.\n\n\tsys.exit(mainwindow.beginGraphics())\n\n\nif __name__ == '__main__':\n\timport sys\n\tmain()\n\n","sub_path":"read_adc.py","file_name":"read_adc.py","file_ext":"py","file_size_in_byte":12843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"556840089","text":"from __future__ import absolute_import, print_function, unicode_literals\nfrom builtins import dict, str\nfrom indra.statements import *\nfrom indra.util import unicode_strs\n\nev = Evidence(source_api='bel', pmid='12345', epistemics={'direct': True},\n text='This is the evidence.')\n\ndef test_mod_condition_from():\n jd = {'mod_type': 'phosphorylation', 'residue': 'S'}\n mc = ModCondition._from_json(jd)\n assert(mc.residue == 'S')\n assert(mc.mod_type == 'phosphorylation')\n assert(mc.position is None)\n\ndef test_agent_mod_condition():\n a = Agent('MAP2K1', mods=[ModCondition('phosphorylation', 'serine', 218),\n ModCondition('phosphorylation', 'serine', 222)])\n jd = a.to_json()\n jd2 = Agent._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_modification():\n stmt = Phosphorylation(Agent('a'), Agent('b'), 'S', evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_selfmodification():\n stmt = Autophosphorylation(Agent('a'), 'Y', '1234', evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_activation():\n stmt = Activation(Agent('a'), Agent('b'), 'kinase', evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_amount():\n stmt = IncreaseAmount(Agent('a'), Agent('b'), evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_active_form():\n stmt = ActiveForm(Agent('a', location='nucleus'), 'kinase', False,\n evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_complex():\n stmt = Complex([Agent('a'), Agent('b')], evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_translocation():\n stmt = Translocation(Agent('a'), 'cytoplasm', 'nucleus', evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_gap():\n stmt = Gap(Agent('a'), Agent('b'), evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_gef():\n stmt = Gef(Agent('a'), Agent('b'), evidence=[ev])\n jd = stmt.to_json()\n g = stmt.to_graph()\n jd2 = Statement._from_json(jd).to_json()\n assert(jd == jd2)\n\ndef test_supports():\n stmt1 = Gap(Agent('B'), Agent('B'), evidence=[ev])\n stmt2 = Gap(Agent('a'), Agent('b'), evidence=[ev])\n stmt1.supports = [stmt2]\n stmt2.supported_by = [stmt1]\n jd1 = stmt1.to_json()\n jd2 = stmt2.to_json()\n jds = [jd1, jd2]\n stmts = stmts_from_json(jds)\n assert(len(stmts[0].supports) == 1)\n assert(len(stmts[1].supported_by) == 1)\n assert(stmts[0].supports[0] == stmts[1])\n assert(stmts[1].supported_by[0] == stmts[0])\n jds2 = stmts_to_json(stmts)\n stmts2 = stmts_from_json(jds2)\n assert(len(stmts2[0].supports) == 1)\n assert(len(stmts2[1].supported_by) == 1)\n assert(stmts2[0].supports[0] == stmts2[1])\n assert(stmts2[1].supported_by[0] == stmts2[0])\n g = stmt1.to_graph()\n g = stmt2.to_graph()\n","sub_path":"indra/tests/test_statements_serialization.py","file_name":"test_statements_serialization.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"505636005","text":"import argparse\r\nimport logging\r\nfrom players_detection import DetectThePlayers\r\n\r\n\r\n\r\nclass Cli:\r\n\r\n def __init__(self):\r\n self.args = None\r\n logger = logging.getLogger(__name__)\r\n self.logger=logger\r\n\r\n\r\n def parse_arguments_advanced(self):\r\n \"\"\" Processing and storing the arguments of the program\r\n returns an argparse.Nampespace object, depicting and store the input arguments\r\n according to the defined flags\r\n \"\"\"\r\n self.logger.info(f\"parsing arguments\")\r\n parser = argparse.ArgumentParser(\r\n description=\"Script Description\"\r\n )\r\n parser.add_argument(\"-i\", \"--input\", required=True,help=\"path to input video\")\r\n self.args = parser.parse_args()\r\n\r\n def args_handel(self):\r\n \"\"\" The function handles the arguments \"\"\"\r\n video_path = self.args.input\r\n detection = DetectThePlayers(video_path,self.logger)\r\n detection.run()","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"272081688","text":"class Solution(object):\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n q=collections.deque()\n res=[]\n \n for index, val in enumerate(nums):\n if q and q[0]<=index-k: # if index not needed discard\n q.popleft()\n #print(q)\n \n while q and nums[q[-1]]=k: \n res.append(nums[q[0]])\n \n return res \n \n \n #Front of the queue keeps track of index which had maximum val at that index\n # rear of the queue keeps track of the index with max value\n \n \n \n","sub_path":"NovemberChallenge/SlidingWindowMaximum.py","file_name":"SlidingWindowMaximum.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"101916085","text":"import tensorflow as tf\nfrom tensorflow.keras import layers, activations, initializers, regularizers, constraints\nfrom tensorflow.keras.mixed_precision import global_policy\n\nfrom core.module import Module\nfrom nn.registry import rnn_registry\nfrom nn.typing import LSTMState\nfrom utility.tf_utils import assert_rank\n\n\nrnn_registry.register('lstm')(layers.LSTM)\n\n\nclass MLSTMCell(layers.Layer):\n def __init__(self,\n units,\n activation='tanh',\n recurrent_activation='sigmoid',\n use_bias=True,\n kernel_initializer='glorot_uniform',\n recurrent_initializer='orthogonal',\n bias_initializer='zeros',\n unit_forget_bias=True,\n use_ln=False,\n kernel_regularizer=None,\n recurrent_regularizer=None,\n bias_regularizer=None,\n kernel_constraint=None,\n recurrent_constraint=None,\n bias_constraint=None,\n dropout=0.,\n recurrent_dropout=0.,\n implementation=1,\n **kwargs):\n super().__init__(**kwargs)\n self.units = units\n self.activation = activations.get(activation)\n self.recurrent_activation = activations.get(recurrent_activation)\n self.use_bias = use_bias\n self.use_ln = use_ln\n\n self.kernel_initializer = initializers.get(kernel_initializer)\n self.recurrent_initializer = initializers.get(recurrent_initializer)\n self.bias_initializer = initializers.get(bias_initializer)\n self.unit_forget_bias = unit_forget_bias\n\n self.kernel_regularizer = regularizers.get(kernel_regularizer)\n self.recurrent_regularizer = regularizers.get(recurrent_regularizer)\n self.bias_regularizer = regularizers.get(bias_regularizer)\n\n self.kernel_constraint = constraints.get(kernel_constraint)\n self.recurrent_constraint = constraints.get(recurrent_constraint)\n self.bias_constraint = constraints.get(bias_constraint)\n\n self.state_size = LSTMState(h=self.units, c=self.units)\n self.output_size = self.units\n\n def build(self, input_shapes):\n input_dim = input_shapes[0][-1]\n self.kernel = self.add_weight(\n shape=(input_dim, self.units * 4),\n name='kernel',\n initializer=self.kernel_initializer,\n regularizer=self.kernel_regularizer,\n constraint=self.kernel_constraint)\n self.recurrent_kernel = self.add_weight(\n shape=(self.units, self.units * 4),\n name='recurrent_kernel',\n initializer=self.recurrent_initializer,\n regularizer=self.recurrent_regularizer,\n constraint=self.recurrent_constraint)\n\n if self.use_bias:\n if self.unit_forget_bias:\n def bias_initializer(_, *args, **kwargs):\n return tf.concat([\n self.bias_initializer((self.units,), *args, **kwargs),\n initializers.Ones()((self.units,), *args, **kwargs),\n self.bias_initializer((self.units * 2,), *args, **kwargs),\n ], -1)\n else:\n bias_initializer = self.bias_initializer\n self.bias = self.add_weight(\n shape=(self.units * 4,),\n name='bias',\n initializer=bias_initializer,\n regularizer=self.bias_regularizer,\n constraint=self.bias_constraint)\n else:\n self.bias = None\n\n if self.use_ln:\n self.x_ln = layers.LayerNormalization(name='x_ln')\n self.h_ln = layers.LayerNormalization(name='h_ln')\n self.c_ln = layers.LayerNormalization(name='c_ln')\n else:\n self.x_ln = lambda x: x\n self.h_ln = lambda x: x\n self.c_ln = lambda x: x\n\n def call(self, x, states):\n x, mask = tf.nest.flatten(x)\n assert_rank([x, mask], 2)\n h, c = states\n if mask is not None:\n h = h * mask\n c = c * mask\n \n x = self.x_ln(tf.matmul(x, self.kernel)) + self.h_ln(tf.matmul(h, self.recurrent_kernel))\n if self.use_bias:\n x = tf.nn.bias_add(x, self.bias)\n i, f, c_, o = tf.split(x, 4, 1)\n i, f, o = self.recurrent_activation(i), self.recurrent_activation(f), self.recurrent_activation(o)\n c_ = self.activation(c_)\n c = f * c + i * c_\n # following OpenAI's baselines, we perform layer normalization on c\n h = o * self.activation(self.c_ln(c))\n \n return h, LSTMState(h, c)\n \n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n state_size = self.state_size\n if inputs is not None:\n assert batch_size is None or batch_size == tf.shape(inputs)[0]\n batch_size = tf.shape(inputs)[0]\n if dtype is None:\n dtype = global_policy().compute_dtype\n return LSTMState(\n h=tf.zeros([batch_size, state_size[0]], dtype),\n c=tf.zeros([batch_size, state_size[1]], dtype))\n\n\n@rnn_registry.register('mlstm')\nclass MLSTM(Module):\n def __init__(self, name='mlstm', **config):\n super().__init__(name=name)\n config = config.copy()\n self._state_mask = config.pop('state_mask', True)\n cell = MLSTMCell(**config)\n self._rnn = layers.RNN(cell, return_sequences=True, return_state=True)\n self.state_type = LSTMState\n \n def call(self, x, state, mask, additional_input=[]):\n xs = [x] + additional_input\n mask = tf.expand_dims(mask, axis=-1)\n assert_rank(xs + [mask], 3)\n if not self._state_mask:\n # mask out inputs\n for i, v in enumerate(xs):\n xs[i] *= tf.cast(mask, v.dtype)\n x = tf.concat(xs, axis=-1) if len(xs) > 1 else xs[0]\n if not mask.dtype.is_compatible_with(global_policy().compute_dtype):\n mask = tf.cast(mask, global_policy().compute_dtype)\n x = self._rnn((x, mask), initial_state=state)\n x, state = x[0], LSTMState(*x[1:])\n return x, state\n\n def reset_states(self, states=None):\n self._rnn.reset_states(states)\n\n def get_initial_state(self, inputs=None, batch_size=None, dtype=None):\n if inputs is None:\n assert batch_size is not None\n inputs = tf.zeros([batch_size, 1, 1])\n return LSTMState(*self._rnn.cell.get_initial_state(inputs, dtype=dtype))\n\n @property\n def state_size(self):\n return self._rnn.cell.state_size\n\n @property\n def state_keys(self):\n return LSTMState(*LSTMState._fields)\n\n\nif __name__ == '__main__':\n from utility.timer import timeit\n # inputs\n shape = (32, 16, 512)\n x0 = tf.random.normal(shape)\n m = tf.random.uniform(shape[:2], 0, 2, dtype=tf.int32)\n em = tf.cast(m[..., None], tf.float32)\n run_times = 1000\n assert x0.shape.ndims == em.shape.ndims\n # keras lstm\n c = tf.keras.layers.LSTMCell(512)\n l = tf.keras.layers.RNN(c, return_sequences=True, return_state=True)\n opt = tf.keras.optimizers.Adam(5e-5)\n lv = l.variables\n\n def keras_lstm_call():\n for _ in range(run_times):\n with tf.GradientTape() as tape:\n x = l(x0, initial_state=None)\n x, s = x[0], x[1:]\n y = tf.ones_like(x)\n loss = tf.reduce_mean((y-x)**2)\n gs = tape.gradient(loss, lv)\n opt.apply_gradients(zip(gs, lv))\n\n timeit(keras_lstm_call, to_print=True)\n\n # custom lstm\n c = MLSTMCell(512)\n l = tf.keras.layers.RNN(c, return_sequences=True, return_state=True)\n opt = tf.keras.optimizers.Adam(5e-5)\n\n def custom_lstm_cell_call():\n for _ in range(run_times):\n with tf.GradientTape() as tape:\n x = l((x0, em), initial_state=None)\n x, s = x[0], x[1:]\n y = tf.ones_like(x)\n loss = tf.reduce_mean((y-x)**2)\n gs = tape.gradient(loss, lv)\n opt.apply_gradients(zip(gs, lv))\n \n timeit(custom_lstm_cell_call, to_print=True)\n\n l = MLSTM({'units': 512})\n opt = tf.keras.optimizers.Adam(5e-5)\n\n def custom_lstm_call():\n for _ in range(run_times):\n with tf.GradientTape() as tape:\n x, s = l(x0, None, m)\n y = tf.ones_like(x)\n loss = tf.reduce_mean((y-x)**2)\n gs = tape.gradient(loss, lv)\n opt.apply_gradients(zip(gs, lv))\n \n timeit(custom_lstm_call, to_print=True)\n\n c = MLSTMCell(512, use_ln=True)\n l = tf.keras.layers.RNN(c, return_sequences=True, return_state=True)\n opt = tf.keras.optimizers.Adam(5e-5)\n\n def custom_lstmln_call():\n for _ in range(run_times):\n with tf.GradientTape() as tape:\n x = l((x0, em), initial_state=None)\n x, s = x[0], x[1:]\n y = tf.ones_like(x)\n loss = tf.reduce_mean((y-x)**2)\n gs = tape.gradient(loss, lv)\n opt.apply_gradients(zip(gs, lv))\n \n timeit(custom_lstmln_call, to_print=True)\n\n","sub_path":"nn/rnns/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":9245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"234743966","text":"from __future__ import division\nfrom Compression_Gabor import mu_out_N\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pywt\n\n\n\n\n\ndef reconstruct_wavelet(list,mu,f,wvlt):\n # evaluate error from reconstructing the signal from the N highest coefficients\n\n L = len(f)\n listFlat = np.array([item for sublist in list for item in sublist])\n N = (abs(listFlat) >= mu).sum()\n C = [np.where(abs(sublist) maxHeadingLevel:\n maxHeadingLevel = headingLevel\n else: # found plain text\n classic = (prevHeadingLevel == 1)\n prevHeadingLevel = 0\n if not classic:\n break\n if prevHeadingLevel == 1 or maxHeadingLevel < 2:\n classic = False\n return classic\n\n\n# Returns True if the file shows a classic erroneous pattern for tN or tQ files.\n# Where the translator has marked note titles (or questions) with 2-or-more level heading (which is incorrect)\n# and not marked the notes with a heading (which is correct).\n# Requirements for classic pattern:\n# The first line is a heading.\n# Headings alternate with plain text lines.\n# At least one of the headings is level 2 or higher (has 2 or more hash marks).\n# A plain text line follows the last heading.\n# Blank lines may occur anywhere.\ndef classic_pattern2(mdpath):\n fp = io.open(mdpath, \"tr\", 1, encoding=\"utf-8\")\n lines = fp.readlines()\n fp.close()\n classic = True\n prevHeadingLevel = 0\n maxHeadingLevel = 0\n\n for line in lines:\n if len(line.strip()) == 0:\n continue\n if heading_re.match(line): # we found a heading\n headingLevel = line.count('#', 0, 5)\n if prevHeadingLevel > 0:\n classic = False\n elif headingLevel > maxHeadingLevel:\n maxHeadingLevel = headingLevel\n prevHeadingLevel = headingLevel\n else: # we found a text line\n if prevHeadingLevel == 0:\n classic = False\n prevHeadingLevel = 0\n if not classic:\n break\n if maxHeadingLevel < 2:\n classic = False\n return classic \n \n\n# Converts the text a whole file at a time.\n# Uses wholestring, newstring[0]\ndef convertWholeFile(mdpath):\n global nChanged\n\n# found = classic_pattern(mdpath)\n input = io.open(mdpath, \"tr\", 1, encoding=\"utf-8-sig\")\n alltext = input.read()\n found = wholestring.search(alltext)\n if found:\n input = io.open(mdpath, \"tr\", 1, encoding=\"utf-8-sig\")\n alltext = input.read()\n input.close()\n if yes_backup:\n bakpath = mdpath + \".orig\"\n if not os.path.isfile(bakpath):\n os.rename(mdpath, bakpath)\n output = io.open(mdpath, \"tw\", buffering=1, encoding='utf-8', newline='\\n')\n \n # Use a loop for multiple replacements per file\n while found:\n output.write(alltext[0:found.start()] + newstring[0])\n alltext = alltext[found.end():]\n found = wholestring.search(alltext)\n output.write(alltext)\n output.close()\n sys.stdout.write(\"Converted \" + shortname(mdpath) + \"\\n\")\n nChanged += 1 \n\nsub_re = re.compile('figs-questions?', re.UNICODE)\n#sub_re = re.compile(r' *', re.UNICODE)\n#sub_re = re.compile(r'', re.UNICODE)\n#sub_re = re.compile(r'', re.UNICODE)\n#sub_re = re.compile(r'& nbsp;', re.UNICODE)\n#sub_re = re.compile(r'rc://en/', re.UNICODE)\n#sub_re = re.compile(r'[Ll]ih?at[\\s]*\\:+[\\s]*\\n+[\\s]*\\[\\[', re.UNICODE)\n#sub_re = re.compile(r'# +[\\*]+(.*)[\\*]+', re.UNICODE)\nreplacement = 'figs-rquestion'\n\n# Stream edit the file by a simple, regular expression substitution\n# To do only one substitution per file, change the count argument to re.sub(), below.\ndef convertFileBySub(path):\n global nChanged\n input = io.open(path, \"tr\", 1, encoding=\"utf-8\")\n alltext = input.read()\n input.close()\n found = sub_re.search(alltext)\n if found:\n if yes_backup:\n bakpath = path + \".orig\"\n if not os.path.isfile(bakpath):\n os.rename(path, bakpath)\n \n output = io.open(path, \"tw\", buffering=1, encoding='utf-8', newline='\\n')\n output.write( re.sub(sub_re, replacement, alltext, count=0) )\n output.close()\n sys.stdout.write(\"Converted \" + shortname(path) + \"\\n\")\n nChanged += 1 \n\ndef convertFile(path):\n convertFileByLines(path)\n# convertWholeFile(path)\n# convertFileBySub(path)\n\n\n# Recursive routine to convert all files under the specified folder\ndef convertFolder(folder):\n global nChanged\n global max_changes\n if nChanged >= max_changes:\n return\n sys.stdout.write(shortname(folder) + '\\n')\n for entry in os.listdir(folder):\n if entry[0] != '.':\n path = os.path.join(folder, entry)\n if os.path.isdir(path):\n convertFolder(path)\n elif filename_re.match(entry):\n convertFile(path)\n if nChanged >= max_changes:\n break\n\n# Processes all .txt files in specified directory, one at a time\nif __name__ == \"__main__\":\n if len(sys.argv) < 2 or sys.argv[1] == 'hard-coded-path':\n path = r'E:\\DCS\\Spanish\\es-419_obs-tn\\content'\n else:\n path = sys.argv[1]\n\n if path and os.path.isdir(path):\n convertFolder(path)\n sys.stdout.write(\"Done. Changed \" + str(nChanged) + \" files.\\n\")\n elif os.path.isfile(path):\n convertFile(path)\n sys.stdout.write(\"Done. Changed \" + str(nChanged) + \" files.\\n\")\n else:\n sys.stderr.write(\"Usage: python streamEdit.py \\n Use . for current folder.\\n\")\n","sub_path":"md/streamEdit.py","file_name":"streamEdit.py","file_ext":"py","file_size_in_byte":9934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"58302635","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\nimport numpy as np\nimport tensorflow as tf\nimport copy\nfrom sklearn import preprocessing\nimport datetime\nimport pickle\nimport os.path\n\n\n# In[ ]:\n\n\ndef sma(data, window):\n \"\"\"\n Calculates Simple Moving Average\n http://fxtrade.oanda.com/learn/forex-indicators/simple-moving-average\n \"\"\"\n if len(data) < window:\n return None\n return sum(data[-window:]) / float(window)\n\ndef get_ema(data, window):\n if len(data) < 2 * window:\n raise ValueError(\"data is too short\")\n c = 2.0 / (window + 1)\n current_ema = sma(data[-window*2:-window], window)\n for value in data[-window:]:\n current_ema = (c * value) + ((1 - c) * current_ema)\n return current_ema\n\n\n# In[ ]:\n\n\nclass NetAttributes:\n def __init__(self, n_neurons = 100, \n learning_rate = 0.003, \n num_layers = 1,\n rnn_type = 2,\n n_repeats = 2):\n self.n_neurons = n_neurons;\n self.learning_rate = learning_rate;\n self.num_layers = num_layers;\n self.rnn_type = rnn_type;\n self.n_repeats = n_repeats\n self.n_steps = None\n self.n_inputs = None\n self.n_outputs = 1\n \n def set_input_dimension(self, n_steps, n_inputs):\n self.n_steps = n_steps\n self.n_inputs = n_inputs\n\n\n# In[ ]:\n\n\nclass NetStates:\n def __init__(self):\n self.prediction_states = None\n self.training_states = None\n \n\n\n# In[ ]:\n\n\nclass StatefulLstmModel:\n def __init__(self,\n n_neurons=100,\n learning_rate=0.002,\n num_layers=2,\n rnn_type=1,\n n_repeats=30):\n\n self.net_attributes = NetAttributes(n_neurons,\n learning_rate,\n num_layers,\n rnn_type,\n n_repeats)\n self.net_states = NetStates()\n self.model_initialized = False\n self.sess = None\n \n def __del__(self):\n if self.sess != None:\n self.sess.close()\n \n def get_batch(self, seq_index, data_train_input, data_train_output):\n X_batch = data_train_input[seq_index:seq_index+1]\n y_batch = data_train_output[seq_index:seq_index+1]\n return X_batch, y_batch\n \n \n def initialize_layers(self):\n layers = None\n net_attributes = self.net_attributes\n if net_attributes.rnn_type == 0:\n layers = [tf.nn.rnn_cell.BasicLSTMCell(net_attributes.n_neurons) \n for _ in range(net_attributes.num_layers)]\n elif net_attributes.rnn_type == 1:\n layers = [tf.nn.rnn_cell.LSTMCell(net_attributes.n_neurons, use_peepholes=False) \n for _ in range(net_attributes.num_layers)]\n elif net_attributes.rnn_type == 2:\n layers = [tf.nn.rnn_cell.LSTMCell(net_attributes.n_neurons, use_peepholes=True) \n for _ in range(net_attributes.num_layers)]\n else:\n print(\"WRONG\")\n return layers\n \n def reset_graph(self, seed=42):\n tf.reset_default_graph()\n tf.set_random_seed(seed)\n np.random.seed(seed)\n \n def create_model(self):\n net_attributes = self.net_attributes\n self.X = tf.placeholder(tf.float32, [None, net_attributes.n_steps, net_attributes.n_inputs])\n self.y = tf.placeholder(tf.float32, [None, net_attributes.n_steps, net_attributes.n_outputs])\n layers = self.initialize_layers()\n cell = tf.nn.rnn_cell.MultiRNNCell(layers)\n self.init_state = tf.placeholder(tf.float32, [net_attributes.num_layers, 2, 1, net_attributes.n_neurons])\n \n state_per_layer_list = tf.unstack(self.init_state, axis=0)\n rnn_tuple_state = tuple(\n [tf.nn.rnn_cell.LSTMStateTuple(state_per_layer_list[idx][0], state_per_layer_list[idx][1])\n for idx in range(net_attributes.num_layers)]\n )\n \n rnn_outputs, self.new_states = tf.nn.dynamic_rnn(cell, self.X, dtype=tf.float32, \n initial_state=rnn_tuple_state)\n \n stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, net_attributes.n_neurons])\n stacked_outputs = tf.layers.dense(stacked_rnn_outputs, net_attributes.n_outputs)\n self.outputs = tf.reshape(stacked_outputs, [-1, net_attributes.n_steps, net_attributes.n_outputs])\n \n self.loss = tf.reduce_mean(tf.square(self.outputs - self.y))\n optimizer = tf.train.AdamOptimizer(learning_rate=net_attributes.learning_rate)\n self.training_op = optimizer.minimize(self.loss)\n\n self.init = tf.global_variables_initializer()\n self.model_initialized = True\n \n # train the model, input is the training data for one cycle\n # input is in the shape: [days, steps, features], the features are \n # 1. diff, 2. volume. 3. timesteps.\n def fit(self, data_train_input, data_train_output, prediction_period):\n net_attributes = self.net_attributes\n net_states = self.net_states\n n_inputs = data_train_input.shape[2]\n n_steps = data_train_input.shape[1]\n\n net_attributes.set_input_dimension(n_steps, n_inputs)\n batch_size = 1\n days = data_train_input.shape[0]\n \n self.reset_graph()\n self.create_model()\n my_loss_train_list = []\n sess = tf.Session()\n # TODO: load from file.\n\n self.init.run(session=sess)\n # if this is the first time of fit?\n if self.net_states.training_states == None:\n init_states = np.zeros((net_attributes.num_layers, 2, 1, net_attributes.n_neurons))\n else:\n init_states = self.net_states.training_states\n \n for repeat in range(net_attributes.n_repeats):\n rnn_states = copy.deepcopy(init_states)\n for seq in range(days):\n X_batch, y_batch = self.get_batch(seq, data_train_input, data_train_output)\n feed_dict = {\n self.X: X_batch,\n self.y: y_batch,\n self.init_state: rnn_states}\n my_op, rnn_states, my_loss_train, my_outputs = sess.run([self.training_op, \n self.new_states, \n self.loss, \n self.outputs], feed_dict=feed_dict)\n\n my_loss_train_list.append(my_loss_train)\n # last repeat , remember the sates\n if seq+1 == prediction_period and repeat == net_attributes.n_repeats-1:\n # next training loop starts from here\n training_states = copy.deepcopy(rnn_states)\n my_loss_train_avg = sum(my_loss_train_list) / len(my_loss_train_list)\n\n print(\"{} repeat={} training finished, training MSE={}\".format(\n datetime.datetime.now().time(),\n repeat, my_loss_train_avg))\n \n self.net_states.training_states = training_states\n self.net_states.prediction_states = rnn_states\n self.sess = sess\n return\n \n def predict_base(self, data_test_input, data_test_output=None):\n net_attributes = self.net_attributes\n net_states = self.net_states\n days = data_test_input.shape[0]\n \n rnn_states = copy.deepcopy(net_states.prediction_states)\n #X, y, init_state, init, training_op, new_states, loss, outputs = self.create_model()\n sess = self.sess\n \n my_loss_test_list = []\n input_shape = data_test_input.shape\n outputs_all_days = np.zeros((input_shape[0], input_shape[1], 1))\n for seq in range(days):\n if data_test_output is None:\n feed_dict = {\n self.X: data_test_input[seq:seq+1],\n self.init_state: rnn_states,\n }\n\n rnn_states, my_outputs = sess.run([self.new_states, self.outputs], feed_dict=feed_dict)\n else:\n feed_dict = {\n self.X: data_test_input[seq:seq+1],\n self.y: data_test_output[seq:seq+1],\n self.init_state: rnn_states,\n }\n\n rnn_states, my_outputs, my_loss_test = sess.run([self.new_states, \n self.outputs, self.loss], feed_dict=feed_dict)\n print(\"Predicting seq:{} testing MSE: {}\".format(seq, my_loss_test))\n outputs_all_days[seq] = my_outputs\n \n \n return outputs_all_days\n \n def predict(self, data_test_input):\n return self.predict_base(data_test_input)\n \n def predict_and_verify(self, data_test_input, data_test_output):\n return self.predict_base(data_test_input, data_test_output)\n \n def get_attributes_filename(self, path):\n if path[-1] != '/':\n path += '/'\n return path + 'net_attributes.pkl'\n \n def get_path(self, path, date):\n return os.path.join(path, date)\n\n \n def get_states_filename(self, path, date):\n return os.path.join(self.get_path(path, date), 'net_states.pkl')\n \n def get_model_filename(self, path, date):\n return os.path.join(self.get_path(path, date),'tf_session.ckpt')\n \n def save(self, path, date):\n saver = tf.train.Saver()\n save_path = saver.save(self.sess, self.get_model_filename(path, date))\n with open(self.get_attributes_filename(path), 'wb') as f:\n # Pickle the 'data' dictionary using the highest protocol available.\n pickle.dump(self.net_attributes, f, pickle.HIGHEST_PROTOCOL)\n with open(self.get_states_filename(path, date), 'wb') as f:\n pickle.dump(self.net_states, f, pickle.HIGHEST_PROTOCOL)\n print(\"Model saved in path: %s\" % path)\n \n \n def load(self, path, date):\n # TODO: if date is none, load the latest.\n \n # restore hyper-params\n with open(self.get_attributes_filename(path), 'rb') as f:\n self.net_attributes = pickle.load(f)\n\n # restore states\n with open(self.get_states_filename(path, date), 'rb') as f:\n self.net_states = pickle.load(f)\n \n # 2. restore graph\n if self.model_initialized == False:\n self.reset_graph()\n self.create_model()\n \n # 3. restore session\n saver = tf.train.Saver()\n self.sess = tf.Session()\n saver.restore(self.sess, self.get_model_filename(path, date))\n print(\"Model restored.\")\n\n\n# In[ ]:\n\n\nclass TimeFormat:\n NONE = 0\n DAY = 1\n WEEK = 2\n\nclass DataManipulator:\n def __init__(self, n_learning_days,\n n_prediction_days, beta, ema, time_format, volume_input, use_centralized_bid, \n split_daily_data, n_training_days):\n self.n_learning_days = n_learning_days\n self.n_prediction_days = n_prediction_days\n self.beta = beta\n self.ema = ema\n self.time_format = time_format\n self.volume_input = volume_input\n self.use_centralized_bid = use_centralized_bid\n self.split_daily_data = split_daily_data\n self.n_training_days = n_training_days\n self.last_learning_date = None\n self.next_prediction_seq = None\n self.next_learning_seq = None\n \n if split_daily_data == True:\n self.n_learning_seqs = self.n_learning_days * 2\n self.n_prediction_seqs = self.n_prediction_days * 2\n else:\n self.n_learning_seqs = self.n_learning_days\n self.n_prediction_seqs = self.n_prediction_days\n \n self.scaler_input = None\n self.scaler_output = None\n \n def update(self, next_prediction_seq, last_learning_date):\n assert(last_learning_date != None)\n print(\"updating, next_prediction_seq={}, last_learning_date={}\".format(next_prediction_seq, last_learning_date))\n self.next_prediction_seq = next_prediction_seq\n self.next_learning_seq = next_prediction_seq - self.n_learning_seqs\n self.last_learning_date = last_learning_date\n \n def volume_transform(self, volume_series):\n # all the volumes must bigger than 0\n assert(np.all(volume_series>=0))\n return np.log(volume_series.astype('float')+1)\n\n def inverse_transform_output(self, scaled_outputs):\n ori_shape = scaled_outputs.shape\n outputs_reshaped = scaled_outputs.reshape((ori_shape[0]*ori_shape[1], \n 1))\n #outputs = np.exp(self.scaler_output.inverse_transform(outputs_reshaped)) - 1\n outputs = self.scaler_output.inverse_transform(outputs_reshaped)\n return outputs.reshape(ori_shape)\n \n def transform(self, data, n_inputs, n_outputs):\n input_scaled = self.transform_input(data[:,:,:n_inputs])\n output_scaled = self.transform_output(data[:,:,-n_outputs:])\n return input_scaled, output_scaled\n \n def transform_input(self, data_input):\n return self.transform_helper(self.scaler_input, data_input)\n \n def transform_output(self, data_output):\n return self.transform_helper(self.scaler_output, data_output)\n \n def transform_helper(self, scaler, data):\n shape = data.shape\n data = data.reshape(shape[0]*shape[1],shape[2])\n data_scaled = scaler.transform(data)\n return data_scaled.reshape(shape)\n \n # do fit and transform at same time\n def fit_transform(self, data_all, n_inputs, n_outputs):\n orig_shape = data_all.shape\n data_train_reshape = data_all.astype('float').reshape((orig_shape[0] * orig_shape[1], orig_shape[2]))\n \n self.scaler_input = preprocessing.MinMaxScaler().fit(data_train_reshape[:,:n_inputs])\n data_train_input_scaled = self.scaler_input.transform(data_train_reshape[:,:n_inputs])\n \n # the invalid step, we change it to zero!\n data_train_input_scaled[~np.any(data_train_reshape, axis=1)] = 0\n data_train_input = data_train_input_scaled.reshape(orig_shape[0], orig_shape[1], n_inputs)\n \n self.scaler_output = preprocessing.MinMaxScaler().fit(data_train_reshape[:,-n_outputs:])\n data_train_output_scaled = self.scaler_output.transform(data_train_reshape[:,-n_outputs:])\n # the invalid step, we change it to zero!\n data_train_output_scaled[~np.any(data_train_reshape, axis=1)] = 0\n data_train_output = data_train_output_scaled.reshape(orig_shape[0], orig_shape[1], n_outputs)\n \n return data_train_input, data_train_output\n\n # to purge data based on parameters like time_input, split_daily_data, etc.\n def purge_data(self, input_path, stock_index):\n # load numpy file\n npy_file_name = input_path + \"/ema{}_beta{}_{}.npy\".format(self.ema, self.beta, stock_index)\n input_np_data = np.load(npy_file_name, allow_pickle=True)\n \n # date list\n date_list = []\n for i in range(self.n_training_days): \n date = input_np_data[i][0][5].date().strftime(\"%y%m%d\")\n date_list.append(date_list)\n \n \n # check if we have days more than training period\n assert(input_np_data.shape[0] >= self.n_training_days)\n # the diff is the mandatory\n input_columns = [2]\n \n time_format = self.time_format\n \n if time_format == TimeFormat.DAY:\n input_columns += [0]\n elif time_format == TimeFormat.WEEK:\n input_columns += [1]\n \n if self.volume_input == 1:\n input_columns += [3]\n \n output_columns = [4]\n timestamp_column = [5]\n price_column = [6]\n input_np_data = input_np_data[:,:,input_columns + output_columns + timestamp_column + price_column]\n \n # we must tranform the volume for it is too big.\n if self.volume_input == 1:\n input_np_data[:,:,-4] = self.volume_transform(input_np_data[:,:,-4])\n \n if self.use_centralized_bid == 0:\n # remove all the rows for centralized bid. it should be from 9.01 to 17.24, which is 516-12=504 steps\n input_np_data = input_np_data[:,7:-5,:]\n \n shape = input_np_data.shape\n n_training_sequences = self.n_training_days\n if self.split_daily_data == 1:\n assert(shape[1] % 2 == 0)\n input_np_data = input_np_data.reshape((shape[0]*2, \n int(shape[1]/2), \n shape[2]))\n # get the first date and last date\n n_training_sequences *= 2\n \n return input_np_data, n_training_sequences, input_columns\n \n def prep_training_data(self, input_path, stock_index):\n input_np_data, n_training_sequences, input_columns = self.purge_data(input_path, stock_index)\n # to scale the data, but not the timestamp and price\n data_train_input, data_train_output = self.fit_transform(input_np_data[:n_training_sequences,:,:-2], len(input_columns), 1)\n return data_train_input, data_train_output, input_np_data[:n_training_sequences,:,-2], input_np_data[:n_training_sequences,:,-1]\n \n def prep_testing_data(self, input_path, stock_index):\n input_np_data, n_training_sequences, input_columns = self.purge_data(input_path, stock_index)\n test_start_seq = self.next_prediction_seq - self.n_learning_seqs\n data_test_input, data_test_output = self.transform(input_np_data[test_start_seq:,:,:-2], len(input_columns), 1)\n return data_test_input, data_test_output, input_np_data[test_start_seq:,:,-2], input_np_data[test_start_seq:,:,-1]\n \n\n\n# In[ ]:\n\n\nimport numpy as np\nfrom pathlib import Path\nimport pandas as pd\nimport GPy\nimport GPyOpt\n\nclass ValueModel:\n mixed_domain = [{'name': 'n_neurons', 'type': 'discrete', 'domain': tuple(range(20,160,20))},\n {'name': 'learning_rate', 'type': 'discrete', 'domain': (0.001,0.002,0.003,0.004)},\n {'name': 'num_layers', 'type': 'discrete', 'domain': (1,2,3,4)},\n {'name': 'rnn_type', 'type': 'discrete', 'domain': (0,1,2)},\n {'name': 'learning_period', 'type': 'discrete', 'domain': (10,20,30,40)},\n {'name': 'prediction_period', 'type': 'discrete', 'domain': (1,2,5,10)},\n {'name': 'n_repeats', 'type': 'discrete', 'domain': (3,5,10,20,30,40)},\n {'name': 'beta', 'type': 'discrete', 'domain': (99,)},\n {'name': 'ema', 'type': 'discrete', 'domain': (20,)},\n {'name': 'time_format', 'type': 'discrete', 'domain': (0,1,2)}, #1 for stepofday, 2 for stepofweek\n {'name': 'volume_input', 'type': 'discrete', 'domain': (0,1)},\n {'name': 'use_centralized_bid', 'type': 'discrete', 'domain': (0,1)},\n {'name': 'split_daily_data', 'type': 'discrete', 'domain': (0,1)}\n ]\n \n mixed_domain_test = [{'name': 'n_neurons', 'type': 'discrete', 'domain': tuple(range(20,160,20))},\n {'name': 'learning_rate', 'type': 'discrete', 'domain': (0.001,0.002,0.003,0.004)},\n {'name': 'num_layers', 'type': 'discrete', 'domain': (1,2,3,4)},\n {'name': 'rnn_type', 'type': 'discrete', 'domain': (0,1,2)},\n {'name': 'learning_period', 'type': 'discrete', 'domain': (10,20)},\n {'name': 'prediction_period', 'type': 'discrete', 'domain': (5,10)},\n {'name': 'n_repeats', 'type': 'discrete', 'domain': (3,5)},\n {'name': 'beta', 'type': 'discrete', 'domain': (99,)},\n {'name': 'ema', 'type': 'discrete', 'domain': (20,)},\n {'name': 'time_format', 'type': 'discrete', 'domain': (0,1,2)}, #1 for stepofday, 2 for stepofweek\n {'name': 'volume_input', 'type': 'discrete', 'domain': (0,1)},\n {'name': 'use_centralized_bid', 'type': 'discrete', 'domain': (0,1)},\n {'name': 'split_daily_data', 'type': 'discrete', 'domain': (0,1)}\n ]\n \n \n def __init__(self, stock_name, stock_index, n_training_days):\n self.stock_name = stock_name\n self.stock_index = stock_index\n self.n_training_days = n_training_days\n self.save_path = \"model_{}_{}\".format(stock_name, n_training_days)\n self.last_training_date = None\n self.model = None\n self.max_profit = -999.0\n return\n \n def get_parameter_str(self, X):\n parameter_str = \"\"\n for i in range(len(self.mixed_domain)):\n parameter_str += self.mixed_domain[i][\"name\"]\n parameter_str += ':'\n parameter_str += str(X[i])\n parameter_str += ','\n return parameter_str\n \n def get_max_steps(self, groups):\n max_steps = 0\n for index, df in groups:\n df_len = len(df)\n if df_len > max_steps:\n max_steps = df_len\n return max_steps\n\n \n def get_data_prep_desc_filename(self, path):\n return path + '/data_prep_desc.pkl'\n \n\n \n def optimize(self, max_iter=300, is_test=False):\n if is_test == True:\n mixed_domain = self.mixed_domain_test\n else:\n mixed_domain = self.mixed_domain\n \n opt_handler = GPyOpt.methods.BayesianOptimization(f=self.opt_func, # Objective function \n domain=mixed_domain, # Box-constraints of the problem\n initial_design_numdata = 30, # Number data initial design\n acquisition_type='EI', # Expected Improvement\n exact_feval = True, \n maximize = True) # True evaluations, no sample noise\n opt_handler.run_optimization(max_iter, eps=0)\n \n def get_data_manipulator_filename(self):\n return os.path.join(self.save_path, 'data_manipulator.pkl')\n \n def save(self):\n # what is the last training date?\n self.model.save(self.save_path, self.data_manipulator.last_learning_date)\n \n # save the data_manipulator\n filename = self.get_data_manipulator_filename()\n with open(filename, 'wb') as f:\n pickle.dump(self.data_manipulator, f, pickle.HIGHEST_PROTOCOL)\n \n # save the strategy model\n self.strategy_model.save(self.save_path)\n \n \n def get_latest_dir(self, save_path):\n all_subdirs = [d for d in os.listdir(save_path) if os.path.isdir(os.path.join(save_path, d))]\n max_time = 0\n for dirname in all_subdirs:\n fullname = os.path.join(save_path, dirname)\n time = os.path.getmtime(fullname)\n if time > max_time:\n max_time = time\n result = dirname\n return result\n\n \n def load(self, load_date=None):\n save_path = self.save_path\n # iterate the path, and find out the latest date as last_training_date\n self.model = StatefulLstmModel()\n \n # get the latest directory\n if load_date == None:\n load_date = self.get_latest_dir(self.save_path)\n \n print(\"Loading model for date: {}\".format(load_date))\n self.model.load(self.save_path, load_date)\n \n # load data manipulator\n with open(self.get_data_manipulator_filename(), 'rb') as f:\n self.data_manipulator = pickle.load(f)\n \n # load strategy\n self.strategy_model = StrategyModel()\n self.strategy_model.load(self.save_path)\n print(\"Model loaded!\")\n \n def get_avg_of_list(self, profit_list):\n return sum(profit_list)/len(profit_list)\n \n def get_ema_profit_per_day(self, profit_list, split_daily_data, window):\n daily_profit_list = self.get_daily_list(profit_list, split_daily_data)\n \n half = int(len(daily_profit_list)/2)\n if window > half:\n window = half\n \n return get_ema(daily_profit_list, window)\n \n def get_daily_list(self, profit_list, split_daily_data):\n result = []\n if split_daily_data == True:\n for i in range(0, len(profit_list), 2):\n daily_profit = (1+profit_list[i])*(1+profit_list[i+1])-1\n result.append(daily_profit)\n return result\n else:\n return profit_list\n \n def get_total_profit_from_list(self, profit_list, seq_num):\n tot_profit = 1\n for i in range(seq_num):\n tot_profit *= (1+profit_list[i])\n return tot_profit - 1\n \n def opt_func(self, X_list):\n assert(len(X_list)==1)\n X_list = X_list[0]\n print(self.get_parameter_str(X_list))\n \n # do 2-layer optimizations.\n error_ema, error_mean, model, data_manipulator, strategy_model = self.get_profit(X_list)\n\n max_profit_list = strategy_model.get_max_profit_list()\n print(\"max_profit_list length:{}\".format(len(max_profit_list)))\n \n max_profit_list = self.get_daily_list(max_profit_list, data_manipulator.split_daily_data)\n print(\"max_profit_list length:{}\".format(len(max_profit_list)))\n # get profit for the training period.\n avg_training_profit = self.get_avg_of_list(max_profit_list)\n ema_5_training_profit = get_ema(max_profit_list, 5)\n ema_10_training_profit = get_ema(max_profit_list, 10)\n \n # get the overall profit for the testing period.\n test_profit, test_profit_list = self.test(model, data_manipulator, strategy_model)\n \n test_profit_list = self.get_daily_list(test_profit_list, data_manipulator.split_daily_data)\n profit_1 = test_profit_list[0]\n \n profit_5 = self.get_total_profit_from_list(test_profit_list, 5)\n \n profit_10 = self.get_total_profit_from_list(test_profit_list, 10)\n \n \n print(\"FINAL RESULT: {},{},{},{},{},{},{},{},{},{},{}\".format(data_manipulator.ema,\n data_manipulator.beta,\n avg_training_profit, \n ema_5_training_profit, \n ema_10_training_profit,\n error_ema, \n error_mean, \n profit_1, \n profit_5, \n profit_10,\n test_profit))\n \n if ema_10_training_profit > self.max_profit and ema_10_training_profit > 0:\n #print(\"find the new best profit:{}, error:{}\".format(profit_ema_per_day, error_ema))\n self.max_profit = ema_10_training_profit\n self.model = model\n self.data_manipulator = data_manipulator\n self.strategy_model = strategy_model\n #self.test()\n self.save()\n \n \n return np.array(ema_10_training_profit).reshape((1,1))\n\n def test(self, model, data_manipulator, strategy_model): \n data_testing_input, data_testing_output, timestamps, price = data_manipulator.prep_testing_data('npy_files', self.stock_index)\n \n # first make a prediction, then do training.\n n_learning_seqs = data_manipulator.n_learning_seqs\n n_prediction_seqs = data_manipulator.n_prediction_seqs\n \n prediction_start = n_learning_seqs - n_prediction_seqs\n prediction_end = prediction_start + n_prediction_seqs\n \n print(\"starting the first prediction from seq:{} to seq:{}\".format(prediction_start, prediction_end-1))\n outputs = model.predict_and_verify(data_testing_input[prediction_start:prediction_end], \n data_testing_output[prediction_start:prediction_end])\n \n print(\"outputs\")\n print(outputs.shape)\n shape = outputs.shape\n assert(shape[2]==1)\n outputs = outputs.reshape((shape[0],shape[1]))\n np_values, np_errors, next_prediction_seq = self.run_model(model, \n data_testing_input, \n data_testing_output, \n n_learning_seqs, \n n_prediction_seqs)\n \n \n \n last_learning_date = self.get_date(timestamps, next_prediction_seq-1)\n data_manipulator.update(next_prediction_seq, last_learning_date)\n print(\"timestamps\")\n print(timestamps[prediction_start:].shape)\n print(outputs.shape)\n print(np_values.shape)\n print(price[prediction_start:].shape)\n \n outputs = np.concatenate((outputs, np_values), axis=0)\n outputs = data_manipulator.inverse_transform_output(outputs)\n strategy_data_input = np.stack((timestamps[prediction_start:], \n outputs,\n price[prediction_start:]), axis=2)\n tot_profit = 1\n profit_list = []\n for i in range(0, len(strategy_data_input), n_prediction_seqs):\n start = i\n end = min(i+n_prediction_seqs, len(strategy_data_input))\n result, result_list = strategy_model.run_test(strategy_data_input[start:end])\n tot_profit *= result\n profit_list += result_list\n #strategy_model.append_data(strategy_data_input[start:end])\n #strategy_model.optimize()\n \n #print(\"test finished, total profit: {} in {} seqs\".format(tot_profit, len(strategy_data_input)))\n return tot_profit-1, profit_list\n \n def get_date(self, timestamps, seq_no):\n return timestamps[seq_no][0].date().strftime(\"%y%m%d\")\n\n def get_profit(self, features):\n n_neurons = int(features[0])\n learning_rate = features[1]\n num_layers = int(features[2])\n rnn_type = int(features[3])\n learning_period = int(features[4])\n prediction_period = int(features[5])\n n_repeats = int(features[6])\n beta = int(features[7])\n ema = int(features[8])\n time_format = int(features[9])\n volume_input = int(features[10])\n use_centralized_bid = int(features[11])\n split_daily_data = int(features[12])\n \n data_manipulator = DataManipulator(learning_period,\n prediction_period,\n beta, ema, \n time_format, \n volume_input, \n use_centralized_bid, \n split_daily_data, \n self.n_training_days)\n \n data_training_input, data_training_output, timestamps, price = data_manipulator.prep_training_data('npy_files', self.stock_index)\n \n model = StatefulLstmModel(n_neurons, learning_rate, num_layers, rnn_type, n_repeats)\n \n n_learning_seqs = data_manipulator.n_learning_seqs\n n_prediction_seqs = data_manipulator.n_prediction_seqs\n \n np_values, np_errors, next_prediction_seq = self.run_model(model, data_training_input, data_training_output, \n n_learning_seqs, n_prediction_seqs)\n \n last_learning_date = self.get_date(timestamps, next_prediction_seq-1)\n data_manipulator.update(next_prediction_seq, last_learning_date)\n \n daily_errors = np.mean(np_errors, axis=1)\n print(\"daily_errors\")\n print(daily_errors.shape)\n error_ema = get_ema(daily_errors, int(len(daily_errors)/2))\n assert(len(daily_errors) != 0)\n error_mean = np.sum(daily_errors)/len(daily_errors)\n # find the best trade strategy.\n # prepare data for the strategy optimization, including timestamp, value, price.\n np_values = data_manipulator.inverse_transform_output(np_values)\n strategy_data_input = np.stack((timestamps[n_learning_seqs:], \n np_values, \n price[n_learning_seqs:]), axis=2)\n print(\"strategy_data_input\")\n print(strategy_data_input.shape)\n ema_window = int(strategy_data_input.shape[0]/2)\n \n \n if split_daily_data == True:\n n_max_trades_per_seq = 1\n else:\n n_max_trades_per_seq = 2\n strategy_model = StrategyModel(n_max_trades_per_seq, ema_window)\n strategy_model.append_data(strategy_data_input)\n strategy_model.optimize()\n return error_ema, error_mean, model, data_manipulator, strategy_model\n \n \n # run the model, do learning and prediction at same time, \n # this will be used for both training and testing.\n # at the test phase, we should do prediction first\n def run_model(self, model, data_input, data_output, n_learning_seqs, n_prediction_seqs):\n # get the date list.\n n_training_seqs = len(data_input)\n errors = None\n all_outputs = None\n n_tot_prediction_seqs = 0\n print(\"start training: training_seq:{}, learning_seq:{}, prediction_seq:{}\".format(n_training_seqs, \n n_learning_seqs, \n n_prediction_seqs,\n ))\n for i in range(0, n_training_seqs-n_learning_seqs+1, n_prediction_seqs):\n learning_end = i + n_learning_seqs\n print(\"start training from seq:{} - seq:{}\".format(i, learning_end-1))\n model.fit(data_input[i:learning_end], data_output[:learning_end], n_prediction_seqs)\n next_prediction_seq = learning_end\n prediction_end = min(learning_end+n_prediction_seqs, len(data_input))\n \n if prediction_end <= learning_end:\n break\n \n print(\"start predicting from seq:{} - seq:{}\".format(learning_end, \n prediction_end-1))\n \n outputs = model.predict_and_verify(data_input[learning_end:prediction_end], \n data_output[learning_end:prediction_end])\n print(\"output.shape\")\n print(outputs.shape)\n y = data_output[learning_end:prediction_end]\n # error is a 1-D array for the every day error\n error = np.square(outputs-y)\n \n n_tot_prediction_seqs += outputs.shape[0]\n if i == 0:\n all_outputs = outputs\n errors = error\n else:\n all_outputs = np.concatenate((all_outputs, outputs), axis=0)\n errors = np.concatenate((errors, error), axis=0)\n return np.squeeze(all_outputs), np.squeeze(errors), next_prediction_seq\n \n\n\n# In[ ]:\n\n\ndef print_verbose_func(verbose, msg):\n if verbose == True:\n print(msg)\n\n\n# In[ ]:\n\n\nclass TradeStrategyDesc:\n def __init__(self,\n X_list,\n ema_window,\n optimize_data):\n self.buy_threshold = X_list[0]\n self.sell_threshold = X_list[1]\n self.stop_loss = X_list[2]\n self.stop_gain = X_list[3]\n self.min_hold_steps = X_list[4]\n self.max_hold_steps = X_list[5]\n self.ema_window = ema_window\n self.optimize_data = optimize_data\n \n def get_parameter_str(self):\n s = \"buy_threshold:{} sell_threshold:{} stop_loss:{} stop_gain:{} min_hold_steps:{} max_hold_steps:{} ema_window:{} optimize_data:{}\".format(self.buy_threshold,\n self.sell_threshold,\n self.stop_loss,\n self.stop_gain,\n self.min_hold_steps,\n self.max_hold_steps,\n self.ema_window,\n self.optimize_data.shape)\n return s\n \n \n def to_list(self):\n return [[self.buy_threshold, self.sell_threshold, self.stop_loss, self.stop_gain, \n self.min_hold_steps,\n self.max_hold_steps]]\n\n\n# In[ ]:\n\n\nfrom functools import partial\n\nclass StrategyModel:\n mixed_domain = [{'name': 'buy_threshold', 'type': 'continuous', 'domain': (0.0, 0.005)},\n {'name': 'sell_threshold', 'type': 'continuous', 'domain': (-0.005, 0.0)},\n {'name': 'stop_loss', 'type': 'continuous', 'domain': (-0.01,-0.003)},\n {'name': 'stop_gain', 'type': 'continuous', 'domain': (0.002, 0.01)},\n {'name': 'min_hold_steps', 'type': 'discrete', 'domain': range(10,100)},\n {'name': 'max_hold_steps', 'type': 'discrete', 'domain': range(50,200)},\n ]\n def __init__(self, n_max_trades_per_seq=4, ema_window=None):\n self.max_profit = -999.0\n self.strategy_desc = None\n self.ema_window = ema_window\n self.optimize_data = None\n self.tot_profit = None\n self.n_max_trades_per_seq = n_max_trades_per_seq\n return\n \n # append the data for the optimization\n def append_data(self, data):\n if self.optimize_data is None:\n self.optimize_data = data\n else:\n self.optimize_data = np.concatenate((self.optimize_data, data), axis=0)\n\n def optimize(self):\n self.trade_strategy_desc = None\n self.max_profit_ema_per_step = -999.0\n self.input_data = self.optimize_data\n myBopt = GPyOpt.methods.BayesianOptimization(self.get_profit_ema, # Objective function \n domain=self.mixed_domain, # Box-constraints of the problem\n initial_design_numdata = 30, # Number data initial design\n acquisition_type='EI', # Expected Improvement\n exact_feval = True,\n maximize = True) # True evaluations, no sample noise\n\n myBopt.run_optimization(150,eps=0)\n self.input_data = None\n return 0\n \n def run_test(self, test_data):\n print(\"starting test: {}\".format(self.trade_strategy_desc.get_parameter_str()))\n X_list = self.trade_strategy_desc.to_list()\n return self.get_total_profit(X_list, test_data)\n \n def get_total_profit(self, X_list, test_data):\n assert(len(X_list) == 1)\n tot_profit, n_tot_trades, daily_profit_list, _, _ = self.run_test_core(X_list[0], \n test_data, \n verbose=True)\n \n print(\"test finished: tot_profit:{} in {} seqs\".format(tot_profit,\n len(daily_profit_list)))\n return tot_profit, daily_profit_list\n \n # the input data is in shape (days, steps, [timestamp, value, price])\n def get_profit_ema(self, X_list):\n assert(len(X_list)==1)\n X_list = X_list[0]\n input_data = self.input_data[-self.ema_window*2:]\n tot_profit, n_tot_trades, seq_profit_list, stock_change_rate, asset_change_rate = self.run_test_core(X_list, input_data)\n \n profit_ema = get_ema(seq_profit_list, self.ema_window)\n \n profit_ema_per_step = profit_ema / self.input_data.shape[1]\n if profit_ema_per_step > self.max_profit_ema_per_step:\n print(\"find best profit_per_step: {} profit_ema:{} tot_profit:{} window:{}\".format(\n profit_ema_per_step,\n profit_ema,\n tot_profit,\n self.ema_window))\n\n self.max_profit_ema_per_step = profit_ema_per_step\n \n self.change_rate = np.concatenate((input_data, \n stock_change_rate,\n asset_change_rate), axis=2)\n self.trade_strategy_desc = TradeStrategyDesc(X_list,\n self.ema_window,\n self.optimize_data)\n self.tot_profit = tot_profit\n self.max_profit_list = seq_profit_list\n \n return np.array(profit_ema_per_step).reshape((1,1))\n \n def run_test_core(self, X_list, input_data, verbose=False):\n print_verbose = partial(print_verbose_func, verbose)\n buy_threshold = X_list[0]\n sell_threshold = X_list[1]\n stop_loss = X_list[2]\n stop_gain = X_list[3]\n min_hold_steps = int(X_list[4])\n max_hold_steps = int(X_list[5])\n tot_profit = 1\n tot_stock_profit = 1\n buy_step = None\n n_max_trades = self.n_max_trades_per_seq\n cost = 0.00015/2\n n_tot_trades = 0\n # to prepare the result data\n shape = input_data.shape\n\n reshaped_price = input_data[:,:,2].reshape((shape[0]*shape[1]))\n \n stock_change_rate = np.diff(reshaped_price) / reshaped_price[:-1]\n stock_change_rate = np.concatenate(([0], stock_change_rate)).reshape((shape[0],shape[1],1))\n \n asset_change_rate = np.zeros((stock_change_rate.shape))\n \n \n daily_profit_list = []\n \n for day_idx in range(len(input_data)):\n print_verbose(\"starting day {}\".format(day_idx))\n n_trades = 0\n daily_profit = 1\n trade_profit = 1\n state = 0\n daily_data = input_data[day_idx]\n hold_steps = 0\n for step in range(len(daily_data)):\n time = daily_data[step][0]\n value = daily_data[step][1]\n price = daily_data[step][2]\n change_rate = stock_change_rate[day_idx][step][0]\n if state == 0 and time.time().hour >= 9 and n_trades < n_max_trades and step < len(daily_data)-min_hold_steps and value > buy_threshold:\n state = 1\n asset_change_rate[day_idx][step][0] = -cost\n tot_profit *= (1-cost)\n daily_profit *= (1-cost)\n trade_profit *= (1-cost)\n print_verbose(\"buy at step: {} price:{}\".format(step, price))\n elif state == 1:\n if (value < sell_threshold and \n hold_steps > min_hold_steps) or step == len(daily_data)-1 or \\\n trade_profit-1 < stop_loss or \\\n trade_profit-1 > stop_gain or \\\n hold_steps >= max_hold_steps:\n # don't do more trade today!\n if trade_profit-1 < stop_loss:\n print_verbose(\"stop loss stop trading!\")\n n_trades = n_max_trades\n\n change_rate = (1+change_rate)*(1-cost)-1 \n tot_profit *= (1 + change_rate)\n daily_profit *= (1 + change_rate)\n state = 0\n n_trades += 1\n print_verbose(\"sell at step: {} price:{} trade_profit:{} hold_steps:{}\".format(step, price, trade_profit, hold_steps))\n trade_profit = 1\n asset_change_rate[day_idx][step] = change_rate\n hold_steps = 0\n \n else:\n tot_profit *= (1+change_rate)\n daily_profit *= (1+change_rate)\n trade_profit *= (1+change_rate)\n asset_change_rate[day_idx][step][0] = change_rate\n hold_steps += 1\n print_verbose(\"finished day {}, daily profit:{}\".format(day_idx,daily_profit))\n daily_profit_list.append(daily_profit - 1)\n n_tot_trades += n_trades\n return tot_profit, n_tot_trades, daily_profit_list, stock_change_rate, asset_change_rate\n \n def get_max_profit_list(self):\n return self.max_profit_list\n \n def get_strategy_desc(self):\n return self.trade_strategy_desc\n \n def get_save_filename(self, path):\n return os.path.join(path, 'strategy_desc.pkl')\n \n def save(self, save_path):\n assert(self.trade_strategy_desc != None)\n with open(self.get_save_filename(save_path), 'wb') as f:\n pickle.dump(self.trade_strategy_desc, f, pickle.HIGHEST_PROTOCOL)\n \n def load(self, save_path):\n with open(self.get_save_filename(save_path), 'rb') as f:\n self.trade_strategy_desc = pickle.load(f)\n this.ema_window = self.trade_strategy_desc.ema_window\n this.optimize_data = self.trade_strategy_desc.optimize_data\n\n\n# In[ ]:\n\n\nvalue_model = ValueModel('Nordea', 5, 60)\nvalue_model.optimize(is_test=False)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"data-analytics/oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":46420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"323005651","text":"import requests\r\nfrom queue import Queue\r\nfrom bs4 import BeautifulSoup\r\nimport re \r\nimport gevent\r\nimport time\r\n\r\nclass Spider:\r\n def __init__(self):\r\n self.headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'}\r\n #基准网址\r\n self.base_url='http://www.bookschina.com/kinder/30000000/'\r\n #数据队列\r\n self.dataQueue=Queue()\r\n #统计数量\r\n #self.count=0\r\n #数据列表\r\n self.books=[]\r\n #获取一页数据的方法\r\n def get_page_books(self,url):\r\n content = requests.get(url, headers=self.headers).content\r\n #对页面数据进行解析\r\n soup = BeautifulSoup(content, 'html5lib')\r\n bookList= soup.find('div', class_='bookList')\r\n for item in bookList:\r\n book={}\r\n book['img']=bookList.find('div',class_='cover').find('img')['src']\r\n book['name']=bookList.find('div',class_='cover').find('a').text\r\n book['janjie']=bookList.find('div',class_='infor').find('p',class_='recoLagu')\r\n\r\n self.dataQueue.put(book)\r\n\r\n def start_work(self,pageNum):\r\n job_list=[]\r\n for page in range(1,pageNum+1):\r\n url=self.base_url.format(page)\r\n #创建协成任务\r\n job=gevent.spawn(self.get_page_books,url)\r\n #\r\n job_list.append(job)\r\n\r\n #等待所有协程执行完毕\r\n gevent.joinall(job_list)\r\n\r\n while not self.dataQueue.empty():\r\n book = self.dataQueue.get()\r\n self.books.append(book)\r\nif __name__==\"__main__\":\r\n pages=int(input('请输入页码:'))\r\n t1=time.time()\r\n spider =Spider()\r\n spider.start_work(pages)\r\n print(len(spider.books),spider.books[-1])\r\n t2=time.time()\r\n print(t2-t1)","sub_path":"my_geventcrawl.py","file_name":"my_geventcrawl.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"400988342","text":"from pandas_datareader import data\nimport pandas as pd\nimport datetime\nimport io, sys\nimport pickle\nimport numpy as np\nfrom time import sleep\n\ntoday = datetime.datetime.now().strftime(\"%Y, %m, %d\")\nstock_watch_list = [\"^GSPC\", \"^IXIC\", \"^DJI\",\"FTNT\", \"TWTR\", \"ECA\", \"CNQ.TO\"]\ncurrency_list = [\"DEXCNUS\", \"DEXCAUS\", \"DEXCNCA\", \"DEXCACA\", \"DEXUSEU\"]\n\nstart = datetime.datetime(2009, 11, 18)\nend = datetime.datetime(2016, 4, 15)\n#end = datetime.datetime(2013, 1, 27)\n#help(data)\n#help(wb)\n# f=data.DataReader(\"FTNT\", 'yahoo', start)\n#print(f.resample('W').tail())\n\n#print(f.ix['2016-03-24'])\n#print(f)\n#print(f)\n#df = pd.concat([f], axis=0)\n# df = f\n# #print(df.head())\n\n# df[\"Day_High_3\"] = pd.Series.rolling(df.High, window=3, min_periods=1).max()\n# df[\"Day_Low_3\"] = pd.Series.rolling(df.Low, window=3, min_periods=1).min()\n# df[\"MA_10\"] = pd.Series.rolling(df.Close, window=10, center = False).mean()\n# df[\"MA_20\"] = pd.Series.rolling(df.Close, window=20, center = False).mean()\n\n\ndef _get_yahoo(stock, start):\n\tdf = data.DataReader(stock, 'yahoo', start)\n\treturn df\n\ndef _moving_average(df, x):\t\t\t## get the x days/weeks/months close price moving average \n\tnew_column = \"MA_\" + str(x)\n\tdf[new_column] = pd.Series.rolling(df.Close, window = x, center = False).mean()\n\ndef _moving_average_up_cross(ma1, ma2):\n\tma1 = _moving_average\n\ndef _periods_index(df):\t\t\t## for _periods to adjust the date\n\tnew_index = []\t\t\t\t## the new index changes format '2016-02-29/2016-03-06' to '2016-02-29'\n\tfor x in df.index:\n\t\tx = str(x).split('/')[0]\n\t\tnew_index.append(x)\n\tdf.index = new_index\n\ndef _periods(df, period):\n\tif period == 'W':\n\t\tdf = df.to_period('W')\n\telif period == 'M':\n\t\tdf = df.to_period('M')\n\telse:\n\t\texit(\"Please use 'W' for Weekly or 'M' for Monthly.\")\n\n\t\t\t## row weekly data\n\tcol_order = ['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']\t\t## the columns order after aggregation\n\tagg_weekly = {'Open' : 'first',\t\t\t## get the corresponding record from each row in the same week\n\t\t\t\t'High' : max,\n\t\t\t\t'Low' : min,\n\t\t\t\t'Close' : 'last',\n\t\t\t\t'Volume' : sum,\n\t\t\t\t'Adj Close' : 'last'}\n\n\tagg_data = df.groupby(df.index).agg(agg_weekly)[col_order]\n\t_periods_index(agg_data)\n\treturn agg_data\n\ndef _daily_watch_stock(stock_watch_list):\n\t## get latest 5 days data first to avoid holidays and weekends\n\ttoday = datetime.datetime.now()\n\tdate = today - datetime.timedelta(days = 5)\t\n\tdf = pd.DataFrame()\n\n\tfor stock in stock_watch_list:\n\t\tstock_data = _get_yahoo(stock, date)\n\n\t\tdf = df.append(stock_data.tail(1))\t\t## choose the latest one\n\t\t#df = df.join(tmp)\n\t#df.index = stock_watch_list\n\t#df.reset_index(level = 0, inplace = True)\t\n\tprint(df.index[0])\n\tdf.index = stock_watch_list\n\tprint(df[['Open', 'Adj Close', 'High', 'Low', 'Volume']])\n\tprint(\"\\n^GSPC is S&P 500\\t^IXIC is NASDAQ\\t\\t^DJI is Dow\")\n\tprint(\"\\n\\n\")\n\ndef _get_currency():\n\turl_usd = \"http://www.x-rates.com/table/?from=USD&amount=1\"\n\turl_cny = \"http://www.x-rates.com/table/?from=CNY&amount=1\"\n\tusd = pd.read_html(url_usd)\n\tusd = pd.DataFrame(usd[0])\n\n\tcny = pd.read_html(url_cny)\n\tcny = pd.DataFrame(cny[0])\n\n\tusd.index = usd[\"US Dollar\"]\n\tcny.index = cny[\"Chinese Yuan Renminbi\"]\n\t\n\tprint(usd.iloc[[0, 1, 4, 9], [0, 1, 2]])\n\tprint(\"\\n\")\n\tprint(cny.iloc[[0, 5], [0, 1, 2]])\n\tprint(\"\\n\\n\")\n\ndef _get_Yhaoo_key_to_csv(stock_symbol, file_path):\n\turl = \"https://finance.yahoo.com/q/ks?s=\" + stock_symbol + \"Key+Statistics\"\n\tdf = pd.read_html(url)\n\tprint(type(df))\n\tdf.to_pickle(file_path + '\\\\' + stock_symbol + '.scv')\n\ndef _select_stocks_key_stat():\t\n\n\t# df = pd.read_csv(\"nasdaq.csv\")\t## 1\n\t# df = pd.read_csv(\"nyse.csv\")\t## 2\n\t# df = pd.read_csv(\"amex.csv\")\t## 3\n\t# stocks = df.Symbol\n\tall_a1 = ['AAON', 'ABMD', 'AEIS', 'ALGN', 'AFOP', 'AMBA', 'ANIK', 'ATRI', 'BSTC', 'BSQR', 'CPLA', 'CBOE', 'JRJC', 'CPSI', 'CRWS', 'CTCM', 'DHIL', 'DRAD', 'DMLP', 'DORM', 'ENTA', 'EFOI', 'ENZN', 'EXPD', 'EXPO', 'FHCO', 'FRAN', 'HCSG', 'HTLD', 'INSY', 'IQNT', 'LINK', 'ISRG', 'IRMD', 'IRIX', 'ITRN', 'LANC', 'TREE', 'LTBR', 'LLTC', 'LRAD', 'LULU', 'MKTX', 'VIVO', 'MSTR', 'MDXG', 'MNDO', 'MSON', 'MNST', 'FIZZ', 'OFLX', 'OXBR', 'PETS', 'SEIC', 'SILC', 'SIMO', 'SLP', 'SWKS', 'SEDG', 'SPOK', 'SHOO', 'STRA', 'SNHY', 'TROW', 'TSRA', 'RMR', 'ULTA', 'UTHR', 'UG', 'UTMD', 'VDSI', 'WETF', 'ZAGG', 'ZLTQ', 'AHC', 'ATHM', 'SAM', 'BPT', 'BKE', 'CATO', 'CMG', 'CBK', 'DSW', 'FIT', 'GLOB', 'GMED', 'HGT', 'INFY', 'LXFT', 'MPX', 'MJN', 'MED', 'MTR', 'MSB', 'KORS', 'MBLY', 'MSI', 'PRLB', 'PZN', 'REX', 'RHI', 'SBR', 'RGR', 'TARO', 'TNH', 'THO', 'VTRB', 'WHG', 'WGO', 'WNS', 'WPT', 'CQH', 'MGH', 'STS']\n\t#stocks = ['AAON']\n\tstocks = all_a1\n\tselects = []\n\t#a1 = ['CTCM', 'ENTA', 'EFOI', 'ITRN', 'SPOK', 'UTHR', 'ZLTQ', 'SAM', 'GLOB', 'LXFT', 'MED', 'KORS', 'RHI']\n\n\tfor stock_symbol in stocks:\n\t\tstock_symbol = stock_symbol.replace(' ', '')\n\t\turl = 'https://finance.yahoo.com/q/ks?s=' + stock_symbol + '+Key+Statistics'\n\t\t#url = 'https://finance.yahoo.com/q/ks?s=FIT+Key+Statistics'\n\t\tprint(url)\n\t\t#https://finance.yahoo.com/q/ks?s=JNPR+Key+Statistics\n\t\tdf = pd.read_html(url)\n\t\t# print(len(df))\n\t\tif len(df) >= 15:\n\n\t\t\tmarket_cap = df[1].iat[5, 1]\t\t## this is class str\n\t\t\ttrailling_PE = df[1].iat[7, 1] ## this is class str\n\t\t\treturn_on_equity_df = df[12]\t\t## this is a dataframe\n\t\t\tbanlance_shert_df = df[15]\t\t\t## this is a dataframe too, and it is includes totaldebt_equity and current_ratio\n\t\t\t#banlance_shert_df = pd.to_numeric(banlance_shert_df, errors = 'coerec')\n\n\t\t\t# x = (return_on_equity_df.iat[2, 1])\n\t\t\t# print(x)\n\t\t\t# print(type(x))\n\t\t\t# print(np.isnan(x))\n\t\t\t# if x == np.nan:\n\t\t\t# \tprint(\"nananana\")\n\t\t\t# print(return_on_equity_df[1][2:3].isnull())\n\n\t\t\t#print(banlance_shert_df[1][5:7])\n\n\t\t\t# return_on_equity = return_on_equity_df[1][2:3]\n\t\t\t# totaldebt_equity = banlance_shert_df[1][5:6]\n\t\t\t# current_ratio = banlance_shert_df[1][6:7]\n\t\t\treturn_on_assets = return_on_equity_df.iat[1, 1]\n\t\t\treturn_on_equity = return_on_equity_df.iat[2, 1]\n\t\t\ttotaldebt_equity = banlance_shert_df.iat[5, 1]\n\t\t\tcurrent_ratio = banlance_shert_df.iat[6, 1]\n\n\t\t\tprint(market_cap, type(market_cap), trailling_PE, type(trailling_PE))\n\t\t\tprint(return_on_assets, type(return_on_assets), return_on_equity, type(return_on_equity), totaldebt_equity, type(totaldebt_equity), current_ratio, type(current_ratio))\n\n\t\t\t# print(type(totaldebt_equity))\n\t\t\t# print(isinstance(totaldebt_equity, np.float64))\n\t\t\t# print(isinstance(totaldebt_equity, str))\n\n\t\t\tif isinstance(market_cap, np.float) or isinstance(market_cap, float):\n\t\t\t\tprint(\"None 1: market_cap is N/A\", stock_symbol)\n\t\t\t\tcontinue\n\t\t\telif 'B' in market_cap and float(market_cap.replace('B', '')) > 2.0:\n\t\t\t\tprint(\"None 2: market_cap > 2B\", stock_symbol)\n\t\t\t\tcontinue\n\t\t\telif isinstance(return_on_assets, np.float64) or isinstance(return_on_assets, float):\n\t\t\t\tprint(\"None 3: return_on_assets\", stock_symbol)\n\t\t\t\tcontinue\t\t\t\n\t\t\telif isinstance(return_on_equity, np.float64) or isinstance(return_on_equity, float):\n\t\t\t\t# if np.isnan(return_on_equity) or np.isnan(current_ratio.item):\n\t\t\t\tprint(\"None 4: return_on_equity\", stock_symbol)\n\t\t\t\tcontinue\n\t\t\telif isinstance(current_ratio, np.float64) or isinstance(current_ratio, float):\n\t\t\t\tprint(\"None 5: current_ratio\", stock_symbol)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tif isinstance(totaldebt_equity, np.float64) or isinstance(totaldebt_equity, float):\n\t\t\t\t\ttotaldebt_equity = 0.0\n\t\t\t\tif isinstance(return_on_assets, str):\n\t\t\t\t\treturn_on_assets = return_on_assets.replace('%', '').replace(',', '')\n\t\t\t\t\treturn_on_assets = float(return_on_assets)\n\t\t\t\tif isinstance(return_on_equity, str):\n\t\t\t\t\treturn_on_equity = return_on_equity.replace('%', '').replace(',', '')\n\t\t\t\t\treturn_on_equity = float(return_on_equity)\n\t\t\t\tif isinstance(totaldebt_equity, str):\n\t\t\t\t\t#return_on_equity = return_on_equity.replace('%', '')\n\t\t\t\t\ttotaldebt_equity = float(totaldebt_equity)\n\t\t\t\tif isinstance(current_ratio, str):\n\t\t\t\t\t#return_on_equity = return_on_equity.replace('%', '')\n\t\t\t\t\tcurrent_ratio = float(current_ratio)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\t\t\t# return_on_equity = return_on_equity[1].replace('%', '')\n\t\t\t\t# return_on_equity = float(return_on_equity)\n\t\t\t\t# current_ratio = float(current_ratio[1])\n\t\t\t\t\n\t\t\t# if np.nan(totaldebt_equity):\n\t\t\t# \ttotaldebt_equity = 0.00\n\t\t\t# else:\n\t\t\t# \t#totaldebt_equity = float(totaldebt_equity[1])\n\t\t\t# \tpass\n\t\t\tprint(market_cap, type(market_cap), trailling_PE, type(trailling_PE))\n\t\t\tprint(return_on_assets, type(return_on_assets),return_on_equity, type(return_on_equity), totaldebt_equity, type(totaldebt_equity), current_ratio, type(current_ratio))\n\t\t\tif return_on_assets > 15 and return_on_equity > 15 and totaldebt_equity < 0.4 and current_ratio > 2:\n\t\t\t\tselects.append(stock_symbol)\n\t\t\t\tprint(\"********** Founded!!! ***********\")\n\t\t\telse:\n\t\t\t\tprint(\"\\tPass\")\n\t\telse:\n\t\t\tprint(\"The lenght is less than 15!!!\")\n\t\tsleep(0.01)\n\tprint(selects)\n\treturn(selects)\n\ndef _select_stocks_competitiors():\n\tselects = []\n\tall_a3 = ['AAON', 'AMBA', 'ATRI', 'BSTC', 'CPLA', 'CPSI', 'DHIL', 'DORM', 'ENTA', 'ENZN', 'FRAN', 'INSY', 'IQNT', 'IRMD', 'ITRN', 'VIVO', 'MNDO', 'OFLX', 'PETS', 'SLP', 'STRA', 'TSRA', 'UG', 'WETF', 'SAM', 'BPT', 'BKE', 'LXFT', 'MED', 'MTR', 'MSB', 'PZN', 'SBR', 'RGR', 'TNH', 'WHG']\n\tall_a2 = ['AAON', 'AMBA', 'ATRI', 'BSTC', 'CPLA', 'CBOE', 'CPSI', 'DHIL', 'DORM', 'ENTA', 'ENZN', 'EXPD', 'FRAN', 'INSY', 'IQNT', 'IRMD', 'ITRN', 'LANC', 'LLTC', 'LULU', 'MKTX', 'VIVO', 'MNDO', 'MNST', 'FIZZ', 'OFLX', 'PETS', 'SLP', 'SWKS', 'STRA', 'TROW', 'TSRA', 'UTHR', 'UG', 'WETF', 'SAM', 'BPT', 'BKE', 'CMG', 'FIT', 'LXFT', 'MJN', 'MED', 'MTR', 'MSB', 'KORS', 'PZN', 'RHI', 'SBR', 'RGR', 'TARO', 'TNH', 'WHG', 'CQH']\n\t#stocks = ['ENTA']\n\tstocks = all_a2\n\t## the url of Competitiors: url = https://finance.yahoo.com/q/co?s=ENTA+Competitors\n\n\tfor stock_symbol in stocks:\n\t\tstock_symbol = stock_symbol.replace(' ', '')\n\t\turl = 'https://finance.yahoo.com/q/co?s=' + stock_symbol + '+Competitors'\n\t\t#url = 'https://finance.yahoo.com/q/ks?s=FIT+Key+Statistics'\n\t\tprint(url)\n\t\t#https://finance.yahoo.com/q/ks?s=JNPR+Key+Statistics\n\t\tdf = pd.read_html(url)\n\t\tprint(len(df))\n\t\t# print(df[4])\n\t\tif len(df) >= 5:\t## avoid empty data, please note the value 4 and 5\n\t\t\tdf = df[4]\t## choose the right list, and df is a dataframe\n\t\t\t# print(len(df))\n\t\t\tdf.columns = df.iloc[1]\t## replace the columns of numbers with strings\n\t\t\t#print(df)\n\t\t\tpe = df[[stock_symbol, 'Industry']].iat[11, 0]\n\t\t\tpe_industry = df[[stock_symbol, 'Industry']].iat[11, 1]\n\t\t\tquarterly_revenue_growth_yoy = df[[stock_symbol, 'Industry']].iat[4, 0]\n\t\t\tquarterly_revenue_growth_yoy_industry = df[[stock_symbol, 'Industry']].iat[4, 1]\n\n\n\t\t\tprint(pe, type(pe), pe_industry, type(pe_industry), quarterly_revenue_growth_yoy, type(quarterly_revenue_growth_yoy), quarterly_revenue_growth_yoy_industry, type(quarterly_revenue_growth_yoy_industry))\n\t\t\tif isinstance(pe, float) or isinstance(pe_industry, float) or isinstance(quarterly_revenue_growth_yoy_industry, float) or isinstance(quarterly_revenue_growth_yoy_industry, float):\n\t\t\t\tprint('One or more P/E, or one or more Quarterly Revenue Growth is N/A', stock_symbol)\n\t\t\telif isinstance(pe, str) and isinstance(pe_industry, str) and isinstance(quarterly_revenue_growth_yoy, str) and isinstance(quarterly_revenue_growth_yoy_industry, str):\n\t\t\t\tpe = float(pe)\n\t\t\t\tpe_industry = float(pe_industry)\n\t\t\t\tquarterly_revenue_growth_yoy = float(quarterly_revenue_growth_yoy)\n\t\t\t\tquarterly_revenue_growth_yoy_industry = float(quarterly_revenue_growth_yoy_industry)\n\t\t\t\t#print(pe, type(pe), pe_industry, type(pe_industry))\n\t\t\t\tprint(pe, type(pe), pe_industry, type(pe_industry), quarterly_revenue_growth_yoy, type(quarterly_revenue_growth_yoy), quarterly_revenue_growth_yoy_industry, type(quarterly_revenue_growth_yoy_industry))\n\n\t\t\t\tif pe/pe_industry < 0.85 and quarterly_revenue_growth_yoy > 0.0 and quarterly_revenue_growth_yoy/quarterly_revenue_growth_yoy_industry > 1.15:\n\t\t\t\t\tselects.append(stock_symbol)\n\t\t\t\t\tprint('Founded, and P/E divided by P/E Industry and quarterly_revenue_growth_yoy divided by quarterly_revenue_growth_yoy_industry are :', pe/pe_industry, quarterly_revenue_growth_yoy/quarterly_revenue_growth_yoy)\n\t\t\t\telse:\n\t\t\t\t\tprint('\\tPass')\n\t\telse:\n\t\t\tprint(\"Empty Data:\\t\", stock_symbol)\n\t\tsleep(0.01)\n\n\tprint(selects)\n\treturn(selects)\n\n#result = pd.concat([a, b])\n#print(result)\n\n# print(_periods(f, \"W\").tail())\n\n#_periods(df, 'M')\n#print(df.head(3))\n\n\n#eca = data.DataReader(\"ECA\", 'yahooDa')\n#print(eca)\n#print(df.ix['24/3/2016'])\n#df1 = pd.DataFrame(df)\n#print(df[df.MA_10.shift(1) < df.MA_20.shift(1) and df.MA_10 > df.MA_20].loc[:, 'Close'])\n\"\"\"\ngc12 = df[(df.MA_10 > df.MA_20) & (df.MA_10.shift(1) < df.MA_20.shift(1))]\n#print(gc12.loc[:, 'Close'])\nprint(gc12.index)\n\nlen_index = len(gc12.index)\nprint(len_index)\nfor i in range(len_index):\n\tif i < len_index - 1:\n\t\tprint(df.loc[gc12.index[i]:gc12.index[i + 1], 'Close'])\n\t\tprint(\"-\" * 20)\n\telse:\n\t\tprint(df.loc[gc12.index[i]:, 'Close'])\n\"\"\"\n\n#print(df.loc[:, 'Low'])\n#x = df1.rolling(center=False,window=20).mean()\n#print(df.loc[gc12.index[1]:, 'Close'])\n\n# x = pd.read_excel('hpi_4_12_2016.xls')\n# print(x.ix[0:10, [1, 2, 3, 7, 8]])\n\n# _daily_watch_stock(stock_watch_list)\n\n# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') \n\n# df = pd.read_html(\"http://www.x-rates.com/table/?from=USD&amount=1\")\n# print(df[0])\n\n# _get_currency()\n\n# usdcad = data.DataReader('DEXCHUS', 'fred')\n# print(usdcad)\n\n# this works\n# s_p = data.DataReader('^GSPC','yahoo') # S&P 500\n# nasdaq = data.DataReader('^IXIC','yahoo') # NASDAQ\n\n# # this doesn't\n# dow = data.DataReader('^DJI','yahoo') # Dow\n\n# print(dow)\n# df = pd.read_csv(\"nasdaq.csv\")\n# stocks = df.Symbol\n\n# df_sort = df.sort_values(by = \"MarketCap\")[[\"Symbol\", \"MarketCap\"]]\n# df_sort.index = df.index\n# #print(df_sort[[\"Symbol\", \"MarketCap\"]].head())\n# #print(df_sort[1308:1368])\n# df_2b = df_sort.loc[df_sort[\"MarketCap\"].isin([\"$2B\"])]\n# print(df_2b)\n\n# df = pd.read_html(\"https://finance.yahoo.com/q/ks?s=JNPR+Key+Statistics\")\n# print(type(df[12]))\n# return_on_equity = df[12].loc[2]\n# print(return_on_equity [0], return_on_equity [1])\n# totaldebt_equity = df[15].loc[5]\n# current_ratio = df[15].loc[6]\n\n# print(totaldebt_equity[0], totaldebt_equity[1])\n# print(current_ratio[0], current_ratio[1])\n# nasdaq\n# ['AAON', 'ABMD', 'AEIS', 'ALGN', 'AFOP', 'AMBA', 'ANIK', 'ATRI', 'BSTC', 'BSQR', 'CPLA', 'CBOE', 'JRJC', 'CPSI', 'CRWS', 'CTCM', 'DHIL', 'DRAD', 'DMLP', 'DORM', 'ENTA', 'EFOI', 'ENZN', 'EXPD', 'EXPO', 'FHCO', 'FRAN', 'HCSG', 'HTLD', 'INSY', 'IQNT', 'LINK', 'ISRG', 'IRMD', 'IRIX', 'ITRN', 'LANC', 'TREE', 'LTBR', 'LLTC', 'LRAD', 'LULU', 'MKTX', 'VIVO', 'MSTR', 'MDXG', 'MNDO', 'MSON', 'MNST', 'FIZZ', 'OFLX', 'OXBR', 'PETS', 'SEIC', 'SILC', 'SIMO', 'SLP', 'SWKS', 'SEDG', 'SPOK', 'SHOO', 'STRA', 'SNHY', 'TROW', 'TSRA', 'RMR', 'ULTA', 'UTHR', 'UG', 'UTMD', 'VDSI', 'WETF', 'ZAGG', 'ZLTQ']\n# nyse\n# ['AHC', 'ATHM', 'SAM', 'BPT', 'BKE', 'CATO', 'CMG', 'CBK', 'DSW', 'FIT', 'GLOB', 'GMED', 'HGT', 'INFY', 'LXFT', 'MPX', 'MJN', 'MED', 'MTR', 'MSB', 'KORS', 'MBLY', 'MSI', 'PRLB', 'PZN', 'REX', 'RHI', 'SBR', 'RGR', 'TARO', 'TNH', 'THO', 'VTRB', 'WHG', 'WGO', 'WNS', 'WPT']\n# amex\n# ['CQH', 'MGH', 'STS']\n\n# _select_stocks_key_stat()\n_select_stocks_competitiors()\n\n#print(df.sort_values(by = \"MarketCap\")[[\"Symbol\", \"MarketCap\"]].head(10))\n# print(df.loc[]","sub_path":"s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":15246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"35589017","text":"\"\"\"Controller module for acceptor app\"\"\"\n\nimport click\n\nfrom prompt import analyze_and_accept, get_columns, get_limit\nfrom sheet_analyzer import SheetAnalyzer\n\n@click.command()\n@click.option(\n '-f',\n '--filename',\n help='Full pathname of xlsx file',\n type=click.Path(exists=True)\n)\ndef main_command(filename):\n \"\"\"Main controller command\"\"\"\n if not filename:\n print('You must provide the --filename flag')\n else:\n limit = get_limit()\n analyzer = SheetAnalyzer(filename, limit)\n analyzer.set_columns(*get_columns(analyzer))\n analyze_and_accept(analyzer)\n","sub_path":"acceptor/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"225618215","text":"# -*- coding: utf-8 -*-\nfrom base import BaseInstanceStep\nfrom dbaas_aclapi.tasks import replicate_acl_for\nfrom dbaas_aclapi.acl_base_client import AclClient\nfrom dbaas_credentials.models import CredentialType\nfrom util import get_credentials_for, GetCredentialException\nfrom workflow.steps.util.base import ACLFromHellClient\n\nimport logging\n\nLOG = logging.getLogger(__name__)\n\n\nclass CantSetACLError(Exception):\n pass\n\n\nclass ACLStep(BaseInstanceStep):\n\n def __init__(self, instance):\n super(ACLStep, self).__init__(instance)\n\n try:\n acl_credential = get_credentials_for(\n environment=self.environment,\n credential_type=CredentialType.ACLAPI)\n except (IndexError, GetCredentialException):\n self.acl_client = None\n else:\n self.acl_client = AclClient(\n acl_credential.endpoint,\n acl_credential.user,\n acl_credential.password,\n self.environment)\n\n def do(self):\n raise NotImplementedError\n\n def undo(self):\n pass\n\n\nclass ReplicateAcls2NewInstance(ACLStep):\n\n def __unicode__(self):\n return \"Replicating ACLs...\"\n\n @property\n def source_host(self):\n return self.infra.instances.filter(\n is_active=True, read_only=False\n ).first().hostname\n\n @property\n def destination_host(self):\n return self.instance.hostname\n\n def do(self):\n if self.acl_client is None:\n return\n replicate_acl_for(\n database=self.database,\n old_ip=self.source_host.address,\n new_ip=self.destination_host.address,\n old_sa=self.source_host.infra.service_account,\n new_sa=self.destination_host.infra.service_account\n )\n\n\nclass ReplicateAclsMigrate(ReplicateAcls2NewInstance):\n\n @property\n def source_host(self):\n return self.host_migrate.host\n\n @property\n def destination_host(self):\n return self.host\n\n\nclass BindNewInstance(ACLStep):\n\n def __unicode__(self):\n return \"Binding new instance ...\"\n\n def __init__(self, instance):\n super(BindNewInstance, self).__init__(instance)\n self.instances = [self.instance]\n self.instance_address_list = [self.instance.address]\n\n @property\n def acl_from_hell_client(self):\n return ACLFromHellClient(self.environment)\n\n def get_rule(self):\n resp = self.acl_from_hell_client.get_rule(self.database)\n\n if resp.ok:\n return resp.json()\n\n return None\n\n def add_acl_for(self, database):\n tsuru_rules = self.get_rule()\n if tsuru_rules:\n rule = tsuru_rules[0]\n app_name = rule.get('Source', {}).get('TsuruApp', {}).get('AppName')\n if app_name:\n self.acl_from_hell_client.add_acl_for_vip_if_needed(\n database,\n app_name\n )\n return self.acl_from_hell_client.add_acl(\n database,\n app_name,\n self.host.hostname\n )\n else:\n raise CantSetACLError(\"App name not found on data\")\n\n return None\n\n def do(self):\n if not self.database:\n return\n\n resp = self.add_acl_for(self.database)\n if resp and not resp.ok:\n raise CantSetACLError(resp.content)\n\n def undo(self):\n if not self.database:\n return\n","sub_path":"dbaas/workflow/steps/util/acl.py","file_name":"acl.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"91641208","text":"try:\n import tensorflow as tf\n import tensorflow.keras as keras\n from tensorflow.python.keras import backend\n from tensorflow.python.keras.engine import training\n from tensorflow.python.keras.applications import imagenet_utils\n from tensorflow.python.lib.io import file_io\n from tensorflow.python.keras.utils import data_utils, layer_utils\n import tensorflow_addons as tfa\nexcept ImportError:\n print(\"\\nPlease run `pip install -r requirements_tf.txt`\\n\")\n raise\n\nfrom layers import BatchNormZeroBias\n\nBASE_WEIGHTS_PATH = ('https://storage.googleapis.com/tensorflow/keras-applications/resnet/')\n\nWEIGHTS_HASHES = {\n 'resnet50': ('2cb95161c43110f7111970584f804107',\n '4d473c1dd8becc155b73f8504c6f6626'),\n 'resnet101': ('f1aeb4b969a6efcfb50fad2f0c20cfc5',\n '88cf7a10940856eca736dc7b7e228a21'),\n 'resnet152': ('100835be76be38e30d865e96f2aaae62',\n 'ee4c566cf9a93f14d82f913c2dc6dd0c'),\n 'resnet50v2': ('3ef43a0b657b3be2300d5770ece849e0',\n 'fac2f116257151a9d068a22e544a4917'),\n 'resnet101v2': ('6343647c601c52e1368623803854d971',\n 'c0ed64b8031c3730f411d2eb4eea35b5'),\n 'resnet152v2': ('a49b44d1979771252814e80f8ec446f9',\n 'ed17cf2e0169df9d443503ef94b23b33'),\n 'resnext50': ('67a5b30d522ed92f75a1f16eef299d1a',\n '62527c363bdd9ec598bed41947b379fc'),\n 'resnext101':\n ('34fb605428fcc7aa4d62f44404c11509', '0f678c91647380debd923963594981b3')\n}\n\n\ndef ResNetIFN(stack_fn,\n model_name='resnet',\n include_top=True,\n weights='imagenet',\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=1000,\n classifier_activation='softmax'):\n \"\"\"Instantiates the ResNetIFN architecture.\n\n Arguments:\n stack_fn: a function that returns output tensor for the\n stacked residual blocks.\n use_bias: whether to use biases for convolutional layers or not\n (True for ResNet and ResNetV2, False for ResNeXt).\n model_name: string, model name.\n include_top: whether to include the fully-connected\n layer at the top of the network.\n weights: one of `None` (random initialization),\n 'imagenet' (pre-training on ImageNet),\n or the path to the weights file to be loaded.\n input_tensor: optional Keras tensor\n (i.e. output of `layers.Input()`)\n to use as image input for the model.\n input_shape: optional shape tuple, only to be specified\n if `include_top` is False (otherwise the input shape\n has to be `(224, 224, 3)` (with `channels_last` data format)\n or `(3, 224, 224)` (with `channels_first` data format).\n It should have exactly 3 inputs channels.\n pooling: optional pooling mode for feature extraction\n when `include_top` is `False`.\n - `None` means that the output of the model will be\n the 4D tensor output of the\n last convolutional layer.\n - `avg` means that global average pooling\n will be applied to the output of the\n last convolutional layer, and thus\n the output of the model will be a 2D tensor.\n - `max` means that global max pooling will\n be applied.\n classes: optional number of classes to classify images\n into, only to be specified if `include_top` is True, and\n if no `weights` argument is specified.\n classifier_activation: A `str` or callable. The activation function to use\n on the \"top\" layer. Ignored unless `include_top=True`. Set\n `classifier_activation=None` to return the logits of the \"top\" layer.\n Returns:\n A `keras.Model` instance.\n Raises:\n ValueError: in case of invalid argument for `weights`,\n or invalid input shape.\n ValueError: if `classifier_activation` is not `softmax` or `None` when\n using a pretrained top layer.\n \"\"\"\n\n if not (weights in {'imagenet', None} or file_io.file_exists(weights)):\n raise ValueError('The `weights` argument should be either '\n '`None` (random initialization), `imagenet` '\n '(pre-training on ImageNet), '\n 'or the path to the weights file to be loaded.')\n\n if weights == 'imagenet' and include_top and classes != 1000:\n raise ValueError('If using `weights` as `\"imagenet\"` with `include_top`'\n ' as true, `classes` should be 1000')\n\n # Determine proper input shape\n input_shape = imagenet_utils.obtain_input_shape(input_shape,\n default_size=224,\n min_size=32,\n data_format=backend.image_data_format(),\n require_flatten=include_top,\n weights=weights)\n\n if input_tensor is None:\n img_input = keras.layers.Input(shape=input_shape)\n else:\n if not backend.is_keras_tensor(input_tensor):\n img_input = keras.layers.Input(tensor=input_tensor, shape=input_shape)\n else:\n img_input = input_tensor\n\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n\n x = keras.layers.ZeroPadding2D(padding=((3, 3), (3, 3)),\n name='conv1_pad')(img_input)\n x = keras.layers.Conv2D(64, 7, strides=2,\n use_bias=False,\n name='conv1_conv')(x)\n\n x = keras.layers.BatchNormalization(axis=bn_axis,\n epsilon=1.001e-5,\n name='conv1_bn')(x)\n x = keras.layers.Activation('relu',\n name='conv1_relu')(x)\n\n x = keras.layers.ZeroPadding2D(padding=((1, 1), (1, 1)),\n name='pool1_pad')(x)\n x = keras.layers.MaxPooling2D(3,\n strides=2,\n name='pool1_pool')(x)\n\n x = stack_fn(x)\n\n if include_top:\n x = keras.layers.GlobalAveragePooling2D(name='avg_pool')(x)\n # Use custom BatchNorm class to implement zero bias BN\n x = BatchNormZeroBias(axis=bn_axis,\n epsilon=1e-5,\n momentum=0.9)(x) \n x = keras.layers.Dense(classes,\n activation=classifier_activation,\n name='predictions',\n use_bias=False)(x)\n else:\n if pooling == 'avg':\n x = keras.layers.GlobalAveragePooling2D(name='avg_pool')(x)\n elif pooling == 'max':\n x = keras.layers.GlobalMaxPooling2D(name='max_pool')(x)\n # Use custom BatchNorm class to implement zero bias BN\n x = BatchNormZeroBias(axis=bn_axis,\n epsilon=1e-5,\n momentum=0.9)(x)\n\n # Ensure that the model takes into account\n # any potential predecessors of `input_tensor`.\n if input_tensor is not None:\n inputs = layer_utils.get_source_inputs(input_tensor)\n else:\n inputs = img_input\n\n # Create model.\n model = training.Model(inputs, x, name=model_name)\n\n # Load weights.\n if (weights == 'imagenet') and (model_name in WEIGHTS_HASHES):\n if include_top:\n file_name = model_name + '_weights_tf_dim_ordering_tf_kernels.h5'\n file_hash = WEIGHTS_HASHES[model_name][0]\n else:\n file_name = model_name + '_weights_tf_dim_ordering_tf_kernels_notop.h5'\n file_hash = WEIGHTS_HASHES[model_name][1]\n weights_path = data_utils.get_file(file_name,\n BASE_WEIGHTS_PATH + file_name,\n cache_subdir='models',\n file_hash=file_hash)\n model.load_weights(weights_path)\n elif weights is not None:\n model.load_weights(weights)\n\n return model\n\n\ndef block(x, filters, kernel_size=3, stride=1, conv_shortcut=True, name=None, IN=False):\n \"\"\"A residual block with instance normalization.\n Arguments:\n x: input tensor.\n filters: integer, filters of the bottleneck layer.\n kernel_size: default 3, kernel size of the bottleneck layer.\n stride: default 1, stride of the first layer.\n conv_shortcut: default True, useconvolution shortcut if True,\n otherwise identity shortcut.\n name: string, block label.\n IN: default False, apply instance normalization to block if True.\n Returns:\n Output tensor for the residual block.\n \"\"\"\n bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1\n\n if conv_shortcut:\n shortcut = keras.layers.Conv2D(\n 4 * filters, 1, strides=stride, name=name + '_0_conv')(x)\n shortcut = keras.layers.BatchNormalization(\n axis=bn_axis, epsilon=1.001e-5, name=name + '_0_bn')(shortcut)\n else:\n shortcut = x\n\n x = keras.layers.Conv2D(filters, 1, strides=stride, name=name + '_1_conv')(x)\n x = keras.layers.BatchNormalization(\n axis=bn_axis, epsilon=1.001e-5, name=name + '_1_bn')(x)\n x = keras.layers.Activation('relu', name=name + '_1_relu')(x)\n\n x = keras.layers.Conv2D(\n filters, kernel_size, padding='SAME', name=name + '_2_conv')(x)\n x = keras.layers.BatchNormalization(\n axis=bn_axis, epsilon=1.001e-5, name=name + '_2_bn')(x)\n x = keras.layers.Activation('relu', name=name + '_2_relu')(x)\n\n x = keras.layers.Conv2D(4 * filters, 1, name=name + '_3_conv')(x)\n x = keras.layers.BatchNormalization(\n axis=bn_axis, epsilon=1.001e-5, name=name + '_3_bn')(x)\n\n x = keras.layers.Add(name=name + '_add')([shortcut, x])\n if IN:\n x = tfa.layers.InstanceNormalization(axis=3, epsilon=1e-5)(x)\n x = keras.layers.Activation('relu', name=name + '_out')(x)\n return x\n\n\ndef stack(x, filters, blocks, stride1=2, name=None, IN=True):\n \"\"\"A set of stacked residual blocks.\n Arguments:\n x: input tensor.\n filters: integer, filters of the bottleneck layer in a block.\n blocks: integer, blocks in the stacked blocks.\n stride1: default 2, stride of the first layer in the first block.\n name: string, stack label.\n IN: default True, apply instance normalization to last block if True.\n Returns:\n Output tensor for the stacked blocks.\n \"\"\"\n x = block(x, filters,\n stride=stride1,\n name=name + '_block1')\n for i in range(2, blocks):\n x = block(x, filters,\n conv_shortcut=False,\n name=name + '_block' + str(i))\n x = block(x, filters,\n conv_shortcut=False,\n name=name + '_block' + str(i + 1),\n IN=True)\n return x\n\n\ndef DualNormResNet50(include_top=True,\n weights='imagenet',\n input_tensor=None,\n input_shape=None,\n pooling=None,\n classes=1000):\n \"\"\"Instantiates a DualNorm model with a ResNet50 backbone.\"\"\"\n\n def stack_fn(x):\n x = stack(x, 64, 3, stride1=1, name='conv2')\n x = stack(x, 128, 4, name='conv3')\n x = stack(x, 256, 6, name='conv4')\n x = stack(x, 512, 3, name='conv5', IN=False)\n return x\n\n return ResNetIFN(stack_fn, 'resnet50', include_top, weights,\n input_tensor, input_shape, pooling, classes)\n","sub_path":"tensorflow/models/resnet_ifn.py","file_name":"resnet_ifn.py","file_ext":"py","file_size_in_byte":11857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"185407970","text":"import math\nfrom pythonds.graphs import PriorityQueue\n\n\ndef dijkstra(a_graph, start):\n pq = PriorityQueue()\n start.distance = 0\n a_graph.append(start)\n pq.buildHeap([(v.distance, v) for v in a_graph])\n while not pq.isEmpty():\n current_vertex = pq.delMin()\n for next_vertex in current_vertex.connections:\n new_dist = current_vertex.distance \\\n + current_vertex.distance_from(next_vertex)\n if new_dist < next_vertex.distance:\n next_vertex.distance = new_dist\n next_vertex.pred = current_vertex\n pq.decreaseKey(next_vertex, new_dist)\n\n\ndef get_dijkastra_vertex_by_point(dv_arr, p):\n for dv in dv_arr:\n if dv.point == p:\n return dv\n return None\n\n\ndef euclidean_distance(p1, p2):\n return math.sqrt(((p1.x - p2.x) ** 2) + ((p1.y - p2.y) ** 2))\n\n\ndef reverse_dijkstra_path_scan(d_src, d_dest):\n current_ver = d_dest\n path = [d_dest.point]\n while current_ver.point != d_src.point:\n current_ver = current_ver.pred\n path.append(current_ver.point)\n return path\n\n\ndef get_points_path_with_dijakstra(world, p_src, p_dest):\n d_src = DijkstraVertex(p_src)\n d_dest = DijkstraVertex(p_dest)\n dijkstra_vertexes = create_dijkstra_vertexes_base(world, d_src, d_dest)\n dijkstra(dijkstra_vertexes, d_src)\n dijkstra_vertexes.remove(d_src)\n d_dest = get_dijkastra_vertex_by_point(dijkstra_vertexes, p_dest)\n path = reverse_dijkstra_path_scan(d_src, d_dest)\n return path[::-1]\n\n\ndef create_dijkstra_vertexes_base(world, d_src, d_dest):\n dijkstra_vertexes = [d_dest]\n excluded_list = []\n for obstacle in world['obstacles']:\n for p in obstacle:\n fill_connections_and_add_to_base(\n world, p, dijkstra_vertexes, excluded_list, d_dest)\n if d_src not in dijkstra_vertexes:\n for d_v in dijkstra_vertexes:\n if is_valid_path(world, d_src.point, d_v.point):\n set_meutual_connection(d_v, d_src)\n # for vertex in dijkstra_vertexes:\n # deleted_vertexes = []\n # for obstacle in world['obstacles']:\n # if (obstacle[0].x == vertex.point.x == obstacle[1].x and obstacle[0].y < vertex.point.y < obstacle[1].y) or (obstacle[0].y == vertex.point.y == obstacle[1].y and obstacle[0].x < vertex.point.x < obstacle[1].x):\n # deleted_vertexes.append(vertex)\n # break\n # for vertex in deleted_vertexes:\n # dijkstra_vertexes.remove(vertex)\n\n return dijkstra_vertexes\n\n\ndef fill_connections_and_add_to_base(world, p, dijkstra_vertexes, excluded_list, d_dest):\n d_p = DijkstraVertex(p)\n for vertex in dijkstra_vertexes:\n if (d_p in dijkstra_vertexes) and (p != d_dest.point):\n excluded_list.append(p)\n excluded_list = list(set(excluded_list))\n dijkstra_vertexes.remove(d_p)\n if (p not in excluded_list) and (is_valid_path(world, p, vertex.point)):\n set_meutual_connection(vertex, d_p)\n if (d_p not in dijkstra_vertexes) and (p not in excluded_list):\n dijkstra_vertexes.append(d_p)\n\n\ndef is_valid_path(world, p_robot, p_dest):\n if is_on_border(world, [p_robot, p_dest]):\n return False\n for obstacle in world['obstacles']:\n if (obstacle[0].x == p_robot.x == obstacle[1].x and obstacle[0].y < p_robot.y < obstacle[1].y) or (obstacle[0].y == p_robot.y == obstacle[1].y and obstacle[0].x < p_robot.x < obstacle[1].x):\n return False\n if (p_dest not in obstacle) and (p_robot not in obstacle) and (is_lines_crossing(p_robot, p_dest, obstacle[0], obstacle[1])):\n return False\n return True\n\n\ndef is_lines_crossing(crossing_p1, crossing_p2, crossed_p1, crossed_p2):\n if (crossing_p1.x > crossed_p1.x) and (crossing_p1.x > crossed_p2.x) and (crossing_p2.x > crossed_p1.x) and (crossing_p2.x > crossed_p2.x):\n return False\n if (crossing_p1.x < crossed_p1.x) and (crossing_p1.x < crossed_p2.x) and (crossing_p2.x < crossed_p1.x) and (crossing_p2.x < crossed_p2.x):\n return False\n if (crossing_p1.y > crossed_p1.y) and (crossing_p1.y > crossed_p2.y) and (crossing_p2.y > crossed_p1.y) and (crossing_p2.y > crossed_p2.y):\n return False\n if (crossing_p1.y < crossed_p1.y) and (crossing_p1.y < crossed_p2.y) and (crossing_p2.y < crossed_p1.y) and (crossing_p2.y < crossed_p2.y):\n return False\n if (crossing_p1.x == crossing_p2.x) and (crossed_p1.y == crossed_p2.y):\n if (crossed_p1.y < max(crossing_p1.y, crossing_p2.y)) and (crossed_p1.y > min(crossing_p1.y, crossing_p2.y)):\n return True\n else:\n return False\n if crossing_p1.x == crossing_p2.x:\n return False\n if (crossing_p1.y == crossing_p2.y) and (crossed_p1.x == crossed_p2.x):\n if (crossed_p1.x < max(crossing_p1.x, crossing_p2.x)) and (crossed_p1.x > min(crossing_p1.x, crossing_p2.x)):\n return True\n else:\n return False\n if crossing_p1.y == crossing_p2.y:\n return False\n if crossed_p1.y == crossed_p2.y:\n x = Vectors.find_x_of_intersection(\n crossing_p1, crossing_p2, crossed_p1.y)\n if (x < max(crossed_p1.x, crossed_p2.x)) and (x > min(crossed_p1.x, crossed_p2.x)):\n return True\n return False\n else:\n y = Vectors.find_y_of_intersection(\n crossing_p1, crossing_p2, crossed_p1.x)\n if (y < max(crossed_p1.y, crossed_p2.y)) and (y > min(crossed_p1.y, crossed_p2.y)):\n return True\n return False\n\n\ndef set_meutual_connection(dv1, dv2):\n dv1.add_connection(dv2)\n dv2.add_connection(dv1)\n\n\ndef is_on_border(world, points):\n for p in points:\n if (p.x == 0) or (p.y == 0) or (p.x == world['width']) or (p.y == world['height']):\n return True\n return False\n\n\nclass DijkstraVertex:\n\n def __init__(self, point):\n self.point = point\n self.distance = 10000000\n self.connections = []\n self.pred = None\n\n def __eq__(self, other):\n return self.point == other.point\n\n def __str__(self):\n if self.pred is None:\n return \"point: {}, distance: {}, Pred: None\".format(self.point, self.distance)\n return \"point: {}, distance: {}, Pred: {}\".format(self.point, self.distance, self.pred.point)\n\n def distance_from(self, other):\n return euclidean_distance(self.point, other.point)\n\n def add_connection(self, other):\n self.connections.append(other)\n\n\nclass Vectors:\n\n @staticmethod\n def normalize(point):\n return point/Vectors.norma(point)\n\n @staticmethod\n def norma(point):\n return math.sqrt((point.x ** 2) + (point.y ** 2))\n\n @staticmethod\n def find_m(p1, p2):\n if (p1.x - p2.x) == 0:\n return None\n return (p1.y - p2.y)/(p1.x - p2.x)\n\n @staticmethod\n def find_b(p, m):\n return p.y - (m * p.x)\n\n @staticmethod\n def find_x_of_intersection(p1, p2, intersection_y):\n m = Vectors.find_m(p1, p2)\n return (intersection_y - Vectors.find_b(p1, m))/m\n\n @staticmethod\n def find_y_of_intersection(p1, p2, intersection_x):\n m = Vectors.find_m(p1, p2)\n return (m * intersection_x) + Vectors.find_b(p1, m)\n","sub_path":"model/utils/dijakstra.py","file_name":"dijakstra.py","file_ext":"py","file_size_in_byte":7253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"408454240","text":"'''\nMap_Util.py\n \nAuthor: Conor Tracey\n\nCreated: April 21, 2016\nLast Updated: April 21, 2016\n\nContains functions to assist in making google maps in flask\n\nDependencies:\n flask_googlemaps flask extension\n >>> pip3 install flask-googlemaps\n'''\n\nfrom flask_googlemaps import GoogleMaps\nfrom flask_googlemaps import Map\n\n\n# To use one of these maps, go into the templates, and in the html\n# file you want the map to appear in, between and type:\n# {{name_of_map.js}}\n# then type {{name_of_map.html}} where you want in in the page\n#\n# You will also need to render the map in the template_render function in flask\ndef make_map(pu_lat, pu_long, dr_lat, dr_long):\n '''\n (float, float) -> Map\n\n takes pickup lattitude/longitude and dropoff lattitude/longitude\n and returns a flask google map (for use in template rendering)\n with markers representing the pickup dropoff locations\n '''\n\n map = Map(\n identifier=\"view-side\",\n zoom = 12,\n style = \"height:450px;width:450px;margin:0;\",\n lat=44.047705,\n lng=-123.086681,\n markers={'http://maps.google.com/mapfiles/ms/icons/green-dot.png':[(pu_lat,pu_long)],\n 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png':[(dr_lat, dr_long)]}\n )\n\n return map\n","sub_path":"Map_Util.py","file_name":"Map_Util.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"234694064","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\ndef get_and_dismiss_messages(element):\n messages = element.find_elements_by_css_selector(\"div.messages div.alert\")\n collect = []\n for message in messages:\n text = message.find_element_by_css_selector(\"p, div\").text\n message.find_element_by_css_selector(\"a.close\").click()\n collect.append(text)\n return collect\n\n\ndef find_already_visible_element_by_xpath(element, driver):\n return WebDriverWait(driver, 160).until(\n EC.visibility_of_element_located((By.XPATH, element)))\n\n\ndef select_from_dropdown(element, label):\n menu_button = element.find_element_by_css_selector(\n \"a[data-toggle='dropdown']\"\n )\n menu_button.click()\n options = element.find_element_by_css_selector(\"ul.dropdown-menu\")\n selection = options.find_element_by_xpath(\n f\"li/button[text()[contains(.,'{label}')]]\"\n )\n selection.click()\n\n\ndef confirm_modal(element):\n confirm = element.find_element_by_css_selector(\n \"#modal_wrapper a.btn-danger\"\n )\n confirm.click()\n","sub_path":"openstack_dashboard/test/selenium/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88965959","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, FloatField, SelectField\nfrom wtforms.validators import InputRequired, Length, ValidationError\nimport datetime\n\nCURRENCY_TYPE = [(\"EUR\", \"EUR\"), (\"USD\", \"USD\"), (\"JPY\", \"JPY\"),\n (\"BGN\", \"BGN\"), (\"CZK\", \"CZK\"), (\"GBP\", \"GBP\"),\n (\"HUF\", \"HUF\"), (\"PLN\", \"PLN\"), (\"RON\", \"RON\"),\n (\"SEK\", \"SEK\"), (\"CHF\", \"CHF\"), (\"ISK\", \"ISK\"),\n (\"NOK\", \"NOK\"), (\"HRK\", \"HRK\"), (\"RUB\", \"RUB\"),\n (\"TRY\", \"TRY\"), (\"AUD\", \"AUD\"), (\"BRL\", \"BRL\"),\n (\"CAD\", \"CAD\"), (\"CNY\", \"CNY\"), (\"HKD\", \"HKD\"),\n (\"IDR\", \"IDR\"), (\"ILS\", \"ILS\"), (\"INR\", \"INR\"),\n (\"KRW\", \"KRW\"), (\"MXN\", \"MXN\"), (\"MYR\", \"MYR\"),\n (\"NZD\", \"NZD\"), (\"PHP\", \"PHP\"), (\"SGD\", \"SGD\"),\n (\"THB\", \"THB\"), (\"ZAR\", \"ZAR\"), (\"DKK\", \"DKK\")]\n\n\n# custom validator for the form,\n# to check if date has a valid format and exsit in DB\ndef date_validate(form, field):\n date_text = field.data\n # Make sure the date has a correct format\n try:\n time = datetime.datetime.strptime(date_text, '%Y-%m-%d')\n except ValueError:\n raise ValidationError(\"Incorrect date format, should be YYYY-MM-DD\")\n\n\nclass CurrencyCovert(FlaskForm):\n \"\"\"CurrencyCovert form\"\"\"\n\n src_currency = SelectField('source currency',\n choices=CURRENCY_TYPE,\n validators=[InputRequired(message=\"currency required\")])\n\n dest_currency = SelectField('destination currency',\n choices=CURRENCY_TYPE,\n validators=[InputRequired(message=\"currency required\")])\n\n amount = FloatField('amount',\n validators=[InputRequired(message=\"amount required\")])\n\n date = StringField('reference date',\n validators=[InputRequired(message=\"Date required\"),\n date_validate])\n","sub_path":"wtform_fields.py","file_name":"wtform_fields.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"383255232","text":"\"\"\"All networks, highlighting routes used by OD flows\n\"\"\"\n# pylint: disable=C0103\nimport os\nimport sys\n\nimport cartopy.crs as ccrs\nimport cartopy.io.shapereader as shpreader\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))\nfrom scripts.utils import *\n\nconfig = load_config()\ndata_path = config['data_path']\nfigures_path = config['figures_path']\n\n# Input data\ninf_path = os.path.join(data_path, 'Infrastructure')\nstats_path = os.path.join(data_path, 'results', 'result_shapefiles')\n\n# Icons\nresource_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'resources')\nboat_icon_filename = os.path.join(resource_path, 'boat.png')\nplane_icon_filename = os.path.join(resource_path, 'plane.png')\n\n# Border crossings\nnodes = {\n \"road\": read_border_geoms_and_labels(\n \"road\",\n os.path.join(\n inf_path, 'Roads', 'road_shapefiles', 'tanroads_nodes_main_all_2017_adj.shp')\n ),\n \"rail\": read_border_geoms_and_labels(\n \"rail\",\n os.path.join(\n inf_path, 'Railways', 'railway_shapefiles', 'tanzania-rail-nodes-processed.shp')\n ),\n \"port\": read_border_geoms_and_labels(\n \"port\",\n os.path.join(\n inf_path, 'Ports', 'port_shapefiles', 'tz_port_nodes.shp')\n ),\n \"air\": read_border_geoms_and_labels(\n \"air\",\n os.path.join(\n inf_path, 'Airports', 'airport_shapefiles', 'tz_od_airport_nodes.shp')\n )\n}\n\n# Read flows\nstats = {}\nfor sector in [\"port\", \"rail\", \"road\"]:\n filename = os.path.join(stats_path, \"{}_stats_2016.shp\".format(\n sector\n ))\n if sector == \"road\":\n stats[\"road_trunk\"] = [\n record\n for record in shpreader.Reader(filename).records()\n if record.attributes['roadclass'] == 'T'\n ]\n stats[\"road_regional\"] = [\n record\n for record in shpreader.Reader(filename).records()\n if record.attributes['roadclass'] != 'T'\n ]\n else:\n stats[sector] = list(shpreader.Reader(filename).records())\n\n# Plot maps\nplots = [\n (\"Transit\", \"tr_ftype\"),\n (\"Import/export\", \"imexp_ftyp\"),\n (\"Domestic\", \"d_ftype\"),\n]\nsector_colors = {\n \"port\": '#051591',\n \"road_trunk\": '#d1170a',\n \"road_regional\": '#ed9a36',\n \"rail\": '#33a02c',\n}\n\nproj_lat_lon = ccrs.PlateCarree()\n\nfor label, column in plots:\n print(label)\n ax = get_tz_axes()\n plot_basemap(ax, data_path)\n plot_basemap_labels(ax, data_path)\n plot_border_crossings(ax, nodes, resource_path, show_labels=False)\n\n for sector in [\"port\", \"rail\", \"road_trunk\", \"road_regional\"]:\n fg_geoms = [\n record.geometry\n for record in stats[sector]\n if record.attributes[column]\n ]\n ax.add_geometries(\n fg_geoms,\n crs=proj_lat_lon,\n edgecolor=sector_colors[sector],\n alpha=1,\n facecolor='none'\n )\n bg_geoms = [\n record.geometry\n for record in stats[sector]\n if not record.attributes[column]\n ]\n ax.add_geometries(\n bg_geoms,\n crs=proj_lat_lon,\n edgecolor=sector_colors[sector],\n alpha=0.2,\n facecolor='none'\n )\n\n # Legend\n boat_icon_filename = os.path.join(resource_path, 'boat.png')\n plane_icon_filename = os.path.join(resource_path, 'plane.png')\n\n boat_handle = mpatches.Patch()\n plane_handle = mpatches.Patch()\n road_handle = mpatches.Patch(color=sector_colors['road_trunk'])\n road_regional_handle = mpatches.Patch(color=sector_colors['road_regional'])\n rail_handle = mpatches.Patch(color=sector_colors['rail'])\n port_handle = mpatches.Patch(color=sector_colors['port'])\n\n plt.legend(\n [plane_handle, boat_handle, road_handle, road_regional_handle, rail_handle, port_handle],\n [\"Airport\", \"Port\", \"Trunk Roads\", \"Regional Roads\", \"Rail\", \"Waterway\"],\n handler_map={\n boat_handle: HandlerImage(boat_icon_filename),\n plane_handle: HandlerImage(plane_icon_filename),\n },\n loc='lower left')\n\n output_filename = os.path.join(figures_path, \"flow_routes_{}.png\".format(\n column.replace(\"_ftype\", \"\")\n ))\n plt.savefig(output_filename)\n plt.close()\n","sub_path":"scripts/3_plot/flows/create_flow_routes_maps.py","file_name":"create_flow_routes_maps.py","file_ext":"py","file_size_in_byte":4379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"391288441","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGrading\n\n\"\"\"\n\n#These are the packages you need to install, this will try to install them, otherwise use pip to install\n\ntry:\n import requests\nexcept:\n import pip\n pip.main(['install', 'requests'])\n import requests\n \ntry:\n import pandas as pd\nexcept:\n import pip\n pip.main(['install', 'pandas'])\n import pandas as pd\n \ntry:\n import json\nexcept:\n import pip\n pip.main(['install', 'json'])\n import json\n\n#Ensure Canvas API token is in the designated file Canvas API Token.txt\nprint ('Before you begin the process, please ensure you have copy & pasted your Canvas API token into the file Canvas API Token.txt.')\nconfirmation = input ('Input any key to continue:')\n\nwith open('Canvas API Token.txt','r') as f:\n for line in f:\n for word in line.split():\n token = word \n#Course url\nurl = \"https://ubc.instructure.com/\"\n\n#Course number\ncourse = input('Input course ID and hit ENTER:\\n')\n\n#Input assignment ID number (located in URL)\nassignment_id = input('Input assignment ID number and hit ENTER:\\n')\n\nprint ('Processing data, please wait......\\n')\n\ntry:\n#Obtaining the assignment information (settings, assignment id, rubric id)\n assignmentInfo = requests.get(url + '/api/v1/courses/' + str(course) + '/assignments/' + str(assignment_id),\n headers= {'Authorization': 'Bearer ' + token})\n\n#Extracting assignment rubric id/rubric for the assignment\n assignmentInfo = json.loads(assignmentInfo.text)\n rubric_id = str(assignmentInfo['rubric_settings']['id'])\n\n payload = {'include': 'peer_assessments',\n 'style' : 'full'}\n r = requests.get(url + '/api/v1/courses/' + str(course) + '/rubrics/' + rubric_id,\n params = payload,\n headers= {'Authorization': 'Bearer ' + token})\n\n rubric_return = json.loads(r.text)\n\n#Obtaining assessor_id (person who did peer review), score for the peer reviews\n assessments_df = pd.DataFrame(rubric_return['assessments'])\n\n\n#Obtaining user_id (person who was peer reviewed), completion and submission comments\n peerReview = requests.get(url + '/api/v1/courses/' + str(course) + '/assignments/' + assignment_id + '/peer_reviews',\n headers= {'Authorization': 'Bearer ' + token})\n\n peerReviewInfo = json.loads(peerReview.text)\n peerReview_df = pd.read_json(peerReview.text)\n peerReview_df['user_id'] = peerReview_df['user_id'].astype(str)\n\n#Merging data together into one csv file named 'peer review information.csv'\n merged_df = pd.merge(peerReview_df, assessments_df, how='outer', left_on=['assessor_id', 'asset_id'], right_on=['assessor_id', 'artifact_id'])\n merged_df.to_csv('peer review information.csv')\n\n#Create a table table with user_id and mean peer review score of each assignment\n#(make sure the mean score is rounded to 2, and the user_id is a string)\n meanScore = pd.DataFrame(merged_df.groupby('user_id')['score'].mean().round(2).reset_index())\n meanScore = meanScore[pd.notnull(meanScore['score'])]\n meanScore['user_id'] = meanScore['user_id'].astype(str)\n meanScore.to_csv(\"course_\" + course + \"_\" + \"assignment_\" + assignment_id + '_complete mean score.csv')\n\n \n print('Data successfully gathered.\\n')\n#if input is True, uploads scores onto Canvas Gradecenter (does not create new assignment)\n upload = input ('Type True to upload peer review scores onto Gradecenter.\\n')\n\n if upload==True:\n for index, row in meanScore.iterrows():\n \n student_id = str(row['user_id'])\n print(student_id)\n score = str(row['score'])\n \n \n payload = {'submission[posted_grade]': score}\n \n r = requests.put(url + '/api/v1/courses/' + str(course) + '/assignments/' + str(assignment_id) +'/submissions/' + str(student_id) + '/', params=payload, headers= {'Authorization': 'Bearer ' + token})\n print('Data successfully uploaded.')\n else: \n print('Data not uploaded')\n \nexcept KeyError:\n print (\"Something went wrong. Perhaps you provided an invalid.....\\n\")\n print (\"Course ID?\")\n print (\"Canvas API Token?\")\n print (\"Assignment ID?\")\n \n \n \n","sub_path":"peer_review_average.py","file_name":"peer_review_average.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"545930017","text":"#!/usr/bin/python3\n# -*- encoding: utf-8 -*-\n\n'''\nFile:\n ngnrgrid.py\nDescription:\n Implementation of 5GNR resource grid.\nChange History:\n 2018-12-28 v0.1 created. github/zhenggao2\n'''\n\nimport math\nimport os\nimport time\nfrom enum import Enum\nfrom collections import OrderedDict\nimport numpy as np\n#from openpyxl import Workbook\nimport xlsxwriter\nimport ngmainwin\n\nclass NrResType(Enum):\n NR_RES_PSS = 0\n NR_RES_SSS = 1\n NR_RES_PBCH = 2\n NR_RES_SIB1 = 3\n NR_RES_PDCCH = 4\n NR_RES_PDSCH = 5\n NR_RES_CSI_RS = 6\n NR_RES_MSG2 = 7\n NR_RES_MSG4 = 8\n \n NR_RES_PRACH = 10\n NR_RES_PUCCH = 11\n NR_RES_PUSCH = 12\n NR_RES_SRS = 13\n NR_RES_MSG3 = 14 \n \n NR_RES_DMRS_PBCH = 20\n NR_RES_DMRS_SIB1 = 21\n NR_RES_DMRS_PDCCH = 22 \n NR_RES_DMRS_PDSCH = 23\n NR_RES_DMRS_MSG2 = 24\n NR_RES_DMRS_MSG4 = 25\n \n NR_RES_DMRS_PUCCH = 30 \n NR_RES_DMRS_PUSCH = 31 \n NR_RES_DMRS_MSG3 = 32 \n \n NR_RES_PTRS_PDSCH = 40 \n NR_RES_PTRS_PUSCH = 41 \n \n NR_RES_DTX = 50 \n \n NR_RES_D = 60 \n NR_RES_F = 61 \n NR_RES_U = 62 \n NR_RES_GB = 63\n \n NR_RES_BUTT = 99\n\nclass NgNrGrid(object):\n def __init__(self, ngwin, args):\n self.ngwin = ngwin\n self.args = args\n if not self.init():\n return\n \n def init(self):\n self.ngwin.logEdit.append('---->inside init')\n \n #HSFN not exit in NR specs, but used in 5GNR resource grid for convenience\n self.hsfn = 0\n \n self.nrSubfPerRf = 10\n self.nrSlotPerSubf = [2 ** mu for mu in range(5)]\n self.nrSlotPerRf = [self.nrSubfPerRf * 2 ** mu for mu in range(5)]\n self.nrScs2Mu = {15:0, 30:1, 60:2, 120:3, 240:4}\n self.nrSymbPerSlotNormCp = 14\n self.nrSymbPerSlotExtCp = 12\n self.nrScPerPrb = 12\n \n self.baseScsFd = 15 if self.args['freqBand']['freqRange'] == 'FR1' else 60 \n self.baseScsTd = 60 if self.args['freqBand']['freqRange'] == 'FR1' else 240 \n \n self.nrCarrierScs = int(self.args['carrierGrid']['scs'][:-3])\n self.nrCarrierMinGuardBand = int(self.args['carrierGrid']['minGuardBand'])\n self.nrCarrierNumRbs = int(self.args['carrierGrid']['numRbs'])\n \n self.nrScTot = self.nrScPerPrb * (self.nrCarrierMinGuardBand + self.nrCarrierNumRbs) * (self.nrCarrierScs // self.baseScsFd)\n self.nrScGb = self.nrScPerPrb * self.nrCarrierMinGuardBand * (self.nrCarrierScs // self.baseScsFd)\n self.nrSymbPerRfNormCp = self.nrSymbPerSlotNormCp * self.nrSlotPerRf[self.nrScs2Mu[self.baseScsTd]]\n \n self.nrDuplexMode = self.args['freqBand']['duplexMode']\n self.nrMibSfn = int(self.args['mib']['sfn'])\n \n self.gridNrTdd = OrderedDict()\n self.gridNrFddDl = OrderedDict()\n self.gridNrFddUl = OrderedDict()\n dn = '%s_%s' % (self.hsfn, self.nrMibSfn)\n if self.nrDuplexMode == 'TDD':\n self.gridNrTdd[dn] = np.full((self.nrScTot, self.nrSymbPerRfNormCp), NrResType.NR_RES_GB.value)\n if not self.initTddUlDlConfig():\n return False\n self.initTddGrid(self.hsfn, self.nrMibSfn)\n elif self.nrDuplexMode == 'FDD':\n self.gridNrFddDl[dn] = np.full((self.nrScTot, self.nrSymbPerRfNormCp), NrResType.NR_RES_D.value)\n self.gridNrFddUl[dn] = np.full((self.nrScTot, self.nrSymbPerRfNormCp), NrResType.NR_RES_U.value)\n #init 'min guard band'\n self.gridNrFddDl[dn][:self.nrScGb, :] = NrResType.NR_RES_GB.value\n self.gridNrFddUl[dn][:self.nrScGb, :] = NrResType.NR_RES_GB.value\n else:\n return False\n \n self.outDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')\n if not os.path.exists(self.outDir):\n os.mkdir(self.outDir)\n \n self.nrSsbPeriod = int(self.args['ssbBurst']['period'][:-2])\n self.nrMibHrf = int(self.args['mib']['hrf'])\n self.nrSsbScs = int(self.args['ssbGrid']['scs'][:-3])\n self.nrSsbPattern = self.args['ssbGrid']['pattern']\n self.nrSsbMinGuardBand240k = int(self.args['ssbGrid']['minGuardBand240k']) if self.nrSsbScs == 240 else None\n self.nrSsbKssb = int(self.args['ssbGrid']['kSsb'])\n self.nrSsbNCrbSsb = int(self.args['ssbGrid']['nCrbSsb'])\n self.nrSsbMaxL = int(self.args['ssbBurst']['maxL'])\n self.nrSsbInOneGroup = self.args['ssbBurst']['inOneGroup']\n self.nrSsbGroupPresence = self.args['ssbBurst']['groupPresence'] if self.nrSsbMaxL == 64 else None\n self.nrMibCommonScs = int(self.args['mib']['commonScs'][:-3])\n self.nrPci = int(self.args['pci'])\n \n if self.nrSsbMaxL == 64:\n self.ssbSet = ''\n for group in self.nrSsbGroupPresence:\n if group == '1':\n self.ssbSet += self.nrSsbInOneGroup\n else:\n self.ssbSet += '00000000'\n else:\n self.ssbSet = self.nrSsbInOneGroup[:self.nrSsbMaxL]\n \n self.ngwin.logEdit.append('ssbSet=\"%s\"' % self.ssbSet)\n \n if self.nrSsbPattern == 'Case A' and self.nrSsbScs == 15:\n ssb1 = [2, 8]\n ssb2 = 14\n ssb3 = [0, 1] if self.nrSsbMaxL == 4 else [0, 1, 2, 3]\n elif self.nrSsbPattern == 'Case B' and self.nrSsbScs == 30:\n ssb1 = [4, 8, 16, 20]\n ssb2 = 28 \n ssb3 = [0,] if self.nrSsbMaxL == 4 else [0, 1]\n elif self.nrSsbPattern == 'Case C' and self.nrSsbScs == 30:\n ssb1 = [2, 8]\n ssb2 = 14 \n ssb3 = [0, 1] if self.nrSsbMaxL == 4 else [0, 1, 2, 3]\n elif self.nrSsbPattern == 'Case D' and self.nrSsbScs == 120:\n ssb1 = [4, 8, 16, 20]\n ssb2 = 28 \n ssb3 = [0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18]\n elif self.nrSsbPattern == 'Case E' and self.nrSsbScs == 240:\n ssb1 = [8, 12, 16, 20, 32, 36, 40, 44]\n ssb2 = 56 \n ssb3 = [0, 1, 2, 3, 5, 6, 7, 8]\n else:\n return False\n \n self.ssbFirstSymbSet = []\n for i in ssb1:\n for j in ssb3:\n self.ssbFirstSymbSet.append(i + ssb2 * j)\n self.ssbFirstSymbSet.sort()\n \n ssbFirstSymbSetStr = [] \n for i in range(len(self.ssbSet)):\n ssbFirstSymbSetStr.append(str(self.ssbFirstSymbSet[i]) if self.ssbSet[i] == '1' else '-')\n self.ngwin.logEdit.append('ssb first symbols: \"%s\"' % ','.join(ssbFirstSymbSetStr))\n \n \n return True\n \n def initTddUlDlConfig(self):\n #refer to 3GPP 38.213 vf30\n #11.1\tSlot configuration\n self.tddCfgRefScsPeriod = {\n '0.5ms_0' : None,\n '0.5ms_1' : 1,\n '0.5ms_2' : 2,\n '0.5ms_3' : 4,\n '0.625ms_0' : None,\n '0.625ms_1' : None,\n '0.625ms_2' : None,\n '0.625ms_3' : 5,\n '1ms_0' : 1,\n '1ms_1' : 2,\n '1ms_2' : 4,\n '1ms_3' : 8,\n '1.25ms_0' : None,\n '1.25ms_1' : None,\n '1.25ms_2' : 5,\n '1.25ms_3' : 10,\n '2ms_0' : 2,\n '2ms_1' : 4,\n '2ms_2' : 8,\n '2ms_3' : 16,\n '2.5ms_0' : None,\n '2.5ms_1' : 5,\n '2.5ms_2' : 10,\n '2.5ms_3' : 20,\n '3ms_0' : 3,\n '3ms_1' : 6,\n '3ms_2' : 12,\n '3ms_3' : 24,\n '4ms_0' : 4,\n '4ms_1' : 8,\n '4ms_2' : 16,\n '4ms_3' : 32,\n '5ms_0' : 5,\n '5ms_1' : 10,\n '5ms_2' : 20,\n '5ms_3' : 40,\n '10ms_0' : 10,\n '10ms_1' : 20,\n '10ms_2' : 40,\n '10ms_3' : 80,\n }\n #period is x8 of actual value\n self.tddCfgPeriod2Int = {'0.5ms':4, '0.625ms':5, '1ms':8, '1.25ms':10, '2ms':16, '2.5ms':20, '3ms':24, '4ms':32, '5ms':40, '10ms':80}\n \n self.nrTddCfgRefScs = int(self.args['tddCfg']['refScs'][:-3])\n key = '%s_%s' % (self.args['tddCfg']['pat1Period'], self.nrScs2Mu[self.nrTddCfgRefScs])\n if not key in self.tddCfgRefScsPeriod or self.tddCfgRefScsPeriod[key] is None:\n self.ngwin.logEdit.append('[%s]Error: Invalid key(=\"%s\") when referring tddCfgRefScsPeriod!' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), key))\n return False\n self.pat1NumSlotsPerPeriod = self.tddCfgRefScsPeriod[key]\n self.nrTddCfgPat1NumDlSlots = int(self.args['tddCfg']['pat1NumDlSlots'])\n self.nrTddCfgPat1NumDlSymbs = int(self.args['tddCfg']['pat1NumDlSymbs'])\n self.nrTddCfgPat1NumUlSymbs = int(self.args['tddCfg']['pat1NumUlSymbs'])\n self.nrTddCfgPat1NumUlSlots = int(self.args['tddCfg']['pat1NumUlSlots'])\n \n if self.args['tddCfg']['pat2Period'] != 'not used':\n key = '%s_%s' % (self.args['tddCfg']['pat2Period'], self.nrScs2Mu[self.nrTddCfgRefScs])\n if not key in self.tddCfgRefScsPeriod or self.tddCfgRefScsPeriod[key] is None:\n self.ngwin.logEdit.append('[%s]Error: Invalid key(=\"%s\") when referring tddCfgRefScsPeriod!' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), key))\n return False\n self.pat2NumSlotsPerPeriod = self.tddCfgRefScsPeriod[key]\n self.nrTddCfgPat2NumDlSlots = int(self.args['tddCfg']['pat2NumDlSlots'])\n self.nrTddCfgPat2NumDlSymbs = int(self.args['tddCfg']['pat2NumDlSymbs'])\n self.nrTddCfgPat2NumUlSymbs = int(self.args['tddCfg']['pat2NumUlSymbs'])\n self.nrTddCfgPat2NumUlSlots = int(self.args['tddCfg']['pat2NumUlSlots'])\n \n period = self.tddCfgPeriod2Int[self.args['tddCfg']['pat1Period']] + self.tddCfgPeriod2Int[self.args['tddCfg']['pat2Period']] \n if 160 % period != 0:\n self.ngwin.logEdit.append('[%s]Error: Invalid TDD-UL-DL-Config periodicity(=%.3fms) with p=%.3fms and p2=%.3fms, which should divide 20ms!' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), period/8, self.tddCfgPeriod2Int[self.args['tddCfg']['pat1Period']]/8, self.tddCfgPeriod2Int[self.args['tddCfg']['pat2Period']]/8))\n return False\n else:\n self.pat2NumSlotsPerPeriod = None\n period = self.tddCfgPeriod2Int[self.args['tddCfg']['pat1Period']]\n if 160 % period != 0:\n self.ngwin.logEdit.append('[%s]Error: Invalid TDD-UL-DL-Config periodicity(=%.3fms), which should divide 20ms!' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), period/8))\n return False\n \n self.periodsPer20ms = 160 // period\n \n pattern = []\n pattern.extend(['D'] * self.nrTddCfgPat1NumDlSlots * self.nrSymbPerSlotNormCp)\n pattern.extend(['D'] * self.nrTddCfgPat1NumDlSymbs)\n pattern.extend(['F'] * ((self.pat1NumSlotsPerPeriod - self.nrTddCfgPat1NumDlSlots - self.nrTddCfgPat1NumUlSlots) * self.nrSymbPerSlotNormCp - self.nrTddCfgPat1NumDlSymbs - self.nrTddCfgPat1NumUlSymbs))\n pattern.extend(['U'] * self.nrTddCfgPat1NumUlSymbs)\n pattern.extend(['U'] * self.nrTddCfgPat1NumUlSlots * self.nrSymbPerSlotNormCp)\n \n if self.pat2NumSlotsPerPeriod is None:\n numSlotsPerPeriod = self.pat1NumSlotsPerPeriod\n else:\n numSlotsPerPeriod = self.pat1NumSlotsPerPeriod + self.pat2NumSlotsPerPeriod\n \n pattern.extend(['D'] * self.nrTddCfgPat2NumDlSlots * self.nrSymbPerSlotNormCp)\n pattern.extend(['D'] * self.nrTddCfgPat2NumDlSymbs)\n pattern.extend(['F'] * ((self.pat2NumSlotsPerPeriod - self.nrTddCfgPat2NumDlSlots - self.nrTddCfgPat2NumUlSlots) * self.nrSymbPerSlotNormCp - self.nrTddCfgPat2NumDlSymbs - self.nrTddCfgPat2NumUlSymbs))\n pattern.extend(['U'] * self.nrTddCfgPat2NumUlSymbs)\n pattern.extend(['U'] * self.nrTddCfgPat2NumUlSlots * self.nrSymbPerSlotNormCp)\n \n pattern = pattern * self.periodsPer20ms\n self.tddPatEvenRf = pattern[:self.nrSlotPerRf[self.nrScs2Mu[self.nrTddCfgRefScs]] * self.nrSymbPerSlotNormCp]\n self.tddPatOddRf = pattern[self.nrSlotPerRf[self.nrScs2Mu[self.nrTddCfgRefScs]] * self.nrSymbPerSlotNormCp:]\n \n self.ngwin.logEdit.append('pattern of even frame:')\n for i in range(len(self.tddPatEvenRf)):\n if (i+1) % self.nrSymbPerSlotNormCp == 0:\n self.ngwin.logEdit.append('-->slot%d: %s' % (i // self.nrSymbPerSlotNormCp, ''.join(self.tddPatEvenRf[i-13:i+1])))\n self.ngwin.logEdit.append('pattern of odd frame:')\n for i in range(len(self.tddPatOddRf)):\n if (i+1) % self.nrSymbPerSlotNormCp == 0:\n self.ngwin.logEdit.append('-->slot%d: %s' % (i // self.nrSymbPerSlotNormCp, ''.join(self.tddPatOddRf[i-13:i+1])))\n \n return True\n \n def initTddGrid(self, hsfn, sfn):\n dn = '%s_%s' % (hsfn, sfn)\n if not dn in self.gridNrTdd:\n #report error\n return\n \n tddCfgMap = {'D':NrResType.NR_RES_D.value, 'F':NrResType.NR_RES_F.value, 'U':NrResType.NR_RES_U.value}\n scale = self.baseScsTd // self.nrTddCfgRefScs\n self.ngwin.logEdit.append('scale=%d where baseScTd=%dKHz and tddCfgRefScs=%dKHz' % (scale, self.baseScsTd, self.nrTddCfgRefScs))\n if sfn % 2 == 0:\n for i in range(len(self.tddPatEvenRf)):\n for j in range(scale):\n self.gridNrTdd[dn][self.nrScGb:,i*scale+j] = tddCfgMap[self.tddPatEvenRf[i]] \n else:\n for i in range(len(self.tddPatOddRf)):\n for j in range(scale):\n self.gridNrTdd[dn][self.nrScGb:,i*scale+j] = tddCfgMap[self.tddPatOddRf[i]] \n \n '''\n rows, cols = self.gridNrTdd[dn].shape\n for i in range(rows):\n self.ngwin.logEdit.append(','.join([str(self.gridNrTdd[dn][i,j]) for j in range(cols)]))\n '''\n \n def exportToExcel(self):\n self.ngwin.logEdit.append('---->exporting to excel(engine=xlsxwriter)...')\n verticalHeader = []\n for i in range(self.nrScTot):\n verticalHeader.append('crb%dsc%d' % (i // self.nrScPerPrb, i % self.nrScPerPrb))\n \n horizontalHeader = ['k/l']\n if self.nrDuplexMode == 'TDD':\n for key in self.gridNrTdd.keys():\n hsfn, sfn = key.split('_')\n for i in range(self.nrSymbPerRfNormCp//self.nrSymbPerSlotNormCp):\n for j in range(self.nrSymbPerSlotNormCp):\n horizontalHeader.append('sfn%s\\nslot%d\\nsymb%d' % (sfn, i, j))\n else:\n for key in self.gridNrFddDl.keys():\n hsfn, sfn = key.split('_')\n for i in range(self.nrSymbPerRfNormCp//self.nrSymbPerSlotNormCp):\n for j in range(self.nrSymbPerSlotNormCp):\n horizontalHeader.append('sfn%s\\nslot%d\\nsymb%d' % (sfn, i, j))\n \n workbook = xlsxwriter.Workbook(os.path.join(self.outDir, '5gnr_grid_%s.xlsx' % (time.strftime('%Y%m%d%H%M%S', time.localtime()))))\n fmtHHeader = workbook.add_format({'font_name':'Arial', 'font_size':9, 'bold':True, 'align':'center', 'valign':'vcenter', 'text_wrap':True, 'bg_color':'yellow'})\n fmtVHeader = workbook.add_format({'font_name':'Arial', 'font_size':9, 'bold':True, 'align':'center', 'valign':'vcenter', 'shrink':True, 'bg_color':'yellow'})\n \n #key=NrResType, val=(name, font_color, bg_color)\n resMap = dict()\n resMap[NrResType.NR_RES_PSS.value] = ('PSS', '#000000', '#00FF00')\n resMap[NrResType.NR_RES_SSS.value] = ('SSS', '#000000', '#FFFF00')\n resMap[NrResType.NR_RES_PBCH.value] = ('PBCH', '#000000', '#80FFFF')\n resMap[NrResType.NR_RES_SIB1.value] = ('SIB1', '#0000FF', '#FFFFFF')\n resMap[NrResType.NR_RES_PDCCH.value] = ('PDCCH', '#000000', '#00FFFF')\n resMap[NrResType.NR_RES_PDSCH.value] = ('PDSCH', '#000000', '#FFFFFF')\n resMap[NrResType.NR_RES_CSI_RS.value] = ('CSI-RS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_MSG2.value] = ('MSG2', '#000000', '#FF00FF')\n resMap[NrResType.NR_RES_MSG4.value] = ('MSG4', '#000000', '#FF00FF')\n \n resMap[NrResType.NR_RES_PRACH.value] = ('CSI-RS', '#000000', '#80FFFF')\n resMap[NrResType.NR_RES_PUCCH.value] = ('PUCCH', '#FFFFFF', '#0000FF')\n resMap[NrResType.NR_RES_PUSCH.value] = ('PUSCH', '#000000', '#FFFFFF')\n resMap[NrResType.NR_RES_SRS.value] = ('PUSCH', '#000000', '#FFFF00')\n resMap[NrResType.NR_RES_MSG3.value] = ('MSG3', '#000000', '#FF00FF')\n \n resMap[NrResType.NR_RES_DMRS_PBCH.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_SIB1.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_PDCCH.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_PDSCH.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_MSG2.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_MSG4.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_PUCCH.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_PUSCH.value] = ('DMRS', '#000000', '#FF0000')\n resMap[NrResType.NR_RES_DMRS_MSG3.value] = ('DMRS', '#000000', '#FF0000')\n \n resMap[NrResType.NR_RES_PTRS_PDSCH.value] = ('PTRS', '#000000', '#FF00FF')\n resMap[NrResType.NR_RES_PTRS_PUSCH.value] = ('PTRS', '#000000', '#FF00FF')\n \n resMap[NrResType.NR_RES_DTX.value] = ('DTX', '#FFFFFF', '#000000')\n \n resMap[NrResType.NR_RES_D.value] = ('D', '#FFFFFF', '#808080')\n resMap[NrResType.NR_RES_F.value] = ('F', '#FFFFFF', '#808080')\n resMap[NrResType.NR_RES_U.value] = ('U', '#FFFFFF', '#808080')\n resMap[NrResType.NR_RES_GB.value] = ('GB', '#808080', '#000000')\n \n formatMap = dict()\n for key, val in resMap.items():\n name, fg, bg = val\n formatMap[key] = workbook.add_format({'font_name':'Arial', 'font_size':9, 'align':'left', 'valign':'vcenter', 'font_color':fg, 'bg_color':bg})\n \n if self.nrDuplexMode == 'TDD':\n sheet1 = workbook.add_worksheet('TDD Grid')\n sheet1.set_zoom(90)\n sheet1.freeze_panes(1, 1)\n \n #write header\n sheet1.write_row(0, 0, horizontalHeader, fmtHHeader)\n sheet1.write_column(1, 0, verticalHeader, fmtVHeader)\n \n count = 0\n for key,val in self.gridNrTdd.items():\n for row in range(val.shape[0]):\n for col in range(val.shape[1]):\n name, fg, bg = resMap[val[row, col]]\n sheet1.write(row+1, col+1+count*val.shape[1], name, formatMap[val[row, col]])\n count += 1\n else:\n sheet1 = workbook.add_worksheet('FDD UL Grid')\n sheet1.set_zoom(90)\n sheet1.freeze_panes(1, 1)\n sheet2 = workbook.add_worksheet('FDD DL Grid')\n sheet2.set_zoom(90)\n sheet2.freeze_panes(1, 1)\n \n #write header\n sheet1.write_row(0, 0, horizontalHeader, fmtHHeader)\n sheet1.write_column(1, 0, verticalHeader, fmtVHeader)\n sheet2.write_row(0, 0, horizontalHeader, fmtHHeader)\n sheet2.write_column(1, 0, verticalHeader, fmtVHeader)\n \n count = 0\n for key,val in self.gridNrFddUl.items():\n for row in range(val.shape[0]):\n for col in range(val.shape[1]):\n name, fg, bg = resMap[val[row, col]]\n sheet1.write(row+1, col+1+count*val.shape[1], name, formatMap[val[row, col]])\n count += 1\n \n count = 0\n for key,val in self.gridNrFddDl.items():\n for row in range(val.shape[0]):\n for col in range(val.shape[1]):\n name, fg, bg = resMap[val[row, col]]\n sheet2.write(row+1, col+1+count*val.shape[1], name, formatMap[val[row, col]])\n count += 1\n \n workbook.close()\n \n def recvSsb(self, hsfn, sfn):\n self.ngwin.logEdit.append('---->inside recvSsb')\n \n if self.nrSsbPeriod >= 10 and self.deltaSfn(self.hsfn, self.nrMibSfn, hsfn, sfn) % (self.nrSsbPeriod // 10) != 0:\n return\n \n dn = '%s_%s' % (hsfn, sfn)\n ssbHrfSet = [0, 1] if self.nrSsbPeriod < 10 else [self.nrMibHrf]\n \n #SSB frequency domain\n scaleFd = self.nrSsbScs // self.baseScsFd\n ssbFirstSc = self.nrSsbNCrbSsb * self.nrScPerPrb + self.nrSsbKssb * (self.nrMibCommonScs // self.baseScsFd if self.args['freqBand']['freqRange'] == 'FR2' else 1)\n v = self.nrPci % 4\n \n for hrf in ssbHrfSet:\n for issb in range(len(self.ssbSet)):\n if self.ssbSet[issb] == '0':\n continue\n #SSB time domain\n scaleTd = self.baseScsTd // self.nrSsbScs\n ssbFirstSymb = hrf * (self.nrSymbPerRfNormCp // 2) + self.ssbFirstSymbSet[issb] * scaleTd\n self.ngwin.logEdit.append('ssbFirstSc=%d, v=%d, ssbFirstSymb=%d' % (ssbFirstSc, v, ssbFirstSymb))\n \n #update nr grid\n #refer to 3GPP 38.211 vf30\n #Table 7.4.3.1-1: Resources within an SS/PBCH block for PSS, SSS, PBCH, and DM-RS for PBCH.\n if self.nrDuplexMode == 'TDD':\n for i in range(scaleTd):\n #symbol 0 of SSB, PSS\n self.gridNrTdd[dn][ssbFirstSc:ssbFirstSc+56*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_DTX.value\n self.gridNrTdd[dn][ssbFirstSc+56*scaleFd:ssbFirstSc+183*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_PSS.value\n self.gridNrTdd[dn][ssbFirstSc+183*scaleFd:ssbFirstSc+240*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_DTX.value\n #symbol 1/3 of SSB, PBCH\n self.gridNrTdd[dn][ssbFirstSc:ssbFirstSc+240*scaleFd, ssbFirstSymb+scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrTdd[dn][j+k, ssbFirstSymb+scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n self.gridNrTdd[dn][ssbFirstSc:ssbFirstSc+240*scaleFd, ssbFirstSymb+3*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrTdd[dn][j+k, ssbFirstSymb+3*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n #symbol 2 of SSB, PBCH and SSS \n self.gridNrTdd[dn][ssbFirstSc:ssbFirstSc+48*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+45)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrTdd[dn][j+k, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n self.gridNrTdd[dn][ssbFirstSc+48*scaleFd:ssbFirstSc+56*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DTX.value\n self.gridNrTdd[dn][ssbFirstSc+56*scaleFd:ssbFirstSc+183*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_SSS.value\n self.gridNrTdd[dn][ssbFirstSc+183*scaleFd:ssbFirstSc+192*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DTX.value\n self.gridNrTdd[dn][ssbFirstSc+192*scaleFd:ssbFirstSc+240*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+(v+192)*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrTdd[dn][j+k, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n else:\n for i in range(scaleTd):\n #symbol 0 of SSB, PSS\n self.gridNrFddDl[dn][ssbFirstSc:ssbFirstSc+56*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_DTX.value\n self.gridNrFddDl[dn][ssbFirstSc+56*scaleFd:ssbFirstSc+183*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_PSS.value\n self.gridNrFddDl[dn][ssbFirstSc+183*scaleFd:ssbFirstSc+240*scaleFd, ssbFirstSymb+i] = NrResType.NR_RES_DTX.value\n #symbol 1/3 of SSB, PBCH\n self.gridNrFddDl[dn][ssbFirstSc:ssbFirstSc+240*scaleFd, ssbFirstSymb+scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrFddDl[dn][j+k, ssbFirstSymb+scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n self.gridNrFddDl[dn][ssbFirstSc:ssbFirstSc+240*scaleFd, ssbFirstSymb+3*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrFddDl[dn][j+k, ssbFirstSymb+3*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n #symbol 2 of SSB, PBCH and SSS \n self.gridNrFddDl[dn][ssbFirstSc:ssbFirstSc+48*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+v*scaleFd, ssbFirstSc+(v+45)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrFddDl[dn][j+k, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n self.gridNrFddDl[dn][ssbFirstSc+48*scaleFd:ssbFirstSc+56*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DTX.value\n self.gridNrFddDl[dn][ssbFirstSc+56*scaleFd:ssbFirstSc+183*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_SSS.value\n self.gridNrFddDl[dn][ssbFirstSc+183*scaleFd:ssbFirstSc+192*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DTX.value\n self.gridNrFddDl[dn][ssbFirstSc+192*scaleFd:ssbFirstSc+240*scaleFd, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_PBCH.value\n for j in range(ssbFirstSc+(v+192)*scaleFd, ssbFirstSc+(v+237)*scaleFd, 4*scaleFd):\n for k in range(scaleFd):\n self.gridNrFddDl[dn][j+k, ssbFirstSymb+2*scaleTd+i] = NrResType.NR_RES_DMRS_PBCH.value\n \n \n def deltaSfn(self, hsfn0, sfn0, hsfn1, sfn1):\n return (1024 * hsfn1 + sfn1) - (1024 * hsfn0 + sfn0)\n \n def monitorPdcch(self):\n pass\n \n def recvSib1(self):\n pass\n \n def sendMsg1(self):\n pass\n \n def recvMsg2(self):\n pass\n \n def sendMsg3(self):\n pass\n \n def recvMsg4(self):\n pass\n \n def sendPucch(self):\n pass\n \n def sendPusch(self):\n pass\n \n def recvPdsch(self):\n pass\n \n def normalOps(self):\n pass\n","sub_path":"ngnrgrid.py","file_name":"ngnrgrid.py","file_ext":"py","file_size_in_byte":27799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"356150266","text":"\"\"\" Ousmane DIA\r\n@authors: Abdoulaye Bara DIAW\r\n Ndeye fatou DIAW\r\nAvril_2020\r\n\"\"\"\r\n\r\nfrom scipy import random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\na=0\r\nb=1\r\nN=10000\r\n\"\"\"Définition de la fonction\"\"\"\r\ndef func(x):\r\n return np.sqrt(1-(x)**2)\r\n\"\"\"Calcule de l'aire\"\"\"\r\nareas = []\r\nfor i in range (N):\r\n xrand=np.zeros(N)\r\n for i in range(len(xrand)):\r\n xrand[i] = random.uniform(a,b)\r\n integral =0.0\r\n for i in range(N):\r\n integral += func(xrand[i])\r\n answer = (b-a)/float(N)*integral\r\n areas.append(answer)\r\nplt.title(\"Distribution d'aire avec MonteCarlo sous python\")\r\nplt.hist(areas, bin=30, ec=\"black\")\r\nplt.xlabel(\"Areas\")\r\n\r\n\r\n","sub_path":"Monte Carlo/Monte Carlo.py","file_name":"Monte Carlo.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"147282969","text":"from pypianoroll import Multitrack, Track\nimport os, pretty_midi\nimport numpy as np\n\nraw_midi_dir = '/Users/apple/Downloads/Pop/'\nmerged_midi_dir = '/Users/apple/Downloads/Pop_merged_midi/'\nfiltered_midi_dir = '/Users/apple/Downloads/Pop_filtered_midi/'\nraw_npy_dir = '/Users/apple/Downloads/Pop_npy/'\n\n\ndef get_merged(multitrack):\n \"\"\"分类并合并乐器轨道,吉他、贝斯、钢琴,其余全部并入弦乐\"\"\"\n category_list = {'drum': [],'piano': []}\n program_dict = {'piano': 0, 'drum': 0}\n\n for idx, track in enumerate(multitrack.tracks):\n if track.is_drum:\n category_list['drum'].append(idx)\n else: #track.program//8 == 0:\n category_list['piano'].append(idx)\n # elif track.program//8 == 3:\n # category_list['Guitar'].append(idx)\n # elif track.program//8 == 4:\n # category_list['Bass'].append(idx)\n # else:\n # category_list['Strings'].append(idx)\n\n tracks = []\n if category_list['drum']:\n drum_merged = multitrack[category_list['drum']].get_merged_pianoroll()\n tracks.append(Track(drum_merged, program_dict['drum'], True, 'drum'))\n\n if category_list['piano']:\n piano_merged = multitrack[category_list['piano']].get_merged_pianoroll()\n tracks.append(Track(piano_merged, program_dict['piano'], False, 'piano'))\n\n # for key in category_list:\n # if category_list[key]:\n # merged = multitrack[category_list[key]].get_merged_pianoroll()\n # tracks.append(Track(merged, program_dict[key], merged.is_drum, key))\n # else:\n # pass\n #tracks.append(Track(None, program_dict[key], False, key))\n merged = Multitrack(None, tracks, multitrack.tempo, multitrack.downbeat, multitrack.beat_resolution, multitrack.name)\n #merged.save(npz_dir + multitrack.name + '.npz')\n return merged\n\ndef get_midi_info(file):\n \"\"\"通过PrettyMIDI对象作为媒介,获取midi文件的信息,用以筛选\"\"\"\n pm = pretty_midi.PrettyMIDI(file)\n \n if pm.time_signature_changes:\n pm.time_signature_changes.sort(key=lambda x: x.time)\n first_beat_time = pm.time_signature_changes[0].time # 第一种TimeSignature的开始时间,秒\n else:\n first_beat_time = pm.estimate_beat_start()\n\n tc_times, tempi = pm.get_tempo_changes() # when tempo changes(in seconds), tempo at these times; both lists\n\n if len(pm.time_signature_changes) == 1:\n time_sign = '{}/{}'.format(pm.time_signature_changes[0].numerator,\n pm.time_signature_changes[0].denominator)\n else:\n time_sign = None\n\n midi_info = {\n 'first_beat_time': first_beat_time,\n 'num_time_signature_change': len(pm.time_signature_changes),\n 'time_signature': time_sign,\n 'tempo': tempi[0] if len(tc_times) == 1 else None,\n 'num_instruments': len(pm.instruments)\n }\n\n return midi_info\n\ndef midi_filter(midi_info):\n \"\"\"filter midi files, return True for qualified midis, return False for others\"\"\"\n if midi_info['first_beat_time'] > 0.0:\n #print(midi_info['first_beat_time'])\n return False\n elif midi_info['num_time_signature_change'] > 1:\n #print(midi_info['num_time_signature_change'])\n return False\n elif midi_info['time_signature'] not in ['4/4']:\n #print(midi_info['time_signature'])\n return False\n elif midi_info['num_instruments'] < 2:\n return False\n else:\n return True\n\ndef get_midi_file(root):\n \"\"\"Return a list of MIDI files in `root` (recursively)\"\"\"\n files = []\n for _, _, filenames in os.walk(root):\n for filename in filenames:\n if filename.endswith('.mid'):\n files.append(filename)\n return files\n\n\ndef get_bar_piano_roll(piano_roll, last_bar_mode='remove'):\n if int(piano_roll.shape[0] % 64) is not 0:\n if last_bar_mode == 'fill':\n piano_roll = np.concatenate((piano_roll, np.zeros((64 - piano_roll.shape[0] % 64, 128))), axis=0)\n elif last_bar_mode == 'remove':\n piano_roll = np.delete(piano_roll, np.s_[-int(piano_roll.shape[0] % 64):], axis=0)\n piano_roll = piano_roll.reshape(-1, 64, 128, 2)\n return piano_roll\n\n# MAIN FUNCTION\n# make sure the directories exist\nif not os.path.exists(raw_midi_dir):\n os.makedirs(raw_midi_dir)\n\nif not os.path.exists(merged_midi_dir):\n os.makedirs(merged_midi_dir)\n\nif not os.path.exists(filtered_midi_dir):\n os.makedirs(filtered_midi_dir)\n\nif not os.path.exists(raw_npy_dir):\n os.makedirs(raw_npy_dir)\n\nmidi_files = get_midi_file(raw_midi_dir) # returns a list of all midi file names in 'raw_midi_dir'\nprint(midi_files) # print that list\n\nfor file in midi_files:\n try:\n midi_info_1 = get_midi_info(os.path.join(raw_midi_dir, file))\n except:\n continue\n if midi_filter(midi_info_1):\n try:\n multitrack = Multitrack(os.path.join(raw_midi_dir, file))\n except:\n continue\n multitrack.write(os.path.join(filtered_midi_dir, file))\n print(file+\" filtered\")\n merged = get_merged(multitrack) # merge the tracks played by the same instruments\n merged.write(os.path.join(merged_midi_dir, file)) # save merged midi files\n midi_info_2 = get_midi_info(os.path.join(merged_midi_dir, file))\n if midi_filter(midi_info_2):\n #midi_info = get_midi_info(os.path.join(merged_midi_dir, file))\n #print(file)\n #print(midi_filter(midi_info))\n #if midi_filter(midi_info):\n # merged.write(os.path.join(filtered_midi_dir, file)) # save filtered midi files\n #merged.save(npz_dir + file.split('.')[0] + '.npz')\n stacked = merged.get_stacked_pianoroll() # returns ndarray, a multi-track pianoroll\n print(stacked.shape) # (7824, 128, 2)\n\n pr = get_bar_piano_roll(stacked)\n print(pr.shape)\n pr_clip = pr[:, :, 24:108, :] # 将第三个维度切断至24-108,长度变为84\n print(pr_clip.shape)\n #pr_re = pr_clip.reshape(-1, 64, 84, 2)\n #print(pr_re.shape)\n np.save(os.path.join(raw_npy_dir, os.path.splitext(file)[0] + '.npy'), pr_clip) # save 4-dim npy files\n","sub_path":"Preprocessing1.py","file_name":"Preprocessing1.py","file_ext":"py","file_size_in_byte":6238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"304414650","text":"'''\nUse beautifulSoup to scrape web for song links\n'''\n\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef getLinks(song, artist):\n\n # Make google search query\n query = song.replace(' ', '+').replace('&','%26') + '+by+' + artist.replace(' ', '+').replace('&','%26')\n\n links = {\"Spotify\":\"\", \"Apple Music\":\"\", \"Amazon Music\":\"\", \"Google Play\":\"\", \"Tidal\":\"\"}\n services = ['Spotify', 'Apple Music', 'Amazon Music', 'Google Play', 'Tidal']\n\n for service in services:\n\n # Create google search query\n url = \"https://www.google.com/search?q=\"\n url += query + '+' + service.replace(' ','+')\n\n # Fetch content from url\n response = requests.get(url, timeout=5)\n content = BeautifulSoup(response.content, \"html.parser\")\n link = content.find(attrs={\"class\": \"r\"}).a.get('href') # Scrape top link from google\n\n # Clean the link\n link = link.replace('/url?q=', '')\n link = link[0:link.find(\"&sa=\")].replace(\"%3F\",'?').replace(\"%3D\",'=').replace(\"%26\", '&').replace(')','\\)')\n\n links[service]=link\n\n print(links)\n return links\n","sub_path":"links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"403650419","text":"#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser\nfrom pathlib import Path\nfrom re import findall\nfrom subprocess import Popen\nfrom time import sleep\n\nHTML_TEMPLATE = '/home/gio/tools/plotly2svg/plotly2svg/template/template.html'\nHTML_OUTPUT = '/home/gio/tools/plotly2svg/plotly.html'\nSVG_OUTPUT = Path('/home/gio/Downloads/plot_image.svg')\nBROWSER_BIN = 'google-chrome-stable'\n\np_src = Path('~/projects/ulsl/group/log/src')\np_img = Path('~/Documents/articles/article_ulsl/img')\n\n\ndef script_convert():\n parser = ArgumentParser(prog='plotly2svg',\n description='Convert plotly image into svg')\n parser.add_argument('-j', '--json',\n help='path to json file')\n parser.add_argument('-md',\n help='path to input md')\n parser.add_argument('-n', '--number',\n help='0-based index of plot to export')\n parser.add_argument('-t', '--template',\n help='template html (' + HTML_TEMPLATE + ')',\n default=HTML_TEMPLATE)\n parser.add_argument('-o', '--output',\n help='output html (' + HTML_OUTPUT + ')',\n default=HTML_OUTPUT)\n args = parser.parse_args()\n \n insert_plotly_in_template(**vars(args))\n from_browser_to_svg()\n\n\ndef insert_plotly_in_template(template=None, md=None, json=None, number=None, output=None):\n HTML_TEMPLATE = Path(template)\n HTML_OUTPUT = Path(output)\n\n if json:\n JSON_INPUT = Path(json)\n with JSON_INPUT.open('r') as f:\n image = f.read()\n\n else:\n MD_INPUT = Path(md)\n\n with MD_INPUT.open('r') as f:\n t = f.read()\n\n images = findall('Plotly.newPlot\\(\"[a-z0-9-]*\", (.*)\\)', t)\n image = images[int(number)]\n\n\n with HTML_TEMPLATE.open('r') as f:\n template = f.read()\n\n width_list = findall('\"width\": ([0-9.]*)', image)\n print(width_list)\n if width_list and width_list[-1] != '0':\n width = width_list[-1]\n else:\n width = '800'\n template = template.replace('INSERT_PLOTLY_WIDTH_HERE', width)\n\n height_list = findall('\"height\": ([0-9.]*)', image)\n print(height_list)\n if height_list and height_list[-1] != '0':\n height = height_list[-1]\n else:\n height = '600'\n template = template.replace('INSERT_PLOTLY_HEIGHT_HERE', height)\n\n template = template.replace('INSERT_PLOTLY_IMAGE_HERE', image)\n\n with HTML_OUTPUT.open('w') as f:\n f.write(template)\n\n\ndef from_browser_to_svg():\n if SVG_OUTPUT.exists():\n SVG_OUTPUT.unlink()\n\n print(str(HTML_OUTPUT))\n # p = Popen([BROWSER_BIN, '--new-window', str(HTML_OUTPUT)])\n p = Popen(['Xvfb', BROWSER_BIN, str(HTML_OUTPUT)])\n \n while not SVG_OUTPUT.exists():\n sleep(2)\n\n sleep(2)\n p.terminate()\n\n print('Output SVG should be in ' + str(SVG_OUTPUT))\n","sub_path":"plotly2svg/convert2svg.py","file_name":"convert2svg.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283672807","text":"from typing import Dict\n\nimport pathlib\nimport sys\n\nimport pandas as pd\n\nfrom sklearn import preprocessing\n\n# logging decorator\nfrom SmartMedApp.logs.logger import debug\n\n\nclass ExtentionFileException(Exception):\n pass\n\n\nclass PandasPreprocessor:\n '''Class to preprocessing any datasets'''\n\n def __init__(self, settings: Dict):\n self.settings = settings # settings['data']\n self.__read_file()\n self.numerics_list = {'int16', 'int32', 'int', 'float', 'bool',\n 'int64', 'float16', 'float32', 'float64'}\n\n @debug\n def __read_file(self):\n ext = pathlib.Path(self.settings['path']).suffix\n\n if ext == '.csv':\n self.df = pd.read_csv(self.settings['path'])\n\n if len(self.df.columns) <= 1:\n self.df = pd.read_csv(self.settings['path'], sep=';')\n\n elif ext == '.xlsx':\n self.df = pd.read_excel(self.settings['path'])\n\n elif ext == '.tcv':\n self.df = pd.read_excel(self.settings['path'], sep='\\t')\n\n else:\n raise ExtentionFileException\n\n @debug\n def preprocess(self):\n self.fillna()\n self.encoding()\n self.scale()\n\n @debug\n def fillna(self):\n value = self.settings['preprocessing']['fillna']\n if value == 'mean':\n for col in self.df.columns:\n if self.df[col].dtype in self.numerics_list:\n self.df[col] = self.df[col].fillna(self.df[col].mean())\n else:\n self.df[col] = self.df[col].fillna(\n self.df[col].mode().values[0])\n elif value == 'median':\n for col in self.df.columns:\n if self.df[col].dtype in self.numerics_list:\n self.df[col] = self.df[col].fillna(self.df[col].median())\n else:\n self.df[col] = self.df[col].fillna(\n self.df[col].mode().values[0])\n elif value == 'droprows':\n self.df = self.df[col].dropna()\n\n @debug\n def encoding(self):\n method = self.settings['preprocessing']['encoding']\n if method == 'label_encoding':\n transformer = preprocessing.LabelEncoder()\n\n for column in self.df.select_dtypes(exclude=self.numerics_list):\n transformer.fit(self.df[column].astype(str).values)\n self.df[column] = transformer.transform(\n self.df[column].astype(str).values)\n\n @debug\n def scale(self):\n method = self.settings['preprocessing']['scaling']\n if method:\n scaler = preprocessing.StandardScaler()\n scaler.fit(self.df)\n self.df = scaler.transform(self.df)\n else:\n pass\n\n def get_numeric_df(self, df):\n return df.select_dtypes(include=self.numerics_list)\n\n def get_categorical_df(self, df):\n return df.select_dtypes(exclude=self.numerics_list)\n","sub_path":"SmartMedApp/backend/modules/dataprep/PandasPreprocessor.py","file_name":"PandasPreprocessor.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"552985384","text":"from cal_setup import get_calendar_service\nimport datetime\nfrom os.path import dirname, abspath\n\n\nDIR = dirname(dirname(dirname(abspath(__file__))))\nTEXT_DIR = f'{DIR}/CALENDAR_ID'\nname = open(TEXT_DIR).readline()\n\ndef create(body):\n # creates new event\n service = get_calendar_service()\n # If have any specific calendar just replace calendar id with primary\n event_result = service.events().insert(\n calendarId=f'{name}', body=body\n ).execute()\n\n print(\"created event\")\n print(\"id: \", event_result['id'])\n print(\"summary: \", event_result['summary'])\n print(\"starts at: \", event_result['start']['dateTime'])\n print(\"ends at: \", event_result['end']['dateTime'])\n\n\ndef list_events_summary():\n service = get_calendar_service()\n # Call the Calendar API\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTCtime\n print('Getting List of events')\n events_result = service.events().list(\n calendarId=f'{name}', timeMin=now,\n maxResults=100, singleEvents=True,\n orderBy='startTime').execute()\n events = events_result.get('items', [])\n\n if not events:\n print('No upcoming events found.')\n event_list = [new_event['summary'] for new_event in events]\n return event_list\n","sub_path":"yara/google_calendar/create_event.py","file_name":"create_event.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"84819957","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n' a test module '\n\n__author__ = 'HijackZhang'\n\n# 第1行和第2行是标准注释,第1行注释可以让这个hello.py文件直接在Unix/Linux/Mac上运行,第2行注释表示.py文件本身使用标准UTF-8编码;\n# 第4行是一个字符串,表示模块的文档注释,任何模块代码的第一个字符串都被视为模块的文档注释;\n# 第6行使用__author__变量把作者写进去,这样当你公开源代码后别人就可以瞻仰你的大名;\n# 以上就是Python模块的标准文件模板,当然也可以全部删掉不写,但是,按标准办事肯定没错。\n# 后面开始就是真正的代码部分。\n\nimport sys\n\n# 即可很清晰的知道整个过程,当在命令行直接调用hello.py时,name是main,如果是模块导入的话,则name是模块的名字\nprint ('__name__ is',__name__)\n\ndef test():\n args = sys.argv\n if len(args)==1:\n print('Hello World')\n elif len(args) == 2:\n print('Hello, %s!' % args[1])\n else:\n print('Too many arguments!')\nif __name__ == '__main__':\n test()\n\n# 你可能注意到了,使用sys模块的第一步,就是导入该模块:\n# import sys\n# 导入sys模块后,我们就有了变量sys指向该模块,利用sys这个变量,就可以访问sys模块的所有功能。\n#\n# sys模块有一个argv变量,用list存储了命令行的所有参数。argv至少有一个元素,因为第一个参数永远是该.py文件的名称,例如:\n#\n# 运行python3 hello.py获得的sys.argv就是['hello.py'];\n#\n# 运行python3 hello.py Michael获得的sys.argv就是['hello.py', 'Michael]。\n\n# 最后,注意到这两行代码:\n# if __name__=='__main__':\n# test()\n# 当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,\n# 因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。\n\n\n#作用域\n\n# 在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用,有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。\n#\n# 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;\n#\n# 类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名;\n#\n# 类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等;\n#\n# 之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用,是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量。\n#\n# private函数或变量不应该被别人引用,那它们有什么用呢?请看例子:\n\ndef _private1(name):\n return 'Hello, %s ' % name\n\ndef _private2(name):\n return 'Hi, %s' % name\n\ndef greeting(name):\n if len(name)>3:\n return _private1(name)\n else:\n return _private2(name)\n# 我们在模块里公开greeting()函数,而把内部逻辑用private函数隐藏起来��,这样,调用greeting()函数不用关心内部的private函数细节,这也是一种非常有用的代码封装和抽象的方法,即:\n\n# 外部不需要引用的函数全部定义成private,只有外部需要引用的函数才定义为public。\n\n# 模块是对象,并且所有的模块都有一个内置属性 name。一个模块的 name 的值取决于如何应用模块。\n# 如果 import 一个模块,那么模块name 的值通常为模块文件名,不带路径或者文件扩展名。\n# 如果像一个标准的程序样直接运行模块,在这 种情况下, name 的值将是一个特别缺省\"main\"。\n# 即:\n# 在cmd 中直接运行.py文件,则name的值是'main';\n# 而在import 一个.py文件后,name的值就不是'main'了;\n# 从而用if name == 'main'来判断是否是在直接运行该.py文件\n#\n# 举个例子:\n# 在cmd中直接运行.py文件:\n# D:\\我的资料库\\python\\start>python test.py\n# Hello, world!\n#\n# import一个.py文件,把它作为模块,那么name就是模块的名字,\n# \"name == 'main'\"不成立。\n# D:\\我的资料库\\python\\start>python\n# Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32\n# Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n#\n# import test\n# test.name\n# 'test'\n# name\n# 'main'\n\n\n\n\n\n\n","sub_path":"module/in_module.py","file_name":"in_module.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"378769443","text":"#!/usr/bin/env python3\nfrom __future__ import print_function\nimport json, sys\n'''\nconcatenate jsonfiles obtained by connecting\nselections of poses for each fragment\n'''\n\ndef map_json(j):\n print(\"map_json\", file = sys.stderr)\n sys.stderr.flush()\n interactions = j['interactions']\n clusters = j[\"clusters\"]\n A = [ i['ranks'][0] for i in clusters[0]]\n B = [ i['ranks'][0] for i in clusters[1]]\n interactions = [ [ A[j[0]], B[j[1]] ] for j in interactions[0] ]\n A = set([ i[0] for i in interactions ])\n B = set([ i[1] for i in interactions ])\n j = [] #free memory\n return clusters, interactions, A, B\n\ndef joinjson(jsonlist):\n j = {}\n j['nfrags'] = 2\n for jj in jsonlist:\n assert jj['nfrags'] == 2, \"more than 2 fragments\"\n j['max_rmsd'] = jsonlist[0]['max_rmsd']\n map_jsonlist = [ map_json(j) for j in jsonlist ]\n print(\"all jsons mapped\", file=sys.stderr)\n sys.stderr.flush()\n int_jsonlist = [ j[1] for j in map_jsonlist ]\n A_jsonlist = [ j[2] for j in map_jsonlist ]\n B_jsonlist = [ j[3] for j in map_jsonlist ]\n del map_jsonlist\n A = list(set.union(*A_jsonlist))\n del A_jsonlist\n print(\"frag A union computed\", file=sys.stderr)\n sys.stderr.flush()\n B = list(set.union(*B_jsonlist))\n del B_jsonlist\n print(\"frag B union computed\", file=sys.stderr)\n sys.stderr.flush()\n A.sort()\n B.sort()\n mapA = {int(value):int(ind) for ind, value in enumerate(A)}\n mapB = {int(value):int(ind) for ind, value in enumerate(B)}\n print(\"frag A and B sorted\", file=sys.stderr)\n sys.stderr.flush()\n clusters = []\n ca, cb = [], []\n ca = [ {'radius': 0, 'ranks':[int(a)] } for a in A]\n cb = [ {'radius': 0, 'ranks':[int(b)] } for b in B]\n print(\"%d + %d clusters constructed\" % (len(ca), len(cb)), file=sys.stderr)\n sys.stderr.flush()\n clusters = [ca, cb]\n interactions = [ i for inter in int_jsonlist for i in inter ]\n del int_jsonlist\n print(\"%d interactions constructed\" % len(interactions), file=sys.stderr)\n int_new = [(mapA[i[0]], mapB[i[1]]) for i in interactions]\n j['clusters'] = clusters\n j['interactions'] = [int_new]\n return j\n\n#jsons = [ json.load(open(i)) for i in sys.argv[1:] ]\njsons = []\nfor i in sys.argv[1:]:\n j = json.load(open(i))\n print(\"json loaded\", i, file=sys.stderr)\n sys.stderr.flush()\n jsons.append(j)\njson_join = joinjson(jsons)\nprint(\"writing joined json\", file=sys.stderr)\nsys.stderr.flush()\njson.dump(json_join, sys.stdout)\n","sub_path":"concatenate_jsonlist.py","file_name":"concatenate_jsonlist.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"251007998","text":"\n# coding: utf-8\n\n# In[130]:\n\n\nimport csv\nimport numpy as np\nimport random\nfrom sklearn import metrics\nimport pickle\n\n\n# In[103]:\n\n\ndef read_csv(filename):\n pixels = []\n labels = []\n with open(filename, 'r') as csvfile:\n spamreader = csv.reader(csvfile, delimiter=',')\n for row in spamreader:\n temp = []\n for i in range(0, 784):\n temp.append((int(row[i]) + 0.0)/255)\n pixels.append(temp)\n labels.append([int(row[784])])\n return pixels, labels\n\n\n# In[104]:\n\n\ntr_fea, tr_lbs = read_csv('train.csv')\nte_fea, te_lbs = read_csv('test.csv')\n\n\n# In[105]:\n\n\ndef getywx(y, w, x, b):\n return y*(np.dot(x, np.transpose(w)) + b)\n\n# X -> m*n\n# y -> m*1\n# w -> 1*n\ndef svm_classifier(X, y, f_len, it, bt):\n w = np.zeros([1, f_len])\n b = 0\n m = len(X)\n for i in range(0, it):\n x_ran = []\n y_ran = []\n prb = random.sample(range(0, m), bt)\n for j in range(0, bt):\n if getywx(y[prb[j]], w, X[prb[j]], b)<1:\n x_ran.append(X[prb[j]])\n y_ran.append(y[prb[j]])\n eta = 1.0/(i+1)\n w = (1-eta)*w + (eta/bt)*np.dot(np.transpose(y_ran), x_ran)\n b = b + (eta/bt)*np.sum(y_ran)\n return w, b\n\ndef create_train(X, y, i, j):\n X_out = []\n y_out = []\n m = len(y)\n for it in range(0, m):\n if(y[it][0]==i):\n X_out.append(X[it])\n y_out.append([-1])\n elif(y[it][0]==j):\n X_out.append(X[it])\n y_out.append([1])\n return X_out, y_out \n \ndef all_classifiers(X, y, f_len, it, bt):\n all_w = []\n all_b = []\n for i in range(0, 10):\n for j in range(i+1, 10):\n print(i, \" \", j)\n X_tp, y_tp = create_train(X, y, i, j)\n w_tp, b_tp = svm_classifier(X_tp, y_tp, f_len, it, bt)\n all_w.append(w_tp)\n all_b.append(b_tp)\n return all_w, all_b\n\n\n# In[106]:\n\n\ndef get_winn(X, i, j, w, b):\n value = np.dot(X, np.transpose(w)) + b\n if value<0:\n return i\n else:\n return j\n\n\n# In[107]:\n\n\ndef classify(X, all_w, all_b):\n wins = np.zeros([10])\n ind = 0\n for i in range(0, 10):\n for j in range(i+1, 10):\n w = all_w[ind]\n b = all_b[ind]\n winner = get_winn(X, i, j, w, b)\n wins[winner] += 1\n ind += 1\n# print(wins)\n \n max_val = 0\n max_ind = -1\n for i in range(0, 10):\n if(wins[i]>=max_val):\n max_val = wins[i]\n max_ind = i\n return max_ind\n\n\n# In[123]:\n\n\nall_w, all_b = all_classifiers(tr_fea, tr_lbs, 784, 10000, 100)\n\n\n# In[124]:\n\n\nlgt = len(te_fea)\nprint(lgt)\npred_lbs = []\nfor i in range(0, lgt):\n if (i%1000==0):\n print(i)\n pred_lbs.append(classify(te_fea[i], all_w, all_b))\n\nprint(metrics.confusion_matrix(te_lbs, pred_lbs))\nprint(metrics.accuracy_score(te_lbs, pred_lbs))\n\n\n# In[125]:\n\n\nlgt = len(tr_fea)\nprint(lgt)\npred_lbs = []\nfor i in range(0, lgt):\n if (i%1000==0):\n print(i)\n pred_lbs.append(classify(tr_fea[i], all_w, all_b))\n \nprint(metrics.confusion_matrix(tr_lbs, pred_lbs))\nprint(metrics.accuracy_score(tr_lbs, pred_lbs))\n\n\n# In[131]:\n\n\nwith open('weights.pkl', 'wb') as f:\n pickle.dump(all_w, f)\nwith open('bias.pkl', 'wb') as f:\n pickle.dump(all_b, f)\n\n","sub_path":"training_code/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"402702732","text":"#!/usr/bin/env python\nimport copy\nimport math\nimport rospy\n\nfrom atf_core import ATFError, ATFAnalyserError\nfrom atf_msgs.msg import MetricResult, Groundtruth, KeyValue, DataStamped\nfrom atf_metrics import metrics_helper\n\nclass CalculatePublishRateParamHandler:\n def __init__(self):\n \"\"\"\n Class for returning the corresponding metric class with the given parameter.\n \"\"\"\n pass\n\n def parse_parameter(self, testblock_name, metric_name, params):\n \"\"\"\n Method that returns the metric method with the given parameter.\n :param params: Parameter\n \"\"\"\n metric_type = \"publish_rate\"\n\n split_name = metric_name.split(\"::\")\n if len(split_name) != 2:\n raise ATFConfigurationError(\"no valid metric name for metric '%s' in testblock '%s'\" %(metric_name, testblock_name))\n if split_name[0] != metric_type:\n raise ATFConfigurationError(\"called invalid metric handle for metric '%s' in testblock '%s'.\" %(metric_name, testblock_name))\n\n if type(params) is not dict:\n rospy.logerr(\"metric config not a dictionary\")\n raise ATFConfigurationError(\"no valid metric configuration for metric '%s' in testblock '%s': %s\" %(metric_name, testblock_name, str(params)))\n\n # check for optional parameters\n groundtruth = Groundtruth()\n try:\n groundtruth.data = params[\"groundtruth\"]\n groundtruth.epsilon = params[\"groundtruth_epsilon\"]\n groundtruth.available = True\n except (TypeError, KeyError):\n groundtruth.data = 0\n groundtruth.epsilon = 0\n groundtruth.available = False\n try:\n mode = params[\"mode\"]\n except (TypeError, KeyError):\n mode = MetricResult.SPAN_MEAN\n try:\n series_mode = params[\"series_mode\"]\n except (TypeError, KeyError):\n series_mode = None\n\n try:\n min_observation_time = params[\"min_observation_time\"]\n except (TypeError, KeyError):\n min_observation_time = 1.0\n\n return CalculatePublishRate(metric_name, min_observation_time, params[\"topic\"], groundtruth, mode, series_mode)\n\nclass CalculatePublishRate:\n def __init__(self, name, min_observation_time, topic, groundtruth, mode, series_mode):\n self.name = name\n self.min_observation_time = min_observation_time\n self.started = False\n self.finished = False\n self.active = False\n self.groundtruth = groundtruth\n if topic.startswith(\"/\"): # we need to use global topics because rostopic.get_topic_class(topic) can not handle non-global topics and recorder will always record global topics starting with \"/\"\n self.topic = topic\n else:\n self.topic = \"/\" + topic\n self.mode = mode\n self.series_mode = series_mode\n self.series = []\n self.data = DataStamped()\n self.counter = 0\n self.start_time = None\n\n def start(self, status):\n self.start_time = status.stamp\n self.active = True\n self.started = True\n\n def stop(self, status):\n # finally trigger calculation once again to update self.series and self.data\n self.calculate_publish_rate()\n self.active = False\n self.finished = True\n\n def pause(self, status):\n # TODO: Implement pause time and counter calculation\n #FIXME: check rate calculation in case of pause (counter, start_time)\n pass\n\n def purge(self, status):\n # TODO: Implement purge as soon as pause is implemented\n pass\n\n def update(self, topic, msg, t):\n # get data if testblock is active\n if self.active:\n if topic == self.topic:\n self.counter += 1\n self.data.stamp = t\n\n # wait for min_observation_time before calculating publish_rate to avoid tiny observation times and thus high publish rates, e.g. shortly after start\n if (self.data.stamp - self.start_time).to_sec() > self.min_observation_time:\n self.calculate_publish_rate()\n\n def calculate_publish_rate(self):\n self.data.data = round(self.counter / (self.data.stamp - self.start_time).to_sec(),6)\n self.series.append(copy.deepcopy(self.data)) # FIXME handle fixed rates\n\n def get_topics(self):\n return [self.topic]\n\n def get_result(self):\n metric_result = MetricResult()\n metric_result.name = self.name\n metric_result.mode = self.mode\n metric_result.started = self.started # FIXME remove\n metric_result.finished = self.finished # FIXME remove\n metric_result.series = []\n metric_result.groundtruth.available = self.groundtruth.available\n metric_result.groundtruth.data = self.groundtruth.data\n metric_result.groundtruth.epsilon = self.groundtruth.epsilon\n \n # assign default value\n metric_result.groundtruth.result = None\n metric_result.groundtruth.error_message = None\n\n if metric_result.started and metric_result.finished and len(self.series) != 0: # we check if the testblock was ever started and stopped and if result data is available\n # calculate metric data\n if self.series_mode != None:\n metric_result.series = self.series\n if metric_result.mode == MetricResult.SNAP:\n metric_result.data = self.series[-1] # take last element from self.series for data and stamp\n metric_result.min = metric_result.data\n metric_result.max = metric_result.data\n metric_result.mean = metric_result.data.data\n metric_result.std = 0.0\n elif metric_result.mode == MetricResult.SPAN_MEAN:\n metric_result.min = metrics_helper.get_min(self.series)\n metric_result.max = metrics_helper.get_max(self.series)\n metric_result.mean = metrics_helper.get_mean(self.series)\n metric_result.std = metrics_helper.get_std(self.series)\n metric_result.data.data = metric_result.mean # take mean for data\n metric_result.data.stamp = self.series[-1].stamp # take stamp from last element in self.series for stamp\n elif metric_result.mode == MetricResult.SPAN_MIN:\n metric_result.min = metrics_helper.get_min(self.series)\n metric_result.max = metrics_helper.get_max(self.series)\n metric_result.mean = metrics_helper.get_mean(self.series)\n metric_result.std = metrics_helper.get_std(self.series)\n metric_result.data = metric_result.min\n elif metric_result.mode == MetricResult.SPAN_ABSMIN:\n metric_result.min = metrics_helper.get_absmin(self.series)\n metric_result.max = metrics_helper.get_absmax(self.series)\n metric_result.mean = metrics_helper.get_mean(self.series)\n metric_result.std = metrics_helper.get_std(self.series)\n metric_result.data = metric_result.min\n elif metric_result.mode == MetricResult.SPAN_MAX:\n metric_result.min = metrics_helper.get_min(self.series)\n metric_result.max = metrics_helper.get_max(self.series)\n metric_result.mean = metrics_helper.get_mean(self.series)\n metric_result.std = metrics_helper.get_std(self.series)\n metric_result.data = metric_result.max\n elif metric_result.mode == MetricResult.SPAN_ABSMAX:\n metric_result.min = metrics_helper.get_absmin(self.series)\n metric_result.max = metrics_helper.get_absmax(self.series)\n metric_result.mean = metrics_helper.get_mean(self.series)\n metric_result.std = metrics_helper.get_std(self.series)\n metric_result.data = metric_result.max\n else: # invalid mode\n raise ATFAnalyserError(\"Analysing failed, invalid mode '%s' for metric '%s'.\"%(metric_result.mode, metric_result.name))\n\n # fill details as KeyValue messages\n details = []\n details.append(KeyValue(\"topic\", self.topic))\n metric_result.details = details\n\n # evaluate metric data\n if not metric_result.groundtruth.available: # no groundtruth given\n metric_result.groundtruth.result = True\n metric_result.groundtruth.error_message = \"all OK (no groundtruth available)\"\n else: # groundtruth available\n if math.fabs(metric_result.groundtruth.data - metric_result.data.data) <= metric_result.groundtruth.epsilon:\n metric_result.groundtruth.result = True\n metric_result.groundtruth.error_message = \"all OK\"\n else:\n metric_result.groundtruth.result = False\n metric_result.groundtruth.error_message = \"groundtruth missmatch: %f not within %f+-%f\"%(metric_result.data.data, metric_result.groundtruth.data, metric_result.groundtruth.epsilon)\n\n else: # testblock did not start and/or finish\n metric_result.groundtruth.result = False\n metric_result.groundtruth.error_message = \"no result\"\n\n if metric_result.groundtruth.result == None:\n raise ATFAnalyserError(\"Analysing failed, metric result is None for metric '%s'.\"%metric_result.name)\n\n return metric_result\n","sub_path":"atf_metrics/src/atf_metrics/calculate_publish_rate.py","file_name":"calculate_publish_rate.py","file_ext":"py","file_size_in_byte":9570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"188022297","text":"#!/usr/bin/python3\n\"\"\"LIFOCache class\"\"\"\nBaseCaching = __import__(\"base_caching\").BaseCaching\n\n\nclass LIFOCache(BaseCaching):\n \"\"\"LIFOCache class inherit from BaseCaching\"\"\"\n\n def __init__(self):\n \"\"\"initialize\"\"\"\n self.key_list = []\n super().__init__()\n\n def get(self, key):\n \"\"\" Get an item by key\n \"\"\"\n if key is None or key not in self.cache_data.keys():\n return\n return self.cache_data.get(key)\n\n def put(self, key, item):\n \"\"\" Add an item in the cache according LIFO Algorithm\n \"\"\"\n if key is None or item is None:\n return\n if key in self.key_list:\n self.key_list.remove(key)\n if len(self.key_list) >= BaseCaching.MAX_ITEMS:\n x = self.key_list[-1]\n print(\"DISCARD: {}\".format(x))\n self.key_list.pop(-1)\n self.cache_data.pop(x)\n self.cache_data.update({key: item})\n self.key_list.append(key)\n","sub_path":"0x03-caching/2-lifo_cache.py","file_name":"2-lifo_cache.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247817146","text":"#Given a string, return all combinations of a new string following commands of\n #?is a 1 or a zero\n #+ is delete the char beforehand, dont add the plus\n #! add2 zeros to the end, dont add the !\n #Implement this iteratively, return a complete list of strings\n\ndef stringCombo(string):\n combos = []\n trail_zero = 0\n for i in range(len(string)):\n for combo in combos: #Scan each string for combinations\n if string[i] == \"?\": #Add more\n combo = combo + \"1\"\n combos.append(combo + \"0\")\n\n if string[i] == \"!\": #Increase the trail by 1\n trail_zeros += 1\n\n if string[i] == \"+\": #Remove 1, from each current string\n combo = combo[:(len(combo) - 1)]\n\n else: #Add one to each of them\n combo = combo + string[i]\n\n return combos\n\n\n\n\n\n\n\n\n\n","sub_path":"arman_string_problem.py","file_name":"arman_string_problem.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"276780201","text":"from __future__ import print_function\n\"\"\"\nGame of Life\n------------\n\nSo what does this code example illustrate?\n\"\"\"\nfrom benchpress import util\nfrom gameoflife_utils import pattern_paths, insert_cells, cells_from_file\nimport numpy as np\n\nSURVIVE_LOW = 2\nSURVIVE_HIGH = 3\nSPAWN = 3\n\ndef world(height, width, B):\n state = np.ones((height+2, width+2), dtype=B.dtype)\n state[2:-2, 2:-2] = B.dtype(0)\n return state\n\ndef world_zeros(height, width, B):\n state = np.zeros((height+2, width+2), dtype=B.dtype)\n return state\n\ndef play(state, iterations, version=1, visualize=False):\n\n cells = state[1:-1,1:-1]\n ul = state[0:-2, 0:-2]\n um = state[0:-2, 1:-1]\n ur = state[0:-2, 2: ]\n ml = state[1:-1, 0:-2]\n mr = state[1:-1, 2: ]\n ll = state[2: , 0:-2]\n lm = state[2: , 1:-1]\n lr = state[2: , 2: ]\n\n def update():\n \"\"\"\n This is the first implementation of the game rules.\n \"\"\"\n neighbors = ul + um + ur + ml + mr + ll + lm + lr # count neighbors\n live = neighbors * cells # extract live cells neighbors\n stay = (live >= SURVIVE_LOW) & (live <= SURVIVE_HIGH) # find cells the stay alive\n dead = neighbors * (cells == 0) # extract dead cell neighbors\n spawn = dead == SPAWN # find cells that spaw new life\n\n cells[:] = stay | spawn # save result for next iteration\n\n def update_optimized():\n \"\"\"\n This is an optimized implementation of the game rules.\n \"\"\"\n neighbors = ul + um + ur + ml + mr + ll + lm + lr # Count neighbors\n\n c1 = (neighbors == SURVIVE_LOW) # Life conditions\n c2 = (neighbors == SPAWN)\n\n cells[:] = cells * c1 + c2 # Update\n\n if version == 1: # Select the update function\n update_func = update\n elif version == 2:\n update_func = update_optimized\n\n for i in range(iterations): # Run the game\n if visualize:\n util.plot_surface(state, \"3d\", 16, 1, 0)\n update_func()\n util.Benchmark().flush()\n\n return state\n\ndef main():\n\n B = util.Benchmark()\n (H, W, I, V) = B.size\n\n if V not in [1, 2]:\n raise Exception(\"Unsupported rule-implementation.\")\n if B.inputfn:\n if \"LIF\" in B.inputfn:\n paths = pattern_paths(\"cells\")\n S = world_zeros(H, W, B)\n cells = cells_from_file(B.inputfn)\n insert_cells(S, cells)\n else:\n S = B.load_array()\n else:\n S = world(H, W, B)\n\n B.start()\n R = play(S, I, V, B.visualize)\n B.stop()\n\n B.pprint()\n if B.outputfn:\n B.tofile(B.outputfn, {'res': R})\n if B.visualize:\n util.confirm_exit()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"benchpress/benchmarks/gameoflife/python_numpy/gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"519923786","text":"import nltk\nimport numpy as np\n\n\ndef getLookUps (path):\n #input: path of dataset\n #output: two lookups- 1 gives the index corresponding to each word in the vocabulry\n #and other which gives the word corresponding to the index\n file_content = open(path).read()\n sentences = nltk.tokenize.sent_tokenize(file_content)\n vocab = {}\n tokens = {}\n\n for a in sentences:\n tokens = nltk.word_tokenize(a)\n #del tokens[0]\n index=0\n for k in tokens:\n vocab[k] = 1\n vocab['EOS']=1\n vocab['PAD']=0\n index=2\n for key, value in vocab.items():\n vocab[key]=index\n index+=1\n reverseLookUp ={}\n\n for key, value in vocab.items():\n reverseLookUp[value]=key\n\n return vocab, reverseLookUp\n\ndef wordEmbeddings(sentence, lookUp):\n words = nltk.word_tokenize(sentence)\n embeddings =[]\n for w in words:\n embeddings.append(lookUp[w])\n return embeddings\n\ndef createBatch(sentences, startIndex, batchSize):\n if startIndex+batchSize 925 and ct < 1101) or (ct > 13 and ct < 1501):\n return True\n\n return False\n\n\ndef get_stock_code(stocks):\n df = pro.stock_basic(exchange='', list_status='L',\n fields='symbol,name,area,industry,list_status')\n\n result = []\n for index, row in df.iterrows():\n\n if row['symbol'] not in stocks:\n continue\n\n if row['list_status'] != 'L':\n continue\n\n if row['symbol'].startswith('60'):\n stock_code = 'sh' + row['symbol']\n else:\n stock_code = 'sz' + row['symbol']\n\n result.append(stock_code)\n\n return ','.join(result)\n\n\ndef main():\n logger.info('prepare')\n\n stock_list = get_stock_code(olist)\n results = []\n\n is_td = is_in_trade_day()\n\n if not is_td:\n return\n\n logger.info('start spidering')\n\n while is_td:\n ct = get_current_time_float()\n logger.info('heart beat %d' % (ct))\n\n if ct > 1502 or ct < 850:\n logger.info('exist')\n break\n\n if is_in_trade_time():\n headers = {\n 'Accept': '*/*',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,ko;q=0.6,zh-TW;q=0.5',\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Host': 'hq.sinajs.cn',\n 'Pragma': 'no-cache',\n 'Referer': 'https://finance.sina.com.cn/realstock/company/%s/nc.shtml' % (stock_list.split(',')[0]),\n 'Sec-Fetch-Dest': 'script',\n 'Sec-Fetch-Mode': 'no-cors',\n 'Sec-Fetch-Site': 'cross-site',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36'\n }\n\n url = 'https://hq.sinajs.cn/rn=%d&list=%s' % (\n time.time(), stock_list)\n\n try:\n r = requests.get(url, headers=headers, timeout=2)\n results.append(r.text)\n except Exception as e:\n logger.error(e)\n\n time.sleep(2)\n else:\n time.sleep(60)\n\n logger.info('start to save')\n logger.info(len(results))\n\n username = urllib.parse.quote_plus(username_str)\n password = urllib.parse.quote_plus(password_str)\n\n data = []\n for result in results:\n for i in re.findall(r'\".+\"', result):\n arr = i.replace('\"', '').split(',')\n\n record = {\n 'name': arr[0],\n 'buy_1_price': arr[11],\n 'buy_1_value': arr[10],\n 'buy_2_price': arr[13],\n 'buy_2_value': arr[12],\n 'buy_3_price': arr[15],\n 'buy_3_value': arr[14],\n 'buy_4_price': arr[17],\n 'buy_4_value': arr[16],\n 'buy_5_price': arr[19],\n 'buy_5_value': arr[18],\n\n 'sell_1_price': arr[21],\n 'sell_1_value': arr[20],\n 'sell_2_price': arr[23],\n 'sell_2_value': arr[22],\n 'sell_3_price': arr[25],\n 'sell_3_value': arr[24],\n 'sell_4_price': arr[27],\n 'sell_4_value': arr[26],\n 'sell_5_price': arr[29],\n 'sell_5_value': arr[28],\n\n 'close': arr[3],\n 'open': arr[1],\n 'yesterday_close': arr[2],\n 'high': arr[4],\n 'low': arr[5],\n\n 'date': arr[30],\n 'time': arr[31],\n 'uni_index': arr[0] + '_' + arr[30] + '_' + arr[31]\n }\n\n data.append(record)\n\n client = pymongo.MongoClient(\n 'mongodb://%s:%s@192.168.31.87:27017/' % (username, password))\n db = client[\"china_a_stock\"]\n\n df = pd.DataFrame(data).drop_duplicates(subset=['uni_index'])\n for index, row in df.iterrows():\n db[\"pankou\"].insert_one(row.to_dict())\n\n client.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"requests/tick_spider.py","file_name":"tick_spider.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}