diff --git "a/2859.jsonl" "b/2859.jsonl" new file mode 100644--- /dev/null +++ "b/2859.jsonl" @@ -0,0 +1,630 @@ +{"seq_id":"55019520","text":"import subprocess\n\n\ndef call_command(command_):\n def sanitize_output(output_):\n return output_.replace(\"\\\\r\\\\n\", \"\\n\").replace(\"\\\\n\", \"\\n\").strip(\"b'\\n\")\n\n try:\n output = subprocess.check_output(command_, stderr=subprocess.STDOUT)\n error = None\n except subprocess.CalledProcessError as e:\n output = e.output\n error = e\n\n return sanitize_output(str(output)), error\n","sub_path":"workflow/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"568922809","text":"from PIL import ImageTk, Image\n\nimage_path = ''\nbackground_image_width = ''\nbackground_image_height = ''\nbackground_image = ''\n\ndef resize_image(image_width, image_height, box_width, box_height, pil_image):\n '''\n resize a pil_image object so it will fit into\n a box of size w_box times h_box, but retain aspect ratio\n '''\n f1 = 1.0*box_width/image_width # 1.0 forces float division in Python2\n f2 = 1.0*box_height/image_height\n factor = min([f1, f2])\n #print(f1, f2, factor) # test\n # use best down-sizing filter\n width = int(image_width*factor)\n height = int(image_height*factor)\n return pil_image.resize((width, height), Image.ANTIALIAS)\n\ndef set_image_path(the_image_path):\n image_path = the_image_path\n return image_path\n\ndef get_image_size(the_image_path = image_path):\n selected_image = Image.open(the_image_path)\n return selected_image.size\n\ndef get_image(the_image_path = image_path):\n selected_image = Image.open(the_image_path)\n return selected_image\n\ndef set_background_image(box_width, box_height, the_image_path = image_path):\n selected_image = Image.open(the_image_path)\n image_width, image_height = selected_image.size\n # print(selected_image.size)\n resize_selected_image = \\\n resize_image(image_width, image_height,\n box_width, box_height,\n selected_image)\n resize_background_image = \\\n ImageTk.PhotoImage(resize_selected_image)\n # background_image = resize_background_image\n return resize_background_image\n\ndef get_background_image():\n return background_image\n\ndef change_image_size(event, image_path, box_label): # 缩放图像,重新显示image\n selected_image = Image.open(image_path)\n image = ImageTk.PhotoImage(\n selected_image.resize(\n (event.width, event.height),\n Image.ANTIALIAS))\n box_label['image'] = image\n box_label.image = image\n\ndef change_image_size_adaptor(fun, **kwd):\n return lambda event, fun=fun, kwds=kwd: fun(event, **kwd)\n\n","sub_path":"utils_background_image.py","file_name":"utils_background_image.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"348690985","text":"from __future__ import absolute_import\nimport logging\nimport argparse\nimport os\nimport sys\nimport apache_beam as beam\n\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.io import ReadFromText\nfrom datetime import datetime\nfrom apache_beam.options.pipeline_options import PipelineOptions, GoogleCloudOptions, SetupOptions\n\n\nclass Printer(beam.DoFn):\n def process(selfself, element):\n print(element)\n\nclass TypeOf(beam.DoFn):\n def process(self,element):\n print(type(element))\n\nclass ParseCleanTransformCSV(beam.DoFn):\n def process(self,element):\n date, seven_day_moving_average, number_of_flights = element.split(',')\n date = date.strip('\"')\n date = datetime.strptime(date, '%Y-%m-%d').strftime('%Y-%m-%d %H:%M:%S')\n return [{'date': date,\n 'seven_day_moving_average': int(seven_day_moving_average),\n 'number_of_flights': int(number_of_flights)}]\n\n\ndef run(argv=None):\n\n # Initiate the pipeline\n p = beam.Pipeline(options=PipelineOptions())\n\n data_from_source = (p\n | 'Read File' >> ReadFromText('input/total-number-of-flights.csv', skip_header_lines=1)\n | 'Parse clean and transform CSV' >> beam.ParDo(ParseCleanTransformCSV())\n #| 'Print data' >> beam.ParDo(Printer())\n )\n\n\n table_schema = 'date:TIMESTAMP, seven_day_moving_average:INTEGER, number_of_flights:INTEGER'\n\n #table_spec = 'my-storage-209112:covid19_2.flights'\n table_spec = 'sa-pipeline-bakeoff:covid19.flights_sf'\n\n # Persist to BigQuery\n # WriteToBigQuery accepts the data as list of JSON objects\n data_from_source | 'Write' >> beam.io.WriteToBigQuery(\n table_spec,\n schema=table_schema,\n create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,\n write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,\n batch_size=int(100)\n )\n\n\n p.run().wait_until_finish()\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()\n","sub_path":"flights.py","file_name":"flights.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"604270484","text":"\n\nfrom xai.brain.wordbase.nouns._engagement import _ENGAGEMENT\n\n#calss header\nclass _ENGAGEMENTS(_ENGAGEMENT, ):\n\tdef __init__(self,): \n\t\t_ENGAGEMENT.__init__(self)\n\t\tself.name = \"ENGAGEMENTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"engagement\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_engagements.py","file_name":"_engagements.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"396313492","text":"\"\"\"\n# Flask-Shell2HTTP\n\nA minimalist REST API wrapper for python's subprocess API.
\nExecute shell commands asynchronously and safely from flask's endpoints.\n\n##### Docs & Example usage on GitHub: https://github.com/eshaan7/flask-shell2http\n\"\"\"\nfrom setuptools import setup\n\n\nwith open(\"README.md\", encoding=\"utf-8\") as f:\n long_description = f.read()\n\nGITHUB_URL = \"https://github.com/eshaan7/flask-shell2http\"\n\n\nsetup(\n name=\"Flask-Shell2HTTP\",\n version=\"1.5.2\",\n url=GITHUB_URL,\n license=\"BSD\",\n author=\"Eshaan Bansal\",\n author_email=\"eshaan7bansal@gmail.com\",\n description=\"A minimalist REST API wrapper for python's subprocess API.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n py_modules=[\"flask_shell2http\"],\n zip_safe=False,\n packages=[\"flask_shell2http\"],\n include_package_data=True,\n platforms=\"any\",\n python_requires=\">= 3.6\",\n install_requires=[\"Flask\", \"Flask-Executor\"],\n classifiers=[\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n keywords=\"flask shell2http subprocess python\",\n project_urls={\n \"Documentation\": GITHUB_URL,\n \"Funding\": \"https://www.paypal.me/eshaanbansal\",\n \"Source\": GITHUB_URL,\n \"Tracker\": \"{}/issues\".format(GITHUB_URL),\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"394544342","text":"#!/usr/bin/env python # wrapBin.py\nimport numpy as np\nfrom subprocess import Popen\nfrom ctypes import CDLL, c_uint\nfrom ctypes.util import find_library\nclass Coin():\n def __init__(self, seed):\n CDLL(find_library(\"c\")).srand(c_uint(seed))\n \n def toss(self, myfunds, yourfunds):\n ifile = open('input.dat', 'wb')\n ifile.write(np.getbuffer(np.array([myfunds, yourfunds], \\\n dtype='int32')))\n ifile.close() \n \n process = Popen('./playBin input.dat output.dat', shell=True)\n process.communicate()\n process.wait()\n \n ofile = open('output.dat', 'rb')\n gain, tosses = np.frombuffer(ofile.read(), dtype='int32')\n ofile.close() \n return gain, tosses\n ","sub_path":"CS501/Homeworks/hw5_gguayaqu/wrapBin.py","file_name":"wrapBin.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"21540562","text":"from tkinter import Tk, Button\nfrom time import strftime, localtime\nfrom tkinter.messagebox import showinfo \n\n# nome da funcao fi definida abaixo\ndef clicked():\n\t'exibe informação de die e hora'\n\thora = strftime('Dia: %d %b %Y \\nHora: %H:%M:%S %p\\n',\n\t\tlocaltime())\n\tshowinfo(message=hora)\n\nraiz = Tk()\n\n# cria botão rotulado com 'Clique aqui' e manipulador de evendo clicked()\nbutton = Button (raiz,\n\ttext='Clique aqui',\n\tcommand=clicked)\t\t# manipulador de evento clique do botao\n\nbutton.pack() \t\t\t\t# posicionado-o na raiz\n\n\n\nraiz.mainloop()\n","sub_path":"introducao_A_computacao/gui/clickit.py","file_name":"clickit.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"470590293","text":"import sqlite3\r\nimport pyttsx3\r\nimport re\r\nfrom time_h import getTime\r\n#连接数据库文件,若文件不存在,会自动创建\r\ndef conn_Sql():\r\n conn = sqlite3.connect('czqdd.db')\r\n cursor_d = conn.cursor()\r\n cursor_d.execute(\"CREATE TABLE IF NOT EXISTS czqdd(name text, time text)\")\r\n print(\"连接数据库成功!!!\")\r\n return cursor_d,conn\r\n#增\r\ndef insert_Sql(cursor,usr_name):\r\n time_str = getTime()\r\n #执行SQL语句\r\n cursor.execute(\"insert into czqdd (name , time) values ('%s','%s')\" % (usr_name,time_str))\r\n print(\"插入数据成功!!!\")\r\n\r\n#查\r\ndef show_Sql(cursor):\r\n cursor.execute('select * from czqdd ',)\r\n result = cursor.fetchall()\r\n for i in result:\r\n print(i)\r\n\r\ndef close_Sql(cursor,conn):\r\n cursor.close()\r\n # 提交事务:\r\n conn.commit()\r\n # 关闭Connection:\r\n conn.close()\r\ndef queryBytime(cursor,day):\r\n cursor.execute('select * from czqdd ',)\r\n result=cursor.fetchall()\r\n for i in result:\r\n record=re.split(\" \",i[1])\r\n if day==record[0]:\r\n print(i)\r\ndef queryByname(cursor,name_d):\r\n cursor.execute('select * from czqdd where name = ?' , (name_d,))\r\n result = cursor.fetchall()\r\n if result:\r\n for i in result:\r\n print(i)\r\n else:\r\n print(\"没有找到!!!\")\r\n return\r\ndef say(engine,str):\r\n engine.say(str)\r\n engine.runAndWait()\r\n\r\nif __name__ == '__main__':\r\n cursor,conn = conn_Sql()\r\n #insert_Sql(cursor , 'berlin')\r\n #show_Sql(cursor)\r\n engine = pyttsx3.init() ##初始化语音播报\r\n rate = engine.getProperty('rate')\r\n engine.setProperty('rate', rate - 20)\r\n while True:\r\n say(engine,\"请输入选项,0按照姓名查询,1按照时间查询其余退出\")\r\n choose=input(\"请输入选项,0按照姓名查询,1按照时间查询其余退出\")\r\n if choose==\"0\":\r\n say(engine, \"请输入姓名:\")\r\n name_d = input(\"请输入姓名:\")\r\n queryByname(cursor, name_d)\r\n elif choose ==\"1\":\r\n say(engine,\"请输入日期\")\r\n time_d=input(\"请输入日期,格式为 年-月-日\")\r\n queryBytime(cursor,time_d)\r\n else:\r\n break\r\n close_Sql(cursor,conn)","sub_path":"py_sql.py","file_name":"py_sql.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"593850448","text":"# 10809 알파벳 찾기\n# ['a','b',...'z'] 로 인덱스 확인할 기준 생성\n# 기준을 for 문으로 돌면서 인덱스를 확인하고, 해당 숫자로 대체\n# .index()를 이용해서 인덱스 확인하면 안되네, 없으면 value error 뱉음\n# .find() 를 통해 확인\n\n\"\"\"\n문제\n알파벳 소문자로만 이루어진 단어 S가 주어진다. 각각의 알파벳에 대해서, 단어에 포함되어 있는 경우에는 처음 등장하는 위치를, 포함되어 있지 않은 경우에는 -1을 출력하는 프로그램을 작성하시오.\n\n입력\n첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.\n\n출력\n각각의 알파벳에 대해서, a가 처음 등장하는 위치, b가 처음 등장하는 위치, ... z가 처음 등장하는 위치를 공백으로 구분해서 출력한다.\n\n만약, 어떤 알파벳이 단어에 포함되어 있지 않다면 -1을 출력한다. 단어의 첫 번째 글자는 0번째 위치이고, 두 번째 글자는 1번째 위치이다.\n\n예제 입력 1 \nbaekjoon\n예제 출력 1 \n1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1\n\"\"\"\n\nalphabet = 'abcdefghijklmnopqrstuvwxyz'\nalphabet = list(alphabet)\n\nstring = input()\n\nfor i in range(len(alphabet)):\n print(string.find(alphabet[i]), end=' ')","sub_path":"baekjoon/personal-04-10809.py","file_name":"personal-04-10809.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"30865063","text":"# Chèn ảnh vào file excel\nfrom openpyxl.drawing.image import Image\nfrom openpyxl import Workbook\n\nm_wb = Workbook()\nm_ws = m_wb.active\nm_ws.title = 'Sheet Moi'\n\n# m_wb.save('file5_logo.xlsx')\n\nm_pic = Image(r'D:/Study/15.Python/openpyxl/Excel_file/pic_1.jpg')\n\nm_ws.add_image(m_pic,'A1')\n\nm_wb.save(r'D:/Study/15.Python/openpyxl/Excel_file/file5_logo.xlsx')","sub_path":"openpyxl/bai5.py","file_name":"bai5.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"616607152","text":"from fastapi import APIRouter, HTTPException\n\nfrom src.api.redis_api.schema import RedisSetModel, RedisValueModel\nfrom src.services.redis import redis\n\nrouter = APIRouter()\nURL_PREFIX = \"/redis\"\n\n\n@router.put(\"/set\")\nasync def set_redis_value(\n redis_target: RedisSetModel,\n) -> None:\n set_key = await redis.client.set(redis_target.key, redis_target.value, expire=redis_target.expire)\n if not set_key:\n raise HTTPException(\n status_code=400,\n detail=\"No, you can't\",\n )\n\n\n@router.get(\"/get\", response_model=RedisValueModel)\nasync def get_redis_value(\n key: str,\n) -> RedisValueModel:\n value = await redis.client.get(key, encoding='utf-8')\n if not value:\n raise HTTPException(\n status_code=400,\n detail=\"I can't get it\",\n )\n return RedisValueModel(value=value)\n","sub_path":"fastapi_template/template/{{cookiecutter.project_name}}/src/api/redis_api/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"233670495","text":"\"\"\"\nVisualizes a one-dimensional null space distribution.\nThis will take a couple of minutes.\n\"\"\"\n\nimport sys\n\nsys.path.append('./code')\n\nfrom models import ISA\nfrom numpy import *\nfrom numpy import min, max\nfrom numpy.random import *\nfrom numpy.linalg import *\nfrom pgf import *\nfrom tools import mapp\n\n# disable parallelization\nmapp.max_processes = 1\n\n# histogram parameters\nNUM_SAMPLES = 1000000\nNUM_BINS = 800\nMCMC_STEPS = 10\nZ_FROM = -25.#-20.\nZ_TO = 25.#30.\n\n# size and resolution for image of prior\nIMG_SIZE = 1024\nDPI = 300\n\ndef main(argv):\n\tseterr(over='raise', divide='raise', invalid='raise')\n\t\n\t# OICA with Student's t-distribution marginals\n\tica = ISA(1, 2, ssize=1, num_scales=20)\n\tica.A[:] = [0.7, 1.1]\n\n\t# fit marginals to exponential power distribution\n\tica.initialize(method='exponpow')\n\n\t# prior landscape\n\txmin, xmax = -35, 35\n\ts = meshgrid(linspace(xmin, xmax, IMG_SIZE), linspace(xmin, xmax, IMG_SIZE))\n\tS = vstack([s[0].flatten(), s[1].flatten()])\n\tE = ica.prior_energy(S).reshape(*s[0].shape)[::-1]\n\n\t# nullspace\n\tW = pinv(ica.A)\n\tV = pinv(ica.nullspace_basis())\n\tx = -8.#18.\n\ts_fr = (W * x + V * Z_FROM).flatten()\n\ts_to = (W * x + V * Z_TO).flatten()\n\n\t# sample nullspace\n\tZ = ica.sample_nullspace(zeros([1, NUM_SAMPLES]) + x,\n\t\tmethod=('gibbs', {'num_steps': MCMC_STEPS})).flatten()\n\n\tfigure()\n\timshow(-E,\n\t\tcmap='shadows', \n\t\tdpi=DPI,\n\t\tvmin=-7.0,\n\t\tvmax=-2.0,\n\t\tlimits=[xmin, xmax, xmin, xmax])\n\tplot([s_fr[0], s_to[0]], [s_fr[1], s_to[1]], line_width=3., color='cyan')\n\tarrow(0, 0, W[0, 0] * x, W[1, 0] * x, line_width=1.5)\n\ttext(5.3, 5., '$A^+$')\n\taxis('origin')\n\txtick([])\n\tytick([])\n\txlabel('$s_1$')\n\tylabel('$s_2$')\n\tsavefig('results/prior.tex')\n\tdraw()\n\n\tfigure()\n\th = hist(Z, NUM_BINS, density=True, color='cyan', opacity=0.8, line_width=0.)\n\th.const_plot = False\n\taxis('origin')\n\taxis([Z_FROM, Z_TO, 0., 0.14])\n\txlabel('$z$')\n\tylabel('$p(z \\mid x)$')\n\txtick([])\n\tytick([])\n\tsavefig('results/nullspace.tex')\n\tdraw()\n\n\treturn 0\n\n\n\nif __name__ == '__main__':\n\tsys.exit(main(sys.argv))\n","sub_path":"code/experiments/nullspace.py","file_name":"nullspace.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"410775366","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 6 09:43:06 2017\n\n@author: jonfroiland\n\"\"\"\n\nfrom datetime import datetime\n\n\nclass CandlePrinter(object):\n\n def __init__(self):\n self.width = {\n 'time': 8,\n 'hour': 2,\n 'type': 8,\n 'price': 8,\n 'volume': 8,\n }\n self.time_width = 8\n\n def print_time(self, candle):\n try:\n time = str(datetime.strptime(\n candle.day, \"%Y-%m-%dT%H:%M:%S.000000000Z\").time())\n except:\n date = candle.time.split(\"T\")[0]\n hour = candle.time.split(\"T\")[1][0:5]\n time = date + ' ' + hour\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[time]}}\".format(\n time,\n width=self.width\n )\n\n time = \"\"\n\n def print_hour(self, candle):\n try:\n hour = str(datetime.strptime(\n candle.day, \"%Y-%m-%dT%H:%M:%S.000000000Z\").time())\n except:\n hour = candle.time.split(\"T\")[1][0:5]\n hour = int(hour[0:2])\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[hour]}}\".format(\n hour,\n width=self.width\n )\n\n hour = \"\"\n\n def print_open(self, candle):\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[price]}}\".format(\n can.o,\n width=self.width\n )\n\n def print_high(self, candle):\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[price]}}\".format(\n can.h,\n width=self.width\n )\n\n def print_low(self, candle):\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[price]}}\".format(\n can.l,\n width=self.width\n )\n\n def print_close(self, candle):\n for price in [\"mid\", \"bid\", \"ask\"]:\n can = getattr(candle, price, None)\n\n if can is None:\n continue\n\n return \"{:>{width[price]}}\".format(\n can.c,\n width=self.width\n )\n","sub_path":"daily/candlePrinter.py","file_name":"candlePrinter.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"209340764","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Diapo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'', max_length=20)),\n ('representativePhoto', models.ImageField(upload_to=b'diapo/template/images/diapos')),\n ],\n ),\n migrations.CreateModel(\n name='Photo',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(default=b'', max_length=20)),\n ('photo', models.ImageField(upload_to=b'diapo/template/images/photos')),\n ('diapo', models.ForeignKey(to='diapos.Diapo')),\n ],\n ),\n migrations.CreateModel(\n name='Photographer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('logo', models.ImageField(upload_to=b'diapo/template/images/photographer')),\n ],\n ),\n migrations.CreateModel(\n name='Video',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('urlId', models.CharField(default=b'', max_length=40)),\n ],\n ),\n ]\n","sub_path":"diapos/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"525042729","text":"# SELECTION - SORT\ndef selection_sort( arr ):\n for i in range(0, len(arr) - 1):\n cur_index = i\n min_index = cur_index\n\n for j in range(i, len(arr)):\n if arr[j] < arr[min_index]:\n min_index = j\n arr[min_index], arr[cur_index] = arr[cur_index], arr[min_index]\n return arr\n\n\n# BUBBLE - SORT\ndef bubble_sort( arr ):\n int = 0\n while int <= (len(arr)-1):\n print(int)\n for i in range(0, (len(arr)-1)):\n if arr[i] > arr[i + 1] and arr[i] != arr[len(arr)-1]:\n arr[i], arr[i + 1] = arr[i + 1], arr[i]\n int+=1\n return arr\n\n\n# COUNT - SORT\ndef count_sort( arr, maximum=-1 ):\n # not sure if I was supposed to do this, but no range was provided in tests and one of the tests was providing random values...\n # count needs to know the range of values to be efficient\n highest = 0\n for item in arr:\n if item > highest:\n highest = item\n\n if len(arr) == 0:\n return arr\n\n count_arr = [0] * (highest + 1)\n\n for i in arr:\n if i < 0:\n return 'Error, negative numbers not allowed in Count Sort'\n count_arr[i] = count_arr[i] + 1\n\n int = 0\n for j in range(len(count_arr)):\n while count_arr[j] > 0:\n arr[int] = j\n int = int+1\n count_arr[j] = count_arr[j] - 1\n return arr\n","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"81975725","text":"import numpy\n\nimport echidna.limit.chi_squared as chi_squared\n\nimport unittest\n\n\nclass TestChiSquared(unittest.TestCase):\n\n def test_pearson_chi_squared(self):\n \"\"\" Test the pearson chi squared function\n\n Tests that the function calculates accurate values\n \"\"\"\n array1 = numpy.array([100.0])\n array2 = numpy.array([110.0])\n self.assertEqual(chi_squared.pearson_chi_squared(array1, array2),\n (10.0 / 11.0))\n array1 = numpy.array([100.0])\n array2 = numpy.array([90.0])\n self.assertEqual(chi_squared.pearson_chi_squared(array1, array2),\n (10.0 / 9.0))\n array1 = numpy.array([100.0])\n array2 = numpy.array([100.0])\n self.assertEqual(chi_squared.pearson_chi_squared(array1, array2), 0.0)\n array1 = numpy.array([1])\n array2 = numpy.array([1, 2])\n self.assertRaises(ValueError, chi_squared.pearson_chi_squared,\n array1, array2)\n\n def test_neyman_chi_squared(self):\n \"\"\" Test the neyman chi squared function\n\n Tests that the function calculates accurate values\n \"\"\"\n array1 = numpy.array([100.0])\n array2 = numpy.array([110.0])\n self.assertEqual(chi_squared.neyman_chi_squared(array1, array2), 1.0)\n array1 = numpy.array([100.0])\n array2 = numpy.array([90.0])\n self.assertEqual(chi_squared.neyman_chi_squared(array1, array2), 1.0)\n array1 = numpy.array([100.0])\n array2 = numpy.array([100.0])\n self.assertEqual(chi_squared.neyman_chi_squared(array1, array2), 0.0)\n array1 = numpy.array([1])\n array2 = numpy.array([1, 2])\n self.assertRaises(ValueError, chi_squared.neyman_chi_squared,\n array1, array2)\n\n def test_log_likelihood(self):\n \"\"\" Test the log likelihood function\n\n Tests that the function calculates accurate values\n \"\"\"\n array1 = numpy.array([100.0])\n array2 = numpy.array([110.0])\n self.assertAlmostEqual(2.0*chi_squared.log_likelihood(array1, array2),\n 0.9379640391350215)\n array1 = numpy.array([100.0])\n array2 = numpy.array([90.0])\n self.assertAlmostEqual(2.0*chi_squared.log_likelihood(array1, array2),\n 1.072103131565271)\n array1 = numpy.array([100.0])\n array2 = numpy.array([100.0])\n self.assertEqual(chi_squared.log_likelihood(array1, array2), 0.0)\n array1 = numpy.array([1])\n array2 = numpy.array([1, 2])\n self.assertRaises(ValueError, chi_squared.log_likelihood,\n array1, array2)\n\n def test_get_chi_squared(self):\n \"\"\" Tests get chi squared method\n\n Tests functionality of the ChiSquared class and its principal\n method in different use case scenarios\n \"\"\"\n # create mock data spectrum\n n_bins = 10\n energy_low = 0.0\n energy_high = 10.0\n data_spectrum = numpy.ndarray(shape=(n_bins), dtype=float)\n data_spectrum.fill(0)\n\n # fill mock data spectrum from random gaussian\n entries = 1000\n numpy.random.seed()\n mu = 5.0\n sigma = 1.5\n for energy in numpy.random.normal(mu, sigma, entries):\n if (energy >= energy_low) and (energy < energy_high):\n energy_bin = int((energy-energy_low) /\n (energy_high-energy_low) * n_bins)\n data_spectrum[energy_bin] += 1\n\n # create mock MC spectrum\n mc_spectrum = data_spectrum * 1.1\n\n # set-up chi squared calculators\n pearson_calculator = chi_squared.ChiSquared(\"pearson\")\n neyman_calculator = chi_squared.ChiSquared(\"neyman\")\n likelihood_calculator = chi_squared.ChiSquared(\"poisson_likelihood\")\n penalty_calculator = chi_squared.ChiSquared(\n \"poisson_likelihood\",\n penalty_terms={\n \"bkg1\": {\n \"parameter_value\": 0.5,\n \"sigma\": 1.0\n }\n })\n\n pearson_chi_squared = pearson_calculator.get_chi_squared(data_spectrum,\n mc_spectrum)\n neyman_chi_squared = neyman_calculator.get_chi_squared(data_spectrum,\n mc_spectrum)\n likelihood_chi_squared = likelihood_calculator.get_chi_squared(\n data_spectrum,\n mc_spectrum)\n\n self.assertNotEqual(pearson_chi_squared, neyman_chi_squared)\n self.assertNotEqual(neyman_chi_squared, likelihood_chi_squared)\n self.assertNotEqual(likelihood_chi_squared, pearson_chi_squared)\n\n penalty_chi_squared = penalty_calculator.get_chi_squared(data_spectrum,\n mc_spectrum)\n self.assertNotEqual(likelihood_chi_squared, penalty_chi_squared)\n self.assertNotEqual(\n penalty_chi_squared,\n penalty_calculator.get_chi_squared(\n data_spectrum,\n mc_spectrum,\n penalty_terms={\n \"bkg1\": {\n \"parameter_value\": 1.0\n }\n }))\n self.assertEqual(\n likelihood_chi_squared,\n penalty_calculator.get_chi_squared(\n data_spectrum,\n mc_spectrum,\n penalty_terms={\n \"bkg1\": {\n \"parameter_value\": 0.0,\n \"sigma\": 0.5\n }\n }))\n self.assertEqual(\n penalty_chi_squared,\n likelihood_calculator.get_chi_squared(\n data_spectrum,\n mc_spectrum,\n penalty_terms={\n \"bkg1\": {\n \"parameter_value\": 0.5,\n \"sigma\": 1.0\n }\n }))\n","sub_path":"echidna/test/test_chi_squared.py","file_name":"test_chi_squared.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"625862929","text":"from math import pi, cos, sin\n\na = []\nb = []\nh = []\n\nm = 801 # filter length\nfca = .196 # cutoff \nfor i in range(m): # calculate first filter kernel\n if(i-m/2 == 0):\n a.append(2*pi*fca)\n\n if(i-m/2 != 0):\n a.append(sin(2*pi*fca * (i-m/2)) / (i-m/2))\n a[i] = a[i] * (0.54 - 0.46*cos(2*pi*i/m))\n \nfor i in range(m): # normalize the filter\n a[i] = a[i]/sum(a)\n \nfcb = .204\nfor i in range(m): # calculate first filter kernel\n if(i-m/2 == 0):\n b.append(2*pi*fcb)\n\n if(i-m/2 != 0):\n b.append(sin(2*pi*fcb * (i-m/2)) / (i-m/2))\n b[i] = b[i] * (0.54 - 0.46*cos(2*pi*i/m))\n \nfor i in range(m): # normalize the filter\n b[i] = b[i]/sum(b)\n \nfor i in range(m): # convert to high pass filter\n b[i] = b[i] * -1\nb[int((m-1)/2)] = b[int((m-1)/2)] + 1\n\nfor i in range(m): # add together to form band stop filter\n h.append(a[i] + b[i])\n \nfor i in range(m): # convert to band pass filter\n h[i] = h[i] * -1\nh[int((m-1)/2)] = h[int((m-1)/2)] + 1\n\nfile = open('header.h', 'w') \nfile.write(\"const double FILTER[\" + str(m) + \"] = \\n\")\nfile.write(\"{\")\n\nfor i in range(m):\n file.write(str(h[i]))\n if(i != m-1):\n file.write(', ')\n if((i+1) % 4 == 0):\n file.write('\\n')\n\nfile.write('}')\n\nfile.close()","sub_path":"FilterGeneration/bandpass.py","file_name":"bandpass.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"152055006","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : Mike\n# @Contact : 597290963@qq.com\n# @Time : 2021/2/27 15:39\n# @File : LongestSubstring.py\n\"\"\"\n给你一个字符串 s 和一个整数 k ,请你找出 s 中的最长子串, 要求该子串中的每一字符出现次数都不少于 k 。返回这一子串的长度。\n\n \n\n示例 1:\n\n输入:s = \"aaabb\", k = 3\n输出:3\n解释:最长子串为 \"aaa\" ,其中 'a' 重复了 3 次。\n示例 2:\n\n输入:s = \"ababbc\", k = 2\n输出:5\n解释:最长子串为 \"ababb\" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\n\"\"\"\n\n\nclass Solution:\n\n def longestSubstring(self, s: str, k: int) -> int:\n \"\"\"\n 先统计所有长度大于等于k 的字符\n 如果滑动到不大于k的字符,判断当前子串是否符合条件 left = cur_index + 1\n :param s:\n :param k:\n :return:\n \"\"\"\n if len(s) < k:\n return 0\n for c in set(s):\n if s.count(c) < k:\n return max(self.longestSubstring(t, k) for t in s.split(c))\n return len(s)\n\n\nif __name__ == '__main__':\n print(Solution().longestSubstring(\"bbaaacbd\",3))\n","sub_path":"datastructure/daily_topic/LongestSubstring.py","file_name":"LongestSubstring.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"340504540","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 12 16:34:44 2019\n\n@author: Alexandre\n\"\"\"\n\n###############################################################################\nimport numpy as np\n###############################################################################\nfrom pyro.control import robotcontrollers\nfrom pyro.control import nonlinear\nfrom pyro.dynamic import manipulator\n###############################################################################\n\nsys = manipulator.TwoLinkManipulator()\n\n# Estimated parameters\nsys.l1 = 0.3\nsys.l2 = 0.3\nsys.lc1 = 0.3\nsys.lc2 = 0.3\nsys.I1 = 0.5\nsys.I2 = 0.2\nsys.m1 = 0.9\nsys.m2 = 0.05\nsys.u_lb[0] = -1.0\nsys.u_lb[1] = -1.0\nsys.u_ub[0] = 1.0\nsys.u_ub[1] = 1.0\nsys.l_domain = 0.6\n\n# Target\nq_desired = np.array([0.,0.])\n\n# Joint PD\ndof = 2\njoint_pd = robotcontrollers.JointPD( dof )\njoint_pd.rbar = q_desired\njoint_pd.kp = np.array([ 3.0, 3.0 ])\njoint_pd.kd = np.array([ 1.0, 1.0 ])\n\n# Effector PD\neff_pd = robotcontrollers.EndEffectorPD( sys )\neff_pd.rbar = np.array([-0.4,+0.2])\neff_pd.kp = np.array([ 3.0, 3.0 ])\neff_pd.kd = np.array([ 1.0, 1.0 ])\n\n## Computed torque controller\nct_ctl = nonlinear.ComputedTorqueController( sys )\nct_ctl.w0 = 2.0\nct_ctl.zeta = 0.7\nct_ctl.rbar = np.array([0.0,0.0])\n\n# Controller selection\nctl = joint_pd\nctl = ct_ctl\nctl = eff_pd\n\n# Closed-loops\ncl_sys = ctl + sys\n\n# Simulations\ntf = 5\ncl_sys.x0 = np.array([-3.14,0,0,0])\ncl_sys.compute_trajectory( tf )\ncl_sys.plot_trajectory('xu')\ncl_sys.animate_simulation()\n","sub_path":"examples/projects/tmotor_robot/tmotor_robot_controller_simulation_tests.py","file_name":"tmotor_robot_controller_simulation_tests.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"186332450","text":"# Recommended imports for all problems\r\n# Some problems may require more\r\n\r\nimport sys\r\nimport math\r\nimport string\r\n\r\n\r\ndef maze_parser(in_file):\r\n cases = []\r\n in_file = iter(in_file)\r\n case_count = int(next(in_file).rstrip())\r\n for case in range(case_count):\r\n dims = next(in_file).rstrip()\r\n w, h = dims.split(' ')\r\n w, h = int(w), int(h)\r\n maze = [list(next(in_file).rstrip()) for _ in range(h)]\r\n cases.append({'w': w, 'h': h, 'maze': maze})\r\n return cases\r\n\r\n\r\ndef get_map(w, h):\r\n map = []\r\n for w_cell in range(w):\r\n for h_cell in range(h):\r\n map.append((w_cell, h_cell))\r\n return map\r\n\r\n\r\ndef find_points(maze):\r\n start = None\r\n exits = []\r\n for r, row in enumerate(maze):\r\n for c, col in enumerate(row):\r\n if col == 'X':\r\n exits.append((c, r))\r\n if col == 'o':\r\n start = ((c, r))\r\n return start, exits\r\n\r\n\r\ndef create_path(came_from, current):\r\n path = [current]\r\n while current in came_from:\r\n current = came_from[current]\r\n path.append(current)\r\n return path\r\n\r\n\r\ndef get_neighbors(cell, maze):\r\n pot_n = ((cell[0], cell[1]-1),\r\n (cell[0]-1, cell[1]),\r\n (cell[0]+1, cell[1]),\r\n (cell[0], cell[1]+1))\r\n neighbors = []\r\n for n in pot_n:\r\n if 0 <= n[1] < len(maze):\r\n row = maze[n[1]]\r\n if 0 <= n[0] < len(row):\r\n unit = maze[n[1]][n[0]]\r\n if unit == ' ' or unit == 'X':\r\n neighbors.append(n)\r\n return neighbors\r\n\r\n\r\ndef a_star(start, goal, map, maze):\r\n visited = []\r\n discovered = [start]\r\n came_from = {}\r\n g_score = {cell: math.inf for cell in map}\r\n g_score[start] = 0\r\n f_score = {cell: math.inf for cell in map}\r\n f_score[start] = math.fabs(start[0] - goal[0]) + math.fabs(start[1] - goal[1])\r\n\r\n while len(discovered) > 0:\r\n current = min(discovered, key=lambda cell: f_score[cell])\r\n if current == goal:\r\n return create_path(came_from, current), f_score[current]\r\n\r\n discovered.remove(current)\r\n visited.append(current)\r\n\r\n for neighbor in get_neighbors(current, maze):\r\n if neighbor in visited:\r\n continue\r\n\r\n next_g_score = g_score[current] + 1\r\n\r\n if neighbor not in discovered:\r\n discovered.append(neighbor)\r\n elif next_g_score >= g_score[neighbor]:\r\n continue\r\n\r\n came_from[neighbor] = current\r\n g_score[neighbor] = next_g_score\r\n f_score[neighbor] = g_score[neighbor] + math.fabs(neighbor[0] - goal[0]) + math.fabs(neighbor[1] - goal[1])\r\n\r\n return None, math.inf\r\n\r\n\r\ndef run(cases):\r\n outs = []\r\n for case in cases:\r\n w = case['w']\r\n h = case['h']\r\n maze = case['maze']\r\n map = get_map(w, h)\r\n\r\n path = None\r\n dist = math.inf\r\n start, exits = find_points(maze)\r\n for e in exits:\r\n new_path, new_dist = a_star(start, e, map, maze)\r\n if new_dist < dist:\r\n path = new_path\r\n dist = new_dist\r\n\r\n # render the path\r\n for p in path:\r\n if p != start and p not in exits:\r\n maze[p[1]][p[0]] = '.'\r\n outs.extend([''.join(row) for row in maze])\r\n return outs\r\n\r\n\r\nif __name__ == \"__main__\":\r\n lines = [l for l in sys.stdin]\r\n cases = maze_parser(lines)\r\n outs = run(cases)\r\n for o in outs:\r\n print(o)\r\n","sub_path":"codequest/2019Solutions/Lockheed Solutions/Python/Prob23.py","file_name":"Prob23.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"332014131","text":"import requests\r\n\r\napi = 'http://api.openweathermap.org/data/2.5/weather?apikey=7dbcb563a005513124e32ec4eeeb8a3b&units=metric&q='\r\ncity = input(\"City name: \" )\r\n# units = 'metrics'\r\nurl = api + city\r\n\r\njson_data = requests.get(url).json()\r\n\r\ndata = json_data['weather'][0]['description']\r\ntemp = json_data['main']['temp']\r\nprint(data, temp)","sub_path":"weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"225273802","text":"\"\"\"Utilities for manipulating samples\n\nNote: We currently just save things to disk as JSON files.\nWe will work with the \"data infrastructure\" team to figure out something better.\n\"\"\"\n\nimport logging\nfrom typing import Iterator\n\nfrom .config import settings\nfrom .models import Sample\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef save_sample(sample: Sample, overwrite: bool = True):\n \"\"\"Save a sample\n\n Args:\n sample: Sample to be saved\n overwrite: Whether overwriting existing files\n \"\"\"\n\n path = settings.sample_folder / f\"{sample.ID}.json\"\n if path.exists():\n if overwrite:\n logger.warning(f'Overwriting file at {sample.ID}')\n else:\n raise ValueError(f\"File already exists. Set overwrite=True, if you want to remove it. Path: {path}\")\n with open(path, 'w') as fp:\n fp.write(sample.json(indent=2))\n logger.info(f'Wrote {sample.ID} to {path}')\n\n\ndef load_samples() -> Iterator[Sample]:\n \"\"\"Load all of the known samples from disk\n\n Yields:\n Samples in no prescribed order\n \"\"\"\n\n for path in settings.sample_folder.glob(\"*.json\"):\n try:\n yield Sample.parse_file(path)\n except BaseException:\n continue\n","sub_path":"polybot/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"263566396","text":"from django.shortcuts import render,redirect\nfrom django.views import generic\nfrom .models import Picture, PComment\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom .forms import PictureForm, CommentForm\nfrom django.shortcuts import render, get_object_or_404,HttpResponseRedirect\nfrom feed.views import set_like,set_save\ndef like_post(request,slug):\n set_like(request,slug,2)\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\ndef save_post(request,slug):\n set_save(request,slug,2)\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\ndef picture_detail(request, slug):\n template_name = 'picture_detail.html'\n picture = get_object_or_404(Picture, slug=slug)\n currentuser=request.user\n alllikescount=picture.likes.count()\n alllikes=picture.likes.all()\n likelist=[]\n for i in alllikes:\n likelist.append(i.liked_by)\n comments = PComment.objects.all().filter(picture = picture)\n #comments = post.comments;\n new_comment = None\n # Comment posted\n if request.method == 'POST':\n comment_form = CommentForm(data=request.POST)\n if comment_form.is_valid():\n\n # Create Comment object but don't save to database yet\n new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment\n new_comment.workout = workout\n new_comment.author = currentuser\n # Save the comment to the database\n new_comment.save()\n else:\n comment_form = CommentForm()\n\n return render(request, template_name, {'picture': picture,\n 'piccomments': comments,\n 'currentuser':currentuser,\n 'new_comment': new_comment,\n 'comment_form': comment_form,\n 'alllikescount':alllikescount,\n 'likelist':likelist,\n })\ndef addpicture(request):\n template_name='addpicture.html'\n user=request.user\n '''user=get_object_or_404(User)\n posts=post.filter(status=1,author=user)'''\n new_picture=None\n if request.method=='POST':\n addpicture_form =PictureForm(request.POST,request.FILES)\n if addpicture_form.is_valid():\n new_picture=addpicture_form.save(commit=False)\n new_picture.author=user\n new_picture.save()\n return redirect('dashboard')\n else:\n addpicture_form=PictureForm()\n return render(request,template_name,{\n 'user':user,\n 'new_picture':new_picture,\n 'addpicture_form':addpicture_form})\n\ndef picture_update(request,slug):\n obj = get_object_or_404(Picture,slug=slug)\n form = PictureForm(request.POST or None, request.FILES or None, instance= obj)\n context= {'form': form}\n if request.method=='POST':\n if form.is_valid():\n obj= form.save(commit= False)\n obj.save()\n return redirect('dashboard')\n else:\n context= {'form': form,'error': 'The form was not updated successfully. Please enter in a title and content'}\n return render(request, 'picture_update.html', context)\n\n\ndef picture_delete(request, slug):\n picture = get_object_or_404(Picture, slug=slug)\n picture.delete()\n return redirect('dashboard')\n\n\ndef picture_comment(request, slug):\n #template_name = 'picture_comment.html'\n picture = get_object_or_404(Picture, slug=slug)\n user=request.user\n #comments = Comment.objects.filter(post = post)\n #comments = workout.comments.filter(active=True)\n new_comment = None\n # Comment posted\n if request.method == 'POST':\n new_comment=PComment(body=request.POST.get('messages'))\n #comment_form = CommentForm(data=request.POST)\n #if comment_form.is_valid():\n # Create Comment object but don't save to database yet\n #new_comment = comment_form.save(commit=False)\n # Assign the current post to the comment\n #new_comment.body = body\n new_comment.picture = picture\n new_comment.author = user\n new_comment.active = True\n # Save the comment to the database\n new_comment.save()\n #else:\n # comment_form = CommentForm()\n #return redirect('newsfeed')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n '''\n return render(request, template_name, {'workout': workout,\n 'comments': comments,\n 'new_comment': new_comment,\n 'comment_form': comment_form})\n'''\n","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"67871071","text":"'''\nTask\n\n\tThe interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3-Q1).\n\t\n\tGiven an array, X, of N integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each x1 occurs at frequency fi. \n\tThen calculate and print S's interquartile range, rounded to a scale of 1 decimal place (i.e., 12.3 format).\n\nInput Format\n\n\tThe first line contains an integer, n, denoting the number of elements in arrays X and F.\n\tThe second line contains n space-separated integers describing the respective elements of array X.\n\tThe third line contains n space-separated integers describing the respective elements of array F.\t\n\nSample Input\n\n\t6\n\t6 12 8 10 20 16\n\t5 4 3 2 1 5\n\nSample Output\n\n\t9.0\n'''\n\nimport statistics as st\n\nn = int(input())\ndata = list(map(int, input().split()))\nfreq = list(map(int, input().split()))\n\ns = []\nfor i in range(n):\n s += [data[i]] * freq[i]\nN = sum(freq)\ns.sort()\n\nif n%2 != 0:\n q1 = st.median(s[:N//2])\n q3 = st.median(s[N//2+1:])\nelse:\n q1 = st.median(s[:N//2])\n q3 = st.median(s[N//2:])\n\nir = round(float(q3-q1), 1)\nprint(ir)\n","sub_path":"interquartile_range.py","file_name":"interquartile_range.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"59564421","text":"import json\nfrom datetime import datetime\nfrom hashlib import md5\nfrom base64 import b64encode\nimport requests\n\nfrom exception_ import RouterError\n\n\nclass SMSManager:\n\n __ROUTER_LOGIN_PATH = 'userRpm/LoginRpm.htm?Save=Save'\n __ROUTER_SMS_REFERER = '/userRpm/_lte_SmsInboxCfgRpm.htm'\n __ROUTER_SMS_CASH = '/userRpm/lteWebCfg'\n\n def __init__(self, router_address, router_admin, router_password) -> None:\n super().__init__()\n self.router_url = 'http://' + router_address + '/'\n self.auth_string = router_admin + ':' + md5(router_password.encode('utf-8')).hexdigest()\n self.auth_string = 'Basic ' + b64encode(self.auth_string.encode('utf-8')).decode('utf-8')\n self.__check_connection()\n\n def update_flowmeter(self, flowmeter):\n sms_list = []\n for sms in self.__get_sms():\n if sms['from'] == flowmeter.phone_number:\n sms_list.append(sms['content'].split())\n sms_last_update = datetime(1999, 1, 1, 1, 1)\n if sms_list:\n if len(sms_list[0]) == 15:\n sms_last_update = datetime.strptime(sms_list[0][1] + \" \" + sms_list[0][2] + \":00\", '%Y-%m-%d %H:%M:%S')\n if flowmeter.last_update < sms_last_update:\n flowmeter.totalizer1 = float(sms_list[0][-1])\n flowmeter.last_update = sms_last_update\n return flowmeter\n else:\n return flowmeter\n\n def __get_sms(self):\n cookie = {'Authorization': self.auth_string}\n session = requests.Session()\n login_request = session.get(self.router_url + self.__ROUTER_LOGIN_PATH, cookies=cookie)\n hash_login = login_request.text.split('/')[3]\n header = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'Connection': 'keep-alive',\n 'Content-Length': '72',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Host': '192.168.1.1',\n 'Origin': 'http://192.168.1.1',\n 'referer': self.router_url + hash_login + self.__ROUTER_SMS_REFERER,\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' +\n 'Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.62',\n 'X-Requested-With': 'XMLHttpRequest',\n }\n data = {\"module\": \"message\", \"action\": 2, \"pageNumber\": 1, \"amountPerPage\": 8, \"box\": 0}\n login_request = session.post(self.router_url + hash_login + self.__ROUTER_SMS_CASH,\n cookies=cookie, headers=header, data=json.dumps(data))\n return login_request.json()['messageList']\n\n def __check_connection(self):\n cookie = {'Authorization': self.auth_string}\n session = requests.Session()\n login_request = session.get(self.router_url + self.__ROUTER_LOGIN_PATH, cookies=cookie)\n hash_login = login_request.text.split('/')\n if len(hash_login) > 9:\n raise RouterError\n","sub_path":"service/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"79544054","text":"from datetime import datetime\nfrom ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.testing import create_ogds_user\nfrom opengever.testing import FunctionalTestCase\nfrom opengever.testing import index_data_for\nfrom opengever.testing import obj2brain\n\n\nclass TestTaskIndexers(FunctionalTestCase):\n\n def setUp(self):\n super(TestTaskIndexers, self).setUp()\n\n create(Builder('org_unit')\n .with_default_groups()\n .id('client2')\n .having(title='Client2', admin_unit=self.admin_unit))\n\n self.task = create(Builder(\"task\")\n .titled(\"Test task 1\")\n .having(task_type='comment'))\n\n def test_date_of_completion(self):\n self.assertEquals(\n obj2brain(self.task).date_of_completion,\n datetime(1970, 1, 1))\n\n self.task.date_of_completion = datetime(2012, 2, 2)\n self.task.reindexObject()\n\n self.assertEquals(\n obj2brain(self.task).date_of_completion,\n datetime(2012, 2, 2))\n\n def test_assigned_client(self):\n self.assertEquals(\n obj2brain(self.task).assigned_client, 'client1')\n\n self.task.responsible = 'hugo.boss'\n self.task.responsible_client = 'client2'\n self.task.reindexObject()\n\n self.assertEquals(\n obj2brain(self.task).assigned_client, 'client2')\n\n def test_is_subtask(self):\n self.subtask = create(Builder(\"task\").within(self.task)\n .titled(\"Test task 1\")\n .having(task_type='comment'))\n\n self.assertFalse(obj2brain(self.task).is_subtask)\n\n self.assertTrue(obj2brain(self.subtask).is_subtask)\n\n def test_searchable_text(self):\n self.task.title = u'Test Aufgabe'\n self.task.text = u'Lorem ipsum olor sit amet'\n self.task.task_type = 'comment'\n\n create_ogds_user('hboss', firstname=u'Hugo', lastname=u'B\\xf6ss')\n self.task.responsible = 'hboss'\n\n self.task.reindexObject()\n\n self.assertEquals(\n ['test', 'aufgabe', 'lorem', 'ipsum', 'olor', 'sit',\n 'amet', 'to', 'comment', '1', 'boss', 'hugo', 'hboss'],\n index_data_for(self.task).get('SearchableText'))\n","sub_path":"opengever/task/tests/test_indexer.py","file_name":"test_indexer.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"589216607","text":"cs = ['HOH','MSE','DOD','MLY','GOL','NAG','FS4','MPD','CME','KCX','HYP','MES','LDA','TRS','EPE','BOG','TRP','PTR','CGU','SEP','TPO','PCA', 'SMC','DLE','CSD','CRY','C8E','LLP','CEA','ABA','IPH','FS3','OXL','YOF','TYS','DVA','SF4','LI1','PG4']\n\npathmmcif = \"/data/pdb/divided/mmCIF\"\n#pathmmcif = \"/Volumes/BIOINFO/mmCIF/\"\n\nimport re\nimport gzip\nfrom Bio.PDB.MMCIFParser import MMCIFParser\nparser = MMCIFParser(QUIET=True)\nfrom Bio.PDB.Polypeptide import three_to_one as tto\n\nf = open(\"entries.idx\",\"r\")\nft = f.readlines()\nf.close()\n\ng = open(\"type_of_protein.txt\",\"w\")\n\nk = 5\nwhile k < len(ft):\n\tprint(k,len(ft))\n\tft1 = ft[k].split()\n\tpdb = ft1[0].lower()\n\tif len(pdb) == 4:\n\t\tcount1 = 0\n\t\tif count1 == 0:\n\t\t#try:\n\t\t\tfol = pdb[1:3]\n\t\t\tpdbfile = \"{}/{}/{}.cif.gz\".format(pathmmcif,fol,pdb)\n\t\t\ttar = gzip.open(\"{}\".format(pdbfile),\"rb\")\n\t\t\tout = open(\"pdbprocess.cif\",\"wb\")\n\t\t\tout.write(tar.read())\n\t\t\ttar.close()\n\t\t\tout.close()\n\n\t\t\tstructure_id = \"{}\".format(pdb)\n\t\t\tfilename = \"pdbprocess.cif\"\n\t\t\tstructure = parser.get_structure(structure_id,filename)\n\n\t\t\tmodel = structure[0]\n\t\t\tnumchains = model.get_list()\n\t\t\tk2 = 0\n\t\t\twhile k2 < len(numchains):\n\t\t\t\tchainpdb = numchains[k2].get_id()\n\t\t\t\tchain = model[\"{}\".format(chainpdb)]\n\t\t\t\tc1 = chain.get_list()\t\t# LIST ALL THE RESIDUES\n\t\t\t\tk1 = 0\n\t\t\t\tcount = 0\n\t\t\t\twhile k1 < len(c1):\n\t\t\t\t\tc2 = c1[k1].get_id()\n\t\t\t\t\tif c2[0] != \" \":\n\t\t\t\t\t\tresidue = chain[c2]\n\t\t\t\t\t\tresname = residue.get_resname()\n\t\t\t\t\t\tif resname.upper() not in cs:\n\t\t\t\t\t\t\tcount = count + 1\n\t\t\t\t\tk1 = k1 + 1\n\t\t\t\tif count != 0:\n\t\t\t\t\tg.write(\"{}\t{}\tHOLO\\n\".format(pdb,chainpdb))\n\t\t\t\telse:\n\t\t\t\t\tg.write(\"{}\t{}\tAPO\\n\".format(pdb,chainpdb))\n\t\t\t\t\n\t\t\t\tk2 = k2 + 1\n\t\t#except:\n\t\t\t#print(\"FILE ERROR\")\n\n\tk = k + 1\n\ng.close()\n\n\n\n\n","sub_path":"mut_prop/apo_holo.py","file_name":"apo_holo.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"435493482","text":"import requests,json,random,time,logging\nimport redis\nfrom lxml import etree\nfrom datetime import datetime\nimport fake_useragent\nfrom fake_useragent import UserAgent\nfrom fake_useragent import FakeUserAgentError\n\nclass CustomLogger(object):\n\tdef __init__(self, logger_name):\n\t\tfilen = datetime.now().strftime('%Y-%m-%d %H')\n\t\t#('%Y-%m-%d %H:%M')\n\t\tself.log_filen = r\"/media/gumoha/资料/Scrapy/QDaily/LOG/-log-{0}.json\".format(filen)\n\t\tself.log_level = logging.INFO\n\t\tself.name = logger_name #\n\t\tself.logger = logging.getLogger(self.name)\n\n\t\t# 定义输出格式\n\t\tlog_format = '%(asctime)s-%(name)s-%(levelname)s-%(lineno)d-%(message)s'\n\t\tself.formatter = logging.Formatter(log_format)\n\n\t\t# 创建一个handler,用于输出到控制台\n\t\tself.sh = logging.StreamHandler()\n\t\tself.sh.setFormatter(self.formatter)\n\n\t\t# 创建一个handler,用于输出到日志文件\n\t\tself.logger.setLevel(self.log_level)\n\t\tself.fh = logging.FileHandler(self.log_filen, mode='w',encoding='utf-8')\n\t\tself.fh.setFormatter(self.formatter)\n\n\t\tself.logger.addHandler(self.sh)\n\t\tself.logger.addHandler(self.fh)\n\n\tdef getlog(self):\n\t\treturn self.logger\n\nclog = CustomLogger('clog').getlog()\n\ndef get_RandomUA():\n\ttry:\n\t\tua = UserAgent()\n\texcept FakeUserAgentError:\n\t\tpass\n\t\n\treturn(ua.random)\n\ndef get_proxies(filen):\n\tips_list = []\n\ttry:\n\t\twith open(filen,'r') as f:\n\t\t\tdataIP = f.readlines()\n\t\t\tfor i in dataIP:\n\t\t\t\ttry:\n\t\t\t\t\tip = json.loads(i)\n\t\t\t\t\t#print('IP:{0},Type:{1}'.format(i,type(i)))\n\t\t\t\t\tips_list.append(ip)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint('ErrorType:{0},Error:{1}'.format(type(e),e))\n\texcept Exception as e:\n\t\tprint('Open File -- ErrorType:{0},Error:{1}'.format(type(e),e))\n\t\n\treturn ips_list\n\t\ndef requests_homeUrl(url,headers):\n\ttry:\n\t\treq = requests.get(url,headers=headers,allow_redirects=False,timeout=5)\n\texcept Exception as e:\n\t\tclog.error('req Error:\\n{0}\\n'.format(e))\n\t\n\treq.encoding = 'utf-8'\n\tplain_text = req.text\n\thtml = etree.HTML(plain_text)\n\t\n\tlast_key = html.xpath('//div[contains(@class,\"packery-container articles\")]/@data-lastkey')[0]\n\tfirstApi = 'http://www.qdaily.com/tags/tagmore/1068/{0}.json'.format(str(last_key))\n\t\n\treturn(firstApi)\n\ndef requests_api(apiurl,headers):\n\ttime.sleep(random.random()*10)\n\ttry:\n\t\treq = requests.get(apiurl,headers=headers,allow_redirects=False,timeout=20)\n\texcept Exception as e:\n\t\tclog.error('req1 Error:{0}\\n'.format(e))\n\t\n\ttry:\n\t\treq.encoding = 'utf-8'\n\t\tplain_text = req.json()\n\texcept Exception as e:\n\t\tclog.error('req2 Error:{0}\\n'.format(e))\n\t\n\tif plain_text['status'] is True:\n\t\treturn(plain_text)\n\ndef nextReqUrl(plain_text):\n\ttry:\n\t\tif plain_text['data']['last_key']:\n\t\t\tlast_key = plain_text['data']['last_key']\n\texcept Exception as e:\n\t\tclog.error('last_key ErrorType:{0},Error:{1}\\n'.format(type(e),e))\n\tnextUrl = 'http://www.qdaily.com/tags/tagmore/1068/{0}.json'.format(str(last_key))\n\treturn nextUrl\n\ndef connect_redis():\n\tpool = redis.ConnectionPool(host='127.0.0.1', port=6379, db=0, password=None,\n\t\t\t\t\t\t\t\tencoding='utf-8', decode_responses=True)\n\tredisdb = redis.Redis(connection_pool=pool)\n\tprint('链接Redis:{0} 成功'.format(redisdb))\n\treturn redisdb\n\n\nif __name__ == '__main__':\n\tfilen_articlesID =r'/media/gumoha/资料/Scrapy/QDaily/ArticlesData/-ArticlesID-.json'\n\tredisdb = connect_redis()\n\tarticlesApiKey = 'Qdaily_articlesApi'\n\tarticlesIDKey = 'Qdaily_articlesID'\n\tua = get_RandomUA()\n\t\n\theadersHome = {\n\t\t'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n\t\t'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n\t\t'Accept-Encoding': 'gzip,deflate,br',\n\t\t'Connection': 'keep-alive',\n\t\t'Host': 'www.qdaily.com',\n\t\t'Referer':'http://www.qdaily.com/',\n\t\t'DNT': '1',\n\t\t'Upgrade-Insecure-Requests':'1',\n\t\t'User-Agent':ua,\n\t\t#'If-Modified-Since':'Sun, 16 Apr 2019 03:10:18 GMT',\n\t\t#'If-None-Match':'\"5cb362a8-5b8f\"',\n\t\t'Cache-Control':'max-age=0'\n\t}\n\thomeUrl = 'http://www.qdaily.com/tags/1068.html'\n\t#articlestApi = 'http://www.qdaily.com/tags/tagmore/1068/1554358329.json'\n\tarticlesApi = requests_homeUrl(homeUrl,headersHome)\n\t\n\t#filen_proxy = r'/media/gumoha/资料/Scrapy/IP_jiangxianli/freeip-DataJson/-RedisProxyData-.json'\n\t#ips_list = get_proxies(filen_proxy)\n\t#ips = random.choice(ips_list)\n\t#{'protocol': 'http', 'ip': '116.209.53.28', 'port': '8229'} \n\t#proxies = {\"{0}\".format(ips['protocol']):\"{0}:{1}\".format(ips['ip'],ips['port']),}\n\t\n\theaders = {\n\t\t'Accept': 'application/json, text/javascript, */*; q=0.01',\n\t\t'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n\t\t'Accept-Encoding': 'gzip,deflate,br',\n\t\t'Connection': 'keep-alive',\n\t\t'Host': 'www.qdaily.com',\n\t\t'Referer':'http://www.qdaily.com/',\n\t\t'DNT': '1',\n\t\t'User-Agent':ua,\n\t}\n\t\n\twhile True:\n\t\ttry:\n\t\t\tredisdb.sadd(articlesApiKey,json.dumps(articlesApi))\n\t\t\tclog.info('Redis Insert:{0}\\n'.format(articlesApi))\n\t\texcept Exception as e:\n\t\t\tclog.error('Insert Redis -- ErrorType:{0},Error:{1}'.format(type(e),e))\n\t\t\n\t\tplain_text = requests_api(articlesApi,headers)\n\t\t\n\t\tids = []\n\t\ttimeNow = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\t\tfeedsInfo = {}\n\t\tfeeds = plain_text['data']['feeds']\n\t\tfor i in range(len(feeds)):\n\t\t\tdatatype = feeds[i]['datatype']\n\t\t\tif datatype == 'article':\n\t\t\t\tarID = feeds[i]['post']['id']\n\t\t\t\tarticlesInfo = {}\n\t\t\t\tarticlesInfo['ID'] = arID\n\t\t\t\tarticlesInfo['Title'] = feeds[i]['post']['title']\n\t\t\t\tarticlesInfo['DataType'] = datatype\n\t\t\t\ttry:\n\t\t\t\t\tredisdb.sadd(articlesIDKey,json.dumps(articlesInfo))\n\t\t\t\t\tclog.info('Redis Insert:{0}\\n'.format(articlesInfo))\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tclog.error('Insert Redis -- ErrorType:{0},Error:{1}'.format(type(e),e))\n\t\t\t\tids.append(arID)\n\t\t\t\t\n\t\twith open(filen_articlesID,'a') as f:\n\t\t\tfeedsInfo['Datetime'] = timeNow\n\t\t\tfeedsInfo['IDNumber'] = ids\n\t\t\ttry:\n\t\t\t\tline = json.dumps(feedsInfo) + '\\n'\n\t\t\t\tf.write(line)\n\t\t\t\tclog.info('{0}保存完成\\n'.format(articlesApi))\n\t\t\texcept Exception as e:\n\t\t\t\tclog.error('Insert Json -- ErrorType:{0},Error:{1}'.format(type(e),e))\n\t\t\t\n\t\tif nextReqUrl(plain_text) is not None:\n\t\t\tarticlesApi = nextReqUrl(plain_text)\n\t\t\tclog.info('下一个Api:{0},继续获取(等待约600秒......)\\n'.format(articlesApi))\n\t\t\ttime.sleep(random.random()*600)\n\t\t\tcontinue\n\t\telse:\n\t\t\tclog.info('没有下一个Api,停止\\n')\n\t\t\tbreak\n\t\t\t\n\t\t\t\n\t\t\n\t\n\t\n","sub_path":"FindArticlesID.py","file_name":"FindArticlesID.py","file_ext":"py","file_size_in_byte":6287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"80563093","text":"\"\"\"Class that can get market prices from the tcgplayer website.\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\nfrom selenium.common.exceptions import NoSuchElementException\n\nclass TCGPlayerAPI():\n \"\"\"This is designed so that it is instantiated once at the beginning of\n a single file, and that single instance is used across all parts of\n that file. This is because the startup for the broswer takes some time,\n and so instantiating multiples can take a long time/require too much\n memory.\"\"\"\n\n\n def __init__(self):\n # This url doesn't work for everything on the TCGPlayer site.\n self.base_url = \"https://www.tcgplayer.com/search/all/product?q=\"\n self.set_url = \"https://shop.tcgplayer.com/magic/\"\n # options = Options()\n # options.headless = True\n # self.driver = webdriver.Firefox(options=options)\n self.driver = webdriver.Firefox()\n\n\n def get_price(self, card_name, card_set=None):\n \"\"\"\n Want to be able to search for multiple things.\n 1. Generic searches of a singular card name. Only return market prices\n cards with the given card names (some generic searches return more\n cards than the one searched for).\n 2. Specific searches, where a card name and set are given. This should\n only return the market price for that specific card.\n 3. Handle searching multiple urls.\n \"\"\"\n\n card_name = card_name.split(\" \")\n card_query = \"%20\".join(card_name).lower()\n\n if card_set:\n prices = self.get_set_price(card_query, card_set)\n else:\n prices = self.get_generic_price(card_query)\n\n if prices[0] == -1:\n # The price fetch failed.\n print(\"Failed to fetch price.\")\n\n return prices\n\n\n def get_generic_price(self, card_query):\n \"\"\"Gets a list of cards from a generic all products endpoint.\"\"\"\n endpoint = f\"{self.base_url}{card_query}\"\n # print(endpoint)\n prices = list()\n\n self.driver.get(endpoint)\n # Wait until a market price can be found, or no results were found.\n WebDriverWait(self.driver, 2).until(\n ec.visibility_of_element_located((\n By.XPATH,\n (\n \"//span[@class='search-result__market-price-value'] | \"\n \"//div[@class='blank-slate']\"\n )\n ))\n )\n\n # Check if no results were found.\n try:\n self.driver.find_element_by_xpath(\n \"//div[@class='blank-slate']\")\n return [-1]\n except NoSuchElementException:\n pass\n\n div = self.driver.find_element_by_xpath(\n \".//div[@id='app']\")\n search_results = div.find_element_by_xpath(\n \".//span[@class='search-results']\")\n results = search_results.find_elements_by_xpath(\n \".//div[@class='search-result']\")\n\n for result in results:\n # Isolate the part of the webpage with the search results.\n body = result.find_element_by_xpath(\n \".//a[@class='search-result__body']\")\n\n try:\n # Check if returned cards have the same name.\n name = body.find_element_by_xpath(\n \".//div[@class='search-result__title']\").text\n if \" \".join(card_query.split(\"%20\")) not in name.lower():\n continue\n\n # Check if the cards are from the same game.\n game = body.find_element_by_xpath(\n \".//div[@class='search-result__category-name']\").text\n if game != \"Magic: The Gathering\":\n # Card was from a different game, but had the same name.\n continue\n\n # Finally get the market price if those previous two conditions\n # are true.\n market_price = body.find_element_by_xpath(\n \".//span[@class='search-result__market-price-value']\").text\n prices.append(market_price)\n\n except NoSuchElementException:\n # The card name, card game, or market price were unavailable,\n # so skip it.\n continue\n\n if not prices:\n prices.append(-1)\n\n return prices\n\n\n def get_set_price(self, card_query, card_set):\n \"\"\"Gets a single card's information from a set specific endpoint.\"\"\"\n card_set = \"-\".join(card_set.split(\" \"))\n endpoint = f\"{self.set_url}{card_set.lower()}/{card_query}\"\n print(endpoint)\n prices = list()\n\n self.driver.get(endpoint)\n # Wait until a market price can be found, or no results were found.\n WebDriverWait(self.driver, 2).until(\n ec.visibility_of_element_located((\n By.XPATH, (\n \"//td[@class='price-point__data'] | \"\n \"//div[@id='maincontentinnerpadding']\")\n ))\n )\n\n try:\n self.driver.find_element_by_xpath(\n \".//div[@id='maincontentinnerpadding']\")\n print(\"nothing found\")\n return [-1]\n except NoSuchElementException:\n pass\n\n try:\n # Narrow down the webpage.\n price_guide = self.driver.find_element_by_xpath(\n \".//section[@class='price-guide']\")\n market_section = price_guide.find_element_by_xpath(\n \".//div[@class='price-point price-point--market']\")\n\n # Scrape the market prices.\n market_price = market_section.find_element_by_xpath(\n \".//td[@class='price-point__data']\").text\n prices.append(market_price)\n except NoSuchElementException as e:\n # Put the not found value in the list instead if an element is not\n # found.\n print(e)\n prices.append(-1)\n\n return prices\n\n\n def close(self):\n \"\"\"Stop the browser.\"\"\"\n self.driver.close()\n","sub_path":"TCGPlayerApi/tcgplayerapi.py","file_name":"tcgplayerapi.py","file_ext":"py","file_size_in_byte":6283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"555150351","text":"# HackerRank\n# Domain: Algorithms\n# Subdomain: Implementation\n# Challenge: Chocolate Feast\n\nT = int(input())\n\nfor i in range(T):\n N, C, M = (int(x) for x in input().split())\n total = wrappers = N / C\n\n while wrappers >= M:\n trade = wrappers // M\n total += trade\n wrappers %= M\n wrappers += trade\n print(int(total))\n","sub_path":"Algorithms/Implementation/ChocolateFeast.py","file_name":"ChocolateFeast.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"421844425","text":"# -*- coding: utf-8 -*-\n# Copyright 2013 Pierre de Buyl\n# Copyright 2013 Konrad Hinsen\n#\n# This file is part of pyh5md\n#\n# pyh5md is free software and is licensed under the modified BSD license (see\n# LICENSE file).\n\n# This file is based on code from the h5py project. The complete h5py license is\n# available at licenses/h5py.txt, in the distribution root directory.\n\nimport numpy\n\nimport h5py\nimport h5py.version\nfrom h5py import h5s, h5t, h5r, h5d\nfrom h5py._hl import dataset\nfrom h5py._hl.base import HLObject\nfrom h5py._hl import filters\nfrom h5py._hl import selections as sel\nfrom h5py._hl import selections2 as sel2\n\n\ndef create_compact_dataset(loc, name, shape=None, dtype=None, data=None,\n chunks=None, compression=None, shuffle=None,\n fletcher32=None, maxshape=None,\n compression_opts=None, fillvalue=None,\n scaleoffset=None, track_times=None):\n \"\"\"Create a new HDF5 dataset with a compact storage layout.\"\"\"\n\n # Convert data to a C-contiguous ndarray\n if data is not None:\n import h5py._hl.base\n data = numpy.asarray(data, order=\"C\", dtype=h5py._hl.base.guess_dtype(data))\n\n # Validate shape\n if shape is None:\n if data is None:\n raise TypeError(\"Either data or shape must be specified\")\n shape = data.shape\n else:\n shape = tuple(shape)\n if data is not None and (numpy.product(shape) != numpy.product(data.shape)):\n raise ValueError(\"Shape tuple is incompatible with data\")\n\n if isinstance(dtype, h5py.Datatype):\n # Named types are used as-is\n tid = dtype.id\n dtype = tid.dtype # Following code needs this\n else:\n # Validate dtype\n if dtype is None and data is None:\n dtype = numpy.dtype(\"=f4\")\n elif dtype is None and data is not None:\n dtype = data.dtype\n else:\n dtype = numpy.dtype(dtype)\n tid = h5t.py_create(dtype, logical=1)\n\n # Legacy\n if any((compression, shuffle, fletcher32, maxshape,scaleoffset)) and chunks is False:\n raise ValueError(\"Chunked format required for given storage options\")\n\n # Legacy\n if compression is True:\n if compression_opts is None:\n compression_opts = 4\n compression = 'gzip'\n\n # Legacy\n if compression in range(10):\n if compression_opts is not None:\n raise TypeError(\"Conflict in compression options\")\n compression_opts = compression\n compression = 'gzip'\n\n if h5py.version.version_tuple >= (2, 2, 0, ''):\n dcpl = filters.generate_dcpl(shape, dtype, chunks, compression,\n compression_opts, shuffle, fletcher32,\n maxshape, None)\n else:\n dcpl = filters.generate_dcpl(shape, dtype, chunks, compression,\n compression_opts, shuffle, fletcher32,\n maxshape)\n\n if fillvalue is not None:\n fillvalue = numpy.array(fillvalue)\n dcpl.set_fill_value(fillvalue)\n\n if track_times in (True, False):\n dcpl.set_obj_track_times(track_times)\n elif track_times is not None:\n raise TypeError(\"track_times must be either True or False\")\n\n dcpl.set_layout(h5d.COMPACT)\n\n if maxshape is not None:\n maxshape = tuple(m if m is not None else h5s.UNLIMITED for m in maxshape)\n sid = h5s.create_simple(shape, maxshape)\n\n\n dset_id = h5d.create(loc.id, None, tid, sid, dcpl=dcpl)\n\n if data is not None:\n dset_id.write(h5s.ALL, h5s.ALL, data)\n\n dset = dataset.Dataset(dset_id)\n if name is not None:\n loc[name] = dset\n return dset\n","sub_path":"pyh5md/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"519361704","text":"# Title: InterpreterForCSV\n# Created by: Samit Shaikh\n# Created: N/A\n# Date of Last Revision: 2018-11-08\n# Purpose: To interpret .csv files\n\nimport os\n\nname = os.path.realpath(__file__)\nlogr = input('LOGR (True/False): ').lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly',\n 'uh-huh'] # If userinput is in the list then variable logr is True\nprint() # Print new line\n\n\ndef log(text, validator, **opt):\n # This function accepts parameters: text, validator and 2 optional parameters.\n namee = ''\n # Initialise name with an empty string.\n if 'name' in opt:\n namee = opt['name']\n # If user did assign a value to the optional parameter, 'name', then the value would be stored in variable name.\n if validator:\n if 'wait' in opt:\n if opt['wait']:\n input('LOG>>> Enter to continue >>>')\n else:\n print('LOG>>> ' + str(text) + ' <<< ' + str(namee))\n else:\n print('LOG>>> ' + str(text) + ' <<< ' + str(namee))\n # If validator is True (normally this is used so when they run the program they can choose if they want logging\n # or not.) then a string with the text and name used in it will be printed unless it is specified that the user\n # enter's to continue. This can be specified in optional paramter, 'wait' with the value: True.\n\n\ndef error(nameee, err, string):\n # This function will return the error name that programs can use and print a error message in the console.\n print('\\n!ERROR_' + err.upper() + '! ' + string + ' [' + nameee + ']\\n')\n return '!ERROR_' + err.upper() + '!'\n\n\ndef exist(filename):\n # Tries to open file which name is stored in the parameter, 'filename'.\n try: # Tries...\n open(str(filename))\n except FileNotFoundError:\n return False\n # If there is a FileNotFoundError than return False...\n return True\n # ...otherwise return True.\n\n\ndef read_csv(filename, header): # Define function read_csv with parameters: filename and header.\n # This function checks for multiple csv file formatting requirements such as ignoring commas between quotation marks\n # and returns a list with dictionaries inside representing each line. If header is True then you can call fields by\n # it's header.\n lognm = ' - read_csv()'\n while True: # Infinitely loop the following until broken.\n if filename.endswith('.csv'): # If variable filename's string ends with '.csv' then...\n try:\n with open(str(filename),\n 'r') as fr: # ...try to open file which name is stored in variable filename as fr.\n content = fr.readlines() # Store list containing each line in the opened file, fr, as a list item.\n content = [xx.strip() for xx in\n content] # Removes whitespace (eg. ' ', '\\n') from each line in list variable content.\n except FileNotFoundError: # If there is an error, FileNotFoundError, then...\n return error(name, '01_FILENOTFOUND',\n 'The file you gave was not found or there was a problem with the program. (the file must '\n 'be in the same directory as this program.)') # return a custom error.\n if not content:\n return error(name, '02_EMPTY', 'The file contains nothing.')\n else:\n for i in range(\n len(content)): # While variable i is in the range of the number of list items in content...\n if ',' not in content[i]: # If there is not a ',' in variable i of content...\n return error(name, '03_FORMATERROR',\n 'Not formatted correctly according to CSV format.') # ..return a custom error.\n log('VERIFIED', logr, name=lognm) # Log 'VERIFIED' if logr is True.\n pp = [] # Store an empty list in variable pp.\n log('LOOP x', logr, name=lognm) # Log 'LOOP X' if logr is true.\n log(len(content), logr, name='len(content)' + lognm)\n for x in range(\n len(content)): # While variable x is in the range of the number of list items in content...\n xx = content[x].split(\n ',') # ...split x of content around the commas and store the list output in variable xx.\n b = [] # Store an empty list in variable b.\n log('LOOP c', logr, name=lognm) # Log 'LOOP C' if logr is True.\n for c in range(\n len(xx)): # While variable c is in the range of the number of items in list variable xx...\n log('LOOP y', logr, name=lognm) # ...log 'LOOP Y' if logr is True.\n for y in range(len(\n xx)): # While variable y is in the range of the number of items in the list variable\n # xx...\n z = ','.join(xx[\n c:y + 1]) # ...join variable c to variable y plus 1 of list variable xx\n # with commas and store it in variable z.\n z = z.strip() # Remove whitespace (eg. ' ', '\\n') from variable z.\n log(z, logr, name='z' + lognm) # Log variable z if logr is True and with the name: 'z'.\n log(str(z.startswith('\\\"')), logr,\n name='z.startswith(\\'\\\"\\')' + lognm) # Log True if z starts with '\"' if logr is true\n # and with the name: 'z.startswith('\"')'.\n log(str(z.endswith('\\\"')), logr,\n name='z.endswith(\\'\\\"\\')' + lognm) # Log True if z ends with '\"' if logr is true and\n # with the name: 'z.endswith('\"')'.\n if z.startswith('\\\"') and z.endswith('\\\"'): # If z starts with and ends with '\"\"' then...\n log(str([c, y + 1]), logr,\n name='[c, y + 1]' + lognm) # ...log list containing c and y plus 1 if logr is\n # True and with the name: '[c, y + 1]'.\n b.append([c, y + 1]) # Append list containing c and y plus 1 to list variable b.\n b.append([-1, -1]) # Append list containing negative 1 and negative 1 to list variabel b.\n log(str(b), logr, name='b' + lognm) # Log variable b if logr is True with the name: 'b'.\n p = [] # Store empty list in variable p.\n m = 0 # Store zero in variable m.\n u = 0 # Store zero in variable u.\n log(len(xx), logr,\n name='len(xx)' + lognm) # Log the number of items in xx if logr is True with the name: 'len(\n # xx)'.\n log('LOOP U', logr, name=lognm) # Log 'LOOP U' if logr is True.\n while u < len(xx): # While u is under the number of items in xx...\n if u == b[m][0]: # ...,if u is the same as 0 of m of b then...\n o = ','.join(\n xx[\n u:b[m][1]]) # ...join u to 1 of m of b of with commas and then store it in\n # variable o.\n o = o.strip()[1:-1]\n log(o, logr,\n name='o (True)' + lognm) # Log variable o if logr is True with the name: 'o (True)'.\n u = b[m][1] # Store 1 of m of b in variable u.\n log(u, logr,\n name='u (True)' + lognm) # Log variable u if logr is True with the name: 'u (True)'.\n else: # Else...\n o = xx[u] # ...store u of xx in o.\n log(o, logr,\n name='o (False)' + lognm) # Log variable o if logr is True with the name: 'o (False)'.\n u += 1\n log(u, logr,\n name='u (False)' + lognm) # Log variable u if logr is True with the name: 'u (False)'.\n p.append(o.strip()) # Append o with whitespace removed to p.\n log(p, logr, name='pp' + lognm) # Log variable p if logr is True with the name: 'p'.\n pp.append(p) # Append p to list pp.\n log(pp, logr, name='pp' + lognm) # Log variable pp if logr is True with the name: 'pp'.\n old = len(pp[0]) # Store the number of items in 0 of pp in old.\n log('LOOP H', logr, name=lognm) # Log 'LOOP H' if logr is True.\n for h in range(len(pp)): # While h is in the range of the number of items in pp...\n new = len(pp[h]) # ...store the number of items in h of pp in variable new.\n log(old, logr, name='old' + lognm) # Log variable old if logr is True with the name: 'old'.\n log(new, logr, name='new' + lognm) # Log variable new if logr is True with the name: 'new'.\n if old == new: # If old is the same as new...\n old = new # Store new in old.\n else: # Else...\n return error(name, '04_FORMATERROR',\n 'Not formatted correctly according to CSV format.') # ...return a custom error.\n log(pp, logr, name='pp' + lognm) # Log variable pp if logr is True with the name: 'pp'.\n keys = [] # Store an empty list in keys.\n csvfile = [] # Store an empty list in csvfile.\n log('LOOP G', logr, name=lognm) # Log 'LOOP G' if logr is True.\n q = 0\n for g in range(len(pp[0])): # While g is in the range of the number of items in 0 of pp...\n if header: # ...if header is true then...\n keys.append(pp[0][g]) # ...append g of 0 of pp to keys.\n else: # Else...\n keys.append(g) # ...append g to keys.\n if header:\n q = 0\n log(keys, logr, name='keys' + lognm) # Log variable keys if logr is True with the name: 'keys'.\n log(header, logr, name='header' + lognm) # Log variable header if logr is True with the name: 'header'.\n log('LOOP Q', logr, name=lognm) # Log 'LOOP Q' if logr is True.\n while q < len(pp): # While q is under the number of items in pp...\n b = {} # ..store an empty dictionary in b.\n for j in range(len(pp[q])): # While j is in the range of the number of q of pp...\n b[keys[j]] = pp[q][j] # ...store j of q of pp in j of keys, of b.\n csvfile.append(b) # Append b to csvfile.\n q += 1 # Add one to q.\n log(csvfile, logr,\n name='csvfile' + lognm) # Log variable csvfile if logr is True with the name: 'csvfile'.\n return csvfile # Return variable csvfile.\n else: # Else...\n return error(name, '05_EXTENSION', 'The file does not have a .csv extension.') # ...return a custom error.\n\n\ndef find_csv_record(filename, key_value, **opt):\n # This function finds the row which key is the key_value specified.\n # This function has the parameters: filename, key_value and an optional parameter, 'key'.\n csvfile = read_csv(filename, True)\n # Call read_csv with its filename parameter as this own function's filename paramter and header parameter with True.\n if not isinstance(csvfile, list):\n if csvfile.startswith('!ERROR'):\n return csvfile\n if 'key' in opt:\n keyy = opt['key']\n else:\n keyy = 'key'\n # If there is the optional parameter, 'key', is present then store the value of the parameter in variable keyy\n # otherwise store 'key'.\n for l in range(len(csvfile)):\n try:\n if csvfile[l][keyy] == str(key_value):\n if 'output' in opt:\n if opt['output'] == 'rownum':\n return int(l)\n elif opt['output'] == 'row':\n return csvfile[l]\n else:\n return error(name, '06_BADPARAM',\n 'The optional parameter, output, did not have or had an incorrect value.')\n else:\n return csvfile[l]\n # If row, l, and field, keyy, is the same as the parameter, key_value.\n else:\n return error(name, '06.5_NOTFOUND', 'Could not find paramter.')\n except IndexError:\n return error(name,\n '07_NOKEY',\n 'CSV not formatted correctly to be used by this program.\\nThere must be header and header '\n 'must have a key field to use.')\n # If there is an IndexError than return a custom error.\n\n\ndef write_csv_record(filename, inside):\n with open(filename, 'w') as f: # opens filename with write permissions\n try: # tries the following\n old = len(inside[0]) # make variable old the number of fields in inside[0]\n for d in range(len(inside)): # loops while number d is in the number of items in inside.\n if isinstance(inside[d], list): # checks if d of inside is a list\n new = len(inside[d]) # makes new the number of items in d of inside\n if old == new: # checks if old is the same as new\n tmp = [] # creates tmp list\n for n in range(len(inside[d])): # loops while n is in the number of items in d of inside\n if ',' in str(inside[d][n]):\n tmp.append('\\\"' + str(inside[d][n]) + '\\\"') # appends string form of n of d of inside\n else:\n tmp.append(str(inside[d][n])) # appends string form of n of d of inside\n f.write(', '.join(\n tmp) + '\\n') # joins together items in tmp with comma and writes it to the file. Adds a\n # new line after.\n else: # else returns error\n return error(name,\n '08_NUMBEROFLINES',\n 'Lines do not have same number of fields. (The file may be incomplete or '\n 'corrupted.)')\n else: # else returns error\n return error(name,\n '09_NOLIST',\n 'Parameters other than filename should be lists. (The file may be incomplete or '\n 'corrupted.)')\n except IndexError: # if there is an index error closes file and returns error\n f.close()\n return error(name, '10_BADPARAM',\n 'Parameters were incorrectly inputted. (The file may be incomplete or corrupted.)')\n f.close() # closes file\n\n\ndef update_csv_record(filename, header, row, field, new_value):\n # This function updates a specific value in the csv file with new value sepcified in new_value.\n csvfile = read_csv(filename, header)\n # Call read_csv with its filename parameter as this own function's filename paramter and header parameter with\n # this own functions's parameter, header.\n if not isinstance(csvfile, list):\n if csvfile.startswith('!ERROR'):\n return csvfile\n try:\n try:\n csvfile[row][field] = str(new_value)\n except TypeError:\n return error(name, '010.5_NOTSTR', 'Row cannot be a str.')\n # Tries to value in the specified row and field with the new_value.\n except IndexError:\n return error(name, '11_PARAMPROB', 'Row and field are not found in file.')\n # If it returns an IndexError than output a custom error.\n if ',' in str(new_value):\n csvfile[row][field] = str('\\\"' + str(new_value) + '\\\"')\n newfile = []\n log(newfile, logr, name='newfile')\n # Variable newfile is initialised with the first row (header row) of csvfile joined together with commas.\n for l in range(len(csvfile)):\n ll = ','.join(csvfile[l])\n ll = ll.split(',')\n pp = []\n for g in range(len(ll)):\n pp.append(csvfile[l][ll[g]])\n newfile.append(pp)\n # For every line turn the dictionary into a list and append it to newfile.\n write_csv_record(filename, newfile)\n\n\ndef append_csv_record(filename, listt):\n if isinstance(listt, list): # checks if listt is a list\n csvfile = read_csv(filename, False) # reads filename with no headers and outputs into csvfile\n try:\n if len(listt) == len(csvfile[\n 0]): # checks if the number of items in listt is the same as the number of\n # items in 0 of csvfile.\n with open(filename, 'a') as f: # opens filename\n tmp = []\n for n in range(len(listt)):\n if ',' in str(listt[n]):\n tmp.append('\\\"' + str(listt[n]) + '\\\"')\n else:\n tmp.append(str(listt[n]))\n f.write(', '.join(tmp) + '\\n')\n f.close()\n else: # else returns error\n return error(name,\n '12_BADNEWROW',\n 'CSV file will not be formatted correctly with this new row. (The number of fields in '\n 'input '\n 'is not the same as file inputted)')\n except IndexError:\n if csvfile.startswith('!ERROR'):\n return csvfile\n else:\n error(name, '12.5', 'There wasn\\'nt an error and there was not a list. Confused.')\n else: # else returns error\n return error(name, '13_NOLIST', 'Parameter list is not a list. (it should be)')\n\n\ndef insert_csv_record(filename, listt, index):\n if isinstance(listt, list): # checks if listt is a list\n data = read_csv(filename, False) # reads file and outputs into data\n try:\n if len(listt) == len(data[\n 0]): # checks if the number of items in listt is the same as the number of\n # items in 0 of data.\n listdata = [] # creates empty list, listdata\n for i in range(len(data)): # while i is in the number of items in data\n tmpitem = [] # creates emptyl list, tmpitem\n for n in range(len(data[i])): # while n is in the number of items in i of data\n tmpitem.append(data[i][n]) # appends to tmpitem n of i of data\n listdata.append(tmpitem) # appends tmpitem to listdata\n tmp = []\n for n in range(len(listt)):\n if ',' in str(listt[n]):\n tmp.append('\\\"' + str(listt[n]) + '\\\"')\n else:\n tmp.append(str(listt[n]))\n listdata.insert(int(index), tmp) # inserts listt at index into listdata\n for b in range(len(listdata)): # while b is in the number of items in listdata\n if not len(listdata[b]) == len(\n listdata[0 - (len(listdata) - b)]): # checks if the number of items in b of\n # listdata is not equal to the number of items in (0 - len(listdata) - b) of listdata). Also\n # returns error after\n return error(name, '14_INCORRECT',\n 'New line does not have the same amount of fields as other lines.')\n write_csv_record(filename, listdata) # if no errors are returned then overwrites listdata to filename\n else: # else returns error\n return error(name,\n '12_BADNEWROW',\n 'CSV file will not be formatted correctly with this new row. (The number of fields in '\n 'input '\n 'is not the same as file inputted)')\n except IndexError:\n if data.startswith('!ERROR'):\n return data\n else:\n error(name, '12.5', 'There wasn\\'nt an error and there was not a list. Confused.')\n else:\n return error(name, '14.5_NOLIST', 'Parameter list is not a list. (it should be)')\n\n\ndef run():\n print('MAINLINE')\n thefile = 'testdata/08_SamitShaikh_updatedfile.csv'\n update_csv_record(thefile, True, find_csv_record(thefile, 1, key='ID', output='rownum'), 'SEM1', 87)\n update_csv_record(thefile, True, find_csv_record(thefile, 'Chris', key='GNAME', output='rownum'), 'GNAME',\n 'Christopher')\n append_csv_record(thefile, [4, 'Humpty', 'Dumpty', 0, 35, 35, 'D', 'Started Late'])\n print(read_csv(thefile, True))\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"_19_InterpreterForCSV.py","file_name":"_19_InterpreterForCSV.py","file_ext":"py","file_size_in_byte":21644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"54091785","text":"import pandas as pd\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom utils import getAmountByColumn\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 6:\n print(sys.argv[0], \"DEPTH-FILE MAPPING-FILE NOUNS MAX-DEPTHS PLOT\")\n sys.exit()\n \n df = pd.merge(pd.read_csv(sys.argv[1], ','), pd.read_csv(sys.argv[2], ','), \"inner\", \"category\")\n df = df.drop(\"category\", axis=1)\n\n df = pd.merge(df, pd.read_json(sys.argv[3], \"columns\"), \"inner\", \"page_title\")\n\n df = df[df[\"depth\"] <= int(sys.argv[4])]\n\n df = df.drop(\"depth\", axis=1)\n df = df.drop_duplicates(subset=[\"page_title\"])\n\n df = getAmountByColumn(df, \"nouns\").tail(20)\n plot = df.plot(kind=\"barh\", title=\"Noun frequency\", legend=False, rot=0, color=[plt.cm.tab20(np.append(np.arange(1, df.size, 2), np.arange(0, df.size, 2)))])\n plot.set_xlabel(\"Frequency\")\n plot.set_ylabel(\"Noun\")\n\n plot.get_figure().savefig(sys.argv[5], bbox_inches='tight')\n","sub_path":"analyzing/nounFrequency.py","file_name":"nounFrequency.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"637593043","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: .\\src\\utils\\uploader.py\n# Compiled at: 2019-10-17 11:50:46\n# Size of source mod 2**32: 1623 bytes\n\"\"\"Uploader for google drive\"\"\"\nimport os, logging\nlogger = logging.getLogger('UPLOADER')\ntry:\n from pydrive.auth import GoogleAuth\n from pydrive.drive import GoogleDrive\nexcept Exception:\n logger.error('`pydrive` was not setup properly')\n\ndef upload(file_path):\n try:\n gauth = GoogleAuth()\n gauth.LoadCredentialsFile('mycreds.txt')\n if gauth.credentials is None:\n gauth.LocalWebserverAuth()\n else:\n if gauth.access_token_expired:\n gauth.Refresh()\n else:\n gauth.Authorize()\n gauth.SaveCredentialsFile('mycreds.txt')\n drive = GoogleDrive(gauth)\n folder_id = '118iN1jzavVV-9flrLPZo7DOi0cuxrQ5F'\n filename_w_ext = os.path.basename(file_path)\n filename, file_extension = os.path.splitext(filename_w_ext)\n f = drive.CreateFile({'parents': [{'kind':'drive#fileLink', 'id':folder_id}]})\n f['title'] = filename_w_ext\n f.SetContentFile(file_path)\n f.Upload()\n logger.info(f['id'])\n return f['id']\n except Exception:\n logger.exception('Failed to upload %s', file_path)","sub_path":"pycfiles/lightnovel_crawler-2.20.0-py3-none-any/uploader.cpython-37.py","file_name":"uploader.cpython-37.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"162322830","text":"import urllib3,json,conf\n\nhttp=urllib3.PoolManager()\n\nurl=\"http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s\" \\\n % (conf.CHANNEL_ID,conf.READ_KEY)\n\ndef main():\n conn =http.request('GET',url)\n response = conn.data.decode('utf8')\n data=json.loads(response)\n print(data['field1'])\n print(data['field2'])\n conn.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"read_from_thingspeak.py","file_name":"read_from_thingspeak.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"365478931","text":"import logging\n\nBLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)\n\nRESET_SEQ = \"\\033[0m\"\nCOLOR_SEQ = \"\\033[1;%dm\"\nBOLD_SEQ = \"\\033[1m\"\n\nCOLORS = {\n 'WARNING': YELLOW,\n 'INFO': WHITE,\n 'DEBUG': BLUE,\n 'CRITICAL': YELLOW,\n 'ERROR': RED\n}\n\n\ndef to_ansi_format(msg, use_color=True):\n if use_color:\n msg = msg.replace(\"$RESET\", RESET_SEQ)\n msg = msg.replace(\"$BOLD\", BOLD_SEQ)\n else:\n msg = msg.replace(\"$RESET\", \"\").replace(\"$BOLD\", \"\")\n return msg\n\n\nclass ColoredFormatter(logging.Formatter):\n\n def __init__(self, msg):\n logging.Formatter.__init__(self, msg)\n\n def format(self, record):\n levelname = record.levelname\n if levelname in COLORS:\n levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname\n levelname_color = levelname_color + RESET_SEQ\n record.levelname = levelname_color\n return logging.Formatter.format(self, record)\n\n\ndef add_stdout_handler(log):\n fmt = '$BOLD%(name)s$RESET - %(levelname)s - $BOLD%(filename)s'\n fmt = fmt + '$RESET:%(lineno)d - %(message)s'\n fmt = to_ansi_format(fmt, True)\n sh = logging.StreamHandler()\n color_formatter = ColoredFormatter(fmt)\n sh.setLevel(logging.WARNING)\n sh.setFormatter(color_formatter)\n log.addHandler(sh)\n\n\ndef add_file_handler(log):\n fmt = '%(asctime)s - $BOLD%(name)s$RESET - %(levelname)s - $BOLD'\n fmt = fmt + '%(filename)s$RESET:%(lineno)d - %(message)s'\n fmt = to_ansi_format(fmt, True)\n fh = logging.FileHandler('log')\n fh.setLevel(logging.DEBUG)\n formatter = logging.Formatter(fmt)\n fh.setFormatter(formatter)\n log.addHandler(fh)\n\n\ndef init(name='main', path='./log', safe_mode=False):\n welcome_msg = '{:#^40s}'.format(' NEW LOG SESSION ')\n log = logging.getLogger(name)\n log.setLevel(logging.DEBUG)\n if safe_mode:\n log.debug(welcome_msg)\n return log\n add_stdout_handler(log)\n add_file_handler(log)\n log.debug(welcome_msg)\n return log\n","sub_path":"log_setup/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"440043984","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/bullseye/special_sums.py\n# Compiled at: 2012-03-02 05:34:47\nimport numpy as np\n\ndef angle_sum(m, angle, aspect=1.0, binsize=None):\n r\"\"\"Compute the sum of a 2D array along an rotated axis.\n\n Parameters\n ----------\n m : array_like, shape(N, M)\n 2D input array to be summed\n angle : float\n The angle of the summation direction defined such that:\n angle_sum(m, angle=0) == np.sum(m, axis=0)\n angle_sum(m, angle=np.pi/2) == np.sum(m, axis=1)\n aspect : float, optional\n The input bin aspect ratio (second dimension/first dimension).\n binsize : float, optional\n The output bin size in units of the first input dimension step\n size. If no binsize is given, it defaults to the \"natural bin\n size\" which is the larger projection of the two input step sizes\n onto the output dimension (the axis perpendicular to the\n summation axis).\n\n Returns\n -------\n out : ndarray, shape(K)\n The sum of `m` along the axis at `angle`.\n\n See also\n --------\n polar_sum : similar method summing azimuthally or radially\n\n Notes\n -----\n The summation angle is relative to the first dimension.\n\n For 0<=angle<=pi/2 the value at [0,0] ends up in the first bin and\n the value at [-1,-1] ends up in the last bin. Up to rounding, the\n center value will always end up in the center bin.\n\n For angle=3/4*pi the summation is along the diagonal.\n For angle=3/4*pi the summation is along the antidiagonal.\n \n The origin of the rotation is the [0,0] index. This determines the\n bin rounding.\n\n Up to index flipping, limits, rounding, offset and the definition of\n `angle` the output `o` is:\n\n .. math::\n o_k = \\sum_l m_{i,j/a}, where\n i(l,k) = \\cos(\\alpha) l - \\sin(\\alpha) k\n j(l,k) = \\sin(\\alpha) l + \\cos(\\alpha) k\n\n There is no interpolation and artefacts are likely if this function\n is interpreted as an image processing function.\n\n The full array sum is always strictly conserved:\n angle_sum(m, t).sum() == m.sum()\n\n The function uses floor(coordinate+.5) to bin (c.f. around, rint,\n trunc).\n\n Examples\n --------\n >>> m = np.arange(9.).reshape((3, 3))\n >>> np.all(angle_sum(m, 0) == m.sum(axis=0))\n True\n >>> np.all(angle_sum(m, np.pi/2) == m.sum(axis=1))\n True\n >>> np.all(angle_sum(m, np.pi) == m.sum(axis=0)[::-1])\n True\n >>> np.all(angle_sum(m, 3*np.pi/2) == m.sum(axis=1)[::-1])\n True\n >>> np.all(angle_sum(m, 2*np.pi) == m.sum(axis=0))\n True\n >>> np.all(angle_sum(m, -np.pi/2) == \n ... angle_sum(m, 3*np.pi/2))\n True\n >>> d1 = np.array([0, 4, 12, 12, 8]) # antidiagonal\n >>> d2 = np.array([2, 6, 12, 10, 6]) # diagonal\n >>> np.all(angle_sum(m, np.pi/4) == d1)\n True\n >>> np.all(angle_sum(m, 3*np.pi/4) == d2)\n True\n >>> np.all(angle_sum(m, 5*np.pi/4) == d1[::-1])\n True\n >>> np.all(angle_sum(m, 7*np.pi/4) == d2[::-1])\n True\n >>> np.all(angle_sum(m, 0, aspect=2, binsize=1) == \n ... np.array([9, 0, 12, 0, 15]))\n True\n >>> np.all(angle_sum(m, 0, aspect=.5, binsize=1) == \n ... np.array([9, 12+15]))\n True\n >>> np.all(angle_sum(m, 0, aspect=.5) == m.sum(axis=0))\n True\n >>> np.all(angle_sum(m, np.pi/2, aspect=2, binsize=1) ==\n ... m.sum(axis=1))\n True\n >>> m2 = np.arange(1e6).reshape((100, 10000))\n >>> np.all(angle_sum(m2, 0) == m2.sum(axis=0))\n True\n >>> np.all(angle_sum(m2, np.pi/2) == m2.sum(axis=1))\n True\n >>> angle_sum(m2, np.pi/4).shape\n (10099,)\n >>> angle_sum(m2, np.pi/4).sum() == m2.sum()\n True\n \"\"\"\n m = np.atleast_2d(m)\n if binsize is None:\n binsize = max(abs(np.cos(angle) * aspect), abs(np.sin(angle)))\n m = m[::-1]\n i, j = np.ogrid[:m.shape[0], :m.shape[1]]\n k = np.cos(angle) * aspect / binsize * j - np.sin(angle) / binsize * i\n cx, cy = (0, 0, -1, -1), (0, -1, 0, -1)\n km = k[(cx, cy)].min()\n k = np.floor(k - (km - 0.5)).astype(np.int)\n return np.bincount(k.ravel(), m.ravel())\n\n\ndef polar_sum(m, center, direction, aspect=1.0, binsize=None):\n \"\"\"Compute the sum of a 2D array radially or azimuthally.\n\n Parameters\n ----------\n m : array_like, shape(N, M)\n 2D input array to be summed\n center : tuple(float, float)\n The center of the summation measured from the [0, 0] index\n in units of the two input step sizes.\n direction : \"radial\" or \"azimuthal\"\n Summation direction.\n aspect : float, optional\n The input bin aspect ratio (second dimension/first dimension).\n binsize : int, optional\n The output bin size. If None is given, and direction=\"radial\"\n then binsize=2*pi/100, else binsize=min(1, aspect).\n\n Returns\n -------\n out : ndarray, shape(K)\n The radial or azimuthal sum of `m`.\n\n See also\n --------\n angle_sum : similar method summing along angled parallel lines\n\n Notes\n -----\n The index of `out` is the floor()-binned radius or the floor()\n binned angle, both according to `binsize`.\n\n Angles are measured from the positive second index axis towards the\n negative first index axis. They correspond to mathematically\n positive angles in the index coordinates of m[::-1] -- or the [0, 0]\n index in the lower left.\n\n If direction=\"azimuthal\" then the length of the output is determined\n by the maximal distance to the center. The radius-bins are [0, binsize),\n [binsize, 2*binsize), ... up to [r, r+binsize) for\n some value r with max_radius-binsize <= r < max_radius.\n \n If direction=\"radial\" the length is always 2*pi/binsize. This is not\n the same as arctan2(i, j) which would distinguish +pi and -pi!\n The azimuthal bins are therefore [-pi, -pi+binsize),\n [-pi+binsize, 2*binsize), ... up to [p-binsize, p) for some p with \n pi-binsize <= p < pi. The values at +pi end up in the first bin.\n See arctan2() for the definition of the behaviour other special\n cases.\n\n There is no interpolation and artefacts are likely if this function\n is interpreted as an image processing function.\n\n The full array sum is always strictly conserved:\n polar_sum(m, ...).sum() == m.sum()\n\n The function uses (coordinate).astype(np.int) to bin.\n\n Examples\n --------\n >>> m = np.arange(1., 10.).reshape((3, 3))\n >>> polar_sum(m, (0, 0), \"radial\").sum() == m.sum()\n True\n >>> polar_sum(m, (0, 0), \"azimuthal\").sum() == m.sum()\n True\n >>> polar_sum(m, (1, 1), \"radial\").sum() == m.sum()\n True\n >>> polar_sum(m, (1, 1), \"azimuthal\").sum() == m.sum()\n True\n >>> polar_sum(m, (1, 1), \"radial\", binsize=np.pi/4)\n array([ 4., 1., 2., 3., 11., 9., 8., 7.])\n >>> polar_sum(m, (1, 1), \"azimuthal\", binsize=1.)\n array([ 5., 40.])\n >>> polar_sum(m, (1, 1), \"azimuthal\", binsize=2**.5/2)\n array([ 5., 20., 20.])\n >>> polar_sum(m, (.5, .5), \"azimuthal\", binsize=1)\n array([ 12., 24., 9.])\n >>> polar_sum(m, (0, 0), \"radial\", binsize=np.pi/8)\n array([ 0., 0., 0., 0., 0., 0., 0., 0., 6., 6., 22.,\n 0., 11., 0., 0., 0.])\n >>> polar_sum(m, (0, 0), \"radial\", binsize=np.pi/2)\n array([ 0., 0., 34., 11.])\n >>> m2 = np.arange(123*345).reshape((123, 345))\n >>> polar_sum(m2, (67, 89), \"radial\", binsize=2*np.pi/1011).shape[0]\n 1011\n \"\"\"\n m = np.atleast_2d(m)\n i, j = np.ogrid[:m.shape[0], :m.shape[1]]\n i, j = i - center[0], j - center[1]\n if direction == 'azimuthal':\n k = (j ** 2 * aspect ** 2 + i ** 2) ** 0.5\n if binsize is None:\n binsize = min(1.0, aspect)\n minlength = None\n elif direction == 'radial':\n k = np.arctan2(i, j * aspect) + np.pi\n if binsize is None:\n binsize = 2 * np.pi / 100\n minlength = int(2 * np.pi / binsize) + 1\n else:\n raise ValueError(\"direction needs to be 'radial' or 'azimuthal'\")\n k = (k / binsize).astype(np.int)\n r = np.bincount(k.ravel(), m.ravel(), minlength)\n if direction == 'radial':\n assert r.shape[0] == minlength, (r.shape, minlength)\n r[0] += r[(-1)]\n r = r[:-1]\n return r\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()","sub_path":"pycfiles/bullseye-0.1.1-py2.7/special_sums.py","file_name":"special_sums.py","file_ext":"py","file_size_in_byte":8488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"304981574","text":"import os.path as path\nimport sys\nfrom configparser import ConfigParser\n\n\ndef get(config, section, field):\n if section not in config:\n return None\n if field not in config[section]:\n return None\n return config[section][field]\n\n\ndef current_folder():\n return path.abspath(path.dirname(sys.argv[0]))\n\n\ndef get_config(patch='..'):\n config_file = sys.argv[1]\n config_file_abs_path = path.abspath(path.join(patch, config_file))\n\n parser = ConfigParser()\n parser.read(config_file_abs_path)\n\n return parser\n","sub_path":"libs/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"632428434","text":"import subprocess\n\ndef parseInput(inputString:str):\n inputString = inputString.lower() #lower case it all\n inputArray = inputString.split() # break line by white space into inputs[] array\n\n cmdstring = inputArray[0] # grab the first chars: (t)empcalc command\n cmd = cmdstring[0] # pluck of the first char\n\n conversionType = None\n temperatureValue = None\n if len(inputArray) > 1 :\n conversionTypeString = inputArray[1] # grab the 2nd string\n conversionType = conversionTypeString[0] # and the 1st char\n if len(inputArray) > 2 :\n temperatureValue = inputArray[2] # grab the 3rd string \n return cmd, conversionType, temperatureValue # return 3 values from a function\n\ndef main():\n print('type exit to leave')\n while True:\n userInput = input('rsh> ')\n if userInput == '' : continue # handle no input case\n cmd, convType, tempValue = parseInput(userInput) # separate the command line\n if cmd == 'e':\n print(\"goodbye!\")\n break\n elif cmd == 't': #tempcalc command \n commandline = f'python ./tempcalc.py {convType} {tempValue}'\n output = subprocess.getoutput(commandline) # getoutput() does the shell out\n print(output)\n elif cmd == 'f': # files command \n commandline = f'ls -al'\n output = subprocess.getoutput(commandline) # getoutput() does the shell out\n print(output)\n elif cmd == 'd':\n commandline = f'df -h'\n output = subprocess.getoutput(commandline)\n print(output)\n elif cmd == 'v':\n commandline = f'lsb_release -a'\n output = subprocess.getoutput(commandline)\n print(output) \n \nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n exit()","sub_path":"rayshell/rayshell.py","file_name":"rayshell.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"532094727","text":"# Copyright (C) 2013 Internet Systems Consortium.\n#\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND INTERNET SYSTEMS CONSORTIUM\n# DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL\n# INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING\n# FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,\n# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION\n# WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# Author: Wlodzimierz Wencel\n\nfrom lettuce.registry import world\n\n\ndef add_ddns_server(address, port):\n world.ddns_enable = True # flag for ddns\n world.ddns_add = \"\" # part of the config which is added to dhcp config section\n world.ddns_main = \"\"\n world.ddns_forw = []\n world.ddns_rev = []\n world.ddns_keys = []\n\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if address == \"default\":\n address = \"127.0.0.1\"\n if port == \"default\":\n port = \"53001\"\n\n world.ddns_main += ',\\n\"DhcpDdns\": {pointer_start} \"ip-address\": \"{address}\",\"dns-server-timeout\": 100,' \\\n ' \"port\": {port},'.format(**locals())\n\n add_ddns_server_options(\"server-ip\", address)\n\n\ndef add_ddns_server_options(option, value):\n pointer_start = \"{\"\n pointer_end = \"}\"\n if world.ddns_add == \"\":\n world.ddns_add += '\"dhcp-ddns\":{'\n else:\n world.ddns_add += \",\"\n if value in [\"true\", \"false\", \"True\", \"False\", \"TRUE\", \"FALSE\"]:\n world.ddns_add += '\"{option}\": {value}'.format(**locals())\n else:\n world.ddns_add += '\"{option}\": \"{value}\"'.format(**locals())\n\n\ndef add_forward_ddns(name, key_name, ip_address, port):\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if key_name == \"EMPTY_KEY\":\n world.ddns_forw.append('''{pointer_start} \"name\": \"{name}\",\n \"dns-servers\": [ {pointer_start}\n \"ip-address\": \"{ip_address}\",\n \"port\": {port} {pointer_end}\n ]\n {pointer_end} '''.format(**locals()))\n else:\n world.ddns_forw.append('''{pointer_start} \"name\": \"{name}\", \"key-name\": \"{key_name}\",\n \"dns-servers\": [ {pointer_start}\n \"ip-address\": \"{ip_address}\",\n \"port\": {port} {pointer_end}\n ]\n {pointer_end} '''.format(**locals()))\n\n\ndef add_reverse_ddns(name, key_name, ip_address, port):\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n if key_name == \"EMPTY_KEY\":\n world.ddns_rev.append('''{pointer_start} \"name\": \"{name}\",\n \"dns-servers\": [ {pointer_start}\n \"ip-address\": \"{ip_address}\",\n \"port\": {port} {pointer_end}\n ]\n {pointer_end} '''.format(**locals()))\n else:\n world.ddns_rev.append('''{pointer_start} \"name\": \"{name}\", \"key-name\": \"{key_name}\",\n \"dns-servers\": [ {pointer_start}\n \"ip-address\": \"{ip_address}\",\n \"port\": {port} {pointer_end}\n ]\n {pointer_end} '''.format(**locals()))\n\n\ndef add_keys(secret, name, algorithm):\n pointer_start = \"{\"\n pointer_end = \"}\"\n\n world.ddns_keys.append('''\n {pointer_start}\n \"secret\": \"{secret}\",\n \"name\": \"{name}\",\n \"algorithm\": \"{algorithm}\"\n {pointer_end}'''.format(**locals()))\n\n\ndef build_ddns_config():\n # TODO multiple domains - now that configuration allow to make one of each\n world.ddns = world.ddns_main\n world.ddns += ' \"reverse-ddns\": {'\n for each in world.ddns_rev:\n world.ddns += '\"ddns-domains\": [' + each + ']'\n world.ddns += '}'\n world.ddns += ' ,\"forward-ddns\": {'\n for each in world.ddns_forw:\n world.ddns += '\"ddns-domains\": [' + each + ']'\n world.ddns += '}'\n world.ddns += ',\"tsig-keys\": ['\n if len(world.ddns_keys) > 0:\n world.ddns += world.ddns_keys[0]\n for each in world.ddns_keys[1:]:\n world.ddns += ',' + each\n world.ddns += ']'\n world.ddns += '}'","sub_path":"lettuce/features/softwaresupport/kea6_server/functions_ddns.py","file_name":"functions_ddns.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"259920530","text":"import yaml\ndef read_yaml(file='../config/work.yaml'):\n with open(file,'r') as fs :\n rs = yaml.load(fs,Loader=yaml.FullLoader)\n return rs\n\n\nif __name__ == '__main__':\n res = read_yaml()\n print(type(res),res)","sub_path":"study_work/read_yaml.py","file_name":"read_yaml.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"444240122","text":"from PIL import Image\n\ndef grayScaleTransform(img):\n grayScaleImage = img.convert('L')\n grayScaleImage.save('grayscale.jpg')\n return grayScaleImage\n\ndef negativeTransform(img):\n mode = img.mode\n width, height = img.size\n if mode == 'L':\n newImage = Image.new('L', (width, height))\n else:\n newImage = Image.new('RGB', (width, height))\n for i in range(width):\n for j in range(height):\n pixels = img.getpixel((i, j))\n if mode == 'L':\n newPixels = 255 - pixels\n else:\n red = 255 - pixels[0]\n green = 255 - pixels[1]\n blue = 255 - pixels[2]\n newPixels = (red, green, blue)\n newImage.putpixel((i, j), newPixels)\n newImage.save('negative_transform.jpg')\n return newImage\n\ndef powerLawTransformation(img):\n mode = img.mode\n width, height = img.size\n gamma = float(input('Input gamma value: '))\n if mode == 'L':\n newImage = Image.new('L', (width, height))\n else:\n newImage = Image.new('RGB', (width, height))\n for i in range(width):\n for j in range(height):\n pixels = img.getpixel((i, j))\n if mode == 'L':\n newPixels = int(255 * (pixels / 255) ** gamma)\n else:\n red = int(255 * (pixels[0] / 255) ** gamma)\n green = int(255 * (pixels[1] / 255) ** gamma)\n blue = int(255 * (pixels[2] / 255) ** gamma)\n newPixels = (red, green, blue)\n newImage.putpixel((i, j), newPixels)\n newImage.save('power_law_transformation.jpg')\n return newImage\n\ndef main():\n img = Image.open('input.jpg')\n # img = grayScaleTransform(img)\n # negativeTransform(img)\n powerLawTransformation(img)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Gray Level Transformation/gray_level_transformation.py","file_name":"gray_level_transformation.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"215655359","text":"from config import active_config\nimport json\n\n\ndef get_old():\n try:\n f = open(active_config['data_file'], 'rb')\n ret = json.loads(f.read().decode('utf8'))\n f.close()\n return ret\n except:\n print(\"No file\")\n return False\n\n\ndef cache_dump(cache):\n with open(\"cache_dump.json\", 'wb') as f:\n f.write(json.dumps(cache, ensure_ascii=False, indent=2).encode('utf8'))\n\n\ndef write(ob, name):\n if name:\n return _write_one(ob, name)\n else:\n return _write_all(ob)\n\n\ndef _write_one(ob, name):\n _write_all(ob)\n\n\ndef _write_all(ob):\n f = open(active_config['data_file'], 'wb')\n f.write(json.dumps(ob, ensure_ascii=False, indent=2).encode('utf8'))\n f.close()\n","sub_path":"db_update.py","file_name":"db_update.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"627144687","text":"import random\nimport urllib.request\nimport socket\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nfrom python_anticaptcha import AnticaptchaClient, NoCaptchaTaskProxylessTask\nfrom datetime import datetime, timedelta\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.firefox.options import Options\nfrom base64 import b64encode\nfrom selenium.webdriver.firefox.webdriver import FirefoxProfile\nfrom itertools import groupby\nimport re\nimport json\n\ndirectory = os.getcwd()\n\n# функция проверки интернета\ndef check_internet( address ):\n\n internet = 0\n while internet == 0:\n try:\n socket.gethostbyaddr('www.google.com')\n except:\n internet = 0\n print('Интернета нет, жду 1 минуту и повторю попытку..')\n sleep(60)\n else:\n internet = 1\n driver.get( address )\n\n# Первоначальная проверка интернета\ninternet = 0\nwhile internet == 0:\n try:\n socket.gethostbyaddr('www.google.com')\n except:\n internet = 0\n print('Интернета нет, жду 1 минуту и повторю попытку..')\n sleep(60)\n else:\n internet = 1\n\nlink = str(urllib.request.urlopen('https://twitter.com/vivex10').read() )\nif 'topscan-off' in link:\n\tpass\nelse:\n print('Вас приветствует спам программа TOPSCAN v1.0 by Miron!\\n')\n\n #Настройки драйвера\n options = Options()\n profile = FirefoxProfile( directory + '\\\\data\\\\Program Files\\\\profile' )\n binary = FirefoxBinary( directory + '\\\\data\\\\Program Files\\\\FirefoxPortable64-60.0.1\\\\FirefoxPortable64\\\\App\\\\Firefox\\\\firefox.exe' )\n driver = Firefox( executable_path = directory + '\\\\data\\\\Program Files\\\\driver\\\\geckodriver64.exe', firefox_binary=binary, firefox_profile=profile, options = options, log_path = directory + '\\\\data\\\\Program Files\\\\driver\\\\log.log')\n driver.set_page_load_timeout(10)\n\n spisok = []\n base = json.load( open( directory + '\\\\data.json' , encoding='utf8') )\n\n FIN = '🔥 **' + datetime.strftime(datetime.now(), \"%d\") + ' ИЮЛЯ** 🔥' + Keys.SHIFT + Keys.ENTER + Keys.SHIFT + Keys.ENTER + Keys.SHIFT + Keys.ENTER + '**TRUDBOX.COM.UA**' + Keys.SHIFT + Keys.ENTER + Keys.SHIFT + Keys.ENTER\n\n print('Захожу на трудбокс')\n\n pn = 0\n try:\n driver.get( 'http://trudbox.com.ua/kiev/jobs-eskort' )\n except:\n driver.stop_client()\n \n print('Скролю вниз 7 раз')\n\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n driver.execute_script('window.scrollBy(1, 999999)') \n sleep(1)\n\n print('Закрываю баннер ')\n\n # Закрыть всплывающий баннер\n try:\n driver_element = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[4]/button')))\n driver_element.click()\n except:\n pass\n\n posts = driver.find_elements_by_link_text('Полное описание')#.get_attribute('href')\n \n finlist = []\n\n print('Собираю ссылки')\n\n # Получить ссылки\n for post in posts:\n mas_number = ''\n finlist.append( post.get_attribute('href') )\n \n col_top = 0\n pn = 0\n\n\n print('Обхожу ссылки')\n\n # Обойти все объявления\n for sylka in finlist:\n\n if pn >= 20:\n break\n\n try:\n driver.get( sylka )\n except:\n driver.stop_client()\n\n # получить заголовок\n title = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div/div[1]')\n title = title.text\n\n\n if 'эскорт' in title.lower():\n try:\n # 1 вариант\n mas_text = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div/div[4]/div[2]/div[2]')\n except:\n # 2 вариант\n mas_text = driver.find_element_by_xpath('/html/body/div[1]/div[2]/div[2]/div/div[5]/div[2]/div[2]')\n \n \n mas_text = mas_text.text\n\n mas_number = re.findall('(\\d+)', mas_text)\n \n fin_mas_number = ''\n # обработать числа\n for item in mas_number:\n fin_mas_number += item\n\n for number, name in base.items():\n check_found = 0\n if number[3:] in fin_mas_number:\n pn += 1\n FIN += Keys.SHIFT + Keys.ENTER + '`{poradkovy_nomer} место:` {office}, {admin}'.format( poradkovy_nomer=str(pn), office=name[0], admin=name[1] ) + Keys.SHIFT + Keys.ENTER\n print('Обработал ' + str(pn) + ' страни��у!')\n check_found = 1\n break\n if check_found == 0:\n pn += 1\n FIN += Keys.SHIFT + Keys.ENTER + '`{poradkovy_nomer} место:` Объявление без номера!'.format( poradkovy_nomer=str(pn) ) + Keys.SHIFT + Keys.ENTER\n print('Обработал ' + str(pn) + ' страницу!')\n \n \n \n print('Захожу в телеграм!')\n try:\n driver.get('https://web.telegram.org/#/im?p=@topeskort')\n except:\n driver.stop_client() \n\n sleep(5)\n\n print('Ввожу')\n\n # Ввести сообщение\n driver.find_element_by_class_name('composer_rich_textarea').send_keys( FIN )\n\n sleep(2)\n\n try:\n driver.find_element_by_xpath('/html/body/div[1]/div[2]/div/div[2]/div[3]/div/div[3]/div[2]/div/div/div/form/div[3]/button').click\n except:\n pass\n\n\n print('Отправил!')\n\n\ndriver.close()","sub_path":"Topscan/topscan.py","file_name":"topscan.py","file_ext":"py","file_size_in_byte":7546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"37852437","text":"# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as part of\n# this distribution.\n#--\n\nfrom datetime import date, timedelta\n\nfrom kansha.cardextension.tests import CardExtensionTestCase\n\nfrom .comp import CardLabels\n\n\nclass CardLabelsTest(CardExtensionTestCase):\n def create_instance(self, card, action_log, configurator):\n return CardLabels(card, action_log, configurator)\n\n def test_activate(self):\n self.assertTrue(self.extension.get_available_labels() > 0)\n self.assertEqual(len(self.extension.labels), 0)\n label_id = self.extension.get_available_labels()[0].id\n self.extension.activate(label_id)\n self.assertIn(label_id, self.extension.labels)\n self.extension.activate(label_id)\n self.assertNotIn(label_id, self.extension.labels)\n\n def test_copy(self):\n label_ids = [self.extension.get_available_labels()[index].id for index in xrange(2)]\n for label_id in label_ids:\n self.extension.activate(label_id)\n cpy = self.extension.copy(self.card_copy, {'labels': self.extension.get_available_labels()})\n for label_id in label_ids:\n self.assertIn(label_id, cpy.labels)\n","sub_path":"kansha/card_addons/label/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"266461476","text":"#----------------------------------------------------------------------\n# Directory File Copy\n# Author: Lukas Mallory\n# Date: 09/12/2018\n#\n# Description: Copies files from a target directory\n# to a destination directory. Calls checkMD before copying.\n#---------------------------------------------------------------------\n\nfrom .. import settings\nimport os, shutil\n\n\ndef fileCopy(srcDir, destDir):\n for root, dirs, files in os.walk(srcDir):\n for file in files:\n fullFilePath = os.path.join(root , file)\n if os.path.isfile(fullFilePath):\n settings.LOG(fullFilePath + \" 1\")\n path = os.path.dirname(fullFilePath)\n path = path.replace(\"Markdown\" , '')\n shutil.copytree(srcDir, destDir)\n return True\n\n# Ricky Dall'Armellina\n# 10/02/2018\n# Adding delete .md files from selcted folder\ndef deleteMD(folder):\n settings.LOG(\"Selected directory: \" + folder)\n # loop through files and directories and remove markdown files from it\n for root, dirs, files in os.walk(folder):\n for fileName in files:\n if fileName.endswith(\".md\"):\n try:\n settings.LOG(\"Removing markdown file directory\")\n os.remove(os.path.join(root, fileName))\n except:\n print(\"An error occured while removing markdown files\")\n return False\n return True","sub_path":"Flock (Windows)/src/copier/fileCopy.py","file_name":"fileCopy.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"579863275","text":"import json\nimport requests\nimport tempfile\nimport urllib.parse\n\nfrom coworks.config import LocalConfig\nfrom coworks.tech.jinja import JinjaRenderMicroService\n\n\nclass TestClass:\n\n def test_render_template_in_url(self, local_server_factory):\n local_server = local_server_factory(JinjaRenderMicroService(configs=LocalConfig()))\n template = urllib.parse.quote_plus(\"hello {{ world_name }}\")\n response = local_server.make_call(requests.get, f\"/render/{template}\", params={'world_name': 'world'})\n assert response.status_code == 200\n assert response.json() == {\"render\": \"hello [\\'world\\']\"}\n\n def test_render_template_multipart_form(self, local_server_factory):\n local_server = local_server_factory(JinjaRenderMicroService(configs=LocalConfig()))\n\n template = tempfile.TemporaryFile()\n template.write(\"hello {{ world_name }}\".encode())\n template.seek(0)\n\n context = tempfile.TemporaryFile()\n context.write(json.dumps({\"world_name\": \"the world\"}).encode())\n context.seek(0)\n\n response = local_server.make_call(requests.post, \"/render/template.jinja\",\n files={'templates': ('template.jinja', template, 'text/plain'),\n 'context': (None, context, 'application/json')})\n assert response.status_code == 200\n assert response.json() == {\"render\": \"hello the world\"}\n","sub_path":"tests/coworks/tech/test_jinja.py","file_name":"test_jinja.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"141948938","text":"import argparse\nimport os\n\n#Parameters to pass into this script\nparser = argparse.ArgumentParser(description=\"Inputs needed to run the phrase searching Python program\")\nparser.add_argument('--phrase', '-p', action='store', dest='phrase', help=\"Phrase to find\", required=True)\nparser.add_argument('--dir', '-d', action='store', dest='dir', help='Directory to search', required=True)\nargs = parser.parse_args()\n\nprint(\"Welcome to Terry's Phrase Search Program\")\nprint(\"This program will be able to recursively find a phrase in a file or a directory\") \n\n\n# os.walk() can traverse through all of the subdirectories and list all of the files and directories\n# in each directory it traverses through. \n# It returns a tuple (current_directory, sub-directories in the current dir, files in current dir)\nfor _, _, files in os.walk(args.dir):\n\tfor file in files:\n\t\twith open(file) as f:\n\n\t\t\t# Use enumerate() - adds counter to an iterable and returns it. \n\t\t\t# The returned object is a enumerate object.\n\t\t\tfor linenumber, line in enumerate(f, 1):\n\t\t\t\tif args.phrase in line:\n\t\t\t\t\tprint(\"The '%s' is in file '%s' on line %d\" % (args.phrase, file, linenumber))\n\t\t\n\nprint(\"Phrase searching done.\")\n\n\n# This can be done in Shell command grep in ONE LINE!\n# grep -rnw '/path/to/somewhere/' -e 'pattern'\n\n","sub_path":"other/phrasesearch.py","file_name":"phrasesearch.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"22015985","text":"import math\ndef isPrime(x):\n temp = int(math.sqrt(x))\n for y in range(2,temp+1):\n if(x % y == 0):\n return False\n return True\n\ndef primeNumbers(lower,upper):\n answer = []\n for tmp in range(lower,upper+1):\n if(isPrime(tmp)):\n answer.append(tmp)\n print(answer)\nprimeNumbers(10,20)\nprimeNumbers(10,30)\n \n","sub_path":"q4.py","file_name":"q4.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"253950802","text":"from apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom httplib2 import Http\n\nscopes = ['https://www.googleapis.com/auth/drive']\n\ncredentials = ServiceAccountCredentials.from_json_keyfile_name('uw-mino.json', scopes)\n\nhttp_auth = credentials.authorize(Http())\ndrive = build('drive', 'v3', http=http_auth)\n\nrequest = drive.files().list().execute()\nfiles = request.get('items', [])\nfor f in files:\n print(f)\n","sub_path":"pipeline/drive-service.py","file_name":"drive-service.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"111870593","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom datetime import datetime, timedelta\nfrom django.db.models.signals import post_init, post_save\nfrom django.core.mail import mail_admins\n\ndef yeld_year():\n \"\"\"\n Helper function to get/set year for limit.\n Returns current year as int.\n \"\"\"\n return datetime.now().year\n\ndef calculate_timedelta(from_date, to_date, has_pk=None):\n \"\"\"\n Helper function to calculate how many days the vacation is.\n \"\"\"\n # https://stackoverflow.com/questions/3615375/count-number-of-days-between-dates-ignoring-weekends#3615984\n days_range = (to_date.date() - from_date.date()).days\n if days_range == 0 and has_pk == None:\n #as the real time delta is datetime.timedelta(0, 32400), set this to 1 day manually\n # after all, we can't have a vacation of 0 days.\n # Additional hack: check if instance is not new. Small updates can be for 0 days.\n # IE do not substract from Limiter\n days_range = 1\n\n #creates a generator by using generator expression\n # ( ex: sum(i*i for i in range(10)) )\n day_generator = (from_date.date() + timedelta(x + 1) \\\n for x in range(days_range))\n vacation_days = sum(1 for day in day_generator if day.weekday() <= 5)\n return vacation_days\n\ndef update_limiter(days, limiter):\n \"\"\"\n Helper function to calculate days for Vacation and update limiter\n \"\"\"\n new_days_left = limiter.days_left - days\n new_days_used = limiter.days_used + days\n\n limiter.days_left=new_days_left\n limiter.days_used=new_days_used\n #specify which fields to save\n limiter.save(update_fields=['days_left', 'days_used'])\n\n\nclass Limit(models.Model):\n \"\"\"\n Contains personal limit for vacations in days.\n NOTE: these values are managed manually by admin.\n\n ::user - Employee\n ::year - For which year the limit is about\n ::initial - Initial amount fo days.\n ::days_left - Vacation left unspent for year.\n ::days_used - Used days this year.\n \"\"\"\n user = models.ForeignKey(User,on_delete=models.CASCADE, null=True)\n year = models.PositiveSmallIntegerField(default=yeld_year)\n initial = models.PositiveSmallIntegerField()\n days_left = models.PositiveSmallIntegerField()\n days_used = models.PositiveSmallIntegerField()\n\n def __str__(self):\n return \"Limit for {0} @ {1}\".format(self.user, self.year).capitalize()\n\n\n\nclass Absence(models.Model):\n \"\"\"\n Absence model, containing absence related info.\n Vacations must be approved by admin.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Partial ovveride for __init__ method.\n Old dates are saved for comparison on AJAX update request.\n \"\"\"\n super(Absence, self).__init__(*args, **kwargs)\n self.old_from_date = self.from_date\n self.old_to_date = self.to_date\n\n VACATION = 'vacation'\n DELAY = 'delay'\n SICK = 'sick'\n HOME = 'home'\n\n TYPE_CHOICES = (\n (VACATION, 'Vacation'),\n (DELAY, 'Delay'),\n (SICK, 'Sick'),\n (HOME, 'Home Office')\n )\n\n from_date = models.DateTimeField()\n to_date = models.DateTimeField()\n type_miss = models.CharField(max_length=10, choices=TYPE_CHOICES, default=DELAY)\n approved = models.BooleanField(default=False)\n user = models.ForeignKey(User,on_delete=models.CASCADE, null=True)\n comment = models.CharField(max_length=250, blank=True, null=True)\n\n def __str__(self):\n return \"{0} {1}\".format(self.type_miss, self.pk).title()\n\n def save(self, *args, **kwargs):\n #Should check if there is a limit for that user/year\n #Update limit on save or return False if limit reached or not set\n if self.type_miss == 'vacation':\n\n #get specified year\n entered_year = self.to_date.year\n\n # calculate amount of already registered vacation days\n if self.pk != None:\n old_days = calculate_timedelta(self.old_from_date, self.old_to_date, self.pk)\n else:\n old_days = 0\n\n #calculate amount of vacation days\n days = calculate_timedelta(self.from_date, self.to_date, self.pk)\n\n # watch the increase or decrease of vacation days\n # Example: old_days = 3, days = 5\n # case increase: substract the difference from the limiter ( 5 - 3)\n # case decrease: get the difference and pass it as negative (3 - 5)\n days_difference = days - old_days\n\n #find limiter for that user\n limiters = Limit.objects \\\n .filter(year=entered_year) \\\n .filter(user__id=self.user.id)\n\n if limiters and limiters.first().days_left >= days:\n update_limiter(days_difference, limiters.first())\n super(Absence, self).save(*args, **kwargs)\n return True\n else:\n #There is no limiter set(found) for this year,\n # so that we can not save this vacation!\n #Or there are no days left in limiter!\n return False\n\n else: #sick, delays and home office have no limits\n super(Absence, self).save(*args, **kwargs)\n return True\n\n def delete(self):\n limiter = Limit.objects.filter(user__id = self.user.id).first()\n days_recover = (self.to_date - self.from_date).days\n if self.type_miss == 'vacation' and days_recover == 0:\n days_recover = 1\n\n #convert days_recover to negative as to recover days,\n # not to substract from limiter\n negative_days = days_recover * -1\n update_limiter(negative_days, limiter)\n super(Absence, self).delete()\n\n\n#signal handler for sending mail notification\ndef send_emails(created, instance):\n subject_prefix = 'New' if created else 'Updated'\n subject = '{} {} {}'.format(subject_prefix,\n 'vacation for',\n instance.user)\n message = \\\n \"\"\"\n User: {}\n From date: {}\n To date: {}\n Comment: {}\n Approved: {}\n\n Please check admin panel to approve/disapprove vacation.\n This is an automated message!\n \"\"\".format(instance.user,\n instance.from_date,\n instance.to_date,\n instance.comment,\n instance.approved)\n\n #subject, message, fail_silently=False, connection=None, html_message=None\n mail_admins(\n subject,\n message,\n fail_silently=True\n )\n\n\ndef save_signal_handler(sender, instance, created, **kwargs):\n\n # if there is no original value...\n if instance.old_from_date is None or instance.old_to_date is None:\n send_emails(created, instance)\n else:\n # there is a change to the from_date or to_date (comment changed or approved)\n if (instance.old_from_date - instance.from_date).seconds != 0 \\\n or (instance.old_to_date - instance.to_date).seconds != 0:\n send_emails(created, instance)\n\n\npost_save.connect(save_signal_handler, sender=Absence)","sub_path":"project/portal/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"642508527","text":"# 载入运动数据帧(240*96),忽略骨骼信息\n\nimport torch\nimport re\nimport os\nimport random\n\ndef loadBVHData(filename):\n with open(filename, 'r') as file:\n bvh = file.read()\n \n # 骨架信息\n skeleton = list(map(float, ' '.join(re.findall(r'OFFSET\\s(.*?)\\n\\s*CHANNELS', bvh)).split(' ')))\n skeleton.extend([0., 0., 0.]) # 补个零占位到 96,因为动作帧里开头有三个元素代表 xyz 坐标\n skeleton = [skeleton] # [1, 96]\n\n # 240 帧运动信息\n bvh = bvh[bvh.find('Frame Time'):]\n bvh = bvh[bvh.find('\\n') + 1:]\n bvh = bvh.strip()\n #print(bvh)\n frame = list(map(lambda f : [float(x) for x in f.split(' ')], bvh.split('\\n'))) # [240, 96]\n\n # 全部信息\n data = skeleton + frame # [1, 96] + [240, 96] = [241, 96]\n label = int(os.path.basename(filename).split('_')[0]) # 文件名第一个数字作为标签\n\n return (data, label)\n\ndef getAllData(dirpath):\n files = [f for f in os.listdir(dirpath)]\n data = []\n for file in files:\n filename = os.path.join(dirpath, file)\n data.append(loadBVHData(filename))\n return data\n\n\nclass MyDataset(torch.utils.data.Dataset):\n # rate 要使用的数据占全部的比率\n def __init__(self, dataset_dir='./v5/walk_id_compacted', rate=1.0):\n self.data = getAllData(dataset_dir)\n # random.shuffle(self.data)\n # self.data = self.data[:int(len(self.data) * rate)]\n # exit()\n\n # 因为 id 从零开始,直接取最后一个文件的 id + 1\n self.category_num = int(os.listdir(dataset_dir)[-1].split('_')[0]) + 1\n \n def __getitem__(self, index):\n data, label = self.data[index]\n return torch.FloatTensor(data), label\n\n def __len__(self):\n return len(self.data)\n\n\nif __name__ == \"__main__\":\n data = getAllData('./v5/walk_id_compacted')\n print(len(data))\n \n # data = loadBVHData('./v5/walk/02_01_1.bvh')\n # print(data)\n #\n # print(data)\n # print('[调试]', 'dataloader.py')\n # ds = MyDataset()\n # print(ds.category_num)\n # dl = torch.utils.data.DataLoader(dataset=ds, batch_size=1, shuffle=True)\n\n # for x in dl:\n # print(x[0].shape)\n\n","sub_path":"removed/version2/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"71831560","text":"__author__ = \"Maciej Bilas\"\n\nimport os.path\nfrom os.path import join as pjoin\nfrom functools import reduce\n\nfrom pandas import DataFrame, concat, merge\n\nfrom veturillo.map_xmls.stations import information as station_info\n\n\nMONTH_TO_PROCESS = '2013-11'\nRAW_TRIPS_DATA_DIR = os.path.realpath(pjoin(os.path.dirname(__file__), '..', '..', 'raw-trips'))\n\n\ndef __load_raw_data(file_path: str or None=None) -> DataFrame:\n if file_path is None:\n file_path = pjoin(RAW_TRIPS_DATA_DIR, 'raw-{}.csv'.format(MONTH_TO_PROCESS))\n\n return DataFrame.from_csv(file_path, sep=';')\n\n\ndef __filter_invalid(trips_df: DataFrame) -> DataFrame:\n return trips_df[trips_df.invalid == 0]\n\n\n# Deprecated\n# Use __add_station_pairs_vectorized instead, as it's ~10x faster\ndef __add_station_pairs_serially(trips_df: DataFrame) -> DataFrame:\n def compute_station_pair(row):\n start_id = row['start_place_id']\n end_id = row['end_place_id']\n id_pair = \"{}-{}\".format(min(start_id, end_id), max(start_id, end_id))\n row['id_pair'] = id_pair\n return row\n\n # Parallel pandas once released will speed up things greatly\n # https://github.com/pydata/pandas/issues/5751\n with_id_pair = trips_df.apply(compute_station_pair, axis=1)\n return with_id_pair\n\n\ndef __add_station_pairs_vectorized(trips_df: DataFrame) -> DataFrame:\n min_s = trips_df[['start_place_id', 'end_place_id']].min(axis=1)\n max_s = trips_df[['start_place_id', 'end_place_id']].max(axis=1)\n id_pairs_series = min_s.map(str) + \"-\" + max_s.map(str)\n id_pairs_df = DataFrame(id_pairs_series, columns=['id_pair'])\n return concat([trips_df, id_pairs_df], axis=1)\n\n\ndef data_with_station_pairs(head=None):\n df = __load_raw_data()\n if head:\n df = df.head(head)\n\n with_pairs = __add_station_pairs_vectorized(__filter_invalid(df))\n return with_pairs\n\n\ndef station_pair_counts(df_with_pairs: DataFrame or None=None) -> DataFrame:\n if df_with_pairs is None:\n df_with_pairs = data_with_station_pairs()\n\n def split_travel_count_index(key):\n (min_st, max_st) = map(int, key.split('-'))\n return {key: [min_st, max_st]}\n\n travel_counts = df_with_pairs.groupby('id_pair').id_pair.count()\n\n def merge_dict(acc, d):\n acc.update(d)\n return acc\n\n index_map = reduce(merge_dict, travel_counts.index.map(split_travel_count_index), {})\n df = DataFrame(index_map).T\n\n # http://stackoverflow.com/questions/11346283/renaming-columns-in-pandas\n df.columns = [\"min_st\", \"max_st\"]\n\n return concat([DataFrame(travel_counts, columns=['count']), df], axis=1)\n\n\ndef station_summary(pair_counts: DataFrame or None=None) -> DataFrame:\n if pair_counts is None:\n pair_counts = station_pair_counts()\n info = station_info()\n lat_lng = info[['lat', 'lng']]\n\n def rename_lat_lng_columns(prefix):\n def do_rename(column):\n if column == 'lat' or column == 'lng':\n return \"{}_{}\".format(prefix, column)\n else:\n return column\n\n return do_rename\n\n with_min_st_coords = merge(pair_counts, lat_lng, how='left', left_on='min_st', right_index=True)\n with_min_st_coords.dropna(inplace=True)\n # http://stackoverflow.com/questions/11346283/renaming-columns-in-pandas\n new_column_names = map(rename_lat_lng_columns(\"min\"), with_min_st_coords.columns)\n with_min_st_coords.columns = new_column_names\n\n with_both_coords = merge(with_min_st_coords, lat_lng, how='left', left_on='max_st', right_index=True)\n with_both_coords.dropna(inplace=True)\n new_column_names = map(rename_lat_lng_columns(\"max\"), with_both_coords.columns)\n with_both_coords.columns = new_column_names\n\n return with_both_coords\n","sub_path":"veturillo/raw_trips/summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"343205596","text":"# -*- coding: utf-8 -*-\n# Copyright 2017 Akretion (http://www.akretion.com).\n# @author Sébastien BEAU \n# @author David BEAL \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).\n\nimport StringIO\nimport logging\n\nfrom openerp import models\n\n_logger = logging.getLogger(__name__)\n\ntry:\n import unicodecsv\nexcept (ImportError, IOError) as err:\n _logger.debug(err)\n\n\nclass AmazonSaleImporter(models.AbstractModel):\n _name = 'amazon.sale.importer'\n _description = 'Amazon Sale Importer'\n\n def _run(self, report, meta_attachment):\n \"\"\" Process the report and generate the sale order\n \"\"\"\n backend = meta_attachment.amazon_backend_id\n file = StringIO.StringIO()\n file.write(report)\n file.seek(0)\n reader = unicodecsv.DictReader(\n file, fieldnames=self._get_header_fieldnames(),\n delimiter='\\t', quoting=False,\n encoding=backend.encoding)\n reader.next() # we pass the file header\n sales = self._extract_infos(reader)\n file.close()\n for item in sales:\n sale = sales[item]\n sale['auto_insert'].update({\n 'external_origin': 'ir.attachment.metadata,%s'\n % meta_attachment.id,\n 'workflow_process_id': backend.workflow_process_id.id,\n })\n if backend._should_skip_sale_order(\n sale['auto_insert']['origin'], is_fba=False):\n _logger.debug(\n \"Order %s already have been imported, skip it\",\n sale['auto_insert']['origin'])\n continue\n backend._create_sale(sales[item])\n\n def _get_header_fieldnames(self):\n return [\n 'order-id', 'order-item-id', 'purchase-date', 'payments-date',\n 'buyer-email', 'buyer-name', 'buyer-phone-number', 'sku',\n 'product-name', 'quantity-purchased', 'currency', 'item-price',\n 'item-tax', 'shipping-price', 'shipping-tax',\n 'ship-service-level', 'recipient-name', 'ship-address-1',\n 'ship-address-2', 'ship-address-3', 'ship-city', 'ship-state',\n 'ship-postal-code', 'ship-country', 'ship-phone-number',\n 'delivery-start-date', 'delivery-end-date',\n 'delivery-time-zone', 'delivery-Instructions', 'sales-channel',\n ]\n\n def _extract_infos(self, reader):\n sales = {}\n for line in reader:\n if not line.get('order-item-id'):\n continue\n if line['order-id'] in sales:\n sales[line['order-id']]['lines'].append(\n self._get_sale_line(line))\n else:\n sales[line['order-id']] = {\n 'auto_insert': {\n # these values will be inserted\n # if matching field exists in the ERP\n 'origin': line['order-id'],\n 'date_order': line['purchase-date'],\n },\n 'partner': {\n 'email': line['buyer-email'],\n 'name': line['buyer-name'],\n 'phone': line['buyer-phone-number'],\n },\n 'part_ship': {\n 'name': line['recipient-name'],\n 'type': 'delivery',\n 'phone': line['ship-phone-number'],\n 'street': line['ship-address-1'],\n 'street2': line['ship-address-2'],\n 'street3': line['ship-address-3'],\n 'city': line['ship-city'],\n 'state': line['ship-state'],\n 'zip': line['ship-postal-code'],\n 'country': line['ship-country'],\n },\n 'lines': [self._get_sale_line(line)],\n }\n return sales\n\n def _get_sale_line(self, line):\n return {\n 'item': line['order-item-id'],\n 'sku': line['sku'],\n 'name': '[%s] %s' % (line['sku'], line['product-name']),\n 'product_uom_qty': line['quantity-purchased'],\n # price is tax included, vat is computed in odoo\n 'price_unit':\n (float(line['item-price']))\\\n / float(line['quantity-purchased']),\n 'shipping': float(line['shipping-price']),\n 'discount': 0,\n }\n","sub_path":"connector_amazon/models/amazon_sale_importer.py","file_name":"amazon_sale_importer.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"512811055","text":"class Solution:\n def isPalindrome(self, x):\n x = str(x)\n _len = len(x)\n for i in range(len(x)):\n if x[i] != x[_len-1-i]:\n return False\n return True\n\ndef main():\n sln = Solution()\n print(sln.isPalindrome(123321))\n\nif __name__ == '__main__':\n main()\n","sub_path":"Palindrome Number/Palindrome Number.py","file_name":"Palindrome Number.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"76180566","text":"import random\nimport threading\nimport time\nimport tkinter as tk\n\nfrom modules.filters import *\nfrom PIL import (\n\tImage,\n\tImageChops,\n\tImageDraw,\n\tImageEnhance,\n\tImageFilter,\n\tImageFont,\n\tImageTk,\n)\n\n# from Tkinter import *\n# import tkMessageBox\n# import PIL.Image\n# import PIL.ImageTk\n# import gc, os\n\n\"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\"\"\"\" \"\"\n\n\nclass AppWindow:\n\t'''[summary]\n\t\n\t[description]\n\t\n\tVariables:\n\t\t) {[type]} -- [description]\n\t'''\n\tdef __init__(self, masterConfig):\n\t\tprint(\"** App Window Initialized ** \")\n\t\tself.masterConfig = masterConfig\n\n\tdef setUp(self):\n\t\t# global root\n\t\t# global root, canvasOffsetX, canvasOffsetY, buff, config\n\t\tself.memoryUsage = 0\n\t\tself.debug = False\n\t\tself.counter = 0\n\n\t\tself.canvasOffsetX = 4\n\t\tself.canvasOffsetY = 7\n\t\tself.buff = 8\n\t\tgc.enable()\n\t\tif self.masterConfig.MID == \"studio-mac\":\n\t\t\tself.masterConfig.path = \"./\"\n\t\t\twindowOffset = [1900, 20]\n\t\t\twindowOffset = [2560, 24]\n\t\t\twindowOffset = [\n\t\t\t\tself.masterConfig.windowXOffset,\n\t\t\t\tself.masterConfig.windowYOffset,\n\t\t\t]\n\t\t\t# windowOffset = [4,45]\n\t\telse:\n\t\t\twindowOffset = [-1, 13]\n\t\t\twindowOffset = [\n\t\t\t\tself.masterConfig.windowXOffset,\n\t\t\t\tself.masterConfig.windowYOffset,\n\t\t\t]\n\n\t\t# -----> this is somewhat arbitrary - just to get the things aligned\n\t\t# after rotation\n\t\t# if(config.rotation == 90) : canvasOffsetY = -25\n\n\t\tself.root = tk.Tk()\n\t\tw = self.masterConfig.screenWidth\n\t\th = self.masterConfig.screenHeight\n\t\tx = windowOffset[0]\n\t\ty = windowOffset[1]\n\n\t\tself.root.overrideredirect(False)\n\t\tself.root.geometry(\"%dx%d+%d+%d\" % (w, h, x, y))\n\t\tself.root.lift()\n\n\n\t'''[summary]\n\t\n\t[description]\n\t'''\n\tdef createMainCanvas(self):\n\t\tself.masterConfig.root = self.root\n\n\t\tself.masterConfig.cnvs = tk.Canvas(\n\t\t\tself.root,\n\t\t\twidth=self.masterConfig.screenWidth + self.buff,\n\t\t\theight=self.masterConfig.screenHeight + self.buff,\n\t\t\tborder=0,\n\t\t)\n\n\t\tself.masterConfig.cnvs.create_rectangle(\n\t\t\t0, 0, self.masterConfig.screenWidth + self.buff, self.masterConfig.screenHeight + self.buff, fill=\"black\"\n\t\t)\n\t\t#config.cnvs.pack()\n\t\tself.masterConfig.cnvs.place(\n\t\t\tbordermode=\"outside\",\n\t\t\twidth=self.masterConfig.screenWidth + self.buff,\n\t\t\theight=self.masterConfig.screenHeight + self.buff,\n\t\t)\n\t\t# root.protocol(\"WM_DELETE_WINDOW\", on_closing)\n\t\t# Button(root, text=\"Quit\", command=root.quit).pack(side=\"bottom\")\n\t\tself.masterConfig.renderImageFull = PIL.Image.new(\"RGBA\", (self.masterConfig.screenWidth, self.masterConfig.screenHeight))\n\t\tself.masterConfig.tempImage = ImageTk.PhotoImage(self.masterConfig.renderImageFull)\n\t\tself.masterConfig.cnvs._image_id = self.masterConfig.cnvs.create_image(self.masterConfig.canvasOffsetX, self.masterConfig.canvasOffsetY, image=self.masterConfig.tempImage, anchor=\"nw\", tag=\"mainer\"\n\t)\n\n\n\tdef startWork(self, work):\n\t\t# global config, work, root, counter\n\t\tglobal counter\n\n\t\t### Putting the animation on its own thread\n\t\t### Still throws and error when manually closed though...\n\n\t\tprint(\"Starting threads\")\n\n\n\t\t'''\n\t\ttry:\n\t\t\tthreadRunning = threading.Thread(target=work.runWork)\n\t\t\tprint(threadRunning)\n\t\t\tthreadRunning.start()\n\t\t\tthreadRunning.join()\n\t\texcept Exception as e:\n\t\t\tprint(\"DID NOT WORK\")\n\t\t\tprint(str(e))\n\t\t'''\n\n\t\ttry:\n\t\t\tt = threading.Thread.__init__(work.runWork())\n\t\t\tt.start()\n\t\t\tt.join()\n\n\t\texcept tk.TclError as details:\n\t\t\tprint(details)\n\t\t\tpass\n\t\t\texit()\n\n\n\tdef run(self):\n\t\tself.root.call(\"wm\", \"attributes\", \".\", \"-topmost\", \"1\")\n\t\tself.root.mainloop()\n\n\t\t\"\"\"\n\t\twhile True:\n\t\t\tself.root.update_idletasks()\n\t\t\tself.root.update()\n\t\t\"\"\"\n","sub_path":"modules/rendering/appWindow.py","file_name":"appWindow.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"604258018","text":"from gpiozero import LED\nfrom time import sleep\nimport random\nimport pygame.mixer\nfrom pygame.mixer import Sound\n\nred = LED(17)\nyellow = LED(27)\ngreen = LED(22)\nblue = LED(23)\nred2 = LED(12)\nyellow2 = LED(16)\ngreen2 = LED(20)\nblue2 = LED(21)\n\nnumberOfCorrect = 0\nnumberOfIncorrect = 0\n\n#===============================================#\n# Light Control ====================#\n#===============================================#\ndef lightShow():\n allLightsOff()\n sleep(.3)\n lightRun()\n lightRunBackward()\n allLightsOn()\n sleep(.2)\n allLightsOff()\n sleep(.2)\n allLightsOn()\n sleep(.2)\n allLightsOff()\n sleep(.3)\n allLightsOn()\n sleep(.3)\n allLightsOff()\n\ndef lightRun():\n allLightsOff()\n for i in allLights():\n i.on()\n sleep(.1)\n i.off()\n\ndef lightRunBackward():\n allLightsOff()\n for i in reversed(allLights()):\n i.on()\n sleep(.1)\n i.off()\n\ndef allLights():\n lights = red, yellow, green, blue, blue2, green2, yellow2, red2\n return lights\n\ndef allLightsOff():\n for i in allLights():\n i.off()\n\ndef allLightsOn():\n for i in allLights():\n i.on()\n\ndef lightUp(color):\n for i in range(5):\n color.on()\n sleep(.1)\n color.off()\n sleep(.1)\n return\n\ndef answerLight(value):\n global numberOfCorrect\n global numberOfIncorrect\n\n num = numberOfCorrect - numberOfIncorrect\n if num < 0:\n num = 0\n if num > len(allLights()):\n num = len(allLights())\n if value == True:\n lightShow()\n allLightsOff()\n for i in range(num):\n allLights()[i].on()\n return\n\n# Light Related End ========================#\n\n\ndef askAdd(num1, num2):\n print(num1, \"+\", num2, \"=\", end=' ')\n input = getNumberInput()\n return input\n\ndef checkAdd(num1, num2, input):\n return input != num1 + num2\n\ndef askRange():\n print(\"Please enter the minimum number: \", end=' ')\n min = int(input())\n print(\"Please enter the maximum number: \", end=' ')\n max = int(input())\n print(\"\")\n return min, max\n\ndef answerSound(bvalue):\n if bvalue:\n Sound(\"soundSamples/aRight\" + str(random.choice(list(range(7)))) + \".wav\").play()\n else:\n Sound(\"soundSamples/aWrong\" + str(random.choice(list(range(7)))) + \".wav\").play()\n\ndef answerResponse(bvalue):\n global numberOfCorrect\n global numberOfIncorrect\n if bvalue:\n numberOfCorrect += 1\n answerSound(True)\n answerLight(True)\n else:\n numberOfIncorrect += 1\n answerSound(False)\n answerLight(False)\n\ndef addition(num1, num2):\n input = askAdd(num1, num2)\n if input == None:\n return False\n\n while checkAdd(num1, num2, input):\n answerResponse(False)\n input = askAdd(num1, num2)\n answerResponse(True)\n return\n\ndef additionGame():\n min, max = askRange()\n\n while True:\n num1 = random.randint(min, max)\n num2 = random.randint(min, max)\n\n if addition(num1, num2) == False:\n # Quiting\n print(\"---------------------------------------\")\n break\n print(\"\")\n return\n\ndef askSubtract(num1, num2):\n print(num1, \"-\", num2, \"=\", end=' ')\n input = getNumberInput()\n return input\n\ndef checkSubtract(num1, num2, input):\n return input != num1 - num2\n\ndef subtraction(num1, num2):\n input = askSubtract(num1, num2)\n if input == None:\n return False\n\n while checkSubtract(num1, num2, input):\n answerResponse(False)\n input = askSubtract(num1, num2)\n answerResponse(True)\n return\n\ndef subtractionGame():\n max = askMax()\n\n while True:\n num1 = random.randint(1, max)\n num2 = random.randint(1, num1)\n\n if subtraction(num1, num2) == False:\n # Quiting\n print(\"---------------------------------------\")\n break\n print(\"\")\n return\n\ndef askMultiplication(num1, num2):\n print(num1, \"x\", num2, \"=\", end=' ')\n input = getNumberInput()\n return input\n\ndef checkMultiplication(num1, num2, input):\n return input != num1 * num2\n\ndef multiplication(num1, num2):\n input = askMultiplication(num1, num2)\n if input == None:\n return False\n\n while checkMultiplication(num1, num2, input):\n answerResponse(False)\n input = askMultiplication(num1, num2)\n answerResponse(True)\n return\n\ndef multiplicationGame():\n while True:\n num1 = random.randint(1, 10)\n num2 = random.randint(1, 10)\n\n if multiplication(num1, num2) == False:\n # Quiting\n print(\"---------------------------------------\")\n break\n print(\"\")\n return\n\ndef askMax():\n print(\"Please enter the maximum number: \", end=' ')\n max = int(input())\n print(\"\")\n return max\n\ndef askAddingMissing(num1, num2):\n print(num1, \"+ __ =\", num2, \"?\", end=' ')\n input = int(input())\n return input\n\ndef checkAddingMissing(num1, num2, input):\n return num1 + input != num2\n\ndef addingMissing(num1, num2):\n input = askAddingMissing(num1, num2)\n\n while checkAddingMissing(num1, num2, input):\n answerResponse(False)\n input = askAddingMissing(num1, num2)\n answerResponse(True)\n print(\"Yes!\", num1, \"+\", input, \"=\", num2)\n return\n\ndef addingMissingGame():\n max = askMax()\n\n while True:\n num1 = random.randint(1, max)\n num2 = random.randint(num1, max)\n\n addingMissing(num1, num2)\n print(\"\")\n return\n\ndef getNumberOfCorrect():\n global numberOfCorrect\n return numberOfCorrect\n\ndef getNumberOfIncorrect():\n global numberOfIncorrect\n return numberOfIncorrect\n\ndef printResult():\n print(\"\")\n print(\"Number of Correct:\", getNumberOfCorrect())\n print(\"Number of Incorrect:\", getNumberOfIncorrect())\n if getNumberOfCorrect() + getNumberOfIncorrect() != 0:\n sum = getNumberOfCorrect() + getNumberOfIncorrect()\n print(\"Grade:\", getNumberOfCorrect()*100.0/sum)\n else:\n print(\"Grade: 000\")\n print(\"\")\n\ndef getNumberInput():\n temp = input()\n while True:\n if temp.isdigit():\n return int(temp)\n if temp == \"q\":\n printResult()\n return\n print(\"That is non-sense. Try again (Enter q to quit): \")\n temp = input()\n\ndef printTitle():\n print(\"**********************************\")\n print(\"| Welcome to |\")\n print(\"| the |\")\n print(\"| MATH GAMES |\")\n print(\"**********************************\")\n print(\"\")\n\ndef chooseGame():\n print(\"Which game would you like to play?\")\n print(\"1) Addition\")\n print(\"2) Adding Missing\")\n print(\"3) Subtraction\")\n print(\"4) Multiplication\")\n print(\"\")\n print(\"Enter a number:\", end=' ')\n return int(input())\n\nwhile True:\n printTitle()\n\n pygame.mixer.init()\n\n while True:\n game = chooseGame()\n print(\"\")\n\n if game == 1:\n additionGame()\n elif game == 2:\n addingMissingGame()\n elif game == 3:\n subtractionGame()\n elif game == 4:\n multiplicationGame()\n\n","sub_path":"mathGames.py","file_name":"mathGames.py","file_ext":"py","file_size_in_byte":7201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"374823286","text":"import abjad\n\ndef tie():\n \"\"\"\n Makes a tie on a single leaf.\n \"\"\"\n return abjad.LilyPondLiteral(\"~\", \"after\")\n\nif __name__ == '__main__':\n voice = r\"c'4 d'2 f'4 f'2 e'2\"\n staff = abjad.Staff(voice)\n abjad.attach(tie(), staff[2])\n abjad.f(staff)\n\n","sub_path":"arctic/tools/tie.py","file_name":"tie.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"416093201","text":"\nfrom qtpy import QtWidgets, QtGui\n\nfrom .server import EmacsProcess, SpyderEPCServer\n\nimport time\nfrom threading import Thread\nimport logging, queue\nlogger = logging.getLogger(__name__)\n\nclass EmacsWidget(QtWidgets.QWidget):\n def __init__(self, plugin, *args, **kwargs):\n super(EmacsWidget, self).__init__(*args, **kwargs)\n self.plugin = plugin\n self._started = False\n self._resizeQueue = queue.Queue()\n def run():\n while True:\n _exit_sig = self._resizeQueue.get()\n if _exit_sig:\n break\n while True:\n try:\n _exit_sig = self._resizeQueue.get(False)\n if _exit_sig:\n return\n except:\n break\n while not self._server.clients:\n time.sleep(0.1)\n self._server.clients[0].call(\"set-width\", [int(self.geometry().width())-40])\n self._server.clients[0].call(\"set-height\", [int(self.geometry().height())-20])\n time.sleep(0.1)\n self._resizeQueue.task_done()\n self._resizeThread = Thread(target=run)\n self._resizeThread.start()\n\n def _resize_emacs(self):\n self._resizeQueue.put(False)\n\n def start(self):\n self._started = True\n self._server = SpyderEPCServer(self.plugin)\n self._emacs_window = QtGui.QWindow()\n self._emacs_widget = QtWidgets.QWidget.createWindowContainer(self._emacs_window)\n self.proc = EmacsProcess(self._emacs_window)\n self.proc.start(int(self._emacs_window.winId()), self._server.server_address[1])\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self._emacs_widget)\n self.setLayout(layout)\n\n def close(self):\n self._server.shutdown()\n self.proc.kill()\n self.proc.waitForFinished()\n\n def resizeEvent(self, event):\n super().resizeEvent(event)\n if not self._started:\n self.start()\n self._resize_emacs()\n","sub_path":"spyder_emacs/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"619014448","text":"from flask import Flask, render_template, url_for, redirect, request, send_from_directory\n\napp = Flask(__name__)\n\n@app.route('/') # decorator\n@app.route('/index/')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/about/')\ndef about():\n return render_template(\"about.html\")\n\n@app.route('/rp_calc/', methods=[\"GET\", \"POST\"])\ndef rp_calc():\n\n def get_points(strGrade, intLevel):\n point_list = [[10, 8.75, 7.5, 6.25, 5, 2.5, 0], [20, 17.5, 15, 12.5, 10, 5, 0]]\n grade = list(\"ABCDESU\")\n for i in range(7):\n if strGrade == grade[i]:\n return point_list[intLevel-1][i]\n\n if request.method == \"POST\":\n data = dict(request.form)\n print(data)\n if \"1h2\" in data:\n base = 80\n score = 0\n h21 = data[\"1h2\"]\n h22 = data[\"2h2\"]\n h23 = data[\"3h2\"]\n h1 = data[\"h1\"]\n gp = data[\"gp\"]\n if \"1pw\" in data:\n pw1 = data[\"1pw\"]\n base += 10\n else:\n pw1 = \"0\"\n if \"1mtl\" in data:\n mtl1 = data[\"1mtl\"]\n else:\n mtl1 = \"0\"\n for item in [h21, h22, h23]:\n score += get_points(item, 2)\n for item in [h1, gp]:\n score += get_points(item, 1)\n if pw1 != \"0\":\n score += get_points(pw1, 1)\n if mtl1 != \"0\":\n score += get_points(mtl1, 1)\n score = round((score/(base + 10))*base, 2)\n total = \"{:0.2f} / {}.00\".format(score, base)\n return render_template(\"rp_calc3.html\", h21 = h21, h22 = h22, h23 = h23, h1 = h1, gp = gp, pw1 = pw1, mtl1 = mtl1, total = total)\n else:\n pw = (data[\"pw\"] == \"1\")\n mtl = (data[\"mtl\"] == \"1\")\n return render_template(\"rp_calc2.html\", pw = pw, mtl = mtl)\n else: #\"GET\"\n return render_template(\"rp_calc.html\")\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"rpcalc/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"635101320","text":"# the third and final part of the lab, which involves searching in the file for some numbers\nimport os\nimport random\n\ndef read_buffer_from_file(): # reads the desired buffer from the file_number-th file\n buffer = []\n global buffer_size\n global disk_access_counter\n global file_pointer\n if (file_pointer <= 99000):\n sorted_file = open(\"final_file\", 'rb')\n sorted_file.seek(file_pointer) # sets the beginning of our reading space on the file at position file_pointer\n byte_array = bytearray(sorted_file.read(buffer_size)) # reads buffer_size amount of bytes from the file\n file_pointer = file_pointer + 1000\n sorted_file.close()\n disk_access_counter = disk_access_counter + 1\n for i in range(buffer_size): # fill the buffer from the file TODO CHECK (-1)\n buffer.append(byte_array[i])\n return buffer\n else:\n print(\"error while reading from file: file_pointer>99000\")\n\ndef serial_search_file(number_we_search,): # used to search the entire file at once using serial(sequential) search\n found = 0\n global file_pointer\n file_pointer = 0 # it is returned to zero to avoid exceeding the limits of the file\n buffer = read_buffer_from_file()\n while (found == 0):\n for i in range(1000):\n if buffer[i] == number_we_search:\n found = 1\n buffer = read_buffer_from_file()\n if file_pointer > 99000:\n return 1\n if found == 1 :\n #print(\"Number found!\")\n return 1 # means that the search was successful\n\ndef serial_search_buffer(number_we_search,buffer):\n found = 0\n global buffer_size\n for i in range(buffer_size):\n if buffer[i] == number_we_search:\n found = 1\n return found # if search was successful, it returns 1\n\ndef binary_search(number_we_search): # file length in bytes is used to determine how many buffers there are to examine\n global file_pointer\n global buffer_size\n beginning = 0 # beginning buffer number\n end = int(100000/buffer_size) # ending buffer number.100000 is the size of the file in bytes\n found = False\n while beginning<=(end-1) and not found:\n midpoint = (beginning + end)//2\n file_pointer = midpoint*buffer_size\n midpopint_buffer = read_buffer_from_file()\n\n if serial_search_buffer(number_we_search,midpopint_buffer) == 1:\n #print(\"Number found using binary search!\")\n return 1\n else:\n if number_we_search < min(midpopint_buffer):\n end = midpoint-1\n else:\n beginning = midpoint+1\n if found == False :\n #print(\"Number was NOT found using binary search!\")\n return 0\n\n\n# essential variables initialisation (some are used as global in the functions)\nfile_pointer = 0\nbuffer_pointer = 0\nbuffer = []\nbuffer_size = 1000\ndisk_access_counter = 0\n\nif os.path.exists(\"final_file\"): # check if there is an old existing file\n print(\"File found.Proceeding.\")\nelse:\n print(\"There was no existing file, the program will be terminated.Run again the previous \")\n print(\"Python scripts ( filemaker.py, filesort.py and filesort_merge.py).\")\n exit() # terminates the program\n\n# test serial search\nprint(\"Attempting serial search...\") # with numbers that are in our file\nfor a in range(40):\n random_int = random.randint(1,18)\n serial_search_file(random_int)\n\navg_disk_access_counter_serial_success = disk_access_counter/40\n\ndisk_access_counter = 0\n\nprint(\"Attempting serial search...\") # with numbers that are not in our file\nfor a in range(40):\n random_int = random.randint(25,100)\n serial_search_file(random_int)\n\navg_disk_access_counter_serial_fail= disk_access_counter/40\n\ndisk_access_counter = 0\n\n# test binary search\nprint(\"Attempting binary search...\" ) # with numbers that are in our file\nfor i in range(40):\n random_integer = random.randint(1,18)\n binary_search(random_integer)\n\navg_disk_access_counter_binary_success = disk_access_counter/40\n\ndisk_access_counter = 0\n\nprint(\"Attempting binary search...\" ) # with numbers that are not in our file\nfor i in range(40):\n random_integer = random.randint(25,100)\n binary_search(random_integer)\navg_disk_access_counter_binary_fail = disk_access_counter/40\n\n\nprint(\"Average disk access count with succeeded binary search: \" + str(avg_disk_access_counter_binary_success))\nprint(\"Average disk access count with failed binary search: \" + str(avg_disk_access_counter_binary_fail) + \"\\n\")\n\nprint(\"Average disk access count with succeeded serial search: \" + str(avg_disk_access_counter_serial_success))\nprint(\"Average disk access count with failed serial search: \" + str(avg_disk_access_counter_serial_fail))\n\n\n\n\n","sub_path":"final_search_file.py","file_name":"final_search_file.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"104976112","text":"import h5py\nimport numpy as np\nimport os\nimport struct\nfrom collections import defaultdict\n\nfrom keras import backend as K\nfrom keras.models import Model, load_model\n\nBACKEND = K.backend()\nDIM_ORDERING = K.image_dim_ordering()\n\ndef load_model_if_exists(prefix=None, out_dir=None):\n '''\n Load a model from path out_dir/prefix_BACKEND_model.h5\n if it exists.\n\n :param prefix:\n :param out_dir:\n :return:\n '''\n if prefix is None:\n prefix = 'keras_model'\n if not prefix.endswith('_'):\n prefix += '_'\n if out_dir is None:\n out_dir = os.getcwd()\n model_path = os.path.join(out_dir, prefix + 'model.h5')\n if os.path.isfile(model_path):\n return load_model(model_path)\n return None\n\n\ndef save_model_details(model, prefix=None, out_dir=None):\n '''\n Save model configuration to out_dir/prefix_BACKEND_config.json,\n model weights to out_dir/prefix_BACKEND_weights.h5, and\n full model to out_dir/prefix_BACKEND_model.h5.\n\n :param model:\n :param prefix:\n :param out_dir:\n :return:\n '''\n if prefix is None:\n prefix = 'keras_model'\n if not prefix.endswith('_'):\n prefix += '_'\n if out_dir is None:\n out_dir = os.getcwd()\n with open(os.path.join(out_dir, prefix + 'config.json'), 'w') as f:\n f.write(model.to_json(indent=1) + '\\n')\n # TODO: save out YAML as well -- seems to be broken currently\n# with open(os.path.join(out_dir, prefix + 'config.yaml'), 'w') as f:\n# f.write(model.to_yaml() + '\\n')\n model.save(os.path.join(out_dir, prefix + 'model.h5'), True)\n model.save_weights(os.path.join(out_dir, prefix + 'weights.h5'), True)\n\n\ndef save_model_output(model, X, Y, nb_examples=None, prefix=None, out_dir=None):\n '''\n Save data necessary to fully test a loaded model to an HDF5 archive: sample\n data (X, Y), model predictions, scores in given metrics, and per-layer activations.\n\n :param model:\n :param X:\n :param Y:\n :param nb_examples:\n :param prefix:\n :param out_dir:\n :return:\n '''\n if prefix is None:\n prefix = 'keras_model'\n if not prefix.endswith('_'):\n prefix += '_'\n if out_dir is None:\n out_dir = os.getcwd()\n\n if nb_examples is not None:\n idx = np.random.choice(X.shape[0], nb_examples, replace=True)\n X = X[idx]\n Y = Y[idx]\n batch_size = nb_examples\n else:\n batch_size = 128\n\n print('saving inputs and ouputs')\n f = h5py.File(os.path.join(out_dir, prefix + 'inputs_and_outputs.h5'), 'w')\n f.create_dataset('X', X.shape, dtype='f', data=X)\n f.create_dataset('Y', Y.shape, dtype='f', data=Y)\n Yhat = model.predict(X, batch_size=batch_size)\n f.create_dataset('Yhat', Yhat.shape, dtype='f', data=Yhat)\n\n print('saving scores')\n Sgroup = f.create_group('scores')\n scores = model.evaluate(X, Y, verbose=0)\n if type(scores) is list:\n for score_name, score in zip(model.metrics_names, scores):\n Sgroup.create_dataset(score_name, (1,), dtype='f', data=np.array([score]))\n else:\n Sgroup.create_dataset(model.metrics_names[0], (1,), dtype='f', data=np.array([scores]))\n\n Agroup = f.create_group('activations')\n for layer in model.layers:\n print('saving activations for layer ' + layer.name)\n m = Model(input=model.inputs, output=layer.output)\n A = m.predict(X, batch_size)\n if len(A.shape) == 4 and DIM_ORDERING == 'tf':\n A = np.rollaxis(A, 3, 1)\n Agroup.create_dataset(layer.name, A.shape, dtype='f', data=A)\n\n f.close()\n","sub_path":"dl4j/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"470460547","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy.fft import fft, fftfreq\n\ndef cosShift(re, im):\n shift = np.arctan2(im, re) * 180/np.pi\n shift = np.floor(shift)\n if shift < 0:\n shift += 360\n return shift\n\ndef fourierDecomp(wavefunction):\n length = len(wavefunction)\n # increase spatial resolution of wavefunction\n # by interpolation for more precise FFT\n index = np.random.randint(0, 9600)\n x = np.linspace(0, length-1, length)\n y = wavefunction\n xvals = np.linspace(0, length-1, 1000)\n yinterp = np.interp(xvals, x, y)\n \n # spatial resolution and domain\n T = 127\n v = 1/T\n # angular frequency\n w = 2*np.pi*v\n # spatial resolution and domain\n n = 2000\n x = np.linspace(0, T, n)\n xsynth = np.linspace(0, T, n)\n \n # extend and mirror signal for Half Range Fourier Series\n sgnl = np.append(yinterp, -yinterp[::-1])\n \n # frequency domain\n freqs = fftfreq(n) * n\n \n # true physical frequency domain\n realFreqs = freqs > 0\n \n # FFT\n fft_vals = fft(sgnl)\n \n # true physical FFT\n fft_phys = 2.0*np.abs(fft_vals/n)\n \n # compose signal out of sinusoidal paramteres\n sgnl_synth = 0\n \n A_list = []\n f_list = []\n s_list = []\n \n Afs = []\n \n for f in range(1, 9):\n Asynth = fft_phys[f]\n re = fft_vals.real[f]\n im = fft_vals.imag[f]\n s = cosShift(re, im)*np.pi/180\n sgnl_synth += Asynth * np.cos(f * w * x + s)\n # if s > np.pi:\n # sgnl_synth += Asynth * np.sin(f * w * x) \n # Afs.append(1)\n # if s < np.pi:\n # sgnl_synth += Asynth * (-1.) * np.sin(f * w * x)\n # Afs.append(-1)\n \n A_list.append(Asynth)\n f_list.append(f)\n s_list.append(s)\n \n Afs.append(f)\n Afs.append(Asynth)\n Afs.append(s)\n\n return Afs\n\n#%%\nbins = 128\nseedmax = 20\ntrainy = []\nvalidy = []\n\nfor i in range(seedmax):\n with open(path+'test_out/test_out'+str(i)+'.csv', 'r') as csvfile:\n flurg = csv.reader(csvfile)\n for row in flurg:\n trainy.append([float(num) for num in row])\n with open(path+'valid_out/valid_out'+str(i)+'.csv', 'r') as csvfile:\n flurg = csv.reader(csvfile)\n for row in flurg:\n validy.append([float(num) for num in row])\n\n#%%\nFourierInfo = fourierDecomp(trainy[79])\n\nT = 127\nv = 1/T\n# angular frequency\nw = 2*np.pi*v\n# spatial resolution and domain'\nn = 254\nx = np.linspace(0, T, n)\n\nsgnl_synth = 0 \n \nsgnl_synth += FourierInfo[1] * np.cos(FourierInfo[0] * w * x + FourierInfo[2])\nsgnl_synth += FourierInfo[4] * np.cos(FourierInfo[3] * w * x + FourierInfo[5])\nsgnl_synth += FourierInfo[7] * np.cos(FourierInfo[6] * w * x + FourierInfo[8])\nsgnl_synth += FourierInfo[10] * np.cos(FourierInfo[9] * w * x + FourierInfo[11])\nsgnl_synth += FourierInfo[13] * np.cos(FourierInfo[12] * w * x + FourierInfo[14])\nsgnl_synth += FourierInfo[16] * np.cos(FourierInfo[15] * w * x + FourierInfo[17])\nsgnl_synth += FourierInfo[19] * np.cos(FourierInfo[18] * w * x + FourierInfo[20])\nsgnl_synth += FourierInfo[22] * np.cos(FourierInfo[21] * w * x + FourierInfo[23])\n\nplt.plot(trainy[79])\nplt.plot(sgnl_synth[:127])\n \n\n#%%\n# plot analyzed and synthized wavefunctions\nplt.grid(1)\nplt.plot(sgnl[0:1000], linewidth=2, label='original Signal')\nplt.plot(sgnl_synth[0:1000], linewidth=2, label='synthesized Signal')\nplt.legend()\nplt.tight_layout()\n\n# plot all information\nplt.figure(2)\nplt.subplot(511)\nplt.grid(1)\nplt.title('Signal extended as odd function')\nplt.plot(sgnl)\n\nplt.subplot(512)\nplt.grid(1)\nplt.title('Synthized Signal')\nplt.plot(xsynth, sgnl_synth)\n\nplt.subplot(513)\nplt.grid(1)\nplt.title('Real Spectrum')\nplt.plot(fft_vals.real, '.')\n\nplt.subplot(514)\nplt.grid(1)\nplt.title('Imaginary Spectrum')\nplt.plot(fft_vals.imag, '.')\n\nplt.subplot(515)\nplt.grid(1)\nplt.title('Processed Amplitudes (processed absolute values)')\nplt.plot(fft_phys, '.')","sub_path":"code/FourierAnaSynFUNC.py","file_name":"FourierAnaSynFUNC.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"211571457","text":"from flask import Flask\r\nfrom flask_migrate import MigrateCommand, Migrate\r\nfrom flask_script import Manager\r\nfrom functools import wraps\r\nfrom models import db\r\n\r\nfrom routes.node import main as node_routes\r\nfrom routes.todo import main as todo_routes\r\nfrom routes.user import main as user_routes\r\nfrom routes.v2ex import main as v2ex_routes\r\nfrom routes.topic import main as topic_routes\r\nfrom routes.comment import main as comment_routes\r\n\r\napp = Flask(__name__)\r\n\r\nmanager = Manager(app)\r\ndb_path = 'my.sqlite'\r\n\r\n\r\ndef register_routes(app):\r\n app.register_blueprint(node_routes, url_prefix='/node')\r\n app.register_blueprint(todo_routes, url_prefix='/todo')\r\n app.register_blueprint(user_routes, url_prefix='/user')\r\n app.register_blueprint(topic_routes, url_prefix='/topic')\r\n app.register_blueprint(comment_routes, url_prefix='/api')\r\n app.register_blueprint(v2ex_routes)\r\n\r\n\r\ndef configure_app():\r\n app.config['SQLALCHEMY_MODIFICATIONS'] = True\r\n app.secret_key = 'random key'\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(db_path)\r\n db.init_app(app)\r\n register_routes(app)\r\n\r\n\r\ndef configured_app():\r\n configure_app()\r\n return app\r\n\r\n\r\ndef configure_manager():\r\n Migrate(app, db)\r\n manager.add_command('db', MigrateCommand)\r\n\r\n\r\n# @manager.command\r\ndef server():\r\n configured_app()\r\n print('server run')\r\n config = dict(\r\n debug=True,\r\n host='localhost',\r\n port=2000,\r\n )\r\n app.run(**config)\r\n\r\n\r\n@manager.command\r\ndef db_built():\r\n db.drop_all()\r\n db.create_all()\r\n\r\n\r\nif __name__ == '__main__':\r\n configure_manager()\r\n configure_app()\r\n # manager.run()\r\n server()\r\n\r\n","sub_path":"项目集合/v2ex/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"260320705","text":"import sys\n\nnum_of_reviews = 0\ncorrect_count = 0\n\nfile_name_ans = sys.argv[-2]\nfile_name_out = sys.argv[-1]\n\nwith open(file_name_ans, 'r') as ans, open(file_name_out, 'r') as output:\n for ans_line in ans:\n num_of_reviews += 1\n output_line = output.readline()\n if ans_line == output_line:\n correct_count += 1\nans.close()\noutput.close()\n\nprint(correct_count)\nprint(correct_count / num_of_reviews)\n","sub_path":"check-accuracy3.py","file_name":"check-accuracy3.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"23339564","text":"#!/usr/bin/python\n\nimport sqlite3\n\nconn = sqlite3.connect('db.sqlite3')\n\nconn.execute('''CREATE TABLE COMPANY\n (ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL);''')\nconn.execute(\"INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \\\n VALUES (1, 'Paul', 32, 'California', 20000.00 )\");\n\ncursor = conn.execute(\"SELECT * from COMPANY\")\nfor row in cursor:\n print(\"ID = \", row[0])\n \nconn.close()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"13716766","text":"# https://oj.leetcode.com/problems/n-queens-ii/\n# Follow up for N-Queens problem.\n# Now, instead outputting board configurations, return the total number of distinct solutions.\n#\n# Author: Tony Wen\n\nclass Solution:\n ans, limit = 0, 0\n # @return an integer\n def totalNQueens(self, n):\n self.ans = 0\n self.limit = (1 << n) - 1\n self.test(0, 0 ,0)\n return self.ans\n def test(self, row, ld, rd):\n if row == self.limit:\n self.ans += 1\n return\n pos = self.limit & (~(row|ld|rd))\n while pos:\n p = pos & (-pos)\n pos -= p\n self.test(row+p, (ld+p)<<1, (rd+p)>>1)\n ","sub_path":"python/NQueensII/NQueensII.py","file_name":"NQueensII.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"311123009","text":"from handlers.base import BaseHandler\nfrom tools import json_helper\n\n\nclass SearchingHandler(BaseHandler):\n async def get(self):\n keyword = '%' + self.get_argument(\"keyword\") + '%'\n if len(keyword) < 3:\n self.write(json_helper.dumps(None))\n return\n self.db.cursor.execute(\n \"SELECT a.id,a.title,a.category,a.img,a.subhead,a.time,u.username as author FROM article a \"\n \"JOIN user u on a.id_user = u.id \"\n \"WHERE a.category LIKE %s OR a.title LIKE %s OR u.username LIKE %s \"\n \"ORDER BY a.time DESC\", (keyword, keyword, keyword)\n )\n data = self.db.cursor.fetchall()\n json = json_helper.dumps(data)\n self.write(json)\n","sub_path":"server/handlers/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"299000922","text":"from django.urls import re_path\nfrom product import views\nfrom rest_framework.urlpatterns import format_suffix_patterns\n\n\nurlpatterns = [\n re_path(r'^category$', views.CategoryList.as_view()),\n re_path(r'^category/(?P[0-9]+)$', views.CategoryDetail.as_view()),\n re_path(r'^product$', views.ProductList.as_view()),\n re_path(r'^product/(?P[0-9]+)$', views.ProductDetail.as_view()),\n re_path(r'^farmer/(?P[0-9]+)/product$', views.ProductForFarmer.as_view()),\n re_path(r'^category/(?P[0-9]+)/product$', views.ProductForCategory.as_view()),\n # re_path(r'^customer/(?P[0-9]+)/cart$', views.CartForCustomer.as_view()),\n re_path(r'^customer/(?P[0-9]+)/cart$', views.CartForCustomer.as_view()),\n re_path(r'^product/(?P[a-zA-Z].*)$', views.ProductSearch.as_view()),\n re_path(r'^customer/(?P[0-9]+)/cart/(?P[0-9]+)', views.CartView.as_view())\n]\n\n# Adding this lets you use filename extensions on URLs to provide an endpoint for a given media type.\n# For example you can get endpoint data in json representation or html static file\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])","sub_path":"backend/product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"130605553","text":"import click\n\nCONTEXT_SETTINGS = dict(\n default_map={\n 'broker_addr':'tcp://127.0.0.1:5552',\n 'worker':{\n 'addr':'tcp://127.0.0.1:5553',\n 'algorithm':{\n 'max_array_size':10,\n }\n }\n }\n)\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n pass\n\n@cli.command()\n@click.option('--broker-addr',default='tcp://127.0.0.1:5551')\n@click.option('--worker-addr',default='tcp://127.0.0.1:5552',default_path=['worker','addr'])\n@click.option('--max-array-size',default=20,default_path='worker.algorithm.max_array_size')\ndef test_my_algorithm(broker_addr,worker_addr,max_array_size):\n \"\"\"Just one simple test subcommand using the global configuration\"\"\"\n print('Using broker_addr: %s'%broker_addr)\n print('Using worker_addr: %s'%worker_addr)\n print('Using max_array_size: %s'%max_array_size)\n","sub_path":"examples/complex/complex/commands/cmd_default_map.py","file_name":"cmd_default_map.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"53396748","text":"def hard_mode():\r\n\r\n# Hard Mode\r\n # Taking the user's name, difficlty level and number of questions he/she wants to answer as an input to enter to the database when saving\r\n\r\n name = input(\"\\n* Enter your name : \" )\r\n qneed = int(input(\"\\n* How many questions you need to answer : \"))# qneed stands for questions need to answer\r\n\r\n # Calling variables and lists that are needed for the functioning of this module\r\n\r\n queslist = [] # List that contains generated questions\r\n canslist = []# List that contains correct answers\r\n uanslist = []# List that contains users' answers\r\n m_operators = [\"+\",\"-\"]\r\n h_operators = [\"+\",\"-\",\"*\"]\r\n count = 0\r\n correctcount = 0\r\n\r\n # Giving user questions according to his inputs \r\n\r\n print(\"\\n\\t\\t\\t Think Well And Answer these questions!!!\")\r\n for x in range(qneed):\r\n import random\r\n rand1 = random.randrange(0,101)\r\n rand2 = random.randrange(0,101)\r\n rand3 = random.choice(h_operators)# In here i am going to use random.choice \r\n if(rand3 == \"+\"):\r\n ques = (f'{rand1} + {rand2} = ')# Creating question as a variable using f strings\r\n queslist.append(ques)# Input the generated questions to the list\r\n print(\"\\t\",rand1 , \"+\" , rand2, \"?\" ,end=\" \")\r\n uans = input()\r\n if uans != \"\" :\r\n count += 1\r\n else:\r\n pass\r\n uanslist.append(uans)# Input the users' answer into the list\r\n cans = str(rand1 + rand2)\r\n canslist.append(cans)# Input the correct answer into the list\r\n elif(rand3 == \"-\"):\r\n ques = (f'{rand1} - {rand2} = ')# Creating question as a variable using f strings\r\n queslist.append(ques)# Input the generated questions to the list\r\n print(\"\\t\",rand1 , \"-\" , rand2, \"?\" ,end=\" \")\r\n uans = input()\r\n if uans != \"\" :\r\n count += 1\r\n else:\r\n pass\r\n uanslist.append(uans)# Input the users' answer into the list\r\n cans = str(rand1 - rand2)\r\n canslist.append(cans)# Input the correct answer into the list\r\n elif(rand3 == \"*\"):\r\n ques = (f'{rand1} * {rand2} = ')# Creating question as a variable using f strings\r\n queslist.append(ques)# Input the generated questions to the list\r\n print(\"\\t\",rand1 , \"*\" , rand2, \"?\" ,end=\" \")\r\n uans = input()\r\n if uans != \"\" :\r\n count += 1\r\n else:\r\n pass\r\n uanslist.append(uans)# Input the users' answer into the list\r\n cans = str(rand1 * rand2)\r\n canslist.append(cans)# Input the correct answer into the list\r\n \r\n # Displaying game results\r\n\r\n print(\"\\n\\t\\t\\t\\t Game results \")\r\n print('''\r\n *************************************************************\r\n | WELLDONE!!! |\r\n | |\r\n | Let's see how well you have played |\r\n | |\r\n | |\r\n *************************************************************\r\n ''')\r\n \r\n \r\n # Showing user the data like his name, difficulty level and no.of questions he/she answered\r\n \r\n print(\"* Your name is \", name,\"\\n\")\r\n print(\"* You played the game with Hard mode\\n\")\r\n print(\"* There were \",qneed, \"Questions generated\\n\")\r\n print(\"* You answered \",count, \"Questions\\n\")\r\n for y in range(qneed):\r\n if canslist[y] == uanslist[y]:\r\n correctcount += 1\r\n print(\"\\t\\t\" f'{queslist[y]}{uanslist[ y ]} (Answer {canslist[y]})[correct]')# Printing the output with the created lists\r\n else:\r\n print(\"\\t\\t\" f'{queslist[y]}{uanslist[ y ]} (Answer {canslist[y]})[Incorrect]' ) \r\n print(\"\\n* you have provided correct answers for \", correctcount, \"questions\")\r\n score = correctcount/qneed * 100\r\n print(\"\\n* your score is \", score ,\"%\")\r\n\r\n # Establishing connection with the database\r\n\r\n import mysql.connector\r\n db = mysql.connector.connect(user=\"Useradmin\",password=\"user123456\",\r\n host=\"127.0.0.1\",database=\"customgame\")\r\n cursor = db.cursor()\r\n sqltext = \"INSERT INTO Hard_mode (Name,Total_Questions,Correct_Answers,Score)VALUES (%s,%s,%s,%s)\"\r\n myvalues = (name,qneed,correctcount,score)\r\n cursor.execute(sqltext,myvalues)\r\n db.commit()\r\n db.close()\r\n\r\n\r\n \r\n\r\n \r\n \r\n \r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n","sub_path":"CW Python Files/Customgame/hard.py","file_name":"hard.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"166325105","text":"from skimage import io\nimport numpy as np \nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras import backend as K\nimport time\nimport os\nimport sys\nimport matlab.engine\n\n\ndef tif_read(file_name):\n \"\"\"\n read tif image in (rows,cols,slices) shape\n \"\"\"\n im = io.imread(file_name)\n im_array = np.zeros((im.shape[1],im.shape[2],im.shape[0]), dtype=im.dtype)\n for i in range(im.shape[0]):\n im_array[:,:,i] = im[i]\n return im_array\n\n\ndef tif_write(im_array, file_name):\n \"\"\"\n write an array with (rows,cols,slices) shape into a tif image\n \"\"\"\n im = np.zeros((im_array.shape[2],im_array.shape[0],im_array.shape[1]), dtype=im_array.dtype)\n for i in range(im_array.shape[2]):\n im[i] = im_array[:,:,i]\n io.imsave(file_name,im)\n return None\n\n\ndef masked_binary_crossentropy(y_true, y_pred):\n mask = K.cast(K.not_equal(y_true,2), K.floatx())\n score = K.mean(K.binary_crossentropy(y_pred*mask, y_true*mask), axis=-1)\n return score\n\n\ndef masked_accuracy(y_true, y_pred):\n mask = K.cast(K.not_equal(y_true,2), K.floatx())\n score = K.mean(K.equal(y_true*mask, K.round(y_pred*mask)), axis=-1)\n return score\n\n\ndef masked_error_pos(y_true, y_pred):\n mask = K.cast(K.equal(y_true,1), K.floatx())\n error = (1-y_pred) * mask\n score = K.sum(error) / K.maximum(K.sum(mask),1)\n return score\n\n\ndef masked_error_neg(y_true, y_pred):\n mask = K.cast(K.equal(y_true,0), K.floatx())\n error = y_pred * mask\n score = K.sum(error) / K.maximum(K.sum(mask),1)\n return score\n\n\ndef unet_test(unet_model, img, input_sz=(64,64,64), step=(24,24,24), mask=None):\n '''\n Test 3D-Unet on an iamge data\n args:\n unet_model: 3D-Unet model\n img: image data for testing\n input_sz: U-net input size\n step: number of voxels to move the sliding window in x-,y-,z- direction\n '''\n \n gap = (int((input_sz[0]-step[0])/2), int((input_sz[1]-step[1])/2), int((input_sz[2]-step[2])/2))\n img = np.float32(img)\n \n if mask is not None:\n assert mask.shape == img.shape, \\\n \"Mask and image shapes do not match!\"\n mask[mask!=0] = 1\n img = img * mask\n mask = 1-mask\n mask = np.uint8(mask)\n img_masked = np.ma.array(img, mask=mask)\n img = (img - img_masked.mean()) / img_masked.std()\n else:\n img = (img - img.mean()) / img.std()\n\n # expand the image to deal with edge issue\n new_img = np.zeros((img.shape[0]+gap[0]+input_sz[0], img.shape[1]+gap[1]+input_sz[1], img.shape[2]+gap[2]+input_sz[2]), dtype=img.dtype)\n new_img[gap[0]:new_img.shape[0]-input_sz[0], gap[1]:new_img.shape[1]-input_sz[1], gap[2]:new_img.shape[2]-input_sz[2]] = img\n img = new_img\n predict_img = np.zeros(img.shape, dtype=img.dtype)\n\n for row in range(0, img.shape[0]-input_sz[0], step[0]):\n for col in range(0, img.shape[1]-input_sz[1], step[1]):\n for vol in range(0, img.shape[2]-input_sz[2], step[2]):\n patch_img = np.zeros((1, input_sz[0], input_sz[1], input_sz[2], 1), dtype=img.dtype)\n patch_img[0,:,:,:,0] = img[row:row+input_sz[0], col:col+input_sz[1], vol:vol+input_sz[2]]\n patch_predict = unet_model.predict(patch_img)\n predict_img[row+gap[0]:row+gap[0]+step[0], col+gap[1]:col+gap[1]+step[1], vol+gap[2]:vol+gap[2]+step[2]] \\\n = patch_predict[0,:,:,:,0]\n\n predict_img[predict_img>=0.5] = 255\n predict_img[predict_img<0.5] = 0\n predict_img = np.uint8(predict_img)\n predict_img = predict_img[gap[0]:predict_img.shape[0]-input_sz[0], gap[1]:predict_img.shape[1]-input_sz[1], gap[2]:predict_img.shape[2]-input_sz[2]]\n\n return predict_img\n\n\ndef main():\n\n start = time.time()\n print(\"############## U-Net prediction ##############\")\n assert 1 < len(sys.argv)-1 < 4, \\\n \"ERROR: 2 or 3 arguments needed: first one is output directory, second one is image, third one (optional) is mask\"\n \n out_path = sys.argv[1]\n if not os.path.exists(out_path):\n os.mkdir(out_path)\n test_file = sys.argv[2]\n assert os.path.exists(test_file), \\\n \"ERROR: Image file does not exist!\"\n test_img = tif_read(test_file)\n if len(sys.argv) - 1 == 3:\n mask_file = sys.argv[3]\n assert os.path.exists(mask_file), \\\n \"ERROR: Mask file does not exist!\"\n mask_img = tif_read(mask_file)\n else: \n mask_img = None\n\n print(\"Loading the model...\")\n model_file = '/groups/dickson/dicksonlab/lillvis/ExM/Ding-Ackerman/crops-for-training_Oct2018/DING/model_DNN/saved_unet_model/model_gen2_final/unet.whole.h5'\n model_whole = load_model(model_file, custom_objects={'masked_binary_crossentropy':masked_binary_crossentropy, \\\n 'masked_accuracy':masked_accuracy, 'masked_error_pos':masked_error_pos, 'masked_error_neg':masked_error_neg})\n \n print(\"Doing prediction...\")\n predict_img = unet_test(model_whole, test_img, mask=mask_img)\n\n tif_write(predict_img, out_path+'/unet_'+os.path.basename(test_file))\n\n eng = matlab.engine.start_matlab()\n img_name = out_path+'/unet_'+os.path.basename(test_file)\n flag = eng.Postprocessing(img_name)\n\n end = time.time()\n print(\"...Running time is {}\".format(end-start))\n print(\"############### Finish ###############\")\n \n\nif __name__==\"__main__\":\n main()","sub_path":"unet_pipeline/Classification.py","file_name":"Classification.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"94156387","text":"import json\nfrom time import gmtime, strftime\n\ndef network_json_export(coins, markets, sizes, balances, balances_usd, exchange_values, trades, date):\n balance_zip = zip(coins, balances, balances_usd, sizes)\n markets_zip = zip(markets, exchange_values, trades)\n\n nodes = [{'data': {'id': item[0], 'balance': item[1], 'balance_usd': item[2], 'size': item[3]}} for item in balance_zip]\n edges = [{'data': {'id': item[0][0] + '-' + item[0][1], 'source': item[0][0], 'target': item[0][1], 'exchange_val': item[1], 'trade': item[2]}, 'classes': 'autorotate'} for item in markets_zip]\n\n out_json = {'global': {'total_usd': sum(balances_usd), 'run_name': 'RUNNAME HERE', 'date': date}, 'nodes': nodes, 'edges': edges}\n json_str = json.dumps(out_json, sort_keys=True, indent = 4, separators = (',', ': '))\n\n json_file_current = open('C:/Users/Harry/Documents/CaishenGraph/json/latest.json', 'w')\n json_file_current.write(json_str)\n json_file_current.close()\n\n # json_file_current = open('./networkjson/' + strftime(\"%a %d %b %H%M%S\", gmtime()) + '.json', 'w')\n # json_file_current.write(json_str)\n # json_file_current.close()","sub_path":"jsonexporter.py","file_name":"jsonexporter.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"611285944","text":"\"\"\"Define category operations used by graph rewriting tool.\"\"\"\n\nfrom regraph.library.data_structures import (TypedGraph,\n TypedDiGraph,\n Homomorphism)\nfrom regraph.library.utils import keys_by_value, merge_attributes\n\n\ndef pullback(h1, h2):\n \"\"\" Given h1 : B -> D; h2 : C -> D returns A, rh1, rh2\n with rh1 : A -> B; rh2 : A -> C and A the pullback\"\"\"\n\n if type(h1.target_) == TypedGraph:\n A = TypedGraph()\n else:\n A = TypedDiGraph()\n\n hom1 = {}\n hom2 = {}\n\n B = h1.source_\n C = h2.source_\n D = h2.target_\n f = h1.mapping_\n g = h2.mapping_\n\n if h1.target_ != D:\n raise ValueError(\n \"Homomorphisms don't have the same codomain, can't do pullback.\\nh1: %s\\nh2:%s\\n\" %\n (h1, h2)\n )\n\n for n1 in B.nodes():\n for n2 in C.nodes():\n if f[n1] == g[n2]:\n if not n1 in A.nodes():\n A.add_node(n1,\n B.node[n1].type_,\n merge_attributes(B.node[n1].attrs_,\n C.node[n2].attrs_,\n 'intersection'))\n\n hom1[n1] = n1\n hom2[n1] = n2\n else:\n i=1\n new_name = str(n1)+str(i)\n while new_name in A.nodes():\n i+=1\n new_name = str(n1)+str(i)\n if not n2 in A.nodes():\n A.add_node(new_name,\n n2,\n merge_attributes(B.node[n1].attrs_,\n C.node[n2].attrs_,\n 'intersection'))\n\n hom1[new_name] = n1\n hom2[new_name] = n2\n\n for n1 in A.nodes():\n for n2 in A.nodes():\n if (hom1[n1], hom1[n2]) in B.edges() or \\\n ((not A.is_directed) and (hom1[n2], hom1[n1]) in B.edges()):\n if (hom2[n1], hom2[n2]) in C.edges() or \\\n ((not A.is_directed) and (hom2[n2], hom2[n1]) in C.edges()):\n A.add_edge(n1, n2)\n A.set_edge(\n n1,\n n2,\n merge_attributes(\n B.get_edge(hom1[n1], hom1[n2]),\n C.get_edge(hom2[n1], hom2[n2]),\n 'intersection'))\n\n return A, Homomorphism(A, B, hom1), Homomorphism(A, C, hom2)\n\ndef pushout(h1, h2):\n \"\"\" Given h1 : A -> B; h2 : A -> C returns D, rh1, rh2\n with rh1 : B -> D; rh2 : C -> D and D the pushout\"\"\"\n\n if h1.source_ != h2.source_:\n raise ValueError(\n \"Domain of homomorphism 1 and domain of homomorphism 2 \" +\n \"don't match, can't do pushout\"\n )\n\n hom1 = {}\n hom2 = {}\n\n A = h1.source_\n B = h1.target_\n C = h2.target_\n D = type(B)()\n f = h1.mapping_\n g = h2.mapping_\n\n for n in C.nodes():\n D.add_node(n,\n C.node[n].type_,\n C.node[n].attrs_)\n hom2[n] = n\n\n for n in B.nodes():\n pred_n = keys_by_value(f, n)\n if len(pred_n) == 0:\n new_name = n\n i = 1\n while new_name in D.nodes():\n new_name = str(n) + str(i)\n i += 1\n D.add_node(new_name,\n B.node[n].type_,\n B.node[n].attrs_)\n hom1[n] = new_name\n else:\n hom1[n] = hom2[g[pred_n[0]]]\n D.add_node_attrs(hom1[n], B.node[n].attrs_)\n\n for (n1, n2) in C.edges():\n D.add_edge(n1, n2, C.get_edge(n1, n2))\n\n for (n1, n2) in B.edges():\n if (hom1[n1], hom1[n2]) in D.edges():\n D.add_edge_attrs(hom1[n1], hom1[n2], B.get_edge(n1, n2))\n else:\n D.add_edge(hom1[n1], hom1[n2], B.get_edge(n1, n2))\n\n return (D, Homomorphism(B, D, hom1), Homomorphism(C, D, hom2))\n\ndef pullback_complement(h1, h2):\n \"\"\" Given h1 : A -> B; h2 : B -> D returns C, rh1, rh2\n with rh1 : A -> C; rh2 : C -> D and C the pullback_complement.\n Doesn't work if h2 is not a matching\"\"\"\n\n if h1.target_ != h2.source_:\n raise ValueError(\n \"Codomain of homomorphism 1 and domain of homomorphism 2 \" +\n \"don't match, can't do pullback complement\"\n )\n\n if not h2.is_monic():\n raise ValueError(\n \"Second homomorphism is not monic, cannot find final pullback complement\"\n )\n\n A = h1.source_\n B = h1.target_\n D = h2.target_\n C = type(B)()\n f = h1.mapping_\n g = h2.mapping_\n\n hom1 = {}\n hom2 = {}\n\n A_D = Homomorphism.compose(h2, h1)\n\n DmB = D.sub(B, h2)\n\n for n in A.nodes():\n C.add_node(n,\n A.node[n].type_,\n A.node[n].attrs_)\n hom1[n] = n\n hom2[n] = g[f[n]]\n\n for n in DmB.nodes():\n is_in_A = False\n for n0 in A.nodes():\n if g[f[n0]] == n:\n is_in_A = True\n break;\n if not is_in_A:\n if DmB.node[n].type_ is None:\n C.add_node(n,\n None,\n DmB.node[n].attrs_)\n else:\n C.add_node(n,\n DmB.node[n].type_,\n DmB.node[n].attrs_)\n hom2[n] = n\n\n for n1 in C.nodes():\n for n2 in C.nodes():\n if n1 in A.nodes():\n if n2 in A.nodes():\n if (n1, n2) in A.edges():\n C.add_edge(n1,\n n2,\n A.get_edge(n1, n2))\n pred_n1 = keys_by_value(hom1, n1)[0]\n pred_n2 = keys_by_value(hom1, n2)[0]\n n11 = f[n1]\n n21 = f[n2]\n if ((g[n11], g[n21]) in D.edges() and\\\n (n11, n21) not in B.edges()):\n C.add_edge(n1,\n n2,\n D.get_edge(g[n11], g[n21]))\n else:\n if (A_D.mapping_[n1], n2) in D.edges():\n pred_n2 = keys_by_value(g, n2)\n if len(pred_n2) == 0 or\\\n (len(pred_n2)>0 and (pred_n2[0], f[n2]) not in B.edges()):\n C.add_edge(n1,\n n2,\n D.get_edge(A_D.mapping_[n1], n2))\n else:\n if n2 in A.nodes():\n if (n1, A_D.mapping_[n2]) in D.edges():\n pred_n1 = keys_by_value(g, n1)\n if len(pred_n1) == 0 or\\\n (len(pred_n1)>0 and (pred_n1[0], f[n2]) not in B.edges()):\n C.add_edge(n1,\n n2,\n D.get_edge(n1, A_D.mapping_[n2]))\n\n else:\n if (n1, n2) in D.edges():\n C.add_edge(n1,\n n2,\n D.get_edge(n1, n2))\n\n return C, Homomorphism(A, C, hom1), Homomorphism(C, D, hom2)\n","sub_path":"regraph/library/category_op.py","file_name":"category_op.py","file_ext":"py","file_size_in_byte":7522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"126065302","text":"#!/bin/python3\n\nimport sys\nimport itertools\n\ns_len = int(input().strip())\ns = input().strip()\n\n\ndef twocharacters(s):\n # takes s, converts to alternating string t, returns len(t)\n # number of deletions = num_characters -2\n # bf = delete every permutation of possible characters, check len(t), return max len t\n # bf2 =check every permutation of possible characters, check len(t)\n # loop through, delete every paired character, then permutethe rest\n # loop through, repeatedly deleting paired characters, then permute.\n\n # if there are no paired characters\n charset = set(list(s))\n max_len_t = 0\n for c1, c2 in itertools.combinations(charset, 2):\n s2 = []\n for char in s:\n if char == c1 or char == c2:\n s2.append(char)\n ok = True\n for i in range(len(s2) - 1):\n if s2[i] == s2[i + 1]:\n ok = False\n if ok and len(s2) > max_len_t:\n max_len_t = len(s2)\n return max_len_t\n\n\nprint(twocharacters(s))","sub_path":"hackerrank/strings/TwoCharacters.py","file_name":"TwoCharacters.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"592360367","text":"# 1- Import the packages\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pathlib2 import Path\nfrom os import path\n\n\n# 2- Read the image as grayscale\nhome_dir = Path.home()\ngoogle_data_dir = \"Google Drive\\OpenCV3ComputerVisionwithPythonCookbook_Code\\data\"\nimage = cv2.imread(filename=path.join(home_dir, google_data_dir, \"Lena - Copy.png\"),\n flags=0)\n\n# 3- Compute the gradient approximations using the Sobel operator\ndx = cv2.Sobel(src=image, ddepth=cv2.CV_32F, dx=1, dy=0)\ndy = cv2.Sobel(src=image, ddepth=cv2.CV_32F, dx=0, dy=1)\n\n# 4- Visualize the results\nplt.figure(figsize=(8,3))\nplt.subplot(131)\nplt.axis(\"off\")\nplt.title(\"image\")\nplt.imshow(image, cmap=\"gray\")\nplt.subplot(132)\nplt.axis(\"off\")\nplt.imshow(dx, cmap=\"gray\")\nplt.title(r\"$\\frac{dI}{dx}$\")\nplt.subplot(133)\nplt.axis(\"off\")\nplt.title(r\"$\\frac{dI}{dy}$\")\nplt.imshow(dy, cmap=\"gray\")\nplt.tight_layout()\nplt.show()","sub_path":"Python3/OpenCV 3 Computer Vision with Python Cookbook/2 - Matrices, Colors, and Filters/2.11 - Computing gradients using Sobel operator.py","file_name":"2.11 - Computing gradients using Sobel operator.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"639682857","text":"import os\nfrom app import app, db\nfrom flask import render_template, request, url_for, redirect, flash\nfrom app.models.tables import Inp\nfrom werkzeug.utils import secure_filename\n\n\n#configurations of upload\nALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'inp'])\n\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route(\"/\")\ndef index():\n\treturn render_template('index.html')\n\n\n@app.route(\"/registration\")\ndef registration():\n\treturn render_template('registration.html')\n\n\n@app.route(\"/register\", methods=['GET', 'POST'])\ndef register():\n\tif request.method == \"POST\":\n\t\t#-------------------------register information----------------------------#\n\t\tinp_name = request.form.get(\"inp_name\")\n\t\tdescription = request.form.get(\"description\")\n\t\tstart_date = request.form.get(\"start_date\")\n\t\tusername = request.form.get(\"username\")\n\t\tdefault = request.form.get(\"default\")\n\n\t\tif inp_name and description and start_date and username and default:\n\t\t\tif default == 'True':\n\t\t\t\tdefault = True\n\t\t\telse:\n\t\t\t\tdefault = False\n\n\t\t\tinp = Inp(inp_name, description, start_date, username, default)\n\t\t\tdb.session.add(inp)\n\t\t\tdb.session.commit()\n\n\t\t#-------------------------upload archive----------------------------#\n\t\tif 'file' not in request.files:\n\t\t\tflash('No file part')\n\t\t\treturn redirect(request.url)\n\n\t\tfile = request.files['file']\n\t\tif file.filename == '':\n\t\t\tflash('No selected file')\n\t\t\treturn redirect(request.url)\n\n\t\tif file and allowed_file(file.filename):\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n\n\treturn redirect(url_for(\"index\"))\n\n\n@app.route(\"/list\")\ndef list():\n\tinps = Inp.query.all()\n\treturn render_template(\"list.html\", inps=inps)\n\n\n@app.route(\"/exclude/\")\ndef exclude(id):\n\tinp = Inp.query.filter_by(id=id).first()\n\tdb.session.delete(inp)\n\tdb.session.commit()\n\n\tinps = Inp.query.all()\n\treturn render_template(\"list.html\", inps=inps)\n\n\n@app.route(\"/update/\", methods=['GET', 'POST'])\ndef update(id):\n\tinp = Inp.query.filter_by(id=id).first()\n\n\tif request.method == \"POST\":\n\t\tinp_name = request.form.get(\"inp_name\")\n\t\tdescription = request.form.get(\"description\")\n\t\tstart_date = request.form.get(\"start_date\")\n\t\tusername = request.form.get(\"username\")\n\t\tdefault = request.form.get(\"default\")\n\n\t\tif inp_name and description and start_date and username and default:\n\t\t\tinp.inp_name = inp_name\n\t\t\tinp.description = description\n\t\t\tinp.start_date = start_date\n\t\t\tinp.username = username\n\n\t\t\tif default == 'True':\n\t\t\t\tdefault = True\n\t\t\telse:\n\t\t\t\tdefault = False\n\n\t\t\tinp.default = default\n\n\t\t\tdb.session.commit()\n\n\t\t\treturn redirect(url_for(\"list\"))\n\n\treturn render_template(\"update.html\", inp=inp)","sub_path":"app/controllers/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"492629062","text":"from OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom math import *\nfrom numpy import *\nfrom sys import *\nfrom math import cos as cosine\nfrom math import sin as sinus\nfrom matrix import *\nfrom copy import *\n\nprint ('Lets start!\\n\\n')\n\ndef translate(dx,dy):\n global coords\n transformation = [[1, 0, 0],[0,1,0],[dx,dy,1]]\n coords = multiplyMatrix(transformation, coords)\n\ndef dilate(k):\n global coords\n transformation = [[k, 0, 0],[0,k,0],[0,0,1]]\n coords = multiplyMatrix(transformation,coords)\n\ndef rotate(deg,a,b):\n global coords\n\n baseTransformation = [[cosine(deg), sinus(deg), 0], [-sinus(deg), cosine(deg), 0], [0,0,1]]\n p1 = [[1,0,0],[0,1,0],[a + 249,b + 249,1]]\n p2 = [[1, 0, 0], [0, 1, 0], [-a -249, -b - 249, 1]]\n\n coords = multiplyMatrix(multiplyMatrix(multiplyMatrix(p1, baseTransformation), p2), coords)\n\ndef reflectX(x):\n t = x + 249\n if (t > 249):\n translate(0, -t)\n elif(t +0< 249):\n translate(0, t+0)\n else:\n return\n global coords\n transformation = [[1, 0, 0],[0, -1, 0],[0,0,1]]\n coords = multiplyMatrix(transformation, coords)\n\n if (t +0> 249):\n translate(0, t+0)\n elif (t +0< 249):\n translate(0, -t+0)\n\ndef reflectY(t):\n t = t + 249\n if (t + 0 > 249):\n translate(-t+0, 0)\n elif(t + 0< 249):\n translate(t-0, 0)\n else:\n return\n global coords\n transformation = [[-1, 0, 0],[0, 1, 0],[0,0,1]]\n coords = multiplyMatrix(transformation, coords)\n\n if (t +0 > 249):\n translate(t-0, 0)\n elif (t +0 < 249):\n translate(-t+0, 0)\n\n\ndef reflect(x, y):\n global coords\n\n if (x == 0 and y == 0):\n t = [[-1,0,0],[0,-1,0],[0,0,1]]\n coords = multiplyMatrix(t, coords)\n translate(2 * 249, 2 * 249)\n return\n reflectX(x)\n reflectY(y)\n\n\ndef shear(axis, m):\n global coords\n if (axis == \"y\" or axis == \"Y\"):\n transformation = [[1, m, 0], [0,1,0],[0,0,-249]*m]\n coords = multiplyMatrix(transformation, coords)\n elif (axis == \"x\" or axis == \"X\"):\n transformation = [[1, 0, 0], [m, 1, 0], [0, 0, -249*m]]\n coords = multiplyMatrix(transformation, coords)\n else:\n print(\"Error: invalid axis\")\n\ndef stretch(axis, k):\n global coords\n if (axis == \"y\" or axis == \"Y\"):\n transformation = [[1, 0, 0], [0, k, 0], [0, 0, 1]]\n coords = multiplyMatrix(transformation, coords)\n elif (axis == \"x\" or axis == \"X\"):\n transformation = [[k, 0, 0], [0, 1, 0], [0, 0, 1]]\n coords = multiplyMatrix(transformation, coords)\n else:\n print(\"Error: invalid axis\")\n\ndef custom(a,b,c,d):\n global coords\n transformation = [[a,c,0],[b,d,0],[0,0,1]]\n coords = multiplyMatrix(transformation, coords)\n\ndef multiple():\n global segi\n global coords\n global initcoords\n\n n = int(input(\"Number of command > \"))\n\n op = []\n for i in range(n):\n cmd = input(\"Command \" + str(i) + \" : \")\n if cmd == \"multiple\":\n print(\"Cannot do multiple command inside a multiple command\")\n else:\n op += [cmd]\n\n for i in op:\n opr = []\n for field in i.split():\n opr.append(field)\n wrongCommand = False\n\n if opr[0] == \"translate\":\n if (len(opr) == 3):\n (translate(float(opr[1]), float(opr[2]))) # (dx, dy)\n else:\n wrongCommand = True\n elif opr[0] == \"dilate\":\n if (len(opr) == 2):\n dilate(float(opr[1]))\n else:\n wrongCommand = True\n elif opr[0] == \"rotate\":\n if len(opr) == 4:\n rotate(float(opr[1]), float(opr[2]), float(opr[3])) # (deg, x, y)\n else:\n wrongCommand = True\n elif opr[0] == \"reflect\":\n if len(opr) == 3:\n reflect(float(opr[1]), float(opr[2])) # (x, y)\n else:\n wrongCommand = True\n elif opr[0] == \"shear\":\n if len(opr) == 3:\n shear(opr[1], float(opr[2])) # (axis, factor)\n else:\n wrongCommand = True\n elif opr[0] == \"stretch\":\n if len(opr) == 3:\n stretch(opr[1], float(opr[2])) # (axis, factor)\n else:\n wrongCommand = True\n elif opr[0] == \"custom\":\n if len(opr) == 5:\n custom(int(opr[1]), int(opr[2]), int(opr[3]), int(opr[4]))\n else:\n wrongCommand = True\n\n elif opr[0] == \"multiple\":\n multiple()\n elif opr[0] == \"reset\":\n coords = reset(initcoords)\n elif opr[0] == \"exit\":\n sys.exit()\n else:\n print(\"Maaf, masukan operasi salah\")\n\n if wrongCommand:\n print(\"Error: not enough arguments\")\n\ndef reset(initcoords):\n global coords\n coords = deepcopy(initcoords)\n\ndef operate(segi,coords, initcoords):\n opr = []\n operation = input(\"Masukkan operasi yang ingin dilakukan: \")#.split()\n for field in operation.split():\n opr.append(field)\n wrongCommand = False\n\n if opr[0] == \"translate\":\n if (len(opr) == 3):\n (translate(float(opr[1]), float(opr[2]))) #(dx, dy)\n else:\n wrongCommand = True\n elif opr[0] == \"dilate\":\n if (len(opr) == 2):\n dilate(float(opr[1]))\n else:\n wrongCommand = True\n elif opr[0] == \"rotate\":\n if len(opr) == 4:\n rotate(float(opr[1]), float(opr[2]), float(opr[3])) #(deg, x, y)\n else:\n wrongCommand = True\n elif opr[0] == \"reflect\":\n if len(opr) == 3:\n reflect(float(opr[1]), float(opr[2])) #(x, y)\n else:\n wrongCommand = True\n elif opr[0] == \"shear\":\n if len(opr) == 3:\n shear(opr[1], float(opr[2])) #(axis, factor)\n else:\n wrongCommand = True\n elif opr[0] == \"stretch\":\n if len(opr) == 3:\n stretch(opr[1],float(opr[2])) #(axis, factor)\n else:\n wrongCommand = True\n elif opr[0] == \"custom\":\n if len(opr) == 5:\n custom(int(opr[1]),int(opr[2]),int(opr[3]),int(opr[4]))\n else:\n wrongCommand = True\n elif opr[0] == \"multiple\":\n multiple()\n elif opr[0] == \"reset\":\n reset(initcoords)\n elif opr[0] == \"exit\":\n sys.exit()\n else:\n print (\"Maaf, masukan operasi salah\")\n\n if wrongCommand:\n print(\"Error: not enough arguments\")\n\n#Class yang menyimpan pasangan koordinat(x,y), akan digunakan pada array of vertex\n# class Vertex:\n# def __init__(self,x,y):\n# self.x = x\n# self.y = y\n\ndef drawShape(segi, coords):\n glBegin(GL_LINE_LOOP) # start drawing a rectangle\n for z in range(segi):\n glVertex3f(coords[z][0], coords[z][1], 0) # bottom left point\n glEnd()\n\n\ndef refresh2d(width, height):\n glViewport(0, 0, width, height)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glOrtho(0.0, width, 0.0, height, 0.0, 1.0)\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n\ndef draw(): # ondraw is called all the time\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # clear the screen\n glLoadIdentity() # reset position\n refresh2d(width, height) # set mode to 2d\n\n glColor3f(1.0, 1.0, 1.0) # set color to blue\n drawShape(segi, coords) # rect at (10, 10) with width 200, height 100\n\n glColor3f(1.0, 0.0, 0.0) # set color to blue\n drawShape(2, [[0,250,1],[499,250,1]])\n drawShape(2, [[250, 0, 1], [250, 499, 1]])\n # glBegin(GL_POLYGON)\n glutSwapBuffers() # important for double buffering\n\n#==================================================================================================\n#==================================================================================================\n#==================================================================================================\n\n\n\n#Meminta masukan jumlah vertex (yang menentukan segi berapa)\nsegi = int(input(\"Masukkan segi berapa yang ingin diolah: \"))\n\n#Inisialisasi array of vertex & meminta input koordinat bidang\ncoords = [None]*segi\nfor z in range(segi):\n x = int(input(\"Masukkan koordinat x untuk simpul \"+ str(z) +\": \"))\n y = int(input(\"Masukkan koordinat y untuk simpul \"+ str(z) +\": \"))\n coords[z] = [x + 249, y + 249, 1]\n\n# print(coords)\nfor v in coords:\n print(\" [\" + str(v[0]-249) + \",\" + str(v[1]-249) + \"] \"),\n# initcoords = [None]*segi\n# for z in range(segi):\n# \tinitcoords[z] = Vertex(coords[z].x,coords[z].y)\ninitcoords = deepcopy(coords)\n#Menggambar pada OpenGL\n\nwindow = 0 # glut window number\nwidth, height = 500, 500 # window size\n\n# initialization\nglutInit() # initialize glut\nglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)\nglutInitWindowSize(width, height) # set window size\nglutInitWindowPosition(0, 0) # set window position\nwindow = glutCreateWindow(b\"AllGeo\") \t # create window with title\ndraw()\n\n#Melakukan operasi\nloop = True\n\nwhile(loop):\n operate(segi,coords, initcoords)\n for v in coords:\n print(\" [\" + str(v[0] - 249) + \",\" + str(v[1] - 249) + \"] \"),\n draw()\n\n\n# def convertVertexToList(segi, v):\n# aColum ={None]}\n# for z in range(segi):\n\n\n# def translate(segi,coords,dx,dy):\n# \tfor z in range(segi):\n# \t\tcoords[z].x += dx\n# \t\tcoords[z].y += dy\n# \treturn (coords)\n#\n# def dilate(segi,coords,k):\n# for z in range(segi):\n# coords[z].x *= k\n# coords[z].y *= k\n# return (coords)\n\n# def translate(segi,coords,dx,dy):\n# for i in range(segi):\n# for j in range(len(coords[i])):\n# coords[i][j] += dx\n# coords[i][j] += dy\n#\n# return (coords)\n\n# def dilate(segi,coords,k):\n# for i in range(segi):\n# for j in range(len(coords[i])):\n# coords[i][j] *= k\n# coords[i][j] *= k\n#\n# return (coords)\n\n# def reset(segi,coords,initcoords):\n# for z in range(segi):\n# coords[z].x = initcoords[z].x\n# coords[z].y = initcoords[z].y\n# return (coords)\n\n# def reset(segi,coords,initcoords):\n# for i in range(segi):\n# for j in range(len(coords[i])):\n# coords[i][j] = initcoords[i][j]\n# coords[i][j] = initcoords[i][j]\n#\n# return(initcoords[:])","sub_path":"src/algeo.py","file_name":"algeo.py","file_ext":"py","file_size_in_byte":10521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"124268039","text":"# script to search through a directory of code (text?) documents and return list/json array of items with refs\nfrom utils import args, query\n\ndef main():\n \"\"\" Entrypoint, takes args for keywords \"\"\"\n sysVars = args.argPairs()\n # print(sysVars)\n # args gathered and valid\n if(sysVars[\"Debug\"] == True):\n debug(sysVars)\n query.query(sysVars)\n\n# tofix\ndef debug(args):\n import cProfile\n cProfile.run(query.query(args))\n\nif __name__ == \"__main__\":\n \"\"\" This is executed when run from the command line \"\"\"\n main()\n\n","sub_path":"py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"350649559","text":"\"\"\"\nConvert DNA sequences to RNA.\n\"\"\"\ndef rna(seq):\n \"\"\"Convert DNA sequence to RNA sequence.\"\"\"\n\n #Determine is original sequence was uppercase\n seq_upper = seq.isupper()\n\n #Convert the sequence to lowercase\n seq = seq.lower()\n\n #Swap out 't' for 'u'\n seq = seq.replace('t', 'u')\n\n #Return upper or lower, depending on input\n if seq_upper:\n return seq.upper()\n else:\n return seq\n\ndef reverse_rna_complement(seq):\n \"\"\"Convert DNA sequence into it's reverse complement as RNA\"\"\"\n\n #Determine is original sequence was uppercase\n seq_upper = seq.isupper()\n\n #Reverse the sequence\n seq = seq[::-1]\n\n #Convert to uppercase\n seq = seq.upper()\n\n #Compute complement\n seq = seq.replace('A', 'u')\n seq = seq.replace('T', 'a')\n seq = seq.replace('G', 'c')\n seq = seq.replace('C', 'g')\n\n #Return in appropriate case\n if seq_upper:\n return seq.upper()\n else:\n return seq\n","sub_path":"dnatorna.py","file_name":"dnatorna.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"336454543","text":"import urllib.request\n\n\n###\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nimport matplotlib.dates as mdates\nimport numpy as np\n###\n\n\n\n\n\ndef grabQuandl(ticker):\n\n netIncomeAr = []\n revAr = []\n ROCAr = []\n \n \n# endLink = 'sort_order=asc'\n datacolumn = 'column_index=4'\n authkey = '&api_key=verQEVug7z8nVnKFfyxp'\n try:\n urlAttempt = 'https://www.quandl.com/api/v3/datasets/WIKI/'+ticker+'.json?'+datacolumn+authkey\n\n\n incomeDate, income = np.loadtxt(netIncomeAr, delimiter=',', unpack=True,\n converters={ 0: mdates.strpdate2num('%Y-%m-%d')})\n\n \n fig = plt.figure()\n ax1 = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=4)\n ax1.plot(incomeDate,income)\n plt.show()\n \n\n\n except (IOError, ValueError):\n print('An I/O error or a ValueError occurred')\n\ngrabQuandl('YHOO')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"193435727","text":"#!/usr/bin/env python3\n\n\"\"\" OpenWeatherMap (экспорт)\n\nСделать скрипт, экспортирующий данные из базы данных погоды, \nсозданной скриптом openweather.py. Экспорт происходит в формате CSV или JSON.\n\nСкрипт запускается из командной строки и получает на входе:\n export_openweather.py --csv filename [<город>]\n export_openweather.py --json filename [<город>]\n export_openweather.py --html filename [<город>]\n \nПри выгрузке в html можно по коду погоды (weather.id) подтянуть \nсоответствующие картинки отсюда: http://openweathermap.org/weather-conditions\n\nЭкспорт происходит в файл filename.\n\nОпционально можно задать в командной строке город. В этом случае \nэкспортируются только данные по указанному городу. Если города нет в базе -\nвыводится соответствующее сообщение.\n\n\"\"\"\n\nimport csv\nimport json\nimport sqlite3\nimport sys\nimport getopt\n\nDB_FILE = 'temp_data.db'\n\n\ndef export_json(data, filename='out.json'):\n try:\n with open(filename, 'w') as j_out:\n j_out.writelines('\\n'.join([json.dumps(row) for row in data]))\n except OSError:\n print('Ошибка записи в файл')\n sys.exit(1)\n\ndef export_csv(data, filename='out.csv'):\n try:\n with open(filename, 'w') as csv_out:\n fields = ['city_id', 'city_name', 'date', 'temp', 'weather_id']\n csv_writer = csv.DictWriter(csv_out, fields)\n csv_writer.writeheader()\n for row in data:\n csv_writer.writerow(row)\n except OSError:\n print('Ошибка записи в файл')\n sys.exit(1)\n\ndef export_html(data, filename='out.html'):\n print('Экспорт в html не реализован.')\n\ndef check_opts(opts):\n for opt in opts:\n if opt[0] in ['--json', '--csv', '--html']:\n return True\n return False\n\ndef usage():\n return 'Usage: {} --json | --csv | --html [city_name]'.format(sys.argv[0])\n\n\ndata = []\ntry:\n opts, args = getopt.getopt(sys.argv[1:], '', ['json=', 'csv=', 'html='])\nexcept getopt.GetoptError:\n print(usage())\n sys.exit(1)\n\nif len(args) > 1 or not check_opts(opts):\n print(usage())\n sys.exit(1)\n\ntry:\n with sqlite3.connect(DB_FILE) as conn:\n cur = conn.cursor()\n if args:\n cur.execute(\"SELECT * FROM temp_data WHERE city_name=?\", (args[0], ))\n else:\n cur.execute(\"SELECT * FROM temp_data\")\n for row in cur:\n data.append({\n 'city_id': row[0],\n 'city_name': row[1],\n 'date': row[2],\n 'temp': row[3],\n 'weather_id': row[4]\n })\nexcept Exception as e:\n print(e)\n\nfor opt in opts:\n if opt[0] == '--json':\n export_json(data, opt[1])\n if opt[0] == '--csv':\n export_csv(data, opt[1])\n if opt[0] == '--html':\n export_html(data, opt[1])\n\n","sub_path":"lesson08/home_work/export_openweather.py","file_name":"export_openweather.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"280134948","text":"import pytest\nimport os\nimport urllib\nfrom subprocess import Popen\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\nBROWSERSTACK_API = 'hub.browserstack.com:80/wd/hub'\n\n\"\"\" See http://www.browserstack.com/automate/capabilities \"\"\"\nBROWSERS = [\n {'browserName': 'chrome'},\n {'browserName': 'firefox'},\n {'browserName': 'safari'},\n {'browserName': 'internet_explorer'}\n]\n\nUSER = {\n \"SUPERUSER\": \"F3rRTqyfQg\",\n \"FACULTY\" : \"mHxyyRfvO7\",\n \"STUDENT\" : \"B3yGtjkIFz\"\n}\n\n@pytest.fixture(scope=\"module\")\ndef tunnel(request):\n if not (request.config.getoption('--local') and\n request.config.getoption('--key')):\n return False\n \n filedir = os.path.dirname(os.path.realpath(__file__))\n jar = filedir + '/BrowserStackTunnel.jar'\n \n ''' Synchronously downloads the jar file if it doesn't already exist. '''\n if not os.path.isfile(jar):\n download =\\\n urllib.urlopen('http://www.browserstack.com/BrowserStackTunnel.jar')\n with open(jar, 'wb') as out:\n out.write(download.read())\n \n \"\"\"Starts a tunnel to the local server\"\"\"\n key = request.config.getoption('--key')\n host = request.config.getoption('--host')\n port = request.config.getoption('--port')\n ssl = request.config.getoption('--ssl')\n link = Popen(['java', '-jar', jar, key, \n ','.join([ str(host),str(port),str(int(ssl)) ]) ])\n def fin():\n link.terminate()\n request.addfinalizer(fin)\n\ndef pytest_generate_tests(metafunc):\n if 'browser' in metafunc.fixturenames:\n browser_list = metafunc.config.option.browsers or BROWSERS\n metafunc.parametrize('browser', browser_list, indirect=True)\n\n\"\"\"\n Creates a driver based on one of the passed in browser dictionaries from\n the BROWSERS array. If a key is an argument, uses Browserstack to run tests\n\"\"\"\n@pytest.fixture\ndef browser(request, tunnel):\n key = request.config.getoption('--key')\n driver = None\n if key is not None:\n url = 'http://www-data:' + key + '@' + BROWSERSTACK_API\n desired = {'acceptSslCerts': True, 'browserstack.tunnel': True}\n desired.update(request.param)\n driver = webdriver.Remote(command_executor=url,\n desired_capabilities=desired)\n else:\n name = request.param['browserName']\n driver = None\n if name == 'internet_explorer':\n name = 'ie'\n elif name.lower() == 'phantomjs':\n name = 'PhantomJS'\n cli_args.append('--ignore-ssl-errors=yes')\n cli_args = []\n driver = getattr(webdriver, name)(service_args=cli_args)\n else:\n name = name.capitalize()\n driver = getattr(webdriver, name)()\n \n def fin():\n driver.close()\n request.addfinalizer(fin)\n \n host = request.config.getoption('--host')\n def login(self, user):\n \"\"\" In a given browser, logs the given user in. This is a method\n on the browser object.\n \n Keyword Arguments\n user -- a user's NetID (see USERS dictionary)\n \"\"\"\n self.get(host) # if we don't go here, we get a cross-domain error\n login_url = host + '/api/v2/account/login/authUser';\n logout_url = host + '/api/v2/account/logout';\n script = '\\\n ;(function(){var xhr = new XMLHttpRequest(); \\\n xhr.open(\"GET\", \"' + logout_url + '\", false); \\\n xhr.send(); \\\n var xhr = new XMLHttpRequest(); \\\n xhr.open(\"GET\", \"' + login_url + '\", false);\\\n xhr.setRequestHeader(\"Authorization\", \"'+ user +'\");\\\n xhr.send();})();'\n self.execute_script(script)\n \n import types\n driver.login = types.MethodType(login, driver)\n return driver\n\n@pytest.fixture\ndef host(request):\n return request.config.getoption('--host')\n\ndef pytest_addoption(parser):\n \n ''' creates a list of dictionaries akin to the BROWSERS element '''\n parser.addoption(\"--browsers\", metavar=\"BROWSERS\", action=\"store\",\n default=None,\n type=lambda x: [dict([('browserName',b)]) for b in x.lower().split(',')],\n help=\"List of browsers separated by commas.\")\n\n parser.addoption(\"--host\", metavar=\"TESTING_HOSTNAME\", action='store',\n default='https://milo.byu.edu', type=str, help=\"The hostname to run on.\")\n \n parser.addoption(\"--ssl\", metavar=\"LOCAL_SSL\", action='store', default=True,\n type=bool, help=\"Whether or not local host is run over SSL. Used in\\\n conjunction with --local and --key. Defaults to true.\")\n \n parser.addoption(\"--port\", metavar=\"LOCAL_PORT\", action='store', default=443,\n type=int, help=\"The port of the local website, tested remotely. Used in\\\n conjunction with --local and --key. Defaults to 443.\")\n \n parser.addoption(\"--local\", metavar=\"IS_LOCAL\", action='store',\n default=True, type=bool,\n help=\"For remote testing. Whether or not the host is local. \\\n Defaults to True. Only matters if --key is set.\")\n\n parser.addoption(\"--key\", metavar=\"BROWSERSTACK_API_KEY\", action='store',\n default=None, type=str,\n help=\"Your Browserstack key. If empty, runs locally.\\n \\\n if you don't have this, you can get it from \\\n https://www.browserstack.com/accounts/automate\")\n","sub_path":"test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"488691052","text":"\nimport numpy\nfrom collections import OrderedDict\n\nclass LensIdeal(object):\n\n def __init__(self, name=\"LensIdeal\", focal_x=0.0, focal_z=0.0, p=0.0, q=0.0):\n self._focal_x = focal_x\n self._focal_z = focal_z\n self._name = name\n self._p = p\n self._q = q\n\n def get_focalX(self):\n return self._focal_x\n\n def get_focalZ(self):\n return self._focal_z\n\n def to_dictionary(self):\n #returns a dictionary with the variable names as keys, and a tuple with value, unit and doc string\n mytuple = [ (\"focal_x\" ,( self._focal_x ,\"m\", \"Ideal lens focal length (horizontal)\" ) ),\n (\"focal_y\" ,( self._focal_y ,\"m\", \"Ideal lens focal length (vertical)\" ) )]\n return(OrderedDict(mytuple))\n\n def trace_beam(self,beam1):\n beam = beam1.duplicate()\n\n\n if self._p != 0.0:\n beam.retrace(self._p,resetY=True)\n\n # rotate around Z\n if self._focal_x != 0.0:\n # whatch out the minus!!\n tan_two_theta = - beam.get_column(1) / self._focal_x\n beam.rotate(numpy.arctan(tan_two_theta),axis=3,rad=True)\n\n # rotate around X\n if self._focal_z != 0.0:\n tan_two_theta = beam.get_column(3) / self._focal_z\n beam.rotate(numpy.arctan(tan_two_theta),axis=1,rad=True)\n\n if self._q != 0.0:\n beam.retrace(self._q,resetY=True)\n\n return beam\n\nclass LensSuperIdeal(object):\n\n def __init__(self, name=\"LensIdeal\", focal_p_x=0.0, focal_p_z=0.0,\n focal_q_x=0.0, focal_q_z=0.0,\n p=0.0, q=0.0):\n self._focal_p_x = focal_p_x\n self._focal_p_z = focal_p_z\n self._focal_q_x = focal_q_x\n self._focal_q_z = focal_q_z\n self._name = name\n self._p = p\n self._q = q\n\n # def get_focalX(self):\n # return self._focal_x\n #\n # def get_focalZ(self):\n # return self._focal_z\n #\n # def to_dictionary(self):\n # #returns a dictionary with the variable names as keys, and a tuple with value, unit and doc string\n # mytuple = [ (\"focal_x\" ,( self._focal_x ,\"m\", \"Ideal lens focal length (horizontal)\" ) ),\n # (\"focal_y\" ,( self._focal_y ,\"m\", \"Ideal lens focal length (vertical)\" ) )]\n # return(OrderedDict(mytuple))\n\n def trace_beam(self,beam1):\n beam = beam1.duplicate()\n\n\n if self._p != 0.0:\n beam.retrace(self._p,resetY=True)\n\n # rotate around Z; watch out the minus!!\n if self._focal_p_x != 0.0:\n tan_theta_p = - beam.get_column(1) / self._focal_p_x\n else:\n tan_theta_p = 0.0\n\n if self._focal_q_x != 0.0:\n tan_theta_q = - beam.get_column(1) / self._focal_q_x\n else:\n tan_theta_q = 0.0\n\n two_theta = numpy.arctan(tan_theta_p) + numpy.arctan(tan_theta_q)\n beam.rotate(two_theta,axis=3,rad=True)\n\n # rotate around X\n if self._focal_p_z != 0.0:\n tan_theta_p = beam.get_column(3) / self._focal_p_z\n else:\n tan_theta_p = 0.0\n\n if self._focal_q_z != 0.0:\n tan_theta_q = beam.get_column(3) / self._focal_q_z\n else:\n tan_theta_q = 0.0\n\n two_theta = numpy.arctan(tan_theta_p) + numpy.arctan(tan_theta_q)\n beam.rotate(two_theta,axis=1,rad=True)\n\n if self._q != 0.0:\n beam.retrace(self._q,resetY=True)\n\n return beam\n\ndef test_with_collimated_beam():\n\n\n from SourceGaussian import SourceGaussian\n from Beam import Beam\n from Shadow.ShadowTools import plotxy\n\n src = SourceGaussian.initialize_collimated_source(number_of_rays=10000,sigmaX=1e-6,sigmaZ=1e-6)\n\n beam = Beam()\n\n beam.genSource(src)\n\n print(beam.info())\n SX, SZ = (1e6*beam.get_standard_deviation(1),1e6*beam.get_standard_deviation(3))\n\n plotxy(beam.get_shadow3_beam(),1,3,nbins=100,title=\"SOURCE\")\n\n lens1 = LensIdeal(\"test\",focal_x=10.0,focal_z=10.0,p=100.0,q=10.0)\n\n method = 2 # 0:direct, 1:interface with overwrite, 2: no overwrite\n if method == 0:\n beam2 = lens1.trace_beam(beam)\n elif method == 1:\n beam.traceOE(lens1,1,overwrite=True)\n beam2 = beam\n elif method == 2:\n beam2 = beam.traceOE(lens1,1,overwrite=True)\n else:\n raise Exception(\"Undefined method\")\n\n #\n\n plotxy(beam2.get_shadow3_beam(),1,3,nbins=100,title=\"FOCAL PLANE\")\n FX, FZ = (1e6*beam2.get_standard_deviation(1),1e6*beam2.get_standard_deviation(3))\n print(\"Source dimensions: %f %f um\"%(SX,SZ))\n print(\"Focal dimensions: %f %f um\"%(FX,FZ))\n print(\"Demagnification: %g %g\"%(SX/FX,SX/FZ))\n\n\ndef test_with_divergent_beam():\n\n from SourceGaussian import SourceGaussian\n from SourceGridCartesian import SourceGridCartesian\n from Beam import Beam\n from Shadow.ShadowTools import plotxy\n\n src = SourceGaussian.initialize_from_keywords(number_of_rays=100000,\n sigmaX= 20e-6/2.35,sigmaZ= 10e-6/2.35,\n sigmaXprime=50e-6/2.35,sigmaZprime=10e-6/2.35)\n\n # src = SourceGridCartesian.initialize_point_source(\n # direction_space = [2*numpy.arccos(numpy.pi/4),2*numpy.arccos(numpy.pi/4)],\n # direction_space_points = [20, 20],\n # direction_space_center = [0.0, 0.0] )\n\n beam = Beam()\n\n beam.genSource(src)\n\n # point source\n beam.set_column(1,0.0)\n beam.set_column(3,0.0)\n\n print(beam.info())\n SX, SZ = (1e6*beam.get_standard_deviation(1),1e6*beam.get_standard_deviation(3))\n\n plotxy(beam.get_shadow3_beam(),4,6,nbins=100,title=\"SOURCE DIVERGENCES\")\n\n beam_tmp = beam.duplicate()\n beam_tmp.retrace(100.0)\n plotxy(beam_tmp.get_shadow3_beam(),1,3,nbins=100,title=\"SOURCE AFTER 10m\")\n # plotxy(beam.get_shadow3_beam(),1,4,nbins=100,title=\"SOURCE PHASE SPACE\")\n\n # p = 30\n # q = 5.0\n p = 10.0\n q = 10.0\n F = 1.0 / (1/p + 1/q)\n # lens1 = LensIdeal(\"test1\",focal_x=F,focal_z=F,p=p,q=q)\n lens1 = LensSuperIdeal(\"test1\",focal_p_x=p,focal_p_z=p,focal_q_x=q,focal_q_z=q,p=p,q=q)\n\n # p = 5.0\n # q = 30\n # F = 1.0 / (1/p + 1/q)\n # lens2 = LensIdeal(\"test2\",focal_x=F,focal_z=F,p=p,q=q)\n\n method = 2 # 0:direct, 1:interface with overwrite, 2: no overwrite\n if method == 0:\n beam2 = lens1.trace_beam(beam)\n elif method == 1:\n beam.traceOE(lens1,1,overwrite=True)\n beam2 = beam\n elif method == 2:\n beam2 = beam.traceOE(lens1,1,overwrite=True)\n # beam2 = beam.traceOE(lens2,2,overwrite=True)\n else:\n raise Exception(\"Undefined method\")\n\n #\n\n X = beam2.get_column(1)\n Y = beam2.get_column(3)\n print(\"X: \",X.min(),X.max(),X.std())\n print(\"Y: \",Y.min(),Y.max(),Y.std())\n # from srxraylib.plot.gol import plot_scatter\n # plot_scatter(X,Y)\n\n\n plotxy(beam2.get_shadow3_beam(),1,3,nbins=100,title=\"FOCAL PLANE\",xrange=[-5e-9,5e-9],yrange=[-5e-9,5e-9])\n # plotxy(beam2.get_shadow3_beam(),1,4,nbins=100,title=\"FOCAL PLANE PHASE SPACE\")\n\n FX, FZ = (1e6*beam2.get_standard_deviation(1),1e6*beam2.get_standard_deviation(3))\n print(\"Source dimensions (rms): %f %f um\"%(SX,SZ))\n print(\"Focal dimensions (rms): %f %f um\"%(FX,FZ))\n print(\"Demagnification: H:%g V:%g (theoretical: %g) \"%(SX/FX,SZ/FZ,p/q))\n\n\n\ndef get_sigmas_radiation(photon_energy,undulator_length):\n import scipy.constants as codata\n lambdan = 1e-10 * codata.h*codata.c/codata.e*1e10 / photon_energy # in m\n print(\"wavelength in m\",lambdan)\n return 1e6*2.740/4/numpy.pi*numpy.sqrt(lambdan*undulator_length),1e6*0.69*numpy.sqrt(lambdan/undulator_length)\n\ndef test_id16ni():\n\n from minishadow.source_geometrical.gaussian import SourceGaussian\n from minishadow.beam.beam import Beam\n from Shadow.ShadowTools import plotxy\n\n\n ESRF = {'sigmaX':387.8,\"sigmaZ\":3.5,\"sigmaX'\":10.3,\"sigmaZ'\":1.2}\n EBS = {'sigmaX':27.2, \"sigmaZ\":3.4,\"sigmaX'\":5.2,\"sigmaZ'\":1.4}\n m = ESRF\n\n photon_energy = 17000.0\n undulator_length = 1.4\n\n\n\n sr,srp = get_sigmas_radiation(photon_energy,undulator_length)\n\n print(\"radiation sigmas: \",sr,srp)\n\n demagX = [2.42,2899]\n demagZ = 1849\n\n\n\n #\n f2dot35 = 2*numpy.sqrt(2*numpy.log(2))\n\n sx,sz,sxp,szp = m['sigmaX'],m['sigmaZ'],m[\"sigmaX'\"],m[\"sigmaZ'\"]\n\n Sx = 1e-6 * numpy.sqrt( sx**2 + sr**2)\n Sz = 1e-6 * numpy.sqrt( sz**2 + sr**2)\n Sxp = 1e-6 * numpy.sqrt( sxp**2 + srp**2)\n Szp = 1e-6 * numpy.sqrt( szp**2 + srp**2)\n\n print(\"Gaussian source dimensions (rms) x z x' z'\",1e6*Sx,1e6*Sz,1e6*Sxp,1e6*Szp)\n print(\"Gaussian source dimensions (FWHM) x z x' z'\",f2dot35*1e6*Sx,f2dot35*1e6*Sz,f2dot35*1e6*Sxp,f2dot35*1e6*Szp)\n\n src = SourceGaussian.initialize_from_keywords(number_of_rays=500000,\n sigmaX=Sx,sigmaZ=Sz,\n sigmaXprime=Sxp,sigmaZprime=Szp)\n\n # src = SourceGaussian.initialize_from_keywords(number_of_rays=10000,\n # sigmaX= 1000e-6/2.35,sigmaZ= 10e-6/2.35,\n # sigmaXprime=30e-6/2.35,sigmaZprime=15e-6/2.35)\n beam = Beam()\n\n beam.genSource(src)\n\n # point source\n # beam.set_column(1,0.0)\n # beam.set_column(3,0.0)\n # beam.set_column(4,0.0)\n # beam.set_column(5,1.0)\n # beam.set_column(6,0.0)\n\n print(beam.info())\n SX, SZ = (1e6*beam.get_standard_deviation(1),1e6*beam.get_standard_deviation(3))\n\n # plotxy(beam.get_shadow3_beam(),1,4,nbins=100,title=\"SOURCE H phase space\")\n plotxy(beam.get_shadow3_beam(),1,3,nbins=100)\n\n # multilayer\n p = 28.3\n q = 11.70\n F = 1/(1/p+1/q)\n lens1 = LensIdeal(\"ML\",focal_x=F,focal_z=0,p=p,q=q)\n # lens1 = LensSuperIdeal(\"ML\",focal_p_x=p,focal_q_x=q,focal_p_z=0,focal_q_z=0,p=p,q=q)\n beam.traceOE(lens1,1,overwrite=True)\n\n # plotxy(beam.get_shadow3_beam(),1,4,nbins=100,title=\"H phase space\")\n # plotxy(beam.get_shadow3_beam(),3,6,nbins=100,title=\"V phase space\")\n\n\n FX, FZ = (1e6*beam.get_standard_deviation(1),1e6*beam.get_standard_deviation(3))\n print(\"----------------- Secondary source---------------------\")\n print(\"Source dimensions (rms): %f %f um\"%(SX,SZ))\n print(\"Focal dimensions (rms): %f %f um\"%(FX,FZ))\n print(\"Focal dimensions (2.35*rms): %f %f um\"%(f2dot35*FX,f2dot35*FZ))\n print(\"Demagnification: H:%g V:%g (theoretical: %g) \"%(SX/FX,SZ/FZ,p/q))\n\n\n # first KB mirror\n p = 144.90\n q = 0.025\n F = 1.0/(1/184.90+1/0.10)\n lens2 = LensIdeal(\"KBV\",focal_x=0,focal_z=F,p=p,q=q)\n # lens2 = LensSuperIdeal(\"KBV\",focal_p_x=0,focal_q_x=0,focal_p_z=184.90,focal_q_z=0.10,p=p,q=q)\n beam.traceOE(lens2,1,overwrite=True)\n\n # second KB mirror\n p = 0.025\n q = 0.05\n F = 1.0/(1/144.95+1/0.05)\n lens3 = LensIdeal(\"KBH\",focal_x=F,focal_z=0,p=p,q=q)\n # lens3 = LensSuperIdeal(\"KBH\",focal_p_x=144.95,focal_q_x=0.05,focal_p_z=0,focal_q_z=0,p=p,q=q)\n beam.traceOE(lens3,1,overwrite=True)\n\n\n #\n\n tkt = plotxy(beam.get_shadow3_beam(),1,3,nbins=300,xrange=[-0.0000005,0.0000005],yrange=[-0.0000005,0.0000005],title=\"FOCAL PLANE\")\n\n print(tkt['fwhm_h'],tkt['fwhm_v'])\n\n FX, FZ = (1e6*beam.get_standard_deviation(1),1e6*beam.get_standard_deviation(3))\n print(\"----------------- Focal position ---------------------\")\n print(\"Source dimensions (rms): %f %f um\"%(SX,SZ))\n print(\"Source dimensions (2.35*rms): %f %f um\"%(f2dot35*SX,f2dot35*SZ))\n print(\"Focal dimensions (rms): %f %f um\"%(FX,FZ))\n print(\"Focal dimensions (2.35*rms): %f %f um\"%(f2dot35*FX,f2dot35*FZ))\n print(\"Focal dimensions (FWHM HISTO): %f %f nm\"%(1e9*tkt['fwhm_h'],1e9*tkt['fwhm_v']))\n print(\"Demagnification (StDev) H:%g V:%g (theoretical: %g,%g) \"%(SX/FX,SZ/FZ,demagX[0]*demagX[1],demagZ))\n print(\"Demagnification:(HISTO) H:%g V:%g (theoretical: %g,%g) \"%(f2dot35*SX/(f2dot35*1e6*tkt['fwhm_h']),SZ/(1e6*tkt['fwhm_v']),demagX[0]*demagX[1],demagZ))\n\nif __name__ == \"__main__\":\n # test_with_collimated_beam()\n # todo check with two elements\n # test_with_divergent_beam()\n test_id16ni()","sub_path":"shadow4/optical_elements/lens_ideal.py","file_name":"lens_ideal.py","file_ext":"py","file_size_in_byte":12244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"354816953","text":"# Прочитать файл, применить функцию, записать файл\n\ndef read_file(filename_in):\n my_list = []\n with open('./files/' + filename_in) as inf:\n for line in inf:\n my_list.append(inf.read().replace('\\n', '').split())\n my_list = my_list[0]\n return(my_list)\n\n# Создаем справочник (ключ - слово, значение - число повторов)\n\ndef dict_create(my_list):\n\tmy_dict = {}\n\tfor item in my_list:\n\t\tif item in my_dict:\n\t\t\tmy_dict[item] +=1\n\t\telse:\n\t\t\tmy_dict[item] = 1\n\treturn my_dict\n\n# Вывести топовое слово с указанием, сколько раз встретилось\ndef top_word(my_dict):\n\tmaximum = max(my_dict, key=my_dict.get)\n\tresult = maximum + ' '+ str(my_dict[maximum])\n\treturn result\n\n# Запись результата в файл\nwith open('./files/' + filename_out,'w') as ouf:\n\tfor i in range(len(result)):\n\t\touf.write(result[i],'\\n')","sub_path":"Stepic_1/Sublime_files(.py)/topWord_file.py","file_name":"topWord_file.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"4058015","text":"#Authors: DS291\n\n# The functions below read in the dataset's gound truths then count the occurances of each target class. \n\nimport numpy as np\nimport SimpleITK as sitk\nfrom tqdm import tqdm\nimport nibabel as nib\nimport os\nfrom tensorflow.keras import backend as K\nimport pickle\n\n# File path:\n#path = \"/home/ds291/Brain_Tumour_Segmentation_CNN_master/dataset/MICCAI_BraTS2020_TrainingData/\"\npath = './dataset_conv/X/'\nlabel_path = './dataset_conv/Y/'\n\ndef read_image(file_path):\n img = nib.load(file_path)\n # the model to which this is being integrated reads the data in form (155, 240, 240), hence the transpose method\n img_data = img.get_fdata()\n return np.transpose(img_data, (2,1,0))\n\ndef read_data(path):\n\n my_dir = sorted(os.listdir(path))\n\n # While testing, limit dataset size. \n limit = 369\n index = 0\n\n #training_names = []\n #ground_truth_names = []\n\n for p in tqdm(my_dir):\n\n #data = []\n gt = []\n\n if ('.csv' not in p) and (index < limit):\n\n index += 1\n\n data_list = sorted(os.listdir(path+p))\n\n # Ground truth images:\n seg = read_image(path + p + '/' + data_list[1])\n\n gt = np.asarray(seg, dtype = np.uint8)\n\n gt_name = 'y' + str(index) +'_gt.npy'\n\n np.save(gt_name, gt)\n\ndef load_data(path):\n\n my_dir = sorted(os.listdir(path))\n\n dataset = []\n\n #For each directory in the dataset, load in the corresponding segmentation, append it to the array.\n for f in tqdm(my_dir):\n print(f)\n data = np.load(path + f)\n print(data.shape)\n dataset.append(data)\n\n #Convert to a numpy array and return it. \n dataset_conv = np.asarray(dataset)\n return dataset_conv\n\n#Calculates class weitghts, saves them as a pkl file. \ndef get_weights(dataset):\n\n print('dataset shape: ' + str(dataset.shape))\n\n flat_dataset = K.flatten(dataset)\n\n print('dataset shape: ' + str(flat_dataset.shape))\n\n #Count the occurances of each class label\n label_count = np.bincount(flat_dataset)\n\n #Calculates weights for each class as (1 / number of occurances) * (2 * (dataset size))\n weight_0 = (1/label_count[0]) * (dataset.size*2)\n weight_1 = (1/label_count[1]) * (dataset.size*2)\n weight_2 = (1/label_count[2]) * (dataset.size*2)\n weight_3 = (1/label_count[4]) * (dataset.size*2)\n\n #Save class weights to a dictionary object\n weight_dictionary = {0:weight_0, 1:weight_1, 2:weight_2 , 3:weight_3}\n\n print('Weight for class 0 (Background): ' + str(weight_0))\n print('Weight for class 1 (Necrotic Core): '+ str(weight_1))\n print('Weight for class 2 (Edema): '+ str(weight_2))\n print('Weight for class 3 (Enhancing Tumour): '+ str(weight_3))\n\n #Save dictionary file to local directory for use by model. \n dict_file = open(\"class_weights.pkl\", \"wb\")\n pickle.dump(weight_dictionary, dict_file)\n dict_file.close()\n\n\n#Execute the functions. \nread_data(label_path)\n\ndata = load_data(label_path)\n\nget_weights(data)\n","sub_path":"ClassWeights.py","file_name":"ClassWeights.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"379014015","text":"import cntk\nfrom utils.files_path import join_paths, is_file\nfrom settings import MNIST_DATA_FOLDER\nfrom datasets.mnistdata.mnist_files import savetxt\nfrom datasets.mnistdata.mnist_downloader import MnistDownloader\nfrom datasets.mnistdata.ctf_reader import init_reader\nfrom settings import MINST_DOWNLOAD_INFO\nfrom batchlog.trainning import progress\nfrom batchlog.tensor_writer import TensorWriter\nfrom utils.devices import set_devices\nfrom evaluation.test_mnist import predict_minist_images\n#from models.logistic_regression import LogisticRegression\n#from models.ml_perceptron import MlPerceptron\n# from models.convolutional_nn import ConvolutionalNN\nfrom models.convolutional_maxpooling import ConvolutionalMaxPooling\n\n\nif __name__ == '__main__':\n\n set_devices()\n input_dim = 784\n input_dim_model = (1, 28, 28)\n num_output_classes = 10\n\n #model_definition = MlPerceptron(input_dim, num_output_classes)\n model_definition = ConvolutionalMaxPooling(input_dim_model, num_output_classes)\n\n learning_rate = 0.2\n lr_schedule = cntk.learning_rate_schedule(\n learning_rate, cntk.UnitType.minibatch)\n learner = cntk.sgd(model_definition.model.parameters, lr_schedule)\n\n tensor_writer = TensorWriter(model_definition.model)\n trainer = cntk.Trainer(\n model_definition.model,\n (model_definition.get_loss(), model_definition.get_classification_error()),\n [learner], tensor_writer.get_writer())\n\n # Trainning\n minibatch_size = 64\n num_samples_per_sweep = 60000\n num_sweeps_to_train_with = 10\n num_minibatches_to_train = (\n num_samples_per_sweep * num_sweeps_to_train_with) / minibatch_size\n\n reader_train = init_reader(join_paths(MNIST_DATA_FOLDER, 'train.txt'), input_dim, num_output_classes)\n input_map = {\n model_definition.label: reader_train.streams.labels,\n model_definition.input: reader_train.streams.features\n }\n\n for i in range(0, int(num_minibatches_to_train)):\n data = reader_train.next_minibatch(minibatch_size, input_map=input_map)\n output = trainer.train_minibatch(\n data, outputs=[model_definition.input])\n tensor_writer.write_model_params(i)\n #tensor_writer.write_image(output[1], i)\n batchsize, loss, error = progress(\n trainer, i, frequency=500, verbose=1)\n\n # Test\n reader_test = init_reader(\n join_paths(MNIST_DATA_FOLDER, 'test.txt'), input_dim, num_output_classes, is_training=False)\n\n test_input_map = {\n model_definition.label: reader_test.streams.labels,\n model_definition.input: reader_test.streams.features\n }\n\n test_minibatch_size = 512\n num_samples = 10000\n num_minibatches_to_test = num_samples // test_minibatch_size\n test_result = 0.0\n\n for i in range(num_minibatches_to_test):\n data = reader_test.next_minibatch(test_minibatch_size,\n input_map=test_input_map)\n eval_error = trainer.test_minibatch(data)\n test_result = test_result + eval_error\n\n print(\"Average test error: {0:.2f}%\".format(\n test_result * 100 / num_minibatches_to_test))\n\n #predict_minist_images(model_definition, mnist_downloader.test_file)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"539360184","text":"\"\"\"15. 주민등록번호를 입력하면 남자인지 여자인지 알려주는 프로그램을 작성하시오. \r\n(리스트 split 과 슬라이싱 활용) \r\n\r\n예시\r\n<입력>\r\n주민등록번호 : 941130-3002222\r\n\r\n<출력>\r\n남자\r\n\"\"\"\r\n#2000년대 이후 출생자는 3: 남자, 4:여자\r\n\r\na = input('주민등록번호 : ')\r\nb=a.split('-')\r\n# print(b[1][0])\r\n\r\nif b[1][0] == '3':\r\n print('남자')\r\nelse:\r\n print('여자')","sub_path":"quiz/pre_python_15.py","file_name":"pre_python_15.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"19029904","text":"\"\"\"\nThis script explores the impact the prior on the virial should have on\npermitting low density components mapping to the field.\n\"\"\"\nfrom __future__ import print_function, division\n\nimport numpy as np\nimport sys\n\nimport chronostar.component\nimport chronostar.likelihood\n\nsys.path.insert(0, '..')\n\nimport chronostar.synthdata as syn\nimport chronostar.compfitter as gf\nimport chronostar.expectmax as em\n\n# 1 comp fit\none_group_pars_ex = [\n np.array([27.21857533, 40.84870565, 23.3006967 , -0.96968654, -3.47371966,\n -0.29458631, 16.70523603, 1.15738955, 14.07591161])\n]\none_weights = [61.9987919]\n\n# 2 comp fit\ntwo_group_pars_ex = [\n np.array([25.24100057, 35.37151966, 23.73419406, 0.68106934, -3.77992686,\n -0.43692936, 8.97195291, 0.92658985, 13.33282707]),\n np.array([ 2.97783565e+01, 4.85637518e+01, 2.45364372e+01, -2.58377259e+00,\n -3.04098661e+00, -3.34909874e-02, 2.16584223e+01, 8.31520834e-01,\n 1.53740845e+01])\n]\ntwo_weights = [33.02902374, 28.97088176, 6.0000945]\n\n# 3 comp fit\nthree_group_pars_ex = [\n np.array([26.54427126, 37.99652339, 24.08375344, 0.36762423, -3.7307971,\n -0.34351942, 9.02614369, 0.92211963, 14.14381967]),\n np.array([ 8.93722359, 22.28633376, -1.18878485, -8.63887102,\n -11.130962, -3.43125315, 8.51810544, 1.77553,\n 1.51311008]),\n np.array([ 3.21488735e+01, 4.88207224e+01, 2.43963555e+01, -2.75347262e+00,\n -2.98063139e+00, 1.26400066e-02, 2.21896254e+01, 7.69173481e-01,\n 1.60651391e+01])\n]\nthree_weights = [36.60656637, 4.70398271, 24.68926151, 2.00018941]\n\n# overallLnLike\noverallLnLikes = [-1092.54943463, -1063.00062202, -1010.87585206]\nBICs = [2234.42221209, 2224.6479297, 2169.72173262]\n\n# gather everything up\nall_group_pars = [one_group_pars_ex,\n two_group_pars_ex,\n three_group_pars_ex]\nall_weights = [one_weights,\n two_weights,\n three_weights]\n\n# For each fit\nfor i, (group_pars_ex, weights) in enumerate(zip(all_group_pars, all_weights)):\n lnalpha_priors = []\n\n print(\"\\n--- {} component fit ---\".format(len(group_pars_ex)))\n print(\"Likelihood from overlaps: {:8.4f}\".format(overallLnLikes[i]))\n print(\"BIC: {:8.4f}\".format(BICs[i]))\n for group_par, weight in zip(group_pars_ex, weights):\n group_obj = chronostar.component.Component(group_par, form=True,\n internal=False)\n lnalpha_prior = gf.lnAlphaPrior(group_obj.getInternalSphericalPars(),\n weight)\n lnalpha_priors.append(lnalpha_prior)\n print(\"nstars: {:6.3f} | age: {:6.3f} | dX: {:6.3f} | dV: {:6.3f} |\"\n \"lnalpha_pr: {:6.3f}\"\\\n .format(weight, group_obj.age, group_obj.dx, group_obj.dv,\n lnalpha_prior))\n #print(lnalpha_priors)\n\n\n# for deeper insight, lets investigate the ratio of overlap between\n# the flat bg field and the crappy 1.5 Myr component (3_comp[1]) and\n# see if the difference will be corrected for by the large prior\n\nrdir = \"../results/em_fit/cf-15/\"\nstar_pars_file = \"../data/bpmg_cand_w_gaia_dr2_astrometry_comb_binars_xyzuvw.fits\"\n\nstar_pars = gf.loadXYZUVW(star_pars_file)\nbg_hists = np.load(rdir + \"bg_hists.npy\")\nfinal_z = np.load(rdir + \"final/final_membership.npy\")\nfinal_groups = np.load(rdir + \"final_groups.npy\")\n\nfor i in range(len(three_group_pars_ex)):\n spec_comp_stars_mask = np.where(final_z[:,i] > .5)\n spec_comp_star_pars = {'xyzuvw':star_pars['xyzuvw'][spec_comp_stars_mask],\n 'xyzuvw_cov':star_pars['xyzuvw_cov'][\n spec_comp_stars_mask]}\n spec_comp_group = chronostar.component.Component(three_group_pars_ex[1],\n internal=False)\n\n spec_ln_bg_ols = em.backgroundLogOverlaps(spec_comp_star_pars['xyzuvw'], bg_hists,\n correction_factor=1.)\n\n # BUG IS FROM ME FORGETTING TO INCORPORATE AMPLITUDE OF\n # GROUP!!!\n weight = np.sum(final_z[:,i])\n print(weight)\n spec_ln_comp_ols = np.log(weight) + \\\n chronostar.likelihood.get_lnoverlaps(spec_comp_group. \\\n getInternalSphericalPars(),\n spec_comp_star_pars)\n try:\n assert np.all(spec_ln_comp_ols > spec_ln_bg_ols)\n except AssertionError:\n print(\"Stars {}\\n are members of component {} despite\"\n \" having stronger overlap with background\".\\\n format(np.where(spec_ln_comp_ols .5)\n# good_comp_star_pars = {'xyzuvw':star_pars['xyzuvw'][good_comp_stars_mask],\n# 'xyzuvw_cov':star_pars['xyzuvw_cov'][good_comp_stars_mask]}\n# good_comp_group = syn.Group(three_group_pars_ex[0], starcount=False,\n# internal=False)\n# good_ln_bg_ols = em.backgroundLogOverlaps(good_comp_star_pars['xyzuvw'], bg_hists,\n# correction_factor=15.)\n# good_ln_comp_ols = gf.getLogOverlaps(good_comp_group.getInternalSphericalPars(),\n# good_comp_star_pars)\n#\n#\n# fine_comp_stars_mask = np.where(final_z[:,2] > .5)\n# fine_comp_star_pars = {'xyzuvw':star_pars['xyzuvw'][fine_comp_stars_mask],\n# 'xyzuvw_cov':star_pars['xyzuvw_cov'][fine_comp_stars_mask]}\n# fine_comp_group = syn.Group(three_group_pars_ex[0], starcount=False,\n# internal=False)\n# fine_ln_bg_ols = em.backgroundLogOverlaps(fine_comp_star_pars['xyzuvw'], bg_hists,\n# correction_factor=15.)\n# fine_ln_comp_ols = gf.getLogOverlaps(fine_comp_group.getInternalSphericalPars(),\n# fine_comp_star_pars)\n#\n# #BUG!!!\n#\n\n","sub_path":"scripts/retired/alpha_prior_sanity_check.py","file_name":"alpha_prior_sanity_check.py","file_ext":"py","file_size_in_byte":6024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"135980860","text":"import matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport seaborn as sns\r\nfrom pandas.plotting import register_matplotlib_converters\r\nregister_matplotlib_converters()\r\n\r\n# Import data (Make sure to parse dates. Consider setting index column to 'date'.)\r\ndf = pd.read_csv(\"fcc-forum-pageviews.csv\", parse_dates=[\"date\"], index_col=\"date\")\r\n\r\n# Clean data\r\ndf = df[(df['value'] >= (df['value'].quantile(0.025))) &\r\n (df['value'] <= (df['value'].quantile(0.975)))].reset_index()\r\ndf['date'] = pd.to_datetime(df['date'])\r\ndf = df.set_index('date')\r\n\r\ndef draw_line_plot():\r\n # Draw line plot\r\n fig = plt.figure(figsize=(6, 3))\r\n df['value'].plot(linewidth=2.5, color='red')\r\n plt.title('Daily freeCodeCamp Forum Page Views 5/2016-12/2019', fontsize=14)\r\n plt.xlabel('Date', fontsize=14)\r\n plt.ylabel('Page Views', fontsize=14)\r\n\r\n # Save image and return fig (don't change this part)\r\n fig.savefig('line_plot.png')\r\n return fig\r\n\r\ndef draw_bar_plot():\r\n # Copy and modify data for monthly bar plot\r\n df_bar = df.copy()\r\n\r\n df_bar[\"Months\"] = df_bar.index.month\r\n df_bar[\"Years\"] = df_bar.index.year\r\n\r\n df_bar = df_bar.groupby([df_bar[\"Years\"], df_bar[\"Months\"]])[\"value\"].mean()\r\n df_bar = df_bar.unstack()\r\n\r\n # Draw bar plot\r\n fig = df_bar.plot(kind=\"bar\", legend=True, figsize=(14, 10)).figure\r\n plt.xlabel('Years', fontsize=14)\r\n plt.ylabel('Average Page Views', fontsize=14)\r\n\r\n plt.xticks(fontsize=14)\r\n plt.yticks(fontsize=14)\r\n plt.legend(fontsize=10, title=\"Months\", labels=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'])\r\n\r\n # Save image and return fig (don't change this part)\r\n fig.savefig('bar_plot.png')\r\n return fig\r\n\r\ndef draw_box_plot():\r\n # Prepare data for box plots (this part is done!)\r\n df_box = df.copy()\r\n df_box.reset_index(inplace=True)\r\n df_box['year'] = [d.year for d in df_box.date]\r\n df_box['month'] = [d.strftime('%b') for d in df_box.date]\r\n\r\n df_box = df_box.rename(columns={\"value\":\"Page Views\"})\r\n df_box[\"month_num\"] = df_box[\"date\"].dt.month\r\n df_box = df_box.sort_values(\"month_num\")\r\n\r\n # Draw box plots (using Seaborn)\r\n fig, (ax1, ax2) = plt.subplots(1,2)\r\n\r\n ax1 = sns.boxplot(x=\"year\", y=\"Page Views\", data=df_box, ax=ax1)\r\n ax1.set_title(\"Year-wise Box Plot (Trend)\")\r\n ax1.set_xlabel('Year')\r\n ax1.set_ylabel('Page Views')\r\n\r\n ax2 = sns.boxplot(x=\"month\", y=\"Page Views\", data=df_box, ax=ax2)\r\n ax2.set_title(\"Month-wise Box Plot (Seasonality)\")\r\n ax2.set_xlabel('Month')\r\n ax2.set_ylabel('Page Views')\r\n\r\n # Save image and return fig (don't change this part)\r\n fig.savefig('box_plot.png')\r\n return fig\r\n","sub_path":"FreeCodeCamp_PageViewTimeSeriesVisualizer.py","file_name":"FreeCodeCamp_PageViewTimeSeriesVisualizer.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"411615716","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/29 20:53\n# @Author : weiyu\n# @File : 860_lemonade_change.py\n\n\nclass Solution:\n def lemonadeChange(self, bills):\n five = ten = 0\n for i in bills:\n if i == 5: five += 1\n elif i == 10: five -= 1; ten += 1\n elif i == 20:\n if ten:\n ten -= 1; five -= 1\n else:\n five -= 3\n if five < 0:\n return False\n return True","sub_path":"Week_03/860_lemonade_change.py","file_name":"860_lemonade_change.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"264704989","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass MabContainerExtendedInfo(Model):\n \"\"\"Additional information of the container.\n\n :param last_refreshed_at: Time stamp when this container was refreshed.\n :type last_refreshed_at: datetime\n :param backup_item_type: Type of backup items associated with this\n container. Possible values include: 'Invalid', 'VM', 'FileFolder',\n 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'VMwareVM',\n 'SystemState', 'Client', 'GenericDataSource'\n :type backup_item_type: str or :class:`BackupItemType\n `\n :param backup_items: List of backup items associated with this container.\n :type backup_items: list of str\n :param policy_name: Backup policy associated with this container.\n :type policy_name: str\n :param last_backup_status: Latest backup status of this container.\n :type last_backup_status: str\n \"\"\"\n\n _attribute_map = {\n 'last_refreshed_at': {'key': 'lastRefreshedAt', 'type': 'iso-8601'},\n 'backup_item_type': {'key': 'backupItemType', 'type': 'str'},\n 'backup_items': {'key': 'backupItems', 'type': '[str]'},\n 'policy_name': {'key': 'policyName', 'type': 'str'},\n 'last_backup_status': {'key': 'lastBackupStatus', 'type': 'str'},\n }\n\n def __init__(self, last_refreshed_at=None, backup_item_type=None, backup_items=None, policy_name=None, last_backup_status=None):\n self.last_refreshed_at = last_refreshed_at\n self.backup_item_type = backup_item_type\n self.backup_items = backup_items\n self.policy_name = policy_name\n self.last_backup_status = last_backup_status\n","sub_path":"azure-mgmt-recoveryservicesbackup/azure/mgmt/recoveryservicesbackup/models/mab_container_extended_info.py","file_name":"mab_container_extended_info.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"579354827","text":"from django.shortcuts import render\n\n# Create your views here.\n\ndef square(request):\n a = request.GET.get('a', None)\n b = request.GET.get('b', None)\n c = request.GET.get('c', None)\n\n if None in (a, b, c):\n result = u'Not the correct input'\n else:\n a = float(a)\n b = float(b)\n c = float(c)\n d = b * b - 4 * a * c\n if d >= 0:\n x1 = (-b - d**(0.5))/(2 * a)\n x2 = (-b + d**(0.5))/(2 * a)\n result = (x1, x2)\n else:\n result = u\"The discriminant is less than zero\"\n\n return render(request, 'nine/index.html', {\"string\" : result})\n\n","sub_path":"nine/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"48738176","text":"class Solution(object):\n def myAtoi(self, str):\n str=str.strip()\n if str=='':\n return 0\n m=re.match(r'^([\\+\\-]?)0*(\\d*)',str)\n newStr=m.group(0)\n conInt=0\n if newStr=='' or newStr=='+' or newStr=='-':\n return 0\n else:\n conInt=int(newStr)\n \n if conInt>2147483647:\n return 2147483647\n if conInt<-2147483648:\n return -2147483648\n return conInt\n ","sub_path":"Python/Title8/StringToInteger(atoi)II.py","file_name":"StringToInteger(atoi)II.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"65237016","text":"from typing import Tuple\nimport numpy as np\nimport json\nfrom collections import deque\nimport itertools\n\n\nclass SliceDeck(deque):\n def __getitem__(self, index):\n try:\n return deque.__getitem__(self, index)\n except TypeError:\n return type(self)(itertools.islice(self, index.start, index.stop))\n\n\nclass Receiver(object):\n \"\"\"Class models the receiver in the microphone array and provides interface for the simulation\"\"\"\n\n srcX: np.float64 = -10.0\n srcY: np.float64 = -10.0\n srcZ: np.float64 = -10.0\n c: np.float64 = 343.0 # m/x\n\n decimal_num: int = 5\n isSimulation: bool = False\n\n def __init__(self, pos_x: np.float64, pos_y: np.float64, pos_z: np.float64, is_reference: bool = False,\n buffer_size: int = 2 * 4096, received_time: np.longfloat = 0):\n\n self._pos_x, self._pos_y, self._pos_z = pos_x, pos_y, pos_z\n self._isReference = is_reference\n self._received_time: np.float64 = np.float64(received_time)\n # public TDOA time variable between this microphone and reference one\n self.tDoA: float = 0.0\n\n self.receive()\n self.data_buffer = SliceDeck(maxlen=buffer_size)\n\n @property\n def is_reference(self) -> bool:\n return self._isReference\n\n @is_reference.setter\n def is_reference(self, is_ref: bool):\n self._isReference = is_ref\n\n @property\n def position(self) -> np.ndarray:\n \"\"\"Return the current position of the receiver (x,y,z)\"\"\"\n\n return np.array([self._pos_x, self._pos_y, self._pos_z])\n\n @position.setter\n def position(self, pos: Tuple[float, float, float]) -> None:\n \"\"\"Sets the position of the receiver (x,y,z)\"\"\"\n\n self._pos_x, self._pos_y, self._pos_z = pos[0], pos[1], pos[2]\n\n def dist(self, other: 'Receiver') -> np.float:\n \"\"\"Expresses the distance between two microphones in terms of TDoA between them\"\"\"\n if Receiver.isSimulation:\n return np.around((self._received_time - other._received_time) * Receiver.c, Receiver.decimal_num)\n return self.tDoA * Receiver.c\n\n def calc_k(self) -> float:\n return self._pos_x ** 2 + self._pos_y ** 2 + self._pos_z ** 2\n\n def receive(self) -> None:\n \"\"\"Simulates the the received time offset, based on src position class variables\"\"\"\n src = Receiver.get_source_position()\n self._received_time = np.linalg.norm(self.position - src) / Receiver.c\n\n @property\n def json(self) -> str:\n obj = {\n \"x\": self._pos_x,\n \"y\": self._pos_y,\n \"z\": self._pos_z,\n \"isReference\": self._isReference\n }\n return json.dumps(obj)\n\n @classmethod\n def set_source_position(cls, src_position: Tuple[float, float, float] = (srcX, srcY, srcZ)):\n \"\"\"Sets the source position coordinates for the simulation purposes\"\"\"\n\n cls.srcX, cls.srcY, cls.srcZ = src_position[0], src_position[1], src_position[2]\n\n @classmethod\n def get_source_position(cls) -> Tuple[float, float, float]:\n \"\"\"Returns source position coordinates, simulation only !\"\"\"\n return cls.srcX, cls.srcY, cls.srcZ","sub_path":"localizator/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"502979499","text":"from django import forms\nfrom secondapp.models import User\nfrom django.core import validators\n\n# def check_start_z(value):\n# \tif value[0].lower() != 'z':\n# \t\traise forms.VaildationError(\"start with z\")\n\n\nclass Form(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = '__all__'\n\n\t\twidgets = {\n\t\t'first_name': forms.TextInput(attrs={'class':'form-control'}),\n\t\t'last_name': forms.TextInput(attrs={'class':'form-control display-inline'}),\n\t\t'email': forms.EmailInput(attrs={'class':'form-control'})\n\n\t\t}\n\t# first_name = forms.CharField()\n\t# last_name = forms.CharField()\n\t# email = forms.EmailField(help_text='A valid email address, please.')\n\t# password = forms.PasswordInput()\n\t# password2 = forms.PasswordInput()\n\tbotcatcher = forms.CharField(required=False,\n\t\t\t\t\t\t\t\twidget= forms.HiddenInput,\n\t\t\t\t\t\t\t\tvalidators=[validators.MaxLengthValidator(0)])\n\t# def clean_botchatcher(self):\n\t# \tbotcatcher = self.cleaned_data['botcatcher']\n\t# \tif len(botcatcher) > 0:\n\t# \t\traise forms.VaildationError(\"GOTCHa BOT!\")\n\t# \treturn botcatcher\n\n\t# def clean(self):\n\t# \tall_cleaned_data = super().clean()\n\t# \temail = all_cleaned_data['email']\n\t# \tverify_email = all_cleaned_data['verify_email']\n\n\t# \tif email != verify_email:\n\t# \t\traise forms.ValidionError(\"Make sure emails are matched\")\n\n","sub_path":"firstproject/secondapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"574671528","text":"def f(s):\n if s<=1:\n return 1\n else:\n t=0 \n for i in range(s):\n t+=f(i)*f(s-1-i)\n return t%(1000000007)\n \nprint(f(int(input().strip())))","sub_path":"Code/CodeRecords/2312/60788/265536.py","file_name":"265536.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"147067576","text":"import numpy as np\nimport os\nimport glob\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom random import randint\n\ndef galtonboard(levels):\n lanes = [0]*(levels)\n for h in range((levels)**2*100):\n stored = -1\n for j in range(levels):\n stored += randint(0, 1)\n lanes[stored] += 1\n\n if len(lanes)%2==0:\n X = np.arange(-((len(lanes)/2)-1), (len(lanes)/2)+1)\n else:\n X = np.arange(-((len(lanes)/2)-.5), (len(lanes)/2)+.5)\n #Fixes thread error: https://stackoverflow.com/questions/14694408/runtimeerror-main-thread-is-not-in-main-loop\n plt.switch_backend('agg')\n\n plt.suptitle('Galton Board')\n plt.bar(X + 0.00, lanes, width=0.25)\n\n # Deletes older boards images\n files = glob.glob('static/imgs/*.png')\n for f in files:\n os.remove(f)\n\n #Gives the png a unique name\n name = str(abs(hash(datetime.now())))\n\n route='static/imgs/'+str(name)+'.png'\n plt.savefig(route)\n print(\"route: \"+route)\n print(\"image saved\")\n return lanes,route\n","sub_path":"galton.py","file_name":"galton.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"514472966","text":"from textwrap import wrap\n\nimport nltk\nfrom PyQt5.QtWidgets import QDialog\nfrom nltk.help import upenn_tagset\n\nfrom gui.gen.tags_help import Ui_TagsHelp\n\n\nclass TagsHelp(QDialog, Ui_TagsHelp):\n def __init__(self, parent):\n super().__init__(parent)\n self.setupUi(self)\n self.textBrowser.setText(self.getText())\n\n @staticmethod\n def getText():\n tagdict = nltk.data.load('help/tagsets/upenn_tagset.pickle')\n tags = sorted(tagdict)\n tagsStrings = []\n for tag in tags:\n entry = tagdict[tag]\n defn = [tag + \": \" + entry[0]]\n examples = wrap(entry[1], width=75, initial_indent=\" \", subsequent_indent=\" \")\n tagsStrings.append(\"\\n\".join(defn + examples))\n return \"\\n\".join(tagsStrings)\n\n\ndialog = None\n\n\ndef showTagsHelp(parent):\n global dialog\n if dialog is not None:\n dialog.close()\n dialog = TagsHelp(parent)\n dialog.show()\n\n\nif __name__ == '__main__':\n upenn_tagset()\n","sub_path":"src/gui/dialogs/tags_help.py","file_name":"tags_help.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"349809905","text":"\"\"\"Experiments with Toxicity Dataset\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tf_trainer.common import base_model\nfrom tf_trainer.common import model_trainer\nfrom tf_trainer.common import tfrecord_input\nfrom tf_trainer.common import types\nfrom tf_trainer.tf_hub_classifier import model as tf_hub_classifier\n\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_integer(\"batch_size\", 32,\n \"The batch size to use during training.\")\ntf.app.flags.DEFINE_integer(\"train_steps\", 40000,\n \"The number of steps to train for.\")\ntf.app.flags.DEFINE_integer(\"eval_period\", 500,\n \"The number of steps per eval period.\")\ntf.app.flags.DEFINE_integer(\"eval_steps\", 50,\n \"The number of steps to eval for.\")\n\n\ndef create_serving_input_fn():\n\n def serving_input_fn_tfrecords():\n\n serialized_example = tf.placeholder(\n shape=[None],\n dtype=tf.string,\n name=\"input_example_tensor\"\n )\n feature_spec = {\n base_model.TEXT_FEATURE_KEY: tf.FixedLenFeature([], dtype=tf.string),\n # key_name is defined in model_trainer.\n FLAGS.key_name: tf.FixedLenFeature([], dtype=tf.int64,\n default_value=-1)\n }\n\n features = tf.parse_example(\n serialized_example, feature_spec)\n\n return tf.estimator.export.ServingInputReceiver(\n features,\n serialized_example)\n\n return serving_input_fn_tfrecords\n\n\ndef main(argv):\n del argv # unused\n\n dataset = tfrecord_input.TFRecordInput(\n batch_size=FLAGS.batch_size)\n\n model = tf_hub_classifier.TFHubClassifierModel(dataset.labels())\n\n trainer = model_trainer.ModelTrainer(dataset, model)\n trainer.train_with_eval(FLAGS.train_steps, FLAGS.eval_period, FLAGS.eval_steps)\n\n serving_input_fn = create_serving_input_fn()\n trainer.export(serving_input_fn)\n\n\nif __name__ == \"__main__\":\n tf.logging.set_verbosity(tf.logging.INFO)\n tf.app.run(main)\n","sub_path":"experiments/tf_trainer/tf_hub_classifier/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"105648180","text":"from larlib import *\n\ndef viewNumbering(V,FV, submodel):\n V,EV = larFacets((V,FV),2,4)\n VV = AA(LIST)(range(len(V)))\n VIEW(larModelNumbering(1,1,1)(V,[VV,EV,FV[:-4]],submodel,1))\n\n\ndef make_roof(V, FV, height):\n \"\"\"\n Return a Hpc object representation of a solid roof.\n\n Arguments:\n V (list): the list of vertices of the 2D polygon above which the roof will be built\n FV (list): the 3D convex cells of the 2D polygon\n scale (float): the lenght of the gables\n height (float): the height of the roof\n Note that the volumetric shape of the polygon \n will be defined using the MKPOL primitive PLaSM operator,\n given vertices and cells\n\n Returns:\n Hpc: The solid roof frame of the polygon\n \n \"\"\"\n \n def area(V,F):\n NF = len(F)\n areap = 0\n for u in range(NF):\n areap += (V[F[(u+1)%NF]-1][0]+V[F[u%NF]-1][0]) * (V[F[(u+1)%NF]-1][1]-V[F[u%NF]-1][1])\n return math.fabs(areap/2)\n \n def isMember(point, verts, cell):\n n = len(cell)\n for z in range(n):\n x1 = verts[cell[z % n]-1][0]\n y1 = verts[cell[z % n]-1][1]\n x2 = verts[cell[(z-1) % n]-1][0]\n y2 = verts[cell[(z-1) % n]-1][1]\n A = -(y2 - y1)\n B = x2 - x1\n C = -(A * x1 + B * y1)\n D = A * point[0] + B * point[1] + C\n if (D<0):\n return 0\n return 1\n \n def scaleFactor(V, F):\n return sqrt( (V[F[2]-1][0] - V[F[0]-1][0])**2 + (V[F[2]-1][1] - V[F[0]-1][1])**2 ) / 4\n \n polygon = MKPOL([V, FV, None])\n polygon3D = PROD([polygon, Q(.1)])\n \n NV = len(V)\n VRFs = []\n debug = []\n \n maxArea = area(V,FV[0])\n k = 0\n for j in range(len(FV)):\n a = area(V,FV[j])\n if (a>maxArea):\n maxArea = a\n k = j\n \n for j in range(len(FV)):\n F = FV[j]\n VRFs.append([])\n NF = len(F)\n scale = scaleFactor(V,F)\n for i in range(NF): \n origin = V[F[i]-1]\n x1 = V[F[(i-1) % NF]-1][0] - origin[0]\n y1 = V[F[(i-1) % NF]-1][1] - origin[1]\n x2 = V[F[(i+1) % NF]-1][0] - origin[0]\n y2 = V[F[(i+1) % NF]-1][1] - origin[1]\n alpha1 = math.atan2(y1,x1)\n alpha2 = math.atan2(y2,x2)\n bisector = (alpha1 + alpha2) / 2\n x = origin[0]+scale*COS(bisector)\n y = origin[1]+scale*SIN(bisector)\n \n if (j!=k and isMember(origin, V, FV[k])):\n bisector+=PI/2\n x = origin[0]+scale*COS(bisector)\n y = origin[1]+scale*SIN(bisector)\n \n if (not isMember([x,y], V, F) and not isMember([x,y], V, FV[k])):\n bisector+=PI\n x = origin[0]+scale*COS(bisector)\n y = origin[1]+scale*SIN(bisector) \n \n VRFs[j].append([x, y])\n # Only for debugging purposes\n debug.append(MKPOL([[origin, [x, y]], [[1,2]], None]))\n \n # Only for debugging purposes\n #viewNumbering(V, FV, SKEL_1(STRUCT([polygon]+debug)))\n # DEBUGGING ENDED\n \n VV = map(lambda vert: [vert[0], vert[1], 0], V)\n VVRFs = []\n terraces = []\n for j in range(len(FV)):\n if (j==k):\n hh = height\n else:\n \n hh = height/3\n VVRFs.append(map(lambda l: [l[0], l[1], hh], VRFs[j]))\n \n terrace2D = MKPOL([VRFs[j], [range(1,len(FV[j])+1)], None])\n terrace = T(3)(hh)(EXTRUDE([None,terrace2D,.025]))\n terraces.append(TEXTURE([\"images/pav2.jpg\", TRUE, FALSE, 1, 1, 0, 6, 6])(terrace))\n \n gables = []\n for j in range(len(FV)):\n F = FV[j]\n NF = len(F)\n for i in range(NF):\n curr, next = i%NF, (i+1)%NF\n v1,v2,v3,v4 = VV[F[curr]-1], VV[F[next]-1], VVRFs[j][curr], VVRFs[j][next]\n gable = STRUCT([MKPOL([[v1,v2,v3,v4],[[1,2,3,4]],None])])\n gables.append(TEXTURE([\"images/roof2.jpg\", TRUE, FALSE, 1, 1, 0, 6, 6])(OFFSET([0,0,.025])(gable)))\n \n gables3D = STRUCT(gables)\n terraces3D = STRUCT(terraces)\n #ridges = TEXTURE([\"images/roof4.jpg\", TRUE, FALSE, 1, 1, 0, 6, 6])(OFFSET([.008,.008,.008])(SKEL_1(gables3D)))\n roof = STRUCT([polygon3D, T(3)(SIZE(3)(polygon3D)), gables3D, terraces3D])\n\n return roof\n\nif __name__==\"__main__\":\n c1 = CUBOID([.4,.5])\n c2 = CUBOID([1.6,1])\n s = STRUCT([c1, T(1)(SIZE(1)(c1)), c2, T(1)(SIZE(1)(c2))(c1), T([1,2])([SIZE(1)(c2)/2, -SIZE(2)(c1)]), c1])\n pp = UKPOL(s)\n VIEW(make_roof(pp[0],pp[1], .4))\n\n V1 = [[0,0],[2,0],[2,2],[0,2],[-0.75,1.25],[-0.75,0.75],[0,0.5],[0,1.5]]\n FV1 = [[2,1,4,3], [7,6,5,8]]\n VIEW(make_roof(V1, FV1, .35))\n\n V3 = [[0,0],[10,0],[10,5],[0,5]]\n FV3 = [[2,1,4,3]]\n roof3 = make_roof(V3, FV3, 2)\n VIEW(roof3)","sub_path":"2017-01-27/roof_builder.py","file_name":"roof_builder.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"202949463","text":"#-*- coding:utf-8 _*-\n\"\"\"\n@author:fxw\n@file: PSEpostprocess.py\n@time: 2020/08/13\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport torch\nfrom .piexlmerge import pan\n\nclass PANPostProcess(object):\n\n def __init__(self, config):\n self.min_text_area = config['postprocess']['min_text_area']\n self.is_poly = config['postprocess']['is_poly']\n self.min_score = config['postprocess']['min_score']\n self.config = config\n\n def polygons_from_bitmap(self, pred):\n \n boxes = []\n scores = []\n pred,label_points,label_values = pan(pred,self.config)\n \n for label_value, label_point in label_points.items():\n if label_value not in label_values:\n continue\n score_i = label_point[0]\n label_point = label_point[2:]\n points = np.array(label_point, dtype=int).reshape(-1, 2)\n\n if points.shape[0] < self.min_text_area :\n continue\n\n if score_i < self.min_score:\n continue\n \n binary = np.zeros(pred.shape, dtype='uint8')\n binary[pred == label_value] = 1\n\n find_out = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n if(len(find_out)==2):\n contours, _ = find_out\n else:\n _, contours, _ = find_out\n contour = contours[0]\n # epsilon = 0.01 * cv2.arcLength(contour, True)\n # box = cv2.approxPolyDP(contour, epsilon, True)\n box = contour\n\n if box.shape[0] <= 2:\n continue\n \n box = box * self.config['postprocess']['scale']\n box = box.astype('int32')\n boxes.append(box[:,0])\n scores.append(score_i)\n return boxes, scores\n\n def boxes_from_bitmap(self, pred):\n boxes = []\n scores = []\n pred,label_points,label_values = pan(pred,self.config)\n \n for label_value, label_point in label_points.items():\n if label_value not in label_values:\n continue\n score_i = label_point[0]\n label_point = label_point[2:]\n points = np.array(label_point, dtype=int).reshape(-1, 2)\n\n if points.shape[0] < self.min_text_area :\n continue\n\n if score_i < self.min_score:\n continue\n box = self.get_mini_boxes(points)*self.config['postprocess']['scale']\n boxes.append(box)\n scores.append(score_i)\n return boxes, scores\n\n def get_mini_boxes(self, contour):\n bounding_box = cv2.minAreaRect(contour)\n points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])\n\n index_1, index_2, index_3, index_4 = 0, 1, 2, 3\n if points[1][1] > points[0][1]:\n index_1 = 0\n index_4 = 1\n else:\n index_1 = 1\n index_4 = 0\n if points[3][1] > points[2][1]:\n index_2 = 2\n index_3 = 3\n else:\n index_2 = 3\n index_3 = 2\n\n box = [\n points[index_1], points[index_2], points[index_3], points[index_4]\n ]\n return np.array(box)\n\n def __call__(self, pred, ratio_list):\n boxes_batch = []\n score_batch = []\n for batch_index in range(pred.shape[0]):\n pred_single = pred[batch_index].unsqueeze(0)\n if (self.is_poly):\n boxes, score = self.polygons_from_bitmap(pred_single)\n new_bboxes =[]\n if len(boxes) > 0:\n ratio_w, ratio_h = ratio_list[batch_index]\n for bbox in boxes:\n bbox[:, 0] = bbox[:, 0] * ratio_w\n bbox[:, 1] = bbox[:, 1] * ratio_h\n new_bboxes.append(bbox)\n\n boxes_batch.append(new_bboxes)\n score_batch.append(score)\n else:\n boxes, score = self.boxes_from_bitmap(pred_single)\n if len(boxes) > 0:\n boxes = np.array(boxes)\n ratio_w, ratio_h = ratio_list[batch_index]\n boxes[:, :, 0] = boxes[:, :, 0] * ratio_w\n boxes[:, :, 1] = boxes[:, :, 1] * ratio_h\n\n boxes_batch.append(boxes)\n score_batch.append(score)\n return boxes_batch, score_batch\n\n","sub_path":"ptocr/postprocess/PANpostprocess.py","file_name":"PANpostprocess.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"434754111","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 ('website', '0044_auto_20150202_1238'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='LocatTheme',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=256, verbose_name='\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435')),\n ('slug', models.SlugField(help_text=b'\\xd0\\x92\\xd0\\xb0\\xd0\\xb6\\xd0\\xbd\\xd0\\xbe! \\xd0\\x97\\xd0\\xb0\\xd0\\xbf\\xd0\\xbe\\xd0\\xbb\\xd0\\xbd\\xd1\\x8f\\xd1\\x82\\xd1\\x8c \\xd0\\xbd\\xd0\\xb0 \\xd0\\xbb\\xd0\\xb0\\xd1\\x82\\xd0\\xb8\\xd0\\xbd\\xd0\\xb8\\xd1\\x86\\xd0\\xb5. \\xd0\\x98\\xd1\\x81\\xd0\\xbf\\xd0\\xbe\\xd0\\xbb\\xd1\\x8c\\xd0\\xb7\\xd1\\x83\\xd0\\xb5\\xd1\\x82\\xd1\\x81\\xd1\\x8f \\xd0\\xb4\\xd0\\xbb\\xd1\\x8f \\xd1\\x81\\xd0\\xbe\\xd0\\xb7\\xd0\\xb4\\xd0\\xb0\\xd0\\xbd\\xd0\\xb8\\xd1\\x8f \\xd1\\x81\\xd1\\x81\\xd1\\x8b\\xd0\\xbb\\xd0\\xbe\\xd0\\xba', unique=True, max_length=128, verbose_name='\\u0421\\u043b\\u0430\\u0433')),\n ('ordering', models.PositiveIntegerField(default=0, verbose_name='\\u041f\\u043e\\u0440\\u044f\\u0434\\u043e\\u043a \\u0432\\u044b\\u0432\\u043e\\u0434\\u0430', db_index=True)),\n ],\n options={\n 'ordering': ['ordering'],\n 'verbose_name': '\\u041f\\u043e\\u0434\\u0431\\u043e\\u0440\\u043a\\u0430',\n 'verbose_name_plural': '\\u041f\\u043e\\u0434\\u0431\\u043e\\u0440\\u043a\\u0438',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='locations',\n name='themes',\n field=models.ManyToManyField(to='website.LocatTheme', null=True, verbose_name='\\u041f\\u043e\\u0434\\u0431\\u043e\\u0440\\u043a\\u0438', blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"website/migrations/0045_auto_20150202_1240.py","file_name":"0045_auto_20150202_1240.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"207755842","text":"from icalendar import vDatetime, Calendar, Event, vText, Alarm\n#from icalendar.prop import LocalTimezone ... potentially useful\nfrom datetime import datetime\nimport pytz\n\n\n\ndef dateTime2iCal(date,time):\n\t#backup check\n\tif date == '' or date == None:\n\t\treturn None\n\n\tif time == 'All Day' or time == '' or time == None:\n\t\ta = split(date, ('/'))\n\t\treturn a[2]+a[1]+a[0]\n\n\tdateTime = str(date)+\":\"+str(time)\n\tdateTime = dateTime.replace(' ','')\n\ta = split(dateTime, (':','/'))\n\ta = [int(x) for x in a]\n\ttime = datetime(a[2],a[1],a[0],a[3],a[4],tzinfo=pytz.timezone(\"Australia/Sydney\"))\n\tdateTime = vDatetime(time).to_ical()\n\treturn dateTime.decode(\"utf-8\")\n\ndef addDateDetails(vDate):\n\t#fix for date created\n\tif '.' in vDate:\n\t\tvDate = vDate.replace('-','')\n\t\tsplit = vDate.split()\n\t\tvDate = split[0]\n\n\t#all day event\n\tallDay = False\n\tif len(vDate) < 9:\n\t\tallDay = True\n\t\tvDate += \"T000000\"\n\n\tdateTime = vDatetime.from_ical(vDate)\n\tday = int(dateTime.strftime(\"%d\"))\n\tif 4 <= day <= 20 or 24 <= day <= 30:\n\t suffix = \"th\"\n\telse:\n\t suffix = [\"st\", \"nd\", \"rd\"][day % 10 - 1]\n\treturnVal = {}\n\treturnVal['day'] = dateTime.strftime(\"%-d\")\n\treturnVal['month'] = dateTime.strftime(\"%b\")\n\treturnVal['year'] = dateTime.strftime(\"%Y\")\n\treturnVal['date']\t= dateTime.strftime(\"%d/%m/%Y\")\n\treturnVal['time']\t= dateTime.strftime(\"%H:%M\")\n\tif allDay:\n\t\treturnVal['time'] = \"All Day\"\n\treturnVal['suffix'] = suffix\n\treturn returnVal\n\ndef addTimeDetails(vDate):\n\tdateTime = vDatetime.from_ical(vDate)\n\treturnVal = dateTime.strftime(\"%-I:%M%p\")\n\treturn returnVal\n\ndef createEvent(dates, name, creator):\n\tcal = Calendar()\n\tcal.add('NAME', name )\n\tcal.add('X-WR-CALNAME', name)\n\tcal.add('prodid', '-//iCalIt//iCalIt Calendar//')\n\tcal.add('version', '2.0')\n\tfor date in dates:\n\t\tif not date:\n\t\t\tcontinue\n\t\tif date.description:\n\t\t\tdate.description = date.description.replace(\"
\", \"\\n\")\n\t\telse:\n\t\t\tdate.description = ''\n\t\t#end piece in description\n\t\taddition = \"\\n\\n\\nMade with iCalIt by \"+creator+\"\\nwww.icalit.com\"\n\t\t#create event\n\t\tevent = Event()\n\t\tevent['uid'] = vText(\"iCalIt/\"+str(date.id))\n\t\tif len(date.dateStart) > 9:\n\t\t\tevent['dtstart'] = date.dateStart\n\t\t\tevent['dtend'] = date.dateFinish\n\t\telse:\n\t\t\tevent['dtstart;value=date'] = date.dateStart\n\t\t\tevent['dtend;value=date'] = date.dateFinish\n\t\tevent['summary'] = vText(date.name)\n\t\tevent['location'] = vText(date.location)\n\t\tevent['description'] = vText(date.description + addition)\n\t\t#create alarm\n\t\talarm = Alarm()\n\t\talarm['trigger'] = vText('-PT4H')\n\t\talarm['action'] = vText('DISPLAY')\n\t\talarm['uid'] = vText(\"iCalIt/alarm/\"+str(date.id))\n\t\talarm['description'] = vText(date.name+\" - Powered by iCalIt\")\n\t\t#add alarm to event\n\t\tevent.add_component(alarm)\n\t\t#add event to calendar\n\t\tcal.add_component(event)\n\treturn cal\n\n\ndef split(txt, seps):\n default_sep = seps[0]\n\n # we skip seps[0] because that's the default seperator\n for sep in seps[1:]:\n txt = txt.replace(sep, default_sep)\n return [i.strip() for i in txt.split(default_sep)]","sub_path":"iCal.py","file_name":"iCal.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"373014393","text":"from modeltranslation.translator import translator, TranslationOptions\nfrom flatblocks.models import FlatBlock\nfrom geonode.maps.models import Layer\n\n\nclass FlatBlockTO(TranslationOptions):\n fields = ('content',)\n\n\nclass LayerTO(TranslationOptions):\n fields = (\n 'title',\n 'edition',\n 'abstract',\n 'purpose',\n 'constraints_other',\n 'distribution_description',\n 'data_quality_statement',\n 'supplemental_information',\n )\n\n\ntranslator.register(FlatBlock, FlatBlockTO)\n#translator.register(Layer, LayerTO)\n\nclass ForceDefaultLanguageMiddleware(object):\n \"\"\"\n Ignore Accept-Language HTTP headers\n\n This will force the I18N machinery to always choose settings.LANGUAGE_CODE\n as the default initial language, unless another one is set via sessions or cookies\n\n Should be installed *before* any middleware that checks request.META['HTTP_ACCEPT_LANGUAGE'],\n namely django.middleware.locale.LocaleMiddleware\n \"\"\"\n def process_request(self, request):\n if request.META.has_key('HTTP_ACCEPT_LANGUAGE'):\n del request.META['HTTP_ACCEPT_LANGUAGE']\n","sub_path":"mozambique/translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"267630035","text":"vowels = ['a','e','i','o','u']\nword = input(\"Give me a word and I'll check dem vowels : \")\n\nfound = {}\t\n\n\nfor letter in word:\n\tif letter in vowels:\n\t\tfound.setdefault(letter,0)\n\t\tfound[letter] += 1\n\nfor k,v in sorted(found.items()):\n\tprint(k,\"was found\",v,\"time (s)\")\n\t\n\n","sub_path":"vowels5.py","file_name":"vowels5.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"345929616","text":"\"\"\"This module contains functions for detecting overlap between\na set of test files (files to check for plagairism) and a set of\nreference files (files that might have been plagairised from).\n\"\"\"\n\nfrom pathlib import Path\nimport time\nimport numpy as np\nimport logging\nfrom .utils import (filter_code, highlight_overlap, get_copied_slices,\n get_document_fingerprints, find_fingerprint_overlap)\nimport matplotlib.pyplot as plt\nimport webbrowser\nimport pkg_resources\nfrom jinja2 import Template\nfrom tqdm import tqdm\nimport io\nimport base64\n\nclass CodeFingerprint:\n \"\"\"Class for tokenizing, filtering, fingerprinting, and winnowing\n a file. Maintains information about fingerprint indexes and token\n indexes to assist code highlighting for the output report.\n\n Parameters\n ----------\n file : str\n Path to the file fingerprints should be extracted from.\n k : int\n Length of k-grams to extract as fingerprints.\n win_size : int\n Window size to use for winnowing (must be >= 1).\n boilerplate : array_like, optional\n List of fingerprints to use as boilerplate. Any fingerprints\n present in this list will be discarded from the hash list.\n filter : bool\n If set to to False, code will not be tokenized & filtered.\n Default: True\n\n Attributes\n ----------\n filename : str\n Name of the originally provided file.\n raw_code : str\n Unfiltered code.\n filtered_code : str\n Code after tokenization and filtering. If filter=False, this is\n the same as raw_code.\n offsets : Nx2 array of ints\n The cumulative number of characters removed during filtering at\n each index of the filtered code. Used for translating locations\n in the filtered code to locations in the unfiltered code.\n hashes : 1D array of ints\n List of fingerprints extracted from the filtered code.\n hash_idx : 1D array of ints\n List of indexes of the selected fingerprints. Used for\n translating hash indexes to indexes in the filtered code.\n k : int\n Value of provided k argument.\n language : str\n If set, will force the tokenizer to use the provided language\n rather than guessing from the file extension.\n \"\"\"\n def __init__(self, file, k, win_size, boilerplate=[], filter=True,\n language=None):\n with open(file) as code_fp:\n code = code_fp.read()\n if filter:\n filtered_code, offsets = filter_code(code, file, language)\n else:\n filtered_code, offsets = code, np.array([])\n hashes, idx = get_document_fingerprints(filtered_code, k, win_size,\n boilerplate)\n\n self.filename = file\n self.raw_code = code\n self.filtered_code = filtered_code\n self.offsets = offsets\n self.hashes = hashes\n self.hash_idx = idx\n self.k = k\n\ndef compare_files(file1_data, file2_data):\n \"\"\"Computes the overlap between two CodeFingerprint objects\n using the generic methods from copy_detect.py. Returns the\n number of overlapping tokens and two tuples containing the\n overlap percentage and copied slices for each unfiltered file.\n\n Parameters\n ----------\n file1_data : CodeFingerprint\n CodeFingerprint object of file #1.\n file2_data : CodeFingerprint\n CodeFingerprint object of file #2.\n\n Returns\n -------\n token_overlap : int\n Number of overlapping tokens between the two files.\n similarities : tuple of 2 ints\n For both files: number of overlapping tokens divided by the\n total number of tokens in that file.\n slices : tuple of 2 2xN int arrays\n For both files: locations of copied code in the unfiltered\n text. Dimension 0 contains slice starts, dimension 1 contains\n slice ends.\n \"\"\"\n if file1_data.k != file2_data.k:\n raise ValueError(\"Code fingerprints must use the same noise threshold\")\n idx1, idx2 = find_fingerprint_overlap(\n file1_data.hashes, file2_data.hashes,\n file1_data.hash_idx, file2_data.hash_idx)\n slices1 = get_copied_slices(idx1, file1_data.k)\n slices2 = get_copied_slices(idx2, file2_data.k)\n if len(slices1[0]) == 0:\n return 0, (0,0), (np.array([]), np.array([]))\n\n token_overlap1 = np.sum(slices1[1] - slices1[0])\n token_overlap2 = np.sum(slices2[1] - slices2[0])\n\n if len(file1_data.filtered_code) > 0:\n similarity1 = token_overlap1 / len(file1_data.filtered_code)\n else:\n similarity1 = 0\n if len(file2_data.filtered_code) > 0:\n similarity2 = token_overlap2 / len(file2_data.filtered_code)\n else:\n similarity2 = 0\n\n if len(file1_data.offsets) > 0:\n slices1 += file1_data.offsets[:,1][np.clip(\n np.searchsorted(file1_data.offsets[:,0], slices1),\n 0, file1_data.offsets.shape[0] - 1)]\n if len(file2_data.offsets) > 0:\n slices2 += file2_data.offsets[:,1][np.clip(\n np.searchsorted(file2_data.offsets[:,0], slices2),\n 0, file2_data.offsets.shape[0] - 1)]\n\n return token_overlap1, (similarity1,similarity2), (slices1,slices2)\n\nclass CopyDetector:\n \"\"\"Main plagairism detection class. Searches provided directories\n and uses detection parameters to calculate similarity between all\n files found in the directories\n\n Parameters\n ----------\n config : dict\n Dictionary containing configuration parameters. Note that this\n uses the verbose version of each of the parameters listed\n below. If provided, parameters set in the configuration\n dictionary will overwrite default parameters and other\n parameters passed to the initialization function.\n test_dirs : list\n (test_directories) A list of directories to recursively search\n for files to check for plagiarism.\n ref_dirs: list\n (reference_directories) A list of directories to search for\n files to compare the test files to. This should generally be a\n superset of test_directories\n boilerplate_dirs : list\n (boilerplate_directories) A list of directories containing\n boilerplate code. Matches between fingerprints present in the\n boilerplate code will not be considered plagiarism.\n extensions : list\n A list of file extensions containing code the detector should\n look at.\n noise_t : int\n (noise_threshold) The smallest sequence of matching characters\n between two files which should be considered plagiarism. Note\n that tokenization and filtering replaces variable names with V,\n function names with F, object names with O, and strings with S\n so the threshold should be lower than you would expect from the\n original code.\n guarantee_t : int\n (guarantee_threshold) The smallest sequence of matching\n characters between two files for which the system is guaranteed\n to detect a match. This must be greater than or equal to the\n noise threshold. If computation time is not an issue, you can\n set guarantee_threshold = noise_threshold.\n display_t : float\n (display_threshold) The similarity percentage cutoff for\n displaying similar files on the detector report.\n same_name_only : bool\n If true, the detector will only compare files that have the\n same name\n ignore_leaf : bool\n If true, the detector will not compare files located in the\n same leaf directory.\n autoopen : bool\n If true, the detector will automatically open a webbrowser to\n display the results of generate_html_report\n disable_filtering : bool\n If true, the detector will not tokenize and filter code before\n generating file fingerprints.\n force_language : str\n If set, forces the tokenizer to use a particular programming\n language regardless of the file extension.\n truncate : bool\n If true, highlighted code will be truncated to remove non-\n highlighted regions from the displayed output\n out_file : str\n Path to output report file.\n silent : bool\n If true, all logging output will be supressed.\n \"\"\"\n def __init__(self, config=None, test_dirs=[], ref_dirs=[],\n boilerplate_dirs=[], extensions=[\"*\"],\n noise_t=25, guarantee_t=30, display_t=0.33,\n same_name_only=False, ignore_leaf=False, autoopen=True,\n disable_filtering=False, force_language=None,\n truncate=False, out_file=\"./report.html\", silent=False):\n self.silent = silent\n self.test_dirs = test_dirs\n if len(ref_dirs) == 0:\n self.ref_dirs = test_dirs\n else:\n self.ref_dirs = ref_dirs\n self.boilerplate_dirs = boilerplate_dirs\n self.extensions = extensions\n self.noise_t = noise_t\n self.guarantee_t = guarantee_t\n self.display_t = display_t\n self.same_name_only = same_name_only\n self.ignore_leaf = ignore_leaf\n self.autoopen = autoopen\n self.disable_filtering = disable_filtering\n self.force_language = force_language\n self.truncate = truncate\n self.out_file = out_file\n\n if config is not None:\n self._load_config(config)\n\n self._check_arguments()\n\n out_path = Path(self.out_file)\n if out_path.is_dir():\n self.out_file += \"/report.html\"\n elif out_path.suffix != \".html\":\n self.out_file = str(out_path) + \".html\"\n\n self.window_size = self.guarantee_t - self.noise_t + 1\n\n self.test_files = self._get_file_list(self.test_dirs, self.extensions)\n self.ref_files = self._get_file_list(self.ref_dirs, self.extensions)\n self.boilerplate_files = self._get_file_list(self.boilerplate_dirs,\n self.extensions)\n\n def _load_config(self, config):\n \"\"\"Sets member variables according to a configuration\n dictionary.\n \"\"\"\n self.noise_t = config[\"noise_threshold\"]\n self.guarantee_t = config[\"guarantee_threshold\"]\n self.display_t = config[\"display_threshold\"]\n self.test_dirs = config[\"test_directories\"]\n if \"reference_directories\" in config:\n self.ref_dirs = config[\"reference_directories\"]\n if \"extensions\" in config:\n self.extensions = config[\"extensions\"]\n if \"boilerplate_directories\" in config:\n self.boilerplate_dirs = config[\"boilerplate_directories\"]\n if \"force_language\" in config:\n self.force_language = config[\"force_language\"]\n if \"same_name_only\" in config:\n self.same_name_only = config[\"same_name_only\"]\n if \"ignore_leaf\" in config:\n self.ignore_leaf = config[\"ignore_leaf\"]\n if \"disable_filtering\" in config:\n self.disable_filtering = config[\"disable_filtering\"]\n if \"disable_autoopen\" in config:\n self.autoopen = not config[\"disable_autoopen\"]\n if \"truncate\" in config:\n self.truncate = config[\"truncate\"]\n if \"out_file\" in config:\n self.out_file = config[\"out_file\"]\n\n def _check_arguments(self):\n \"\"\"type/value checking helper function for __init__\"\"\"\n if not isinstance(self.test_dirs, list):\n raise TypeError(\"Test directories must be a list\")\n if not isinstance(self.ref_dirs, list):\n raise TypeError(\"Reference directories must be a list\")\n if not isinstance(self.extensions, list):\n raise TypeError(\"extensions must be a list\")\n if not isinstance(self.boilerplate_dirs, list):\n raise TypeError(\"Boilerplate directories must be a list\")\n if not isinstance(self.same_name_only, bool):\n raise TypeError(\"same_name_only must be true or false\")\n if not isinstance(self.ignore_leaf, bool):\n raise TypeError(\"ignore_leaf must be true or false\")\n if not isinstance(self.disable_filtering, bool):\n raise TypeError(\"disable_filtering must be true or false\")\n if not isinstance(self.autoopen, bool):\n raise TypeError(\"disable_autoopen must be true or false\")\n if self.force_language is not None:\n if not isinstance(self.force_language, str):\n raise TypeError(\"force_language must be a string\")\n if not isinstance(self.truncate, bool):\n raise TypeError(\"truncate must be true or false\")\n if not isinstance(self.noise_t, int):\n if int(self.noise_t) == self.noise_t:\n self.noise_t = int(self.noise_t)\n self.window_size = int(self.window_size)\n else:\n raise TypeError(\"Noise threshold must be an integer\")\n if not isinstance(self.guarantee_t, int):\n if int(self.guarantee_t) == self.guarantee_t:\n self.guarantee_t = int(self.guarantee_t)\n self.window_size = int(self.window_size)\n else:\n raise TypeError(\"Guarantee threshold must be an integer\")\n\n # value checking\n if self.guarantee_t < self.noise_t:\n raise ValueError(\"Guarantee threshold must be greater than or \"\n \"equal to noise threshold\")\n if self.display_t > 1 or self.display_t < 0:\n raise ValueError(\"Display threshold must be between 0 and 1\")\n if Path(self.out_file).parent.exists() == False:\n raise ValueError(\"Invalid output file path \"\n \"(directory does not exist)\")\n\n def _get_file_list(self, dirs, exts, unique=True):\n \"\"\"Recursively collects list of files from provided\n directories. Used to search test_dirs, ref_dirs, and\n boilerplate_dirs\n \"\"\"\n file_list = []\n for dir in dirs:\n for ext in exts:\n if ext == \"*\":\n matched_contents = Path(dir).rglob(\"*\")\n else:\n matched_contents = Path(dir).rglob(\"*.\"+ext.lstrip(\".\"))\n files = [str(f) for f in matched_contents if f.is_file()]\n\n if len(files) == 0:\n logging.warning(\"No files found in \" + dir)\n file_list.extend(files)\n\n return set(file_list)\n\n def add_file(self, filename, type=\"testref\"):\n \"\"\"Adds a file to the list of test files, reference files, or\n boilerplate files. The \"type\" parameter should be one of\n [\"testref\", \"test\", \"ref\", \"boilerplate\"]. \"testref\" will add\n the file as both a test and reference file.\n \"\"\"\n if type == \"testref\":\n self.test_files.add(filename)\n self.ref_files.add(filename)\n elif type == \"test\":\n self.test_files.add(filename)\n elif type == \"ref\":\n self.ref_files.add(filename)\n elif type == \"boilerplate\":\n self.boilerplate_files.add(filename)\n\n def _get_boilerplate_hashes(self):\n \"\"\"Generates a list of hashes of the boilerplate text. Returns\n a set containing all unique k-gram hashes across all files\n found in the boilerplate directories.\n \"\"\"\n boilerplate_hashes = []\n for file in self.boilerplate_files:\n try:\n with open(file) as boilerplate_fp:\n boilerplate = boilerplate_fp.read()\n except UnicodeDecodeError:\n logging.warning(f\"Skipping {file}: file not ASCII text\")\n continue\n fingerprint = CodeFingerprint(file, self.noise_t, 1,\n filter=not self.disable_filtering,\n language=self.force_language)\n boilerplate_hashes.extend(fingerprint.hashes)\n\n return np.unique(np.array(boilerplate_hashes))\n\n def _preprocess_code(self, file_list):\n boilerplate_hashes = self._get_boilerplate_hashes()\n\n file_data = {}\n for code_f in tqdm(file_list, bar_format= ' {l_bar}{bar}{r_bar}',\n disable=self.silent):\n try:\n file_data[code_f] = CodeFingerprint(\n code_f, self.noise_t, self.window_size,\n boilerplate_hashes, not self.disable_filtering,\n self.force_language)\n\n except UnicodeDecodeError:\n logging.warning(f\"Skipping {code_f}: file not ASCII text\")\n continue\n\n return file_data\n\n def _comparison_loop(self):\n \"\"\"The core code used to determine code overlap. The overlap\n between each test file and each compare file is computed and\n stored in similarity_matrix. Token overlap information and the\n locations of copied code are stored in slice_matrix and\n token_overlap_matrix, respectively.\n \"\"\"\n start_time = time.time()\n if not self.silent:\n print(\" 0.00: Generating file fingerprints\")\n test_f_list = sorted(list(self.test_files))\n self.all_files = (test_f_list\n + sorted([f for f in self.ref_files if f not in self.test_files]))\n self.file_data = self._preprocess_code(self.all_files)\n\n self.similarity_matrix = np.full((\n len(self.all_files), len(self.all_files)), -1, dtype=np.float64)\n self.token_overlap_matrix = np.full((\n len(self.all_files), len(self.all_files)), -1)\n self.slice_matrix = [[np.array([]) for _ in range(len(self.all_files))]\n for _ in range(len(self.all_files))]\n\n if not self.silent:\n print(f\"{time.time()-start_time:6.2f}: Beginning code comparison\")\n\n for i, test_f in enumerate(tqdm(test_f_list,\n bar_format= ' {l_bar}{bar}{r_bar}', disable=self.silent)):\n for j, ref_f in enumerate(self.all_files):\n if test_f not in self.file_data or ref_f not in self.file_data:\n continue\n elif test_f == ref_f:\n continue\n elif self.similarity_matrix[i,j] != -1:\n continue\n elif (self.all_files[i] not in self.test_files or\n self.all_files[j] not in self.ref_files):\n continue\n\n if self.same_name_only:\n if Path(test_f).name != Path(ref_f).name:\n continue\n if self.ignore_leaf:\n if Path(test_f).parent == Path(ref_f).parent:\n continue\n\n overlap, (sim1,sim2), (slices1,slices2) = compare_files(\n self.file_data[test_f], self.file_data[ref_f])\n\n self.similarity_matrix[i,j] = sim1\n self.slice_matrix[i][j] = [slices1, slices2]\n self.similarity_matrix[j,i] = sim2\n self.slice_matrix[j][i] = [slices2,slices1]\n\n self.token_overlap_matrix[i,j] = overlap\n self.token_overlap_matrix[j,i] = overlap\n\n if not self.silent:\n print(f\"{time.time()-start_time:6.2f}: Code comparison completed\")\n\n def run(self):\n \"\"\"User-facing code overlap computing function. Checks for a\n session that can be resumed from then calls _comparison_loop to\n generate results.\n \"\"\"\n if len(self.test_files) == 0 or len(self.ref_files) == 0:\n err_folder = \"test\"\n if len(self.test_files) > len(self.ref_files):\n err_folder = \"reference\"\n\n logging.error(\"Copy detector failed: No files found in \"\n f\"{err_folder} directories\")\n self.similarity_matrix = np.array([])\n self.token_overlap_matrix = np.array([])\n self.slice_matrix = np.array([])\n return\n\n self._comparison_loop()\n\n def get_copied_code_list(self):\n \"\"\"Get a list of copied code to display on the output report.\n Returns a list of tuples containing the similarity score, the\n test file name, the compare file name, the highlighted test\n code, and the highlighted compare code,\n \"\"\"\n if len(self.similarity_matrix) == 0:\n logging.error(\"Cannot generate code list: no files compared\")\n return []\n x,y = np.where(self.similarity_matrix > self.display_t)\n\n code_list = []\n selected_pairs = set([])\n for idx in range(len(x)):\n test_f = self.all_files[x[idx]]\n ref_f = self.all_files[y[idx]]\n if test_f + ref_f in selected_pairs:\n continue\n\n selected_pairs.add(test_f + ref_f)\n selected_pairs.add(ref_f + test_f)\n test_sim = self.similarity_matrix[x[idx], y[idx]]\n ref_sim = self.similarity_matrix[y[idx], x[idx]]\n slices_test = self.slice_matrix[x[idx]][y[idx]][0]\n slices_ref = self.slice_matrix[x[idx]][y[idx]][1]\n\n if self.truncate:\n truncate = 10\n else:\n truncate = -1\n hl_code_1, _ = highlight_overlap(\n self.file_data[test_f].raw_code, slices_test,\n \"\", \"\",\n truncate=truncate, escape_html=True)\n hl_code_2, _ = highlight_overlap(\n self.file_data[ref_f].raw_code, slices_ref,\n \"\", \"\",\n truncate=truncate, escape_html=True)\n overlap = self.token_overlap_matrix[x[idx], y[idx]]\n\n code_list.append([test_sim, ref_sim, test_f, ref_f,\n hl_code_1, hl_code_2, overlap])\n\n code_list.sort(key=lambda x: -x[0])\n return code_list\n\n def generate_html_report(self, output_mode=\"save\"):\n \"\"\"Generates an html report listing all files with similarity\n above the display_threshold, with the copied code segments\n highlighted.\n \"\"\"\n if len(self.similarity_matrix) == 0:\n logging.error(\"Cannot generate report: no files compared\")\n return\n\n code_list = self.get_copied_code_list()\n data_dir = pkg_resources.resource_filename('copydetect', 'data/')\n\n plot_mtx = np.copy(self.similarity_matrix)\n plot_mtx[plot_mtx == -1] = np.nan\n plt.imshow(plot_mtx)\n plt.colorbar()\n plt.tight_layout()\n sim_mtx_buffer = io.BytesIO()\n plt.savefig(sim_mtx_buffer)\n sim_mtx_buffer.seek(0)\n sim_mtx_base64 = base64.b64encode(sim_mtx_buffer.read()).decode()\n plt.close()\n\n scores = self.similarity_matrix[self.similarity_matrix != -1]\n plt.hist(scores, bins=20)\n plt.tight_layout()\n sim_hist_buffer = io.BytesIO()\n plt.savefig(sim_hist_buffer)\n sim_hist_buffer.seek(0)\n sim_hist_base64 = base64.b64encode(sim_hist_buffer.read()).decode()\n plt.close()\n\n # render template with jinja and save as html\n with open(data_dir + \"report.html\") as template_fp:\n template = Template(template_fp.read())\n\n flagged = self.similarity_matrix > self.display_t\n flagged_file_count = np.sum(np.any(flagged, axis=1))\n\n output = template.render(test_count=len(self.test_files),\n compare_count=len(self.ref_files),\n flagged_file_count=flagged_file_count,\n code_list=code_list,\n sim_mtx_base64=sim_mtx_base64,\n sim_hist_base64=sim_hist_base64)\n\n if output_mode == \"save\":\n with open(self.out_file, \"w\") as report_f:\n report_f.write(output)\n\n if not self.silent:\n print(f\"Output saved to {self.out_file.replace('//', '/')}\")\n if self.autoopen:\n webbrowser.open('file://' + str(Path(self.out_file).resolve()))\n elif output_mode == \"return\":\n return output\n else:\n raise ValueError(\"output_mode not supported\")\n","sub_path":"copydetect/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":24298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"413220843","text":"# -*- encoding: utf-8 -*-\n\nfrom django.views import generic\nfrom jobs.models import Job, JobPostulation\nfrom accounts.models import User\nfrom django.http import JsonResponse\n\nclass StatsView(generic.View):\n \n def get(self, response):\n jobs = len(Job.objects.all())\n users = 0\n employers = 0\n for user in User.objects.all():\n if user.is_employer:\n employers += 1\n users += 1\n return JsonResponse({ \"jobs\": jobs, \"users\": users, \"employers\": employers })","sub_path":"rolejobs_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"150335006","text":"import re\nimport argparse\n\nfrom pyserini.search.pysearch import get_topics,SimpleSearcher\n\nparser = argparse.ArgumentParser(description='Create a input schema')\nparser.add_argument('-index', metavar='path', required=True,\n help='the path to workspace')\nparser.add_argument('-topics', metavar='topicsname', required=True,\n help='topicsname')\nparser.add_argument('-output', metavar='path', required=True,\n help='path to the output file')\nparser.add_argument('-rm3', action='store_true',\n help='take rm3 ranker')\nparser.add_argument('-qld', action='store_true',\n help='take qld ranker')\nargs = parser.parse_args()\nsearcher = SimpleSearcher(args.index)\ntopics_dic = get_topics(args.topics)\nif topics_dic != {}:\n target_file = open(args.output, 'w')\n for key, value in sorted(topics_dic.items()):\n search = value.get('title')\n hits = searcher.search(search, 1000)\n for i in range(0, len(hits)):\n target_file.write(f'{key} Q0 {hits[i].docid.strip()} {i + 1} {hits[i].score:.6f} Anserini\\n')\n target_file.close()\nelse:\n print('Topic Not Found')","sub_path":"pyserini/search/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"88822325","text":"from api.views import *\nfrom rest_framework.routers import DefaultRouter\nfrom django.urls import path\n\n\n\nrouter = DefaultRouter(trailing_slash=False)\nurlpatterns = [\n path('getuseruni', getuseruni),\n path('signup', signup),\n]\n\nrouter.register(r'post', PostViewSet, basename='post')\n\nrouter.register(r'comment', CommentViewSet, basename='comment')\n\nrouter.register(r'university', UniViewSet, basename='university')\n\nurlpatterns += router.urls\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"617618753","text":"import argparse\nimport collections\nimport numpy as np\n\ndef read_file(file_path):\n print(\"Read dataset: %s\" % args.input_file)\n attrs_list = collections.defaultdict(list)\n attrs = []\n labels = []\n with open(file_path, 'r') as dataset:\n for line in dataset.readlines():\n toks = line.strip().split(' ')\n labels.append(int(toks[0]))\n attr_vec = dict()\n for key, value in [pair.split(':') for pair in toks[1:]]:\n # print(key, value)\n key, value = int(key), float(value)\n attrs_list[key].append(value)\n attr_vec[key] = value\n attrs.append(attr_vec)\n \n # Map key to [0, d - 1]. d is the dimension of attributes\n key_mapping = dict()\n for i, key in enumerate(sorted(attrs_list.keys())):\n key_mapping[key] = len(key_mapping)\n\n bin_attr = 0\n attr_mean = np.zeros((len(key_mapping),), dtype=float)\n attr_std = np.zeros((len(key_mapping),), dtype=float)\n for key, index in key_mapping.items():\n attr_mean[index] = np.mean(attrs_list[key])\n attr_std[index] = np.std(attrs_list[key])\n if attr_std[index] < 1e-10:\n bin_attr += 1\n \n print('Binary attributes: %d, Unknown type: %d' % (bin_attr, len(key_mapping) - bin_attr))\n\n X = np.zeros((len(attrs), len(key_mapping),), dtype=float)\n for i, attr_vec in enumerate(attrs):\n for key, index in key_mapping.items():\n if attr_std[index] < 1e-10:\n X[i, index] = attr_vec.get(key, 0)\n else:\n X[i, index] = attr_vec.get(key, attr_mean[index])\n\n return X, np.array(labels)\n\ndef pca(X, total_threshold=0.5, single_threshold=0.01):\n x_mean = np.mean(X, axis=0)\n S = (X - x_mean).T.dot(X - x_mean) / (X.shape[0] - 1)\n\n eig_value, eig_vec = np.linalg.eig(S)\n eig_value_with_index = sorted(\n [(i, eig_value[i]) for i in range(len(eig_value))],\n key=lambda tup: tup[1],\n reverse=True\n )\n eig_value_sum = np.sum(eig_value) + 1e-10\n eig_value_cumulative = 0\n eig_vec_used = []\n \n for tup in eig_value_with_index:\n if tup[1] / eig_value_sum < single_threshold and eig_value_cumulative / eig_value_sum > total_threshold:\n break\n eig_value_cumulative += tup[1]\n eig_vec_used.append(tup[0])\n\n print('Reduce dimension: %d -> %d' % (X.shape[1], len(eig_vec_used)))\n eig_vec_selected = eig_vec[:, eig_vec_used]\n return (lambda X: X.dot(eig_vec_selected).real)\n\ndef normalization(X, mean, std):\n if mean is None or std is None:\n mean = np.zeros(X.shape[1])\n std = np.zeros(X.shape[1])\n for i in range(X.shape[1]):\n mean[i] = X[:,i].mean()\n std[i] = X[:,i].std()\n X_ = np.zeros(X.shape)\n for i in range(X.shape[1]):\n if std[i] == 0:\n X_[:,i] = 0\n else:\n X_[:,i] = (X[:,i]) / std[i]\n return X_, mean, std\n\ndef save_dataset(output_path, X, Y):\n print('Save file to: %s' % output_path)\n buf = []\n for i in range(len(Y)):\n buf.append('%s %s\\n' % (\n Y[i],\n ' '.join(['%d:%.6f' % (j + 1, X.real[i, j]) for j in range(X.shape[1])])\n ))\n with open(output_path, 'w') as output_dataset:\n output_dataset.write(\"\".join(buf))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dimension reduction')\n parser.add_argument('input_file')\n args = parser.parse_args()\n\n X, Y = read_file(args.input_file)\n X, mean, std = normalization(X, None, None)\n X = pca(X)(X)\n\n save_dataset(args.input_file[:-4] + '_out.txt', X, Y)","sub_path":"Assignment-3/0410824.py","file_name":"0410824.py","file_ext":"py","file_size_in_byte":3666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"468266997","text":"# -*- coding: utf-8 -*-\nfrom openerp import api, fields, models, _, tools\nfrom openerp.exceptions import UserError, RedirectWarning, ValidationError\nimport datetime\n\n\nclass account_invoice_Inherit(models.Model):\n _inherit = \"account.invoice\"\n\n @api.multi\n def invoice_validate(self):\n '''Generates the cfdi attachments for mexican companies when validated.'''\n result = super(account_invoice_Inherit, self).invoice_validate()\n version = self.l10n_mx_edi_get_pac_version()\n for record in self.filtered(lambda r: r.l10n_mx_edi_is_required()):\n if record.type == 'out_refund' and not record.refund_invoice_id.l10n_mx_edi_cfdi_uuid:\n record.message_post(\n body='

' + _(\n 'The invoice related has no valid fiscal folio. For this '\n 'reason, this refund didn\\'t generate a fiscal document.') + '

',\n subtype='account.mt_invoice_validated')\n continue\n record.l10n_mx_edi_cfdi_name = ('%s-%s-MX-Invoice-%s.xml' % (\n record.journal_id.code, record.number, version.replace('.', '-'))).replace('/', '')\n record._l10n_mx_edi_retry()\n #self._assign_payment_invoice_global()\n return result\n\n @api.multi\n def assign_payment_invoice_global(self):\n if self.state == 'open':\n if 'Factura Global' in self.origin:\n pos_order = self.env['pos.order'].search([('invoice_id','=',self.id)])\n payment_type = self.type in ('out_invoice', 'in_refund') and 'inbound' or 'outbound'\n if payment_type == 'inbound':\n payment_method = self.env.ref('account.account_payment_method_manual_in')\n else:\n payment_method = self.env.ref('account.account_payment_method_manual_out')\n vals = {\n 'invoice_ids': [(6, 0, self.ids)],\n 'amount' : self.residual,\n 'journal_id' : 12,\n 'payment_date' : datetime.datetime.now(),\n 'communication': self.number,\n 'partner_id': self.partner_id.id,\n 'partner_type': self.type in ('out_invoice', 'out_refund') and 'customer' or 'supplier',\n 'payment_type': payment_type,\n 'payment_method_id': payment_method.id\n }\n payment = self.env['account.payment'].create(vals)\n payment.post()\n","sub_path":"xmarts_pos_invoice/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"184528801","text":"from db import session\nfrom utils.util import uid, model_to_dict, encoded_text, decoded_text\nfrom models.subject_gallery_model import SubjectsModel, SubjectGalleryModel\n\nfrom mappers.subjects_mapper import SubjectsMapper\nfrom mappers.subject_gallery_mapper import SubjectGalleryMapper\n\nimport datetime\n\n\nclass SubjectGalleryService:\n session_info = None\n\n def mapping(self, model, view):\n view['subjectImg'] = view.get('subjectImg')\n model.subjects = session.query(SubjectsModel).filter_by(id=view['subjectId']).first()\n if model.id is None:\n model.id = uid()\n model.subjectId = model.subjects.id\n model.subjectImg= view['subjectImg']\n\n model.createdOn = datetime.datetime.now()\n model.updatedOn = datetime.datetime.now()\n SubjectGalleryMapper(model, view).model_mapping()\n SubjectsMapper(model.subjects, view.get('subjects')).model_mapping()\n\n def is_validate(self, model, is_new):\n\n query = session.query(SubjectGalleryModel). \\\n filter(\n (SubjectGalleryModel.subjectId == model.subjectId)\n )\n data_list = query.all()\n if data_list:\n if is_new:\n print(\"true\")\n return False\n else:\n for item in data_list:\n print(\"item\", item)\n if item.id != model.id:\n print(\"item.id\", item.id)\n print(\"model.id\", model.id)\n return False\n return True\n\n def map_data(self, data):\n data['subjectName'] = data['subjects']['name']\n del data['subjects']\n return data\n\n def model(self, _id):\n data = session.query(SubjectGalleryModel).filter_by(id=_id).first()\n data = model_to_dict(data)\n return self.map_data(data)\n\n def save(self, req_data):\n\n subject_gallery = None\n _id = req_data.get('id')\n print(_id)\n if _id is not None:\n subject_gallery = session.query(SubjectGalleryModel).filter_by(id=_id).first()\n if subject_gallery is None:\n subject_gallery = SubjectGalleryModel()\n self.mapping(subject_gallery, req_data)\n\n if self.is_validate(subject_gallery, False if _id else True):\n session.add(subject_gallery)\n session.commit()\n return {'message': 'Saved Successfully', 'id': subject_gallery.id}\n else:\n raise Exception('Record already exists')\n\n def search(self, req_data):\n result = []\n query = session.query(SubjectGalleryModel)\n if req_data and req_data.get('subjectId'):\n query = query.filter_by(subjectId=req_data['subjectId'])\n data_list = query.limit(9999).all()\n res = [model_to_dict(x) for x in data_list]\n result = list(map(self.map_data, res))\n return result\n\n def delete(self, id):\n user = SubjectGalleryModel.query.get(id)\n session.delete(user)\n session.commit()\n return {'message': 'deleted Successfully', 'id': id}","sub_path":"src/services/subject_gallery_service.py","file_name":"subject_gallery_service.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"369133366","text":"import pygame\nimport os\nMPATH = os.path.dirname( os.path.abspath(__file__) )\n\nfrom PygameUI.screen import Widget, cHandle\n\n# convert your button image\tbefore passing them to them button\nclass ButtonImage(object):\n\tdef __init__(self, normal, over, toggle, down, _is_converted=False):\n\t\tself.normal = normal\n\t\tself.over = over\n\t\tself.toggle = toggle\n\t\tself.down = down\n\t\tself.is_converted = _is_converted\n\t\t\n\tdef convert(self, colorkey=(0,0,0)):\n\t\tself.normal = self.normal.convert()\n\t\tself.over = self.over.convert()\n\t\tself.toggle = self.toggle.convert()\n\t\tself.down = self.down.convert()\n\t\tself.is_converted = True\n\t\t\n\tdef convert_alpha(self):\n\t\tself.normal = self.normal.convert_alpha()\n\t\tself.over = self.over.convert_alpha()\n\t\tself.toggle = self.toggle.convert_alpha()\n\t\tself.down = self.down.convert_alpha()\n\t\tself.is_converted = True\n\t\t\n\tdef scale(self, size):\n\t\treturn ButtonImage(\n\t\t\tpygame.transform.scale(self.normal, size),\n\t\t\tpygame.transform.scale(self.over, size),\n\t\t\tpygame.transform.scale(self.toggle, size),\n\t\t\tpygame.transform.scale(self.down, size),\n\t\t\tself.is_converted )\n\t\t\n\nclass ButtonBase(Widget):\n\tdef __init__(self, ui_string, rect, callback=None, pydata=None, toggle=False, group=None, image=None):\n\t\tif not isinstance(rect, pygame.Rect):\n\t\t\trect = pygame.Rect(rect)\n\t\t\t\n\t\tself.string = ui_string\n\t\tself._string_handle(rect)\n\t\tself._image_load(rect, image)\n\t\t\n\t\tself.rect = rect\n\t\tself.callback = callback\n\t\tself.mouseover = False\n\t\tself.group = group\n\t\t\n\t\tself.data = cHandle()\n\t\tself.data.pydata = pydata\n\t\tself.data.toggle = toggle\n\t\tself.data.text = self._text\n\t\t\n\tdef _text(self, text):\n\t\tself.string.text = text\n\t\t\n\tdef blit(self, surface):\n\t\tif self.mouseover and self.data.toggle:\n\t\t\tsurface.blit(self.image.down, self.rect.topleft)\n\t\telif self.mouseover:\n\t\t\tsurface.blit(self.image.over, self.rect.topleft)\n\t\telif self.data.toggle:\n\t\t\tsurface.blit(self.image.toggle, self.rect.topleft)\n\t\telse:\n\t\t\tsurface.blit(self.image.normal, self.rect.topleft)\n\t\t\t\n\t\tself.string.blit(surface)\n\t\t\t\t\nclass Button(ButtonBase):\n\tdefault_image = ButtonImage(\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_button_u.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_button_uo.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_button_d.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_button_do.png\")))\n\t\n\tdef _string_handle(self, rect):\n\t\tself.string.position = rect.center\n\t\t\n\tdef _image_load(self, rect, image):\n\t\tif image is None:\n\t\t\tif not Button.default_image.is_converted:\n\t\t\t\tButton.default_image.convert_alpha()\n\t\t\tself.image = Button.default_image.scale(rect.size)\n\t\telse:\n\t\t\tself.image = image.scale(rect.size)\n\n\t\t\n\tdef event(self, event):\n\t\tif event.type == pygame.MOUSEBUTTONUP:\n\t\t\tif self.mouseover and self.data.toggle:\n\t\t\t\tif event.button == 1:\n\t\t\t\t\tself.data.toggle = False\n\t\t\t\t\tif self.callback is not None:\n\t\t\t\t\t\tself.callback( self.data )\n\t\t\t\t\t\t\n\t\telif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tif self.mouseover:\n\t\t\t\tif event.button == 1:\n\t\t\t\t\tself.data.toggle = True\n\t\t\t\n\t\telif event.type == pygame.MOUSEMOTION:\n\t\t\tself.mouseover = self.rect.collidepoint(event.pos)\n\t\t\tif self.data.toggle and not self.mouseover:\n\t\t\t\tself.data.toggle = False\n\nclass ToggleButton(Button):\t\t\n\tdef event(self, event):\n\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\tif self.mouseover and event.button == 1:\n\t\t\t\tif self.data.toggle:\n\t\t\t\t\tself.data.toggle = False\n\t\t\t\t\tself.callback(self.data)\n\t\t\t\t\tif self.group is not None:\n\t\t\t\t\t\tself.group.focus = None\n\t\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tself.data.toggle = True\n\t\t\t\t\tif self.group is not None:\n\t\t\t\t\t\tif self.group.focus is not None:\n\t\t\t\t\t\t\tself.group.focus.data.toggle = False\n\t\t\t\t\t\tself.group.focus = self\t\n\t\t\t\t\tself.callback(self.data)\n\n\t\telif event.type == pygame.MOUSEMOTION:\n\t\t\tself._mouse_collide(event.pos)\n\t\n\tdef _mouse_collide(self, pos):\t\t\n\t\tself.mouseover = self.rect.collidepoint(pos)\n\t\t\t\t\nclass CheckBox(ToggleButton):\n\tdefault_image = ButtonImage(\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_box_u.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_box_o.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_box_mo.png\")),\n\t\tpygame.image.load(os.path.join(MPATH, \"UI_Images/blue_box_m.png\")))\n\t\t\t\n\tdef _string_handle(self, rect):\n\t\tself.string.position = rect.left, rect.centery\n\t\tself.string.anchor_left()\n\t\t\n\tdef _image_load(self, rect, image):\n\t\tsize = int(rect.h * .25 + rect.h), rect.h\n\t\tif image is None:\n\t\t\tif not CheckBox.default_image.is_converted:\n\t\t\t\tCheckBox.default_image.convert_alpha()\n\t\t\tself.image = CheckBox.default_image.scale(size)\n\t\telse:\n\t\t\tself.image = image.scale(size)\n\t\t\n\t\tself.boxrect = self.image.normal.get_rect()\n\t\tself.boxrect.topright = rect.topleft\n\t\t\n\tdef blit(self, surface):\n\t\tif self.data.toggle and self.mouseover:\n\t\t\tsurface.blit(self.image.toggle, self.boxrect.topleft)\n\t\telif self.data.toggle:\n\t\t\tsurface.blit(self.image.down, self.boxrect.topleft)\n\t\telif self.mouseover:\n\t\t\tsurface.blit(self.image.over, self.boxrect.topleft)\n\t\telse:\n\t\t\tsurface.blit(self.image.normal, self.boxrect.topleft)\n\t\t\t\n\t\tself.string.blit(surface)\n\t\t\n\tdef _mouse_collide(self, pos):\t\t\n\t\tself.mouseover = self.boxrect.collidepoint(pos)\n","sub_path":"PygameUI/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":5205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"13584567","text":"import pymongo\nimport pandas as pd\nimport requests\nimport csv\nimport os\nfrom argparse import ArgumentParser\nimport xml.etree.ElementTree as ET\nfrom urllib.request import urlopen\n\n\"\"\"UPA - 1st part\n Theme: Covid-19\n Authors: \n - Filip Bali (xbalif00)\n - Natália Holková (xholko02)\n - Roland Žitný (xzitny01)\n\"\"\"\n\nparser = ArgumentParser(prog='UPA-data_loader')\nparser.add_argument('-m', '--mongo', help=\"Mongo db location\",\n default=\"mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000\")\nparser.add_argument('-f', '--folder', help=\"Folder for downloading csv files\", default=\"data/\")\nparser.add_argument('-d', '--database', help=\"Database name\", default=\"UPA-db\")\n\nDATA_FOLDER = \"data/\"\nCSV_FILES = {\n \"infected\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/osoby.csv\",\n \"filename\": DATA_FOLDER + \"infected.csv\"},\n \"cured\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/vyleceni.csv\",\n \"filename\": DATA_FOLDER + \"cured.csv\"},\n \"dead\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/umrti.csv\",\n \"filename\": DATA_FOLDER + \"dead.csv\"},\n \"hospitalized\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/hospitalizace.csv\",\n \"filename\": DATA_FOLDER + \"hospitalized.csv\"},\n \"tests\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/testy-pcr-antigenni.csv\",\n \"filename\": DATA_FOLDER + \"tests.csv\"},\n \"vaccinated_geography\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/ockovani-geografie.csv\",\n \"filename\": DATA_FOLDER + \"vaccinated-geography.csv\"},\n \"demographic_data\":\n {\"url\": \"https://www.czso.cz/documents/62353418/143522504/130142-21data043021.csv/760fab9c-d079-4d3a-afed-59cbb639e37d?version=1.1\",\n \"filename\": DATA_FOLDER + \"demographic_data.csv\"},\n \"vaccinated_by_profession\":\n {\"url\": \"https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/ockovani-profese.csv\",\n \"filename\": DATA_FOLDER + \"vaccinated_by_profession.csv\"},\n}\n\nXML_FILES = {\n \"region_enumerator\":\n {\"url\": \"http://apl.czso.cz/iSMS/cisexp.jsp?kodcis=100&typdat=0&cisjaz=203&format=0\",\n \"filename\": DATA_FOLDER + \"region_enumerator.xml\"},\n\n \"district_enumerator\":\n {\"url\": \"http://apl.czso.cz/iSMS/cisexp.jsp?kodcis=101&typdat=0&cisjaz=203&format=0\",\n \"filename\": DATA_FOLDER + \"district_enumerator.xml\"},\n}\ngender_dict = {\"M\": \"male\", \"Z\": \"female\"}\n\n\ndef download_csv(url, filename):\n \"\"\"\n Get CSV data.\n\n Args:\n url: csv URL\n filename: name of file\n\n \"\"\"\n # check if already downloaded\n if not os.path.exists(filename):\n # download csv\n response = requests.get(url)\n with open(filename, 'w') as f:\n writer = csv.writer(f)\n for line in response.iter_lines():\n writer.writerow(line.decode('utf-8').split(','))\n\n\ndef download_xml(url, filename):\n if not os.path.exists(filename):\n response = requests.get(url)\n with open(filename, 'wb') as f:\n f.write(response.content)\n\n\ndef insert_df_to_mongo(db, col_name, df):\n \"\"\"\n Inserts data frame into mongo DB.\n If collections are already inserted, drop them and load again.\n\n Args:\n db: Mongo DB\n col_name: collection name\n df: data frame\n\n \"\"\"\n # drop collection if already exists?\n if col_name in db.list_collection_names():\n db[col_name].drop()\n mycol = db[col_name]\n mycol.insert_many(df.to_dict('records'))\n\n\ndef load_infected(db):\n \"\"\"\n Loads infected as: date | age | gender | region | district\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # Infected CSV\n df_infected = pd.read_csv(CSV_FILES[\"infected\"][\"filename\"],\n usecols=lambda c: c in {'datum', 'vek', 'pohlavi', 'kraj_nuts_kod', 'okres_lau_kod'},\n sep=\",\")\n df_infected.rename(columns={'datum': 'date', 'vek': 'age', 'pohlavi': 'gender', 'kraj_nuts_kod': 'region',\n 'okres_lau_kod': 'district'}, inplace=True)\n\n # rename gender names (M/Z) to full name (male/female)\n df_infected = df_infected.replace({\"gender\": gender_dict})\n\n # convert age to int\n df_infected['age'] = pd.to_numeric(df_infected['age'], errors='coerce')\n df_infected = df_infected.dropna(subset=['age'])\n df_infected['age'] = df_infected['age'].astype('int')\n\n insert_df_to_mongo(db, \"infected\", df_infected) # insert into NoSQL db\n\n\ndef load_cured(db):\n \"\"\"\n Loads cured as: data | age | gender | region | district\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # Cured CSV\n df_cured = pd.read_csv(CSV_FILES[\"cured\"][\"filename\"],\n usecols=lambda c: c in {'datum', 'vek', 'pohlavi', 'kraj_nuts_kod', 'okres_lau_kod'},\n sep=\",\")\n df_cured.rename(columns={'datum': 'date', 'vek': 'age', 'pohlavi': 'gender', 'kraj_nuts_kod': 'region',\n 'okres_lau_kod': 'district'}, inplace=True)\n\n # rename gender names (M/Z) to full name (male/female)\n df_cured = df_cured.replace({\"gender\": gender_dict})\n\n # convert age to int\n df_cured['age'] = pd.to_numeric(df_cured['age'], errors='coerce')\n df_cured = df_cured.dropna(subset=['age'])\n df_cured['age'] = df_cured['age'].astype('int')\n\n insert_df_to_mongo(db, \"cured\", df_cured) # insert into NoSQL db\n\n\ndef load_dead(db):\n \"\"\"\n Loads dead as: date | age | gender | region | district\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # Dead CSV\n df_dead = pd.read_csv(CSV_FILES[\"dead\"][\"filename\"],\n usecols=lambda c: c in {'datum','kraj_nuts_kod'}, sep=\",\")\n df_dead.rename(columns={'datum': 'date','kraj_nuts_kod': 'region'}, inplace=True)\n\n insert_df_to_mongo(db, \"dead\", df_dead) # insert into NoSQL db\n\n\ndef load_hospitalized(db):\n \"\"\"\n Loads hospitalized as: month | patients\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # Hospitalized CSV\n df_hospitalized = pd.read_csv(CSV_FILES[\"hospitalized\"][\"filename\"],\n usecols=lambda c: c in {'datum', 'pacient_prvni_zaznam'}, sep=\",\")\n df_hospitalized.rename(columns={'datum': 'date', 'pacient_prvni_zaznam': 'patients'}, inplace=True)\n df_hospitalized['date'] = pd.to_datetime(df_hospitalized['date'])\n df_hospitalized['patients'] = pd.to_numeric(df_hospitalized['patients'], errors='coerce')\n df_hospitalized = df_hospitalized.dropna(subset=['patients'])\n df_hospitalized['patients'] = df_hospitalized['patients'].astype('int')\n df_hospitalized['month'] = df_hospitalized[\"date\"].dt.to_period(\"M\")\n grouped_hospitalized = df_hospitalized.groupby(['month'])['patients'].sum()\n grouped_hospitalized = grouped_hospitalized.reset_index()\n\n # convert Period month to Object (can't store Period to mongo)\n grouped_hospitalized['month'] = grouped_hospitalized['month'].astype(str)\n grouped_hospitalized['month'] = pd.to_datetime(grouped_hospitalized['month']).apply(lambda x: x.strftime('%Y-%m'))\n insert_df_to_mongo(db, \"hospitalized\", grouped_hospitalized) # insert into NoSQL db\n\n\ndef load_tests(db):\n \"\"\"\n Loads tests as: month | tests\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # Tests CSV\n df_tests = pd.read_csv(CSV_FILES[\"tests\"][\"filename\"],\n usecols=lambda c: c in {'datum', 'pocet_PCR_testy', 'pocet_AG_testy'}, sep=\",\")\n df_tests.rename(columns={'datum': 'date', 'pocet_PCR_testy': 'tests_PCR', 'pocet_AG_testy': 'tests_antigen'},\n inplace=True)\n df_tests['date'] = pd.to_datetime(df_tests['date'])\n\n # convert tests PCR to int\n df_tests['tests_PCR'] = pd.to_numeric(df_tests['tests_PCR'], errors='coerce')\n df_tests = df_tests.dropna(subset=['tests_PCR'])\n df_tests['tests_PCR'] = df_tests['tests_PCR'].astype('int')\n\n # convert tests antigen to int\n df_tests['tests_antigen'] = pd.to_numeric(df_tests['tests_antigen'], errors='coerce')\n df_tests = df_tests.dropna(subset=['tests_antigen'])\n df_tests['tests_antigen'] = df_tests['tests_antigen'].astype('int')\n\n df_tests['month'] = df_tests[\"date\"].dt.to_period(\"M\")\n grouped_tests = df_tests.groupby(['month']).agg({'tests_PCR': 'sum', 'tests_antigen': 'sum'})\n grouped_tests = grouped_tests.reset_index()\n grouped_tests['tests'] = grouped_tests['tests_PCR'] + grouped_tests['tests_antigen']\n grouped_tests = grouped_tests.drop([\"tests_PCR\", \"tests_antigen\"], axis=1) # drop PCR and antigen tests\n\n # convert Period month to Object (can't store Period to mongo)\n grouped_tests['month'] = grouped_tests['month'].astype(str)\n grouped_tests['month'] = pd.to_datetime(grouped_tests['month']).apply(lambda x: x.strftime('%Y-%m'))\n\n insert_df_to_mongo(db, \"tests\", grouped_tests) # insert into NoSQL db\n\n\ndef load_vaccinated(db):\n \"\"\"\n Loads vaccinated as:\n vaccinated_regions: region | count\n\n vaccinated_people: date | age_group | gender\n\n Args:\n db: Mongo DB\n\n \"\"\"\n # vaccinated geography\n # (date, region, vaccine code)\n df_vac_geo = pd.read_csv(CSV_FILES[\"vaccinated_geography\"][\"filename\"],\n usecols=lambda c: c in {'datum',\n 'vakcina_kod',\n 'poradi_davky',\n 'kraj_nuts_kod',\n 'orp_bydliste',\n 'orp_bydliste_kod',\n 'pocet_davek',\n }, sep=\",\")\n df_vac_geo.rename(columns={'datum' : 'date',\n 'vakcina_kod' : 'vaccine_code',\n 'poradi_davky' : 'shot_order',\n 'kraj_nuts_kod' : 'cznuts',\n 'orp_bydliste' : 'district_name',\n 'orp_bydliste_kod': 'orp',\n 'pocet_davek' : 'shot_count'\n }, inplace=True)\n\n insert_df_to_mongo(db, \"vaccinated_geography\", df_vac_geo) # insert into NoSQL db\n\n\ndef load_demographic_data(db):\n \"\"\"\n Loads demographic data:\n Args:\n db: Mongo DB\n\n \"\"\"\n\n df_dem_data = pd.read_csv(CSV_FILES[\"demographic_data\"][\"filename\"],\n usecols=lambda c: c in {'idhod',\n 'hodnota',\n 'stapro_kod',\n 'pohlavi_cis',\n 'pohlavi_kod',\n 'vek_cis',\n 'vek_kod',\n 'vuzemi_cis',\n 'vuzemi_kod',\n 'casref_do',\n 'pohlavi_txt',\n 'vek_txt',\n 'vuzemi_txt'},\n names=['idhod',\n 'hodnota',\n 'stapro_kod',\n 'pohlavi_cis',\n 'pohlavi_kod',\n 'vek_cis',\n 'vek_kod',\n 'vuzemi_cis',\n 'vuzemi_kod',\n 'casref_do',\n 'pohlavi_txt',\n 'vek_txt',\n 'vuzemi_txt'],\n sep=\",\", header=0)\n\n df_dem_data = df_dem_data.replace('\"', '', regex=True)\n df_dem_data.rename(columns={'idhod': 'idhod',\n 'hodnota': 'value',\n 'stapro_kod': 'stapro_code',\n 'pohlavi_cis': 'gender_enum',\n 'pohlavi_kod': 'gender_code',\n 'vek_cis': 'age_enum',\n 'vek_kod': 'age_code',\n 'vuzemi_cis': 'territory_enum',\n 'vuzemi_kod': 'territory_code',\n 'casref_do': 'valid_date',\n 'pohlavi_txt': 'gender_txt',\n 'vek_txt': 'age_txt',\n 'vuzemi_txt': \"territory_txt\"\n }, inplace=True)\n\n df_dem_data = df_dem_data.drop(columns=['idhod',\n 'stapro_code',\n 'age_enum',\n 'territory_enum'])\n\n\n insert_df_to_mongo(db, \"demographic_data\", df_dem_data) # insert into NoSQL db\n\n\ndef load_vaccinated_by_profession(db):\n \"\"\"\n Loads demographic data:\n Args:\n db: Mongo DB\n\n \"\"\"\n\n df_dem_data = pd.read_csv(CSV_FILES[\"vaccinated_by_profession\"][\"filename\"],\n usecols=lambda c: c in {\n 'kraj_nuts_kod',\n 'vekova_skupina',\n 'pohlavi',\n },\n sep=\",\", header=0)\n\n\n insert_df_to_mongo(db, \"vaccinated_by_profession\", df_dem_data) # insert into NoSQL db\n\ndef load_region_enumerator_data(db):\n\n df_region_enumerator = pd.DataFrame(columns=['value', 'text', 'cznuts', 'region_shortcut'])\n\n tree = ET.parse(XML_FILES[\"region_enumerator\"][\"filename\"])\n root = tree.getroot()\n for POLOZKA in list(root[1]):\n data = {'value': POLOZKA[0].text,\n 'text': POLOZKA[2].text,\n 'cznuts': POLOZKA[6][0].text,\n 'region_shortcut': POLOZKA[6][2].text}\n df_region_enumerator = df_region_enumerator.append(data, ignore_index=True)\n\n insert_df_to_mongo(db, \"region_enumerator\", df_region_enumerator)\n\ndef load_district_enumerator_data(db):\n\n df_district_enumerator = pd.DataFrame(columns=['value', 'text', 'cznuts', 'okres_lau', 'region_shortcut'])\n\n tree = ET.parse(XML_FILES[\"district_enumerator\"][\"filename\"])\n root = tree.getroot()\n for POLOZKA in list(root[1]):\n\n data = {'value': POLOZKA[0].text,\n 'text': POLOZKA[2].text,\n 'cznuts': POLOZKA[6][0].text,\n 'okres_lau': POLOZKA[6][1].text,\n 'region_shortcut': POLOZKA[6][3].text}\n df_district_enumerator = df_district_enumerator.append(data, ignore_index=True)\n\n insert_df_to_mongo(db, \"district_enumerator\", df_district_enumerator)\n\ndef create_indexes(db):\n\n def infected_indexes():\n ...\n def cured_indexes():\n ...\n def dead_indexes():\n ...\n def hospitalized_indexes():\n ...\n def tests_indexes():\n ...\n def vaccinated_indexes():\n ...\n def demographic_data_indexes():\n ...\n def region_enumerator_data_indexes():\n ...\n def district_enumerator_data_indexes():\n ...\n\n def vaccinated_by_profession_indexes():\n\n # print(db.vaccinated_by_profession.index_information())\n\n # db.vaccinated_by_profession.drop_index('index_region_date')\n # db.vaccinated_by_profession.drop_index('index_date')\n\n db.vaccinated_by_profession.create_index([('kraj_nuts_kod', pymongo.ASCENDING),\n ('datum', pymongo.ASCENDING),\n ('pohlavi', pymongo.ASCENDING),\n ('vekova_skupina', pymongo.ASCENDING)\n ],\n name='index_region_date')\n\n db.vaccinated_by_profession.create_index('datum', name='index_date')\n\n # print(db.vaccinated_by_profession.index_information())\n\n infected_indexes()\n cured_indexes()\n dead_indexes()\n hospitalized_indexes()\n tests_indexes()\n vaccinated_indexes()\n demographic_data_indexes()\n region_enumerator_data_indexes()\n district_enumerator_data_indexes()\n vaccinated_by_profession_indexes()\n\n\ndef main():\n \"\"\"\n Run the data loader - downloads d\n Example:\n ./data_loader.py --mongo mongodb://localhost:27017/\n # runs data loader on localhost mongo db\n \"\"\"\n args = parser.parse_args()\n\n global DATA_FOLDER\n DATA_FOLDER = args.folder\n\n # MongoDB connection\n mongo_client = pymongo.MongoClient(args.mongo)\n mongo_db = mongo_client[args.database]\n\n # Download CSV files into ./data/ folder\n # create folder if it doesn't exist\n if not os.path.exists(DATA_FOLDER):\n os.makedirs(DATA_FOLDER)\n\n download_csv(CSV_FILES[\"infected\"][\"url\"], CSV_FILES[\"infected\"][\"filename\"]) # infected\n download_csv(CSV_FILES[\"cured\"][\"url\"], CSV_FILES[\"cured\"][\"filename\"]) # cured\n download_csv(CSV_FILES[\"dead\"][\"url\"], CSV_FILES[\"dead\"][\"filename\"]) # dead\n download_csv(CSV_FILES[\"hospitalized\"][\"url\"], CSV_FILES[\"hospitalized\"][\"filename\"]) # hospitalized\n download_csv(CSV_FILES[\"tests\"][\"url\"], CSV_FILES[\"tests\"][\"filename\"]) # tests\n download_csv(CSV_FILES[\"vaccinated_geography\"][\"url\"],\n CSV_FILES[\"vaccinated_geography\"][\"filename\"]) # vaccinated geography\n download_csv(CSV_FILES[\"demographic_data\"][\"url\"],\n CSV_FILES[\"demographic_data\"][\"filename\"]) # vaccinated geography\n download_csv(CSV_FILES[\"vaccinated_by_profession\"][\"url\"],\n CSV_FILES[\"vaccinated_by_profession\"][\"filename\"]) # vaccinated\n\n download_xml(XML_FILES[\"region_enumerator\"][\"url\"],\n XML_FILES[\"region_enumerator\"][\"filename\"])\n download_xml(XML_FILES[\"district_enumerator\"][\"url\"],\n XML_FILES[\"district_enumerator\"][\"filename\"])\n\n print(\"All documents downloaded. Loading into database now...\")\n\n # Manually deal with each collection\n load_infected(mongo_db)\n print(\"- infected loaded\")\n load_cured(mongo_db)\n print(\"- cured loaded\")\n load_dead(mongo_db)\n print(\"- dead loaded\")\n load_hospitalized(mongo_db)\n print(\"- hospitalized loaded\")\n load_tests(mongo_db)\n print(\"- tests loaded\")\n load_vaccinated(mongo_db)\n print(\"- vaccinated loaded\")\n load_demographic_data(mongo_db)\n print(\"- demographic data loaded\")\n load_region_enumerator_data(mongo_db)\n print(\"- region enumerator data loaded\")\n load_district_enumerator_data(mongo_db)\n print(\"- district enumerator data loaded\")\n load_vaccinated_by_profession(mongo_db)\n print(\"- load_vaccinated by profession loaded\")\n\n # Create indexes for each collection\n create_indexes(mongo_db)\n\n print(\"All done.\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"MITAI/1MIT/UPA/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":19612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"106410265","text":"import tensorflow as tf\nfrom tensorflow import keras\n\nmnist = keras.datasets.fashion_mnist\n(training_images, training_labels), (test_images, test_labels) = mnist.load_data()\n\n\n# NN work better on low data value so we get scale them. Since the max value is 255 we will divide by 255\ntraining_images = training_images / 255.0\ntest_images = test_images / 255.0\n\n# lets to create the NN 3 layers: Input layer 28x28, hidden layer with 128 nodes, output layer with 10 as the number\n# of the classes\n\n# Flatten just takes that square and turns it into a 1 dimensional set\nmodel = keras.Sequential([keras.layers.Flatten(),\n keras.layers.Dense(units=128, activation=tf.nn.relu),\n keras.layers.Dense(units=10, activation=tf.nn.softmax)])\nmodel.compile(optimizer=tf.train.AdamOptimizer(),\n loss=keras.losses.sparse_categorical_crossentropy,\n metrics=['accuracy'])\n\nmodel.fit(training_images, training_labels, epochs=5)\n\n# Let's get evaluate how the model works with unseen data\nprint(\"Evaluating the model...\")\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\nprint(\"Loss:\", test_loss, \"Accuracy:\", test_acc)\n\nclassification = model.predict(test_images)\nprint(classification[0])\nprint(test_labels[0])\n","sub_path":"TensorFlow in Practice Specialization/01 - Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning/02-01 - A Computer Vision Example.py","file_name":"02-01 - A Computer Vision Example.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"245062241","text":"def rev_str(my_str):\n length = len(my_str)\n for i in range(length - 1,-1,-1):\n yield my_str[i]\n\nfor char in rev_str(\"hello\"):\n print(char)\n\n# range(start, stop[, step]) -> range object Return an object that produces a sequence of integers\n# from start (inclusive) to stop(exclusive) by step.\n\n#range(i, j) produces i, i + 1, i + 2, ..., j - 1.\n\n# start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid\n# indices for a list of 4 elements. When step is given, it specifies the increment or decrement.","sub_path":"10_*ators/02_generators-str-reverse.py","file_name":"02_generators-str-reverse.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"628375926","text":"from tests.testmodels import Foo\nfrom postmodel.exceptions import OperationalError\nfrom postmodel.transaction import atomic, in_transaction\nfrom postmodel import Postmodel\nimport pytest\n\n@atomic()\nasync def atomic_decorated_func():\n foo = Foo(foo_id=15, name=\"Test\", tag=\"test\", memo=\"atomic\")\n await foo.save()\n await Foo.bulk_create([\n Foo(foo_id=14, name=\"1\", tag=\"b\", memo=\"bulk create rocks\"),\n Foo(foo_id=13, name=\"2\", tag=\"e\", memo=\"bulk create rocks\"),\n Foo(foo_id=12, name=\"1\", tag=\"a\", memo=\"bulk create rocks\"),\n ])\n\n@pytest.mark.asyncio\nasync def test_transaction_1(db_url):\n await Postmodel.init(db_url, modules=[\"tests.testmodels\"])\n assert len(Postmodel._databases) == 1\n assert Postmodel._inited == True\n await Postmodel.generate_schemas()\n await Foo.all().delete()\n\n foo = await Foo.first()\n assert foo == None\n\n try:\n async with in_transaction():\n foo = Foo(foo_id=110, name=\"transaction\", tag=\"b\", memo=\"...\")\n await foo.save()\n raise Exception(\"exception in transaction\")\n except:\n pass\n\n foo = await Foo.filter(foo_id = 110)\n assert len(foo) == 0\n\n async with in_transaction():\n foo = Foo(foo_id=110, name=\"transaction\", tag=\"b\", memo=\"...\")\n await foo.save()\n\n foo = await Foo.filter(foo_id = 110)\n assert len(foo) == 1\n\n async with in_transaction():\n await Foo.bulk_create([\n Foo(foo_id=114, name=\"1\", tag=\"b\", memo=\"bulk create rocks\"),\n Foo(foo_id=115, name=\"2\", tag=\"e\", memo=\"bulk create rocks\"),\n Foo(foo_id=116, name=\"1\", tag=\"a\", memo=\"bulk create rocks\"),\n ])\n\n foo = await Foo.filter(foo_id__gt = 110)\n assert len(foo) == 3\n\n await atomic_decorated_func()\n foo = await Foo.filter(foo_id__lt = 20)\n assert len(foo) == 4\n\n await Postmodel.close()\n","sub_path":"tests/test_transaction.py","file_name":"test_transaction.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"336330704","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (). All Rights Reserved\n# $Id$\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\n\"\"\"stock_move inherit, manage stock moves for check traceability and mixes\"\"\"\n\nfrom osv import osv, fields\nfrom mx.DateTime import now\nfrom datetime import datetime\nimport netsvc\nfrom tools.translate import _\n\ndef reverse_list( item_x, item_y ):\n \"\"\"ordered a list of ids descently\"\"\"\n if item_x > item_y:\n rst = -1\n elif item_x < item_y:\n rst = 1\n else :\n rst = 0\n return rst\n\nclass stock_move(osv.osv):\n \"\"\"stock_move inherit, manage stock moves for check traceability and mixes\"\"\"\n _inherit = 'stock.move'\n\n def write_relationship(self, cr, move_parent_id, move_child_id):\n \"\"\"method to write to stock_move_history_ids\"\"\"\n if move_parent_id and move_child_id:\n if not isinstance(move_parent_id, list):\n move_parent_id = [move_parent_id]\n for parent_id in move_parent_id:\n if parent_id != move_child_id:\n cr.execute(\"select parent_id from stock_move_history_ids where parent_id = %s and child_id = %s\", (parent_id, move_child_id))\n if not cr.rowcount:\n cr.execute('insert into stock_move_history_ids (parent_id, child_id) values (%s,%s)', (parent_id, move_child_id))\n\n return True\n\n def get_move_type(self, cr, uid, ids, context=None):\n \"\"\"return the type of moves\"\"\"\n if context is None: context = {}\n res = {}\n\n for move in self.browse(cr, uid, ids):\n if move.picking_id and move.picking_id.type != 'internal':\n if move.picking_id.type == 'in':\n res[move.id] = _('IN')\n elif move.picking_id.type == 'out':\n res[move.id] = _('OUT')\n elif move.picking_id.type == 'return':\n res[move.id] = _('RETURN')\n else:\n if move.location_dest_id.usage == 'customer':\n res[move.id] = _('OUT')\n elif move.virtual and move.location_dest_id.usage == 'intermediate':\n res[move.id] = _('TO MIX')\n elif move.prodlot_id and move.location_id.usage == 'intermediate' and move.prodlot_id.is_mix:\n res[move.id] = _('MIX')\n elif move.location_dest_id.usage == 'elimination':\n res[move.id] = _('WASTE')\n elif move.location_dest_id.usage == 'inventory':\n res[move.id] = _('INVENTORY')\n elif move.location_id.usage == 'inventory':\n res[move.id] = _('FROM INVENTORY')\n elif move.location_dest_id.usage == 'production':\n res[move.id] = _('PRODUCTION')\n elif move.production_id:\n res[move.id] = _('PRODUCTION FINAL MOVE')\n elif move.location_dest_id.usage == 'procurement':\n res[move.id] = _('PROCUREMENT')\n elif move.procurement_id:\n res[move.id] = _('PROCUREMENT')\n else:\n res[move.id] = _('INTERNAL')\n return res\n\n\n def _get_supplier(self, cr, uid, ids, field_name, arg, context):\n \"\"\"gets the name of the supplier\"\"\"\n res = {}\n for move in self.browse(cr, uid, ids):\n res[move.id] = None\n if move.location_id.name == 'Suppliers':\n if move.picking_id:\n res[move.id] = move.picking_id.address_id.partner_id.name\n return res\n \n def _get_expiry_date(self, cr, uid, ids, field_name, arg, context):\n \"\"\"gets the expiry date of the product\"\"\"\n res = {}\n for move in self.browse(cr, uid, ids):\n if move.prodlot_id:\n res[move.id] = move.prodlot_id.dlc\n else:\n res[move.id] = False\n return res\n\n def _get_moves_to_update_from_prodlot(self, cr, uid, ids, context={}):\n \"\"\"return moves to update it raises from production lots when update\"\"\"\n result = []\n for prodlot_obj_id in self.browse(cr, uid, ids):\n move_ids = self.pool.get('stock.move').search(cr, uid, [('prodlot_id', '=', prodlot_obj_id.id)])\n result.extend(move_ids)\n return result\n\n _columns = {\n 'supplier': fields.function(_get_supplier, method=True, string=\"Supplier\", type='char', size=64, store = True),\n 'expiry_date': fields.function(_get_expiry_date, method=True, string=\"Expiry Date\", type='datetime',\n store = {'stock_production_lot': (_get_moves_to_update_from_prodlot, ['dlc'], 10),\n 'stock.move': (lambda self, cr, uid, ids, c={}: ids, None, 20)}),\n 'virtual' : fields.boolean('Virtual Move', help=\"A virtual move, is an internal move necessary for follow-up the traceability\"),\n 'procurement_id': fields.many2one('mrp.procurement', 'Procurement', select=True),\n #now this field doesn't use\n 'procurements': fields.one2many('mrp.procurement', 'dummy', 'Procurements'),\n 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', help=\"Production lot is used to put a serial number on the production\", required=False,\n states={'assigned':[('required', True)], 'done':[('required', True)]}),\n }\n\n def _check_location(self, cr, uid, ids):\n \"\"\"checks if the location only acepts mixes and if the product is miscible\"\"\"\n for move in self.browse(cr, uid, ids):\n if move.location_dest_id.liquid_location and (not move.product_id.liquid) and move.state in ('confirm', 'assigned', 'done'):\n return False\n elif (not move.location_dest_id.liquid_location) and move.product_id.liquid and 'internal' in move.location_dest_id.usage and move.location_dest_id.chained_location_type == 'none' and move.state in ('confirm', 'assigned', 'done'):\n return False\n return True\n\n def _check_prodlot(self, cr, uid, ids):\n \"\"\"checks if prodlot is ok for done move\"\"\"\n for move in self.browse(cr, uid, ids):\n if move.state == 'done' and not move.prodlot_id and move.location_id.usage != 'inventory' and move.location_dest_id.usage != 'inventory' and move.product_id.type == 'product':\n return False\n\n return True\n\n _constraints = [\n (_check_location, 'Location not valid for this product', ['location_dest_id']),\n (_check_prodlot, 'Production Lot is required to done move', ['prodlot_id'])\n ]\n \n def create_move_mix(self, cr, uid, vals, data):\n \"\"\"creates the move for the mix\"\"\"\n #creates new production lot number\n production_lot_number = self.pool.get('stock.production.lot').make_sscc(cr, uid, context={'product_id': data['obj_virtual_move_inlocation'].product_id.id})\n #creates an object with this production lot number\n mix_vals = {\n 'name' : production_lot_number,\n 'product_id' : data['obj_virtual_move_tomix'].product_id.id,\n 'is_mix' : 1,\n }\n\n #if prodlots uom is same\n if data['obj_virtual_move_tomix'].prodlot_id.product_uom.id == data['obj_virtual_move_inlocation'].prodlot_id.product_uom.id:\n mix_vals['product_uom'] = data['obj_virtual_move_tomix'].prodlot_id.product_uom.id\n # pylint: disable-msg=W0212\n #if move to mix uom not same that prodlots uom\n if data['obj_virtual_move_tomix'].product_uom.id != mix_vals['product_uom']:\n data['obj_virtual_move_tomix'].product_qty = self.pool.get('product.uom')._compute_qty(cr, uid, data['obj_virtual_move_tomix'].product_uom.id, data['obj_virtual_move_tomix'].product_qty, mix_vals['product_uom'])\n # pylint: disable-msg=W0212\n #if move in location not same that prodlots uom\n if data['obj_virtual_move_inlocation'].product_uom.id != mix_vals['product_uom']:\n data['obj_virtual_move_inlocation'].product_qty = self.pool.get('product.uom')._compute_qty(cr, uid, data['obj_virtual_move_inlocation'].product_uom.id, data['obj_virtual_move_inlocation'].product_qty, mix_vals['product_uom'])\n\n qty = data['obj_virtual_move_tomix'].product_qty + data['obj_virtual_move_inlocation'].product_qty\n mix_vals['unit_price'] = float(((float(data['obj_virtual_move_tomix'].prodlot_id.unit_price) * float(data['obj_virtual_move_tomix'].product_qty)) + (float(data['obj_virtual_move_inlocation'].prodlot_id.unit_price) * float(data['obj_virtual_move_inlocation'].product_qty))) / float(qty))\n else:\n #default uom from product\n mix_vals['product_uom'] = data['obj_virtual_move_inlocation'].product_id.product_tmpl_id.uom_id.id\n \n \n #TO MIX\n # pylint: disable-msg=W0212\n if data['obj_virtual_move_tomix'].product_uom.id == mix_vals['product_uom']:\n tomix_qty = float(data['obj_virtual_move_tomix'].product_qty)\n else:\n tomix_qty = self.pool.get('product.uom')._compute_qty(cr, uid, data['obj_virtual_move_tomix'].product_uom.id, data['obj_virtual_move_tomix'].product_qty, mix_vals['product_uom'])\n\n # pylint: disable-msg=W0212\n if data['obj_virtual_move_tomix'].prodlot_id.product_uom.id == mix_vals['product_uom']:\n tomix_price = data['obj_virtual_move_tomix'].prodlot_id.unit_price\n else:\n if data['obj_virtual_move_tomix'].prodlot_id.product_uom.factor_inv_data:\n tomix_price = data['obj_virtual_move_tomix'].prodlot_id.unit_price / data['obj_virtual_move_tomix'].prodlot_id.product_uom.factor_inv_data\n else:\n tomix_price = data['obj_virtual_move_tomix'].prodlot_id.unit_price * data['obj_virtual_move_tomix'].prodlot_id.product_uom.factor\n\n\n #IN LOCATION\n # pylint: disable-msg=W0212\n if data['obj_virtual_move_inlocation'].product_uom.id == mix_vals['product_uom']:\n inlocation_qty = float(data['obj_virtual_move_inlocation'].product_qty)\n else:\n inlocation_qty = self.pool.get('product.uom')._compute_qty(cr, uid, data['obj_virtual_move_inlocation'].product_uom.id, data['obj_virtual_move_inlocation'].product_qty, mix_vals['product_uom'])\n\n # pylint: disable-msg=W0212\n if data['obj_virtual_move_inlocation'].prodlot_id.product_uom.id == mix_vals['product_uom']:\n inlocation_price = data['obj_virtual_move_inlocation'].prodlot_id.unit_price\n else:\n if data['obj_virtual_move_inlocation'].prodlot_id.product_uom.factor_inv_data:\n tomix_price = data['obj_virtual_move_inlocation'].prodlot_id.unit_price / data['obj_virtual_move_inlocation'].prodlot_id.product_uom.factor_inv_data\n else:\n tomix_price = data['obj_virtual_move_inlocation'].prodlot_id.unit_price * data['obj_virtual_move_inlocation'].prodlot_id.product_uom.factor\n\n qty = tomix_qty + inlocation_qty\n\n mix_vals['unit_price'] = float(((float(tomix_price) * float(tomix_qty)) + (float(inlocation_price) * float(inlocation_qty))) / float(qty))\n\n #create mix lot\n production_lot_number_id = self.pool.get('stock.production.lot').create(cr, uid, mix_vals)\n\n values = {\n 'product_uom' : mix_vals['product_uom'],\n 'date' : data['obj_virtual_move_tomix'].date_planned,\n 'product_qty' : qty,\n 'location_id' : data['obj_virtual_move_tomix'].product_id.product_tmpl_id.property_mix.id,\n 'product_id' : data['obj_virtual_move_inlocation'].product_id.id,\n 'name' : 'M:' + production_lot_number,\n 'date_planned' : data['obj_virtual_move_tomix'].date_planned,\n 'state' : 'done',\n 'location_dest_id' : data['destination'],\n 'prodlot_id' : production_lot_number_id,\n }\n #creates the mix move\n new_id = super(stock_move, self).create(cr, uid, values)\n return new_id\n \n def create_virtual_moves(self, cr, user, obj_move_id, obj_stock_real_prodlots_id, orig_vals):\n \"\"\"creates the virtual move for the product to mix because need this move that stock decrease\"\"\"\n #creates the virtual move from in location move\n date_planned = orig_vals.get('date_planned', False) or obj_move_id.date_planned\n values = {\n 'product_uom' : obj_stock_real_prodlots_id.prodlot_id.product_uom.id,\n 'product_uos_qty' : obj_stock_real_prodlots_id.name * float(obj_stock_real_prodlots_id.prodlot_id.product_uom.factor),\n 'date' : date_planned,\n 'product_qty' : obj_stock_real_prodlots_id.name * float(obj_stock_real_prodlots_id.prodlot_id.product_uom.factor),\n 'product_uos' : obj_stock_real_prodlots_id.product_id.uos_id and obj_stock_real_prodlots_id.product_id.uos.id or False,\n 'location_id' : obj_stock_real_prodlots_id.location_id.id,\n 'product_id' : obj_stock_real_prodlots_id.product_id.id,\n 'name' : 'M:' + str(obj_stock_real_prodlots_id.location_id.id) + 'TOMVS' + date_planned,\n 'date_planned' : date_planned,\n 'state' : 'done',\n 'location_dest_id' : obj_stock_real_prodlots_id.product_id.product_tmpl_id.property_mix.id,\n 'prodlot_id' : obj_stock_real_prodlots_id.prodlot_id.id,\n 'virtual' : 1,\n }\n virtual_move_from_inlocation_id = super(stock_move, self).create(cr, user, values)\n\n #saves the real destination\n destination = orig_vals.get('location_dest_id', False) or obj_move_id.location_dest_id.id\n #changes the destination to property moves for specific product because it's id of virtual location where do mixes\n #vals['location_dest_id'] = move_inlocation.product_id.product_tmpl_id.property_moves.id\n #creates the virtual move from the move to mix\n\n #movimiento que entra\n\n vals = {\n 'product_uom' : orig_vals.get('location_dest_id', False) or obj_move_id.product_uom.id,\n 'product_uos_qty' : orig_vals.get('product_uos_qty', False) or obj_move_id.product_uos_qty,\n 'date' : date_planned,\n 'product_qty' : orig_vals.get('product_qty', False) or obj_move_id.product_qty,\n 'product_uos' : orig_vals.get('product_uos', False) or (obj_move_id.product_uos and obj_move_id.product_uos.id or False),\n 'location_id' : orig_vals.get('location_dest_id', False) or obj_move_id.location_dest_id.id,\n 'product_id' : orig_vals.get('product_id', False) or obj_move_id.product_id.id,\n 'name' : 'M:' + str(obj_move_id.id) + 'TOMVS' + date_planned,\n 'date_planned' : date_planned,\n 'state' : 'done',\n 'location_dest_id' : orig_vals.get('property_mix', False) or obj_move_id.product_id.product_tmpl_id.property_mix.id,\n 'prodlot_id' : orig_vals.get('prodlot_id', False) or obj_move_id.prodlot_id.id,\n 'virtual' : 1,\n }\n virtual_move_from_movetomix_id = super(stock_move, self).create(cr, user, vals)\n #dictionary with the params to return needed for create the mix (the object of the virtual moves and the real destination)\n data = {\n 'obj_virtual_move_inlocation' : self.browse(cr, user, virtual_move_from_inlocation_id),\n 'obj_virtual_move_tomix' : self.browse(cr, user, virtual_move_from_movetomix_id),\n 'destination' : destination,\n }\n \n return data\n\n def get_move_in_location(self, cr, uid, location_id, prodlot_id, qty = 0):\n \"\"\"returns the move in location\"\"\"\n moves = []\n ids = self.search(cr, uid, [('location_dest_id', '=', location_id), ('prodlot_id', '=', prodlot_id), ('location_id', '!=', location_id)])\n if len(ids) == 1:\n moves = ids\n elif len(ids) == 0 or not prodlot_id:\n return False\n else:\n ids_to_remove = []\n for move in self.browse(cr, uid, ids):\n m_qty = move.product_qty\n for child_move in move.move_history_ids:\n m_qty -= child_move.product_qty\n if m_qty <= 0:\n ids_to_remove.append(move.id)\n if ids_to_remove:\n ids = list(set(ids) - set(ids_to_remove))\n\n if qty:\n #if there are many items with that params, go on with one param more\n move_id = self.search(cr, uid, [('location_dest_id', '=', location_id), ('prodlot_id', '=', prodlot_id), ('location_id', '!=', location_id), ('product_qty', '>=', qty)])\n if len(move_id) == 1:\n moves = move_id\n elif len(move_id) > 1:\n moves = [move_id[len(move_id)-1]]\n else:\n #check if stock in location are in more that one move\n select_moves = []\n move_qty = qty\n ids.sort(reverse_list)\n for obj_move_id in self.browse(cr, uid, ids):\n move_qty = move_qty - obj_move_id.product_qty\n select_moves.append(obj_move_id.id)\n if move_qty <= 0:\n break\n moves = select_moves\n\n if moves:\n ids_to_remove = []\n for move in self.browse(cr, uid, moves):\n if move.location_dest_id.usage == 'inventory':\n ids_to_remove.append(move.id)\n ids = list(set(moves) - set(ids_to_remove))\n return ids\n else:\n return moves\n \n\n def create(self, cr, uid, vals, context = {}):\n \"\"\"overwrites this method for check location in purchase orders\"\"\"\n if vals.get('purchase_line_id') and vals.get('location_dest_id'):\n obj_purchase_line_id = self.pool.get('purchase.order.line').browse(cr, uid, vals['purchase_line_id'])\n if obj_purchase_line_id.location_id.id != vals['location_dest_id']:\n #El location_id de la compra no es igual al de vals\n vals['location_dest_id'] = obj_purchase_line_id.location_id.id\n return super(stock_move, self).create(cr, uid, vals)\n\n def write(self, cr, uid, ids, vals, context={}):\n \"\"\"overwrites this method for create mixes if was necessary\"\"\"\n res = []\n if type(ids) != type([]):\n ids = [ids]\n if 'state' in vals:\n if vals['state'] == 'done':\n result = 0\n for move_id in ids:\n obj_move_id = self.browse(cr, uid, move_id)\n #checks if can be a valid move to mix, if the location contents a miscible product of the same type\n is_mix = False\n if obj_move_id.location_dest_id.liquid_location and obj_move_id.product_id.liquid and (obj_move_id.prodlot_id or vals.get('prodlot_id', False)) and obj_move_id.product_id.type == 'product':\n #Es una ubicación de líquidos, el producto es líquido y el movimiento tiene lote\n res = []\n res = self.pool.get('stock.real.report.prodlots').search(cr, uid, [('location_id', '=', obj_move_id.location_dest_id.id), ('product_id', '=', obj_move_id.product_id.id)])\n if len(res) > 0:\n is_mix = True\n res2 = self.pool.get('stock.real.report.prodlots').search(cr, uid, [('location_id', '=', obj_move_id.location_dest_id.id), ('prodlot_id', '=', vals.get('prodlot_id', False) or obj_move_id.prodlot_id.id)])\n if res2:\n obj_real_report_prodlot_id = self.pool.get('stock.real.report.prodlots').browse(cr, uid, res2[0])\n if obj_move_id.production_id:\n for production_move in obj_move_id.production_id.move_lines:\n if production_move.product_uom and production_move.prodlot_id and production_move.location_dest_id:\n #obtains the base uom of move uom\n base_uom_id = self.pool.get('product.uom').search(cr, uid, [('category_id', '=', production_move.product_uom.category_id.id), ('factor', '=', 1.0)])\n #converts the quantity to base uom\n production_move.product_qty = self.pool.get('product.uom')._compute_qty(cr, uid, production_move.product_uom.id, production_move.product_qty, base_uom_id[0])\n #if all stock in dest location is consumed in production the location is valid because after confirm production the location was empty\n if production_move.prodlot_id.id == obj_real_report_prodlot_id.prodlot_id.id and production_move.product_qty == obj_real_report_prodlot_id.name and production_move.location_id.id == obj_move_id.location_dest_id.id:\n is_mix = False\n break\n else:\n is_mix = False\n #Es una mezcla\n #there are some prodlot in this location\n if is_mix:\n for record in res:\n obj_record_prodlot_id = self.pool.get('stock.real.report.prodlots').browse(cr, uid, record)\n #get the move in location\n move_parent_id = self.get_move_in_location(cr, uid, obj_record_prodlot_id.location_id.id, obj_record_prodlot_id.prodlot_id.id, obj_move_id.product_qty)\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n if move_parent_id:\n params = self.create_virtual_moves(cr, uid, obj_move_id, obj_record_prodlot_id, vals)\n mix_id = self.create_move_mix(cr, uid, vals, params)\n\n #creates in move_history_ids the parental relationships if not exists\n self.write_relationship(cr, params['obj_virtual_move_inlocation'].id, mix_id)\n\n self.write_relationship(cr, params['obj_virtual_move_tomix'].id, mix_id)\n\n self.write_relationship(cr, move_parent_id, params['obj_virtual_move_inlocation'].id)\n\n self.write_relationship(cr, obj_move_id.id, params['obj_virtual_move_tomix'].id)\n\n move_original_parent_id = self.get_move_in_location(cr, uid, obj_move_id.location_id.id, obj_move_id.prodlot_id.id, obj_move_id.product_qty)\n self.write_relationship(cr, move_original_parent_id, obj_move_id.id)\n\n if len(res) <= 0 or is_mix == False:\n #isn't mix\n res = self.pool.get('stock.real.report.prodlots').search(cr, uid, [('location_id', '=', obj_move_id.location_dest_id.id)])\n if len(res) == 1:\n valid = False\n obj_real_report_prodlot_id = self.pool.get('stock.real.report.prodlots').browse(cr, uid, res[0])\n if obj_move_id.production_id:\n for production_move in obj_move_id.production_id.move_lines:\n if production_move.product_uom and production_move.prodlot_id and production_move.location_dest_id:\n #obtains the base uom of move uom\n base_uom_id = self.pool.get('product.uom').search(cr, uid, [('category_id', '=', production_move.product_uom.category_id.id), ('factor', '=', 1.0)])\n #converts the quantity to base uom\n production_move.product_qty = self.pool.get('product.uom')._compute_qty(cr, uid, production_move.product_uom.id, production_move.product_qty, base_uom_id[0])\n #if all stock in dest location is consumed in production the location is valid because after confirm production the location was empty\n if production_move.prodlot_id.id == obj_real_report_prodlot_id.prodlot_id.id and production_move.product_qty == obj_real_report_prodlot_id.name and production_move.location_id.id == obj_move_id.location_dest_id.id:\n valid = True\n break\n if obj_real_report_prodlot_id.prodlot_id.id == vals.get('prodlot_id', False) or obj_move_id.prodlot_id.id:\n valid=True\n if not valid:\n raise osv.except_osv(_('Error'),\n _(\"Can not mix products that are not of the same type in this mixtures destination. Only can mix \") + self.pool.get('stock.real.report.prodlots').browse(cr, uid, res[0]).product_id.product_tmpl_id.name + \".\")\n elif (len(res) > 1):\n raise osv.except_osv(_('Error'), _(\"Invalid mixtures location. The location has more that one lot.\"))\n\n\n move_parent_id = self.get_move_in_location(cr, uid, obj_move_id.location_id.id, obj_move_id.prodlot_id.id, obj_move_id.product_qty)\n self.write_relationship(cr, move_parent_id, obj_move_id.id)\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n elif not obj_move_id.location_dest_id.liquid_location and not obj_move_id.product_id.liquid and (obj_move_id.prodlot_id or vals.get('prodlot_id', False)):\n res = []\n #No es una ubicación de líquidos y el producto no es líquido y tiene lote\n #gets a check if exists a move with all this params\n if vals.get('prodlot_id', False):\n res = self.pool.get('stock.real.report.prodlots').search(cr, uid, [('location_id', '=', obj_move_id.location_id.id), ('prodlot_id', '=', vals['prodlot_id'])])\n elif obj_move_id.prodlot_id:\n res = self.pool.get('stock.real.report.prodlots').search(cr, uid, [('location_id', '=', obj_move_id.location_id.id), ('prodlot_id', '=', obj_move_id.prodlot_id.id)])\n if len(res) == 1:\n obj_record_prodlot_id = self.pool.get('stock.real.report.prodlots').browse(cr, uid, res[0])\n #gets the move with the params\n move_parent_ids = self.get_move_in_location(cr, uid, obj_record_prodlot_id.location_id.id, obj_record_prodlot_id.prodlot_id.id, obj_move_id.product_qty)\n if move_parent_ids:\n if not isinstance(move_parent_ids, list):\n move_parent_ids = [move_parent_ids]\n for move_parent_id in move_parent_ids:\n #creates the move\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n #insert the parental move history\n if obj_move_id.name.startswith('PROD'):\n #Empieza por prod\n cr.execute('select parent_id from stock_move_history_ids where child_id = %s', (obj_move_id.id,))\n if cr.rowcount:\n parent2 = cr.fetchall()\n cr.execute('select parent_id from stock_move_history_ids where parent_id = %s and child_id = %s', (move_parent_id, parent2[0][0]))\n if not cr.rowcount:\n self.write_relationship(cr, move_parent_id, obj_move_id.id)\n else:\n self.write_relationship(cr, move_parent_id, obj_move_id.id)\n else:\n self.write_relationship(cr, move_parent_id, obj_move_id.id)\n elif len(res) > 1:\n raise osv.except_osv(_('Error'), _(\"Parental relationship error. The location has more that one lot for this product.\"))\n else:\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n elif obj_move_id.prodlot_id or vals.get('prodlot_id', False):\n #En cualquier otro caso con lote\n move_parent_id = self.get_move_in_location(cr, uid, obj_move_id.location_id.id, obj_move_id.prodlot_id.id, obj_move_id.product_qty)\n self.write_relationship(cr, move_parent_id, obj_move_id.id)\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n else:\n #En cualquier otro caso\n result = super(stock_move, self).write(cr, uid, move_id, vals, context=context)\n if result:\n return result\n return super(stock_move, self).write(cr, uid, ids, vals, context=context)\n\n def action_done(self, cr, uid, ids, context=None):\n \"\"\"overwrites this method for that the procurement move pass his prodlot to move child\"\"\"\n for move in self.browse(cr, uid, ids):\n if move.move_dest_id and (move.state != 'done') and move.prodlot_id and not move.move_dest_id.production_id:\n self.write(cr, uid, move.move_dest_id.id, {'prodlot_id': move.prodlot_id.id})\n return super(stock_move, self).action_done(cr, uid, ids, context)\n\n def check_assign(self, cr, uid, ids, context={}):\n \"\"\"overwrites this method beacause if stock in product lot not fix teh procurement in one move there is create more moves\"\"\"\n done = []\n count = 0\n pickings = {}\n for move in self.browse(cr, uid, ids):\n if move.product_id.type == 'consu':\n if move.state in ('confirmed', 'waiting'):\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n continue\n if move.state in ('confirmed', 'waiting'):\n # pylint: disable-msg=W0212\n # warning disabled in pylint because I need access to protected method\n res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id})\n if res:\n self.write(cr, uid, move.id, {'state':'assigned'})\n done.append(move.id)\n pickings[move.picking_id.id] = 1\n res_pop = res.pop(0)\n cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (res_pop[1], res_pop[0], move.id))\n\n while res:\n res_pop = res.pop(0)\n vals = {\n 'product_uos_qty': move.product_uos_qty,\n 'product_uom': move.product_uom.id or None,\n 'price_unit': move.price_unit,\n 'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n 'product_qty': res_pop[0],\n 'product_uos': move.product_uos.id or None,\n 'location_id': res_pop[1],\n 'product_id': move.product_id.id,\n 'name': move.name,\n 'date_planned': move.date_planned,\n 'picking_id': move.picking_id.id or None,\n 'state': move.state,\n 'location_dest_id': move.location_dest_id.id,\n 'sale_line_id': move.sale_line_id.id,\n 'procurement_id': move.procurement_id.id,\n 'move_dest_id': move.move_dest_id.id or None\n }\n move_id = self.create(cr, uid, vals)\n done.append(move_id)\n\n if not move.prodlot_id:\n raise osv.except_osv(_('Warning!'),\n _('Production lots required: Please set reservations\\' production lots.'))\n if done:\n count += len(done)\n self.write(cr, uid, done, {'state':'assigned'})\n\n if count:\n for pick_id in pickings:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_write(uid, 'stock.picking', pick_id, cr)\n return count\n\n def onchange_product_id(self, cr, uid, context, prod_id=False, loc_id=False, loc_dest_id=False, prod_qty=0, prodlot_id=False):\n \"\"\"event overwrite. Checks if the move not has a realationship with a procurement move and load data for this product\"\"\"\n #checks if can write in this move\n result = self.onchange_check_can_write(cr, uid, context=context)\n if result:\n return result\n #return a value with the product and the product_uom, if not product return nothing\n parent_result = super(stock_move, self).onchange_product_id(cr, uid, context, prod_id, loc_id, loc_dest_id)\n if not parent_result:\n #No hay product_id\n return parent_result\n #gets the object of the product\n obj_product_id = self.pool.get('product.product').browse(cr, uid, prod_id)\n #if there is id\n if context and context[0]:\n #checks if this product is available in the location\n result = self.onchange_location_id(cr, uid, context = context, product_id = prod_id, location_id = loc_id, product_qty = prod_qty)\n if 'value' in result and not 'warning' in result:\n if not prodlot_id:\n result['value']['name'] = parent_result['value']['name']\n else:\n result['value']['name'] = parent_result['value']['name'] + \" (\" + self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id).name + \")\"\n result['value']['product_uom'] = parent_result['value']['product_uom']\n return result\n elif 'warning' in result:\n return result\n\n result = {\n 'product_uom': obj_product_id.product_tmpl_id.uom_id.id\n }\n\n if prodlot_id:\n result['name'] = obj_product_id.product_tmpl_id.name + \" (\" + self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id).name + \")\"\n else:\n result['name'] = obj_product_id.product_tmpl_id.name\n return {'value': result}\n\n def onchange_lot_id2(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_uom=False, context={}):\n \"\"\"this event manages product_uom and then call real onchange_lot_id\"\"\"\n res = self.onchange_lot_id(cr, uid, ids, prodlot_id=prodlot_id, product_qty=product_qty, loc_id=loc_id, context=context)\n if 'warning' in res and res['warning']:\n #Hay warning en lot-id\n return res\n else:\n if prodlot_id:\n prodlot_obj_id = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id)\n if not 'value' in res:\n res['value'] = {}\n\n if product_uom and product_qty:\n if prodlot_obj_id.product_uom.id != product_uom:\n # pylint: disable-msg=W0212\n res['value']['price'] = prodlot_obj_id.unit_price * self.pool.get('product.uom')._compute_qty(cr, uid, product_uom, product_qty, prodlot_obj_id.product_uom.id)\n else:\n res['value']['price'] = prodlot_obj_id.unit_price * product_qty\n\n return res\n\n def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, context=None):\n \"\"\"overwrites this evento for change the name by product code + prodlot name\"\"\"\n res = super(stock_move, self).onchange_lot_id(cr, uid, ids, prodlot_id = prodlot_id, product_qty = product_qty, loc_id = loc_id, context = context)\n if 'warning' in res and res['warning']:\n #Hay warning en lot-id\n return res\n else:\n if prodlot_id:\n prodlot_obj_id = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id)\n if not 'value' in res:\n res['value'] = {}\n res['value']['name'] = prodlot_obj_id.product_id.product_tmpl_id.name + \" (\" + prodlot_obj_id.name + \")\"\n\n return res\n \n def onchange_check_can_write(self, cr, uid, context = {}, dummy = False):\n \"\"\"checks if the move not has a realationship with a procurement move\"\"\"\n if context and context[0]:\n obj_move = self.pool.get('stock.move').browse(cr, uid, context[0])\n moves_found = self.search(cr, uid, [('move_dest_id', '=', obj_move.id)])\n if (obj_move.picking_id and obj_move.picking_id.state == 'done') or (moves_found and obj_move.state != 'draft'):\n result = {\n 'location_id': obj_move.location_id.id,\n 'location_dest_id': obj_move.location_dest_id.id,\n 'product_id': obj_move.product_id.id,\n 'product_qty': obj_move.product_qty,\n 'product_uom': obj_move.product_uom.id,\n 'name': obj_move.name,\n 'prodlot_id': obj_move.prodlot_id.id,\n }\n #shows an alert explains because not changes the location\n warning = {\n 'title': _('Alert !'),\n 'message': _('Can not change because a procurement with a reserve that was created and assigned for this move.')\n }\n return {'value': result,\n 'warning': warning,}\n return {}\n\n def onchange_location_id(self, cr, uid, context, product_id = False, location_id = False, dummy = False, product_qty=False):\n \"\"\"event fires when changes the location, checks the location and return a default production lot for this location\"\"\"\n #if not location or product not return anything\n if not location_id or not product_id:\n return {}\n #if the product quantity needed not exist or is <= 0, set the product quantity to one because is 0 or less not return a valid default_prodlot\n if not product_qty or product_qty <= 0:\n product_qty = 1\n #searches the default prodlot for this location and this product\n default_prodlot = self.pool.get('stock.production.lot').get_default_production_lot(cr, uid, location_id, product_id, product_qty, deep = False)\n #context[0] = stock_move.id\n if context and context[0]:\n obj_move = self.pool.get('stock.move').browse(cr, uid, context[0])\n #if exists prodlot and an id is because the move exists yet, and not can change the location because a procurement created it\n moves_found = self.search(cr, uid, [('move_dest_id', '=', obj_move.id)])\n if (obj_move.picking_id and obj_move.picking_id.state == 'done') or moves_found:\n result = {\n 'location_id': obj_move.location_id.id,\n 'prodlot_id': obj_move.prodlot_id.id,\n 'product_id': obj_move.product_id.id,\n }\n #shows an alert explains because not changes the location\n warning = {\n 'title': _('Alert !'),\n 'message': _('Can not change because a procurement with a reserve that was created and assigned for this move.')\n }\n return {'value': result,\n 'warning': warning,}\n #if not return anything, raises an alert because no exist a production lot and must be created\n if not default_prodlot:\n result = {\n 'location_id': obj_move.location_id.id,\n 'prodlot_id': obj_move.prodlot_id.id,\n 'product_id': obj_move.product_id.id,\n }\n warning = {\n 'title': _('Alert !'),\n 'message': _('There are not any production lot in this location, must be created.')\n }\n return {'value': result,\n 'warning': warning}\n elif self.pool.get('stock.location').browse(cr, uid, location_id).name == 'Suppliers':\n result = {\n 'prodlot_id': None,\n }\n return {'value': result}\n else:\n result = {\n 'prodlot_id': default_prodlot,\n }\n return {'value': result}\n return {}\n\n def unlink(self, cr, uid, ids, context=None):\n \"\"\"overwrites this method for managed the deletes moves in move_lines\"\"\"\n for move in self.browse(cr, uid, ids, context=context):\n #if the move is a production move with a procurement move\n if move.move_dest_id and move.procurement_id:\n #searches moves that have for move_dest_id this move\n move_found = self.search(cr, uid, [('move_dest_id', '=', move.id)])\n #if have found one move and this move has picking id, this is a procurement move\n if len(move_found) == 1 and self.browse(cr, uid, move_found[0]).picking_id:\n #gets the procurement id from the move\n procurement_id = self.pool.get('mrp.procurement').search(cr, uid, [('move_id', '=', move_found[0])])\n #gets the picking id from the move\n picking_id = self.browse(cr, uid, move_found[0]).picking_id.id\n #searches the moves in this picking where the move_id not was the id of move\n picking_moves = self.search(cr, uid, [('picking_id', '=', picking_id), ('id', '!=', move_found[0])])\n #if only the move took part of this picking, deletes the picking\n if len(picking_moves) == 0:\n self.pool.get('stock.picking').write(cr, uid, picking_id, {'state': 'draft'}, context = context)\n self.pool.get('stock.picking').unlink(cr, uid, [picking_id])\n #if only and normally there is a procurement for a procurement move, deletes teh procurement\n if len(procurement_id) == 1:\n self.pool.get('mrp.procurement').write(cr, uid, procurement_id[0], {'state': 'draft'}, context = context)\n self.pool.get('mrp.procurement').unlink(cr, uid, [procurement_id[0]])\n #addes the procurement move id to move to delete\n ids.append(move_found[0])\n if move.move_history_ids:\n raise osv.except_osv(_('Error'), _('You cannot remove the move %s which has got child moves !') % (move.name,))\n\n #updates the moves to draft because in other state not can delete\n self.write(cr, uid, ids, {'state': 'draft'}, context = context)\n #deletes teh moves\n return super(stock_move, self).unlink(cr, uid, ids)\n\nstock_move()\n \n \n","sub_path":"addons-community/pxgo_full_stock_traceability/stock_move.py","file_name":"stock_move.py","file_ext":"py","file_size_in_byte":45667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"216493241","text":"import numpy as np\n\nDIM = 10000\nGAMMA = 20\nC = 10\n\nnp.random.seed(22)\nW = np.sqrt(2*GAMMA)*np.random.normal(0, 1, (DIM, 400))\nB = np.random.uniform(0, 2*np.pi, DIM)\n\ndef transform(X):\n # Make sure this function works for both 1D and 2D NumPy arrays.\n # Random Fourier Feature\n if X.ndim == 1:\n return np.sqrt(2./DIM)*np.cos(W.dot(X)+B)\n elif X.ndim == 2:\n return np.sqrt(2./DIM)*np.cos(X.dot(W.T)+B)\n\ndef read_from_string(line):\n nums = np.fromstring(line, dtype=float, sep=' ')\n return nums[0], nums[1:]\n\ndef mapper(key, value):\n # key: None\n # value: one line of input file\n np.random.seed(22)\n np.random.shuffle(value)\n w = np.zeros(DIM) #init w as zero vector\n t = 0 #iteration\n num_ins = len(value) # number of instances\n for line in value:\n t += 1;\n y, x = read_from_string(line)\n x = transform(x)\n eta = 1.0 / np.sqrt(t)\n loss = 1 - y*np.dot(w,x)\n if loss > 0:\n w = w - eta*(w/num_ins - C*loss*y*x)\n else:\n w = w - eta*(w/num_ins)\n yield 0, w # This is how you yield a key, value pair\n\n\ndef reducer(key, values):\n # key: key from mapper used to aggregate\n # values: list of all value for that key\n # Note that we do *not* output a (key, value) pair here.\n w = np.array(values)\n w = np.mean(w, axis=0)\n yield w\n","sub_path":"psgd.py","file_name":"psgd.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"383090668","text":"import os\nimport json\nimport pickle\nimport re\nfrom utils.crypto import sha256\n\n\ndef replace_backslashes_with_forward_slashes(path):\n return path.replace('\\\\', '/')\n\n\ndef make_dirs(dirname):\n if dirname is None:\n raise Exception(\"dirname cannot be None\")\n if os.path.isfile(dirname):\n raise Exception(\"dirname cannot be a file\")\n if not os.path.isdir(dirname):\n os.makedirs(dirname)\n\ndef load_json(filepath):\n try:\n with open(filepath, \"r\") as read_file:\n data = json.load(read_file)\n return data\n except:\n raise Exception(\"Cannot load config file\")\n\ndef save_json(data, filepath):\n try:\n dirname = os.path.dirname(filepath)\n make_dirs(dirname)\n with open(filepath, \"w\") as write_file:\n json.dump(data, write_file)\n except:\n raise Exception(\"Cannot write config file\")\n\n# Data\ndef cache_data(data, path):\n dir_prefix = os.path.dirname(path)\n make_dirs(dir_prefix)\n with open(path, 'wb') as f:\n pickle.dump(data, f)\n\ndef restore_data(path):\n with open(path, 'rb') as f:\n data = pickle.load(f)\n return data\n\n\ndef get_chunk_file_name(part_num):\n return 'part%04d' % part_num\n\n\ndef delete_chunk_files(chunk_dir):\n \"\"\"\n Delete all the chunk files (any file matching the regex) from this provided directory.\n :param chunk_dir: directory whose chunk files are being deleted\n :return:\n \"\"\"\n file_list = os.listdir(chunk_dir)\n for f in file_list:\n if re.fullmatch(r'^part[0-9][0-9][0-9][0-9]$', f):\n os.remove(os.path.join(chunk_dir, f))\n\n\ndef split_file(file_path, out_dir, chunk_size=1000000):\n \"\"\"\n Split a file into chunks of a specific size, save these chunks\n to the provided directory, deleting all chunks already stored in\n the directory.\n :param file_path: path of file to be split\n :param out_dir: directory to save file chunks\n :param chunk_size: size of file chunks in bytes\n :return:\n \"\"\"\n if not os.path.exists(file_path):\n raise Exception(\"file_path does not exist\")\n if not os.path.isfile(file_path):\n raise Exception(\"file_path must be a file\")\n\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n if not os.path.isdir(out_dir):\n raise Exception(\"out_dir must be a directory\")\n\n delete_chunk_files(out_dir)\n\n with open(file_path, \"rb\") as f:\n part_num = 0\n while True:\n chunk = f.read(chunk_size)\n if not chunk:\n break\n filename = os.path.join(out_dir, get_chunk_file_name(part_num))\n with open(filename, 'wb') as p:\n p.write(chunk)\n part_num += 1\n\n\ndef join_chunks(chunk_dir, out_file_path):\n \"\"\"\n Join chunks of split file back together to recreate file\n :param chunk_dir: directory containing chunks of file\n :param out_file_path: path of file being created\n :return:\n \"\"\"\n if not os.path.exists(chunk_dir):\n raise Exception(\"chunk_dir does not exist\")\n if not os.path.isdir(chunk_dir):\n raise Exception(\"chunk_dir must be a directory\")\n\n if os.path.dirname(out_file_path) and not os.path.exists(os.path.dirname(out_file_path)):\n os.makedirs(os.path.dirname(out_file_path))\n\n with open(out_file_path, \"wb\") as output:\n part_num = 0\n while True:\n filename = os.path.join(chunk_dir, get_chunk_file_name(part_num))\n if not os.path.exists(filename):\n break\n with open(filename, \"rb\") as f:\n chunk = f.read()\n output.write(chunk)\n part_num = part_num + 1\n\ndef split_file_and_get_hash(file_path, out_dir, chunk_size=1000000):\n \"\"\"\n Split a file into chunks of a specific size, save these chunks\n to the provided directory, deleting all chunks already stored in\n the directory, and return list of hashes of all chunks.\n :param file_path: path of file to be split\n :param out_dir: directory to save file chunks\n :param chunk_size: size of file chunks in bytes\n :return: dictionary, with key is path of chunk \n and value is string of hash of this chunk.\n \"\"\"\n if not os.path.exists(file_path):\n raise Exception(\"file_path does not exist\")\n if not os.path.isfile(file_path):\n raise Exception(\"file_path must be a file\")\n\n make_dirs(out_dir)\n if not os.path.isdir(out_dir):\n raise Exception(\"out_dir must be a directory\")\n\n delete_chunk_files(out_dir)\n \n hashes = {}\n with open(file_path, \"rb\") as f:\n part_num = 0\n while True:\n chunk = f.read(chunk_size)\n if not chunk:\n break\n filename = os.path.join(out_dir, get_chunk_file_name(part_num))\n with open(filename, 'wb') as p:\n p.write(chunk)\n part_num += 1\n hashes[filename] = str(sha256(chunk))\n return hashes\n\n\ndef get_hash_list_file_objects(directory, set_file_object_ids):\n \"\"\"\n Compute hash of all file objects in set_file_object_ids\n :param directory: string, a folder contains file objects\n :param set_file_object_ids: set of integers, contains list of file_id\n needed to compute hash\n :return: list of hashes of all file objects in set_file_object_ids\n \"\"\"\n hashList = []\n for file_id in set_file_object_ids:\n filepath = os.path.join(directory, str(file_id))\n with open(filepath, \"rb\") as f:\n hashList.append(sha256(f.read()))\n return hashList\n \ndef recursive_get_hash_list(directory):\n \"\"\"\n Recursively compute list of hashes of all file in the directory\n :param directory: string, a folder contains file needed to compute hash\n :return: list of hashes of all files in directory\n \"\"\"\n hashList = []\n for path in os.listdir(directory):\n path = os.path.join(directory, path)\n if os.path.isfile(path):\n with open(path, \"rb\") as f:\n hashList.append(sha256(f.read()))\n else:\n hashListInSubfolder = recursive_get_hash_list(path)\n hashList += hashListInSubfolder\n return hashList\n","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"426913370","text":"\"\"\"Unit tests for item_class.py\"\"\"\n\nimport pytest\nfrom flask import Flask, request, render_template, redirect, flash\nimport requests\nimport json\nfrom todo_app.item_class import item, get_card_object, get_items_on_a_board,get_list_progress,check_if_task_recently_completed, get_current_date\n\ndef test_always_passes():\n assert True\n\ndef test_get_current_date():\n current_date = get_current_date()\n assert len(current_date) > 9\n\n\"\"\"Integration tests for item_class.py\"\"\"\n\ndef test_get_items_on_a_board():\n item_count = 0\n test_items_on_board = get_items_on_a_board()\n found_item = False\n for myitem in test_items_on_board:\n if myitem[\"id\"] == '5fc6941c796b150565cb3836':\n found_item = True\n\n assert found_item == True\n\n\ndef test_get_card_object():\n \n test_items_on_board = get_card_object('DummyCard')\n\n assert test_items_on_board[\"id\"] == \"5f74ee5505790c8355378641\"\n\n\n\n\n","sub_path":"tests/test_item_class.py","file_name":"test_item_class.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"264095498","text":"import torch\nimport torch.nn as nn\n\n\nclass MultiSimilarityLoss(nn.Module):\n def __init__(self, alpha, beta, lamda, epsilon):\n super(MultiSimilarityLoss, self).__init__()\n self.alpha = alpha\n self.beta = beta\n self.lamda = lamda\n self.epsilon = epsilon\n \n def forward(self, x, y):\n S = x @ x.t()\n\n loss = []\n for i in range(x.shape[0]):\n pos_idx = y == y[i]\n pos_idx[i] = 0\n neg_idx = y != y[i]\n\n S_pos = S[i][pos_idx]\n S_neg = S[i][neg_idx]\n\n neg_idx = (S_neg + self.epsilon) > torch.min(S_pos)\n pos_idx = (S_pos - self.epsilon) < torch.max(S_neg)\n\n if not torch.sum(neg_idx) or not torch.sum(pos_idx):\n continue\n\n S_pos = S_pos[pos_idx]\n S_neg = S_neg[neg_idx]\n\n pos_loss = 1. / self.alpha * torch.log(1 + torch.sum(torch.exp(-self.alpha * (S_pos - self.lamda))))\n neg_loss = 1. / self.beta * torch.log(1 + torch.sum(torch.exp(self.beta * (S_neg - self.lamda))))\n loss.append(pos_loss + neg_loss)\n if len(loss) == 0:\n return 0 * S.mean()\n else:\n return torch.mean(torch.stack(loss))\n","sub_path":"MultiSimilarity/criterion/multi_similarity.py","file_name":"multi_similarity.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"82087639","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport os\r\n\r\nsensor_type = []\r\ntimes = []\r\ndata = []\r\nwith open('output.csv') as csvfile:\r\n reader = csv.reader(csvfile, delimiter = '\\t')\r\n names = reader.__next__()\r\n for line in reader:\r\n sensor_type.append(line[0])\r\n times.append(line[1])\r\n data.append(line[2:])\r\n\r\nnames.pop(0)\r\nnames.pop(0)\r\nsensor_type = np.array(sensor_type)\r\ntimes = np.array(times, dtype=float)\r\ndata = np.array(data, dtype=float)\r\n\r\ntitles = ['px','py','vx','vy','yaw', 'yaw_rate']\r\nunits = ['m','m','m/s','m/s','rad','rad/s']\r\nfig, ax = plt.subplots(nrows=3, ncols=2, figsize=(20,15))\r\ncurrent_datum = 0\r\nfor row in range(3):\r\n for col in range(2):\r\n diff = data[:,current_datum] - data[:,current_datum+1]\r\n rmse = np.sqrt(np.mean(diff*diff))\r\n print(\"{} RMSE: {:.3f}\".format(titles[row*2+col],rmse))\r\n ax[row, col].set_title(titles[row*2+col])\r\n ax[row, col].set_xlabel('s')\r\n ax[row, col].set_ylabel(units[row*2+col])\r\n ax[row, col].plot(times, data[:,current_datum], '-.', label = names[current_datum])\r\n ax[row, col].plot(times, data[:,current_datum+1], label = names[current_datum + 1])\r\n ax[row, col].legend()\r\n current_datum += 2\r\n\r\nfig.savefig('plots.png', bbox_inches='tight')\r\n\r\nfig, ax = plt.subplots(nrows=2, ncols=1, figsize=(20,15))\r\nlidar_nis = data[sensor_type=='L', 12]\r\nnum_sample = lidar_nis.shape[0]\r\nx_axis = np.arange(num_sample)\r\nax[0].set_title(\"LIDAR NIS\")\r\nax[0].plot(x_axis, lidar_nis)\r\nax[0].plot([0, num_sample], [5.991, 5.991])\r\n\r\nradar_nis = data[sensor_type=='R', 12]\r\nradar_nis = radar_nis[1:]\r\nnum_sample = radar_nis.shape[0]\r\nx_axis = np.arange(num_sample)\r\nax[1].set_title(\"RADAR NIS\")\r\nax[1].plot(x_axis, radar_nis)\r\nax[1].plot([0, num_sample], [7.815, 7.815])\r\n\r\nfig.savefig('nis.png', bbox_inches='tight')\r\n","sub_path":"src/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"138657444","text":"#software to encode, byte swapped pcm file (input to p1)\n#set hdkboard to a3kdirect mode\n\nimport re\nimport serial\nimport time\nimport byte_swap\n\n#configure serial\nser = serial.Serial(\n port = 'COM4',\n baudrate = 460800,\n timeout = 0.02,\n rtscts = 0,\n xonxoff = 0\n)\n\n#send opening packet\npckOp1 = '6100110010003200400B0709270518401500012F37'\n\nser.write(pckOp1.decode('hex'))\ntime.sleep(0.02)\n\n#swap byte of pcm file\nbyte_swap.swap('rec_packet_raw.pcm','rec_packet_raw_byte_swap.pcm')\n\n\n#open byte swapped pcm file\nf = open('rec_packet_raw_byte_swap.pcm','rb') #open manually recorded file\n#f = open('ref_codec_dec_byte_swap.pcm','rb') #open recorded file by hdkcom\nfPcm = f.read()\nf.close()\n\nh = fPcm.encode('hex')\n\n#split audio file to chunk\nwhole = len(h)\nchunkSize = 640\nchunks = []\npckHeader = '01470200A0'\npckCmode = '0210402F'\nfor i in range(0,whole,chunkSize):\n chunk = h[i:i+chunkSize]\n if len(chunk) < chunkSize:\n chunk = chunk.ljust(chunkSize,'0')\n chunk = pckHeader + chunk + pckCmode\n #print chunk\n chunks.append(chunk)\n\n#calculate parity of each chunk then send to vocoder\nbyteSize = 2\npckStart = '61'\ns = ''\nfor i in range(len(chunks)):\n xorRslt = 0\n #xor each byte in chunk\n for j in range(0,len(chunks[i]),byteSize):\n byte = chunks[i][j:j+2]\n num = int(byte,16)\n xorRslt = xorRslt ^ num\n if xorRslt < 16:\n pckPrty = str(format(xorRslt,'x'))\n pckPrty = '0' + pckPrty\n else:\n pckPrty = str(format(xorRslt,'x'))\n chunks[i] = pckStart + chunks[i] + pckPrty\n #print chunks[i]\n #send chunk continuously\n ser.write(chunks[i].decode('hex'))\n rspn = ser.read(25)\n s += rspn.encode('hex')\n #print rspn.encode('hex')\n#print s\n\n#remove response of opening packet\npckOpRspn1 = '6100010401'\npckOpRspn2 = '610010001000320040000b000900050015002f4f'\n\ns = re.sub(pckOpRspn1,'',s,count=1)\ns = re.sub(pckOpRspn2,'',s,count=1)\n#print s\n\n#open encoded file\nfEncoded = open('manual_enc.bit','wb')\n\n#split response of speech packet to chunk\nwhole = len(s)\nchunkSize = 40\nfor i in range(0,whole,chunkSize):\n chunk = s[i:i+chunkSize]\n if len(chunk) == 40:\n chunk = chunk[12:] #remove pckStart and pckHeader\n chunk = chunk[:-10] #remove pckCmode and pckPrty\n chunk = chunk.decode('hex')\n fEncoded.write(chunk)\nfEncoded.close()\n","sub_path":"hdkcom/packet_mode/encode_manual_p1.py","file_name":"encode_manual_p1.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"42799470","text":"# import time\n# class Clock:\n# def __init__(self, hr, mi, se):\n#\n# self.hour = hr\n# self.minute = mi\n# self.second = se\n#\n# def setHour(self, hour):\n# self.hour = hour\n#\n# def getHour(self):\n# if int(self.hour) <= 23 and int(self.hour) >= 0:\n# return self.hour\n# else:\n# return (\" Hour should be between 0 and 23\")\n#\n# def setMin(self, minute):\n# self.mintue = minute\n#\n# def getMin(self):\n# if int(self.minute) <= 59 and int(self.minute) >= 0:\n# return self.minute\n# else:\n# return(\" Minute should be between 0 and 59\")\n#\n# def setSec(self, second):\n# self.second = second\n#\n# def getSec(self):\n# if int(self.second) <= 59 and int(self.second) >= 0:\n# return self.second\n# else:\n# return(\" Seconds should be between 0 and 59\")\n#\n# def increase(self):\n# hr = int(self.hour)\n# mi = int(self.minute)\n# sc = int(self.second)\n# print('Increased second ', int(self.second)+1)\n#\n# if int(sc) > 59:\n# print(\"Minute increase: \",mi + 1)\n# sc = 0\n# print(\"Second rest: \",sc)\n#\n# if int(mi) > 59:\n# print(\"Hour increased \",hr + 1)\n# mi = 0\n# print(\"minute rest \", mi)\n#\n#\n#\n# def __str__(self):\n# # msg = \" Time : \"+ str(self.getHour())+ \" minutes \"+ str(self.getMin())\n# # \" seconds\"+str(self.getSec())\n# if(self.getSec() and self.getMin() and self.getHour() == None):\n# return \"Empty\"\n# else:\n# msg = \"jjjj\"\n# return msg\n#\n#\n#\n#\n\nfrom clockApp import Clock\n\n\ndef main():\n hour = int(input(\"Enter hour: \\n\"))\n minute = int(input(\"Enter minute: \\n\"))\n second = int(input(\"Enter seconds: \\n\"))\n\n codd = Clock(hour, minute, second)\n\n # print(\">>>\",codd.increase())\n # codd.setSec(second)\n # codd.setMin(minute)\n # codd.setHour(hour)\n print(\"Clock value before increase\")\n print(codd)\n print(\"Clock value after increase\")\n codd.increase()\n print(codd)\nmain()\n","sub_path":"Clock/ClockTest.py","file_name":"ClockTest.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"273244190","text":"from __future__ import absolute_import, unicode_literals\n\nfrom django.conf import settings\n\nCONFIG_DEFAULTS = {\n \"CLIENT_ID\": None,\n \"SECRET_KEY\": None,\n \"AUTHORIZATION_BASE_URL\": \"https://login.eveonline.com/oauth/authorize\",\n \"TOKEN_URL\": \"https://login.eveonline.com/oauth/token\",\n \"VERIFY_URL\": \"https://login.eveonline.com/oauth/verify\",\n \"SCOPE\": None, # list\n}\n\nEVE_AUTH_CONFIG = getattr(settings, 'EVE_AUTH_CONFIG', {})\n\nCONFIG = CONFIG_DEFAULTS.copy()\nCONFIG.update(EVE_AUTH_CONFIG)\n\nEVE_AUTH_ALLOW_INSECURE_TRANSPORT = getattr(settings, \"EVE_AUTH_ALLOW_INSECURE_TRANSPORT\", settings.DEBUG)\n","sub_path":"eve_auth/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"50317470","text":"import os\n\nimport pytest\n\nfrom jina import Document, __default_host__\nfrom jina.clients import Client\nfrom jina.clients.grpc import GRPCClient\nfrom jina.parsers import set_client_cli_parser\nfrom tests import validate_callback\nfrom ..helpers import create_workspace, wait_for_workspace, create_flow, assert_request\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\ncompose_yml = os.path.join(cur_dir, 'docker-compose.yml')\nflow_yaml = os.path.join(cur_dir, 'flow.yml')\npod_dir = os.path.join(cur_dir, 'pods')\n\n\nJINAD_HOST = __default_host__\nGATEWAY_HOST = __default_host__\nJINAD_PORT = 8000\nGATEWAY_PORT = 45678\n\n\n@pytest.fixture\ndef doc_to_index():\n doc = Document()\n doc.text = 'test'\n return doc\n\n\n@pytest.fixture\ndef client():\n return Client(host='localhost', port=45678)\n\n\n@pytest.fixture\ndef grpc_client():\n args = set_client_cli_parser().parse_args(\n ['--host', 'localhost', '--port', '45678']\n )\n\n return GRPCClient(args)\n\n\n@pytest.fixture(params=['client', 'grpc_client'])\ndef client_instance(request):\n return request.getfixturevalue(request.param)\n\n\n@pytest.mark.skip('jinad with docker-compose not supported for now')\n@pytest.mark.timeout(360)\n@pytest.mark.parametrize('docker_compose', [compose_yml], indirect=['docker_compose'])\ndef test_flow(docker_compose, doc_to_index, client_instance, mocker):\n def validate_resp(resp):\n assert len(resp.data.docs) == 2\n assert resp.data.docs[0].text == 'test'\n assert resp.data.docs[1].text == 'test'\n\n mock = mocker.Mock()\n workspace_id = create_workspace(filepaths=[flow_yaml], dirpath=pod_dir)\n assert wait_for_workspace(workspace_id)\n flow_id = create_flow(\n workspace_id=workspace_id,\n filename='flow.yml',\n )\n\n client_instance.search(inputs=[doc_to_index], on_done=mock)\n\n assert_request(method='get', url=f'http://{JINAD_HOST}:8000/flows/{flow_id}')\n\n assert_request(\n method='delete',\n url=f'http://{JINAD_HOST}:8000/flows/{flow_id}',\n # payload={'workspace': False},\n )\n\n mock.assert_called_once()\n validate_callback(mock, validate_resp)\n","sub_path":"tests/distributed/test_join_local_from_remote/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"563638987","text":"from PyQt4 import QtCore, QtGui\nimport sys\nfrom controller import *\nfrom PyQt4.QtCore import *\n\nimport threading\nimport rospy\nimport process\nimport os\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_Dialog(object):\n # def __init__(self, key, val):\n # self._key = key\n # self._val = val\n\n def setupUi(self, Dialog):\n Dialog.setObjectName(_fromUtf8(\"Dialog\"))\n Dialog.resize(948, 651)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../../../../../.designer/backup/monitoring_icon.jpg\")),\n QtGui.QIcon.Normal, QtGui.QIcon.Off)\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\"../../../../../../.designer/backup/monitoring_icon.jpg\")),\n QtGui.QIcon.Normal, QtGui.QIcon.On)\n Dialog.setWindowIcon(icon)\n self.tabWidget = QtGui.QTabWidget(Dialog)\n self.tabWidget.setGeometry(QtCore.QRect(0, 0, 741, 641))\n self.tabWidget.setObjectName(_fromUtf8(\"tabWidget\"))\n self.tab = QtGui.QWidget()\n self.tab.setObjectName(_fromUtf8(\"tab\"))\n self.listWidget = QtGui.QListWidget(self.tab)\n self.listWidget.setGeometry(QtCore.QRect(0, 0, 731, 601))\n self.listWidget.setObjectName(_fromUtf8(\"listWidget\"))\n self.tabWidget.addTab(self.tab, _fromUtf8(\"\"))\n self.tab_3 = QtGui.QWidget()\n self.tab_3.setObjectName(_fromUtf8(\"tab_3\"))\n self.frame_4 = QtGui.QFrame(self.tab_3)\n self.frame_4.setGeometry(QtCore.QRect(30, 10, 191, 271))\n self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_4.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_4.setObjectName(_fromUtf8(\"frame_4\"))\n self.label_19 = QtGui.QLabel(self.frame_4)\n self.label_19.setGeometry(QtCore.QRect(150, 50, 66, 17))\n self.label_19.setText(_fromUtf8(\"\"))\n self.label_19.setObjectName(_fromUtf8(\"label_19\"))\n self.label_27 = QtGui.QLabel(self.frame_4)\n self.label_27.setGeometry(QtCore.QRect(110, 80, 66, 17))\n self.label_27.setText(_fromUtf8(\"\"))\n self.label_27.setObjectName(_fromUtf8(\"label_27\"))\n self.label_10 = QtGui.QLabel(self.frame_4)\n self.label_10.setGeometry(QtCore.QRect(110, 160, 66, 17))\n self.label_10.setText(_fromUtf8(\"\"))\n self.label_10.setObjectName(_fromUtf8(\"label_10\"))\n self.label_7 = QtGui.QLabel(self.frame_4)\n self.label_7.setGeometry(QtCore.QRect(10, 240, 121, 17))\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.label = QtGui.QLabel(self.frame_4)\n self.label.setGeometry(QtCore.QRect(10, 40, 111, 16))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.label_5 = QtGui.QLabel(self.frame_4)\n self.label_5.setGeometry(QtCore.QRect(10, 160, 101, 17))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.label_8 = QtGui.QLabel(self.frame_4)\n self.label_8.setGeometry(QtCore.QRect(110, 80, 66, 17))\n self.label_8.setText(_fromUtf8(\"\"))\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.label_2 = QtGui.QLabel(self.frame_4)\n self.label_2.setGeometry(QtCore.QRect(110, 40, 66, 17))\n self.label_2.setText(_fromUtf8(\"\"))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_11 = QtGui.QLabel(self.frame_4)\n self.label_11.setGeometry(QtCore.QRect(110, 200, 66, 17))\n self.label_11.setText(_fromUtf8(\"\"))\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.label_9 = QtGui.QLabel(self.frame_4)\n self.label_9.setGeometry(QtCore.QRect(110, 120, 66, 17))\n self.label_9.setText(_fromUtf8(\"\"))\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.label_12 = QtGui.QLabel(self.frame_4)\n self.label_12.setGeometry(QtCore.QRect(110, 240, 66, 17))\n self.label_12.setText(_fromUtf8(\"\"))\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.label_6 = QtGui.QLabel(self.frame_4)\n self.label_6.setGeometry(QtCore.QRect(10, 200, 121, 17))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.label_3 = QtGui.QLabel(self.frame_4)\n self.label_3.setGeometry(QtCore.QRect(10, 80, 121, 17))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.label_4 = QtGui.QLabel(self.frame_4)\n self.label_4.setGeometry(QtCore.QRect(10, 120, 101, 17))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.label_16 = QtGui.QLabel(self.frame_4)\n self.label_16.setGeometry(QtCore.QRect(10, 10, 131, 17))\n self.label_16.setObjectName(_fromUtf8(\"label_16\"))\n self.frame_5 = QtGui.QFrame(self.tab_3)\n self.frame_5.setGeometry(QtCore.QRect(240, 10, 261, 271))\n self.frame_5.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_5.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_5.setObjectName(_fromUtf8(\"frame_5\"))\n self.label_20 = QtGui.QLabel(self.frame_5)\n self.label_20.setGeometry(QtCore.QRect(130, 50, 66, 17))\n self.label_20.setText(_fromUtf8(\"\"))\n self.label_20.setObjectName(_fromUtf8(\"label_20\"))\n self.label_24 = QtGui.QLabel(self.frame_5)\n self.label_24.setGeometry(QtCore.QRect(20, 50, 91, 17))\n self.label_24.setTextFormat(QtCore.Qt.AutoText)\n self.label_24.setObjectName(_fromUtf8(\"label_24\"))\n self.label_26 = QtGui.QLabel(self.frame_5)\n self.label_26.setGeometry(QtCore.QRect(20, 90, 101, 17))\n self.label_26.setObjectName(_fromUtf8(\"label_26\"))\n self.label_28 = QtGui.QLabel(self.frame_5)\n self.label_28.setGeometry(QtCore.QRect(130, 90, 66, 17))\n self.label_28.setText(_fromUtf8(\"\"))\n self.label_28.setObjectName(_fromUtf8(\"label_28\"))\n self.label_17 = QtGui.QLabel(self.frame_5)\n self.label_17.setGeometry(QtCore.QRect(20, 10, 71, 17))\n self.label_17.setObjectName(_fromUtf8(\"label_17\"))\n self.label_31 = QtGui.QLabel(self.frame_5)\n self.label_31.setGeometry(QtCore.QRect(130, 130, 66, 17))\n self.label_31.setText(_fromUtf8(\"\"))\n self.label_31.setObjectName(_fromUtf8(\"label_31\"))\n self.label_36 = QtGui.QLabel(self.frame_5)\n self.label_36.setGeometry(QtCore.QRect(20, 130, 111, 17))\n self.label_36.setObjectName(_fromUtf8(\"label_36\"))\n self.label_38 = QtGui.QLabel(self.frame_5)\n self.label_38.setGeometry(QtCore.QRect(20, 170, 101, 17))\n self.label_38.setObjectName(_fromUtf8(\"label_38\"))\n self.label_39 = QtGui.QLabel(self.frame_5)\n self.label_39.setGeometry(QtCore.QRect(130, 170, 66, 17))\n self.label_39.setText(_fromUtf8(\"\"))\n self.label_39.setObjectName(_fromUtf8(\"label_39\"))\n self.frame_6 = QtGui.QFrame(self.tab_3)\n self.frame_6.setGeometry(QtCore.QRect(520, 10, 171, 271))\n self.frame_6.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_6.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_6.setObjectName(_fromUtf8(\"frame_6\"))\n self.label_21 = QtGui.QLabel(self.frame_6)\n self.label_21.setGeometry(QtCore.QRect(90, 40, 66, 17))\n self.label_21.setText(_fromUtf8(\"\"))\n self.label_21.setObjectName(_fromUtf8(\"label_21\"))\n self.label_29 = QtGui.QLabel(self.frame_6)\n self.label_29.setGeometry(QtCore.QRect(150, 90, 66, 17))\n self.label_29.setText(_fromUtf8(\"\"))\n self.label_29.setObjectName(_fromUtf8(\"label_29\"))\n self.label_30 = QtGui.QLabel(self.frame_6)\n self.label_30.setGeometry(QtCore.QRect(90, 160, 66, 17))\n self.label_30.setText(_fromUtf8(\"\"))\n self.label_30.setObjectName(_fromUtf8(\"label_30\"))\n self.label_32 = QtGui.QLabel(self.frame_6)\n self.label_32.setGeometry(QtCore.QRect(10, 40, 71, 16))\n self.label_32.setObjectName(_fromUtf8(\"label_32\"))\n self.label_33 = QtGui.QLabel(self.frame_6)\n self.label_33.setGeometry(QtCore.QRect(10, 160, 71, 17))\n self.label_33.setObjectName(_fromUtf8(\"label_33\"))\n self.label_34 = QtGui.QLabel(self.frame_6)\n self.label_34.setGeometry(QtCore.QRect(90, 80, 66, 17))\n self.label_34.setText(_fromUtf8(\"\"))\n self.label_34.setObjectName(_fromUtf8(\"label_34\"))\n self.label_35 = QtGui.QLabel(self.frame_6)\n self.label_35.setGeometry(QtCore.QRect(140, 40, 66, 17))\n self.label_35.setText(_fromUtf8(\"\"))\n self.label_35.setObjectName(_fromUtf8(\"label_35\"))\n self.label_37 = QtGui.QLabel(self.frame_6)\n self.label_37.setGeometry(QtCore.QRect(90, 120, 66, 17))\n self.label_37.setText(_fromUtf8(\"\"))\n self.label_37.setObjectName(_fromUtf8(\"label_37\"))\n self.label_40 = QtGui.QLabel(self.frame_6)\n self.label_40.setGeometry(QtCore.QRect(10, 80, 71, 17))\n self.label_40.setObjectName(_fromUtf8(\"label_40\"))\n self.label_41 = QtGui.QLabel(self.frame_6)\n self.label_41.setGeometry(QtCore.QRect(10, 120, 71, 17))\n self.label_41.setObjectName(_fromUtf8(\"label_41\"))\n self.label_42 = QtGui.QLabel(self.frame_6)\n self.label_42.setGeometry(QtCore.QRect(10, 10, 71, 17))\n self.label_42.setObjectName(_fromUtf8(\"label_42\"))\n self.frame_7 = QtGui.QFrame(self.tab_3)\n self.frame_7.setGeometry(QtCore.QRect(240, 300, 261, 281))\n self.frame_7.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_7.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_7.setObjectName(_fromUtf8(\"frame_7\"))\n self.label_43 = QtGui.QLabel(self.frame_7)\n self.label_43.setGeometry(QtCore.QRect(60, 80, 66, 20))\n self.label_43.setText(_fromUtf8(\"\"))\n self.label_43.setObjectName(_fromUtf8(\"label_43\"))\n self.label_44 = QtGui.QLabel(self.frame_7)\n self.label_44.setGeometry(QtCore.QRect(30, 50, 71, 17))\n self.label_44.setTextFormat(QtCore.Qt.AutoText)\n self.label_44.setObjectName(_fromUtf8(\"label_44\"))\n self.label_45 = QtGui.QLabel(self.frame_7)\n self.label_45.setGeometry(QtCore.QRect(150, 50, 81, 17))\n self.label_45.setObjectName(_fromUtf8(\"label_45\"))\n self.label_47 = QtGui.QLabel(self.frame_7)\n self.label_47.setGeometry(QtCore.QRect(80, 10, 101, 17))\n self.label_47.setObjectName(_fromUtf8(\"label_47\"))\n self.label_53 = QtGui.QLabel(self.frame_7)\n self.label_53.setGeometry(QtCore.QRect(30, 80, 21, 17))\n self.label_53.setTextFormat(QtCore.Qt.AutoText)\n self.label_53.setObjectName(_fromUtf8(\"label_53\"))\n self.label_54 = QtGui.QLabel(self.frame_7)\n self.label_54.setGeometry(QtCore.QRect(60, 110, 66, 20))\n self.label_54.setText(_fromUtf8(\"\"))\n self.label_54.setObjectName(_fromUtf8(\"label_54\"))\n self.label_55 = QtGui.QLabel(self.frame_7)\n self.label_55.setGeometry(QtCore.QRect(30, 110, 21, 17))\n self.label_55.setTextFormat(QtCore.Qt.AutoText)\n self.label_55.setObjectName(_fromUtf8(\"label_55\"))\n self.label_68 = QtGui.QLabel(self.frame_7)\n self.label_68.setGeometry(QtCore.QRect(150, 110, 21, 17))\n self.label_68.setTextFormat(QtCore.Qt.AutoText)\n self.label_68.setObjectName(_fromUtf8(\"label_68\"))\n self.label_67 = QtGui.QLabel(self.frame_7)\n self.label_67.setGeometry(QtCore.QRect(180, 110, 66, 20))\n self.label_67.setText(_fromUtf8(\"\"))\n self.label_67.setObjectName(_fromUtf8(\"label_67\"))\n self.label_69 = QtGui.QLabel(self.frame_7)\n self.label_69.setGeometry(QtCore.QRect(180, 140, 66, 20))\n self.label_69.setText(_fromUtf8(\"\"))\n self.label_69.setObjectName(_fromUtf8(\"label_69\"))\n self.label_70 = QtGui.QLabel(self.frame_7)\n self.label_70.setGeometry(QtCore.QRect(150, 140, 21, 17))\n self.label_70.setTextFormat(QtCore.Qt.AutoText)\n self.label_70.setObjectName(_fromUtf8(\"label_70\"))\n self.label_71 = QtGui.QLabel(self.frame_7)\n self.label_71.setGeometry(QtCore.QRect(180, 170, 66, 20))\n self.label_71.setText(_fromUtf8(\"\"))\n self.label_71.setObjectName(_fromUtf8(\"label_71\"))\n self.label_72 = QtGui.QLabel(self.frame_7)\n self.label_72.setGeometry(QtCore.QRect(150, 170, 21, 17))\n self.label_72.setTextFormat(QtCore.Qt.AutoText)\n self.label_72.setObjectName(_fromUtf8(\"label_72\"))\n self.label_73 = QtGui.QLabel(self.frame_7)\n self.label_73.setGeometry(QtCore.QRect(180, 200, 66, 20))\n self.label_73.setText(_fromUtf8(\"\"))\n self.label_73.setObjectName(_fromUtf8(\"label_73\"))\n self.label_74 = QtGui.QLabel(self.frame_7)\n self.label_74.setGeometry(QtCore.QRect(150, 200, 21, 17))\n self.label_74.setTextFormat(QtCore.Qt.AutoText)\n self.label_74.setObjectName(_fromUtf8(\"label_74\"))\n self.label_75 = QtGui.QLabel(self.frame_7)\n self.label_75.setGeometry(QtCore.QRect(180, 230, 66, 20))\n self.label_75.setText(_fromUtf8(\"\"))\n self.label_75.setObjectName(_fromUtf8(\"label_75\"))\n self.label_76 = QtGui.QLabel(self.frame_7)\n self.label_76.setGeometry(QtCore.QRect(150, 230, 21, 17))\n self.label_76.setTextFormat(QtCore.Qt.AutoText)\n self.label_76.setObjectName(_fromUtf8(\"label_76\"))\n self.label_77 = QtGui.QLabel(self.frame_7)\n self.label_77.setGeometry(QtCore.QRect(180, 260, 66, 20))\n self.label_77.setText(_fromUtf8(\"\"))\n self.label_77.setObjectName(_fromUtf8(\"label_77\"))\n self.label_78 = QtGui.QLabel(self.frame_7)\n self.label_78.setGeometry(QtCore.QRect(150, 260, 21, 17))\n self.label_78.setTextFormat(QtCore.Qt.AutoText)\n self.label_78.setObjectName(_fromUtf8(\"label_78\"))\n self.label_57 = QtGui.QLabel(self.frame_7)\n self.label_57.setGeometry(QtCore.QRect(60, 140, 66, 20))\n self.label_57.setText(_fromUtf8(\"\"))\n self.label_57.setObjectName(_fromUtf8(\"label_57\"))\n self.label_59 = QtGui.QLabel(self.frame_7)\n self.label_59.setGeometry(QtCore.QRect(30, 140, 21, 17))\n self.label_59.setTextFormat(QtCore.Qt.AutoText)\n self.label_59.setObjectName(_fromUtf8(\"label_59\"))\n self.label_61 = QtGui.QLabel(self.frame_7)\n self.label_61.setGeometry(QtCore.QRect(60, 170, 66, 20))\n self.label_61.setText(_fromUtf8(\"\"))\n self.label_61.setObjectName(_fromUtf8(\"label_61\"))\n self.label_63 = QtGui.QLabel(self.frame_7)\n self.label_63.setGeometry(QtCore.QRect(30, 170, 21, 17))\n self.label_63.setTextFormat(QtCore.Qt.AutoText)\n self.label_63.setObjectName(_fromUtf8(\"label_63\"))\n self.label_65 = QtGui.QLabel(self.frame_7)\n self.label_65.setGeometry(QtCore.QRect(60, 200, 66, 20))\n self.label_65.setText(_fromUtf8(\"\"))\n self.label_65.setObjectName(_fromUtf8(\"label_65\"))\n self.label_66 = QtGui.QLabel(self.frame_7)\n self.label_66.setGeometry(QtCore.QRect(30, 200, 21, 17))\n self.label_66.setTextFormat(QtCore.Qt.AutoText)\n self.label_66.setObjectName(_fromUtf8(\"label_66\"))\n self.label_83 = QtGui.QLabel(self.frame_7)\n self.label_83.setGeometry(QtCore.QRect(60, 230, 66, 20))\n self.label_83.setText(_fromUtf8(\"\"))\n self.label_83.setObjectName(_fromUtf8(\"label_83\"))\n self.label_84 = QtGui.QLabel(self.frame_7)\n self.label_84.setGeometry(QtCore.QRect(30, 230, 21, 17))\n self.label_84.setTextFormat(QtCore.Qt.AutoText)\n self.label_84.setObjectName(_fromUtf8(\"label_84\"))\n self.label_85 = QtGui.QLabel(self.frame_7)\n self.label_85.setGeometry(QtCore.QRect(60, 260, 66, 20))\n self.label_85.setText(_fromUtf8(\"\"))\n self.label_85.setObjectName(_fromUtf8(\"label_85\"))\n self.label_86 = QtGui.QLabel(self.frame_7)\n self.label_86.setGeometry(QtCore.QRect(30, 260, 21, 17))\n self.label_86.setTextFormat(QtCore.Qt.AutoText)\n self.label_86.setObjectName(_fromUtf8(\"label_86\"))\n self.label_87 = QtGui.QLabel(self.frame_7)\n self.label_87.setGeometry(QtCore.QRect(180, 80, 66, 20))\n self.label_87.setText(_fromUtf8(\"\"))\n self.label_87.setObjectName(_fromUtf8(\"label_87\"))\n self.label_88 = QtGui.QLabel(self.frame_7)\n self.label_88.setGeometry(QtCore.QRect(150, 80, 21, 17))\n self.label_88.setTextFormat(QtCore.Qt.AutoText)\n self.label_88.setObjectName(_fromUtf8(\"label_88\"))\n self.label_64 = QtGui.QLabel(self.frame_7)\n self.label_64.setGeometry(QtCore.QRect(60, 260, 66, 17))\n self.label_64.setText(_fromUtf8(\"\"))\n self.label_64.setObjectName(_fromUtf8(\"label_64\"))\n self.label_58 = QtGui.QLabel(self.frame_7)\n self.label_58.setGeometry(QtCore.QRect(60, 170, 66, 17))\n self.label_58.setText(_fromUtf8(\"\"))\n self.label_58.setObjectName(_fromUtf8(\"label_58\"))\n self.label_18 = QtGui.QLabel(self.frame_7)\n self.label_18.setGeometry(QtCore.QRect(60, 200, 66, 17))\n self.label_18.setText(_fromUtf8(\"\"))\n self.label_18.setObjectName(_fromUtf8(\"label_18\"))\n self.label_62 = QtGui.QLabel(self.frame_7)\n self.label_62.setGeometry(QtCore.QRect(60, 230, 66, 17))\n self.label_62.setText(_fromUtf8(\"\"))\n self.label_62.setObjectName(_fromUtf8(\"label_62\"))\n self.label_46 = QtGui.QLabel(self.frame_7)\n self.label_46.setGeometry(QtCore.QRect(180, 80, 66, 17))\n self.label_46.setText(_fromUtf8(\"\"))\n self.label_46.setObjectName(_fromUtf8(\"label_46\"))\n self.frame_8 = QtGui.QFrame(self.tab_3)\n self.frame_8.setGeometry(QtCore.QRect(30, 300, 191, 281))\n self.frame_8.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_8.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_8.setObjectName(_fromUtf8(\"frame_8\"))\n self.label_48 = QtGui.QLabel(self.frame_8)\n self.label_48.setGeometry(QtCore.QRect(60, 40, 66, 17))\n self.label_48.setText(_fromUtf8(\"\"))\n self.label_48.setObjectName(_fromUtf8(\"label_48\"))\n self.label_49 = QtGui.QLabel(self.frame_8)\n self.label_49.setGeometry(QtCore.QRect(20, 40, 31, 17))\n self.label_49.setTextFormat(QtCore.Qt.AutoText)\n self.label_49.setObjectName(_fromUtf8(\"label_49\"))\n self.label_50 = QtGui.QLabel(self.frame_8)\n self.label_50.setGeometry(QtCore.QRect(20, 70, 31, 17))\n self.label_50.setObjectName(_fromUtf8(\"label_50\"))\n self.label_51 = QtGui.QLabel(self.frame_8)\n self.label_51.setGeometry(QtCore.QRect(60, 70, 66, 17))\n self.label_51.setText(_fromUtf8(\"\"))\n self.label_51.setObjectName(_fromUtf8(\"label_51\"))\n self.label_52 = QtGui.QLabel(self.frame_8)\n self.label_52.setGeometry(QtCore.QRect(20, 10, 161, 17))\n self.label_52.setObjectName(_fromUtf8(\"label_52\"))\n self.label_79 = QtGui.QLabel(self.frame_8)\n self.label_79.setGeometry(QtCore.QRect(60, 100, 66, 17))\n self.label_79.setText(_fromUtf8(\"\"))\n self.label_79.setObjectName(_fromUtf8(\"label_79\"))\n self.label_80 = QtGui.QLabel(self.frame_8)\n self.label_80.setGeometry(QtCore.QRect(20, 100, 31, 17))\n self.label_80.setObjectName(_fromUtf8(\"label_80\"))\n self.label_81 = QtGui.QLabel(self.frame_8)\n self.label_81.setGeometry(QtCore.QRect(60, 130, 66, 17))\n self.label_81.setText(_fromUtf8(\"\"))\n self.label_81.setObjectName(_fromUtf8(\"label_81\"))\n self.label_82 = QtGui.QLabel(self.frame_8)\n self.label_82.setGeometry(QtCore.QRect(20, 130, 31, 17))\n self.label_82.setObjectName(_fromUtf8(\"label_82\"))\n self.tabWidget.addTab(self.tab_3, _fromUtf8(\"\"))\n self.frame = QtGui.QFrame(Dialog)\n self.frame.setGeometry(QtCore.QRect(750, 280, 191, 191))\n self.frame.setStyleSheet(_fromUtf8(\" border-style: ridge;\\n\"\n \" border-width: 1px;\\n\"\n \"\"))\n self.frame.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame.setFrameShadow(QtGui.QFrame.Raised)\n self.frame.setObjectName(_fromUtf8(\"frame\"))\n self.label_13 = QtGui.QLabel(self.frame)\n self.label_13.setGeometry(QtCore.QRect(10, 10, 171, 17))\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.radioButton = QtGui.QRadioButton(self.frame)\n self.radioButton.setGeometry(QtCore.QRect(10, 100, 151, 22))\n self.radioButton.setObjectName(_fromUtf8(\"radioButton\"))\n self.radioButton_2 = QtGui.QRadioButton(self.frame)\n self.radioButton_2.setGeometry(QtCore.QRect(10, 130, 151, 22))\n self.radioButton_2.setObjectName(_fromUtf8(\"radioButton_2\"))\n self.radioButton_3 = QtGui.QRadioButton(self.frame)\n self.radioButton_3.setGeometry(QtCore.QRect(10, 160, 151, 22))\n self.radioButton_3.setObjectName(_fromUtf8(\"radioButton_3\"))\n self.radioButton_4 = QtGui.QRadioButton(self.frame)\n self.radioButton_4.setGeometry(QtCore.QRect(10, 40, 116, 22))\n self.radioButton_4.setObjectName(_fromUtf8(\"radioButton_4\"))\n self.radioButton_5 = QtGui.QRadioButton(self.frame)\n self.radioButton_5.setGeometry(QtCore.QRect(10, 70, 116, 22))\n self.radioButton_5.setObjectName(_fromUtf8(\"radioButton_5\"))\n self.frame_2 = QtGui.QFrame(Dialog)\n self.frame_2.setGeometry(QtCore.QRect(750, 30, 191, 241))\n self.frame_2.setStyleSheet(_fromUtf8(\" border-style: ridge;\\n\"\n \" border-width: 1px;\\n\"\n \"\"))\n self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame_2.setFrameShadow(QtGui.QFrame.Raised)\n self.frame_2.setObjectName(_fromUtf8(\"frame_2\"))\n self.checkBox = QtGui.QCheckBox(self.frame_2)\n self.checkBox.setGeometry(QtCore.QRect(10, 40, 121, 22))\n self.checkBox.setObjectName(_fromUtf8(\"checkBox\"))\n self.checkBox_2 = QtGui.QCheckBox(self.frame_2)\n self.checkBox_2.setGeometry(QtCore.QRect(10, 70, 121, 22))\n self.checkBox_2.setObjectName(_fromUtf8(\"checkBox_2\"))\n self.checkBox_3 = QtGui.QCheckBox(self.frame_2)\n self.checkBox_3.setGeometry(QtCore.QRect(10, 100, 121, 22))\n self.checkBox_3.setObjectName(_fromUtf8(\"checkBox_3\"))\n self.checkBox_4 = QtGui.QCheckBox(self.frame_2)\n self.checkBox_4.setGeometry(QtCore.QRect(10, 130, 121, 22))\n self.checkBox_4.setObjectName(_fromUtf8(\"checkBox_4\"))\n self.pushButton = QtGui.QPushButton(self.frame_2)\n self.pushButton.setGeometry(QtCore.QRect(10, 200, 98, 27))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.checkBox_5 = QtGui.QCheckBox(self.frame_2)\n self.checkBox_5.setGeometry(QtCore.QRect(10, 160, 121, 22))\n self.checkBox_5.setObjectName(_fromUtf8(\"checkBox_5\"))\n self.label_14 = QtGui.QLabel(self.frame_2)\n self.label_14.setGeometry(QtCore.QRect(10, 10, 131, 17))\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.label_56 = QtGui.QLabel(self.frame_7)\n self.label_56.setGeometry(QtCore.QRect(300, 470, 66, 20))\n self.label_56.setText(_fromUtf8(\"\"))\n self.label_56.setObjectName(_fromUtf8(\"label_56\"))\n\n self.retranslateUi(Dialog)\n self.tabWidget.setCurrentIndex(1)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n self.update_values()\n self.logg_diagnostics()\n self.update_motors_status()\n self.update_mobile_base_status()\n\n def retranslateUi(self, Dialog):\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Monitoring v.1\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate(\"Dialog\", \"Communications\", None))\n self.label_7.setText(_translate(\"Dialog\", \"Component 6:\", None))\n self.label.setText(_translate(\"Dialog\", \"Component 1:\", None))\n self.label_5.setText(_translate(\"Dialog\", \"Component 4:\", None))\n self.label_6.setText(_translate(\"Dialog\", \"Component 5:\", None))\n self.label_3.setText(_translate(\"Dialog\", \"Component 2:\", None))\n self.label_4.setText(_translate(\"Dialog\", \"Component 3:\", None))\n self.label_16.setText(_translate(\"Dialog\", \"SOFTWARE NODES\", None))\n self.label_24.setText(_translate(\"Dialog\", \"Torso_laser:\", None))\n self.label_26.setText(_translate(\"Dialog\", \"Bottom_laser:\", None))\n self.label_17.setText(_translate(\"Dialog\", \"SENSORS\", None))\n self.label_36.setText(_translate(\"Dialog\", \"Kinnect_visual:\", None))\n self.label_38.setText(_translate(\"Dialog\", \"Kinnect_audio:\", None))\n self.label_32.setText(_translate(\"Dialog\", \"Battery 1:\", None))\n self.label_33.setText(_translate(\"Dialog\", \"Battery 4:\", None))\n self.label_40.setText(_translate(\"Dialog\", \"Battery 2:\", None))\n self.label_41.setText(_translate(\"Dialog\", \"Battery 3:\", None))\n self.label_42.setText(_translate(\"Dialog\", \"BATTERIES\", None))\n self.label_44.setText(_translate(\"Dialog\", \"Left hand:\", None))\n self.label_45.setText(_translate(\"Dialog\", \"Right hand:\", None))\n self.label_47.setText(_translate(\"Dialog\", \"ARM MOTORS\", None))\n self.label_53.setText(_translate(\"Dialog\", \"L1:\", None))\n self.label_55.setText(_translate(\"Dialog\", \"L2:\", None))\n self.label_68.setText(_translate(\"Dialog\", \"R2:\", None))\n self.label_70.setText(_translate(\"Dialog\", \"R3:\", None))\n self.label_72.setText(_translate(\"Dialog\", \"R4:\", None))\n self.label_74.setText(_translate(\"Dialog\", \"R5:\", None))\n self.label_76.setText(_translate(\"Dialog\", \"R6:\", None))\n self.label_78.setText(_translate(\"Dialog\", \"R7:\", None))\n self.label_59.setText(_translate(\"Dialog\", \"L3:\", None))\n self.label_63.setText(_translate(\"Dialog\", \"L4:\", None))\n self.label_66.setText(_translate(\"Dialog\", \"L5:\", None))\n self.label_84.setText(_translate(\"Dialog\", \"L6:\", None))\n self.label_86.setText(_translate(\"Dialog\", \"L7:\", None))\n self.label_88.setText(_translate(\"Dialog\", \"R1:\", None))\n self.label_49.setText(_translate(\"Dialog\", \"M1:\", None))\n self.label_50.setText(_translate(\"Dialog\", \"M2:\", None))\n self.label_52.setText(_translate(\"Dialog\", \"MOBILE BASE MOTORS\", None))\n self.label_80.setText(_translate(\"Dialog\", \"M3:\", None))\n self.label_82.setText(_translate(\"Dialog\", \"M4:\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate(\"Dialog\", \"Nodes\", None))\n self.label_13.setText(_translate(\"Dialog\", \"Communications control\", None))\n self.radioButton.setText(_translate(\"Dialog\", \"/scan\", None))\n self.radioButton_2.setText(_translate(\"Dialog\", \"/base_motors\", None))\n self.radioButton_3.setText(_translate(\"Dialog\", \"/hand_motors\", None))\n self.radioButton_4.setText(_translate(\"Dialog\", \"/diagnostics\", None))\n self.radioButton_5.setText(_translate(\"Dialog\", \"/geometry\", None))\n self.checkBox.setText(_translate(\"Dialog\", \"Component 1\", None))\n self.checkBox_2.setText(_translate(\"Dialog\", \"Component 2\", None))\n self.checkBox_3.setText(_translate(\"Dialog\", \"Component 3\", None))\n self.checkBox_4.setText(_translate(\"Dialog\", \"Component 4\", None))\n self.pushButton.setText(_translate(\"Dialog\", \"Re-initialize\", None))\n self.checkBox_5.setText(_translate(\"Dialog\", \"Component 5\", None))\n self.label_14.setText(_translate(\"Dialog\", \"Nodes control\", None))\n\n def update_values(self):\n self.thread = slave1()\n # add is a slot function\n QtCore.QObject.connect(self.thread, QtCore.SIGNAL(\"update(QString)\"), self.displaylabels)\n self.thread.start()\n\n def update_motors_status(self):\n self.motors_thread = slave2()\n QtCore.QObject.connect(self.motors_thread, QtCore.SIGNAL(\"update(QString)\"), self.displayMotorsStatus)\n self.motors_thread.start()\n\n def update_mobile_base_status(self):\n self.mobile_thread = slave3()\n QtCore.QObject.connect(self.mobile_thread, QtCore.SIGNAL(\"update(QString)\"), self.displayMobileBaseStatus)\n self.mobile_thread.start()\n\n def logg_diagnostics(self):\n self.log = slave4()\n QtCore.QObject.connect(self.log, QtCore.SIGNAL(\"update(QString)\"), self.displaylogg_diagnostics)\n self.log.start()\n\n def gomaster(self):\n os.system(\"roscore\")\n\n def displayMobileBaseStatus(self):\n motor_name = rospy.get_param(\"MotorName\")\n motor_status = rospy.get_param(\"MotorStatus\")\n newStatus = int(motor_status)\n\n if motor_name == \"Motor1\":\n if newStatus == 0:\n self.label_49.setText(\"M1\")\n self.label_48.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_49.setText(\"M1\")\n self.label_48.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_49.setText(\"M1\")\n self.label_48.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_49.setText(\"M1\")\n self.label_48.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"Motor2\":\n if newStatus == 0:\n self.label_50.setText(\"M2\")\n self.label_51.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_50.setText(\"M2\")\n self.label_51.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_50.setText(\"M2\")\n self.label_51.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_50.setText(\"M2\")\n self.label_51.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"Motor3\":\n if newStatus == 0:\n self.label_80.setText(\"M3\")\n self.label_79.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_80.setText(\"M3\")\n self.label_79.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_80.setText(\"M3\")\n self.label_79.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_80.setText(\"M3\")\n self.label_79.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"Motor4\":\n if newStatus == 0:\n self.label_82.setText(\"M4\")\n self.label_81.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_82.setText(\"M4\")\n self.label_81.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_82.setText(\"M4\")\n self.label_81.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_82.setText(\"M4\")\n self.label_81.setStyleSheet(\"background-color:blue;\")\n\n def displaylogg_diagnostics(self):\n # please make sure that the diagnostic_agg node is running\n\n base_motor_name = rospy.get_param('MotorName')\n base_motor_status = rospy.get_param('MotorStatus')\n\n hand_motors_name = rospy.get_param('motorsName')\n hand_motors_status = rospy.get_param('motorStatus')\n\n name = rospy.get_param(\"component_name\")\n status = rospy.get_param(\"status\")\n\n output1 = \"{},{}\".format(base_motor_name, base_motor_status)\n output2 = \"{},{}\".format(hand_motors_name, hand_motors_status)\n output3 = \"{},{}\".format(name, status)\n\n if self.radioButton_2.isChecked():\n self.listWidget.addItem(output1)\n self.listWidget.scrollToBottom()\n if self.radioButton_3.isChecked():\n self.listWidget.addItem(output2)\n self.listWidget.scrollToBottom()\n if self.radioButton_4.isChecked():\n self.listWidget.addItem(output3)\n self.listWidget.scrollToBottom()\n\n def displayMotorsStatus(self):\n motor_name = rospy.get_param(\"motorsName\")\n motor_status = rospy.get_param(\"motorStatus\")\n newStatus = int(motor_status)\n\n if motor_name == \"L1\":\n if newStatus == 0:\n self.label_53.setText(\"L1\")\n self.label_43.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_53.setText(\"L1\")\n self.label_43.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_53.setText(\"L1\")\n self.label_43.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_53.setText(\"L1\")\n self.label_43.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L2\":\n if newStatus == 0:\n self.label_55.setText(\"L2\")\n self.label_54.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_55.setText(\"L2\")\n self.label_54.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_55.setText(\"L2\")\n self.label_54.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_55.setText(\"L2\")\n self.label_54.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L3\":\n if newStatus == 0:\n self.label_59.setText(\"L3\")\n self.label_56.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_59.setText(\"L3\")\n self.label_56.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_59.setText(\"L3\")\n self.label_56.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_59.setText(\"L3\")\n self.label_56.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L4\":\n if newStatus == 0:\n self.label_63.setText(\"L4\")\n self.label_58.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_63.setText(\"L4\")\n self.label_58.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_63.setText(\"L4\")\n self.label_58.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_63.setText(\"L4\")\n self.label_58.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L5\":\n if newStatus == 0:\n self.label_66.setText(\"L5\")\n self.label_18.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_66.setText(\"L5\")\n self.label_18.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_66.setText(\"L5\")\n self.label_18.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_66.setText(\"L5\")\n self.label_18.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L6\":\n if newStatus == 0:\n self.label_84.setText(\"L6\")\n self.label_62.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_84.setText(\"L6\")\n self.label_63.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_84.setText(\"L6\")\n self.label_62.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_84.setText(\"L6\")\n self.label_62.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"L7\":\n if newStatus == 0:\n self.label_86.setText(\"L7\")\n self.label_64.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_86.setText(\"L7\")\n self.label_64.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_86.setText(\"L7\")\n self.label_64.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_86.setText(\"L7\")\n self.label_64.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R1\":\n if newStatus == 0:\n self.label_88.setText(\"R1\")\n self.label_46.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_88.setText(\"R1\")\n self.label_46.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_88.setText(\"R1\")\n self.label_46.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_88.setText(\"R1\")\n self.label_46.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R2\":\n if newStatus == 0:\n self.label_68.setText(\"R2\")\n self.label_67.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_68.setText(\"R2\")\n self.label_67.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_68.setText(\"R2\")\n self.label_67.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_68.setText(\"R2\")\n self.label_67.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R3\":\n if newStatus == 0:\n self.label_70.setText(\"R3\")\n self.label_69.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_70.setText(\"R3\")\n self.label_69.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_70.setText(\"R3\")\n self.label_69.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_70.setText(\"R3\")\n self.label_69.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R4\":\n if newStatus == 0:\n self.label_72.setText(\"R4\")\n self.label_71.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_72.setText(\"R4\")\n self.label_71.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_72.setText(\"R4\")\n self.label_71.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_72.setText(\"R4\")\n self.label_71.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R5\":\n if newStatus == 0:\n self.label_74.setText(\"R5\")\n self.label_73.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_74.setText(\"R5\")\n self.label_73.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_74.setText(\"R5\")\n self.label_73.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_74.setText(\"R5\")\n self.label_73.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R6\":\n if newStatus == 0:\n self.label_76.setText(\"R6\")\n self.label_75.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_76.setText(\"R6\")\n self.label_75.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_76.setText(\"R6\")\n self.label_75.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_76.setText(\"R6\")\n self.label_75.setStyleSheet(\"background-color:blue;\")\n\n if motor_name == \"R7\":\n if newStatus == 0:\n self.label_78.setText(\"R7\")\n self.label_77.setStyleSheet(\"background-color:green;\")\n if newStatus == 1:\n self.label_78.setText(\"R7\")\n self.label_77.setStyleSheet(\"background-color:yellow;\")\n if newStatus == 2:\n self.label_78.setText(\"R7\")\n self.label_77.setStyleSheet(\"background-color:red;\")\n if newStatus == 3:\n self.label_78.setText(\"R7\")\n self.label_77.setStyleSheet(\"background-color:blue;\")\n\n # @staticmethod\n def displaylabels(self):\n # name = key\n # status = val\n name = rospy.get_param(\"component_name\")\n status = rospy.get_param(\"status\")\n new_status = int(status)\n\n if name == \"component1\":\n if new_status == 0:\n self.label.setText(\"component1\")\n self.label_2.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label.setText(\"component1\")\n self.label_2.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label.setText(\"component1\")\n self.label_2.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label.setText(\"component1\")\n self.label_2.setStyleSheet(\"background-color:blue;\")\n\n if name == \"component2\":\n if new_status == 0:\n self.label_3.setText(\"component2\")\n self.label_8.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label_3.setText(\"component2\")\n self.label_8.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label_3.setText(\"component2\")\n self.label_8.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label_3.setText(\"component2\")\n self.label_8.setStyleSheet(\"background-color:blue;\")\n\n if name == \"component3\":\n if new_status == 0:\n self.label_4.setText(\"component3\")\n self.label_9.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label_4.setText(\"component3\")\n self.label_9.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label_4.setText(\"component3\")\n self.label_9.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label_4.setText(\"component3\")\n self.label_9.setStyleSheet(\"background-color:blue;\")\n\n if name == \"component4\":\n if new_status == 0:\n self.label_5.setText(\"component4\")\n self.label_10.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label_5.setText(\"component4\")\n self.label_10.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label_5.setText(\"component4\")\n self.label_10.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label_5.setText(\"component4\")\n self.label_10.setStyleSheet(\"background-color:blue;\")\n\n if name == \"component5\":\n if new_status == 0:\n self.label_6.setText(\"component5\")\n self.label_11.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label_6.setText(\"component5\")\n self.label_11.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label_6.setText(\"component5\")\n self.label_11.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label_6.setText(\"component5\")\n self.label_11.setStyleSheet(\"background-color:blue;\")\n\n if name == \"component6\":\n if new_status == 0:\n self.label_7.setText(\"component6\")\n self.label_12.setStyleSheet(\"background-color:green;\")\n if new_status == 1:\n self.label_7.setText(\"component6\")\n self.label_12.setStyleSheet(\"background-color:yellow;\")\n if new_status == 2:\n self.label_7.setText(\"component6\")\n self.label_12.setStyleSheet(\"background-color:red;\")\n if new_status == 3:\n self.label_7.setText(\"component6\")\n self.label_12.setStyleSheet(\"background-color:blue;\")\n\n def main(self):\n app = QtGui.QApplication(sys.argv)\n app.connect(app, SIGNAL(\"lastWindowClosed()\"), app, SLOT(\"quit()\"))\n Form = QtGui.QWidget()\n ui = Ui_Dialog()\n ui.setupUi(Form)\n Form.show()\n sys.exit(app.exec_())\n\n\nclass slave1(QtCore.QThread):\n def __init__(self):\n QtCore.QThread.__init__(self)\n\n def __del__(self):\n self.wait()\n\n def run(self):\n while True:\n time.sleep(1)\n self.emit(QtCore.SIGNAL(\"update(QString)\"), \"\")\n\n\nclass slave2(QtCore.QThread):\n def __init__(self):\n QtCore.QThread.__init__(self)\n\n def __del__(self):\n self.wait()\n\n def run(self):\n while True:\n time.sleep(1)\n self.emit(QtCore.SIGNAL(\"update(QString)\"), \"\")\n\n\nclass slave3(QtCore.QThread):\n def __init__(self):\n QtCore.QThread.__init__(self)\n\n def __del__(self):\n self.wait()\n\n def run(self):\n while True:\n time.sleep(1)\n self.emit(QtCore.SIGNAL(\"update(QString)\"), \"\")\n\n\nclass slave4(QtCore.QThread):\n def __init__(self):\n QtCore.QThread.__init__(self)\n\n def __del__(self):\n self.wait()\n\n def run(self):\n while True:\n time.sleep(1)\n self.emit(QtCore.SIGNAL(\"update(QString)\"), \"\")\n","sub_path":"monitoring_dashboard/scripts/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":46756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"344943055","text":"import unittest\nimport random\nimport numpy as np\n\ndef merge(arr1: list, arr2: list) -> list:\n \"\"\"Merge two lists which are each sorted.\n\n :param arr1: Sorted list\n :type arr1: list\n :param arr2: Sorted list\n :type arr2: list\n :return: Merge of arr1 and arr2 in sorted order\n :rtype: list\n \"\"\"\n\n p1 = p2 = 0\n n = len(arr1)\n m = len(arr2)\n\n merged_arr = []\n\n while p1 < n and p2 < m:\n\n v1 = arr1[p1]\n v2 = arr2[p2]\n\n if v1 < v2:\n merged_arr.append(v1)\n p1 += 1\n if v2 < v1:\n merged_arr.append(v2)\n p2 += 1\n if v1 == v2:\n merged_arr.append(v1)\n merged_arr.append(v2)\n p1 += 1\n p2 += 1\n \n while p1 < n:\n v1 = arr1[p1]\n merged_arr.append(v1)\n p1 += 1\n \n while p2 < m:\n v2 = arr2[p2]\n merged_arr.append(v2)\n p2 += 1\n \n return merged_arr\n\ndef merge_sort(arr1: list) -> list:\n \"\"\"Apply the merge routine to recursively\n merge sort an array.\n\n :param arr1: Array to be sorted\n :type arr1: list\n :return: Sorted array\n :rtype: list\n \"\"\"\n \n if len(arr1) == 1:\n return arr1\n \n l = 0\n h = len(arr1)\n m = (l + h) // 2\n\n left_arr = merge_sort(arr1[:m])\n right_arr = merge_sort(arr1[m:])\n\n return merge(left_arr, right_arr)\n\nclass TestSelection(unittest.TestCase):\n\n def test_merge(self):\n arr1 = sorted(list(np.random.randint(0, 100, size=(10))))\n arr2 = sorted(list(np.random.randint(0, 100, size=(15))))\n\n merged_arr = merge(arr1, arr2)\n\n self.assertEqual(merged_arr, sorted(arr1 + arr2))\n \n def test_mergesort(self):\n arr1 = list(np.random.randint(0, 100, size=(103)))\n\n ms_array = merge_sort(arr1)\n\n self.assertEqual(ms_array, sorted(arr1))\n\nunittest.main()","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"266303240","text":"#!/usr/bin/python3\n# filename:server.py\n\nimport socket\nimport sys\n\nserversocket = socket.socket(\n socket.AF_INET, socket.SOCK_STREAM) \nhost = socket.gethostname()\nip = '127.0.0.1'\nport = 8888\nserversocket.bind((ip, port))\nserversocket.listen(5)\n\nwhile True:\n clientsocket,addr = serversocket.accept() \n\n print(\"Addredd: %s\" % str(addr))\n \n # send \n with open('../MyProject/Saved/Test.json', 'rb') as fileHandle:\n clientsocket.send(fileHandle.read())\n clientsocket.close()","sub_path":"Server/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"67924418","text":"\nimport pandas as pd\nfrom IPython.core.display import Image\nimport requests\n\nwith open (\"../data/google_api_key.txt\", \"r\") as f:\n google_api_key=f.read()\n \nSTATIONS = pd.read_pickle('../data/HYDAT_STATIONS')\nLEVELS = pd.read_pickle('../data/HYDAT_LEVELS')\nFLOWS = pd.read_pickle('../data/HYDAT_FLOWS')\n\n\ndef mapStations(stationList, zoom=8):\n \"\"\"Return a google static map showing the location of flow and level stations.\n \n Globals:\n STATIONS: Pandas dataframe with HYDAT station data.\n \n Args:\n stationList (str): List of station codes.\n zoom (int): zoom level of the resulting map.\n \n Returns:\n Image object containing the static map. Stations are displayed as:\n red: flow station\n green: level station\n yellow: flow and level\n \n \"\"\"\n locs = [\"{0},{1}\".format(STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) \\\n for s in stationList]\n flows = [s for s in stationList if STATIONS.loc[s,'Flow'] == True]\n levels = [s for s in stationList if STATIONS.loc[s,'Level'] == True]\n bSet = set(levels).intersection(set(flows)) \n google_maps_url = \\\n \"https://maps.googleapis.com/maps/api/staticmap?\" + \\\n f\"key={google_api_key}\" + \\\n \"&size=640x400\" + \\\n f\"&zoom={zoom}\" + \\\n \"&maptype=terrain\" + \\\n \"&markers=color:red%7Csize:mid%7Clabel:F%7C\" + \"|\".join([\"{0},{1}\".format(\n STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in set(flows).difference(bSet)]) + \\\n \"&markers=color:green%7Csize:mid%7Clabel:L%7C\" +\"|\".join([\"{0},{1}\".format(\n STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in set(levels).difference(bSet)]) + \\\n \"&markers=color:yellow%7Csize:mid%7Clabel:B%7C\" + \"|\".join([\"{0},{1}\".format(\n STATIONS.loc[s,'LATITUDE'], STATIONS.loc[s,'LONGITUDE']) for s in bSet])\n return Image(requests.get(google_maps_url).content)\n\ndisplay(mapStations(STATIONS.index))\n","sub_path":"notebooks/mycode/mapStations.py","file_name":"mapStations.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"305046372","text":"from django.urls import include, path\nfrom rest_framework.routers import DefaultRouter\nfrom . import views\n\n\nrouter = DefaultRouter()\nrouter.register('viewset', views.HelloViewSet, basename='viewset')\n\nurlpatterns = [\n path('', views.home, name='eds_home'),\n path('', include(router.urls)),\n path('weather/', views.weather, name=\"weather\"),\n path('pets/', views.pet_form_choice, name='pets'),\n path('pets/adopt/', views.render_animal_form, name='adopt'),\n path('api/', views.HelloAPIView.as_view(), name='api'),\n ]\n","sub_path":"LiveProject-Python/AppBuilder9000/ZPYLP0612/EdsApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"307437858","text":"import time\nimport pandas as pd\nimport numpy as np\nfrom miu2_iterative_deepening import iterative_deepening\n\ndef run_search(goal):\n start_time = time.time()\n goal_path, extend_count = iterative_deepening(goal)\n end_time = time.time()\n time_taken = end_time - start_time\n return goal_path, time_taken, extend_count\n\ndef create_record(goal, goal_path, time_taken, extend_count):\n algorithm_result = { \"Goal\" : goal, \"Path\" : goal_path, \"Depth\" : len(goal_path), \"Time Taken\" : time_taken, \"Extend Count\" : extend_count}\n return algorithm_result\n\ndef iterate_through_goals(list_of_goals):\n results = []\n for goal in list_of_goals:\n goal_path, time_taken, extend_count = run_search(goal)\n results.append(create_record(goal, goal_path, time_taken, extend_count))\n results_dataframe = pd.DataFrame(results)\n return results_dataframe","sub_path":"practical1_miu_part5/miu2_main.py","file_name":"miu2_main.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"153444011","text":"# -*- coding:utf-8 -*-\n__author__ = 'walkskyer'\n\"\"\"\n\"\"\"\nimport wx\nimport wx.lib.newevent\n\n#刷新纸牌\n(CardRePaint, EVT_CARD_REPAINT) = wx.lib.newevent.NewEvent()\n#重设纸牌位置\n(CardChangePos, EVT_CARD_CHANGEPOS) = wx.lib.newevent.NewEvent()\n\n\nclass MCard(wx.StaticText):\n def __init__(self, *args, **kwargs):\n wx.StaticText.__init__(self, *args, **kwargs)\n self.setBitmap('31.jpg')\n self.SetSize((447, 681))\n\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.Bind(wx.EVT_LEFT_UP, self.OnClick)\n self.Bind(EVT_CARD_CHANGEPOS, self.ChangePos)\n\n self.is_pickup = False\n self.pos = self.GetPosition()\n if kwargs.has_key('order_index'):\n self.order_index = kwargs['order_index']\n\n def setBitmap(self, filename):\n self.bmp = wx.Image(filename, wx.BITMAP_TYPE_JPEG).ConvertToBitmap()\n\n def OnPaint(self, *args, **kwargs):\n dc = wx.PaintDC(self)\n dc.DrawBitmap(self.bmp, 0,0, True)\n\n def ChangePos(self, evt):\n self.SetPosition(self.pos)\n\n\n def OnClick(self, evt):\n self.is_pickup = not self.is_pickup\n\n #点击以后应该出发EVT_PAINT事件让所有card都执行刷新一次\n pos = self.GetPosition()\n if self.is_pickup:\n self.pos=(pos[0], pos[1]-20)\n else:\n self.pos=(pos[0], pos[1]+20)\n\n evt = CardRePaint()\n wx.PostEvent(self.GetParent(), evt)\n\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n self.Center()\n self.cards = []\n self.initCard()\n self.Bind(EVT_CARD_REPAINT,self.repaint_cards)\n\n def initCard(self):\n posX=0\n for i in xrange(1,6):\n self.cards.append(MCard(self, wx.ID_ANY, pos=(posX+(100*i), 50)))\n\n def repaint_cards(self, evt):\n for card in self.cards:\n evt = CardChangePos()\n wx.PostEvent(card, evt)\n\nif __name__ == \"__main__\":\n app = wx.App(False)\n frame = MyFrame(None, size=(2000, 900))\n frame.Show()\n app.MainLoop()","sub_path":"wxPython/mytest/panel_paint/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"209969407","text":"import web \r\nimport csv\r\n\r\nrender = web.template.render('templates/', base = 'base')\r\n\r\nurls = ('/', 'index' )\r\napp = web.application(urls, globals())\r\n\r\n\r\ndatos=[]\r\nwith open('viviendaa.csv','r') as file:\r\n data = csv.reader(file,delimiter=\",\")\r\n for row in data:\r\n \r\n datos.append(row)\r\n\r\n\r\nclass index: \r\n def GET(self): \r\n dato=datos\r\n return render.index(dato) \r\n\r\n\r\nif __name__==\"__main__\": \r\n app.run()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"521685466","text":"#!/usr/bin/env python\n#blender is at /usr/bin/blender\n\n#based on 'export-sprites.py' and 'glsprite.py' from TCHOW Rainbow; code used is released into the public domain.\n\n#Note: Script meant to be executed from within blender, as per:\n#blender --background --python export-layer.py\n\n#reads 'robot.blend' and writes 'robot.blob' from the first layer.\n\nimport sys\n\nimport bpy\nimport struct\n\nprint(sys.argv)\n\nargs = None\nfor arg in sys.argv:\n\tif arg == '--':\n\t\targs = []\n\telif args != None:\n\t\targs.append(arg)\n\nif args == None: args = []\n\nif len(args) != 2:\n\tprint(\"Usage:\\n\\tblender --background --python export-layer.py -- \")\n\texit(1)\n\ninfile = args[0]\noutfile = args[1]\n\nprint(\"Reading '\" + infile + \"'\")\nbpy.ops.wm.open_mainfile(filepath=infile)\n\n#data contains vertex, normal, and vertex color data from the meshes:\ndata_vertices = b''\ndata_normals = b''\ndata_colors = b''\n\nvertex_count = 0\nfor obj in bpy.data.objects:\n\tif obj.type != 'MESH': continue;\n\tif obj.layers[0] == False: continue\n\tprint(\"Writing '\" + obj.name + \"'...\")\n\t#bpy.ops.object.mode_set(mode='OBJECT') #get out of edit mode (just in case)\n\n\tobj.data = obj.data.copy() #make mesh single user, just in case it is shared with another object the script needs to write later.\n\n\t#make sure object is on a visible layer:\n\tbpy.context.scene.layers = obj.layers\n\t#select the object and make it the active object:\n\tbpy.ops.object.select_all(action='DESELECT')\n\tobj.select = True\n\tbpy.context.scene.objects.active = obj\n\n\t#subdivide object's mesh into triangles:\n\tbpy.ops.object.mode_set(mode='EDIT')\n\tbpy.ops.mesh.select_all(action='SELECT')\n\tbpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\n\t#compute normals (respecting face smoothing):\n\tmesh = obj.data\n\tmesh.calc_normals_split()\n\n\tmatrix = obj.matrix_world\n\tnormal_matrix = matrix.to_3x3()\n\tnormal_matrix.transpose()\n\tnormal_matrix.invert()\n\n\tcolors = mesh.vertex_colors.active.data\n\n\t#write the mesh:\n\tfor poly in mesh.polygons:\n\t\tassert(len(poly.loop_indices) == 3)\n\t\tfor i in range(0,3):\n\t\t\tassert(mesh.loops[poly.loop_indices[i]].vertex_index == poly.vertices[i])\n\t\t\tloop = mesh.loops[poly.loop_indices[i]]\n\t\t\tcolor = colors[poly.loop_indices[i]].color\n\t\t\tvertex = matrix * mesh.vertices[loop.vertex_index].co\n\t\t\tnormal = normal_matrix * loop.normal\n\t\t\tfor x in vertex:\n\t\t\t\tdata_vertices += struct.pack('f', x)\n\t\t\tfor x in normal:\n\t\t\t\tdata_normals += struct.pack('f', x)\n\t\t\tdata_colors += struct.pack('BBBB',\n\t\t\t\tint(color.r * 255),\n\t\t\t\tint(color.g * 255),\n\t\t\t\tint(color.b * 255),\n\t\t\t\t255\n\t\t\t)\n\n\tvertex_count += len(mesh.polygons) * 3\n\n#write the data chunk and index chunk to an output blob:\nblob = open(outfile, 'wb')\n#first chunk: the data\nblob.write(data_vertices)\nblob.write(data_normals)\nblob.write(data_colors)\n\nprint(\"Wrote \" + str(blob.tell()) + \" bytes to '\" + outfile + \"'.\")\n","sub_path":"dist/export-layer.py","file_name":"export-layer.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"576077111","text":"# K近邻算法,KNN\r\n# 求未知样本与已知样本集中的最近距离,距离为欧式距离\r\n# K近邻算法需要标准化处理\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.datasets import fetch_20newsgroups\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.feature_extraction import DictVectorizer\r\nfrom sklearn.tree import DecisionTreeClassifier, export_graphviz\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n\r\ndef knncls():\r\n \"\"\"\r\n K近邻预测用户签到位置\r\n 优点:简单,无需估计参数,无需训练\r\n 缺点:样本计算量大,必须指定K值\r\n 使用场景:几千-几万样本量\r\n :return: None\r\n \"\"\"\r\n data = pd.read_csv(\"./data/FBlocation/train.csv\")\r\n # print(data.head())\r\n\r\n # 缩小数据\r\n data = data.query(\"x > 1.0 & x < 1.25 & y > 2.5 & y < 2.75\")\r\n\r\n # 时间处理,将时间戳改为时间日期\r\n time_value = pd.to_datetime(data['time'], unit='s')\r\n # print(time_value)\r\n time_value = pd.DatetimeIndex(time_value) # 时间日期变为字典格式\r\n\r\n # 增加特征:日、时、星期,其中年月都是一样的,而分秒等数据认为对签到位置无影响\r\n data = data.copy() # 避免出现SettingWithCopyWarning,可以不用loc\r\n data['day'] = time_value.day\r\n data['hour'] = time_value.hour\r\n data['weekday'] = time_value.weekday\r\n\r\n # 删除时间戳特征的列\r\n data = data.drop(['time'], axis=1)\r\n # print(data.head())\r\n\r\n # 删除签到数量过少的地点\r\n place_count = data.groupby(\"place_id\")['row_id'].count() # 根据地点id分类,统计入住人数\r\n tf = place_count[place_count.values > 10] # 删选签到人数大于10的地点,tf的格式时index是place_id,values是签到人数\r\n data = data[data['place_id'].isin(tf.index)] # 这要这些大于10的地点的id\r\n # print(data)\r\n\r\n # 取出特征值和目标值\r\n y = data['place_id']\r\n x = data.drop(['place_id', 'row_id'], axis=1)\r\n\r\n # 进行数据分割,训练集为25%\r\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\r\n\r\n # 特征工程,标准化\r\n std = StandardScaler()\r\n x_train = std.fit_transform(x_train) # 只对特征值做标准化,目标值只是一列不需要标准化\r\n x_test = std.transform(x_test) # 不需要再fit了,fit只是为了求平均值,方差等等用的,训练集和测试集来源一样,这些值也不会差太多\r\n\r\n # KNN算法\r\n knn = KNeighborsClassifier() # 选择最近的n个\r\n # knn.fit(x_train, y_train)\r\n # y_predict = knn.predict(x_test)\r\n # print(\"预测值\", y_predict)\r\n # print(\"准确l率\", knn.score(x_test, y_test)) # 其实直接用时间戳,不分日、小时、星期结果更高\r\n\r\n # 网格搜素+交叉验证\r\n param = {\"n_neighbors\": [3, 5, 10]}\r\n gc = GridSearchCV(knn, param_grid=param, cv=5) # 5折交叉验证\r\n gc.fit(x_train, y_train)\r\n print(\"测试集上的准确率:\", gc.score(x_test, y_test))\r\n print(\"最优结果:\", gc.best_score_)\r\n print(\"最好的模型:\", gc.best_estimator_)\r\n print(\"每个超参数交叉验证的结果:\", gc.cv_results_)\r\n return None\r\n\r\n\r\ndef naviebayes():\r\n \"\"\"\r\n 朴素贝叶斯进行文本分类\r\n 优点:稳,准,快,简单,缺失数据不敏感,不用调参数\r\n 缺点:样本要求高,样本属性之间需要独立性\r\n 使用场景:常用于文本分类\r\n :return:None\r\n \"\"\"\r\n news = fetch_20newsgroups(subset=\"all\")\r\n # 数据分割\r\n x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25)\r\n\r\n # 对数据集进行特征抽取\r\n tf = TfidfVectorizer()\r\n x_train = tf.fit_transform(x_train)\r\n x_test = tf.transform(x_test)\r\n\r\n # 算法\r\n mlt = MultinomialNB(alpha=1.0)\r\n mlt.fit(x_train, y_train)\r\n y_predict = mlt.predict(x_test)\r\n print(\"预测值\", y_predict)\r\n print(\"准确率:\", mlt.score(x_test, y_test))\r\n print(\"精确率和召回率:\", classification_report(y_test, y_predict, target_names=news.target_names))\r\n return None\r\n\r\n\r\ndef decison():\r\n \"\"\"\r\n 决策树预测titanic生存概率\r\n 优点:可视化、不需要归一化\r\n 缺点:过拟合\r\n 优化: 随机森林\r\n :return: None\r\n \"\"\"\r\n titanic = pd.read_csv(\"./data/titanic/train.csv\")\r\n\r\n # 找到特征值和目标值\r\n x = titanic[['Age', 'Pclass', 'Sex', 'Embarked']]\r\n y = titanic['Survived']\r\n # 空缺值处理\r\n x = x.copy() # 避免SettingWithCopyWarning\r\n x['Age'].fillna(x['Age'].mean(), inplace=True)\r\n x['Embarked'].fillna(x['Embarked'].mode()[0], inplace=True)\r\n\r\n # 数据集分割\r\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\r\n\r\n # 特征工程\r\n dict = DictVectorizer(sparse=False)\r\n x_train = dict.fit_transform(x_train.to_dict(orient=\"records\")) # 按行进行转换成字典,每个字典再组成列表\r\n x_test = dict.transform(x_test.to_dict(orient=\"records\"))\r\n print(dict.get_feature_names())\r\n\r\n # 决策树算法\r\n # dec = DecisionTreeClassifier(max_depth=5)\r\n # 默认是使用基尼系数,若乡选择最大信息增益的熵criterion=\"entropy\";决策树分层数为max_depth,默认为train集100%预测率的分层数\r\n # dec.fit(x_train, y_train)\r\n # print(\"准确率:\", dec.score(x_test, y_test))\r\n\r\n # 导出决策树结构\r\n # export_graphviz(dec, out_file=\"./titanic_tree.dot\", feature_names=['年龄', 'C地登船', 'Q地登船', 'S地登船', '船舱等级', '女性', '男性'])\r\n # 记事本打开dot,在node属性中空格添加fontname=\"FangSong\",使其支持中文\r\n # cmd中输入dot -Tpng titanic_tree.dot -o titanic_tree.png转换格式\r\n\r\n # 随机森林算法\r\n rf = RandomForestClassifier()\r\n param = {\"n_estimators\": [120, 200, 300, 500, 800, 1200], \"max_depth\": [5, 8, 15, 25, 30]}\r\n # 网格搜索与交叉验证\r\n gc = GridSearchCV(rf, param_grid=param, cv=3)\r\n gc.fit(x_train, y_train)\r\n print(\"准确率:\", gc.score(x_test, y_test))\r\n print(\"最佳模型:\", gc.best_params_)\r\n # 随机森林不能可视\r\n # 决策树和随机森林还有min_sample_split和min_sample_leaf两个参数,\r\n # min_sample_split小于这个数的节点将不会再开支分裂,\r\n # min_sample_leaf小于这个数的节点将被剪枝\r\n return None\r\n\r\n\r\nif __name__ == '__main__':\r\n decison()\r\n","sub_path":"04classification.py","file_name":"04classification.py","file_ext":"py","file_size_in_byte":6768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"630003878","text":"# Python Version of WordNetExtractor.java\nimport os\nimport sys\n\nsys.path.append('..')\n\nfrom collections import defaultdict\nimport numpy as np\nimport codecs\n\n#exWordNet\nfrom util.exWordNet import exWordNet\nfrom config import *\n\nclass ExtractorError(Exception):\n \"\"\"An exception class for wordnet-related errors.\"\"\"\n\nwn = exWordNet('./')\n\ndef load_vector_line(file_name):\n model = {}\n f = open(file_name, 'r')\n for line in f.readlines():\n name = line.strip().split(' ')[0]\n vector_line = line.strip().split(' ')[1:]\n vector_line = ' '.join(vector_line)\n model[name] = vector_line\n return model\n\nclass ForwardWordNetExtractor:\n def __init__(self, root, lang):\n self._normalize = True\n if lang in wn.langs():\n self.lang = lang\n else:\n raise ExtractorError(\"language: '%s' is not supported, try another language\" % lang)\n self._root= root\n self.folder = '%s/%s' % (self._root, self.lang)\n # make directory for the language\n try:\n os.mkdir(self.folder)\n except:\n print('Folder %s already exists' % self.folder)\n # file name for synset vector\n self.file_name = '%s/words.txt' % self._root\n #initialize\n self.WordIndex = {}\n self.SynsetIndex = {}\n self.pos_list = ['a', 'r', 'n', 'v']\n self.pointer_map = {\"@\":\"hypernym\", \"&\":\"similar\", \"$\":\"verbGroup\", \"!\":\"antonym\"}\n\n def get_normalized_lemma_count(self):\n # self.total_count = 0\n self.countW = defaultdict(dict)\n self.countS = defaultdict(dict)\n for ss in wn.all_synsets():\n for l in ss.lemmas(lang=lang):\n if l.count() == 0:\n count = 0.1\n else:\n count = l.count()\n self.countS[ss.name()][l.name()] = count\n self.countW[l.name()][ss.name()] = count\n for w in self.countW.keys():\n for s in self.countW[w].keys():\n counts = np.array(list(map(float,self.countW[w].values())))\n norm = np.sqrt(sum(counts*counts))\n self.countW[w][s] /= norm\n\n for s in self.countS.keys():\n for w in self.countS[s].keys():\n counts = np.array(list(map(float,self.countS[s].values())))\n norm = np.sqrt(sum(counts*counts))\n self.countS[s][w] /= norm\n\n def main(self):\n # Load vector line\n self.model = load_vector_line(self.file_name)\n ver = wn.get_version()\n print(\"RESOURCE: WN \" + str(ver) + \"\\n\")\n print(\"LANGUAGE: \"+self.lang+\"\\n\")\n print(\"VECTORS: \" + self.file_name + \"\\n\")\n print(\"TARGET: \" + self.folder + \"\\n\")\n self.extractWordsAndSynsets(self.folder + \"/words.txt\",self.folder + \"/synsets.txt\",self.folder + \"/lexemes.txt\")\n self.extractWordRelations(self.folder + \"/hypernym.txt\", '@')\n self.extractWordRelations(self.folder + \"/similar.txt\", '&')\n self.extractWordRelations(self.folder + \"/verbGroup.txt\", '$')\n self.extractWordRelations(self.folder + \"/antonym.txt\", '!')\n\n print(\"DONE\")\n\n\n def extractWordsAndSynsets(self, filenameWords, filenameSynsets, filenameLexemes):\n if self._normalize:\n self.get_normalized_lemma_count()\n #file\n fWords = codecs.open(filenameWords, 'w', 'utf-8')\n fSynsets = codecs.open(filenameSynsets, 'w', 'utf-8')\n fLexemes = codecs.open(filenameLexemes, 'w', 'utf-8')\n\n wordCounter = 0\n wordCounterAll = 0\n synsetCounter = 0\n synsetCounterAll = 0\n lexemCounter = 0\n lexemCounterAll = 0\n\n _wordCounter = {}\n _wordCounterAll = {}\n _synsetCounter = {}\n _synsetCounterAll = {}\n _lexemCounter = {}\n _lexemCounterAll = {}\n ovv = {}\n\n for pos in self.pos_list:\n _wordCounter[pos] = 0\n _wordCounterAll[pos] = 0\n _synsetCounter[pos] = 0\n _synsetCounterAll[pos] = 0\n _lexemCounter[pos] = 0\n _lexemCounterAll[pos] = 0\n ovv[pos] = []\n for synset in wn.all_synsets(pos=pos):\n synsetCounterAll += 1\n _synsetCounterAll[pos] += 1\n synsetId = synset.name()\n self.SynsetIndex[synsetId] = synsetCounterAll\n fSynsets.write('%s ' % synsetId)\n wordInSynset = 0\n for lemma in synset.lemmas():\n lexemCounterAll += 1\n _lexemCounterAll[pos] += 1\n wordId = lemma.name()\n\n if wordId in self.model.keys():\n wordInSynset += 1\n if wordId not in self.WordIndex:\n fWords.write('%s %s\\n' % (wordId, self.model[wordId]))\n wordCounter += 1\n _wordCounter[pos] += 1\n self.WordIndex[wordId] = wordCounter\n\n lexemCounter += 1\n _lexemCounter[pos] += 1\n lexemeId = '%s.%s' % (synset.name(), lemma.name())\n if self._normalize:\n cW = self.countW[lemma.name()][synset.name()]\n cS = self.countS[synset.name()][lemma.name()]\n else:\n cW = lemma.count()\n cS = lemma.count()\n\n fSynsets.write('%s,' % lexemeId)\n fLexemes.write('%d %d %f %f\\n' % (self.WordIndex[wordId], synsetCounterAll, cW, cS))\n\n else:\n if wordId not in ovv[pos]:\n ovv[pos].append(wordId)\n\n fSynsets.write('\\n')\n if wordInSynset != 0:\n synsetCounter += 1\n _synsetCounter[pos] += 1\n else:\n self.SynsetIndex[synsetId] = -1\n\n print(\"POS: %s\" % pos)\n print(\" Words: %d / %d\\n\" % (_wordCounter[pos], (_wordCounter[pos]+len(ovv[pos]))))\n print(\" Synset: %d / %d\\n\" % (_synsetCounter[pos], _synsetCounterAll[pos]))\n print(\" Lexems: %d / %d\\n\" % (_lexemCounter[pos], _lexemCounterAll[pos]))\n fWords.close()\n fSynsets.close()\n fLexemes.close()\n\n def extractWordRelations(self, filename, relation_symbol):\n affectedPOS = {}\n f = codecs.open(filename, 'w', 'utf-8')\n for pos in self.pos_list:\n for synset in wn.all_synsets(pos=pos):\n synsetId = synset.name()\n # get related words\n if relation_symbol == '!':\n targetSynsets = []\n for l in synset.lemmas():\n for a in l.antonyms():\n targetSynsets.append(a.synset())\n else:\n targetSynsets = synset._related(relation_symbol)\n\n for targetSynset in targetSynsets:\n pos = targetSynset.pos()\n targetSynsetId = targetSynset.name()\n\n if pos in affectedPOS:\n affectedPOS[pos] += 1\n else:\n affectedPOS[pos] = 1\n\n if synsetId in self.SynsetIndex and targetSynsetId in self.SynsetIndex:\n if self.SynsetIndex[synsetId] >= 0 and self.SynsetIndex[targetSynsetId] >= 0:\n f.write('%d %d\\n' % (self.SynsetIndex[synsetId], self.SynsetIndex[targetSynsetId]))\n else:\n print(synsetId, targetSynsetId)\n f.close()\n print(\"Extracted %s: done!\\n\" % self.pointer_map[relation_symbol])\n\n for k,v in affectedPOS.items():\n print(\" %s: %d\\n\" % (k, v))\n\nif __name__ == '__main__':\n # get root\n root = sys.argv[1]\n # get languages\n langs = sys.argv[2:]\n\n for lang in langs:\n fwne = ForwardWordNetExtractor(root, lang)\n fwne.main()\n\n #List of Languages\n # ['als', 'arb', 'cat', 'cmn', 'dan', 'eng', 'eus', 'fas',\n # 'fin', 'fra', 'fre', 'glg', 'heb', 'ind', 'ita', 'jpn', 'nno',\n # 'nob', 'pol', 'por', 'spa', 'tha', 'zsm']\n","sub_path":"Extractor/fgextractor.py","file_name":"fgextractor.py","file_ext":"py","file_size_in_byte":8377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"314160011","text":"from django.urls import path, re_path\nfrom .views import case_view, task_view, result_view\n\nurlpatterns = [\n # 测试用例\n path('case_manage/', case_view.case_manage, name='case_manage'),\n path('add_case/', case_view.add_case, name='api_debug'),\n path('api_debug/', case_view.debug),\n path('save_case/', case_view.save_case),\n path('edit_case//', case_view.edit_case, name='edit'),\n path('delete_case//', case_view.delete_case, name='delete'),\n path('search_case/', case_view.search_case, name=\"search\"),\n path('get_case_info/', case_view.get_case_info, name=\"getCaseInfo\"),\n path('api_assert/', case_view.api_assert),\n path('get_cases_list/', case_view.get_cases_list),\n\n #测试计划\n path('task_manage/', task_view.task_manage),\n path('add_task/', task_view.add_task),\n path('save_task/', task_view.save_task),\n path('run_task//', task_view.run_task),\n path('edit_task//', task_view.edit_task),\n path('delete_task//', task_view.delete_task),\n path('is_task_run/', task_view.is_task_run),\n\n # 测试结果\n path('task_result_list//', result_view.task_result_list),\n path('result_detail/', result_view.result_detail),\n]","sub_path":"test_plantform/interface_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"29745624","text":"# Lesson 6, stop at dark\n# the microbit uses a photoresistor (light sensor) and when it reaches 0 brightness it stops\n# at 1 brightness it backs up, and 2/3 it drives forward\nfrom microbit import *\nimport time\n# motobit class, would be imported but having some issues.\nclass motobit:\n moto_l = 0x21\n moto_r = 0x20\n moto_on = 0x70\n \n def __init__(self, address=0x59):\n self.ADDR = address\n \n def write16(self, a, b):\n i2c.write(self.ADDR, bytes([a, b]), repeat=False)\n \n # True or False\n def enable(self, pwr):\n if pwr:\n self.write16(0x70, 1)\n else:\n self.write16(0x70, 0)\n \n # 0 for right, 1 for left, speed -127 to 127 \n def set_speed(self, motor, speed):\n motor = motor + 32\n if speed >= 0:\n self.write16(motor, 128 + speed)\n else:\n speed = speed + 127\n self.write16(motor, speed)\n # left and right speeds\n \n def drive(self, left, right):\n self.set_speed(0, right)\n self.set_speed(1, left)\n\ncar = motobit()\n# just a fancy image of a fully filled square.\nfullSquare = Image(\"88888:\"\"85558:\"\"85958:\"\"85558:\"\"88888:\")\ntoggle = True # toggle for motors, this way things that turn off the motor\n# don't mess with the buttons\nwhile True:\n # setup for brightness reading, for whatever reason doing lots of steps\n # at once was being weird.\n brightness = 1023 # inverting the light, so starting at 1023 and the subtracting the reading of brightness\n brightness = brightness - pin1.read_analog() \n sizedBrightness = int(brightness / 256) # split the brightness reading into 4 parts 0,1,2,3\n car.enable(toggle)\n if sizedBrightness == 0: # if it's too dark, the car stops.\n display.clear()\n car.enable(False)\n time.sleep(0.1)\n elif sizedBrightness == 1: # if it's pretty dark the car backs up\n display.show(Image(\"00000:\"\"00000:\"\"00900:\"\"00000:\"\"00000:\"))\n car.drive(64, 64)\n time.sleep(0.1)\n elif sizedBrightness == 2: # if it's normal lighting it drives forwards\n display.show(Image.SQUARE_SMALL)\n car.drive(-54, -54)\n time.sleep(0.1)\n elif sizedBrightness == 3: # likewise for when it's bright, just faster\n display.show(fullSquare)\n car.drive(-64, -64)\n time.sleep(0.1)\n if button_a.was_pressed():\n toggle = True\n if button_b.was_pressed():\n toggle = False\n","sub_path":"microbit-micropython/lesson6 - Stop at Dark.py","file_name":"lesson6 - Stop at Dark.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"465575913","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nimport six\nimport codecs\nimport random\nimport collections\nimport tensorflow as tf\nimport PlatformNlp.tokenization as tokenization\nfrom PlatformNlp.data.base_dataset import BaseDataset\nfrom PlatformNlp.data import register_dataset\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass PaddingInputExample(object):\n \"\"\"Fake example so the num input examples is a multiple of the batch size.\n\n When running eval/predict on the TPU, we need to pad the number of examples\n to be a multiple of the batch size, because the TPU requires a fixed batch\n size. The alternative is to drop the last batch, which is bad because it means\n the entire output data won't be generated.\n\n We use this class instead of `None` because treating `None` as padding\n battches could cause silent errors.\n \"\"\"\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n label_ids,\n input_mask,\n segment_ids,\n is_real_example=True):\n self.input_ids = input_ids\n self.label_ids = label_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.is_real_example = is_real_example\n\n\n@register_dataset(\"multi_label\")\nclass MultiLabelFixLenDataset(BaseDataset):\n \"\"\"Loader for MultiClass dDataset\"\"\"\n\n def __init__(self, args):\n self.args = args\n self.max_seq_length = 200 if not args.max_seq_length or args.max_seq_length <= 0 else args.max_seq_length\n self.num_labels = 2 if args.num_labels is None or args.num_labels <= 0 else args.num_labels\n if args.label_file is not None and os.path.exists(args.label_file):\n self.label_mapping = six.moves.cPickle.load(open(args.label_file, 'rb'))\n else:\n self.label_mapping = {}\n\n def build_dataset(self, args, tokenizer):\n set_type = args.type\n data_file = args.data_file\n label_file = args.label_file\n output_file = args.output_file\n if not os.path.exists(data_file):\n raise FileExistsError(\"{} does not exists!!!\".format(data_file))\n if os.path.exists(output_file):\n os.remove(output_file)\n all_lines = []\n with codecs.open(data_file, \"r\", 'utf-8', errors='ignore') as f:\n lines = []\n for line in f:\n line = line.strip('\\n')\n line = line.strip(\"\\r\")\n line = line.split(',')\n if len(line) < 2:\n continue\n lines.append(line)\n shuffle_index = list(range(len(lines)))\n random.shuffle(shuffle_index)\n for i in range(len(lines)):\n shuffle_i = shuffle_index[i]\n if len(lines[i]) != 2:\n continue\n line_i = [str(lines[shuffle_i][0]), str(lines[shuffle_i][1])]\n all_lines.append(line_i)\n del lines\n\n examples = []\n for (i, line) in enumerate(all_lines):\n # Only the test set has a header\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[0])\n label = tokenization.convert_to_unicode(line[1])\n if set_type.lower() == \"train\":\n labels = str(label).split(\"+\")\n for l in labels:\n if l not in self.label_mapping:\n self.label_mapping[l] = len(self.label_mapping)\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n\n if set_type.lower() != \"train\":\n if not os.path.exists(label_file):\n raise EnvironmentError(\"no labels exists !!!!!\")\n self.label_mapping = six.moves.cPickle.load(open(label_file, 'rb'))\n else:\n with open(label_file, 'wb') as f:\n six.moves.cPickle.dump(self.label_mapping, f)\n\n writer = tf.python_io.TFRecordWriter(output_file)\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = self.convert_single_example(ex_index, example, self.label_mapping, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n def create_str_feature(value):\n if isinstance(value, str):\n value = bytes(value, encoding='utf-8')\n f = tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature(feature.label_ids)\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n def builder(self, tfrecord_file, is_training, batch_size, drop_remainder, args):\n name_to_features = {\n \"input_ids\": tf.FixedLenFeature([self.max_seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([self.max_seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([self.max_seq_length], tf.int64),\n \"label_ids\": tf.FixedLenFeature([self.num_labels], tf.int64),\n \"is_real_example\": tf.FixedLenFeature([], tf.int64),\n }\n args.name_to_features = name_to_features\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n # batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(tfrecord_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n def convert_single_example(self, ex_index, example, label_mapping, tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n if isinstance(example, PaddingInputExample):\n return InputFeatures(\n input_ids=[0] * self.max_seq_length,\n input_mask=[0] * self.max_seq_length,\n segment_ids=[0] * self.max_seq_length,\n label_id=[0] * self.num_labels,\n is_real_example=False)\n\n tokens_a = tokenizer.tokenize(example.text_a)\n\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > self.max_seq_length - 2:\n tokens_a = tokens_a[0:(self.max_seq_length - 2)]\n\n tokens = []\n segment_ids = []\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n input_mask = [1] * len(input_ids)\n # Zero-pad up to the sequence length.\n while len(input_ids) < self.max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == self.max_seq_length\n assert len(input_mask) == self.max_seq_length\n assert len(segment_ids) == self.max_seq_length\n\n labels = str(example.label).split(\"+\")\n label_ids = [0] * self.num_labels\n\n for label in labels:\n label_i = int(label_mapping.get(label, 0))\n label_ids[label_i] = 1\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"label: %s (id = %s)\" % (example.label, \" \".join([str(x) for x in label_ids])))\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_ids=label_ids,\n is_real_example=True)\n return feature\n","sub_path":"src/nlp/PlatformNlp/data/multi_label_fix_len_dataset.py","file_name":"multi_label_fix_len_dataset.py","file_ext":"py","file_size_in_byte":10642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"332546457","text":"def swap(li, a, b):\n t = li[a]\n li[a] = li[b]\n li[b] = t\n\n\ndef bubble_sort(li):\n for i in range(len(li) - 1, 0, -1):\n for j in range(0, i):\n if li[j] > li[j + 1]:\n swap(li, j, j + 1)\n\n\ndef selection_sort(li):\n for i in range(0, len(li)):\n for j in range(i, len(li)):\n if li[j] < li[i]:\n swap(li, i, j)\n\n\ndef insertion_sort(li, h=1):\n for i in range(h, len(li)):\n p = li[i]\n for j in range(i - h, -1, -h):\n if li[j] > li[j + 1]:\n swap(li, j, j + 1)\n else:\n break\n\n\ndef shell_sort(li):\n h = 1\n while h < len(li) // 3: h = 3 * h + 1\n while h:\n insertion_sort(li, h)\n h = h // 3\n\n\ndef merge_sort(li):\n def merge(li_a, li_b):\n i, j = 0, 0\n merged = []\n while i < len(li_a) and j < len(li_b):\n if li_a[i] < li_b[j]:\n merged.append(li_a[i])\n i += 1\n else:\n merged.append(li_b[j])\n j += 1\n return merged + li_a[i:] + li_b[j:]\n\n if len(li) <= 1:\n return li\n else:\n mid = len(li) // 2\n return merge(merge_sort(li[:mid]), merge_sort(li[mid:]))\n\n\ndef __quick_sort(li, left, right):\n def quick_sort_once(l, r):\n p = li[l]\n pindex = l + 1\n for i in range(l + 1, r + 1):\n if li[i] < p:\n swap(li, i, pindex)\n pindex += 1\n swap(li, pindex - 1, l)\n return pindex - 1\n\n if right - left < 1:\n return\n else:\n pindex = quick_sort_once(left, right)\n __quick_sort(li, left, pindex - 1)\n __quick_sort(li, pindex + 1, right)\n\n\ndef heap_sort(li):\n def max_index(a, b, lastIndex):\n if b > lastIndex or li[a] > li[b]:\n return a\n else:\n return b\n\n def swap_if_a_lt_b(a, b):\n if li[a] > li[b]:\n return -1\n else:\n swap(li, a, b)\n return b\n\n # max heap\n def fix(i, lastIndex=len(li) - 1):\n l = 2 * i + 1\n if l > lastIndex:\n return\n r = 2 * i + 2\n m = max_index(l, r, lastIndex)\n result = swap_if_a_lt_b(i, m)\n if result > 0:\n fix(result, lastIndex)\n\n # create max heap:\n length = len(li) // 2\n for x in range(length, -1, -1):\n fix(x)\n # sort\n for j in range(len(li) - 1, -1, -1):\n swap(li, j, 0)\n fix(0, j - 1)\n\n\ndef radix_sort(li):\n bucket = []\n for i in range(0, 10):\n bucket.append([])\n temp = li\n\n def find_max(li):\n m = li[0]\n for x in li:\n if x > m: m = x\n return m\n\n def digit_count(d):\n c = 0\n while d:\n d = d // 10\n c += 1\n return c\n\n def insert(n):\n d = 10 ** (n - 1)\n for x in temp:\n bucket[(x // d) % 10].append(x)\n\n def popitem():\n nonlocal temp\n temp = []\n for x in bucket:\n while x:\n temp.append(x.pop(0))\n\n m = find_max(li)\n d = digit_count(m)\n for i in range(1, d + 1):\n insert(i)\n popitem()\n\n return temp\n\n\ndef judege(li):\n for i in range(0, len(li) - 1):\n if li[i] > li[i + 1]: return False\n return True\n\n\nif __name__ == '__main__':\n import random\n\n li = []\n for i in range(0, 1000000):\n li.append(random.randint(1000, 1000000))\n __quick_sort(li, 0, len(li) - 1)\n print(judege(li))\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":3525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"575276865","text":"# modified from source https://github.com/jazzsaxmafia/Weakly_detector/blob/master/src/train.caltech.py#L27\r\n\r\nimport numpy as np\r\nimport os\r\nimport pandas as pd\r\nfrom params import TrainingParams, HyperParams, CNNParams\r\n\r\nhparams = HyperParams(verbose=False)\r\ntparam = TrainingParams(verbose=False)\r\n\r\nimage_dir_list = os.listdir(tparam.images_path)\r\n\r\nlabel_pairs = map(lambda x: x.split('.'), image_dir_list)\r\nlabels, label_names = zip(*label_pairs)\r\nlabels = map(lambda x: int(x), labels)\r\n\r\n# label_pairs = [x.split('.') for x in image_dir_list]\r\n# labels, label_names = list(zip(*label_pairs))\r\n# labels = [int(x) for x in labels]\r\n\r\nlabel_dict = pd.Series(labels, index=label_names) - 1\r\nimage_paths_per_label = map(lambda one_dir: map(lambda one_file: os.path.join(tparam.images, one_dir, one_file),\r\n os.listdir(os.path.join(tparam.images, one_dir))), image_dir_list)\r\nimage_paths_train = np.hstack(map(lambda one_class: one_class[:-10], image_paths_per_label))\r\n\r\n# image_paths_per_label = [\r\n# [os.path.join(tparam.images, one_dir, one_file) for one_file in os.listdir(os.path.join(tparam.images, one_dir))]\r\n# for one_dir in image_dir_list]\r\n# image_paths_train = np.hstack([one_class[:-10] for one_class in image_paths_per_label])\r\n\r\nimage_paths_test = np.hstack(map(lambda one_class: one_class[-10:], image_paths_per_label))\r\n# image_paths_test = np.hstack([one_class[-10:] for one_class in image_paths_per_label])\r\n\r\ntrainset = pd.DataFrame({'image_path': image_paths_train})\r\ntestset = pd.DataFrame({'image_path': image_paths_test})\r\n\r\ntrainset = trainset[trainset['image_path'].map(lambda x: x.endswith('.jpg'))]\r\ntrainset['label'] = trainset['image_path'].map(lambda x: int(x.split('/')[-2].split('.')[0]) - 1)\r\ntrainset['label_name'] = trainset['image_path'].map(lambda x: x.split('/')[-2].split('.')[1])\r\n\r\ntestset = testset[testset['image_path'].map(lambda x: x.endswith('.jpg'))]\r\ntestset['label'] = testset['image_path'].map(lambda x: int(x.split('/')[-2].split('.')[0]) - 1)\r\ntestset['label_name'] = testset['image_path'].map(lambda x: x.split('/')[-2].split('.')[1])\r\n\r\nif not os.path.exists(tparam.data_train_path.split('/')[0]):\r\n os.makedirs(tparam.data_train_path.split('/')[0])\r\n\r\ntrainset.to_pickle(tparam.data_train_path)\r\ntestset.to_pickle(tparam.data_test_path)","sub_path":"prepare_data.py","file_name":"prepare_data.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"577197483","text":"from __future__ import annotations\n\nimport copy\nimport struct\nimport logging\n\nfrom io import BufferedReader\nfrom typing import Tuple, Union, ClassVar, List\n\n\nclass Structure(object):\n\n\t\"\"\"A base class for all structures.\n\n\n\tAttributes\n\t----------\n\t\t_fields_ : ClassVar[Tuple[Tuple[str, Union[int, str]]]]\n\t\t\tAll Structures need a _fields_ attribute which contains\n\t\t\tall the fields in the structure. Each entry is a Tuple\n\t\t\twith the field's name and an int, if it is a bytes field,\n\t\t\tor an str with a struct format. For example;\n\n\t\t\t\t_fields_ = (\n\t\t\t\t\t(\"uint32Field\", \" List[Tuple[str, Union[int, str]]]:\n\t\t\"\"\"Gets all the fields in the class.\n\n\t\tReturns\n\t\t-------\n\t\t\tList[Tuple[str, Union[int, str]]]\n\t\t\t\tA list of all the fields in order from the base class\n\t\t\t\tto the child class.\n\t\t\"\"\"\n\n\t\tmro = cls.mro()\n\n\t\tfields = []\n\t\tfor clsDef in reversed(mro):\n\t\t\tif not hasattr(clsDef, \"_fields_\"):\n\t\t\t\tcontinue\n\n\t\t\t[fields.append(field) for field in clsDef._fields_]\n\t\t\n\t\treturn fields\n\t\n\t@classmethod\n\tdef parse(cls, buffer: BufferedReader, offset: int, loadData: bool = True) -> Structure:\n\t\t\"\"\"Load the structure.\n\n\t\tThis method can be overridden to parse fields that cannot\n\t\tbe encoded in the _fields_ attribute, through super must\n\t\tbe called.\n\n\t\tParameters\n\t\t----------\n\t\t\tbuffer : BufferedReader\n\t\t\t\tThe source of data.\n\t\t\toffset : int\n\t\t\t\tByte offset to start at.\n\t\t\tloadData : bool, optional\n\t\t\t\tDetermines if the method \"loadData\" is called, by\n\t\t\t\tdefault True.\n\n\t\tReturns\n\t\t-------\n\t\t\tStructure\n\t\t\t\tAn instance of the structure.\n\t\t\"\"\"\n\n\t\tfields = cls._getFields()\n\n\t\tinst = cls()\n\t\tif offset < 0:\n\t\t\tlogging.critical(\"Structure.parse offset is negative\")\n\t\t\t# buffer.seek() is going to raise OSError\n\t\t\t# maybe this should be abstracted to a custom internal error?\n\t\tbuffer.seek(offset)\n\n\t\tfor field in fields:\n\t\t\tfieldValue = None\n\t\t\tif isinstance(field[1], str):\n\t\t\t\tfieldSize = struct.calcsize(field[1])\n\t\t\t\tfieldValue = struct.unpack(field[1], buffer.read(fieldSize))[0]\n\t\t\telse:\n\t\t\t\tfieldValue = buffer.read(field[1])\n\t\t\t\n\t\t\tsetattr(inst, field[0], fieldValue)\n\t\t\n\t\tinst._buffer = buffer\n\t\tinst._offset = offset\n\n\t\tif loadData:\n\t\t\tinst.loadData()\n\t\t\n\t\treturn inst\n\t\n\t@classmethod\n\tdef parseBytes(cls, buffer: bytes, offset: int) -> Structure:\n\t\t\"\"\"loads the structure with a bytes object.\n\n\t\tSimilar to the parse method, this method fills the structure with\n\t\tthe bytes like object. Though loadData will not be called.\n\n\t\tParameters\n\t\t----------\n\t\t\tbuffer : bytes\n\t\t\t\tSource of data.\n\t\t\toffset : int\n\t\t\t\tWhere to start in the data source.\n\n\t\tReturns\n\t\t-------\n\t\t\tStructure\n\t\t\t\tAn instance of the structure.\n\t\t\"\"\"\n\n\t\tfields = cls._getFields()\n\n\t\tinst = cls()\n\n\t\tbufferHead = offset\n\t\tfor field in fields:\n\n\t\t\tfieldValue = None\n\t\t\tif isinstance(field[1], str):\n\t\t\t\tfieldSize = struct.calcsize(field[1])\n\t\t\t\tfieldValue = struct.unpack_from(field[1], buffer, bufferHead)[0]\n\n\t\t\t\tbufferHead += fieldSize\n\t\t\telse:\n\t\t\t\tfieldValue = buffer[bufferHead:bufferHead+field[1]]\n\t\t\t\tbufferHead += field[1]\n\t\t\t\n\t\t\tsetattr(inst, field[0], fieldValue)\n\t\t\n\t\treturn inst\n\t\n\tdef asBytes(self) -> bytes:\n\t\t\"\"\"Returns the structure in bytes.\n\n\t\tThis can be overridden to add any fields not encoded in\n\t\tthe _fields_ attribute, though super must be called.\n\n\t\tReturns\n\t\t-------\n\t\t\tbytes\n\t\t\t\tThe data of the structure.\n\t\t\"\"\"\n\n\t\tfields = self._getFields()\n\n\t\tdata = b\"\"\n\t\tfor field in fields:\n\t\t\tfieldValue = getattr(self, field[0])\n\n\t\t\tif isinstance(field[1], str):\n\t\t\t\tdata += struct.pack(field[1], fieldValue)\n\t\t\telse:\n\t\t\t\tdata += fieldValue\n\t\t\n\t\treturn data\n\t\n\tdef loadData(self) -> None:\n\t\t\"\"\"Loads extra data.\n\n\t\tThis data should be descriptive, and not contained in\n\t\tthe structure itself\n\t\t\"\"\"\n\t\t...\n\t\n\tdef __deepcopy__(self, memo):\n\t\tnewInst = type(self)()\n\t\tfor var in vars(self):\n\n\t\t\tif var == \"_buffer\":\n\t\t\t\tnewInst._buffer = self._buffer\n\t\t\t\tcontinue\n\n\t\t\tvalue = copy.deepcopy(getattr(self, var), memo)\n\t\t\tsetattr(newInst, var, value)\n\t\t\n\t\treturn newInst\n\t\n\t@classmethod\n\tdef offsetOf(cls, fieldName: str) -> int:\n\t\t\"\"\"\n\t\tReturns the offset of the field.\n\t\t\"\"\"\n\t\tfields = cls._getFields()\n\n\t\toffset = 0\n\t\tfor field in fields:\n\t\t\tif field[0] == fieldName:\n\t\t\t\treturn offset\n\t\t\t\n\t\t\tif isinstance(field[1], str):\n\t\t\t\toffset += struct.calcsize(field[1])\n\t\t\telse:\n\t\t\t\toffset += field[1]","sub_path":"DyldExtractor/Structure.py","file_name":"Structure.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"67287546","text":"import os\nimport sys\nimport pygame\nimport random\n\npygame.init()\nclock = pygame.time.Clock()\n\nsize = width, height = 700, 500\nscreen = pygame.display.set_mode(size)\nFPS = 50\nSTEP = 10\nscore = 0\nplayer = pygame.sprite.Group()\nfon = pygame.sprite.Group()\ncls = pygame.sprite.Group()\n\n\ndef load_image(name):\n fullname = os.path.join('data', name)\n try:\n image = pygame.image.load(fullname)\n if name.endswith(\".png\"):\n image = image.convert_alpha()\n else:\n image = image.convert()\n except pygame.error as message:\n print('Cannot load image:', name)\n raise SystemExit(message)\n\n return image\n\n\ndef terminate():\n pygame.quit()\n sys.exit()\n\n\ndef start_screen():\n intro_text = [\"Игра Flappy Bird\", \"\",\n \"Правила игры\",\n \"Используйте Пробел, чтобы прыгать,\",\n \"Пролетайте между колоннами и не врезайтесь!\",\n \"Нажмите любую кнопку, чтобы начать.\"]\n\n fon = pygame.transform.scale(load_image('bckgrd.png'), (width * 3,\n height))\n screen.blit(fon, (0, 0))\n font = pygame.font.Font(None, 30)\n text_coord = 50\n for line in intro_text:\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 10\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n terminate()\n elif event.type == pygame.KEYDOWN or event.type == \\\n pygame.MOUSEBUTTONDOWN:\n return\n pygame.display.flip()\n clock.tick(FPS)\n\n\nclass Fon(pygame.sprite.Sprite):\n image = pygame.transform.scale(load_image('bckgrd.png'), (width * 3,\n height))\n speed = 1\n\n def __init__(self, group):\n super().__init__(group)\n self.image = Fon.image\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = 0, 0\n\n def update(self):\n self.rect.x -= Fon.speed\n if self.rect.x == -width * 2:\n self.rect.x = 0\n\n\nclass Bird(pygame.sprite.Sprite):\n speed = 2\n jump_flag = True\n up_flag = False\n dir_speed = 1\n\n def __init__(self, group, sheet, columns, rows, x, y):\n super().__init__(group)\n self.frames = []\n self.cut_sheet(sheet, columns, rows)\n self.cur_frame = 0\n self.num = 0\n self.image = self.frames[self.cur_frame]\n self.rect = self.rect.move(x, y)\n self.mask = pygame.mask.from_surface(self.image)\n self.dir = 1\n self.k = 1\n\n def cut_sheet(self, sheet, columns, rows):\n self.rect = pygame.Rect(0, 0, sheet.get_width() // columns,\n sheet.get_height() // rows)\n for j in range(rows):\n for i in range(columns):\n frame_location = (self.rect.w * i, self.rect.h * j)\n self.frames.append(sheet.subsurface(pygame.Rect(\n frame_location, self.rect.size)))\n\n def update(self):\n if self.jump_flag:\n if self.rect.y + 50 < height:\n self.rect.y += Bird.speed\n if self.num == 12:\n Bird.speed = 2\n self.num += 1\n self.k += 0.1\n self.cur_frame = (round(self.k)) % len(self.frames)\n self.image = self.frames[self.cur_frame]\n\n def jump(self):\n if Bird.jump_flag is True:\n Bird.up_flag = True\n Bird.speed = -5\n self.num = 0\n\n\nclass Column(pygame.sprite.Sprite):\n cl = load_image('cl.png')\n speed = 2\n\n def __init__(self, group):\n super().__init__(group)\n self.image = Column.cl\n self.rect = self.image.get_rect()\n self.rect.x, self.rect.y = width, -200 + random.randint(-179, 179)\n self.mask = pygame.mask.from_surface(self.image)\n\n def update(self, *args):\n self.rect.x -= Column.speed\n if pygame.sprite.collide_mask(self, bird):\n Column.speed = 0\n Fon.speed = 0\n Bird.speed = 0\n Bird.jump_flag = False\n Bird.dir_speed = 0\n\n\nbird = Bird(player, load_image(\"bird_sheet5x1.png\"), 5, 1, width // 2,\n height // 2)\nback = Fon(fon)\ncl = Column(cls)\nstart_screen()\n\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n bird.jump()\n screen.fill(pygame.Color('black'))\n if cl.rect.x < width / 2 - 130:\n cl = Column(cls)\n score += 1\n fon.update()\n fon.draw(screen)\n player.update()\n player.draw(screen)\n cls.update()\n cls.draw(screen)\n pygame.display.flip()\n clock.tick(75)\n\nterminate()\n","sub_path":"FlappyBird.py","file_name":"FlappyBird.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"11539500","text":"#!/usr/bin/python\r\n# -*- coding: cp936 -*-\r\n# Author: xuzhonglei\r\n# Date: 2015-1120\r\n\r\nimport time\r\nimport string\r\nimport re\r\n\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.lib_cmd.inter_mode import *\r\nfrom libcom.lib_cmd.config_mode import *\r\nfrom libcom.lib_cmd.shell_mode import *\r\nfrom libcom.lib_cmd.chg_mode import *\r\nfrom libcom.console_drv.console_drv import *\r\nfrom libcom.config_topo.topo_controller import *\r\nfrom cases_set.intf.l2pt.l2pt_commn_cmd import *\r\nfrom cases_set.intf.intf_commn_cmd import *\r\nfrom cases_set.intf.ap.ap_commn_cmd import *\r\n\r\n__all__ = [\"IT_L2PT_SSD_PROCESS_RESTART\"]\r\n\r\nSUCCESS = 0\r\nFAIL = -1\r\n\r\ndef kill_ssd_process(sw):\r\n cmd = 'end'\r\n run_cmd(sw, cmd)\r\n cmd = 'run-system-shell'\r\n run_cmd(sw, cmd)\r\n\r\n cmd = 'pkill -15 ssd_process'\r\n run_cmd(sw, cmd)\r\n\r\n cmd = 'exit'\r\n run_cmd(sw, cmd)\r\n\r\ndef ssd_get_port_attr_info(sw):\r\n cmd = 'end'\r\n run_cmd(sw, cmd)\r\n cmd = 'run-system-shell'\r\n run_cmd(sw, cmd)\r\n\r\n cmd = 'debug-ssd'\r\n write_cmd(sw, cmd)\r\n time.sleep(1)\r\n cmd = 'at'\r\n write_cmd(sw, cmd)\r\n time.sleep(1)\r\n cmd = 'load ssd_port'\r\n write_cmd(sw, cmd)\r\n time.sleep(1)\r\n cmd = 'load ssd_port'\r\n write_cmd(sw, cmd)\r\n time.sleep(1)\r\n cmd = 'ut dump_pt 0 0 0'\r\n info = run_at_cmd(sw, cmd)\r\n time.sleep(5)\r\n cmd = 'quit'\r\n write_cmd(sw, cmd)\r\n time.sleep(1)\r\n quit_ssa_mode(sw) \r\n\r\n cmd = 'exit'\r\n run_cmd(sw, cmd)\r\n return info\r\n\r\ndef IT_L2PT_SSD_PROCESS_RESTART_P(cb_arg):\r\n \r\n #step 0 init\r\n ret = SUCCESS\r\n \r\n dev_name = cb_arg.dev_names[0]\r\n attr_info = ssd_get_port_attr_info(dev_name)\r\n for y in range(0, 1):\r\n kill_ssd_process(dev_name)\r\n time.sleep(30)\r\n attr_info_tmp = ssd_get_port_attr_info(dev_name)\r\n if attr_info_tmp.find(attr_info) == -1:\r\n return FAIL\r\n return ret\r\n\r\n#this is main-function\r\ndef IT_L2PT_SSD_PROCESS_RESTART(cb_arg):\r\n if len(cb_arg.dev_names) == 0:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n\r\n dev_name = cb_arg.dev_names[0]\r\n wake_up_console(dev_name)\r\n result = FAIL\r\n try:\r\n result = IT_L2PT_SSD_PROCESS_RESTART_P(cb_arg)\r\n finally:\r\n exit_console(dev_name)\r\n return result\r\n\r\n","sub_path":"cases_set/intf/l2pt/smoking/IT_L2PT_SSD_PROCESS_RESTART.py","file_name":"IT_L2PT_SSD_PROCESS_RESTART.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"202653375","text":"import atexit\nimport logging\nfrom pytz import timezone\nimport pytz\nimport os\nfrom twilio.rest import Client\nfrom datetime import datetime\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom apscheduler.triggers.cron import CronTrigger\n\n#######REMEMBER WHEN DEBUGGING THE SCHEDULER MESSAGES WITH TWILIO IT TAKES UP TO TWO MINUTES FOR THE CODE TO BE FULLY DEPLOYED#######\n\nlogging.basicConfig()\nutc = pytz.utc\t\t\n# Find these values at https://twilio.com/user/account\naccount_sid = 'ACdc0bae8c0927f2fc28fb18d90d742832'\nauth_token = 'bd0968ff79b1c26e84f5eae794757416'\nclient = Client(account_sid, auth_token)\nscheduler = BackgroundScheduler()\nclass AveryPillScheduler():\n\t\n\tdef avery_pill_job(self):\n\t\tscheduler.start()\n\t\tscheduler.add_job(\n\t\tfunc=self.print_pill_message,\n\t\t#use this timer after daylight savings time ends on November 17\n\t\ttrigger=CronTrigger(year='*', month='*', day='*', week='*', day_of_week='*', hour='16', minute='30', second='00',timezone=utc),\n\t\t#use this timer after daylight savings time begin on March 10\n\t\t#trigger=CronTrigger(year='*', month='*', day='*', week='*', day_of_week='*', hour='15', minute='30', second='00',timezone=utc),\n\t\tid='printing_job',\n\t\tname='Print pill message every day at 11:30 AM Eastern Time',\n\t\treplace_existing=True)\n\t\t#UTC IS FIVE HOURS AHEAD BUT WHEN DAYLIGHT SAVINGS TIME KICKS IN AROUND MARCH IT IS ONLY 4 HOURS AHEAD!!!\n\t\t# Shut down the scheduler when exiting the app\n\t\tatexit.register(lambda: scheduler.shutdown())\n\n\tdef print_pill_message(self):\n\t\tprint('pill func was called')\n\t\t#+14782513043 - ryyan's phone number\n\t\t#+14782922142 - twilio number\n\t\t#+12514228131 - avery's phone number\n\t\ttry:\n\t\t\tmessage = client.api.account.messages.create(to=\"+12514228131\",\n from_=\"+14782922142\",\n body=\"Don't forget to take your pill babe! I love you! \")\n\t\texcept error:\n\t\t\tprint(error)\n","sub_path":"Schedulers/avery_pill_scheduler.py","file_name":"avery_pill_scheduler.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"612430598","text":"# 2020 Tommaso Ciussani and Giacomo Giuliari\nimport networkx as nx\nfrom geopy.distance import great_circle\n\nfrom icarus_simulator.strategies.routing.base_routing_strat import BaseRoutingStrat\nfrom icarus_simulator.structure_definitions import GridPos, SdPair, Coverage, LbSet\n\n\nclass KDSRoutStrat(BaseRoutingStrat):\n def __init__(self, desirability_stretch: float, k: int, **kwargs):\n super().__init__()\n self.desirability_stretch = desirability_stretch\n self.k = k\n if len(kwargs) > 0:\n pass # Appease the unused param inspection\n\n @property\n def name(self) -> str:\n return \"kds\"\n\n @property\n def param_description(self) -> str:\n return f\"{self.desirability_stretch}k{self.k}\"\n\n def compute(\n self, pair: SdPair, grid: GridPos, network: nx.Graph, coverage: Coverage\n ) -> LbSet:\n in_grid, out_grid = pair[0], pair[1]\n fiber_len = (\n great_circle(\n (grid[in_grid].lat, grid[in_grid].lon),\n (grid[out_grid].lat, grid[out_grid].lon),\n ).meters\n * self.desirability_stretch\n )\n # Add the gnd nodes\n for gnd in pair:\n for dst_sat in coverage[gnd]:\n network.add_edge(-gnd, dst_sat, length=coverage[gnd][dst_sat])\n\n # Compute the possible paths using the chosen criterion\n lbset: LbSet = []\n lengths = {}\n cnt = 0\n while True:\n try:\n length, path = nx.single_source_dijkstra(\n network, -pair[0], -pair[1], cutoff=fiber_len, weight=\"length\"\n )\n except nx.NetworkXNoPath:\n break\n\n lbset.append((path, length))\n cnt += 1\n if cnt >= self.k:\n break\n # It makes no sense to find alternate paths in gnd-sat-gnd situation, as they will likely be too long\n if len(path) <= 3:\n break\n # Set used edges to INF length, and also the ones coming out of the nodes\n ed = path[1], path[2]\n lengths[ed] = network[ed[0]][ed[1]][\"length\"]\n network[ed[0]][ed[1]][\"length\"] = float(\"inf\")\n for n in path[2:-2]:\n out_ed = network.edges(n)\n for ed in out_ed:\n # Exclude up and downlinks from the disjointness\n if ed not in lengths and (ed[1], ed[0]) not in lengths:\n lengths[ed] = network[ed[0]][ed[1]][\"length\"]\n network[ed[0]][ed[1]][\"length\"] = float(\"inf\")\n\n # Restore the infinite lengths\n for ed in lengths:\n network[ed[0]][ed[1]][\"length\"] = lengths[ed]\n\n # Delete the added nodes\n for gnd in pair:\n network.remove_node(-gnd)\n return lbset\n","sub_path":"icarus_simulator/strategies/routing/kds_rout_strat.py","file_name":"kds_rout_strat.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"210671681","text":"import json\nimport traceback\nfrom peewee import PeeweeException\nfrom logzero import logger\nfrom tornado.web import HTTPError, ErrorHandler as TorErrorHandler, RequestHandler\nfrom settings import settings, is_production\nfrom exception import CustomException\n\n\nclass BaseHandler(RequestHandler):\n request_body = None\n\n def set_default_headers(self):\n if not is_production:\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"access-control-allow-origin,authorization,content-type,x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'GET, PUT, PATCH, DELETE, OPTIONS')\n\n def get_current_user(self):\n return self.get_secure_cookie('user_id')\n\n def prepare(self):\n content_type = self.request.headers.get(\"Content-Type\", \"\")\n jsontype, textplain = \"application/json\", \"text/plain\"\n valid_content_type = jsontype in content_type or textplain in content_type\n\n if valid_content_type:\n self.request_body = json.loads(self.request.body)\n\n def options(self):\n self.set_status(204)\n self.finish()\n\n def json_response(self, response='', meta=''):\n standard_resp = {\n 'payload': response,\n 'meta': meta,\n }\n self.write(standard_resp)\n\n def write_error(self, status_code, **kwargs):\n _, http_exception, stack_trace = kwargs['exc_info']\n\n error = {\n 'code': status_code,\n 'message': self._reason,\n 'detail': str(http_exception),\n }\n\n if isinstance(http_exception, CustomException):\n error['code'] = http_exception.status_code\n error['message'] = http_exception.message\n error['detail'] = http_exception.detail\n\n elif isinstance(http_exception, PeeweeException):\n error['code'] = 500\n error['message'] = 'DatabaseError: {}'.format(http_exception)\n error['detail'] = self.request_body\n\n else:\n # if settings['stg'] == 'development':\n # logger.exception(http_exception)\n # traceback.print_tb(stack_trace)\n # breakpoint()\n pass\n\n self.set_status(error['code'])\n self.finish(json.dumps({'error': error}))\n\n\nclass ErrorHandler(TorErrorHandler, BaseHandler):\n \"\"\"\n Default handler to be used in case of 404 error\n \"\"\"\n\n\nclass NotFoundHandler(BaseHandler):\n\n def prepare(self):\n raise HTTPError(\n status_code=404,\n reason=\"Invalid api endpoint.\",\n )\n","sub_path":"backend/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"645304154","text":"import json\nimport os\nfrom awesome.plugins.utils.methods import *\n\n\ndef getQQ(session):\n return str(session.ctx['sender']['user_id'])\n\ndef getMsg(qq):\n path = './data/note/' + qq + '.json'\n if not os.path.exists(path):\n return {}\n else:\n tmp = {}\n try:\n with open(path, 'r', encoding='utf-8') as f:\n tmp = json.load(f)\n except Exception:\n pass\n return tmp\n\ndef writeMsg(qq, msg):\n path = './data/note/' + qq + '.json'\n try:\n with open(path,'w',encoding='utf-8') as f:\n json.dump(msg, f, ensure_ascii=False)\n return True\n except Exception:\n return False\n\ndef addNote(session, op):\n keys = ['addTitle', 'addContent']\n if op != '':\n setSessionArgs(op.split(' '), keys, session, True)\n addTitle = session.get('addTitle',prompt='输入要添加的标题[-c]取消:')\n \n if addTitle == '-c':\n return '操作已取消'\n \n addContent = session.get('addContent', prompt='输入想要添加的内容:')\n \n qq = getQQ(session)\n msg = getMsg(qq)\n msg[addTitle] = addContent\n print(msg)\n if writeMsg(qq, msg):\n return '添加成功'\n else:\n return '添加失败'\n\ndef delNote(session, op):\n msg = getMsg(str(session.ctx['sender']['user_id']))\n if len(msg.keys()) <= 0 :\n return '没有记录可以删除,请先添加'\n \n keys = ['delTitle']\n if op != '':\n setSessionArgs(op.split(' '), keys, session, True)\n \n delTitle = session.get('delTitle', prompt='请输入要删除的标题(输入[-c]可以取消此操作):')\n \n delTitle = delTitle.strip()\n if delTitle == '-c':\n return '删除已取消'\n \n if delTitle in msg.keys():\n del msg[delTitle]\n try:\n writeMsg(getQQ(session), msg)\n except Exception:\n return '删除失败,请稍后重试'\n \n return '删除' + delTitle + '成功'\n else:\n return '没有这个记录,可以使用[note v]查看'\n \ndef insertNote(session, op):\n keys = ['addTitle', 'insertContent']\n if op != '':\n setSessionArgs(op.split(' '), keys, session, True)\n \n addTitle = session.get('addTitle', prompt='请输入要插入的标题,输入[-c]可取消操作:')\n if addTitle == '-c':\n return '操作已取消'\n msg = getMsg(getQQ(session))\n if addTitle not in msg.keys():\n flag = session.get('flag', prompt='未找到该标题,是否直接添加?(Y/N)')\n flag = flag.strip()\n if flag.lower() == 'y':\n return addNote(session, op)\n else:\n return '添加操作已取消'\n else:\n insertContent = session.get('insertContent', prompt='请输入要添加的内容(输入[-c]可以取消此操作):')\n insertContent = insertContent.strip()\n if insertContent == '-c':\n return '操作已取消'\n \n if type(msg[addTitle]) is not list:\n msg[addTitle] = [msg[addTitle]]\n msg[addTitle].append(insertContent)\n if writeMsg(getQQ(session), msg):\n return '信息插入成功'\n else:\n return '信息插入失败'\n \n \n\ndef viewNote(session, op):\n msg = getMsg(str(session.ctx['sender']['user_id']))\n op = op.strip()\n \n keys = ['viewTitle']\n if op != '':\n setSessionArgs(op.split(' '), keys, session, True)\n viewTitle = session.get('viewTitle',prompt='输入要查看的标题(输入[-all]可查看全部记录标题):')\n \n viewTitle = viewTitle.strip()\n if viewTitle == '-all':\n if len(msg.keys()) <= 0:\n return '没有记录,要先添加'\n return msg.keys()\n \n if viewTitle not in msg.keys():\n return '没有这个记录'\n else:\n return msg[viewTitle]\n\ndef helpNote(session, op):\n msg = []\n msg.append('note帮助([]表示可选参数)')\n msg.append('note add [记录名]\\t添加记录')\n msg.append('note v [记录名]\\t查看记录')\n msg.append('note del [记录名]\\t删除记录')\n msg.append('note i [记录名]\\t插入记录')\n msg.append('note 帮助\\t功能帮助')\n return msg\n\nhDict = {}\n\ndef initData():\n hDict['add'] = addNote\n hDict['v'] = viewNote\n hDict['del'] = delNote\n hDict['i'] = insertNote\n hDict['帮助'] = helpNote\n\nasync def handleOp(op, session) -> str:\n initData()\n # 去除前后空格\n op = op.strip()\n args = op.split(' ', 1)\n\n # 如果没有第二个参数就添加一个,保持数���一致\n if len(args) < 2:\n args.append('')\n msg = None\n \n if args[0] in hDict.keys():\n msg = hDict[args[0]](session, args[1])\n else:\n msg=\"没有这个操作,请确认后重试\"\n return msg\n ","sub_path":"awesome/plugins/note/data_source.py","file_name":"data_source.py","file_ext":"py","file_size_in_byte":4848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"2453238","text":"from kafkaesk import Application\nfrom kafkaesk import Subscription\nfrom kafkaesk import SubscriptionConsumer\nfrom kafkaesk.exceptions import ConsumerUnhealthyException\nfrom kafkaesk.exceptions import StopConsumer\nfrom kafkaesk.subscription import MessageHandler\nfrom tests.utils import record_factory\nfrom unittest.mock import AsyncMock\nfrom unittest.mock import MagicMock\nfrom unittest.mock import patch\n\nimport aiokafka.errors\nimport asyncio\nimport opentracing\nimport pydantic\nimport pytest\n\npytestmark = pytest.mark.asyncio\n\n\n@pytest.fixture()\ndef subscription():\n yield SubscriptionConsumer(\n Application(kafka_servers=[\"foobar\"]), Subscription(\"foo\", lambda record: 1, \"group\")\n )\n\n\ndef test_subscription_repr():\n sub = Subscription(\"stream_id\", lambda x: None, \"group\")\n assert repr(sub) == \"\"\n\n\nclass TestMessageHandler:\n def factory(self, func):\n consumer = MagicMock()\n consumer._subscription.func = func\n return MessageHandler(consumer)\n\n async def test_message_handler(self):\n async def raw_func(data):\n assert isinstance(data, dict)\n\n mh = self.factory(raw_func)\n await mh.handle(record_factory(), None)\n\n async def test_message_handler_map_types(self):\n class Foo(pydantic.BaseModel):\n foo: str\n\n async def handle_func(ob: Foo, schema, record, app, subscriber, span: opentracing.Span):\n assert ob.foo == \"bar\"\n assert schema == \"Foo:1\"\n assert record is not None\n assert app is not None\n assert subscriber is not None\n assert span is not None\n\n mh = self.factory(handle_func)\n await mh.handle(record_factory(), MagicMock())\n\n\nclass TestSubscriptionConsumer:\n async def test_consumer_property_rasises_exception(self, subscription):\n with pytest.raises(RuntimeError):\n subscription.consumer\n\n async def test_retry_policy_property_rasises_exception(self, subscription):\n with pytest.raises(RuntimeError):\n subscription.retry_policy\n\n async def test_maybe_commit(self, subscription):\n subscription._consumer = AsyncMock()\n subscription._last_commit = -10 # monotonic\n await subscription._maybe_commit()\n subscription.consumer.commit.assert_called_once()\n\n async def test_maybe_commit_handles_commit_failure(self, subscription):\n subscription._consumer = AsyncMock()\n subscription._consumer.commit.side_effect = aiokafka.errors.CommitFailedError\n subscription._last_commit = -10 # monotonic\n await subscription._maybe_commit()\n subscription.consumer.commit.assert_called_once()\n\n async def test_healthy_with_no_consumer_set(self, subscription):\n assert await subscription.healthy() is None\n\n async def test_healthy(self, subscription):\n subscription._consumer = MagicMock()\n subscription._consumer._coordinator.coordinator_id = \"coordinator_id\"\n subscription._consumer._client.ready = AsyncMock(return_value=True)\n assert await subscription.healthy() is None\n subscription._consumer._client.ready.assert_called_with(\"coordinator_id\")\n\n async def test_unhealthy(self, subscription):\n subscription._consumer = MagicMock()\n subscription._consumer._client.ready = AsyncMock(return_value=False)\n with pytest.raises(ConsumerUnhealthyException):\n assert await subscription.healthy()\n\n async def test_emit(self):\n probe = AsyncMock()\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n event_handlers={\"event\": [probe]},\n )\n await sub.emit(\"event\", \"foo\", \"bar\")\n probe.assert_called_with(\"foo\", \"bar\")\n\n async def test_emit_raises_stop(self):\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n event_handlers={\"event\": [AsyncMock(side_effect=StopConsumer)]},\n )\n with pytest.raises(StopConsumer):\n await sub.emit(\"event\", \"foo\", \"bar\")\n\n async def test_emit_swallow_ex(self):\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n event_handlers={\"event\": [AsyncMock(side_effect=Exception)]},\n )\n await sub.emit(\"event\", \"foo\", \"bar\")\n\n async def test_retries_on_connection_failure(self):\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n )\n run_mock = AsyncMock()\n sleep = AsyncMock()\n run_mock.side_effect = [aiokafka.errors.KafkaConnectionError, StopConsumer]\n with patch.object(sub, \"initialize\", AsyncMock()), patch.object(\n sub, \"finalize\", AsyncMock()\n ), patch.object(sub, \"_run\", run_mock), patch(\"kafkaesk.subscription.asyncio.sleep\", sleep):\n await sub()\n sleep.assert_called_once()\n assert len(run_mock.mock_calls) == 2\n\n async def test_finalize_handles_exceptions(self):\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n )\n consumer = AsyncMock()\n consumer.stop.side_effect = Exception\n consumer.commit.side_effect = Exception\n retry_policy = AsyncMock()\n retry_policy.finalize.side_effect = Exception\n\n sub._consumer = consumer\n sub._retry_policy = retry_policy\n await sub.finalize()\n\n consumer.stop.assert_called_once()\n consumer.commit.assert_called_once()\n retry_policy.finalize.assert_called_once()\n\n async def test_run_exits_when_fut_closed_fut(self):\n sub = SubscriptionConsumer(\n Application(),\n Subscription(\"foo\", lambda record: 1, \"group\"),\n )\n consumer = AsyncMock()\n consumer.getmany.return_value = {\"\": [record_factory() for _ in range(10)]}\n sub._consumer = consumer\n sub._running = True\n\n async def _handle_message(record):\n await asyncio.sleep(0.03)\n\n with patch.object(sub, \"_handle_message\", _handle_message):\n task = asyncio.create_task(sub._run())\n await asyncio.sleep(0.01)\n stop_task = asyncio.create_task(sub.stop())\n await asyncio.sleep(0.01)\n sub._close_fut.set_result(None)\n\n await asyncio.wait([stop_task, task])\n","sub_path":"tests/unit/test_subscription.py","file_name":"test_subscription.py","file_ext":"py","file_size_in_byte":6575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"348169077","text":"\"\"\"\nHelper functions for PASTIS.\n\"\"\"\n\nimport os\nimport numpy as np\nfrom astropy.io import fits\nimport astropy.units as u\n\n\ndef write_fits(data, filepath, header=None, metadata=None):\n \"\"\"\n Writes a fits file and adds header and metadata when necessary.\n :param data: numpy data (aka image)\n :param filepath: path to save the file, include filename.\n :param header: astropy hdu.header.\n :param metadata: list of MetaDataEntry objects that will get added to header.\n :return: filepath\n \"\"\"\n # Make sure file ends with fit or fits.\n #if not (filepath.endswith(\".fit\") or filepath.endswith(\".fits\")):\n # filepath += \".fits\"\n\n if not os.path.exists(os.path.dirname(filepath)):\n os.makedirs(os.path.dirname(filepath))\n\n # Create a PrimaryHDU object to encapsulate the data.\n hdu = fits.PrimaryHDU(data)\n if header is not None:\n hdu.header = header\n\n # Add metadata to header.\n if metadata is not None:\n for entry in metadata:\n if len(entry.name_8chars) > 8:\n print('Fits Header Keyword: ' + entry.name_8chars +\n ' is greater than 8 characters and will be truncated.')\n if len(entry.comment) > 47:\n print('Fits Header comment for ' + entry.name_8chars +\n ' is greater than 47 characters and will be truncated.')\n hdu.header[entry.name_8chars[:8]] = (entry.value, entry.comment)\n\n # Create a HDUList to contain the newly created primary HDU, and write to a new file.\n fits.HDUList([hdu])\n hdu.writeto(filepath, overwrite=True)\n\n #print('Wrote ' + filepath)\n return filepath\n\n\ndef circle_mask(im, xc, yc, rcirc):\n \"\"\" Create a circle on array im centered on xc, yc with radius rcirc; inside circle equals 1.\"\"\"\n x, y = np.shape(im)\n newy, newx = np.mgrid[0:y,0:x]\n circ = (newx-xc)**2 + (newy-yc)**2 < rcirc**2\n return circ\n\n\ndef zoom_point(im, x, y, bb):\n \"\"\"\n Cut out a square box from image im centered on (x,y) with half-box size bb.\n :param im: image from which box will be taken\n :param x: x coordinate of center of box\n :param y: y coordinate of center of box\n :param bb: half-box size\n :return:\n \"\"\"\n return (im[int(y - bb):int(y + bb), int(x - bb):int(x + bb)])\n\n\ndef zoom_cen(im, bb):\n \"\"\"\n Cut out a square box from the image center with half-box size bb.\n :param im: image from which box will be taken\n :param bb: half-box size\n :return:\n \"\"\"\n x = int(im.shape[1]/2)\n y = int(im.shape[0]/2)\n return im[int(y-bb):int(y+bb), int(x-bb):int(x+bb)]\n\n\ndef FFT(ef):\n \"\"\"Do the numpy Fourier transform on complex array 'ef', together with all the shifting needed.\"\"\"\n FFT_E = np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(ef)))\n return FFT_E\n\n\ndef IFFT(ef):\n \"\"\"Do the numpy inverse Fourier transform on complex array 'ef', together with all the shifting needed.\"\"\"\n IFFT_E = np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(ef)))\n return IFFT_E\n\n\ndef create_dark_hole(pup_im, iwa, owa, samp):\n \"\"\"\n Create a dark hole on pupil image pup_im.\n :param pup_im: np.array of pupil image\n :param iwa: inner working angle in lambda/D\n :param owa: outer working angle in lambda/D\n :param samp: sampling factor\n :return: dh_area, np.array\n \"\"\"\n circ_inner = circle_mask(pup_im, pup_im.shape[0]/2., pup_im.shape[1]/2., iwa * samp) * 1 # *1 converts from booleans to integers\n circ_outer = circle_mask(pup_im, pup_im.shape[0]/2., pup_im.shape[1]/2., owa * samp) * 1\n dh_area = circ_outer - circ_inner\n\n return dh_area\n\n\ndef dh_mean(im, dh):\n \"\"\"\n Return the dark hole contrast.\n\n Calculate the mean intensity in the dark hole area dh of the image im.\n im and dh have to have the same array size and shape.\n \"\"\"\n darkh = im * dh\n con = np.mean(darkh[np.where(darkh != 0)])\n return con\n\n\n@u.quantity_input(aber=u.nm)\ndef pastis_contrast(aber, matrix_pastis):\n \"\"\"\n Calculate the contrast with PASTIS matrix model.\n :param aber: aberration vector, its length is number of segments, aberration coefficients in NANOMETERS\n :param matrix_pastis: PASTIS matrix\n :return:\n \"\"\"\n result = np.matmul(np.matmul(aber, matrix_pastis), aber)\n return result.value\n\n\ndef rms(ar):\n rms = np.sqrt(np.mean(np.square(ar)) - np.square(np.mean(ar)))\n return rms\n\n\ndef aber_to_opd(aber_rad, wvln):\n \"\"\"\n Convert phase aberration in rad to OPD in meters.\n :param aber_rad: float, phase aberration in radians\n :param wvln: float, wavelength\n :return:\n aber_m: float, OPD in meters\n \"\"\"\n aber_m = aber_rad * wvln / (2 * np.pi)\n return aber_m\n\n\ndef noll_to_wss(zern):\n \"\"\"\n Transform a Noll Zernike index into a JWST WSS framework Zernike index.\n :param zern: int; Noll Zernike index\n :return: WSS Zernike index\n \"\"\"\n noll = {1: 'piston', 2: 'tip', 3: 'tilt', 4: 'defocus', 5: 'astig45', 6: 'astig0', 7: 'ycoma', 8: 'xcoma',\n 9: 'ytrefoil', 10: 'xtrefoil', 11: 'spherical'}\n wss = {'piston': 1, 'tip': 2, 'tilt': 3, 'defocus': 5, 'astig45': 4, 'astig0': 6, 'ycoma': 8, 'xcoma': 7,\n 'ytrefoil': 10, 'xtrefoil': 11, 'spherical': 9}\n wss_ind = wss[noll[zern]]\n\n return wss_ind\n\n\ndef wss_to_noll(zern):\n \"\"\"\n Transform a JWST WSS framework Zernike index into a Noll Zernike index.\n :param zern: int; WSS Zernike index\n :return: Noll Zernike index\n \"\"\"\n noll = {'piston': 1, 'tip': 2, 'tilt': 3, 'defocus': 4, 'astig45': 5, 'astig0': 6, 'ycoma': 7, 'xcoma': 8,\n 'ytrefoil': 9, 'xtrefoil': 10, 'spherical': 11}\n wss = {1: 'piston', 2: 'tip', 3: 'tilt', 5: 'defocus', 4: 'astig45', 6: 'astig0', 8: 'ycoma', 7: 'xcoma',\n 10: 'ytrefoil', 11: 'xtrefoil', 9: 'spherical'}\n noll_ind = noll[wss[zern]]\n\n return noll_ind\n\n\ndef zernike_name(index, framework='Noll'):\n \"\"\"Get the name of the Zernike with input index in inpit framework (Noll or WSS).\"\"\"\n noll_names = {1: 'piston', 2: 'tip', 3: 'tilt', 4: 'defocus', 5: 'astig45', 6: 'astig0', 7: 'ycoma', 8: 'xcoma',\n 9: 'ytrefoil', 10: 'xtrefoil', 11: 'spherical'}\n wss_names = {1: 'piston', 2: 'tip', 3: 'tilt', 5: 'defocus', 4: 'astig45', 6: 'astig0', 8: 'ycoma', 7: 'xcoma',\n 10: 'ytrefoil', 11: 'xtrefoil', 9: 'spherical'}\n\n if framework == 'Noll':\n zern_name = noll_names[index]\n elif framework == 'WSS':\n zern_name = wss_names[index]\n else:\n raise ValueError('No known Zernike convention passed.')\n\n return zern_name\n\n\nclass ZernikeMode:\n \"\"\"\n A Zernike mode with Zernike mode index, name of mode and name of ordering convention.\n\n It can use framework = 'Noll' or 'WSS' and an index = between 1 and 11.\n It initializes with framework = 'Noll', but needs an index given.\n If you change ZernikeMode.convention directly, you screw things up... there are methods to change naming convention\n which are capable of changing everything that comes with that.\n \"\"\"\n\n def __init__(self, index, framework='Noll'):\n self.convention = framework\n self.index = index\n\n def get_info(self):\n \"\"\"Prints full Zernike mode info.\"\"\"\n print('This is Zernike mode', self.index, 'in the', self.convention, 'convention, which is:', self.name)\n\n def change_to_wss(self):\n \"\"\"Change form Noll to WSS Zernike index.\"\"\"\n if self.convention == 'WSS':\n print('You are already in the WSS convention!')\n else:\n self.index = noll_to_wss(self.index)\n self.convention = 'WSS'\n\n def change_to_noll(self):\n \"\"\"Change from WSS to Noll Zernike index.\"\"\"\n if self.convention == 'Noll':\n print('You are already in the Noll convention!')\n else:\n self.index = wss_to_noll(self.index)\n self.convention = 'Noll'\n\n @property\n # this property needs some fixing\n def name(self):\n zern_name = zernike_name(self.index, self.convention)\n return zern_name\n","sub_path":"pastis/util_pastis.py","file_name":"util_pastis.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"158978023","text":"'''Provides the `Variable` and `Parameter` objects for the semantic\r\nmodel.\r\n'''\r\n\r\n__all__ = ['Variable', 'Parameter']\r\n\r\nclass Parameter(object):\r\n '''Represents a parameter in a function call. Parameters either\r\n have a name and a value (explicit parameter) or just a name\r\n (implicit paramter; `value` is ``None``).\r\n '''\r\n tag = 'parameter'\r\n\r\n def __init__(self, name_value_pair, span=None):\r\n self.name = name_value_pair[0]\r\n '''The parameter name. This must be a string.'''\r\n self.value = name_value_pair[1]\r\n '''The parameter value. This may be ``None`` to indicate an\r\n implicit parameter.\r\n '''\r\n self.span = span\r\n '''A list of the tokens constituting this parameter.'''\r\n assert isinstance(self.name, str), \"`name` must be `str`, not %s\" % self.name\r\n\r\n def __iter__(self):\r\n yield self.name\r\n yield self.value\r\n\r\n def __getitem__(self, index):\r\n if index == 0: return self.name\r\n if index == 1: return self.value\r\n raise IndexError()\r\n\r\n def __str__(self):\r\n if self.value is not None:\r\n return '%s=%s' % (self.name, self.value)\r\n else:\r\n return str(self.name)\r\n\r\n def execute(self, context):\r\n '''Returns a resolved ``name, value`` pair.'''\r\n if self.value is not None:\r\n return (self.name, self.value.execute(context))\r\n else:\r\n return (self.name, context.get(self.name, True))\r\n\r\nclass Variable(object):\r\n '''Represents a variable in the semantic model. Variables may be\r\n constant, in which case the `value` member is valid, external, or\r\n neither. Constant and external variables may not be reassigned.\r\n '''\r\n tag = 'variable'\r\n\r\n def __init__(self, name=None, value=None, external=False, constant=False, span=None):\r\n self.name = str(name or value)\r\n '''The name of the variable. For anonymous constants, this is\r\n a string representation of `value`.\r\n '''\r\n self.value = value\r\n '''The value of the variable. For externals or constants, this\r\n may not be modified within the system. For other variables,\r\n this may be ``None``.\r\n '''\r\n self.external = external\r\n '''Indicates that the variable is provided externally to the\r\n system. External variables cannot be modified within a system.\r\n '''\r\n self.constant = constant\r\n '''Indicates that the variable is a constant. Constants must\r\n provide a value at compile-time; this value may be substituted\r\n directly into any generated code.\r\n '''\r\n self.references = []\r\n '''A list of references to this variable.\r\n '''\r\n self.span = span\r\n '''The list of tokens constituting the original definition of\r\n this variable. Each reference may have its own distinct span.\r\n '''\r\n self.alias = None\r\n '''The original variable aliased by this variable. This is not\r\n valid except when executing the model.'''\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n def execute(self, context):\r\n '''Returns the current value for this variable.'''\r\n if self.constant:\r\n return self.value\r\n elif self.alias:\r\n return self.alias.execute(context)\r\n else:\r\n return context[self.name]\r\n","sub_path":"esec/esdlc/model/components/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"236440731","text":"from sqlalchemy import *\nfrom migrate import *\nfrom _utils import get_prev_meta\n\nmeta = get_prev_meta(__file__)\ndocumentos = meta.tables['documentos']\nitems_documento = meta.tables['items_documento']\ntasas = meta.tables['tasas']\ncache = meta.tables['cache']\n\nicach = Index('ix_cache_cliente_id', cache.c.cliente_id)\nidoc = Index('ix_documentos_cliente_id', documentos.c.cliente_id)\niidoc_art = Index('ix_items_documento_articulo_id', items_documento.c.articulo_id)\niidoc_doc = Index('ix_items_documento_documento_id', items_documento.c.documento_id)\nitas = Index('ix_tasas_documento_id', tasas.c.documento_id)\n\ndef upgrade(migrate_engine):\n # Upgrade operations go here. Don't create your own engine; bind migrate_engine\n # to your metadata\n meta.bind = migrate_engine\n\n icach.create()\n idoc.create()\n iidoc_art.create()\n iidoc_doc.create()\n itas.create()\n\ndef downgrade(migrate_engine):\n # Operations to reverse the above upgrade go here.\n meta.bind = migrate_engine\n\n icach.drop()\n idoc.drop()\n iidoc_art.drop()\n iidoc_doc.drop()\n itas.drop()\n","sub_path":"dbmigrate/versions/002_added_indexes.py","file_name":"002_added_indexes.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"241206104","text":"#!/usr/bin/env python\n\nimport sys, os.path, re, copy\nimport itertools, operator\n\n\ndef computeResult2(classnb, input):\n\n\tcontainer = [set()]*(classnb+1)\n\toldcontainer = set()\t\n\t\n\t#print \"%s %s\" % (classnb, input)\t\n\t\n\tfor i in range(1,classnb+1):\t\t\n\t\tcontainer[i] = set(input[i-1][1:])\n\t\t\n\twhile oldcontainer != container:\n\t\t#print \"%s\" % container\n\t\toldcontainer = copy.deepcopy(container)\n\t\tfor i in range(1,classnb+1):\n\t\t\t\n\t\t\ttempcontainer = copy.deepcopy(container[i])\n\n\t\t\tfor j in tempcontainer:\n\t\t\t\tif j != i and len(container[j])>0:\n\t\t\t\t\tif len(container[i] & container[j]) > 0:\n\t\t\t\t\t\t\treturn \"Yes\"\n\t\t\t\t\tcontainer[i].discard(j)\n\t\t\t\t\tcontainer[i] = container[i].union(container[j])\t\t\t\t\t\n\t\t\t\n\n\treturn \"No\"\n\n\n\nif __name__ == '__main__':\n\n\tif len(sys.argv) != 2 or not os.path.isfile(sys.argv[1]):\n\t\tinputFile = sys.stdin\n\telse:\n\t\tinputFile = open(sys.argv[1], 'r')\n\n\ttestNB = 0\n\tinputFile.readline()\n\t\n\twhile True:\n\t\t\n\t\tline = inputFile.readline()\n\t\tif line == \"\":\n\t\t\tbreak \n\n\t\ttestNB += 1\n\n\n\t\tclassnb = int(line.strip())\n\t\tinput = []\n\t\tfor i in range(classnb):\n\t\t\tinput.append([ int(x) for x in inputFile.readline().split() ])\t\t\n\n\t\tresult = computeResult2(classnb, input)\n\t\tprint(\"Case #%s: %s\" % (testNB, result))\t\t\n\nexit(0)\n","sub_path":"solutions_1674486_0/Python/Dalmat/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"18167649","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys \nimport os\nimport xlwt\nimport xlrd\nimport pandas as pd\nimport sklearn.linear_model\nregr = sklearn.linear_model.LinearRegression()\nfrom scipy.optimize import curve_fit\nimport operator\n\n#from unpack_and_split_data import extract_xl_BLF, yr_unwrap, split_years_unwrap, consider_lag\n\n#-------------------------------------------------------------------------\n#MODEL FUNCTIONS:\ndef avg_of_funcs(x,funcs):\n return sum([fun(x) for fun in funcs])/len(funcs)\n\n#exponential and logistic\n#def func_exp(x,a,b,c):\n #return a * np.exp(b * x) + c\n#def func_logistic(x,c,a,b,d):\n #return c/(1+a*np.exp(b*x)) + d\ndef func_exp(x,a,b):\n return a * np.exp(b * x) \ndef func_logistic(x,c,a,b,d):\n return c/(1+a*np.exp(b*x)) + d\n\nimport numpy, scipy.optimize\n#polynomial approximations\ndef func_poly(x, *args):\n n, poly = 0,0\n for a in args:\n poly += a*(x**n)\n n += 1\n return poly\ndef func_linear(x,a0,a1):\n return func_poly(x,a0,a1)\ndef func_poly2(x,a0,a1,a2):\n return func_poly(x,a0,a1,a2)\ndef func_poly3(x,a0,a1,a2,a3):\n return func_poly(x,a0,a1,a2,a3)\n\ndef func_poly2_fixed_endpoints(xy1,xy2):\n x1,y1 = xy1[0],xy1[1]\n x2,y2 = xy2[0],xy2[1]\n def polyA(x,a):\n b = (y1-a*x1**2-y2+a*x2**2)/(x1-x2)\n c = y1-a*x1**2-b*x1\n return c+b*x+a**2\n return polyA\n\n#-----------------------------------------------------------------------------\n#PLOTTING FUNCTIONS\ndef model_type(funct):\n classA = [func_linear, func_poly,func_poly2,func_poly3]\n if funct in classA:\n return 'poly'\n else:\n return funct\n\ndef pre_plot(tupl,fit_type='poly'):#,y_axis=None):\n if fit_type=='poly':\n strg = 'f(x) = %5.3f + %5.3fx'\n for i in range(2, len(tupl)):\n strg += ' %5.3fx^'+str(i)\n return strg % tuple(tupl)\n elif fit_type==func_exp:\n return 'f(x) = %5.3fexp(%5.3fx)' % tuple(tupl)\n elif fit_type==func_logistic:\n return ' %5.3f/{1 + %5.3fexp(-%5.3fx)}+%5.3f' % tuple(tupl)\n \n# Create linear regression object\n#regr = sklearn.linear_model.LinearRegression()\n\ndef fit_2sets(X_series,Y_series, fit_func=func_linear, mask=None):\n \n X,Y = X_series, Y_series\n if type(mask)!=type(None):\n Xm = np.ma.masked_array(X,mask=mask)\n Ym = np.ma.masked_array(Y,mask=mask)\n X,Y = Xm.compressed(), Ym.compressed()\n popt, pcov = curve_fit(fit_func, X, Y)#,sigma=sigma)\n def newf(x): return fit_func(x,*popt)\n labe = pre_plot(tuple(popt),model_type(fit_func))\n dic1={}\n dic1.update({'function':newf})\n dic1.update({'parameters':popt})\n dic1.update({'print function':labe})\n return dic1\n\ndef lin_fit(X_series,Y_series, fit_func=func_linear, mask=None):\n X,Y = X_series, Y_series\n if type(mask)!=type(None):\n Xm = np.ma.masked_array(X,mask=mask)\n Ym = np.ma.masked_array(Y,mask=mask)\n X,Y = Xm.compressed(), Ym.compressed()\n slope, intercept, rvalue, pvalue, stderr = linregress(X,Y)\n return slope\n \n #X,Y = X_series, Y_series\n #if type(mask)!=type(None):\n #Xm = np.ma.masked_array(X,mask=mask)\n #Ym = np.ma.masked_array(Y,mask=mask)\n #X,Y = Xm.compressed(), Ym.compressed()\n #popt, pcov = curve_fit(fit_func, X, Y)#,sigma=sigma)\n #def newf(x): return fit_func(x,*popt)\n #labe = pre_plot(tuple(popt),model_type(fit_func))\n #dic1={}\n #dic1.update({'function':newf})\n #dic1.update({'parameters':popt})\n #dic1.update({'print function':labe})\n #return dic1\n\ndef array_span(Xob, function,dense=0,specify_points=0):\n if dense==0 and specify_points==0:\n Xspan = sorted(Xob)\n Yexp = [function(x) for x in Xob]\n return Xspan, Yexp\n else:\n pts = len(Xob) if specify_points==0 else specify_points\n x0,xN = min(Xob),max(Xob)\n Xspan = np.linspace(x0,xN,pts)\n Yexp = [function(x) for x in Xspan]\n return Xspan, Yexp\n\nimport scipy\nfrom scipy.stats import chisquare, linregress\n#def include_chi2(X_series,Y_series, fit_func=func_linear, mask=None):\n #dic1 = fit_2sets(X_series,Y_series, fit_func=fit_func, mask=mask)\n #print(linregress(X_series,Y_series))\n #popt = dic1['parameters']\n #def fun_test(xx): return popt[0]+1*popt[1]*xx\n #Y_exp = [fun_test(xx) for xx in X_series]\n #Yscip_exp = scipy.array(Y_exp)\n #X_ob,Y_ob = scipy.array(X_series), scipy.array(Y_series)\n #chi2 = 0\n #for ii in range(0,len(Y_exp)):\n #chi2 += ((Y_series[ii]-Y_exp[ii])**2)/Y_exp[ii]\n #print(chi2)\n #print(chisquare(Y_ob, f_exp=Yscip_exp))\n\n#def r_squared(X,Y):\n #linregress(X,Y)\n\ndef distance_2pts(p1,p2):\n x1,y1 = p1[0],p1[1]\n x2,y2 = p2[0],p2[1]\n D2 = (x2-x1)**2 + (y2-y1)**2\n D = D2**(1/2)\n return D\n#print(distance_2pts([0,0],[1,3]))\ndef line_2pts(p1,p2):\n x1,y1 = p1[0],p1[1]\n x2,y2 = p2[0],p2[1]\n m = (y2-y1)/(x2-x1)\n b = y1 - m*x1\n return m,b\ndef line_mpt(m,pt):\n x1,y1 = pt[0],pt[1]\n b = y1 - m*x1\n return m,b\n\nimport math\ndef plot_mxb(*m_b_pairs,xwindow=[0,10]):\n xar = np.linspace(xwindow[0],xwindow[1],20)\n ct = 0\n #phis = []\n for mb in m_b_pairs:\n if type(mb[0])!=type([]) and type(mb[1])!=type([]):\n m,b = mb[0],mb[1]\n else:\n if type(mb[0])!=type([]):\n m,b = line_mpt(mb[0],mb[1])\n else:\n m,b = line_2pts(mb[0],mb[1])\n yar = [m*x+b for x in xar]\n plt.plot(xar,yar,label='line '+str(ct+1))\n phi0 = math.degrees(math.atan(m))\n phi = phi0 if phi0>=0 else 360+phi0\n #print(phi)\n if ct>0:\n #print('angles between line '+str(ct)+' and line '+str(ct+1)+':')\n tot_ang = abs(phi-phi_prev)\n ang1 = tot_ang if tot_ang<=180 else tot_ang-180\n ang2 = 180-ang1\n #print(ang1,ang2)\n #print(' ')\n phi_prev = phi\n ct += 1\n plt.xlim(xmin=xwindow[0],xmax=xwindow[1])\n plt.ylim(ymin=xwindow[0],ymax=xwindow[1])\n plt.legend()\n plt.show()\n \n#plot_mxb([3,5],[-1/3,4])\n \n\ndef fit_stats(X_series,Y_series, fit_func=func_linear, mask=None):\n X,Y = X_series,Y_series\n dic1 = fit_2sets(X,Y, fit_func=fit_func, mask=mask)\n #print(dic1['parameters'])\n if type(mask)!=type(None):\n Xm = np.ma.masked_array(X,mask=mask)\n Ym = np.ma.masked_array(Y,mask=mask)\n X,Y = Xm.compressed(), Ym.compressed()\n Yexp = [dic1['function'](xx) for xx in X]\n residuals = [Y[i]-Yexp[i] for i in range(0,len(X))]\n ybar = sum(Y)/len(Y)\n R2_n = [(Yexp[i]-ybar)**2 for i in range(0,len(X))]\n R2_d = [(Y[i]-ybar)**2 for i in range(0,len(X))]\n R2 = sum(R2_n)/sum(R2_d)\n #print(R2)\n\n#observed_values=scipy.array([18,21,16,7,15])\n#expected_values=scipy.array([22,19,44,8,16])\n\n#scipy.stats.chisquare(observed_values, f_exp=expected_values)\n\n \n\n#m = [1,0,0,1,1,1,0,0,1,1,0]\n#x = [1,2,5,8,10,2,3,4,4,5,3]\n#y = [3,4,-1,9,0,1,1,2,3,4,5]\n\n#m = [0,0,0,0]\n#x = [1,2,3,4]\n#y = [1,2,3,7]\n#lin_fit(x,y)\n\n#fit_stats(x,y,fit_func=func_exp)\n#print(sum(x)/4,sum(y)/4)\n\n# with mask m\n#dicc = fit_2sets(x,y,fit_func=func_linear,mask=m)\n#fun = dicc['function']\n#xs, yexp = array_span(x,fun,specify_points=20)\n#Xm = np.ma.masked_array(x,mask=m)\n#Ym = np.ma.masked_array(y,mask=m)\n#plt.plot(Xm,Ym,'bo')\n#plt.plot(xs,yexp,'r',label=dicc['print function'])\n#plt.show()\n\n## with mask of all 1's (no values masked)\n#dicc = fit_2sets(x,y,fit_func=func_linear,mask=[0,0,0,0,0,0,0,0,0,0,0])\n#fun = dicc['function']\n#Xm = np.ma.masked_array(x,mask=[0,0,0,0,0,0,0,0,0,0,0])\n#Ym = np.ma.masked_array(y,mask=[0,0,0,0,0,0,0,0,0,0,0])\n#xs, yexp = array_span(x,fun,specify_points=20)\n#plt.plot(Xm,Ym,'g.')\n#plt.plot(xs,yexp,'y--',label=dicc['print function'])\n\n## with mask=None\n#dicc = fit_2sets(x,y,fit_func=func_linear)\n#fun = dicc['function']\n#xs, yexp = array_span(x,fun,specify_points=20)\n#plt.plot(x,y,'g.')\n#plt.plot(xs,yexp,'y.',label=dicc['print function'])\n##plot_fit(x,y,func_linear)\n#plt.legend()\n#plt.show()\n","sub_path":"basic_fitting_funcs.py","file_name":"basic_fitting_funcs.py","file_ext":"py","file_size_in_byte":8066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"112463470","text":"# Authors: Soledad Galli \n# License: BSD 3 clause\n\nfrom typing import Optional, List, Union\n\nimport pandas as pd\n\nfrom feature_engine.dataframe_checks import _is_dataframe\nfrom feature_engine.imputation.base_imputer import BaseImputer\nfrom feature_engine.variable_manipulation import (\n _find_or_check_categorical_variables,\n _check_input_parameter_variables,\n)\n\n\nclass CategoricalImputer(BaseImputer):\n \"\"\"\n The CategoricalImputer() replaces missing data in categorical variables\n by a string like 'Missing' or any other entered by the user. Alternatively, it\n replaces missing data by the most frequent category.\n\n The CategoricalVariableImputer() works only with categorical variables.\n\n The user can pass a list with the variables to be imputed. Alternatively,\n the CategoricalImputer() will automatically find and select all variables of type\n object.\n\n **Note**\n\n If you want to impute numerical variables with this transformer, you first need to\n cast them as object. It may well be that after the imputation, they are re-casted\n by pandas as numeric. Thus, if planning to do categorical encoding with\n feature-engine to this variables after the imputation, make sure to return the\n variables as object by setting `return_object=True`.\n\n\n Parameters\n ----------\n imputation_method : str, default=missing\n Desired method of imputation. Can be 'frequent' or 'missing'.\n\n fill_value : str, default='Missing'\n Only used when `imputation_method='missing'`. Can be used to set a\n user-defined value to replace the missing data.\n\n variables : list, default=None\n The list of variables to be imputed. If None, the imputer will find and\n select all object type variables.\n\n return_object: bool, default=False\n If working with numerical variables cast as object, decide\n whether to return the variables as numeric or re-cast them as object.\n Note that pandas will re-cast them automatically as numeric after the\n transformation with the mode.\n\n Attributes\n ----------\n imputer_dict_:\n Dictionary with most frequent category or string per variable.\n\n Methods\n -------\n fit:\n Learn more frequent category, or assign string to variable.\n transform:\n Impute missing data.\n fit_transform:\n Fit to the data, than transform it.\n \"\"\"\n\n def __init__(\n self,\n imputation_method: str = \"missing\",\n fill_value: str = \"Missing\",\n variables: Union[None, int, str, List[Union[str, int]]] = None,\n return_object: bool = False,\n ) -> None:\n\n if imputation_method not in [\"missing\", \"frequent\"]:\n raise ValueError(\n \"imputation_method takes only values 'missing' or 'frequent'\"\n )\n\n if not isinstance(fill_value, str):\n raise ValueError(\"parameter 'fill_value' should be string\")\n\n self.imputation_method = imputation_method\n self.fill_value = fill_value\n self.variables = _check_input_parameter_variables(variables)\n self.return_object = return_object\n\n def fit(self, X: pd.DataFrame, y: Optional[pd.Series] = None):\n \"\"\"\n Learn the most frequent category if the imputation method is set to frequent.\n\n Parameters\n ----------\n X : pandas dataframe of shape = [n_samples, n_features]\n The training dataset.\n\n y : pandas Series, default=None\n y is not needed in this imputation. You can pass None or y.\n\n Raises\n ------\n TypeError\n - If the input is not a Pandas DataFrame.\n - If any user provided variable is not categorical\n ValueError\n If there are no categorical variables in the df or the df is empty\n\n Returns\n -------\n self\n \"\"\"\n\n # check input dataframe\n X = _is_dataframe(X)\n\n # find or check for categorical variables\n self.variables = _find_or_check_categorical_variables(X, self.variables)\n\n if self.imputation_method == \"missing\":\n self.imputer_dict_ = {var: self.fill_value for var in self.variables}\n\n elif self.imputation_method == \"frequent\":\n self.imputer_dict_ = {}\n\n for var in self.variables:\n mode_vals = X[var].mode()\n\n # careful: some variables contain multiple modes\n if len(mode_vals) == 1:\n self.imputer_dict_[var] = mode_vals[0]\n else:\n raise ValueError(\n \"Variable {} contains multiple frequent categories.\".format(var)\n )\n\n self.input_shape_ = X.shape\n\n return self\n\n def transform(self, X: pd.DataFrame) -> pd.DataFrame:\n # bring functionality from the BaseImputer\n X = super().transform(X)\n\n # add additional step to return variables cast as object\n if self.return_object:\n X[self.variables] = X[self.variables].astype(\"O\")\n\n return X\n\n # Ugly work around to import the docstring for Sphinx, otherwise not necessary\n transform.__doc__ = BaseImputer.transform.__doc__\n","sub_path":"feature_engine/imputation/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"438717447","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nfrom scrapy.http import Request\nimport json\nimport re\nimport datetime as dt\nimport pymysql\nfrom ..process_datetime import to_datetime, to_datetime_mintime\nfrom ..items import BlogTextItem\nfrom .. import settings\nimport logging\nimport redis\nimport time\n\nsort_map = {u'实时': u'61', u'热门': u'60'}\nlogger = logging.getLogger(__name__)\n\n# typeDt = {\n# '综合': '1', '用户': '3', '实时': '61', '关注': '62', '视频': '64', '文章': '21',\n# '图片': '63', '热门': '60', '印象': '44', '话题': '38', '主页': '32',\n# }\n\n\nclass SinaUnloginBlogtextSpider(scrapy.Spider):\n name = 'sina_unlogin_blogtext'\n custom_settings = {\n 'DOWNLOAD_DELAY': 0.2,\n 'CONCURRENT_REQUESTS': 8,\n 'DOWNLOADER_MIDDLEWARES': {\n 'weibo.middlewares.RandomProxyMiddleware': 543,\n 'weibo.middlewares.RandomUserAgentMiddleware': 543,\n },\n 'SPIDER_MIDDLEWARES': {'weibo.middlewares.FilterBlogtextItemMiddleware': 543},\n 'ITEM_PIPELINES': {'weibo.pipelines.WeiboToSqlPipeline': 300},\n }\n # 存储采集到的 Item 的数据库表\n tablename = 'weibo_sina_unlogin_blogtext'\n # 用于提取关键字进行采集的数据库表\n main_keyword_table = 'main_keyword'\n # redis 中存放当前 json.dumps([main, keywords]) 的键\n main_keyword_queue = 'weibo:sina:mk'\n # redis 中存放全部 blog_id 的 set 型 key\n blog_id_queue = 'weibo:sina:unlogin:blog_id'\n # redis 中存放 blog_id 的复制key, 用于采集评论\n blog_id_queue_copy = 'weibo:sina:unlogin:blog_id:copy'\n # 根据 main,keyword,blog_id 字段对 item 去重\n blogtext_item_queue = 'weibo:sina:unlogin:blogtext_item'\n\n def __init__(self, sorttype=u'实时', **kwargs):\n \"\"\"\n :param sorttype: 微博搜索的类型\n :param kwargs:\n \"\"\"\n super(SinaUnloginBlogtextSpider, self).__init__(**kwargs)\n self.sort = sort_map[sorttype]\n self.sorttype = sorttype\n # 如果没有搜索的开始时间则设置为当天最小时间\n if kwargs.get('starttime') is not None:\n self.starttime = to_datetime(self.starttime)\n else:\n self.starttime = to_datetime_mintime(dt.datetime.now())\n # 如不指定结束时间,则设置为当前时间\n if kwargs.get('endtime') is not None:\n self.endtime = to_datetime(kwargs.get('endtime'))\n else:\n self.endtime = dt.datetime.now() # 当前时间\n self.kwargs = kwargs\n\n if self.starttime > self.endtime:\n raise Exception('starttime should be smaller then endtime')\n\n logger.info('\\n\\n====== starttime:{} endtime:{} ==========\\n'.format(self.starttime, self.endtime))\n\n self.mysqlConn = pymysql.connect(\n host=settings.MYSQL_HOST,\n port=settings.MYSQL_PORT,\n db=settings.MYSQL_DB,\n user=settings.MYSQL_USER,\n password=settings.MYSQL_PASS,\n charset='utf8',\n )\n self.cursor = self.mysqlConn.cursor()\n\n self.redisConn = redis.StrictRedis(\n host=settings.REDIS_HOST,\n port=settings.REDIS_PORT,\n password=settings.REDIS_PASS,\n decode_responses=True\n )\n\n def start_requests(self):\n # 传递参数 main:keywords\n if self.kwargs.get('mk') is not None:\n # 补数 main:keyword\n main = self.kwargs.get('mk').split(':')[0]\n keyword = self.kwargs.get('mk').split(':')[1]\n self.main_keyword_queue = 'unicorn:weibo:sina:company:{}'.format(int(time.time()))\n self.redisConn.sadd(self.main_keyword_queue, json.dumps([main, keyword], ensure_ascii=False))\n else:\n # 从数据库中获取全部被监控的keyword\n self.mysqlConn.ping()\n sqlslstr = u\"SELECT main,keyword FROM {}\".format(self.main_keyword_table)\n watch_mkw_count = self.cursor.execute(sqlslstr) # select 得到的条数\n watch_mkw = self.cursor.fetchall()\n self.cursor.close()\n self.mysqlConn.close()\n if watch_mkw_count == 0: # 若找不到被监控的keyword, 则结束爬虫\n return\n self.redisConn.sadd(self.main_keyword_queue, *[json.dumps(mk, ensure_ascii=False) for mk in watch_mkw])\n\n while True:\n one_main_keyword = self.redisConn.spop(self.main_keyword_queue)\n if one_main_keyword is None:\n break\n main, keyword = json.loads(one_main_keyword)\n for kw in [kw.strip() for kw in re.sub(',', ',', keyword).split(',')]:\n if re.search(\"^\\d{10}$\", kw): # 根据 uid 进行采集\n base_url = u\"https://m.weibo.cn/api/container/getIndex?containerid=107603{keyword}&page={page}\"\n get_blog_data = u\"json_text['data']['cards']\"\n get_next_page_link = u\"response.meta['base_url'].format(\" \\\n u\"keyword=response.meta['keyword'], page=response.meta['page'])\"\n start_url = base_url.format(keyword=kw, page='1')\n else: # 根据搜索 关键词 进行采集\n base_url = u\"https://m.weibo.cn/api/container/getIndex?containerid=100103type%3D\" \\\n u\"{sort}%26q%3D{keyword}%26t%3D0&page_type=searchall&page={page}\"\n get_blog_data = u\"json_text['data']['cards'][0]['card_group']\"\n get_next_page_link = u\"response.meta['base_url'].format(keyword=response.meta[\" \\\n u\"'keyword'],sort=self.sort, page=response.meta['page'])\"\n start_url = base_url.format(keyword=kw, sort=self.sort, page='1')\n yield Request(\n url=start_url,\n meta={'page': 1, 'base_url': base_url, 'get_blog_data': get_blog_data,\n 'get_next_page_link': get_next_page_link, 'keyword': kw, 'main': main,\n 'unfit_itemcount': 0, 'unok_urlcount': 0})\n\n def parse(self, response):\n json_text = json.loads(response.text)\n if json_text['ok'] == 0:\n response.meta['unok_urlcount'] += 1\n if response.meta['unok_urlcount'] > 5: # 如果连续五页都没有微博内容, 则放回 None\n return\n else:\n response.meta['unok_urlcount'] = 0\n blog_data = eval(response.meta['get_blog_data']) # array, 微博页面列表\n for i in range(len(blog_data)):\n # 判断是否是微博,如果不是则跳过\n if 'mblog' not in blog_data[i].keys():\n continue\n\n pubtime = to_datetime(blog_data[i]['mblog']['created_at']) # 该条微博的发布时间\n\n # stype为实时,微博排序是按时间降序的\n if pubtime < self.starttime and self.sorttype == u'实时':\n # 这里做一个check_count的检查是因为虽然按照时间降序,但有些时候会某一页会有一两个小日期的微博混入,\n # 所以这里做判断如果总共找到20个小日期的, 则返回None。\n response.meta['unfit_itemcount'] += 1\n if response.meta['unfit_itemcount'] > 20:\n return\n else:\n continue\n\n elif pubtime < response.meta['starttime'] or pubtime > self.endtime:\n continue\n\n item = BlogTextItem()\n item['main'] = response.meta['main']\n item['keyword'] = response.meta['keyword'] # str, 搜索关键词\n # item['userinfo'] = blog_data[i]['mblog']['user'] # dict, 博主用户信息\n item['blog_uid'] = blog_data[i]['mblog']['user']['id'] # int, 博主用户ID, 例: 1878335471\n item['blog_id'] = blog_data[i]['mblog']['id'] # str, 该条微博的id, 例:\"4261282863313851\"\n # mid = blog_data[i]['mblog']['mid'] # str, 一般与id一样, 用于采集评论, 例: 4261282863313851\"\n # 微博标题, str\n if 'page_info' in blog_data[i]['mblog'].keys():\n item['blog_title'] = blog_data[i]['mblog']['page_info'].get('page_title')\n # 微博发布时��(有:xx分钟前,xx小时前,月(01-12)-日(01-31),年-月(01-12)-日(01-31))\n item['blog_pubTime'] = to_datetime(blog_data[i]['mblog']['created_at']) # string\n # 微博正文, 太长显示不完整需到微博详细页面抓取\n item['blog_text'] = blog_data[i]['mblog']['text'] # string\n\n item['blog_link'] = 'https://m.weibo.cn/status/' + item['blog_id'] # 该条微博详细链接\n\n # blogData[i]['mblog']['retweeted_status'] # dict 博主转发的内容(内容字段跟微博差不多), 非必填\n if 'retweeted_status' in blog_data[i]['mblog'].keys():\n if blog_data[i]['mblog']['retweeted_status'].get('isLongText') is True:\n repost_text = blog_data[i]['mblog']['retweeted_status']['longText']['longTextContent']\n else:\n repost_text = blog_data[i]['mblog']['retweeted_status']['text']\n item['blog_text'] = item['blog_text'] + u' | 转发了微博:' + repost_text\n # #item['retweeted_userinfo'] = blog_data[i]['mblog']['retweeted_status']['user']\n # item['retweeted_uid'] = blog_data[i]['mblog']['retweeted_status']['user']['id']\n # item['retweeted_blogId'] = blog_data[i]['mblog']['retweeted_status']['id']\n # item['retweeted_blogText'] = blog_data[i]['mblog']['retweeted_status']['text']\n # item['retweeted_pubTime'] = to_datetime(blog_data[i]['mblog']['retweeted_status']['created_at'])\n item['repost_count'] = blog_data[i]['mblog']['reposts_count'] # int, 该条微博被转发次数\n item['comment_count'] = blog_data[i]['mblog']['comments_count'] # int, 该条微博被评论条数\n item['attitude_count'] = blog_data[i]['mblog']['attitudes_count'] # int, 该条微博被点赞次数\n # string, 该条微博中的视屏被观看次数(3334次观看)\n # item['obj_ext'] = process_obj_ext(blog_data[i]['mblog'].get('obj_ext'))\n # True: 表示微博正文字数超出限制, 显示不完整; False: 表示正文显示完整\n is_longtext = blog_data[i]['mblog']['isLongText'] # boolean\n if is_longtext is True:\n # 太长的微博正文抓取接口api\n detail_api = 'https://m.weibo.cn/statuses/extend?id=' + item['blog_id']\n yield Request(detail_api, callback=self.parse_blogtext, meta={'item': item})\n else:\n yield item\n\n response.meta['page'] += 1\n next_page_link = eval(response.meta['get_next_page_link'])\n yield Request(next_page_link, meta=response.meta)\n\n def parse_blogtext(self, response):\n item = response.meta['item']\n if u' | 转发了微博:' in item['blog_text']:\n item['blog_text'] = json.loads(response.text)['data']['longTextContent'] + u' | 转发了微博:' + \\\n item['blog_text'].split(u' | 转发了微博:')[-1]\n else:\n item['blog_text'] = json.loads(response.text)['data']['longTextContent']\n yield item\n\n# def process_obj_ext(obj_ext):\n# if obj_ext is not None:\n# if re.search(u'\\d+亿次', obj_ext):\n# obj_ext = int(re.findall(u'(\\d+)亿', obj_ext)[0]) * (10**8)\n# elif re.search(u'\\d+万次', obj_ext):\n# obj_ext = int(re.findall(u'(\\d+)万', obj_ext)[0]) * (10 ** 4)\n# elif re.search(u'\\d+次', obj_ext):\n# obj_ext = int(re.findall(u'(\\d+)次', obj_ext)[0])\n# return obj_ext\n","sub_path":"微博/weibo/weibo/spiders/sina_unlogin_blogtext.py","file_name":"sina_unlogin_blogtext.py","file_ext":"py","file_size_in_byte":12205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"258574996","text":"# -*- coding: utf-8 -*-\nimport time\nfrom fixture.vacancy import Vacancy\n\n\ndef test_check_vacancy_email(app):\n wd = app.wd\n vacancy = Vacancy(\n title=\"Тест создания вакансии %s\" % int(time.time()),\n area=\"Кино\", role=\"Агент\", location=\"Амстердам\",\n description=\"Тест создания вакансии\",\n email=\"vacancy_testing@mail.com\", company=\"Sample Company\")\n\n app.session.login_as(app.users[\"user1\"])\n app.vacancy.create_and_publish(vacancy)\n\n app.session.login_as(app.users[\"user2\"])\n app.vacancy.respond_to(vacancy)\n\n app.session.login_as(app.users[\"admin\"])\n app.open_page(\"admin/emailQueue\")\n assert \"vacancy_testing@mail.com\" == wd.find_element_by_xpath(\"//tbody/tr[1]/td[4]\").text\n","sub_path":"tests/check_vacancy_email.py","file_name":"check_vacancy_email.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"579414566","text":"class Tamagotchi:\n nombre=\"\"\n hambre=0\n animo=0\n energia=0\n\n def __init__(self,nombre,hambre,animo,energia):\n self.nombre=nombre\n self.hambre=hambre\n self.animo=animo\n self.energia=energia\n \n def jugar(self):\n self.animo+=1\n self.energia-=1\n\n def alimentar(self):\n self.animo+=1\n self.hambre-=1\n\n def dormir(self):\n self.hambre+=1\n self.energia+=1\n\n def pasar(self):\n self.animo-=1\n self.hambre+=1\n self.energia-=1\n \n def __str__(self):\n return (\"Nombre:%s\\tNiveles: Hambre:%d\\tAnimo:%d\\tEnergia:%d \") %(self.nombre,self.hambre,self.animo, self.energia)\n\n# Programa Principal\n\nt=Tamagotchi(\"Tamagotchito\",10,10,10)\nt.dormir()\nt.jugar()\nt.alimentar()\nt.pasar()\nprint(t)\n\n\"\"\"\n# menu\nopcion=999 \nwhile opcion != 0:\n print(\"\\t\\t\\tMenu de opciones\")\n print(\"\\t\\t\\t0 Salir\")\n print(\"\\t\\t\\t1 Crear tamagotchi\")\n print(\"\\t\\t\\t2 Jugar\")\n print(\"\\t\\t\\t3 Alimentar\")\n print(\"\\t\\t\\t4 Pasar tiempo\")\n print(\"\\t\\t\\t5 Dormir\")\n \n if t.energia<=0:\n print(\"*********************Game over**************************\")\n opcion=0\n else:\n opcion=int(input(\"\\t\\t\\tIngrese una opcion:\"))\n \n if opcion==0:\n print(\"*********************Chau********************************\")\n elif opcion==1:\n nom=input(\"Ingrese nombre:\")\n t=Tamagotchi(nom,10,10,10)\n print(t) \n elif opcion==2: #jugar\n t.jugar()\n print(t)\n elif opcion==3: #Alimentar\n t.alimentar()\n print(t)\n elif opcion==4: # Pasar tiempo\n t.pasar()\n print(t)\n elif opcion==5: # Dormir\n t.dormir()\n print(t)\n else: #error\n print(\"opcion erronea\")\n \n\"\"\"","sub_path":"tamagotchi.py","file_name":"tamagotchi.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"153048080","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 15 15:04:52 2019\n\n@author: ahmetkaanipekoren\n\"\"\"\n\n\n\ndef data_preparation():\n df = pd.read_csv(\"heart.csv\")\n\n return df\n\n\ndef normalization(df):\n \n df_norm = (df-df.min()) / (df.max() - df.min())\n \n return df_norm\n\n\ndef x_y_values(df):\n df_y = df.loc[:,\"target\"]\n df_x = df.drop([\"target\"],axis=1)\n \n \n return df_x,df_y\n\n \ndef train_test(df_x,df_y):\n \n train_x,test_x,train_y,test_y = train_test_split(df_x,df_y,test_size = 0.2,random_state=42)\n\n train_x,test_x,train_y,test_y = np.array(train_x),np.array(test_x),np.array(train_y),np.array(test_y)\n \n return train_x,test_x,train_y,test_y\n\n\n\ndef eig_pairs(eigen_value,eigen_vector):\n \n eigen_pairs = []\n for i in range(len(eigen_value)):\n eigen_pairs.append((np.abs(eigen_value[i]), eigen_vector[:,i]))\n\n eigen_pairs = sorted(eigen_pairs,key=lambda k: k[0], reverse=True)\n return eigen_pairs\n\n \ndef cumulative_variance(eigenvalues):\n \n sum_eigen_values = sum(eigenvalues)\n cum_var_list = []\n for i in eigenvalues:\n cum_var_list.append(i/sum_eigen_values)\n \n cum_var = np.cumsum(cum_var_list)\n \n #plt.plot(cum_var)\n #plt.grid(True)\n #plt.show()\n \n return cum_var\n\n\ndef classification(df_x,eigenpairs):\n \n reduced_matrix = np.hstack((eigenpairs[0][1].reshape(13,1),eigenpairs[1][1].reshape(13,1)))\n \n new_data_set = np.dot(df_x,reduced_matrix)\n\n # plt.plot(new_data_set,\"ko\")\n # plt.show() \n \n return new_data_set\n \n \ndef drawing_new_points(df_y,data_set):\n \n sum_red = 0,0\n sum_green = 0,0\n count_red = 0\n count_green = 0\n for i in range(len(df_y)):\n if df_y[i] == 1 :\n plt.scatter(data_set.T[0][i],data_set.T[1][i], color=\"green\")\n sum_red = sum_red + data_set[i]\n count_green += 1\n elif df_y[i] == 0:\n plt.scatter(data_set.T[0][i],data_set.T[1][i], color =\"red\", alpha = 0.2)\n sum_green = sum_green + data_set[i]\n count_red += 1\n \n \n plt.show()\n \n \n return sum_green / count_green , sum_red / count_red\n \n \n\ndef svm_classifier(x_train,y_train,x_test,y_test):\n from sklearn.svm import SVC\n \n svm = SVC(random_state = 1, degree=2)\n svm.fit(x_train,y_train)\n \n acc_svm = svm.score(x_test,y_test)\n \n\n \n return acc_svm\n\n\n\n\nif __name__ == \"__main__\":\n import numpy as np\n import pandas as pd\n from sklearn.model_selection import train_test_split\n import matplotlib.pyplot as plt\n df = data_preparation()\n df_norm = normalization(df)\n df_x,df_y = x_y_values(df_norm)\n \n cov_mat = np.cov(df_x.T)\n eigenvalues,eigenvectors = np.linalg.eig(cov_mat)\n eigen_pairs = eig_pairs(eigenvalues,eigenvectors)\n cum_var = cumulative_variance(eigenvalues)\n new_data_set = classification(df_x,eigen_pairs)\n mean_green, mean_red = drawing_new_points(df_y,new_data_set)\n \n train_x,test_x,train_y,test_y = train_test(new_data_set,df_y)\n acc_svm = svm_classifier(train_x,train_y,test_x,test_y)\n \n \n \n\n\n","sub_path":"heart_disease_pca.py","file_name":"heart_disease_pca.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"88523019","text":"from lua_token import TokenKind\nimport lua_exp\nfrom lua_value import LuaValue\n\n\nclass Optimizer:\n # or\n @staticmethod\n def optimize_logical_or(exp):\n if Optimizer.is_true(exp.exp1):\n # true or x => true\n return exp.exp1\n if Optimizer.is_false(exp.exp1) and not Optimizer.is_var_arg_or_func_call(exp.exp2):\n # false or x => x\n return exp.exp2\n return exp\n\n # and\n @staticmethod\n def optimize_logical_and(exp):\n if Optimizer.is_false(exp.exp1):\n # false and x => false\n return exp.exp1\n if Optimizer.is_true(exp.exp1) and not Optimizer.is_var_arg_or_func_call(exp.exp2):\n # true and x => x\n return exp.exp2\n return exp\n\n # & | ~ << >>\n @staticmethod\n def optimize_bitwise_binary_op(exp):\n i, oki = Optimizer.cast_to_int(exp.exp1)\n j, okj = Optimizer.cast_to_int(exp.exp2)\n if oki and okj:\n if exp.op == TokenKind.OP_BAND:\n return lua_exp.IntegerExp(exp.line, i & j)\n if exp.op == TokenKind.OP_BOR:\n return lua_exp.IntegerExp(exp.line, i | j)\n if exp.op == TokenKind.OP_BXOR:\n return lua_exp.IntegerExp(exp.line, i ^ j)\n if exp.op == TokenKind.OP_SHL:\n return lua_exp.IntegerExp(exp.line, i << j)\n if exp.op == TokenKind.OP_SHR:\n return lua_exp.IntegerExp(exp.line, i >> j)\n return exp\n\n # + - * / // %\n @staticmethod\n def optimize_arith_binary_op(exp):\n if isinstance(exp.exp1, lua_exp.IntegerExp):\n if isinstance(exp.exp2, lua_exp.IntegerExp):\n if exp.op == TokenKind.OP_ADD:\n return lua_exp.IntegerExp(exp.line, exp.exp1.val + exp.exp2.val)\n if exp.op == TokenKind.OP_SUB:\n return lua_exp.IntegerExp(exp.line, exp.exp1.val - exp.exp2.val)\n if exp.op == TokenKind.OP_MUL:\n return lua_exp.IntegerExp(exp.line, exp.exp1.val * exp.exp2.val)\n if exp.op == TokenKind.OP_IDIV:\n if exp.exp2.val != 0:\n return lua_exp.IntegerExp(exp.line, exp.exp1.val // exp.exp2.val)\n if exp.op == TokenKind.OP_MOD:\n if exp.exp2.val != 0:\n return lua_exp.IntegerExp(exp.line, exp.exp1.val % exp.exp2.val)\n\n f, okf = Optimizer.cast_to_float(exp.exp1)\n g, okg = Optimizer.cast_to_float(exp.exp2)\n if okf and okg:\n if exp.op == TokenKind.OP_ADD:\n return lua_exp.IntegerExp(exp.line, f + g)\n if exp.op == TokenKind.OP_SUB:\n return lua_exp.IntegerExp(exp.line, f - g)\n if exp.op == TokenKind.OP_MUL:\n return lua_exp.IntegerExp(exp.line, f * g)\n if exp.op == TokenKind.OP_DIV:\n if g != 0:\n return lua_exp.IntegerExp(exp.line, f / g)\n if exp.op == TokenKind.OP_IDIV:\n if g != 0:\n return lua_exp.IntegerExp(exp.line, f // g)\n if exp.op == TokenKind.OP_MOD:\n if g != 0:\n return lua_exp.IntegerExp(exp.line, f % g)\n if exp.op == TokenKind.OP_POW:\n return lua_exp.IntegerExp(exp.line, f ** g)\n return exp\n\n # ^\n @staticmethod\n def optimize_pow(exp):\n if isinstance(exp, lua_exp.BinopExp):\n if exp.op == TokenKind.OP_POW:\n exp.exp2 = Optimizer.optimize_pow(exp.exp2)\n return Optimizer.optimize_arith_binary_op(exp)\n return exp\n\n # - not ~\n @staticmethod\n def optimize_unary_op(exp):\n if exp.op == TokenKind.OP_UNM:\n return Optimizer.optimize_unm(exp)\n if exp.op == TokenKind.OP_NOT:\n return Optimizer.optimize_not(exp)\n if exp.op == TokenKind.OP_BNOT:\n return Optimizer.optimize_bnot(exp)\n return exp\n\n @staticmethod\n def optimize_unm(exp):\n if isinstance(exp.exp, lua_exp.IntegerExp):\n exp.exp.val = -exp.exp.val\n return exp.exp\n if isinstance(exp.exp, lua_exp.FloatExp):\n if exp.exp.val != 0:\n exp.exp.val = -exp.exp.val\n return exp.val\n return exp\n\n # not\n @staticmethod\n def optimize_not(exp):\n if isinstance(exp.exp, lua_exp.NilExp) or isinstance(exp.exp, lua_exp.FalseExp):\n return lua_exp.TrueExp(exp.line)\n if isinstance(exp.exp, lua_exp.TrueExp) or isinstance(exp.exp, lua_exp.FloatExp) or \\\n isinstance(exp.exp, lua_exp.StringExp):\n return lua_exp.FalseExp(exp.line)\n return exp\n\n # ~\n @staticmethod\n def optimize_bnot(exp):\n if isinstance(exp.exp, lua_exp.IntegerExp):\n exp.exp.val = ~exp.exp.val\n return exp.exp.val\n if isinstance(exp.exp, lua_exp.FloatExp):\n i = LuaValue.float2integer(exp.exp.val)\n if i is not None:\n return lua_exp.IntegerExp(exp.exp.line, ~i)\n return exp\n\n # false\n @staticmethod\n def is_false(exp):\n if isinstance(exp, lua_exp.FalseExp) or isinstance(exp, lua_exp.NilExp):\n return True\n return False\n\n # true\n @staticmethod\n def is_true(exp):\n if isinstance(exp, lua_exp.TrueExp) or isinstance(exp, lua_exp.IntegerExp) or \\\n isinstance(exp, lua_exp.FloatExp) or isinstance(exp, lua_exp.StringExp):\n return True\n return False\n\n @staticmethod\n def is_var_arg_or_func_call(exp):\n if isinstance(exp, lua_exp.VarArgExp) or isinstance(exp, lua_exp.FuncCallExp):\n return True\n return False\n\n @staticmethod\n def cast_to_int(exp):\n if isinstance(exp, lua_exp.IntegerExp):\n return exp.val, True\n if isinstance(exp, lua_exp.FloatExp):\n i = LuaValue.float2integer(exp.val)\n return i, i is not None\n return 0, False\n\n @staticmethod\n def cast_to_float(exp):\n if isinstance(exp, lua_exp.IntegerExp):\n return float(exp.val), True\n if isinstance(exp, lua_exp.FloatExp):\n return exp.val, True\n return 0, False\n","sub_path":"code/python/ch15_16/src/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":6304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"509145371","text":"#!/usr/bin/python3\n'''\nPython script that takes in a URL, sends a request to the\nURL and displays the value of the X-Request-Id variable found\nin the header of the response.\n'''\n\nif __name__ == \"__main__\":\n import urllib.request\n import sys\n url_arg = urllib.request.Request(sys.argv[1])\n with urllib.request.urlopen(url_arg) as response:\n display = response.getheader('X-Request-Id')\n print(display)\n","sub_path":"0x11-python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"403149988","text":"#!/usr/bin/env python2\nimport numpy as np\nimport caffe\n\n\nclass EuclideanLossLayer(caffe.Layer):\n \"\"\"\n Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer\n to demonstrate the class interface for developing layers in Python.\n \"\"\"\n def setup(self, bottom, top):\n # check input pair\n if len(bottom) != 2:\n raise Exception(\"Need two inputs to compute distance.\")\n if len(top) != 1:\n raise Exception(\"Must output \\\"loss\\\" blob.\")\n\n def reshape(self, bottom, top):\n # check input dimensions match\n if bottom[0].data.shape != bottom[1].data.shape:\n raise Exception(\"Inputs must have the same dimension.\")\n # difference is shape of inputs\n self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)\n # loss output is scalar\n top[0].reshape(1)\n\n def forward(self, bottom, top):\n self.diff[...] = bottom[0].data - bottom[1].data\n top[0].data[...] = (self.diff**2).sum() / bottom[0].num / 2.\n\n def backward(self, top, propagate_down, bottom):\n for i in range(2):\n if propagate_down[i]:\n sign = 1 if i == 0 else -1\n bottom[i].diff[...] = sign * top[0].diff / bottom[i].num * self.diff\n","sub_path":"caffe/pyloss_euclidean.py","file_name":"pyloss_euclidean.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"223156557","text":"import re\nimport math\nimport io\nimport sys\n\n\ndef find_closest_particle(particles):\n closest = None\n for index, particle in enumerate(particles):\n a = sum(abs(val) for val in particle['a'])\n s = sum(abs(val) for val in particle['s'])\n p = sum(abs(val) for val in particle['p'])\n if (\n closest is None or\n closest['a'] > a or\n closest['a'] == a and closest['s'] > s or\n closest['a'] == a and closest['s'] == s and closest['p'] > p\n ):\n closest = {'index': index, 'a': a, 's': s, 'p': p}\n\n return closest\n\n\ndef get_particles(stream):\n particles = []\n reg = 'p=<([^,]+),([^,]+),([^>]+)>, v=<([^,]+),([^,]+),([^>]+)>, a=<([^,]+),([^,]+),([^>]+)>'\n for line in stream.readlines():\n p = re.search(reg, line.rstrip('\\n'))\n particle = (\n (int(p.group(1)), int(p.group(2)), int(p.group(3))),\n (int(p.group(4)), int(p.group(5)), int(p.group(6))),\n (int(p.group(7)), int(p.group(8)), int(p.group(9)))\n )\n particles.append(particle)\n return particles\n\n\ndef solve_equation(a, b, c):\n t = None\n if a != 0:\n d = (b ** 2) - 4 * a * c\n if d >= 0:\n t = max(\n (-b - math.sqrt(d)) / (2 * a),\n (-b + math.sqrt(d)) / (2 * a)\n )\n elif b != 0:\n t = -c / b\n t = t if t >= 0 else None\n elif c == 0:\n t = c\n\n return t\n\n\ndef remove_collisions(particles):\n nb_particles = len(particles)\n particles_indexes = set(range(len(particles)))\n collisions = {}\n for i, p1 in enumerate(particles):\n for j in range(i + 1, nb_particles):\n p2 = particles[j]\n ax, bx, cx = [p1[x][0] - p2[x][0] for x in ['a', 's', 'p']]\n ay, by, cy = [p1[y][1] - p2[y][1] for y in ['a', 's', 'p']]\n az, bz, cz = [p1[z][2] - p2[z][2] for z in ['a', 's', 'p']]\n collision = {\n c\n for c in [\n solve_equation(ax, bx, cx),\n solve_equation(ay, by, cy),\n solve_equation(az, bz, cz)\n ]\n if c is not None\n }\n\n if len(collision) > 1 and 0 in collision:\n collision -= {0}\n if len(collision) == 1:\n collision = str(collision.pop())\n if collision in collisions:\n collisions[collision].add(i)\n collisions[collision].add(j)\n else:\n collisions[collision] = {i, j}\n\n for collision_time in sorted(collisions, key=lambda collision: collision[0]):\n particles_colliding = collisions[collision_time]\n if particles_colliding.issubset(particles_indexes):\n particles_indexes -= particles_colliding\n\n return particles_indexes\n\n\n# test_data_1 = \"\"\"\\\n# p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0>\n# p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>\n# \"\"\"\n# test_data_2 = \"\"\"\\\n# p=< 3,0,0>, v=< 2,0,0>, a=<-2,0,0>\n# p=< 4,0,0>, v=< 0,0,0>, a=<-2,0,0>\n# \"\"\"\n# test_data_3 = \"\"\"\\\n# p=< 3,0,0>, v=< 2,0,0>, a=<-1,0,0>\n# p=< 4,0,0>, v=< 2,0,0>, a=<-2,0,0>\n# \"\"\"\n# particles_1 = get_particles(io.StringIO(test_data_1))\n# assert find_closest_particle(particles_1)['index'] == 0\n# particles_2 = get_particles(io.StringIO(test_data_2))\n# assert find_closest_particle(particles_2)['index'] == 1\n# particles_3 = get_particles(io.StringIO(test_data_3))\n# assert find_closest_particle(particles_3)['index'] == 0\n#\n# test_data_collisions = \"\"\"\\\n# p=<-6,0,0>, v=< 3,0,0>, a=< 0,0,0>\n# p=<-4,0,0>, v=< 2,0,0>, a=< 0,0,0>\n# p=<-2,0,0>, v=< 1,0,0>, a=< 0,0,0>\n# p=< 3,0,0>, v=<-1,0,0>, a=< 0,0,0>\n# \"\"\"\n# particles = get_particles(io.StringIO(test_data_collisions))\n# assert remove_collisions(particles) == {3}\n#\n# test_data_collisions = \"\"\"\\\n# p=<-6,6,0>, v=< 3,-3,0>, a=< 0,0,0>\n# p=<-4,0,0>, v=< 2,0,0>, a=< 0,0,0>\n# p=<0,-2,0>, v=< 0,1,0>, a=< 0,0,0>\n# p=< 3,0,0>, v=<-1,0,0>, a=< 0,0,0>\n# \"\"\"\n# particles = get_particles(io.StringIO(test_data_collisions))\n# assert remove_collisions(particles) == {3}\n#\nparticles = get_particles(sys.stdin)\n# print(find_closest_particle(particles)['index'])\n# print(len(remove_collisions(particles)))\n\nfrom collections import Counter\n\ndef run_p(p):\n (x, y, z), (vx, vy, vz), (ax, ay, az) = p\n vx, vy, vz = vx + ax, vy + ay, vz + az\n x, y, z = x + vx, y + vy, z + vz\n return (x, y, z), (vx, vy, vz), (ax, ay, az)\n\nfor i in range(10000):\n c = Counter(x[0] for x in particles)\n particles = [run_p(x) for x in particles if c[x[0]] == 1]\n print(len(particles))\n","sub_path":"2017/day20.py","file_name":"day20.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"77760623","text":"\n\"\"\"\nProblem 2\n\nAssume s is a string of lower case characters.\n\nWrite a program that prints the number of times the string 'bob'\noccurs in s. For example, if s = 'azcbobobegghakl',\nthen your program should print\n\nNumber of times bob occurs is: 2\n\n\n\n\"\"\"\n#define s\ns = 'bjobobqvoboobooboobob'\n\nnumBob = 0\nmyId = 0\n\nfor char in s:\n if s[myId:myId+3]==\"bob\":\n #if s[myId:myId]==\"b\" and s[myId:myId+1]==\"o\"and s[myId:myId+2]==\"b\" \n numBob += 1\n print(\"myId : \" + str(myId) + \", numBob : \" + str(numBob) )\n myId += 1\n\nprint(len(s))\nprint('Number of times \"bob\" occurs is : ' + str(numBob))\n\n\n","sub_path":"Python_week1/week1_pbset1_pb2.py","file_name":"week1_pbset1_pb2.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"501834769","text":"import sys\n\nsys.stdin = open('input_4871.txt', \"r\")\nsys.stdout = open('output_4871.txt', \"w\")\nT = int(input())\nfor t in range(1, T+1):\n V, E = map(int, input().split())\n G = [[] for x in range(V + 1)]\n\n for i in range(E):\n u, v = map(int, input().split())\n G[u].append(v)\n\n S = list(map(int, input().split()))\n stack = [S[0]]\n result = [S[0]]\n v = S[0]\n while len(stack) > 0:\n for x in G[v]:\n if x not in result:\n stack.append(x)\n num = stack.pop()\n if num not in result:\n result.append(num)\n v = num\n\n if S[0] in result and S[1] in result:\n print(f'#{t} 1')\n else:\n print(f'#{t} 0')\n\n\n\n","sub_path":"SWEA/4871_그래프 경로.py","file_name":"4871_그래프 경로.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"276022056","text":"def register(fix_im_fname, mov_im_fname, dest_dir):\n import os\n import cv2\n import numpy as np\n from .models import ACRegNet\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n import tensorflow as tf\n\n mov_im_nda = cv2.imread(mov_im_fname, cv2.IMREAD_GRAYSCALE)\n fix_im_nda = cv2.imread(fix_im_fname, cv2.IMREAD_GRAYSCALE)\n if mov_im_nda.shape != fix_im_nda.shape or \\\n mov_im_nda.shape[0] != mov_im_nda.shape[1]:\n raise ValueError(\n 'The input images must be square and have the same size')\n\n print('Loading input images...done')\n\n im_size = list(mov_im_nda.shape)\n mov_im_nda = np.reshape(\n mov_im_nda, [1] + im_size + [1]).astype(np.float32) / 255.\n fix_im_nda = np.reshape(\n fix_im_nda, [1] + im_size + [1]).astype(np.float32) / 255.\n\n pkg_dir, _ = os.path.split(__file__)\n ckpt_dir = os.path.join(pkg_dir, 'model')\n\n tf.reset_default_graph()\n sess = tf.Session()\n\n model = ACRegNet(sess, 'ACRegNet', im_size)\n print('Building AC-RegNet model...done')\n model.restore(ckpt_dir)\n print('Loading trained AC-RegNet model...done')\n\n print('Registering images...')\n model.deploy(dest_dir, mov_im_nda, fix_im_nda, True)\n\n print('Result image and deformation field saved in: ' + dest_dir)\n\n tf.reset_default_graph()\n sess.close()\n","sub_path":"CLI_application/acregnet/acregnet/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"395877845","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom bs4 import BeautifulSoup\nimport urllib2\nfrom urllib import urlretrieve\n\n\n\nbaseurl = \"http://archaeologydataservice.ac.uk/archives/view/amphora_ahrb_2005/drawings.cfm?id=\"\n\nfor i in range(380):\n url = baseurl + str(i)\n request = urllib2.Request(url)\n request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')\n request.add_header('Content-Type','application/json')\n response = urllib2.urlopen(request)\n soup = BeautifulSoup(response.read(), 'html.parser')\n imgContainer =soup.body.find(\"div\",attrs={'class':'imgdraw'}) \n if imgContainer:\n image = imgContainer.findAll(\"img\")[0]\n print(\"http://archaeologydataservice.ac.uk/\"+image[\"src\"])\n print(image[\"alt\"])\n urlretrieve(\"http://archaeologydataservice.ac.uk/\"+image[\"src\"],\"img/\"+str(i)+\".jpg\")\n","sub_path":"dev/philo/geDrawing.py","file_name":"geDrawing.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"512733593","text":"#import main\nimport pulp as p\nimport json\n\ndef transfer(x):\n\n t = open('podaci.json')\n data = json.load(t)\n transfer = data[\"transfer\"]\n\n #ljudi = main.ljudi\n ljudi = int(x)\n\n #problem se zove Transfer\n Lp_prob1 = p.LpProblem('Transfer', p.LpMinimize)\n\n #var odluke\n x1 = p.LpVariable(\"x1\", 0, None, 'Integer')\n x2 = p.LpVariable(\"x2\", 0, None, 'Integer')\n x3 = p.LpVariable(\"x3\", 0, None, 'Integer')\n x4 = p.LpVariable(\"x4\", 0, None, 'Integer')\n x5 = p.LpVariable(\"x5\", 0, None, 'Integer')\n\n #f cilja\n Lp_prob1 += int(transfer[0][\"cijena_km\"])*x1 + int(transfer[1][\"cijena_km\"])*x2 + int(transfer[2][\"cijena_km\"])*x3 + int(transfer[3][\"cijena_km\"])*x4 + int(transfer[4][\"cijena_km\"])*x5 \n\n #ogranicenja\n Lp_prob1 += int(transfer[0][\"kapacitet\"])*x1 + int(transfer[1][\"kapacitet\"])*x2 + int(transfer[2][\"kapacitet\"])*x3 + int(transfer[3][\"kapacitet\"])*x4 + int(transfer[4][\"kapacitet\"])*x5 >= ljudi\n \n\n Lp_prob1.writeLP(\"Transfer.lp\")\n\n Lp_prob1.solve()\n\n #print('------------RJESENJE-------------')\n\n #print(\"Vrijednost funkcije cilja: {}\".format(p.value(Lp_prob.objective)))\n\n #print(\"Varijable odluke: x1 = {}, x2 = {}, x3 = {}, x4 = {}, x5 = {}\".format(p.value(x1), p.value(x2), p.value(x3), p.value(x4), p.value(x5)))\n\n\n rezultat = p.value(Lp_prob1.objective)\n\n varijable = {}\n varijable[\"rez\"] = rezultat\n pom={}\n\n for v in Lp_prob1.variables():\n if(v.varValue):\n i=int(v.name[1])-1\n pom[transfer[i][\"vrsta\"]] = int(v.varValue)\n\n varijable[\"vozila\"] = pom\n\n return varijable\n\n\n ","sub_path":"transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"562793627","text":"#!/usr/bin/env python\nimport os\nimport tempfile\nimport shutil\nimport json\nimport unittest\nimport mock\n\nfrom taca.analysis import analysis as an\nfrom taca.utils import config\n\nCONFIG = config.load_yaml_config('data/taca_test_cfg.yaml')\n\nclass TestAnalysis(unittest.TestCase):\n \"\"\"Tests for the Analysis functions.\"\"\"\n\n @classmethod\n def setUpClass(self):\n \"\"\"Creates the following directory tree for testing purposes:\n\n tmp/\n |__ 141124_ST-COMPLETED_01_AFCIDXX\n | |__ RunInfo.xml\n | |__ Demultiplexing\n | | |__ Undetermined_S0_L001_R1_001.fastq.gz\n | | |__ Stats\n | | |__ DemultiplexingStats.xml\n | |__ RTAComplete.txt\n | |__ SampleSheet.csv\n \"\"\"\n self.tmp_dir = os.path.join(tempfile.mkdtemp(), 'tmp')\n self.completed = os.path.join(self.tmp_dir, '141124_ST-COMPLETED1_01_AFCIDXX')\n\n # Create runs directory structure\n os.makedirs(self.tmp_dir)\n os.makedirs(os.path.join(self.completed, 'Demultiplexing', 'Stats'))\n\n # Set up files\n open(os.path.join(self.completed, 'RTAComplete.txt'), 'w').close()\n shutil.copy('data/samplesheet.csv', os.path.join(self.completed, 'SampleSheet.csv'))\n open(os.path.join(self.completed, 'Demultiplexing', 'Stats', 'DemultiplexingStats.xml'), 'w').close()\n open(os.path.join(self.completed, 'Demultiplexing', 'Undetermined_S0_L001_R1_001.fastq.gz'), 'w').close()\n with open(os.path.join(self.completed, 'Demultiplexing', 'Stats', 'Stats.json'), 'w') as stats_json:\n json.dump({'silly': 1}, stats_json)\n shutil.copy('data/RunInfo.xml', self.completed)\n shutil.copy('data/runParameters.xml', self.completed)\n\n @classmethod\n def tearDownClass(self):\n shutil.rmtree(self.tmp_dir)\n\n def test_get_runObj_hiseq(self):\n \"\"\"Return HiSeq run object.\"\"\"\n hiseq_run = os.path.join(self.tmp_dir, '141124_ST-HISEQ1_01_AFCIDXX')\n os.mkdir(hiseq_run)\n shutil.copy('data/runParameters_hiseq.xml', os.path.join(hiseq_run, 'runParameters.xml'))\n got_hiseq_run = an.get_runObj(hiseq_run)\n self.assertEqual(got_hiseq_run.sequencer_type, 'HiSeq')\n\n def test_get_runObj_hiseqx(self):\n \"\"\"Return HiSeqX run object.\"\"\"\n got_run = an.get_runObj(self.completed)\n self.assertEqual(got_run.sequencer_type, 'HiSeqX')\n\n def test_get_runObj_miseq(self):\n \"\"\"Return MiSeq run object.\"\"\"\n miseq_run = os.path.join(self.tmp_dir, '141124_ST-MISEQ1_01_AFCIDXX')\n os.mkdir(miseq_run)\n shutil.copy('data/runParameters_miseq.xml', os.path.join(miseq_run, 'runParameters.xml'))\n got_miseq_run = an.get_runObj(miseq_run)\n self.assertEqual(got_miseq_run.sequencer_type, 'MiSeq')\n\n def test_get_runObj_nextseq(self):\n \"\"\"Return NextSeq run object.\"\"\"\n nextseq_run = os.path.join(self.tmp_dir, '141124_ST-NEXTSEQ1_01_AFCIDXX')\n os.mkdir(nextseq_run)\n shutil.copy('data/runParameters_nextseq.xml', os.path.join(nextseq_run, 'runParameters.xml'))\n got_nextseq_run = an.get_runObj(nextseq_run)\n self.assertEqual(got_nextseq_run.sequencer_type, 'NextSeq')\n\n def test_get_runObj_novaseq(self):\n \"\"\"Return NovaSeq run object.\"\"\"\n novaseq_run = os.path.join(self.tmp_dir, '141124_ST-NOVASEQ1_01_AFCIDXX')\n os.mkdir(novaseq_run)\n shutil.copy('data/runParameters_novaseq.xml', os.path.join(novaseq_run, 'RunParameters.xml'))\n got_novaseq_run = an.get_runObj(novaseq_run)\n self.assertEqual(got_novaseq_run.sequencer_type, 'NovaSeq')\n\n @mock.patch('taca.analysis.analysis.get_runObj')\n @mock.patch('taca.analysis.analysis._upload_to_statusdb')\n def test_upload_to_statusdb(self, mock_upload_to_statusdb, mock_get_runobj):\n \"\"\"Get run object and initiate upload to statusdb.\"\"\"\n mock_get_runobj.return_value = 'HiSeqX_run_object'\n an.upload_to_statusdb(self.completed)\n mock_upload_to_statusdb.assert_called_once_with('HiSeqX_run_object')\n\n @mock.patch('taca.analysis.analysis.statusdb')\n def test__upload_to_statusdb(self, mock_statusdb):\n \"\"\"Upload to statusdb.\"\"\"\n run = os.path.join(self.tmp_dir, '141124_ST-NOINDEX1_01_AFCIDYX')\n os.mkdir(run)\n shutil.copy('data/runParameters_minimal.xml', os.path.join(run, 'runParameters.xml'))\n demux_dir = os.path.join(run, 'Demultiplexing', 'Stats')\n os.makedirs(demux_dir)\n shutil.copy('data/DemuxSummaryF1L1.txt', demux_dir)\n reports_dir = os.path.join(run, 'Demultiplexing', 'Reports', 'html', 'FCIDYX', 'all', 'all', 'all')\n os.makedirs(reports_dir)\n shutil.copy('data/laneBarcode.html', (reports_dir))\n shutil.copy('data/lane.html', (reports_dir))\n noindex_run = an.get_runObj(run)\n an._upload_to_statusdb(noindex_run)\n mock_statusdb.update_doc.assert_called_once()\n\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.transfer_run')\n def test_transfer_run(self, mock_transfer_run):\n \"\"\"Transfer run to Uppmax.\"\"\"\n run_dir = (self.completed)\n an.transfer_run(run_dir)\n mock_transfer_run.assert_called_once_with('nosync/data/transfer.tsv', 'some_user@some_email.com')\n\n @mock.patch('taca.analysis.analysis.RsyncAgent.transfer')\n @mock.patch('taca.analysis.analysis.subprocess.call')\n @mock.patch('taca.analysis.analysis.os.remove')\n @mock.patch('taca.analysis.analysis.open')\n def test_transfer_runfolder(self, mock_open, mock_remove, mock_subprocess_call, mock_transfer):\n \"\"\"Transfer runfolder to uppmax.\"\"\"\n run_dir = (self.completed)\n pid = 'P1775'\n exclude_lane = ''\n an.transfer_runfolder(run_dir, pid, exclude_lane)\n mock_subprocess_call.assert_called()\n mock_transfer.assert_called()\n\n def test_extract_project_samplesheet(self):\n \"\"\"Extract project specific lines from sample sheet.\"\"\"\n sample_sheet = 'data/samplesheet.csv'\n pid = 'P1775'\n samplesheet_content = an.extract_project_samplesheet(sample_sheet, pid)\n expected_samplesheet_content = \"\"\"Lane,SampleID,SampleName,SamplePlate,SampleWell,index,Project\n1,Sample_P1775_147,P1775_147,FCB_150423,1:1,GAATTCGT,J_Lundeberg_14_24\n\"\"\"\n self.assertEqual(samplesheet_content, expected_samplesheet_content)\n\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.get_run_status')\n @mock.patch('taca.analysis.analysis._upload_to_statusdb')\n def test_run_preprocessing_sequencing(self, mock_upload_to_statusdb, mock_get_run_status):\n \"\"\"Run preprocess run still sequencing.\"\"\"\n run = self.completed\n mock_get_run_status.return_value = 'SEQUENCING'\n an.run_preprocessing(run, force_trasfer=True, statusdb=True)\n mock_upload_to_statusdb.assert_called_once()\n\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.get_run_status')\n @mock.patch('taca.analysis.analysis._upload_to_statusdb')\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.demultiplex_run')\n def test_run_preprocessing_to_start(self, mock_demultiplex_run, mock_upload_to_statusdb, mock_get_run_status):\n \"\"\"Run preprocessing start demux.\"\"\"\n run = self.completed\n mock_get_run_status.return_value = 'TO_START'\n an.run_preprocessing(run, force_trasfer=True, statusdb=True)\n mock_upload_to_statusdb.assert_called_once()\n mock_demultiplex_run.assert_called_once()\n\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.get_run_status')\n @mock.patch('taca.analysis.analysis._upload_to_statusdb')\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.check_run_status')\n def test_run_preprocessing_in_progress(self, mock_check_run_status, mock_upload_to_statusdb, mock_get_run_status):\n \"\"\"Run preprocessing demux in progress.\"\"\"\n run = self.completed\n mock_get_run_status.return_value = 'IN_PROGRESS'\n an.run_preprocessing(run, force_trasfer=True, statusdb=True)\n mock_upload_to_statusdb.assert_called_once()\n mock_check_run_status.assert_called_once()\n\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.get_run_status')\n @mock.patch('taca.analysis.analysis._upload_to_statusdb')\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.send_mail')\n @mock.patch('taca.analysis.analysis.HiSeqX_Run.transfer_run')\n @mock.patch('taca.analysis.analysis.os.mkdir')\n @mock.patch('taca.analysis.analysis.copyfile')\n def test_run_preprocessing_completed(self, mock_copy, mock_mkdir, mock_transfer_run, mock_send_mail, mock_upload_to_statusdb, mock_get_run_status):\n \"\"\"Run preprocessing demux completed.\"\"\"\n run = self.completed\n mock_get_run_status.return_value = 'COMPLETED'\n an.run_preprocessing(run, force_trasfer=True, statusdb=True)\n mock_upload_to_statusdb.assert_called_once()\n message = 'The run 141124_ST-COMPLETED1_01_AFCIDXX has been demultiplexed.\\n The Run will be transferred to the analysis cluster for further analysis.\\n\\n \\\n The run is available at : https://genomics-status.scilifelab.se/flowcells/141124_ST-COMPLETED1_01_AFCIDXX\\n\\n '\n mock_send_mail.assert_called_once_with(message, rcp='some_user@some_email.com')\n mock_transfer_run.assert_called_once_with('data/transfer.tsv', 'some_user@some_email.com')\n","sub_path":"tests/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":9404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"275908887","text":"__author__ = 'garrus'\n\n# Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.\n# Do not allocate extra space for another array, you must do this in place with constant memory.\n# For example,\n# Given input array A = [1,1,2],\n# Your function should return length = 2, and A is now [1,2].\n\n\nclass Solution:\n # @param a list of integers\n # @return an integer\n def removeDuplicates(self, A):\n if not A:\n return 0\n\n n=A.__len__()\n\n start=1\n for i in range(1,n):\n if(A[i]!=A[i-1]):\n A[start]=A[i]\n start+=1\n\n return start\n\n\nif __name__=='__main__':\n sol=Solution()\n A=[1,1,1,1]\n\n print(sol.removeDuplicates(A))","sub_path":"EasyProblems/RemoveDuplicates.py","file_name":"RemoveDuplicates.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"426942186","text":"__all__ = [\"windows_builder\"]\n\nfrom buildbot.process.properties import Property, renderer\nfrom buildbot.process.factory import BuildFactory\nfrom buildbot.steps.source.git import Git\nfrom buildbot.steps.shell import Compile, Test, SetPropertyFromCommand\nfrom buildbot.steps.transfer import FileUpload\nfrom buildbot.steps.slave import RemoveDirectory\nfrom buildbot.config import BuilderConfig\n\nimport config\nfrom .common import common_flags, buildtype_flag, whl_version_steps, whl_version, whl_filename, whl_upload_filename, publish_rtdist_steps\nfrom .common import MakeTorrent, SeedTorrent\n\n@renderer\ndef exe_filename(props):\n \"Determines the name of an .exe file for uploading.\"\n\n if props[\"arch\"] == \"amd64\":\n suffix = \"-x64\"\n else:\n suffix = \"\"\n\n if \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != \"2.7\":\n suffix = \"-py\" + props[\"python-version\"] + suffix\n\n if \"buildtype\" in props and props[\"buildtype\"] == \"runtime\":\n prefix = \"Panda3D-Runtime\"\n else:\n prefix = \"Panda3D\"\n\n return \"%s-%s%s.exe\" % (prefix, props[\"version\"], suffix)\n\n@renderer\ndef pdb_filename(props):\n \"Determines the name of an -pdb.zip file for uploading.\"\n\n if props[\"arch\"] == \"amd64\":\n suffix = \"-x64\"\n else:\n suffix = \"\"\n\n if \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != \"2.7\":\n suffix = \"-py\" + props[\"python-version\"] + suffix\n\n return \"Panda3D-%s%s-pdb.zip\" % (props[\"version\"], suffix)\n\n@renderer\ndef exe_upload_filename(props):\n \"Determines the upload location of an .exe file on the master.\"\n\n if props[\"arch\"] == \"amd64\":\n suffix = \"-x64\"\n else:\n suffix = \"\"\n\n if \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != \"2.7\":\n suffix = \"-py\" + props[\"python-version\"] + suffix\n\n if \"buildtype\" in props and props[\"buildtype\"] == \"runtime\":\n prefix = \"Panda3D-Runtime\"\n else:\n prefix = \"Panda3D-SDK\"\n\n if props[\"revision\"].startswith(\"v\"):\n basename = \"%s-%s%s.exe\" % (prefix, props[\"version\"], suffix)\n #elif \"commit-description\" in props:\n # basename = \"%s-%s%s.exe\" % (prefix, props[\"commit-description\"][1:], suffix)\n else:\n basename = \"%s-%spre-%s%s.exe\" % (prefix, props[\"version\"], props[\"got_revision\"][:7], suffix)\n\n return '/'.join((config.downloads_dir, props[\"got_revision\"], basename))\n\n@renderer\ndef pdb_upload_filename(props):\n \"Determines the upload location of a -pdb.zip file on the master.\"\n\n if props[\"arch\"] == \"amd64\":\n suffix = \"-x64\"\n else:\n suffix = \"\"\n\n if \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != \"2.7\":\n suffix = \"-py\" + props[\"python-version\"] + suffix\n\n if props[\"revision\"].startswith(\"v\"):\n basename = \"Panda3D-SDK-%s%s-pdb.zip\" % (props[\"version\"], suffix)\n #elif \"commit-description\" in props:\n # basename = \"Panda3D-SDK-%s%s-pdb.zip\" % (props[\"commit-description\"][1:], suffix)\n else:\n basename = \"Panda3D-SDK-%spre-%s%s-pdb.zip\" % (props[\"version\"], props[\"got_revision\"][:7], suffix)\n\n return '/'.join((config.downloads_dir, props[\"got_revision\"], basename))\n\n@renderer\ndef python_executable(props):\n \"Determines the location of python.exe on the slave.\"\n\n if props[\"arch\"] == \"amd64\":\n suffix = \"-x64\"\n else:\n suffix = \"\"\n\n if \"buildtype\" in props and props[\"buildtype\"] == \"rtdist\":\n return 'C:\\\\Python27%s\\\\python.exe' % (suffix)\n elif \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != \"2.7\":\n return 'C:\\\\thirdparty\\\\win-python%s%s\\\\python.exe' % (props[\"python-version\"], suffix)\n else:\n return 'C:\\\\thirdparty\\\\win-python%s\\\\python.exe' % (suffix)\n\n@renderer\ndef dist_flags(props):\n if \"buildtype\" in props and props[\"buildtype\"] == \"rtdist\":\n return []\n elif \"buildtype\" in props and props[\"buildtype\"] == \"runtime\":\n return [\"--installer\", \"--lzma\"]\n\n pythonv = (2, 7)\n if \"python-version\" in props and props[\"python-version\"]:\n pythonv = tuple(map(int, props[\"python-version\"].split('.')))\n\n if pythonv >= (3, 5):\n return [\"--installer\", \"--lzma\", \"--msvc-version=14\", \"--wheel\"]\n else:\n return [\"--installer\", \"--lzma\", \"--wheel\"]\n\n@renderer\ndef outputdir(props):\n if \"python-version\" in props and props[\"python-version\"] and props[\"python-version\"] != '2.7':\n return ['built-py' + props[\"python-version\"]]\n else:\n return ['built']\n\nbuild_cmd = [\n python_executable,\n \"makepanda\\\\makepanda.py\",\n \"--everything\",\n \"--outputdir=built\",\n \"--no-touchinput\",\n common_flags, dist_flags,\n \"--outputdir\", outputdir,\n \"--arch\", Property(\"arch\"),\n \"--version\", whl_version,\n]\n\ntest_cmd = [\n python_executable,\n \"makepanda\\\\test_wheel.py\",\n \"--verbose\",\n whl_filename,\n]\n\ncheckout_steps = [\n Git(config.git_url, getDescription={'match': 'v*'}),\n\n # Decode the version number from the dtool/PandaVersion.pp file.\n SetPropertyFromCommand(\"version\", command=[\n python_executable, \"makepanda/getversion.py\", buildtype_flag],\n haltOnFailure=True),\n]\n\nwhl_steps = [\n SetPropertyFromCommand(\"python-abi\", command=[\n python_executable, \"-c\", \"import makewheel;print(makewheel.get_abi_tag())\"],\n workdir=\"build/makepanda\", haltOnFailure=True),\n] + whl_version_steps\n\nbuild_steps = [\n # Run makepanda - give it enough timeout (6h) since some steps take ages\n Compile(command=build_cmd, timeout=6*60*60,\n env={\"MAKEPANDA_THIRDPARTY\": \"C:\\\\thirdparty\",\n \"MAKEPANDA_SDKS\": \"C:\\\\sdks\"}, haltOnFailure=True),\n\n # Run the test suite, but in a virtualenv.\n Test(command=test_cmd, haltOnFailure=True),\n]\n\npublish_exe_steps = [\n FileUpload(slavesrc=exe_filename, masterdest=exe_upload_filename,\n mode=0o664, haltOnFailure=True),\n\n MakeTorrent(exe_upload_filename),\n SeedTorrent(exe_upload_filename),\n]\n\npublish_sdk_steps = [\n # Upload the wheel.\n FileUpload(slavesrc=whl_filename, masterdest=whl_upload_filename,\n mode=0o664, haltOnFailure=True),\n\n # Upload the pdb zip file.\n FileUpload(slavesrc=pdb_filename, masterdest=pdb_upload_filename,\n mode=0o664, haltOnFailure=False),\n] + publish_exe_steps\n\n# Now make the factories.\nsdk_factory = BuildFactory()\nfor step in checkout_steps + whl_steps + build_steps + publish_sdk_steps:\n sdk_factory.addStep(step)\n\nruntime_factory = BuildFactory()\nfor step in checkout_steps + build_steps + publish_exe_steps:\n runtime_factory.addStep(step)\n\nrtdist_factory = BuildFactory()\nrtdist_factory.addStep(RemoveDirectory(dir=\"built/slave\"))\nfor step in checkout_steps + build_steps + publish_rtdist_steps:\n rtdist_factory.addStep(step)\n\n\ndef windows_builder(buildtype, arch, optimize=False):\n if buildtype == \"rtdist\":\n factory = rtdist_factory\n elif buildtype == \"runtime\":\n factory = runtime_factory\n else:\n factory = sdk_factory\n\n if arch == \"amd64\":\n platform = \"win_amd64\"\n else:\n platform = \"win32\"\n\n return BuilderConfig(name='-'.join((buildtype, \"windows\", arch)),\n slavenames=config.windows_slaves,\n factory=factory,\n properties={\"buildtype\": buildtype, \"arch\": arch, \"platform\": platform, \"optimize\": optimize})\n","sub_path":"builders/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":7524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"567364866","text":"import os\nimport tarfile\nimport numpy as np\nfrom PIL import Image\nimport tensorflow as tf\nimport time, datetime\nimport requests\nfrom io import BytesIO\nfrom django.core.files.base import ContentFile\nfrom .models import Imageupload\n\nclass DeepLabModel(object):\n INPUT_TENSOR_NAME = 'ImageTensor:0'\n OUTPUT_TENSOR_NAME = 'SemanticPredictions:0'\n INPUT_SIZE = 513 #圖片長寬\n FROZEN_GRAPH_NAME = 'frozen' #_inference_graph\n def __init__(self, tarball_path):\n self.graph = tf.Graph()\n graph_def = None\n tar_file = tarfile.open(tarball_path)\n for tar_info in tar_file.getmembers():\n if self.FROZEN_GRAPH_NAME in os.path.basename(tar_info.name):\n file_handle = tar_file.extractfile(tar_info)\n graph_def = tf.GraphDef.FromString(file_handle.read())\n break\n tar_file.close()\n if graph_def is None:\n raise RuntimeError('Cannot find inference graph in tar archive.')\n with self.graph.as_default():\n tf.import_graph_def(graph_def, name='')\n self.sess = tf.Session(graph=self.graph)\n def run(self, image):\n width, height = image.size\n resize_ratio = 1.0 * self.INPUT_SIZE / max(width, height)\n target_size = (int(resize_ratio * width), int(resize_ratio * height))\n resized_image = image.convert('RGB').resize(target_size, Image.ANTIALIAS)\n batch_seg_map = self.sess.run(\n self.OUTPUT_TENSOR_NAME,\n feed_dict={self.INPUT_TENSOR_NAME: [np.asarray(resized_image)]})\n seg_map = batch_seg_map[0]\n return resized_image, seg_map\ndef create_pascal_label_colormap():\n colormap = np.zeros((256, 3), dtype=int)\n ind = np.arange(256, dtype=int)\n for shift in reversed(range(8)):\n for channel in range(3):\n colormap[:, channel] |= ((ind >> channel) & 1) << shift\n ind >>= 3\n return colormap\ndef label_to_color_image(label):\n if label.ndim != 2:\n raise ValueError('Expect 2-D input label')\n colormap = create_pascal_label_colormap()\n if np.max(label) >= len(colormap):\n raise ValueError('label value too large.')\n return colormap[label]\n\nMODEL_xception65_trainval = DeepLabModel(\"model_xception65_coco_voc_trainval.tar.gz\")\n#MODEL_xception65_trainval = DeepLabModel(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../model_xception65_coco_voc_trainval.tar.gz'))\nprint(\"deeplabv3+ model loading\")\n\ndef seg_result(rows, cols, cm, img):\n for x in range(0, rows):\n for y in range(0, cols):\n if cm[x][y] == 0:\n img[x][y] = np.array([255, 255, 255], dtype='uint8')\n return Image.fromarray(img)\n\ndef mask_result(rows, cols, cm, img):\n for x in range(0, rows):\n for y in range(0, cols):\n if cm[x][y] == 0:\n img[x][y] = np.array([0, 0, 0], dtype='uint8')\n else:\n img[x][y] = np.array([255, 255, 255], dtype='uint8')\n return Image.fromarray(img)\n\ndef run_deeplabv3plus2(photo_input): #output result and mask\n MODEL = MODEL_xception65_trainval\n #load input photo\n if \"http\" in photo_input: # for GCS\n response = requests.get(photo_input)\n original_im = Image.open(BytesIO(response.content))\n else:\n original_im = Image.open(photo_input)\n width, height = original_im.size\n resized_im, seg_map = MODEL.run(original_im)\n cm = seg_map\n img = np.array(resized_im)\n rows = cm.shape[0]\n cols = cm.shape[1]\n\n img_seq = seg_result(rows, cols, cm, img)\n img_seq = img_seq.resize((width, height),Image.ANTIALIAS)\n img_mask = mask_result(rows, cols, cm, img)\n img_mask = img_mask.resize((width, height),Image.ANTIALIAS)\n\n #get file name and extension\n f_n = photo_input.split(\"/\")[-1].split(\".\")[0]\n f_e = photo_input.split(\".\")[-1]\n #remove special charactor\n tbd = ['!','@','#','$','%','^','&','*','(',')','-','+','=']\n for i in tbd:\n f_n = f_n.replace(i,'')\n #if the extension is too long make it .jpg\n if len(f_e) > 7:\n f_e = \"jpg\"\n out_f_name = f_n + \"_out.\" + f_e\n out_m_name = f_n + \"_mask.\" + f_e\n #save output image\n img_io = BytesIO()\n img_seq.save(img_io, format='JPEG')\n img_content = ContentFile(img_io.getvalue(), out_f_name)\n date_of_upload = str(datetime.datetime.today())\n img2 = Imageupload(image_file=img_content, title= out_f_name.split('.')[-2], date_of_upload = date_of_upload)\n img2.save()\n #save mask image\n img_io = BytesIO()\n img_mask.save(img_io, format='JPEG')\n img_content = ContentFile(img_io.getvalue(), out_m_name)\n date_of_upload = str(datetime.datetime.today())\n img3 = Imageupload(image_file=img_content, title= out_m_name.split('.')[-2], date_of_upload = date_of_upload)\n img3.save()\n\n return img2.pk, img3.pk, img2.image_file.url, img3.image_file.url #seg_out pk, mask pk, seg_out url, mask url\n","sub_path":"bot/deepllabv3plus.py","file_name":"deepllabv3plus.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"402713882","text":"# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\n# list of points \nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nnp.random.seed(22)\n\nmeans = [[0, 5], [5, 0]]\ncov0 = [[4, 3], [3, 4]]\ncov1 = [[3, 1], [1, 1]]\nN0 = 50\nN1 = 40\nN = N0 + N1\nX0 = np.random.multivariate_normal(means[0], cov0, N0) # each row is a data point \nX1 = np.random.multivariate_normal(means[1], cov1, N1)\n\n# display\nwith PdfPages('data.pdf') as pdf:\n plt.scatter(X0[:, 0], X0[:, 1], color='blue', marker = 's', alpha=.8, \n label='class 1')\n plt.scatter(X1[:, 0], X1[:, 1], color='red', marker = 'o', alpha=.8, \n label='class 2')\n plt.legend(loc='best', shadow=False, scatterpoints=1)\n \n # hide ticks\n cur_axes = plt.gca()\n cur_axes.axes.get_xaxis().set_ticks([])\n cur_axes.axes.get_yaxis().set_ticks([])\n plt.xlim([0, 1])\n plt.ylim([-10, 10])\n plt.axis('equal')\n\n pdf.savefig()\n\n plt.show()\n \n \n \n \n \n \n \n \n \n# Build S_B\nm0 = np.mean(X0.T, axis = 1, keepdims = True)\nm1 = np.mean(X1.T, axis = 1, keepdims = True)\n\na = (m0 - m1)\nS_B = a.dot(a.T)\n\n# Build S_W\nA = X0.T - np.tile(m0, (1, N0))\nB = X1.T - np.tile(m1, (1, N1))\n\nS_W = A.dot(A.T) + B.dot(B.T)\n\n\n\n\n\n_, W = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))\nw = W[:,0]\n\n\n\n\n\n\nwith PdfPages('res.pdf') as pdf:\n plt.scatter(X0[:, 0], X0[:, 1], color='blue', marker = 's', alpha=.8, \n label='class 1')\n plt.scatter(X1[:, 0], X1[:, 1], color='red', marker = 'o', alpha=.8, \n label='class 2')\n \n# plt.legend(loc = \"best\", fontsize = 17)\n\n \n cur_axes = plt.gca()\n cur_axes.axes.get_xaxis().set_ticks([])\n cur_axes.axes.get_yaxis().set_ticks([])\n plt.xlim([0, 1])\n plt.ylim([-10, 10])\n plt.axis('equal')\n# plt.arrow(5*w[0],5*w[1],-10*w[0],-10*w[1], shape='full', lw=1, length_includes_head=True, head_width=.31)\n plt.plot([-5*w[0], 6*w[0]], [-5*w[1], 6*w[1]], 'g', label = 'Solution by LDA')\n \n plt.legend(loc='best', shadow=False, scatterpoints=1, fontsize = 13)\n pdf.savefig()\n plt.show()\n \n \n \n \n \nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nX = np.concatenate((X0, X1))\ny = np.array([0]*N0 + [1]*N1)\nclf = LinearDiscriminantAnalysis()\nclf.fit(X, y)\n\nprint(clf.coef_/np.linalg.norm(clf.coef_)) # normalize","sub_path":"Blog anh tiep/Bai 29 LDA/LDA.py","file_name":"LDA.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"338794905","text":"# To find whether a number is Perfect or not.\r\n# Explaination : \"Perfect number, a positive integer that \r\n# is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3\"\r\n\r\ndef check_perfect_number(n):\r\n\tsum = 0\r\n\tfor i in range(1,n):\r\n\t\tif n%i == 0:\r\n\t\t\tsum+=i\r\n\tif sum == n:\r\n\t\treturn True\r\n\treturn False\r\n\r\n\r\nn = int(input())\r\nprint(check_perfect_number(n))\r\n\r\n\r\n\r\n","sub_path":"Day 14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"544089139","text":"# -*- coding: utf-8 -*-\n\"\"\"\nlehman package\n\nImports all parts from lehman here\n\"\"\"\nfrom ._version import __version__\n\n__author__ = '''Argiris Gounaris'''\n__email__ = '''agounaris@gmail.com'''\n\n# This is to 'use' the module(s), so lint doesn't complain\nassert __version__\n","sub_path":"lehman/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"328677390","text":"\n\n#calss header\nclass _MODULATE():\n\tdef __init__(self,): \n\t\tself.name = \"MODULATE\"\n\t\tself.definitions = [u'to change the style, loudness, etc. of something such as your voice in order to achieve an effect or express an emotion: ', u'to change from one musical key to another: ', u'to change something, such as an action or a process, to make it more suitable for its situation: ', u'to mix an electrical signal that represents sounds or pictures with a radio signal so that it can be broadcast']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_modulate.py","file_name":"_modulate.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"553626108","text":"from matplotlib import pyplot as plt\nfrom matplotlib import gridspec as gs\nfrom sklearn.datasets import load_iris\n\ndata=load_iris()\nfeatures = data.data\nfeature_names = data.feature_names\ntarget = data.target\ntarget_names = data.target_names\ngrid = gs.GridSpec(2,3)\nax0 = plt.subplot(grid[0])\nax0.set_xlabel(feature_names[0])\nax0.set_ylabel(feature_names[1])\nax1 = plt.subplot(grid[1])\nax1.set_xlabel(feature_names[0])\nax1.set_ylabel(feature_names[2])\nax2 = plt.subplot(grid[2])\nax2.set_xlabel(feature_names[0])\nax2.set_ylabel(feature_names[3])\nax3 = plt.subplot(grid[3])\nax3.set_xlabel(feature_names[1])\nax3.set_ylabel(feature_names[2])\nax4 = plt.subplot(grid[4])\nax4.set_xlabel(feature_names[1])\nax4.set_ylabel(feature_names[3])\nax5 = plt.subplot(grid[5])\nax5.set_xlabel(feature_names[2])\nax5.set_ylabel(feature_names[3])\nfor t in xrange(3):\n if t == 0:\n col = 'r'\n marker = '>'\n elif t == 1:\n col = 'g'\n marker = 'o'\n elif t == 2:\n col = 'b'\n marker = 'x'\n lbl = target_names[t]\n ax0.scatter(features[target==t, 0],\n features[target==t, 1],\n marker = marker,\n c = col,\n label=lbl)\n\n ax1.scatter(features[target==t, 0],\n features[target==t, 2],\n marker = marker,\n c = col,\n label=lbl)\n\n ax2.scatter(features[target==t, 0],\n features[target==t, 3],\n marker = marker,\n c = col,\n label=lbl)\n\n ax3.scatter(features[target==t, 1],\n features[target==t, 2],\n marker = marker,\n c = col,\n label=lbl)\n\n ax4.scatter(features[target==t, 1],\n features[target==t, 3],\n marker = marker,\n c = col,\n label=lbl)\n\n ax5.scatter(features[target==t, 2],\n features[target==t, 3],\n marker = marker,\n c = col,\n label=lbl)\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., scatterpoints=1)\n\n\nplt.show()","sub_path":"IrisRecognition/IrisGroupPlotting.py","file_name":"IrisGroupPlotting.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"221691304","text":"#--------------------------------- IMPORTS ------------------------------------\n\nimport numpy as np\nimport math\nimport csv\nimport datetime as dt\n\n#-------------------------- FUNCTION DEFINITIONS ----------------------------\n\ndef jdate_fxn(year, month, day, hour, minute):\n # Calculate Julian date\n # http://aa.usno.navy.mil/faq/docs/JD_Formula.php\n return 367*year-math.floor(7*(year+math.floor((month+9)/12))/4) + \\\n math.floor(275*month/9)+day+1721013.5+(hour + minute/60.0)/24 - \\\n 0.5*(2*((100*year+month-190002.5)>0)-1)+0.5\n \n\ndef RA_fxn(lon, jdate):\n # All equations from USNO\n # Take lat. and lon. as degrees. Return right ascension in hours.\n # Right ascension is in coordinates of date, not J2000 coordinates.\n jdate_2000 = jdate - 2451545.0\n\n # GMST formula accurate to 0.1 s per century \n GMST = (18.697374558 + 24.06570982441908*jdate_2000) % 24\n \n obliquity = (23.4393 - 0.0000004*jdate_2000)*(np.pi*2/360)\n ascending_node_moon = (125.04 - 0.052954*jdate_2000)*(np.pi*2/360)\n mean_lon_sun = (280.47 + 0.98565*jdate_2000)*(np.pi*2/360)\n nutation = -0.000319*np.sin(ascending_node_moon) - 0.000024*np.sin(2*mean_lon_sun)\n eqeq = np.cos(obliquity)*nutation\n GAST = GMST + eqeq\n LHA = 0 # Local hour angle = 0 for zenith\n RA = GAST-(LHA*15-lon)*(24./360)\n RA = RA % 24\n return RA\n\n\ndef precess_RA_to_J2000(old_epoch, old_RA, old_dec):\n # old_epoch as a Julian date\n # old_RA and new_RA in hours, old_dec in degrees\n \n axial_tilt = 23.44*(np.pi/180)\n\n # This formula adapted from www.stargazing.net/mas/epoch.htm\n # No documentation about its source.\n \n delta_RA = (1./3600)*3.3*((2451545.0-old_epoch)/365.25)*\\\n (np.cos(axial_tilt) + np.sin(axial_tilt)*np.sin(old_RA*2*np.pi/24)*np.tan(old_dec*np.pi/180))\n \n new_RA = old_RA + delta_RA\n return new_RA\n\n\ndef precess_dec_to_J2000(old_epoch, new_RA, old_dec):\n # old_epoch as a Julian date\n # new_RA in hours, old_dec and new_dec in degrees \n \n axial_tilt = 23.5*(np.pi/180)\n\n # This formula adapted from www.stargazing.net/mas/epoch.htm\n # No documentation about its source.\n # Original formula seemed to use the precessed RA, rather than the old RA; not sure if this was error\n \n delta_dec = (1./3600)*50*((2451545.0-old_epoch)/365.25)*\\\n np.sin(axial_tilt)*np.cos(new_RA*np.pi/12)\n \n new_dec = old_dec+delta_dec\n return new_dec\n\n\ndef spherical_to_cartesian(RA,dec):\n # Takes RA as hours and dec as degrees\n # returns coords (x,y,z) for unit sphere\n x = np.sin((-dec+90)*np.pi/180)*np.cos(RA*15*np.pi/180)\n y = np.sin((-dec+90)*np.pi/180)*np.sin(RA*15*np.pi/180)\n z = np.cos((-dec+90)*np.pi/180)\n \n return([x,y,z])\n\n\ndef find_nearest_star(target_RA, target_dec, catalog_RA, catalog_dec):\n catalog_size = len(catalog_RA)\n target_x, target_y, target_z = spherical_to_cartesian(target_RA,target_dec)\n distance = []\n \n for i in range(catalog_size):\n catalog_x,catalog_y,catalog_z = spherical_to_cartesian(catalog_RA[i],catalog_dec[i])\n distance.append(np.sqrt((catalog_x-target_x)**2+(catalog_y-target_y)**2+(catalog_z-target_z)**2))\n \n min_distance = min(distance)\n\n nearest_row = distance.index(min_distance)\n\n return nearest_row\n\n\ndef adjust_for_propermotions(RA_J2000, dec_J2000, pmRA, pmdec, epoch):\n # epoch is Julian date of birthday\n # approximates changes in RA and dec as linear w/ time.\n # units of pm are milliarcseconds per year\n years = (epoch-2451545.0)/365.25\n epoch_RA = [0 for i in range(len(pmRA))]\n epoch_dec = [0 for i in range(len(pmRA))] \n \n for i in range(len(pmRA)):\n epoch_RA[i] = pmRA[i]*(0.001/3600/15)*years+RA_J2000[i]\n epoch_dec[i] = pmdec[i]*(0.001/3600)*years+dec_J2000[i]\n\n return (epoch_RA, epoch_dec)\n\n\ndef get_date_time_from_user():\n \"\"\"\n Prompt user to type in date of the event.\n Prompt user to type in the GMT time of event.\n Returns a datetime object that stores that data.\n \"\"\"\n valid_input = False\n while not valid_input:\n date_str = input('Enter date as YYYY-MM-DD : ')\n try:\n this_date = dt.datetime.strptime(date_str, '%Y-%m-%d')\n valid_input=True\n except:\n print('Invalid input')\n \n valid_input = False\n while not valid_input: \n time_str = input('Enter GMT time as hh:mm : ') \n try:\n this_time = dt.datetime.strptime(time_str, '%H:%M')\n valid_input=True\n except:\n print('Invalid input')\n\n this_datetime = dt.datetime.combine(this_date.date(), this_time.time())\n return this_datetime\n\n\ndef get_lat_lon_from_user():\n \"\"\"\n Prompt user to type in latitude of event.\n Prompt user to type in longitude ofof event.\n Returns a tuple (latitude, longitude) in decimal form.\n \"\"\"\n \n def parse_latlon(coord_str):\n \"\"\"\n Both latitude and longitde should be entered in format D:M:S,\n where D and M and S are integers.\n If input is correctly formatted, returns the coordinate as a tuple\n of integers (D,M,S), and returns a value of True. Otherwise returns\n None and a value of False.\n \"\"\"\n parts = coord_str.split(':')\n if len(parts)==3:\n try:\n degrees = int(parts[0])\n minutes = int(parts[1])\n seconds = int(parts[2])\n coord = (degrees, minutes, seconds)\n except:\n print('Invalid values')\n return None, False\n else:\n print('Invalid format')\n return None, False\n \n return coord, True\n \n \n # Get Latitude\n valid_input = False\n while not valid_input:\n coord_str = input('Enter latitude as D:M:S, '+\n 'where -90<=D<=90, 0<=M<=59,0<=S<=59 : ')\n coord, valid_input = parse_latlon(coord_str)\n lat = coord[0]+coord[1]/60.0+coord[2]/3600.0\n \n # Get longitude\n valid_input = False\n while not valid_input:\n coord_str = input('Enter longitude as D:M:S, '+\n 'where -180<=D<=180, 0<=M<=59,0<=S<=59 : ')\n coord, valid_input = parse_latlon(coord_str)\n lon = coord[0]+coord[1]/60.0+coord[2]/3600.0\n \n return lat, lon\n#-------------------------------- MAIN BODY ---------------------------------\n\n#----- Get user input -----\n\nthis_datetime = get_date_time_from_user()\nlat, lon = get_lat_lon_from_user()\n\n#----- Crunch the numbers -----\n\n# Calculate Julian date of birthday\n#jdate = jdate_fxn(year, month, day, hour, minute)\njdate = jdate_fxn(this_datetime.year, this_datetime.month, this_datetime.day, \n this_datetime.hour, this_datetime.minute)\n\n# For zenith, of-date declination equals latitude of observer\ndec = lat\n\n# Calculate of-date right ascension\nRA = RA_fxn(lon, jdate)\n\nprint('Right Ascension is {:.6f} hours'.format(RA))\nprint('Declination is {:.6f} degrees'.format(dec))\n\n# Calculate celestial coordinates for J2000 epoch and equinox\nRA_J2000 = precess_RA_to_J2000(jdate, RA, dec)\ndec_J2000 = precess_dec_to_J2000(jdate, RA_J2000, dec)\n\nprint('J2000 Right Ascension is {:.6f} hours'.format(RA_J2000))\nprint('J2000 Declination is {:.6f} degrees'.format(dec_J2000))\n","sub_path":"stars/code/find_RA_dec.py","file_name":"find_RA_dec.py","file_ext":"py","file_size_in_byte":7339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"149242707","text":"import os\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\nimport xxx\r\nfrom xxx import core\r\n\r\nBOT = core.Bot(command_prefix=\"\", pm_help=None, config_file=\"config.json\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n BOT.load_config()\r\n\r\n BOT.description = BOT.config.get(\"description\",\"Description Unavailable!\")\r\n\r\n prefix = BOT.config.get(\"prefix\",\"x \")\r\n\r\n prefixes = [f\"{prefix} \", f\"{prefix} \".capitalize(), prefix, prefix.capitalize()]\r\n\r\n BOT.command_prefix = commands.when_mentioned_or(*prefixes)\r\n\r\n \r\n #load all the cogs listed in config file\r\n for cog in BOT.config[\"cogs\"]:\r\n extension = f\"cogs.{cog}\"\r\n print(extension)\r\n BOT.load_extension(extension)\r\n\r\n \r\n BOT.run(BOT.config[\"discord_token\"])\r\n \r\n\r\n\r\n","sub_path":"xxxbot.py","file_name":"xxxbot.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"644799538","text":"from itertools import permutations\nimport sys\nname_list = list(map(str, sys.stdin.readline().split()))\n\nlen_name_list = len(name_list)\n\npermutation_list = list(permutations(name_list, len_name_list))\n\nname = []\nfor i in range(len(permutation_list)):\n naming = ' '.join(list(permutation_list[i]))\n print(naming)","sub_path":"My_project/Keyword_program/Combination.py","file_name":"Combination.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"272790627","text":"from django.conf.urls.defaults import patterns, url\n\nurlpatterns = patterns('',\n url(r'^$', 'app.views.home', name='home'),\n url(r'^paypal/data.json$', 'app.views.data', name='data'),\n url(r'^paypal$', 'app.views.paypal', name='paypal'),\n url(r'^graphite$', 'app.views.graphite', name='graphite'),\n url(r'^ganglia$', 'app.views.ganglia', name='ganglia'),\n url(r'^webapps/sample-manifest.webapp$', 'app.views.webapp_manifest', name='webapp-manifest'),\n url(r'^webapps/sample-image.png$', 'app.views.webapp_image', name='webapp-image'),\n)\n","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"349822542","text":"#!/usr/bin/env python\n\nimport logging\nimport optparse\nimport os\nimport re\nimport subprocess\nimport sys\nimport time\n\ndef job_status(id):\n\tlogging.debug('Entering function job_status(%s)' % id)\n\tbsub_cmd = 'bjobs %s' % (id)\n\tlogging.debug('Executing command \\'%s\\'' % bsub_cmd)\n\tbsub_out = os.popen(bsub_cmd).readlines()\n\t# 935611 ecote DONE linux_imm centos-mada mipscs508.m *60_64.sdb Aug 30 12:22\n\tlogging.debug(bsub_out[1])\n\tmatch = re.match('%s\\s+\\w+\\s+DONE' % (id), bsub_out[1])\n\tif match:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\ndef do_merge(array, level, x, y):\n\tlogging.debug('Entering function do_merge(array, %s, %s, %s)' % (level, x, y))\n\n\t# Create list of coverage files to be merged\n\tfilename = 'ax_coverage_tmp_%0d_%0d_%0d' % (level, x, y)\n\tlogging.debug('Opening file \\'%s\\'' % filename)\n\tFILE = open(filename + '.flist', 'w')\n\tfor sdb_file in array[x:y]:\n\t\tFILE.write(sdb_file)\n\tFILE.close()\n\n\t# Merge coverage data\n\tatsim_command = 'atsim +merge_cov_filelist+%s.flist +merge_cov_outfile+%s.sdb' % (filename, filename)\n\tbsub_cmd = 'bsub -q linux_imm -o %s.log \"%s\"' % (filename, atsim_command)\n\tlogging.debug('Executing command \\'%s\\'' % bsub_cmd)\n\tbsub_out = os.popen(bsub_cmd).readlines()\n\tmatch = re.match('Job <(\\d+)>', bsub_out[0])\n\tif match:\n\t\tjob_id = match.group(1)\n\t\tlogging.debug('Job ID %s returned' % job_id)\n\t\treturn job_id\n\telse:\n\t\tsys.stderr.write('Fatal Error: Unable to submit job to grid')\n\t\tsys.exit(0)\n\ndef parallel_merge(level):\n\tlogging.debug('Entering function parallel_merge(%s)' % level)\n\n\tif level == 0:\n\t\tfilename = 'ax_coverage.sdb'\n\telse:\n\t\tfilename = 'ax_coverage_tmp_%0d_*.sdb' % (int(level)-1)\n\n\n\tfind_cmd = 'find . -name \"%s\"' % (filename)\n\tlogging.debug('Executing command \\'%s\\'' % find_cmd)\n\tsdb_files = os.popen(find_cmd).readlines()\n\tsdb_count = len(sdb_files)\n\n\tif sdb_count == 1:\n\t\t# Save merged coverage file\n\t\tcopy_cmd = 'cp %s ax_coverage_merged.sdb' % sdb_files[0].rstrip()\n\t\tlogging.debug('Executing command \\'%s\\'' % copy_cmd)\n\t\tos.popen(copy_cmd)\n\t\t# Delete temporary files\n\t\trm_cmd = 'rm -f ax_coverage_tmp*'\n\t\tlogging.debug('Executing command \\'%s\\'' % rm_cmd)\n\t\tos.popen(rm_cmd)\n\t\treturn 0\n\telif sdb_count == 0:\n\t\tlogging.error('Fatal Error: Please see log file for more information')\n\t\tsys.exit(1)\n\n\t# Split the list\n\tid_list = []\n\tfor i in range(0, sdb_count/options.jobs_per_node):\n\t\tx = i*options.jobs_per_node\n\t\ty = i*options.jobs_per_node+options.jobs_per_node\n\t\tid = do_merge(sdb_files, level, x, y)\n\t\tid_list.append(id)\n\n\t # remainder\n\tx = sdb_count/options.jobs_per_node*options.jobs_per_node\n\ty = sdb_count\n\tif (x - y != 0): # corner case\n\t\tid = do_merge(sdb_files, level, x, y)\n\t\tid_list.append(id)\n\n\t# Check status\n\twhile 1:\n\t\tall_done = 1\n\t\tfor id in id_list:\n\t\t\tif job_status(id) == 0:\n\t\t\t\tall_done = 0\n\t\t\t\tbreak\n\t\tif all_done == 1:\n\t\t\tbreak\n\t\ttime.sleep(10)\n\treturn 1\n\nlogging.basicConfig(filename='.parallel_merge.log', filemode='w', level=logging.DEBUG)\n\n# Get command line arguments\nparser = optparse.OptionParser()\nparser.add_option(\"-n\", dest = 'jobs_per_node', default = '20', type = 'int', help = 'Number of jobs per node')\n(options, args) = parser.parse_args()\n\nlevel = 0\nwhile parallel_merge(level):\n\tlevel += 1\n\n\n","sub_path":"parallel_merge.py","file_name":"parallel_merge.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"371986403","text":"# Programmer: Rob Laudadio\r\n# GitHub: roblaud\r\n# Program created following a tutorial by Al Sweigart\r\n# A simple program to brute force ceaser cipher in python if no key is known\r\nimport timeit\r\n\r\nprint('What is your message?')\r\nmessage = input()\r\n\r\n#All possible symbols\r\nSYMBOLS = 'ABCDEFGHIJKLMNOPQRTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?'\r\n\r\nfor key in range(len(SYMBOLS)):\r\n translated = ''\r\n\r\n #Iterate over message checking every possible combination of symbols\r\n for symbol in message:\r\n if symbol in SYMBOLS:\r\n symbolIndex = SYMBOLS.find(symbol)\r\n translatedIndex = symbolIndex - key\r\n\r\n if translatedIndex < 0:\r\n translated = translated + SYMBOLS[translatedIndex]\r\n\r\n translated = translated + SYMBOLS[translatedIndex]\r\n else:\r\n translated = translated + symbol\r\n #All combinations will be displayed with only one being legible\r\n print('Key #%s: %s' % (key, translated))\r\n\r\n#Timer to print time in seconds rounded to 100ths decimal place\r\nprint('Time to completion: ' + str(round(timeit.default_timer(),2)) + ' Seconds')","sub_path":"brute_force_cipher.py","file_name":"brute_force_cipher.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"142549954","text":"import os\nimport shutil\n\n\ndef read_mapping():\n d_mapping = {}\n with open(PATH_MAPPING) as f:\n f.readline()\n for line in f.readlines():\n line = line.strip()\n if line == '':\n continue\n line_split = line.split(',')\n trader_name_pm = line_split[1]\n strategy_name = line_split[2]\n if strategy_name not in d_mapping.keys():\n d_mapping[strategy_name] = []\n d_mapping[strategy_name].append(trader_name_pm)\n return d_mapping\n\n\ndef main():\n # 读取mapping\n d_mapping = read_mapping()\n\n for strategy_name in os.listdir(PATH_TARGET_FOLDER):\n if strategy_name not in d_mapping.keys():\n print('strategy folder name error, ', strategy_name)\n continue\n path_strategy = os.path.join(PATH_TARGET_FOLDER, strategy_name)\n l_traders_file = [i.strip('.csv') for i in os.listdir(path_strategy)]\n l_traders_target = d_mapping[strategy_name]\n\n l_not_find = set(l_traders_file).difference(set(l_traders_target))\n l_not_exists = set(l_traders_target).difference(set(l_traders_file))\n\n if l_not_find or l_not_exists:\n if l_not_find:\n print('%s 缺少这些trader: \\n\\t%s' % (strategy_name, ',\\n\\t'.join(l_not_find)))\n if l_not_exists:\n print('%s 多了这些trader: \\n\\t%s' % (strategy_name, ',\\n\\t'.join(l_not_exists)))\n else:\n print('%s 正常,trader完全一致' % strategy_name)\n\n\nif __name__ == '__main__':\n PATH_ROOT = os.path.dirname(__file__)\n PATH_MAPPING = os.path.join(PATH_ROOT, '0.Configuration', 'Mapping.csv')\n PATH_TARGET_FOLDER = os.path.join(PATH_ROOT, '3.Output')\n\n main()\n # os.system('pause')\n","sub_path":"Night/1.SimulationData/4.CheckFiles.py","file_name":"4.CheckFiles.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"556806353","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom DataTranform import Normalizer\nfrom sklearn.preprocessing import normalize\nfrom ReadIpsData import *\ntf.set_random_seed(777) # reproducibility\nnp.random.seed(7)\n\nNormX2 = Normalizer()\nNormY2 = Normalizer()\nips = ReadIPS(r\"F:\\IPSData\")\nthicknessPath = r\"F:\\KLAData\\ThicknessData\"\nsavepath = r\"F:\\Program\\DataAnalysis\\DataAnalysis\\DataAnalysis\\save\" \nx2Temp , y2Temp , p2temp = ips.GetAllReflcThick(2 , thicknessPath)\nx2Temp = x2Temp[: , 350:850]\n\nx2Train = NormX2.Normalization( x2Temp)\ny2Train = NormY2.Normalization( y2Temp)\n\n\nx3Temp , y3Temp , p3temp = ips.GetAllReflcThick(3 , thicknessPath)\nx3Temp = x3Temp[: , 350:850]\n\nx3Train = NormX2.Normalization( x3Temp)\ny3Train = NormY2.Normalization( y3Temp)\n\n\n#x2Test = x2Train[:10,:]\n#x2Train = x2Train[11:: , : ]\n#y2Test = y2Train[:10]\n#y2Train = y2Train[11:]\n#\n#x3Test = x3Train[:10,:]\n#x3Train = x3Train[11:: , : ]\n#y3Test = y3Train[:10]\n#y3Train = y3Train[11:]\n\n\n\n\n\nxTrain = np.concatenate( (x2Train , x3Train) , axis = 0)\nyTrain = np.concatenate( (y2Train , y3Train) )\npTrain = np.concatenate( ( p2temp,p3temp) )\nyTrain = yTrain.reshape( yTrain.shape[0] , 1)\n\n#xTest = np.concatenate( (x2Test , x3Test) , axis = 0)\n#yTest = np.concatenate( (y2Test , y3Test) )\n#yTest = yTest.reshape( yTest.shape[0] , 1)\n\n\n\n\nsampleSize , iSize = xTrain.shape\n\nlr = 0.01\nh1Size = 200\nh2Size = 30\nh3Size = 10\noSize = 1\nbatchSize = 10\ntrainEpoch = 100000\n\n\n\nX = tf.placeholder( tf.float32 , [None,iSize])\nY = tf.placeholder( tf.float32 , [None,oSize])\n\n#Layer\nW1 = tf.Variable( tf.random_normal( [iSize , oSize] ) , name=\"W1\" )\nb1 = tf.Variable( tf.zeros( [oSize] ))\n\n#W2 = tf.Variable( tf.random_normal( [h1Size , h2Size] ) , name=\"W2\" )\n#b2 = tf.Variable( tf.zeros( [h2Size] ))\n#\n#W3 = tf.Variable( tf.random_normal( [h2Size , oSize] ) , name=\"W3\" )\n#b3 = tf.Variable( tf.zeros( [oSize] ))\n\n#W4 = tf.Variable( tf.random_normal( [h3Size , oSize] ) , name=\"W4\" )\n#b4 = tf.Variable( tf.zeros( [oSize] ))\nparamList = [W1,b1]\nsaver = tf.train.Saver(paramList)\n\n#Output\n \n#L1 = tf.nn.relu( tf.matmul( X , W1) + b1 )\n#L2 = tf.nn.relu( tf.matmul( L1 , W2 ) + b2)\n#L3 = tf.nn.relu( tf.matmul( L2 , W3 ) + b3)\nOutput = tf.matmul( X , W1) + b1 \n#Output = tf.matmul( L2 , W3) + b3 \n#Output = tf.nn.softmax( tf.matmul( L3 , W4 ) + b4)\n\n#Loss = tf.reduce_mean( - tf.reduce_sum( Y * tf.log( Output ) , reduction_indices = [1] ) ) \nLoss = tf.sqrt(tf.reduce_mean(tf.square(tf.subtract(Y, Output))))\n\noptimizer = tf.train.AdamOptimizer( lr ).minimize( Loss )\n\n\n#init\n\nsess =tf.Session()\nsess.run( tf.global_variables_initializer() )\nsaver.restore(sess , os.path.join(savepath , 'Best_model.ckpt')) \n\n\nLossList = []\n#LossTest = []\n\nCorrBest = 0\n\nlossTrain , _ = sess.run([Loss , optimizer] , feed_dict = { X :xTrain , Y : yTrain })\nPredict , Label = sess.run([Output , Y] , feed_dict = { X : xTrain , Y : yTrain })\nPredict = NormY2.DeNormalization(Predict) \nLabel = NormY2.DeNormalization(Label) \n\npre = np.ndarray.flatten( Predict)\nlb = np.ndarray.flatten( Label )\ncore = np.corrcoef( pre , lb )[0,1]\nprint(\"Current Best Correlation : {0}\".format(core))\n\n\nsavepath = r\"F:\\Program\\DataAnalysis\\DataAnalysis\\DataAnalysis\\result\"\n\npre.tofile( os.path.join(savepath, \"Predict.csv\") ,sep=',')\nlb.tofile( os.path.join(savepath, \"Label.csv\"), sep=',')\npTrain.tofile( os.path.join(savepath, \"Point.csv\"), sep=',')\n\nprint(pre.shape)\nprint(lb.shape)\n\n#for i in range(0,xTrain.shape[0]):\n# print(\"Predict : {0} Target L {1}\".format( Predict[i], Label[i]))\n\nplt.title( \"Corr\" )\nplt.xlabel( \"Predict\" )\nplt.ylabel( \"Target\" )\nplt.scatter(pre , lb )\n#plt.plot(LossTest , 'b' )\nplt.show()\n \n\n\n\n\n\n\n\n\n\n","sub_path":"Result_Backup/DataAnalysis_20171026/DataAnalysis/IPS/IPSCheckModel.py","file_name":"IPSCheckModel.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"410272281","text":"from core.models.data_source_format_master import DataSourceFormatMaster\nfrom google_spreadsheet_api.function import (\n get_gsheet_name,\n get_list_of_sheet_title,\n get_df_from_speadsheet,\n)\nimport time\nimport pandas as pd\nfrom termcolor import colored\nimport json\n\n\ndef get_gsheet_id_from_url(url: object) -> object:\n url_list = url.split(\"/\")\n gsheet_id = url_list[5]\n return gsheet_id\n\n\ndef get_key_value_from_gsheet_info(gsheet_info: str, key: str):\n value = json.loads(gsheet_info)[key]\n return value\n\n\ndef add_key_value_from_gsheet_info(gsheet_info: str, key_value: dict):\n sheet_info_log_ = json.loads(gsheet_info)\n for key, value in key_value.items():\n sheet_info_log_[key] = value\n sheet_info_log = json.dumps(sheet_info_log_)\n return sheet_info_log\n\n\nclass WhenExist:\n SKIP = \"skip\"\n REPLACE = \"replace\"\n KEEP_BOTH = \"keep both\"\n\n\nclass ObjectType:\n ARTIST = \"artist\"\n ALBUM = \"album\"\n TRACK = \"track\"\n\n\nclass DataReports:\n column_name = [\n \"gsheet_name\",\n \"gsheet_url\",\n \"type\",\n \"running_time\",\n \"status\",\n \"count_complete\",\n \"count_incomplete\",\n \"notice\",\n ]\n status_type_processing = \"processing\"\n status_type_done = \"done\"\n\n\nclass SheetNames:\n MP3_SHEET_NAME = \"MP3_SHEET_NAME\"\n MP4_SHEET_NAME = \"MP4_SHEET_NAME\"\n VERSION_SHEET_NAME = \"VERSION_SHEET_NAME\"\n ARTIST_IMAGE = \"ARTIST_IMAGE\"\n ALBUM_IMAGE = \"ALBUM_IMAGE\"\n ARTIST_WIKI = \"ARTIST_WIKI\"\n ALBUM_WIKI = \"ALBUM_WIKI\"\n TRACK_WIKI = \"TRACK_WIKI\"\n S_11 = \"S_11\"\n C_11 = \"C_11\"\n\n\nclass PageType:\n class NewClassic:\n name = \"NewClassic\"\n priority = 530\n\n class TopSingle:\n name = \"TopSingle\"\n priority = 530\n\n class TopAlbum:\n name = \"TopAlbum\"\n priority = 100\n\n class Contribution:\n name = \"contribution\"\n priority = 520\n\n class ArtistPage:\n name = \"ArtistPage\"\n priority = 80\n\n\nclass Page(object):\n def __init__(self, url: str):\n self.gsheet_id = get_gsheet_id_from_url(url=url)\n self.url = url\n self.page_name = get_gsheet_name(gsheet_id=self.gsheet_id)\n self.sheet_name_type = self.SheetNameType(url=self.url)\n\n class SheetNameType:\n def __init__(self, url: str):\n gsheet_id = get_gsheet_id_from_url(url=url)\n list_of_sheet_title = get_list_of_sheet_title(gsheet_id=gsheet_id)\n sheet_names = get_list_of_sheet_title(gsheet_id=gsheet_id)\n if \"MP_3\" in sheet_names:\n self.MP3_SHEET_NAME = {\n \"sheet_name\": \"MP_3\",\n \"fomatid\": DataSourceFormatMaster.FORMAT_ID_MP3_FULL,\n \"column_name\": [\n \"track_id\",\n \"memo\",\n \"mp3_link\",\n \"url_to_add\",\n \"type\",\n \"checking_mp3\",\n \"already_existed\",\n \"is_released\",\n \"assignee\",\n ],\n }\n if \"MP_4\" in sheet_names:\n self.MP4_SHEET_NAME = {\n \"sheet_name\": \"MP_4\",\n \"fomatid\": DataSourceFormatMaster.FORMAT_ID_MP4_FULL,\n \"column_name\": [\n \"track_id\",\n \"memo\",\n \"mp4_link\",\n \"url_to_add\",\n \"checking_mp4\",\n \"already_existed\",\n \"is_released\",\n \"verified\",\n \"assignee\",\n ],\n }\n if \"Version_done\" in sheet_names:\n self.VERSION_SHEET_NAME = {\n \"sheet_name\": \"Version_done\",\n \"fomatid\": [\n DataSourceFormatMaster.FORMAT_ID_MP4_REMIX,\n DataSourceFormatMaster.FORMAT_ID_MP4_LIVE,\n ],\n \"column_name\": [\n \"track_id\",\n \"remix_url\",\n \"remix_artist\",\n \"live_url\",\n \"live_venue\",\n \"live_year\",\n ],\n }\n if f\"{SheetNames.ARTIST_IMAGE} cant upload\" in list_of_sheet_title:\n if get_df_from_speadsheet(\n gsheet_id, f\"{SheetNames.ARTIST_IMAGE} cant upload\"\n ).values.tolist() == [[\"Upload thành công 100% nhé các em ^ - ^\"]]:\n pass\n else:\n sheet_name = f\"{SheetNames.ARTIST_IMAGE} cant upload\"\n self.ARTIST_IMAGE = {\n \"sheet_name\": f\"{sheet_name}\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\"],\n \"object_type\": ObjectType.ARTIST,\n }\n elif \"image\" in list_of_sheet_title:\n sheet_name = \"image\"\n self.ARTIST_IMAGE = {\n \"sheet_name\": f\"{sheet_name}\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\"],\n \"object_type\": ObjectType.ARTIST,\n }\n elif \"Artist_image\" in list_of_sheet_title:\n sheet_name = \"Artist_image\"\n self.ARTIST_IMAGE = {\n \"sheet_name\": f\"{sheet_name}\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\"],\n \"object_type\": ObjectType.ARTIST,\n }\n else:\n pass\n if \"Album_image\" in sheet_names:\n self.ALBUM_IMAGE = {\n \"sheet_name\": \"Album_image\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\"],\n \"object_type\": ObjectType.ALBUM,\n }\n if \"Artist_wiki\" in sheet_names:\n self.ARTIST_WIKI = {\n \"sheet_name\": \"Artist_wiki\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\", \"content_to_add\"],\n \"table_name\": \"artists\",\n }\n if \"Album_wiki\" in sheet_names:\n self.ALBUM_WIKI = {\n \"sheet_name\": \"Album_wiki\",\n \"column_name\": [\"uuid\", \"memo\", \"url_to_add\", \"content_to_add\"],\n \"table_name\": \"albums\",\n }\n if \"Track_wiki\" in sheet_names:\n self.TRACK_WIKI = {\n \"sheet_name\": \"Track_wiki\",\n \"column_name\": [\"id\", \"memo\", \"url_to_add\", \"content_to_add\"],\n \"table_name\": \"tracks\",\n }\n if \"S_11\" in sheet_names:\n self.S_11 = {\n \"sheet_name\": \"S_11\",\n \"column_name\": [\n \"release_date\",\n \"album_title\",\n \"album_artist\",\n \"itune_album_url\",\n \"sportify_album_url\",\n ],\n }\n if \"Youtube collect_experiment\" in sheet_names:\n self.C_11 = {\n \"sheet_name\": \"Youtube collect_experiment\",\n \"column_name\": [\n \"pre_valid\",\n \"p.i.c\",\n \"itune_album_url\",\n \"official_music_video_2\",\n \"artist_name\",\n \"year\",\n \"live_concert_name_place\",\n \"track_title/track_num\",\n \"contribution_link\",\n \"content type\",\n \"pointlogsid\",\n \"itune_id\",\n \"region\",\n \"checking_validate_itune\",\n \"06_id\",\n \"06_status\",\n \"e5_id\",\n \"e5_status\",\n \"track_title\",\n \"track_id\",\n \"similarity\",\n \"recheck\",\n \"d9_id\",\n \"d9_status\",\n ],\n }\n\n def process_file(self, sheet_info: str):\n sheet_name = sheet_info.get(\"sheet_name\")\n column_names = sheet_info.get(\"column_name\")\n df = get_df_from_speadsheet(gsheet_id=self.gsheet_id, sheet_name=sheet_name)\n\n lower_names = [name.lower() for name in df.columns]\n df.columns = lower_names\n\n if sheet_name in get_list_of_sheet_title(gsheet_id=self.gsheet_id):\n # reformat_column_name\n df.columns = df.columns.str.replace(\"track_id\", \"track_id\")\n df.columns = df.columns.str.replace(\"track id\", \"track_id\")\n df.columns = df.columns.str.replace(\"trackid\", \"track_id\")\n\n df.columns = df.columns.str.replace(\"s12\", \"memo\")\n df.columns = df.columns.str.replace(\"a12\", \"memo\")\n\n df.columns = df.columns.str.replace(\"mp3_link\", \"mp3_link\")\n df.columns = df.columns.str.replace(\"mp3link\", \"mp3_link\")\n df.columns = df.columns.str.replace(\"mp4_link\", \"mp4_link\")\n df.columns = df.columns.str.replace(\"mp4link\", \"mp4_link\")\n\n df.columns = df.columns.str.replace(\"url to add\", \"url_to_add\")\n df.columns = df.columns.str.replace(\"artist_url_to_add\", \"url_to_add\")\n\n df.columns = df.columns.str.replace(\"artist_uuid\", \"uuid\")\n df.columns = df.columns.str.replace(\"objectid\", \"uuid\")\n df.columns = df.columns.str.replace(\"album_uuid\", \"uuid\")\n\n df.columns = df.columns.str.replace(\"content tomadd\", \"content_to_add\")\n\n df.columns = df.columns.str.replace(\"albumtitle\", \"album_title\")\n df.columns = df.columns.str.replace(\"albumartist\", \"album_artist\")\n df.columns = df.columns.str.replace(\"itunes_album_url\", \"itune_album_url\")\n df.columns = df.columns.str.replace(\"itunes_album_link\", \"itune_album_url\")\n df.columns = df.columns.str.replace(\"albumurl\", \"sportify_album_url\")\n\n df_columns = df.columns\n column_name_reformat = []\n for column_name in column_names:\n if column_name in df_columns:\n column_name_reformat.append(column_name)\n df = df[column_name_reformat]\n return df\n else:\n print(f\"sheet_name: {sheet_name} not have\")\n\n def media_file(self, sheet_info: object, page_priority: int):\n df = self.process_file(sheet_info=sheet_info)\n info = {\n \"url\": f\"{self.url}\",\n \"gsheet_id\": f\"{self.gsheet_id}\",\n \"gsheet_name\": f\"{get_gsheet_name(gsheet_id=self.gsheet_id)}\",\n \"sheet_name\": f\"{sheet_info.get('sheet_name')}\",\n \"page_type\": \"top_single\",\n \"page_priority\": page_priority,\n }\n df[\"gsheet_info\"] = df.apply(lambda x: json.dumps(info), axis=1)\n return df\n\n\n# media_file = Page.media_file\nSheetNameType = Page.SheetNameType\n\n\ndef merge_file(sheet_name: str, urls: list, page_type: object = None):\n # Step 1: remove duplicate url\n url_reformats = list(\n set(\n map(\n lambda x: \"https://docs.google.com/spreadsheets/d/\"\n + get_gsheet_id_from_url(x),\n urls,\n )\n )\n )\n # print(url_reformats)\n priority = page_type.priority\n df = pd.DataFrame()\n for url in url_reformats:\n try:\n page = Page(url=url)\n sheet_info = getattr(page.sheet_name_type, sheet_name)\n df_ = page.media_file(sheet_info=sheet_info, page_priority=priority)\n df = df.append(df_, ignore_index=True)\n except AttributeError:\n print(\n colored(\n f\"AttributeError: {page.page_name} object has no attribute {sheet_name}\\nurl: {url}\",\n \"yellow\",\n )\n )\n return df\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n pd.set_option(\n \"display.max_rows\", None, \"display.max_columns\", 50, \"display.width\", 1000\n )\n urls = [\n \"https://docs.google.com/spreadsheets/d/1byh3LFm1NhzFPLfROyS9kwgqKKG2P8k7aTnGQXAXr-o/edit#gid=1962142102\"\n ]\n\n sheet_name = SheetNames.C_11\n page_type = PageType.Contribution\n k = merge_file(sheet_name=sheet_name, urls=urls, page_type=page_type)\n print(k.head(10))\n\n # get_df_from_speadsheet(gsheet_id=\"1ZgMTydySAvqoyJgo4OZchQVC42NZgHbzocdy50IH2LY\", sheet_name=\"S_11\")\n\n print(\"\\n --- total time to process %s seconds ---\" % (time.time() - start_time))\n","sub_path":"Data_lake_process/class_definition.py","file_name":"class_definition.py","file_ext":"py","file_size_in_byte":12874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"257535860","text":"150# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 2 02:07:50 2019\r\n\r\n@author: Mahmoud Ashraf\r\n\"\"\"\r\n\r\nannual_salary = int(input(\"Enter your starting annual salary: \"))\r\nportion_saved = float(input(\"Enter portion of salary to \\\r\nbe saved, as decimal: \"))\r\ntotal_cost = int(input(\"Enter cost of your dream home: \"))\r\n\r\nsemi_annual_raise = float(input(\"Enter your semi-annual salary raise \\\r\n, as decimal: \"))\r\n\r\n\r\nportion_down_payment = 0.25 * total_cost\r\ncurrent_savings = 0\r\n\r\nnumber_of_months = 0\r\nwhile current_savings < portion_down_payment:\r\n if number_of_months % 6 == 0 and number_of_months != 0:\r\n annual_salary += annual_salary * semi_annual_raise\r\n \r\n current_savings += portion_saved * annual_salary / 12 \\\r\n + current_savings * 0.04 / 12\r\n number_of_months += 1\r\n \r\n\r\nprint(\"Number of months: \" , number_of_months)","sub_path":"ps1-house_hunting/ps1-b.py","file_name":"ps1-b.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"614222322","text":"from locust import HttpUser, task, between\nfrom random import sample\nimport faker\n\n\nfake = faker.Faker()\n\nexistingWords = ['Goods', 'Department', 'nostrud']\n\nclass CommonUser(HttpUser):\n\n @task(1)\n def get_product_id(self):\n # self.client.get('/products/' + str(fake.random_int(3, 100000)), name='product_id')\n # self.client.get('/products/product?criteriaString=Goods', name='product_search_2')\n self.client.get('/search?q=' + fake.word(), name='product_non_existing_search')\n\n\n @task(10)\n def search(self):\n # self.client.get('/search?q=' + fake.word(), name='product_search')\n randomExistingWord = sample(existingWords, 1)[0]\n self.client.get('/processing/history?criteriaString=' + randomExistingWord, name='product_existing_work_search')\n\n wait_time = between(5, 15)","sub_path":"load_testing_script/locustfile.py","file_name":"locustfile.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"585030642","text":"import cmath\nimport sys\nimport os\nimport time\nimport math\nimport numpy as np\nimport numpy.fft\nimport pylab\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom scipy import stats\nimport Keithley\nimport getfreqs\nimport vnasweep\nfrom scipy.signal import butter, filtfilt, lfilter\n\ndef butter_lowpass(cutoff, fs, order=5):\n nyq = 0.5 * fs\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\n return b, a\n \ndef butter_lowpass_filtfilt(data, cutoff, fs, order=5):\n b, a = butter_lowpass(cutoff, fs, order=order)\n y = filtfilt(b, a, data,method='gust')\n return y\n \ndef hanning(i,N,data):\n return data*0.5*(1-math.cos(2*math.pi*i/(N-1)))\n \ndatafolder = \"Data\\\\ILrun2\"\n\nampdata = []\nphasedata = []\naxisdata = []\nrefampdata = []\nrefphasedata = []\nrefaxisdata = []\n\n#list to keep track of what references have been plotted!\nplottedrefs = []\n\ndiodesweep = vnasweep.extractsweep(datafolder + '\\\\device_fixed.txt')\nref1 = vnasweep.extractsweep(datafolder + \"\\\\ref1_fixed.txt\")\nref2 = vnasweep.extractsweep(datafolder + \"\\\\ref2_fixed.txt\")\nref = vnasweep.avgsweeps(ref1,ref2)\naxisdata = diodesweep[:,0]\nampdata = diodesweep[:,1] - ref[:,1]\nphasedata = (diodesweep[:,2] - ref[:,2]+180)%360 - 180\nrefampdata.append(ref1[:,1])\nrefphasedata.append(ref1[:,2])\nrefaxisdata.append(ref1[:,0])\nrefampdata.append(ref2[:,1])\nrefphasedata.append(ref2[:,2])\nrefaxisdata.append(ref2[:,0])\n\nampdata = np.array(ampdata)\nphasedata = np.array(phasedata)\naxisdata = np.array(axisdata)\nrefampdata = np.array(refampdata)\nrefphasedata = np.array(refphasedata)\nrefaxisdata = np.array(refaxisdata)\n\nprint(np.shape(ampdata))\nprint(np.shape(phasedata))\nprint(np.shape(axisdata))\n\nfig1 = plt.figure(1)\nax11 = fig1.add_subplot(221)\nax12 = fig1.add_subplot(222)\nax13 = fig1.add_subplot(223)\nax14 = fig1.add_subplot(224)\n\nax11.plot(axisdata,ampdata)\nax12.plot(axisdata,phasedata)\n \nfor i in range(0,len(refampdata)):\n ax13.plot(refaxisdata[i],refampdata[i],label = \"Ref#\" + str(i))\n ax14.plot(refaxisdata[i],refphasedata[i],label = \"Ref#\" + str(i))\n \nax13.legend(loc = 'upper right')\nax14.legend(loc = 'upper right')\n\n#plot smoothed data in different ways\ncutoff = 1.0/7.75\nfreqspacing = 0.5 #in GHz\norder = 7 #filter order\nfs = 1/freqspacing #f_sample in units of 1/GHz or nS\ntnyq = fs/2 #in ns\nampdata_smooth = butter_lowpass_filtfilt(ampdata, cutoff, fs, order)\n\n### Try time domain gating with FFT's ###\n\nwindowdata = 0\n\n#re-insert phase information\nampphasedata = []\nphaseoffset = 0\nfor i in range(0,len(ampdata)):\n ampphasedata.append(10**(ampdata[i]/20)*(math.cos((phasedata[i]+phaseoffset)*math.pi/180.0) + 1j*math.sin((phasedata[i]+phaseoffset)*math.pi/180.0)))\n\n#window data \nampdata_windowed = []\nfor i in range(0,len(ampdata)):\n ampdata_windowed.append(hanning(i,len(ampphasedata),ampphasedata[i]))\n\nphasespeed = 46.429 #deg per GHz\npadnum = int(round(3*order/cutoff))#int(round((len(ampdata)-1)/2.0))\n#pad data with zeros or last element phase corrected\npaddatalow = []\npaddatahigh = []\nfor i in range(0,padnum):\n paddatalow.append(ampphasedata[0]*cmath.exp(1j*(i-padnum)*phasespeed*freqspacing*math.pi/180.0))\n paddatahigh.append(ampphasedata[len(ampphasedata)-1]*cmath.exp(1j*(i+1)*phasespeed*freqspacing*math.pi/180.0))\nif windowdata == 1:\n ampphasedata_pad = np.concatenate((paddatalow,ampdata_windowed,paddatahigh))\nelse:\n ampphasedata_pad = np.concatenate((paddatalow,ampphasedata,paddatahigh))\n\n#take fft to convert to time domain\nampdata_fft = numpy.fft.fft(ampphasedata)\nampdata_windowed_fft = numpy.fft.fft(ampdata_windowed)\nampdata_fft_pad = numpy.fft.fft(ampphasedata_pad)\nfft_axis = np.linspace(-tnyq,tnyq,len(ampdata))\nfft_pad_axis = np.linspace(-tnyq,tnyq,len(ampphasedata_pad))\n\nt0 = -0.878 #ns center of device offset\n#filter in time domain\nampdata_fft_filt = []\nampdata_fft_pad_filt = []\nampdata_fft_chop = []\nfor i in range(0,len(ampdata)):\n #figure out deltat\n if t0 > 0:\n if fft_axis[i] >= t0-tnyq:\n deltat = fft_axis[i]-t0\n else:\n deltat = 2*tnyq + fft_axis[i] - t0\n if t0 < 0:\n if fft_axis[i] < t0 + tnyq:\n deltat = fft_axis[i]-t0\n else:\n deltat = -2*tnyq + fft_axis[i] - t0\n else:\n deltat = fft_axis[i] - t0\n ampdata_fft_filt.append(ampdata_fft[i]/(1+(abs(deltat)/cutoff)**(2*order)))\n \nfor i in range(0,len(ampphasedata_pad)):\n #figure out deltat\n if t0 > 0:\n if fft_pad_axis[i] >= t0-tnyq:\n deltat = fft_pad_axis[i]-t0\n else:\n deltat = 2*tnyq + fft_pad_axis[i] - t0\n if t0 < 0:\n if fft_pad_axis[i] < t0 + tnyq:\n deltat = fft_pad_axis[i]-t0\n else:\n deltat = -2*tnyq + fft_pad_axis[i] - t0\n else:\n deltat = fft_pad_axis[i] - t0\n ampdata_fft_pad_filt.append(ampdata_fft_pad[i]/(1+(abs(deltat)/cutoff)**(2*order)))\n\nampdata_rot = []\naxisdata_rot = []\nfft_axis_chop = []\nminoff = tnyq\nrotindex = -1\nzeropad = 0\n#cycle ampdata and axisdata until t0 ~ 0\nfor i in range(0,len(ampphasedata)):\n if abs(fft_axis[i] - t0) < minoff:\n minoff = abs(fft_axis[i] - t0)\n rotindex = i\nfor i in range(0,len(ampphasedata)):\n newindex = ((i+rotindex)+ (len(ampdata_fft)-1)/2)%len(ampdata_fft) \n ampdata_rot.append(ampdata_fft[newindex])\n axisdata_rot.append(fft_axis[newindex])\nfor i in range(0,len(ampphasedata)):\n if abs(fft_axis[i]) <= cutoff: \n ampdata_fft_chop.append(ampdata_rot[i])\n fft_axis_chop.append(fft_axis[i])\n elif zeropad == 1:\n ampdata_fft_chop.append(0)\n fft_axis_chop.append(fft_axis[i])\nfreqaxis_chop = np.linspace(220,330,len(ampdata_fft_chop)) \n\n#take fft back to freq space\nampdata_ifft = np.fft.ifft(ampdata_fft_filt)\nampdata_pad_ifft = np.fft.ifft(ampdata_fft_pad_filt)\nampdata_ref = np.fft.ifft(ampdata_fft)\nampdata_chop = np.fft.ifft(ampdata_fft_chop)*len(ampdata_fft_chop)/len(ampdata)\n\n#now remove zero padding\nampdata_pad_ifft_remove = []\nfor i in range(0,len(ampdata_pad_ifft)):\n if i >= padnum and i < len(ampdata_pad_ifft) - padnum:\n ampdata_pad_ifft_remove.append(ampdata_pad_ifft[i])\nprint(len(ampdata_pad_ifft_remove))\n\nnormindex = int(round((len(ampdata)-1)/2.0))\nnorm = (ampdata_ref[normindex]/ampphasedata[normindex])\nprint(norm)\n\nfig2 = plt.figure(2)\nax21 = fig2.add_subplot(121)\nax22 = fig2.add_subplot(122)\nax22.set_xlabel(r'$\\Delta$t (nS)')\n\nfig4 = plt.figure(4)\nax41 = fig4.add_subplot(111)\nax41.set_xlabel(r'$\\Delta$t (pS)',fontsize=14)\nax41.set_ylabel(r'S$_{21}$ (dB)',fontsize=14)\nax41.set_title('Time Domain Insertion Loss')\nax41.set_ylim(-70,0)\nax41.grid()\n#find max index\nmax = -100\nmaxindex = -1\nfor i in range(0,len(ampdata_windowed_fft)):\n if max < np.absolute(np.fft.fftshift(ampdata_windowed_fft))[i]:\n max = np.absolute(np.fft.fftshift(ampdata_windowed_fft))[i]\n maxindex = i\nmaxtime = 1000*fft_axis[maxindex]\nprint(maxtime)\nmaxtime = 1000*(t0 + tnyq)\nleftwindow = [maxtime - 1000*cutoff,maxtime - 1000*cutoff]\nrightwindow = [maxtime + 1000*cutoff,maxtime + 1000*cutoff]\nwindowdata = [-70,0]\n\nax41.plot(1000*fft_axis,20*np.log10(np.absolute(1.0/len(ampdata)*np.fft.fftshift(ampdata_windowed_fft))),c='r',linewidth = 2,label=r'S$_{21}$')\nax41.plot(leftwindow,windowdata,c='k',linestyle = '--',linewidth = 2,label = 'Gate Window')\nax41.plot(rightwindow,windowdata,c='k',linestyle = '--',linewidth = 2)\nax41.text(maxtime+1000*cutoff+50, -10, 'Gate Window', fontsize=14)\n#ax41.legend(loc='upper right')\n\nax21.plot(axisdata,ampdata,c='r',label='Raw Data')\n#ax21.plot(axisdata,20*np.log10(np.absolute(ampphasedata)),label = 'Complex Data')\n#ax21.plot(axisdata,20*np.log10(np.absolute(ampdata_ifft)),label = 'Filtered')\nax21.plot(axisdata,20*np.log10(np.absolute(ampdata_pad_ifft_remove)),c='g',linewidth = 3,label = 'Hand Time Domain Gated')\n#ax21.plot(axisdata,20*np.log10(np.absolute(ampdata_ref)),label='Reference')\nax21.plot(axisdata,ampdata_smooth,linewidth=3,c='b',label='Time Domain Gated')\nax21.plot(freqaxis_chop,20*np.log10(np.absolute(ampdata_chop)),linewidth=3,c='k',label='Chop Data')\n\nax22.plot(fft_axis,np.real(ampdata_fft),label = 'Re Raw')\nax22.plot(fft_axis,np.imag(ampdata_fft),label = 'Im Raw')\nax22.plot(fft_axis,np.real(ampdata_rot),label = 'Re Rot')\nax22.plot(fft_axis,np.imag(ampdata_rot),label = 'Im Rot')\nax22.plot(fft_axis_chop,np.real(ampdata_fft_chop),label = 'Re Rot Chop')\nax22.plot(fft_axis_chop,np.imag(ampdata_fft_chop),label = 'Im Rot Chop')\n#ax22.plot(fft_axis,20*np.log10(np.absolute(ampdata_fft)),label = 'Mag Raw')\nax22.plot(fft_axis,np.real(ampdata_fft_filt),label = 'Re Filtered')\nax22.plot(fft_axis,np.imag(ampdata_fft_filt),label = 'Im Filtered')\n#ax22.plot(fft_axis,20*np.log10(np.absolute(ampdata_fft_filt)),label = 'Mag Filtered')\nax22.plot(fft_pad_axis,np.real(ampdata_fft_pad),label = 'Re Padded')\nax22.plot(fft_pad_axis,np.imag(ampdata_fft_pad),label = 'Im Padded')\n#ax22.plot(fft_pad_axis,20*np.log10(np.absolute(ampdata_fft_pad)),label = 'Mag Padded')\n\nax21.legend(loc='upper right') \nax22.legend(loc='upper right')\n\nfig3 = plt.figure(3)\nax31 = fig3.add_subplot(111)\nax31.set_title(\"On-State Insertion Loss\",fontsize=18)\nax31.set_xlabel(\"Freq. (GHz)\",fontsize=16)\nax31.set_ylabel(r'S$_{\\rm 21}$ (dB)',fontsize=16)\nax31.grid()\nax31.set_xlim(220,330)\nax31.set_ylim(-2.5,0.5)\n\nax31.plot(axisdata,ampdata,c='r',label='Raw Data')\nax31.plot(axisdata,ampdata_smooth,linewidth=3,c='b',label='Time Domain Gated')\n#ax31.plot(freqaxis_chop,20*np.log10(np.absolute(ampdata_chop)),linewidth=3,c='k',label='Chop Data')\n\nax31.legend(loc = 'upper right')\n\nplt.show()","sub_path":"receiverLab/legacy/meas/VNA/WR3_QO/plot_wr3_att_IL.py","file_name":"plot_wr3_att_IL.py","file_ext":"py","file_size_in_byte":9608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"137753273","text":"#!/usr/bin/env python\n# coding:utf-8\n'''\nCandlestick events analyzer\n'''\nfrom __future__ import print_function\n\nfrom datetime import datetime\nfrom helpers import talib_candlestick_funcs, load_symbols, show_candlestick, find_candlestick_patterns\nfrom mktdata import MktTypes, init_marketdata, get_mkt_data\n\n\nclass AverageChange(object):\n ''' Class for calculating normalized average values '''\n def __init__(self, size):\n self._dict = {}\n for x in MktTypes:\n self._dict[x] = [(0, 0)] * size\n\n def add_item(self, type, idx, relative_val, val):\n acc = self._dict[type][idx][0] + float(val)/relative_val\n cnt = self._dict[type][idx][1] + 1\n self._dict[type][idx] = (acc, cnt)\n\n def add(self, type, relative_val, vals):\n for idx, val in enumerate(vals):\n self.add_item(type, idx, relative_val, val)\n\n def average(self, type):\n return [acc/cnt for (acc, cnt) in self._dict[type] if cnt > 0]\n\n def cnt(self):\n return self._dict['open'][0][1]\n\n def __repr__(self):\n val = ['%s: %s' % (x, str(self.average(x))) for x in MktTypes]\n return '' % (self.cnt(), '\\n'.join(val))\n\n\nCONSIDERED_NDAYS = 10\n\n\nclass CandlestickPatternEvents(object):\n ''' Class for finding candlestick pattern events and counting average changes. '''\n def __init__(self, symbols, candlestick_funcitons, from_date, to_date):\n self._symbols = symbols\n self._avgs = {}\n self._palg = candlestick_funcitons\n self._from_date = from_date\n self._to_date = to_date\n\n def __get_average_changes(self):\n for k in self._avgs.keys():\n yield (k, self._avgs[k])\n average_changes = property(__get_average_changes)\n\n def _process_patterns(self, res, mdata, alg):\n for (idx, val) in res:\n next_day_open = mdata['open'][idx + 1] if idx + 1 < len(mdata['open']) else 0\n for m in MktTypes:\n key = '%s:%d' % (alg, val)\n if key not in self._avgs:\n self._avgs[key] = AverageChange(CONSIDERED_NDAYS)\n self._avgs[key].add(m, next_day_open, mdata[m][idx + 1:idx + 1 + min(CONSIDERED_NDAYS, len(mdata['open']) - (idx+1))])\n\n def __call__(self):\n for s in self._symbols:\n mdata = get_mkt_data(s, self._from_date, self._to_date)\n for a in self._palg:\n res = find_candlestick_patterns(a, mdata)\n self._process_patterns(res, mdata, a)\n return self\n\n\ndef output_results(average_changes, diff_level, min_cnt):\n #TODO: output results and graphs to files/html\n\n i = 0\n for (k, val) in average_changes:\n mn = mx = 1.0\n for x in ['open', 'close']:\n v = val.average(x)\n mn = min(mn, min(v))\n mx = max(mx, max(v))\n if (mx > 1.0 + diff_level or mn < 1.0 - diff_level) and val.cnt() >= min_cnt:\n print(k)\n print(repr(val))\n i += 1\n val = [val.average(t) for t in [MktTypes[0], MktTypes[3], MktTypes[1], MktTypes[2]]]\n days = [[x for x in range(len(val[0]))]] # put fake dates\n quotes = days + val\n quotes = zip(*quotes)\n show_candlestick(quotes)\n print('Total: %d' % i)\n\n\ndef main(fname, from_date, to_date):\n symbols = load_symbols(fname)\n init_marketdata(symbols, from_date, to_date)\n\n palg = talib_candlestick_funcs()\n\n c = CandlestickPatternEvents(symbols, palg, from_date, to_date)()\n\n diff_level = 0.02 # output patterns where up/down > diff_level\n min_cnt = 5 # output patterns with > min_cnt events\n\n output_results(c.average_changes, diff_level, min_cnt)\n\n\nif __name__ == '__main__':\n from_date = datetime(2012, 1, 1)\n to_date = datetime(2012, 12, 31)\n main('idx_ftse100.txt', from_date, to_date)\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"604319829","text":"from pathlib import Path\nimport shutil\n\nimport click\n\nLIBAI_FILE_SUFFIX = '.csv'\nGARMIN_FIT_SUFFIX = '.fit'\nPOLAR_CSV_SUFFIX = '.csv'\n\nLIBAI_FILE_PREFIX = 'libai_'\nGARMIN_FIT_PREFIX = 'garmin_'\nPOLAR_CSV_PREFIX = 'polar_'\n\nCLEANED_DIR = Path().home() / 'data/new-sensor-bucket/libai/heartrate/cleaned'\nLIBAI_CLEANED_DIR = CLEANED_DIR / 'libai'\nGARMIN_CLEANED_DIR = CLEANED_DIR / 'garmin'\nPOLAR_CLEANED_DIR = CLEANED_DIR / 'polar'\n\n\ndef rename_and_clean_libai_record(source_dir: Path, target_dir: Path,\n libai_file_suffix: str):\n source_dir = Path(source_dir)\n target_dir = Path(target_dir)\n\n assert source_dir != target_dir\n\n for file_path in source_dir.rglob(f'*{libai_file_suffix}'):\n file_name = file_path.name\n\n if len(file_name.split('.')) == 3: # Unvisiable file in __MAXCOSX\n print(f'Unvalid file: {file_path}')\n continue\n\n file_new_name = LIBAI_FILE_PREFIX + file_name\n libai_name = file_path.parent.name\n libai_date_str = '-'.join(libai_name.split('_')[:3])\n save_dir = target_dir / libai_date_str / libai_name\n save_dir.mkdir(parents=True, exist_ok=True)\n file_new_path = save_dir / file_new_name\n shutil.copyfile(file_path, file_new_path)\n print(f'Copy {file_path.name} to {file_new_path.name}')\n print(f'Succeed: copy {source_dir} to {LIBAI_CLEANED_DIR}')\n\n\ndef rename_and_clean_garmin_fit(source_dir: Path, target_dir: Path,\n garmin_fit_suffix: str):\n source_dir = Path(source_dir)\n target_dir = Path(target_dir)\n\n for garmin_fit_path in source_dir.rglob(f'*{garmin_fit_suffix}'):\n tag = garmin_fit_path.parents[1].name\n\n garmin_fit_name = garmin_fit_path.name\n garmin_new_name = GARMIN_FIT_PREFIX + garmin_fit_name\n\n garmin_date_str = '-'.join(garmin_fit_name.split('-')[:3])\n\n save_dir = target_dir / garmin_date_str / tag\n\n save_dir.mkdir(parents=True, exist_ok=True)\n\n garmin_fit_new_path = save_dir / garmin_new_name\n\n shutil.copyfile(garmin_fit_path, garmin_fit_new_path)\n\n print(f'Copy {garmin_fit_path.name} to {garmin_fit_new_path}')\n\n\ndef rename_and_clean_polar_csv(source_dir: Path, target_dir: Path,\n polar_csv_suffix: str):\n source_dir = Path(source_dir)\n target_dir = Path(target_dir)\n\n for polar_csv_path in source_dir.rglob(f'*{polar_csv_suffix}'):\n tag = polar_csv_path.parents[1].name\n\n polar_csv_name = polar_csv_path.name\n polar_new_name = POLAR_CSV_PREFIX + polar_csv_name\n\n polar_date_str = '-'.join(polar_csv_name.split('_')[1].split('-')[:3])\n\n save_dir = target_dir / polar_date_str / tag\n\n save_dir.mkdir(parents=True, exist_ok=True)\n\n polar_fit_new_path = save_dir / polar_new_name\n\n shutil.copyfile(polar_csv_path, polar_fit_new_path)\n\n print(f'Copy {polar_csv_path.name} to {polar_fit_new_path}')\n\n\ndef run(libai_source_dir: Path, garmin_source_dir: Path,\n polar_source_dir: Path):\n\n if libai_source_dir is not None and Path(libai_source_dir).exists():\n rename_and_clean_libai_record(libai_source_dir, LIBAI_CLEANED_DIR,\n LIBAI_FILE_SUFFIX)\n if garmin_source_dir is not None and Path(garmin_source_dir).exists():\n rename_and_clean_garmin_fit(garmin_source_dir, GARMIN_CLEANED_DIR,\n GARMIN_FIT_SUFFIX)\n\n if polar_source_dir is not None and Path(polar_source_dir).exists():\n rename_and_clean_polar_csv(polar_source_dir, POLAR_CLEANED_DIR,\n POLAR_CSV_SUFFIX)\n\n\n@click.command()\n@click.option('-libai', '--libai-source-dir', type=str)\n@click.option('-garmin', '--garmin-source-dir', type=str)\n@click.option('-polar', '--polar-source-dir', type=str)\ndef main(libai_source_dir, garmin_source_dir, polar_source_dir):\n\n run(libai_source_dir, garmin_source_dir, polar_source_dir)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"xiaomi/libai_garmin_polar_preprocess/clean_libai_garmin_polar.py","file_name":"clean_libai_garmin_polar.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"553053773","text":"from __future__ import print_function\nimport boto3\nimport json\nfrom urllib2 import Request, urlopen, URLError, HTTPError\nimport logging\nfrom botocore.exceptions import ClientError\nimport os\nfrom base64 import b64decode\nimport chef\n\n# CHEF_URL, SLACK_HOOK,user and region should be set to some value\n# in get_pem we encrypt chef key.\n# Function requires IAM role with ec2 tag read permission and Chef user with org\n# admin permissions\n# Tested against Chef 12\n\nCHEF_URL=''\nHOOK\nuser = ''\ninstancename = ''\nregion = ''\n\n# KMS\ndef get_pem():\n try:\n with open('encrypted_pem.txt', 'r') as encrypted_pem:\n pem_file = encrypted_pem.read()\n\n kms = boto3.client('kms', region_name=region)\n return kms.decrypt(CiphertextBlob=b64decode(pem_file))['Plaintext']\n except (IOError, ClientError, KeyError) as err:\n LOGGER.error(err)\n return False\n\n# Find instance tag key 'Name' and return value form aws instance-id\ndef get_instance_tag(instancename):\n ec2 = boto3.resource('ec2')\n ec2instance = ec2.Instance(instancename)\n tags = ec2instance.tags\n\n for i in tags:\n if i['Key'] == 'Name':\n name = i['Value']\n return name\n\n# Chef\ndef lambda_handler(event, context):\n instanceState = event[\"detail\"][\"state\"]\n instanceId = event[\"detail\"][\"instance-id\"]\n get_pem()\n get_instance_tag(instanceId)\n with chef.ChefAPI(CHEF_URL, get_pem(), user):\n node = chef.Node(get_instance_tag(instanceId))\n node.delete()\n# SLACK\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n\n slack_message = {\n 'channel': \"devops\",\n 'userame': 'awsbot',\n 'mrkdwn': 'true',\n 'text': \"Instance *%s*\\nEntered *%s* state\\n Removed from Chef\" % (get_instance_tag(instanceId), instanceState)\n }\n hook = SLACK_HOOK\n req = Request(hook, json.dumps(slack_message))\n try:\n response = urlopen(req)\n response.read()\n logger.info(\"Message posted to %s\", slack_message['channel'])\n except HTTPError as e:\n logger.error(\"Request failed: %d %s\", e.code, e.reason)\n except URLError as e:\n logger.error(\"Server connection failed: %s\", e.reason)\n\n return 'Hello from Lambda'\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"318430271","text":"#Main page for Apul.py http://github.com/GrautDevelopes/Apul.py/\n#Very alpha. Expect bugs!\n#Only use redirectors that go to blobar and don't go to clickvalidator.net. Examples:\n#Usage `python Apul.py http://youtuber.com/ youtuber.com.log`\n#http://youtuber.com/\n#http://pete.com/\n#http://youtibe.com/\nimport urllib2\nimport base64\nimport sys\nimport re\nimport os\nimport time\nprint(\"[Apul] Starting...\")\nprint(\"[Apul] Checking \" + sys.argv[1] + \" ...\")\nprint(\"[Apul] Getting timezone...\")\nutcoffsetinmin = str(\n time.timezone / 60\n) # - 60) #remove \")#\" when US DST adds back an hour. #During DST this returns DST while the browser still wants to use Standard? #This is a new feature please report any issues with timezone identification!\nprint(\"[Apul] \" + utcoffsetinmin + \" is current timezone.\")\n### Config ######################\n#Feel free to change these if you know what you're doing.\n#utcoffsetinmin = 240 #Overides time detection if uncommented\n### Useragent ###################\n#ua = \"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\" #Chrome\nua = \"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; TNJB; rv:11.0) like Gecko\" #Internet Explorer\n#ua = \"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0\" #Edge\n#ua = \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; fi-fi) AppleWebKit/420+ (KHTML, like Gecko) Safari/419.3\" #Mac Safari\n#ua = \"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A5297c Safari/602.1\" #iPhone Safari\n#ua = \"Insert own useragent here\" #Custom\n#################################\nreq = urllib2.Request(sys.argv[1], headers={'User-Agent': ua})\nRedirectorResponse = urllib2.urlopen(req)\nRedirectorResponseHTML = RedirectorResponse.read()\nRedirectorResponse.close()\n\n\ndef clean_text(rgx, text):\n new_text = text\n new_text = re.sub(rgx, '', new_text)\n return new_text\n\n\ndef save():\n logstream = open(sys.argv[2], 'a+') #Was 'w'\n for item in Popups:\n logstream.write(\"%s\\n\" % item)\n logstream.close()\n lines = open(sys.argv[2], 'r').readlines()\n lines_set = set(lines)\n logstream.close()\n out = open(sys.argv[2], 'w')\n for line in lines_set:\n out.write(line)\n\n\ndef getnewblobarurl():\n req = urllib2.Request(sys.argv[1], headers={'User-Agent': ua})\n RedirectorResponse = urllib2.urlopen(req)\n RedirectorResponseHTML = RedirectorResponse.read()\n RedirectorResponse.close()\n trim0 = clean_text('.*var u = \\'', RedirectorResponseHTML)\n trim1 = clean_text('\\'\\+\\(\\(r.*', trim0)\n trim2 = clean_text('\\'\\+\\(\\(.*', trim1)\n Redirecter3url = trim2 + \"2.1.\" + base64ofdomain + \"&r=&z=\" + utcoffsetinmin\n #print(\"[Apul] Resolving \" + Redirecter3url + \" at \" + sys.argv[1] + \" ...\") #The blobar url, disabled because we don't clear our screen anymore\n return Redirecter3url\n\n\nif \"related content to what you are looking for\" in RedirectorResponseHTML:\n print(\"[Apul] Verifed \" + sys.argv[1] + \" !\")\n base64ofdomain = base64.urlsafe_b64encode(\n clean_text('/', clean_text('.*://', sys.argv[1])))\n Popups = []\n while True:\n req3 = urllib2.Request(getnewblobarurl(), headers={'User-Agent': ua})\n Redirector3Response = urllib2.urlopen(req3)\n PopUpHTML = Redirector3Response.read()\n PopUpURL = Redirector3Response.geturl()\n if 'ww90.' in PopUpURL:\n getnewblobarurl()\n num = re.search(\n r\"(((((\\(\\d{3})|(\\s\\d{3}))((\\)|-)|(\\s|\\) )|(\\)-)?))?)|(\\d{3}(-|\\s)))?\\d{3}(-|\\s)\\d{4}\",\n PopUpHTML\n ) #.group(0) #Much thanks to Eclipse. Created by Eclipse for Graut and the scambaiting community. https://0-eclipse-0.github.io/phone_regex.txt\n Redirector3Response.close()\n if num:\n outline = PopUpURL + \" | {}\".format(num.group(0))\n else:\n outline = PopUpURL\n Popups = list(set(Popups))\n Popups.sort()\n if outline not in Popups:\n print(outline)\n Popups.append(outline)\n save()\nelse:\n print(\"[Apul] The redirector \" + sys.argv[1] + \" does not use blobar.\")\n","sub_path":"Apul.py","file_name":"Apul.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"582172660","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\n\ndir_cifar10 = '/nfs/cold_project/hezihao/dataset/'\n\n# Data\nprint('==> Preparing data..')\n\n\ndef train_loader(batchsize):\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n trainset = torchvision.datasets.CIFAR10(root=dir_cifar10, train=True, download=True, transform=transform_train)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=batchsize, shuffle=True, num_workers=4)\n return trainloader\n\n\ndef test_loader(batchsize):\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n testset = torchvision.datasets.CIFAR10(root=dir_cifar10, train=False, download=True, transform=transform_test)\n testloader = torch.utils.data.DataLoader(testset, batch_size=batchsize, shuffle=False, num_workers=4)\n return testloader\n","sub_path":"cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"350606418","text":"from collections import defaultdict\nclass Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n longest_window = 0\n letter_counts = collections.defaultdict(lambda: 0)\n max_freq_char = 0\n left = 0\n for right in range(len(s)):\n letter_counts[s[right]] += 1\n max_freq_char = max(max_freq_char, letter_counts[s[right]])\n \n while right - left + 1 - max_freq_char > k:\n letter_counts[s[left]] -= 1 \n left += 1\n \n longest_window = max(longest_window, right - left + 1)\n \n return longest_window\n","sub_path":"string/longest-repeating-character-replacement.py","file_name":"longest-repeating-character-replacement.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"529472733","text":"import unittest\nimport os\nimport sys\nfrom decorator import logger\n\n\n@logger\ndef func(x, y):\n return x * y\n\n\ndef read_log(path):\n with open(path, \"r\") as file:\n return file.readlines()\n\n\nclass TestLogger(unittest.TestCase):\n def test_log(self):\n log_contains = False\n func(1, 2)\n log_list = read_log('/var/tmp/decorator.log')\n\n if repr(os.getcwd()) and repr(sys.argv[0]) in log_list[0]:\n log_contains = True\n\n self.assertEqual(True, log_contains)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"decorator_test.py","file_name":"decorator_test.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"75974808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 25 14:36:10 2019\n\n@author: mushtu\n\"\"\"\n##Problem 1\nx=23\nwhile x in range(23,50):\n print(x)\n x+=1\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n##Problem 2 \nx=23\nwhile x in range(23,50):\n if x%2==0:\n print(x, end=' ')\n x+=1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n##Problem 3\nx=1952\nwhile x<2020:\n x+=4\n print(x, end=' ')\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n#Problem 4\nx=10\nwhile x>=1:\n print(x, end=' ')\n x-=1\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n##Problem 5 \na = 0\nwhile a < 101:\n print('*', end=' ')\n a+= 1\nprint()\n\n\n\n\n\n\n\n\n\n\n\n##Problem 6\nl1=[1,2,3,4]\nl2=[-2,3,1,0]\nl3=[]\ni=0\nwhile iRat2[i]:\n days.append(i+1)\n i+=1\nprint(days)\n \n\n\n\n\n\n\n\n\n\n\n\n\n##Problem 9: Guessing game\nimport random\ntarget_num = random.randint(1, 10)\nguess_num=0\nwhile target_num != guess_num:\n guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))\nprint('Well guessed!')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#Problem 10\nitems = []\ni=100\nwhile i in range(100, 401):\n s = str(i)\n if (int(s[0])%2==0) and (int(s[1])%2==0) and (int(s[2])%2==0):\n items.append(s)\n i+=1\nprint( \",\".join(items))\n\n#The join() method takes all items in an iterable and joins them into one string.\n#A string must be specified as the separator.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n##class exercise\nnum=int(input(\"enter a number \"))\nfactors=[]\ni=1\nwhile i <=num+1:\n if num%i==0:\n factors.append(i)\n i+=1\nprint (factors)\n \n","sub_path":"CS1010Fall2019-master/Class Excercises/ClassExercise10.py","file_name":"ClassExercise10.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"510421965","text":"# coding=utf-8\r\nimport sqlite3\r\n\r\nclass DB:\r\n def __init__(self):\r\n a=1\r\n \r\n sqlitedb = 'my.db' \r\n \r\n @staticmethod\r\n def create_db():\r\n conn = sqlite3.connect(DB.sqlitedb)\r\n c = conn.cursor()\r\n c.execute('''CREATE TABLE IF NOT EXISTS post (title varchar, name varchar, text varchar)''')\r\n conn.commit()\r\n c.close()\r\n conn.close()\r\n return True\r\n \r\n @staticmethod\r\n def insert_db(title, name, text):\r\n conn = sqlite3.connect(DB.sqlitedb)\r\n rows = [(title, name, text)]\r\n conn.cursor().executemany(\"INSERT INTO post VALUES (?,?,?)\", rows)\r\n conn.commit()\r\n conn.close()\r\n return True\r\n \r\n @staticmethod\r\n def show_db():\r\n conn = sqlite3.connect(DB.sqlitedb)\r\n c = conn.cursor()\r\n c.execute('SELECT * FROM post')\r\n row = c.fetchone()\r\n res = ''\r\n while row is not None:\r\n a = \"title: \" + row[0] + \" | name: \" + row[1] + \" | text: \" + row[2] + \"
\"\r\n res += a\r\n row = c.fetchone()\r\n c.close()\r\n conn.close()\r\n return res\r\n \r\n @staticmethod\r\n def getpostbyname(name):\r\n conn = sqlite3.connect(DB.sqlitedb)\r\n c = conn.cursor()\r\n c.execute('SELECT * FROM post WHERE title = \"' + name + '\"')\r\n row = c.fetchone()\r\n c.close()\r\n conn.close()\r\n return row ","sub_path":"app/DB.py","file_name":"DB.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"113256029","text":"\"\"\"Find the mean of any list, nested or otherwise\nwithout using any iterative loops, the built-in sum,\ncount, or numpy.\n\"\"\"\n\ndef summation(alist) -> int:\n if type(alist) == int:\n return alist\n elif len(alist) == 0:\n return 0\n else:\n return summation(alist[0]) + summation(alist[1:])\n\ndef length(alist) -> int:\n if type(alist) == int:\n return 1\n elif len(alist) == 0:\n return 0\n else:\n return length(alist[0]) + length(alist[1:])\n\ndef mean(alist) -> int:\n return summation(alist) / length(alist)\n \ndef main():\n print(\"First testcase: [1 ,[2 ,3 ,[4]]] -->\", mean([1 ,[2 ,3 ,[4]]]))\n print(\"Second testcase: ([[[1]] ,[[2] ,[3] ,[4]]] -->\", mean([[[1]] ,[[2] ,[3] ,[4]]]))\n \nmain()","sub_path":"recMean.py","file_name":"recMean.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"251642966","text":"from src.enum.DatasetEnum import DatasetEnum\n\n\ndef get_domain_descriptor(dataset_type):\n if dataset_type == DatasetEnum.Robot:\n return RobotDomainDescriptor()\n elif dataset_type == DatasetEnum.Road:\n return RoadDomainDescriptor()\n elif dataset_type == DatasetEnum.Simulated:\n return SimulatedDomainDescriptor()\n else:\n raise ValueError(\"Unknown dataset\")\n\n\nclass RobotDomainDescriptor:\n def __init__(self):\n # domain is not grid-like\n self.grid_gap = None\n\n self.grid_domain = None\n\n self.domain_size = 145\n\n\nclass RoadDomainDescriptor:\n def __init__(self):\n\n self.grid_gap = 1.0\n\n # upper values are not included\n self.grid_domain = ((0.0, 50.0), (0.0, 100.0))\n\n self.domain_size = 50 * 100\n\n\nclass SimulatedDomainDescriptor:\n\n def __init__(self):\n\n self.grid_gap = 0.05\n\n # unused\n # number of samples in each dimension\n self.num_samples_grid = (50, 50)\n\n # upper values are not included\n self.grid_domain = ((-0.25, 2.25), (-0.25, 2.25))\n self.domain_size = 50 * 50\n","sub_path":"src/dataset_model/DomainDescriptorFactory.py","file_name":"DomainDescriptorFactory.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"335129803","text":"def get_answer(prompt):\n\twhile True: \n\t\t\"\"\"与下面的code相比,优点在于more concise,因为对于answer只进行了一次赋值\"\"\"\n\t\tanswer = input(prompt).strip().lower() #r如果只写到这里,就会进行无限循环,无论输入的是什么\n\t\t\"\"\"strip()是使得消除空格的影响,lower()是消除大写的影响\"\"\"\n\t\tif answer in ('yes', 'no'): #设定条件去break the loop\n\t\t\treturn answer #上述条件满足的时候,就打破了循环,输出这个值\n\n\ndef get_answer_oringinal(prompt):\n\tanswer = input(prompt)\n\twhile answer not in (\"yes\", \"no\"):\n\t\tanswer = input(prompt)\n\treturn answer\n\nprint(get_answer(\"yes or no? \"))","sub_path":"demo/lec6_yes_or_no.py","file_name":"lec6_yes_or_no.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"491297627","text":"import requests\nimport gallifrey\nimport config\nlogger = gallifrey.Logger(\n application_name='{}.{}'.format(config.APPLICATION_NAME, __name__),\n filename=config.LOG_FILE_NAME\n)\n\n# Access Token for Single User , does not use OAuth flow as we do not require user specific compression\nACCESS_TOKEN_OF_BITLY = '2e4b646a6261ef2302b441687d353bf454b76f89'\n\n# Bitly Url Compressor\ndef getTinyUrl(url):\n\n hitUrl = 'https://api-ssl.bitly.com/v3/shorten?access_token=' + ACCESS_TOKEN_OF_BITLY + '&longUrl=' + url + '&format=txt'\n logger.info(\"Getting Tiny URL\")\n response = requests.get(hitUrl)\n return response.text\n\n","sub_path":"rssfeed/Bitly.py","file_name":"Bitly.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"564142736","text":"\"\"\"\n Created on 2018-09-24 21:20:00\n @author: dhshuai@163.com\n @desc: 盘中实时定时任务\n\"\"\"\n\nfrom api_test.auto_task.cron_gw_task import *\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom django_apscheduler.jobstores import DjangoJobStore, register_events\n\nscheduler_realtime = BackgroundScheduler()\nscheduler_realtime.add_jobstore(DjangoJobStore(), \"default\")\n\n# A股----------------------------------------------------------------------\n\n# 盘中行情实时更新\nscheduler_realtime.add_job(update_today_realtime_cron, 'cron', minute='*/5', hour='9-14', day_of_week='0-4',\n id='update_today_realtime_cron', name='update_today_realtime_cron',replace_existing=True)\nscheduler_realtime.add_job(update_today_realtime_cron, 'cron', minute='2', hour='15',day_of_week='0-4',\n id='update_today_realtime_cron_once', name='update_today_realtime_cron_once',replace_existing=True)\n# 每日增量数据补齐\nscheduler_realtime.add_job(update_astock_add_each_day, 'cron', minute='30', hour='8',day_of_week='0-6',\n id='update_astock_add_each_day', name='update_astock_add_each_day',replace_existing=True)\n\n# 日内大盘温度\nscheduler_realtime.add_job(cron_astock_market_trend, 'cron', second='20', minute='*/10', hour='9-14',day_of_week='0-6',\n id='cron_astock_market_trend', name='cron_astock_market_trend', replace_existing=True) # 全市场温度\n# 日内板块温度\nscheduler_realtime.add_job(cron_astock_allsector_trend, 'cron', second='50', minute='0', hour='10',day_of_week='0-6',\n id='cron_astock_allsector_trend', name='cron_astock_allsector_trend', replace_existing=True) # 盘中实时板块评分和排序\n\n\n# 美股--------------------------------------------------------------------\n\n# 盘中行情实时更新\nscheduler_realtime.add_job(update_ustock_today_cron, 'cron', minute='*/5', hour='22-23', day_of_week='0-4',\n id='update_ustock_today_cron', name='update_ustock_today_cron', replace_existing=True) # 美股实时数据\nscheduler_realtime.add_job(update_ustock_today_cron, 'cron', minute='*/5', hour='0-5', day_of_week='1-5',\n id='update_ustock_today_cron_sub', name='update_ustock_today_cron_sub', replace_existing=True) # 美股实时数据\n# 每日增量数据补齐\nscheduler_realtime.add_job(update_ustock_add_each_day, 'cron', minute='10', hour='22', day_of_week='0-6',\n id='update_ustock_add_each_day', name='update_ustock_add_each_day', replace_existing=True)\n\n# 日内大盘温度\nscheduler_realtime.add_job(cron_ustock_market_trend, 'cron', second='50', minute='*/10', hour='16-23,0-5',day_of_week='0-6',\n id='cron_ustock_allmarket_today', name='cron_ustock_allmarket_today', replace_existing=True) # 全市场温度\n\nscheduler_realtime.add_job(cron_ustock_allsector_trend, 'cron', second='10', minute='*/5', hour='22-23,0-5',day_of_week='0-6',\n id='cron_ustock_allsector_today', name='cron_ustock_allsector_today', replace_existing=True) # 盘中实时板块评分和排序\n\n\nregister_events(scheduler_realtime)\nscheduler_realtime.start()\nprint(\"Scheduler started!\")","sub_path":"api_test/auto_task/start_realtime_data.py","file_name":"start_realtime_data.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"413802404","text":"import xlrd\nimport csv\nimport re\n\nnumOfRows = 10000\n\n\ndef read_Xlrd(numOfRows):\n\t#------------open table-----------\n\twith xlrd.open_workbook('0001.xlsx', on_demand = True) as workbook:#on_demand - for big table\n\t#-------------open sheet---------\n\t\tworksheet = workbook.sheet_by_index(0)\n\t#------------create CSC and header-----------\n\t\twriteCSV = create_csv(numOfRows)\n\t#----------------read first 1000---------\n\t\tfor i in range(numOfRows-10000,numOfRows):\n\t\t\tnameOfCompany = worksheet.cell(i,0).value\n\t\t\tcity = worksheet.cell(i,1).value\n\t\t\tadress = worksheet.cell(i,2).value\n\t\t\tphone = change_Phone(worksheet.cell(i,4).value)#chage phone before\n\t\t\temail = worksheet.cell(i,5).value\n\t\t\twebSite = changeWeb(worksheet.cell(i,7).value)#change web before\n\t\t\tcategory1 = worksheet.cell(i,8).value\n\t\t\tcategory2 = worksheet.cell(i,9).value\n\n\t\t\twrite_CSV(nameOfCompany,city,adress,phone,email,\\\n\t\t\twebSite,category1,category2,writeCSV)\n\t\n\t\t\n\t\n\t\ndef del_String_That_Removed():\n\tNone\n#------------create CSC and header-----------\ndef create_csv(numOfRows):\n\tcsvFile = open('first{}-{}.csv'.format(numOfRows-10000,numOfRows),'w')\n\tfieldnames = ['Название лида','Город','Адрес',\\\n\t'Рабочий телефон','Рабочий e-mail',\\\n\t'Корпоративный сайт','Комментарий']\n\twriteCSV = csv.DictWriter(csvFile, fieldnames=fieldnames)\n\twriteCSV.writeheader()\n\treturn writeCSV\n\ndef write_CSV(nameOfCompany,city,adress,phone,email,\\\n\t\t\twebSite,category1,category2, writeCSV):\n\twriteCSV.writerow({'Название лида':nameOfCompany,\\\n\t\t'Город':city,'Адрес':adress,'Рабочий телефон':phone\\\n\t\t,'Рабочий e-mail':email,'Корпоративный сайт':webSite\\\n\t\t,'Комментарий':(category1+'/'+category2)})\n\n#-------change webadress---\ndef changeWeb(web):\n\tx1 = 'http://www.'\n\tx2 = 'http://'\n\tx3 = 'www.'\n\tif x1 in web:\n\t\tweb = web[11:]\n\telif x2 in web:\n\t\tweb = web[7:]\n\telif x3 in web:\n\t\tweb = web[4:]\n\treturn web\n\n#-------change phone---\ndef change_Phone(phone):\n\tphone1 = ''\n\t#with8 = re.match(r'^8.+',phone)\n\tphone = re.sub(r'^8',r'7',phone)\n\t#if phone == with8.group(0):\n\t\t#phone = '7'+phone[1:]\n\tif not phone.startswith('7') and phone not in ['','0','-','.']:\n\t\tphone = '7' + phone\n\tfor i in phone:\n\t\tif i.isdigit():\n\t\t\tphone1 += i\n\treturn phone1\n\t\nfor i in range(20):\n\tread_Xlrd(numOfRows)\n\tnumOfRows += 10000\n","sub_path":"work/base/main_convert_base.py","file_name":"main_convert_base.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"283163999","text":"from data_pre import data_preprocessing\nfrom WAC_SATTR import WAC_SATTR\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import log\nimport torch.optim as optim\nimport time\nfrom torch.utils.data import DataLoader, TensorDataset\n\ntorch.manual_seed(1)\n\nprint(torch.cuda.is_available())\nprint(torch.__version__)\n\n\n'''\nload and prepare data\n'''\n(voc_ix, train_data,test_data, dev_data) = data_preprocessing()\nprint(\"finish preparing data\\n\")\n\n'''\nset parameters\n'''\n## set hyperparameters\nVOCAB_SIZE = len(voc_ix) + 1\nEMBEDDING_DIM = 100\nn_epoch = 20\nbatch_size = 500\neval_per = 20000/batch_size\nPATH = \"../model/wac_sattr.pt\"\n\n## define model\nmodel = WAC_SATTR(EMBEDDING_DIM, VOCAB_SIZE)\noptimizer = optim.Adagrad(model.parameters(), lr = 1e-2)\n\n\n## training\nlosses = []\naccs = []\ni = 0\nbest_dev_acc = 0\n\nmyloss = torch.nn.BCELoss(weight=None)\n#with torch.autograd.set_detect_anomaly(True):\nstart = time.time()\nfor epoch in range(n_epoch):\n print(\"epoch \" + str(epoch))\n\n #dataloaders\n # make sure to SHUFFLE your data\n train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)\n for X,y,lens in train_loader:\n\n if i % eval_per == 0:\n print(\"time: {}\".format(time.time() - start))\n acc = model.evaluate(dev_data.tensors)\n if acc > best_dev_acc:\n best_dev_acc = acc\n torch.save(model, PATH)\n print(\"accuracy on dev: \" + str(acc))\n accs.append(acc)\n\n # Step 3. Run our forward pass.\n prob = model.forward(X, lens)\n\n # Step 4. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n #loss_sent = - y*log(prob) - (1-y)*log(1-prob)\n loss = myloss(prob, y.unsqueeze(1).float())\n #loss += loss_sent\n\n #import pdb; pdb.set_trace()\n loss.backward()\n optimizer.step()\n model.zero_grad()\n i +=1\n\n losses.append(loss.item())\n runtime = time.time() - start\nprint(\"runtime: \" + str(runtime) + \"s\")\n\nmodel_best = torch.load(PATH)\nmodel_best.eval()\nacc_dev = model_best.evaluate(dev_data.tensors)\nprint(\"best model acc on dev: \" + str(acc_dev))\nacc_test = model_best.evaluate(test_data.tensors)\nprint(\"best model acc on test: \" + str(acc_test))\n","sub_path":"hw2/code/wac_sattr_eval.py","file_name":"wac_sattr_eval.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"192997947","text":"'''\nCreated on Feb 18, 2018\n\n@author: hello\n'''\nfrom datetime import datetime\nstart_time = datetime.now()\nimport numpy as np\nnp.random.seed(1999)\nimport pandas as pd\nimport re\n# import os\n# os.environ(\"OMP_NUM_THREADS\") = 4\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, Embedding, Dropout, Activation, GRU, \\\n CuDNNGRU, CuDNNLSTM, SpatialDropout1D, concatenate, BatchNormalization\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalAveragePooling1D\nfrom keras.models import Model\nfrom keras import initializers, regularizers, constraints, optimizers, layers\nfrom keras.optimizers import Adam\nfrom keras.callbacks import EarlyStopping\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import roc_auc_score\n\n\ndef clean_text(text):\n text = text.lower()\n text = re.sub(\"it's\", \"it is\", text)\n return text\n\n\nemb_size = 300\nmax_features = 20000\nmaxlen = 150\n\npath = \"../input/\"\ncomp = \"../output/\"\n# EMBEDDING_FILE = f'{path}glove6b/glove.6B.50d.txt'\nEMBEDDING_FILE = f'{path}glove6b/glove.6B.300d.txt'\n\ntrain = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\n\nprint(len(test[\"id\"].unique()))\n\ncols = [\"toxic\", \"severe_toxic\", \"obscene\",\n \"threat\", \"insult\", \"identity_hate\"]\n\nlist_sentences_train = train[\"comment_text\"].fillna(\"unknown\")\nlist_sentences_test = test[\"comment_text\"].fillna(\"unknown\")\n\nlist_sentences_train = list_sentences_train.apply(lambda x: clean_text(x))\n\nprint(list_sentences_train[2])\n\ntk = Tokenizer(num_words=max_features)\ntk.fit_on_texts((list(list_sentences_train)))\nlist_tokenized_train = tk.texts_to_sequences(list_sentences_train)\nlist_tokenized_test = tk.texts_to_sequences(list_sentences_test)\nX = pad_sequences(list_tokenized_train, maxlen=maxlen)\nX_test = pad_sequences(list_tokenized_test, maxlen=maxlen)\ny = train[cols].values\n\nX_tr, X_dev, y_tr, y_dev = train_test_split(X, y, train_size=0.90)\n\n# Read the glove word vectors (space delimited strings) into a dictionary\n# from word->vector.\n\n\ndef get_coefs(word, *arr): return word, np.asarray(arr, dtype='float32')\n\n\nembeddings_index = dict(get_coefs(*o.strip().split())\n for o in open(EMBEDDING_FILE, \"r\", encoding=\"utf-8\"))\n\nall_embs = np.stack(embeddings_index.values())\nemb_mean, emb_std = all_embs.mean(), all_embs.std()\n\nprint(emb_mean, emb_std)\n\nword_index = tk.word_index\nnb_words = min(max_features, len(word_index))\nembedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, emb_size))\nfor word, i in word_index.items():\n if i >= max_features:\n continue\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\nprint(\"embedding matrix size: \", embedding_matrix.shape)\n######################################################\n# RNN model\n\n# Set hyper parameters for the model.\nBATCH_SIZE = 32 # 32\nepochs = 3\n\n# Calculate learning rate decay.\n\n\ndef exp_decay(init, fin, steps):\n return (init / fin) ** (1 / (steps - 1)) - 1\n\n\nsteps = int(len(train[\"id\"]) / BATCH_SIZE) * epochs\nlr_init, lr_fin = 0.009, 0.0008 # 0.009, 0.0008\nlr_decay = exp_decay(lr_init, lr_fin, steps)\n\noptimizer = Adam(lr=lr_init, decay=lr_decay)\n\ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, emb_size, weights=[embedding_matrix])(inp)\n# x = Bidirectional(LSTM(64, return_sequences=True,\n# dropout=0.1, recurrent_dropout=0.1))(x)\nx = SpatialDropout1D(0.5)(x) # spatial drop-out regularize all 1d input.\nx = Bidirectional(GRU(128, return_sequences=True,\n dropout=0.2, recurrent_dropout=0.2))(x)\nx = SpatialDropout1D(0.5)(x)\n# x = Bidirectional(CuDNNGRU(64))(x)\nmax_pool = GlobalMaxPool1D()(x)\navg_pool = GlobalAveragePooling1D()(x)\n# conc = concatenate([x, max_pool, avg_pool])\n\nconc = concatenate([max_pool, avg_pool])\nx = Dropout(0.5)(conc)\noutput = Dense(6, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=output)\nmodel.compile(loss='binary_crossentropy',\n optimizer=optimizer,\n metrics=['accuracy'])\n\nmodel.fit(X_tr, y_tr,\n batch_size=BATCH_SIZE,\n epochs=epochs,\n validation_data=(X_dev, y_dev),\n callbacks=[EarlyStopping(patience=2, monitor='val_loss')],\n verbose=2)\n\n'''\nmodel.fit(X_tr, y_tr,\n batch_size=BATCH_SIZE ,\n epochs=1,\n validation_data=(X_dev, y_dev),\n callbacks=[EarlyStopping(patience=2, monitor='val_loss')])\n'''\nfilepath = f\"{comp}saved_RNN_model.h5\"\nmodel.save_weights(filepath=filepath, overwrite=True)\n\ny_dev_pred = model.predict(X_dev)\nprint(\"AUC on dev sets:\", roc_auc_score(y_dev, y_dev_pred))\ny_test = model.predict(X_test, batch_size=1024, verbose=1)\n\nsample_submission = pd.DataFrame()\nsample_submission[\"id\"] = test[\"id\"].astype(str)\n\nfor i, col in enumerate(cols):\n sample_submission[col] = y_test[:, i]\n\nend_time = datetime.now()\nprint(\" program-run ends: \", end_time - start_time)\nend_time = re.sub(\"[ :]+\", \"_\", str(end_time))\nend_time = re.sub(\"[.]*[0-9]*$\", \"\", str(end_time))\nsample_submission.to_csv(f'{comp}GRU_submission_{end_time}.csv', index=False)\n","sub_path":"RNN_model.py","file_name":"RNN_model.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"466531456","text":"\"\"\"\nThis page is in the table of contents.\nHome is a script to home the tool.\n\nThe home manual page is at:\nhttp://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Home\n\n==Operation==\nThe default 'Activate Home' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called.\n\n==Settings==\n===Name of Homing File===\nDefault is homing.gcode.\n\nAt the beginning of a each layer, home will add the commands of a gcode script with the name of the \"Name of Homing File\" setting, if one exists. Home does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names. Home looks for those files in the alterations folder in the .skeinforge folder in the home directory. If it doesn't find the file it then looks in the alterations folder in the skeinforge_tools folder. If it doesn't find anything there it looks in the craft_plugins folder.\n\n==Examples==\nThe following examples home the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and home.py.\n\n\n> python home.py\nThis brings up the home dialog.\n\n\n> python home.py Screw Holder Bottom.stl\nThe home tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe home tool has created the file:\n.. Screw Holder Bottom_home.gcode\n\n\n> python\nPython 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)\n[GCC 4.2.1 (SUSE Linux)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import home\n>>> home.main()\nThis brings up the home dialog.\n\n\n>>> home.writeOutput( 'Screw Holder Bottom.stl' )\nThe home tool is parsing the file:\nScrew Holder Bottom.stl\n..\nThe home tool has created the file:\n.. Screw Holder Bottom_home.gcode\n\n\"\"\"\n\nfrom __future__ import absolute_import\n#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.\nimport __init__\n\nfrom skeinforge_tools import profile\nfrom skeinforge_tools.meta_plugins import polyfile\nfrom skeinforge_tools.skeinforge_utilities import consecution\nfrom skeinforge_tools.skeinforge_utilities import euclidean\nfrom skeinforge_tools.skeinforge_utilities import gcodec\nfrom skeinforge_tools.skeinforge_utilities import interpret\nfrom skeinforge_tools.skeinforge_utilities import settings\nfrom skeinforge_tools.skeinforge_utilities.vector3 import Vector3\nimport math\nimport os\nimport sys\n\n\n__author__ = \"Enrique Perez (perez_enrique@yahoo.com)\"\n__date__ = \"$Date: 2008/21/04 $\"\n__license__ = \"GPL 3.0\"\n\n\ndef getCraftedText( fileName, text, homeRepository = None ):\n\t\"Home a gcode linear move file or text.\"\n\treturn getCraftedTextFromText( gcodec.getTextIfEmpty( fileName, text ), homeRepository )\n\ndef getCraftedTextFromText( gcodeText, homeRepository = None ):\n\t\"Home a gcode linear move text.\"\n\tif gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'home' ):\n\t\treturn gcodeText\n\tif homeRepository == None:\n\t\thomeRepository = settings.getReadRepository( HomeRepository() )\n\tif not homeRepository.activateHome.value:\n\t\treturn gcodeText\n\treturn HomeSkein().getCraftedGcode( gcodeText, homeRepository )\n\ndef getNewRepository():\n\t\"Get the repository constructor.\"\n\treturn HomeRepository()\n\ndef writeOutput( fileName = '' ):\n\t\"Home a gcode linear move file. Chain home the gcode if it is not already homed. If no fileName is specified, home the first unmodified gcode file in this folder.\"\n\tfileName = interpret.getFirstTranslatorFileNameUnmodified( fileName )\n\tif fileName != '':\n\t\tconsecution.writeChainTextWithNounMessage( fileName, 'home' )\n\n\nclass HomeRepository:\n\t\"A class to handle the home settings.\"\n\tdef __init__( self ):\n\t\t\"Set the default settings, execute title & settings fileName.\"\n\t\tsettings.addListsToRepository( 'skeinforge_tools.craft_plugins.home.html', '', self )\n\t\tself.fileNameInput = settings.FileNameInput().getFromFileName( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Home', self, '' )\n\t\tself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute( 'http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_home' )\n\t\tself.activateHome = settings.BooleanSetting().getFromValue( 'Activate Home', self, True )\n\t\tself.nameOfHomingFile = settings.StringSetting().getFromValue( 'Name of Homing File:', self, 'homing.gcode' )\n\t\tself.executeTitle = 'Home'\n\n\tdef execute( self ):\n\t\t\"Home button has been clicked.\"\n\t\tfileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled )\n\t\tfor fileName in fileNames:\n\t\t\twriteOutput( fileName )\n\n\nclass HomeSkein:\n\t\"A class to home a skein of extrusions.\"\n\tdef __init__( self ):\n\t\tself.distanceFeedRate = gcodec.DistanceFeedRate()\n\t\tself.extruderActive = False\n\t\tself.highestZ = None\n\t\tself.homingText = ''\n\t\tself.lineIndex = 0\n\t\tself.lines = None\n\t\tself.oldLocation = None\n\t\tself.shouldHome = False\n\t\tself.travelFeedRatePerMinute = 957.0\n\n\tdef addFloat( self, begin, end ):\n\t\t\"Add dive to the original height.\"\n\t\tbeginEndDistance = begin.distance( end )\n\t\talongWay = self.absolutePerimeterWidth / beginEndDistance\n\t\tcloseToEnd = euclidean.getIntermediateLocation( alongWay, end, begin )\n\t\tcloseToEnd.z = self.highestZ\n\t\tself.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRatePerMinute, closeToEnd.dropAxis( 2 ), closeToEnd.z ) )\n\n\tdef addHopUp( self, location ):\n\t\t\"Add hop to highest point.\"\n\t\tlocationUp = Vector3( location.x, location.y, self.highestZ )\n\t\tself.distanceFeedRate.addLine( self.distanceFeedRate.getLinearGcodeMovementWithFeedRate( self.travelFeedRatePerMinute, locationUp.dropAxis( 2 ), locationUp.z ) )\n\n\tdef addHomeTravel( self, splitLine ):\n\t\t\"Add the home travel gcode.\"\n\t\tlocation = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )\n\t\tself.highestZ = max( self.highestZ, location.z )\n\t\tif not self.shouldHome:\n\t\t\treturn\n\t\tself.shouldHome = False\n\t\tif self.oldLocation == None:\n\t\t\treturn\n\t\tif self.extruderActive:\n\t\t\tself.distanceFeedRate.addLine( 'M103' )\n\t\tself.addHopUp( self.oldLocation )\n\t\tself.distanceFeedRate.addLinesSetAbsoluteDistanceMode( self.homingLines )\n\t\tself.addHopUp( self.oldLocation )\n\t\tself.addFloat( self.oldLocation, location )\n\t\tif self.extruderActive:\n\t\t\tself.distanceFeedRate.addLine( 'M101' )\n\n\tdef getCraftedGcode( self, gcodeText, homeRepository ):\n\t\t\"Parse gcode text and store the home gcode.\"\n\t\tself.homingText = settings.getFileInAlterationsOrGivenDirectory( os.path.dirname( __file__ ), homeRepository.nameOfHomingFile.value )\n\t\tif len( self.homingText ) < 1:\n\t\t\treturn gcodeText\n\t\tself.lines = gcodec.getTextLines( gcodeText )\n\t\tself.homeRepository = homeRepository\n\t\tself.parseInitialization( homeRepository )\n\t\tself.homingLines = gcodec.getTextLines( self.homingText )\n\t\tfor self.lineIndex in xrange( self.lineIndex, len( self.lines ) ):\n\t\t\tline = self.lines[ self.lineIndex ]\n\t\t\tself.parseLine( line )\n\t\treturn self.distanceFeedRate.output.getvalue()\n\n\tdef parseInitialization( self, homeRepository ):\n\t\t\"Parse gcode initialization and store the parameters.\"\n\t\tfor self.lineIndex in xrange( len( self.lines ) ):\n\t\t\tline = self.lines[ self.lineIndex ]\n\t\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\t\tfirstWord = gcodec.getFirstWord( splitLine )\n\t\t\tself.distanceFeedRate.parseSplitLine( firstWord, splitLine )\n\t\t\tif firstWord == '()':\n\t\t\t\tself.distanceFeedRate.addLine( '( home )' )\n\t\t\t\treturn\n\t\t\telif firstWord == '(':\n\t\t\t\tself.absolutePerimeterWidth = abs( float( splitLine[ 1 ] ) )\n\t\t\telif firstWord == '(':\n\t\t\t\tself.travelFeedRatePerMinute = 60.0 * float( splitLine[ 1 ] )\n\t\t\tself.distanceFeedRate.addLine( line )\n\n\tdef parseLine( self, line ):\n\t\t\"Parse a gcode line and add it to the bevel gcode.\"\n\t\tsplitLine = gcodec.getSplitLineBeforeBracketSemicolon( line )\n\t\tif len( splitLine ) < 1:\n\t\t\treturn\n\t\tfirstWord = splitLine[ 0 ]\n\t\tif firstWord == 'G1':\n\t\t\tself.addHomeTravel( splitLine )\n\t\t\tself.oldLocation = gcodec.getLocationFromSplitLine( self.oldLocation, splitLine )\n\t\telif firstWord == '(':\n\t\t\tif self.homingText != '':\n\t\t\t\tself.shouldHome = True\n\t\telif firstWord == 'M101':\n\t\t\tself.extruderActive = True\n\t\telif firstWord == 'M103':\n\t\t\tself.extruderActive = False\n\t\tself.distanceFeedRate.addLine( line )\n\n\ndef main():\n\t\"Display the home dialog.\"\n\tif len( sys.argv ) > 1:\n\t\twriteOutput( ' '.join( sys.argv[ 1 : ] ) )\n\telse:\n\t\tsettings.startMainLoopFromConstructor( getNewRepository() )\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"skeinforge_tools/craft_plugins/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":8710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"164263079","text":"import numpy as np\nimport os\n\n\nclass LocalAlignment:\n def __init__(self, string1, string2, gap_penalty, matrix):\n \"\"\"\n :param string1: first string to be aligned, string\n :param string2: second string to be aligned, string\n :param gap_penalty: gap penalty, integer\n :param matrix: substitution matrix containing scores for amino acid\n matches and mismatches, dict\n\n Attention! string1 is used to index columns, string2 is used to index rows\n \"\"\"\n self.string1 = string1\n self.string2 = string2\n self.gap_penalty = gap_penalty\n self.substitution_matrix = matrix\n self.score_matrix = np.zeros((len(string2) + 1, len(string1) + 1), dtype=np.int)\n self.alignmentList = ()\n self.alignmentNbrsStr1 = []\n self.alignmentNbrsStr2 = []\n self.align()\n\n def align(self):\n \"\"\"\n Align given strings using the Smith-Waterman algorithm.\n NB: score matrix and the substitution matrix are different matrices!\n \"\"\"\n\n for row, residue2 in enumerate(self.string2):\n for col, residue1 in enumerate(self.string1):\n diagonal = self.score_matrix[row][col] + self.substitution_matrix[residue1][residue2]\n gapHorizontal = self.score_matrix[row+1][col] + self.gap_penalty\n gapVertical = self.score_matrix[row][col+1] + self.gap_penalty\n\n maxScore = max(diagonal, gapHorizontal, gapVertical, 0)\n self.score_matrix[row+1][col+1] = maxScore\n print(self.score_matrix)\n\n def has_alignment(self):\n \"\"\"\n :return: True if a local alignment has been found, False otherwise\n \"\"\"\n \"\"\"\n for row,_ in enumerate(self.string2):\n for col,_ in enumerate(self.string1):\n if self.score_matrix[row][col] > 0:\n print(\"True\")\n return True\n print(\"False\")\n return False\n \"\"\"\n if self.score_matrix.any() > 0:\n print(\"True\")\n return True\n print(\"False\")\n return False\n\n def get_alignment(self):\n \"\"\"\n :return: alignment represented as a tuple of aligned strings\n \"\"\"\n if not self.has_alignment():\n self.alignmentList = (\"\",\"\")\n print(self.alignmentList)\n return self.alignmentList\n else:\n maxIndex = np.where(self.score_matrix == np.amax(self.score_matrix))\n print(int (maxIndex[0]), int (maxIndex[1]))\n self.get_optimal_alignment(int (maxIndex[0]), int (maxIndex[1]), [\"\", \"\"])\n print(self.alignmentList)\n return self.alignmentList\n\n\n def get_optimal_alignment(self, row, col, result):\n print(\"______ROWCOL________\")\n print(row, col)\n\n if self.score_matrix[row][col] == 0:\n alig1 = result[0][::-1]\n alig2 = result[1][::-1]\n self.alignmentList = (alig1,alig2)\n print(\"appened\" , result)\n print(self.alignmentList)\n result[0] = result[0][:-1]\n result[1] = result[1][:-1]\n return\n else:\n #if self.score_matrix[row][col] != 0:\n print(self.score_matrix[row][col])\n print(self.score_matrix[row-1][col-1])\n\n print(self.string2)\n print(self.string1)\n\n print(self.string2[row-1])\n print(self.string1[col-1])\n\n print(self.score_matrix[row][col] - self.substitution_matrix[self.string1[col-1]][self.string2[row-1]])\n\n current = self.score_matrix[row][col]\n diagonal = self.score_matrix[row-1][col-1]\n vertical = self.score_matrix[row-1][col]\n horizontal = self.score_matrix[row][col-1]\n charString1 = self.string1[col-1]\n charString2 = self.string2[row-1]\n subst = self.substitution_matrix[charString1][charString2]\n #1. Fall diagonal: Wert muss kleiner der substitution matrix sein\n if diagonal == (current - subst):\n print(\"Fall 1\")\n result[0] += charString1\n result[1] += charString2\n print(result)\n self.alignmentNbrsStr1.append((charString1,col-1))\n self.alignmentNbrsStr2.append((charString2,row-1))\n self.get_optimal_alignment(row-1, col-1, result)\n\n #2. Fall links: Wert - gap_penalty --> vertical\n if vertical == (current - self.gap_penalty):\n print(\"Fall 2\")\n result[0] += (\"-\")\n result[1] += charString2\n self.alignmentNbrsStr1.append((\"-\",-1))\n self.alignmentNbrsStr2.append((charString2,row-1))\n print(result)\n self.get_optimal_alignment(row-1, col, result)\n\n #3. Fall oben: Wert - gap_penalty --> horizontal\n if horizontal == (current - self.gap_penalty):\n print(\"Fall 3\")\n result[0] += charString1\n result[1] += (\"-\")\n self.alignmentNbrsStr1.append((charString1, col-1))\n self.alignmentNbrsStr2.append((\"-\", -1))\n print(result)\n self.get_optimal_alignment(row, col-1, result)\n\n\n result[0] = result[0][:-1]\n result[1] = result[1][:-1]\n print(\"Fall 4\")\n print(row, col) \n return\n\n def is_residue_aligned(self, string_number, residue_index):\n \"\"\"\n :param string_number: number of the string (1 for string1, 2 for string2) to check\n :param residue_index: index of the residue to check\n :return: True if the residue with a given index in a given string has been alined\n False otherwise\n \"\"\"\n #string = \"string\" + str (string_number)\n #print(\"Test: \", string)\n\n print(self.alignmentNbrsStr1)\n print(self.alignmentNbrsStr2)\n\n \n if string_number == 1:\n for residue in self.alignmentNbrsStr1:\n print(self.string2[residue_index], residue[0], residue_index, residue[1])\n if self.string1[residue_index] == residue[0] and residue_index == residue[1]:\n print(\"True\")\n return True\n print(\"False\")\n return False\n elif string_number == 2: \n for residue in self.alignmentNbrsStr2:\n print(self.string2[residue_index], residue[0], residue_index, residue[1])\n if self.string2[residue_index] == residue[0] and residue_index == residue[1]:\n print(\"True\")\n return True\n print(\"False\")\n return False\n else:\n return\n\n \"\"\"\n if string_number == 1:\n print(self.alignmentList[0], self.string1[residue_index])\n if self.string1[residue_index] in self.alignmentList[0]:\n print(\"True\")\n return True\n else:\n print(\"False\")\n return False\n elif string_number == 2:\n print(self.alignmentList[1], self.string2[residue_index])\n if self.string2[residue_index] in self.alignmentList[1]:\n print(\"True\")\n return True\n else:\n print(\"False\")\n return False\n else:\n print(\"False\")\n return False\n \"\"\"\n\n","sub_path":"codechecker/repos/3/collected_files/local_alignment/ga54paz.py","file_name":"ga54paz.py","file_ext":"py","file_size_in_byte":7546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"525348363","text":"\"\"\"\nDescrição: Este programa recebe todas as ordens de atentimento de uma fila de uma única fez e depois as executa.\nAutor:Henrique Joner\nVersão:0.0.1\nData:07/01/2019\nComentário: Não consegui pensar em uma forma diferente de resolver o problema, ficou igual ao livro. :/\n\"\"\"\n\n\n#Inicialização de variáveis\n\nultimo = 0\n\nfila = 0\n\noperacao = 0\n\nx = 0\n\natendido = 0\n\nsair = 0\n\n\n\n#Entrada de dados\n\nultimo = 10\nfila = list(range(1,ultimo+1))\nwhile True:\n print(\"\\n Existem %d clientes na fila\" % len(fila))\n print(\"Fila atual:\", fila)\n print(\"Digite F para adicionar um cliente ao fim da fila, \")\n print(\"ou A para realizar o atendimento. S para sair.\")\n operacao = input(\"Operação(F, A ou S):\")\n\n#Processamento de dados\n\n x=0\n sair = False \n while x < len(operacao):\n if operacao[x] == \"A\":\n if(len(fila))>0:\n atendido = fila.pop(0)\n print(\"Cliente %d atendido\" % atendido)\n else:\n print(\"Fila vazia! Niguém para atender!\")\n \n elif operacao[x] == \"F\":\n ultimo += 1\n fila.append(ultimo)\n elif operacao[x] == \"S\":\n sair = True\n break\n else:\n print(\"Operação inválida! Digite apenas F, A ou S!\")\n x += 1 \n\n#Saída de dados\n if(sair):\n break\n","sub_path":"exercicio65.py","file_name":"exercicio65.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"316080995","text":"import pytest\nfrom pytest_regressions.data_regression import DataRegressionFixture\nfrom pytest_regressions.num_regression import NumericRegressionFixture\n\nfrom gdsfactory.component import Component\nfrom gdsfactory.components import factory\nfrom gdsfactory.difftest import difftest\n\nskip_test = {\n \"version_stamp\",\n \"extend_ports_list\",\n \"extend_port\",\n \"component_sequence\",\n \"mzi_arm\",\n}\n\ncomponents_to_test = set(factory.keys()) - skip_test\n\n\n@pytest.fixture(params=components_to_test, scope=\"function\")\ndef component(request) -> Component:\n return factory[request.param]()\n\n\ndef test_gds(component: Component) -> None:\n \"\"\"Avoid regressions in GDS geometry shapes and layers.\"\"\"\n difftest(component)\n\n\ndef test_settings(component: Component, data_regression: DataRegressionFixture) -> None:\n \"\"\"Avoid regressions when exporting settings.\"\"\"\n data_regression.check(component.get_settings())\n\n\ndef test_ports(component: Component, num_regression: NumericRegressionFixture) -> None:\n \"\"\"Avoid regressions in port names and locations.\"\"\"\n if component.ports:\n num_regression.check(component.get_ports_array())\n\n\ndef test_assert_ports_on_grid(component: Component):\n \"\"\"Ensure ports are on grid.\"\"\"\n component.assert_ports_on_grid()\n\n\nif __name__ == \"__main__\":\n import gdsfactory as gf\n\n c = gf.components.coupler(length=1.0 + 1e-4)\n # c = gf.components.coupler()\n # c.assert_ports_on_grid()\n print(c.ports)\n","sub_path":"gdsfactory/tests/test_components.py","file_name":"test_components.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"95358276","text":"import xml.etree.cElementTree as ET\nimport pprint\n\n# Counts number of first-level tags in file\ndef count_tags(filename):\n tag_dict = {}\n for event, elem in ET.iterparse(filename):\n if not elem.tag in tag_dict:\n tag_dict[elem.tag] = 1\n else:\n tag_dict[elem.tag] += 1\n print(tag_dict)\n return tag_dict\n\ncount_tags('map_slc')","sub_path":"mapparser.py","file_name":"mapparser.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"40710468","text":"from __future__ import division, print_function, absolute_import\n\n#from tmm.tmm_core import (coh_tmm, unpolarized_RT, ellips,\n# position_resolved, find_in_structure_with_inf)\nfrom wptherml.wptherml.datalib import datalib\nimport tmm.tmm_core as tmm\nfrom numpy import linspace, inf, pi, stack, array\nimport matplotlib.pyplot as plt\nimport matplotlib as mplib\nfrom scipy.interpolate import interp1d, InterpolatedUnivariateSpline\n\n\nmplib.rcParams['lines.linewidth'] = 4\nmplib.rcParams['lines.markersize'] = 4\nmplib.rcParams['axes.titlesize'] = 20\nmplib.rcParams['axes.labelsize'] =24\nmplib.rcParams['xtick.labelsize'] = 24\nmplib.rcParams['ytick.labelsize'] = 24\nmplib.rcParams['font.size'] = 24\n\n##############################################################################\n##############################################################################\n#%%\n\n\"\"\" \nDefine wavelength range of interest and layer thicknesses\n\"\"\"\n\nnm = 1e-9\nlda = linspace(250, 1999, 1000) # list of wavelengths in nm\n\n \n\n##############################################################################\n##############################################################################\n#%%\n\"\"\"\nRun the TMM code per wavelength for SiO2 NP on Si using IDEAL MATERIALS \n\"\"\"\n\n\"\"\"\nDefine materials of interest for layered film simulation\n\nNotes:\n 1) materials are described in SI units\n 2) materials are stored in datalib\n 3) materials are output as m = n+j*k\n 4) materials are iterpolated in datalib based on input lda values\n\"\"\"\n\n\nm = datalib.Material_RI(lda*nm, 'SiC') #convert lda to SI unit\nmsic_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nm = datalib.Material_RI(lda*nm, 'SiO2') #convert lda to SI unit\nmsio2_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nm = datalib.Material_RI(lda*nm, 'Ag') #convert lda to SI unit\nmag_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nm = datalib.alloy(lda*nm, 0.10, 'Air','RC0_1B_SiO2','Bruggeman') # 15% ff good\nmsio2np10_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nm = datalib.alloy(lda*nm, 0.30, 'Air','RC0_1B_SiO2','Bruggeman')\nmsio2np_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nm = datalib.alloy(lda*nm, 0.30, 'Air','SiC','Bruggeman')\nmsicnp_fn = interp1d(lda, m, kind='linear') # make mat data a FUNCTION of lda, in nm\n\nd_list = [inf, 900, 1200, 100, 1000, 200, inf] # list of layer thicknesses in nm # 500nm Al2O3 good\nd_list = [inf, 1500, 0, 0, 0, 200, inf] # list of layer thicknesses in nm # 500nm Al2O3 good\nc_list = ['i', 'i', 'c','c','c','c','i']\ntheta = 0\nT_list = [];\nR_list = [];\nA_list = [];\nfor lda0 in lda:\n\n n_list = [1, msicnp_fn(lda0), msio2np_fn(lda0),msic_fn(lda0), msio2_fn(lda0), mag_fn(lda0), 1]\n inc_tmm_data = tmm.inc_tmm('s',n_list,d_list,c_list,theta,lda0)\n A_list.append(tmm.inc_absorp_in_each_layer(inc_tmm_data)) #stores as list of np.arrays\n T_list.append(inc_tmm_data['T'])\n R_list.append(inc_tmm_data['R']) \n \nA = stack(A_list, axis = 0) # convert list of np.arrays to single np.array\nT = array(T_list, dtype = complex) # Convert list to array for math operations\nR = array(R_list, dtype = complex) # Convert list to array for math operations\n\n##############################################################################\n##############################################################################\n#%%\n\n\n\n\n\"\"\"\nPlot TMM and measured absorption\n\"\"\" \n\n\n#if (min(lda) > 2000):\n\n\nmask = (lda > 2000) & (lda <= max(lda))\nt_atmosphere = datalib.ATData(lda*1e-9)\nfig1 = plt.figure()\nplt.plot(lda[mask]*1e-3, t_atmosphere[mask]*100,'k', alpha = 0.1, label='Atmospheric \\n transmittance')\nplt.plot(lda[mask]*1e-3, (1-T[mask]-R[mask])*100,'r', label = 'Device absorption \\n (Coherent)')\nplt.plot(lda[mask]*1e-3, A[mask,1]*100,':', label = 'Abs. $TiO_{2}$ NP \\n (10%, Brugg.)') \nplt.plot(lda[mask]*1e-3, A[mask,2]*100,':', label = 'Abs. $SiO_{2}$ NP \\n (30%, Brugg.)')\nplt.plot(lda[mask]*1e-3, A[mask,3]*100,':', label = 'Abs. $SiO_{2}$')\nplt.plot(lda[mask]*1e-3, A[mask,4]*100,':', label = 'Abs. $Ag$')\nplt.xlabel('Wavelength (nm)')\nplt.ylabel('%')\n#plt.legend()\nplt.tight_layout(rect=[-0.10,0,0.75,1])\nplt.legend(bbox_to_anchor=(1.04, 1))\nfig1.show()\n \nmask = (lda >= min(lda)) & (lda <= 2000)\nAM1p5 = datalib.AM(lda*1e-9) \nfig2 = plt.figure()\nplt.plot(lda[mask], (AM1p5[mask]/(1.4*1e9))*100,'k', alpha = 0.1, label='AM1.5')\nplt.plot(lda[mask], (1-T[mask]-R[mask])*100,'r', label = 'Device absorption \\n (Coherent)')\nplt.plot(lda[mask], A[mask,1]*100,':', label = 'Abs. $TiO_{2}$ NP \\n (10%, Brugg.)') \nplt.plot(lda[mask], A[mask,2]*100,':', label = 'Abs. $SiO_{2}$ NP \\n (30%, Brugg.)')\nplt.plot(lda[mask], A[mask,3]*100,':', label = 'Abs. $SiO_{2}$')\nplt.plot(lda[mask], A[mask,4]*100,':', label = 'Abs. $Ag$')\nplt.xlabel('Wavelength (nm)')\nplt.ylabel('%')\n#plt.legend()\nplt.tight_layout(rect=[-0.10,0,0.75,1])\nplt.legend(bbox_to_anchor=(1.04, 1))\nfig2.show()\n\n\n\n\n#print(\"Radiative Power (cooling) is \",np_slab.radiative_power_val, \"W/m^2\")\n#print(\"Absorbed Solar Power (warming) is \",np_slab.solar_power_val, \"W/m^2\")\n#print(\"Absorbed Atmospheric Radiation (warming) is \",np_slab.atmospheric_power_val, \"W/m^2\")\n#print(\"Net Power flux out of the structure is \",np_slab.cooling_power_val, \"W/m^2\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"179189888","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.db.models import Count, Q\nfrom django.template.loader import render_to_string\nfrom django.conf import settings\nfrom web.models import SSLCert, VHost, LetsEncrypt\nfrom subprocess import call\nfrom free_tls_certificates import client\nfrom django.utils import timezone\nfrom cProfile import Profile\nimport requests.exceptions\nimport acme.messages\nimport uuid\nimport os\nimport io\nimport pstats\nimport re\nif settings.KUMQUAT_USE_0RPC:\n\timport zerorpc\n\ndef issue_cert():\n\tletsencrypt_issued = False\n\tfor vhost in VHost.objects.filter(use_letsencrypt=True):\n\t\tif vhost.letsencrypt_state() not in ['REQUEST', 'RENEW']:\n\t\t\tcontinue\n\t\ttry:\n\t\t\tdata = client.issue_certificate(\n\t\t\t\t[str(vhost),] + list(vhost.vhostalias_set.values_list('alias', flat=True)),\n\t\t\t\tsettings.LETSENCRYPT_STATE_FOLDER,\n\t\t\t\tagree_to_tos_url = settings.LETSENCRYPT_TOS,\n\t\t\t\tacme_server = settings.LETSENCRYPT_ACME_SERVER)\n\n\t\t\tchain = b\"\\n\".join(data['chain'])\n\t\t\tcert = SSLCert()\n\t\t\tcert.set_cert(cert=data['cert'].decode(), key=data['private_key'].decode(), ca=chain.decode())\n\t\t\tcert.save()\n\n\t\t\tvhost.cert = cert\n\t\t\tvhost.save()\n\n\t\t\tvhost.letsencrypt.last_message = ''\n\t\t\tvhost.letsencrypt.save()\n\n\t\t\tletsencrypt_issued = True\n\n\t\texcept client.NeedToTakeAction as e:\n\t\t\tvhost.letsencrypt.last_message = str(e)\n\t\t\tfor action in e.actions:\n\t\t\t\tif isinstance(action, client.NeedToInstallFile):\n\t\t\t\t\tfile_name = re.sub(r'[^\\w-]', '', action.file_name)\n\t\t\t\t\twith open(settings.LETSENCRYPT_ACME_FOLDER + '/' + file_name, 'w') as f:\n\t\t\t\t\t\tf.write(action.contents)\n\t\t\t\t\tvhost.letsencrypt.last_message = ''\n\t\t\tvhost.letsencrypt.save()\n\t\texcept Exception as e:\n\t\t\tvhost.letsencrypt.last_message = str(e)\n\t\t\tvhost.letsencrypt.save()\n\n\tif letsencrypt_issued and settings.KUMQUAT_USE_0RPC:\n\t\tzerorpc.Client(connect_to=settings.KUMQUAT_BACKEND_SOCKET).update_vhosts()\n\nclass Command(BaseCommand):\n\targs = ''\n\thelp = 'issue lets encrypt ssl certificates'\n\n\tdef add_arguments(self, parser):\n\t\tparser.add_argument('--profile', dest='profile', default=False, action='store_true')\n\n\tdef handle(self, *args, **options):\n\t\tif options['profile']:\n\t\t\tprofiler = Profile()\n\t\t\tprofiler.runcall(issue_cert)\n\t\t\tpstats.Stats(profiler).sort_stats('cumulative').print_stats(25)\n\t\t\treturn\n\t\tissue_cert()\n","sub_path":"kumquat/management/commands/letsencrypt.py","file_name":"letsencrypt.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"59883124","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom time import perf_counter\nfrom tqdm import tqdm\n\n\ndef time_matrix_mult(A, B, n):\n \"\"\"\n A : n by n constant matrix\n B : n by n constant matrix\n Return time taken to multiply n by n matrices A and B.\n \"\"\"\n C = np.zeros([n, n], float)\n \n s1 = perf_counter()\n for i in range(n):\n for j in range(n):\n for k in range(n):\n C[i, j] += A[i,k] * B[k,j]\n \n t1 = perf_counter() - s1\n \n return t1\n \n\ndef experiment():\n \"\"\"\n Plot time taken to multiply n by n constant matrices using time_matrix_mult\n and np.dot.\n \"\"\"\n n_start = 2\n n_end = 250\n time_loop = []\n time_numpy = []\n \n for n in tqdm(range(n_start, n_end)):\n A = np.ones([n,n], float) * 3\n B = np.ones([n,n], float) * 3\n time_loop.append(time_matrix_mult(A, B, n) * 1000)\n \n # time matrix multiplication using np.dot\n s = perf_counter()\n C_matrix = np.dot(A, B)\n t_np = (s - perf_counter()) * 1000\n time_numpy.append(t_np)\n \n plt.figure()\n plt.plot(np.arange(n_start, n_end), time_loop, label=\"loop implementation\")\n plt.plot(np.arange(n_start, n_end), time_numpy, label=\"numpy.dot\")\n plt.grid()\n plt.xlabel(\"N\")\n plt.ylabel(\"Time (ms)\")\n plt.title(\"Time taken for NxN matrix multiplication\")\n plt.legend()\n plt.savefig(\"q3a.pdf\")\n \n \n plt.figure()\n plt.plot(np.arange(n_start, n_end)**3, time_loop, label=\"loop implementation\")\n plt.plot(np.arange(n_start, n_end)**3, time_numpy, label=\"numpy.dot\")\n plt.grid()\n plt.xlabel(\"N^3\")\n plt.ylabel(\"Time (ms)\")\n plt.title(\"Time taken for NxN matrix multiplication\")\n plt.legend()\n plt.savefig(\"q3b.pdf\")\n\n\nif __name__ == \"__main__\":\n experiment()\n","sub_path":"Planetary Orbits and Bifurcations (Lab1)/Submission Package/lab01_Q3.py","file_name":"lab01_Q3.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"471678008","text":"import json\r\nfrom itertools import combinations\r\nimport nltk\r\nfrom nltk.tokenize import sent_tokenize, RegexpTokenizer\r\nfrom nltk.stem.snowball import RussianStemmer\r\nimport networkx as nx\r\nimport sys\r\n\r\ndef similarity(s1, s2):\r\n if not len(s1) or not len(s2):\r\n return 0.0\r\n return len(s1.intersection(s2))/(1.0 * (len(s1) + len(s2)))\r\n\r\ndef textrank(text):\r\n sentences = sent_tokenize(text)\r\n tokenizer = RegexpTokenizer(r'\\w+')\r\n lmtzr = RussianStemmer()\r\n words = [set(lmtzr.stem(word) for word in tokenizer.tokenize(sentence.lower()))\r\n for sentence in sentences] \t \r\n pairs = combinations(range(len(sentences)), 2)\r\n scores = [(i, j, similarity(words[i], words[j])) for i, j in pairs]\r\n scores = filter(lambda x: x[2], scores)\r\n g = nx.Graph()\r\n g.add_weighted_edges_from(scores)\r\n pr = nx.pagerank(g)\r\n return sorted(((i, pr[i], s) for i, s in enumerate(sentences) if i in pr), key=lambda x: pr[x[0]], reverse=True)\r\n\r\ndef sumextract(text, n=5):\r\n tr = textrank(text)\r\n top_n = sorted(tr[:n])\r\n return ' '.join(x[2] for x in top_n)\r\n\r\ndef load_json(json_path):\r\n return json.load(open(json_path))\r\n\r\ndef analysis_news(news_one):\r\n if news_one['headline'] is not None:\r\n news = news_one['headline']\r\n else:\r\n news = news_one['body']\r\n news_one = news.replace('/', '')\r\n news_one = news_one.replace('\\\\', '')\r\n news_one = news_one.replace('ар+2', '')\r\n news_one = news_one.replace('2ар+1', '')\r\n news_one = news_one.replace('ар++', '')\r\n news_one = news_one.replace('мк+1', '')\r\n news_one = news_one.replace('ak+3', '')\r\n news_one = news_one.replace('of+3', '')\r\n news_one = news_one.lower()\r\n return news_one\r\n\r\n\r\ndef sorted_all_dict(my_d):\r\n return sorted(my_d.items(), key=lambda x: x[1], reverse=True)\r\n\r\n\r\nsend_data = []\r\nfor stack_news in load_json(sys.argv[1]):\r\n word_one = []\r\n for one_news in stack_news['news']:\r\n word_not_one = analysis_news(one_news)\r\n if word_not_one in word_one:\r\n #nothing\r\n pass\r\n else:\r\n word_one.append(word_not_one)\r\n send_data.append('. '.join(word_one))\r\n\r\n\r\ndd = load_json(sys.argv[1])\r\nfor i, text in enumerate(send_data):\r\n target = sumextract(text, 1)\r\n\r\n # final_target = target.split(',')[0]\r\n\r\n print(f\"Old: {dd[i].get('title')}\")\r\n print(f'New: {target.capitalize()}\\n')\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"158745169","text":"import sys\r\nimport argparse\r\nfrom plasTeX.TeX import TeX\r\nfrom xml.dom.minidom import parseString\r\n\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"infile\", help=\"the file to read from\",\r\n type=str, nargs=\"?\")\r\nparser.add_argument(\"outfile\", help=\"the file to write to\",\r\n type=str, nargs=\"?\")\r\nargs = parser.parse_args()\r\n\r\nif args.infile:\r\n with open(args.infile, 'r', encoding='utf8') as infile:\r\n source = infile.read()\r\n doc = TeX().input(source).parse()\r\n doc.normalizeDocument()\r\n xml = doc.toXML()\r\n\r\n if args.outfile:\r\n with open(args.outfile, 'w', encoding='utf8') as outfile:\r\n outfile.write(xml)\r\n else:\r\n sys.stdout.write(parseString(xml).toprettyxml())\r\nelse:\r\n while True:\r\n source=input(\"> \")\r\n print(source)\r\n if source:\r\n doc=TeX().input(source).parse()\r\n doc.normalizeDocument()\r\n xml=doc.toXML()\r\n print(parseString(xml).toprettyxml(indent=\" \"))\r\n else:\r\n break\r\n","sub_path":"textoxml.py","file_name":"textoxml.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"271169940","text":"# LINEAR SEARCH\n\n# This algorithm checks whether the given element is present in the array or not.\n# If the element is found in the array it returns the index of that element else \n# it returns -1 if the element is not found in the array.\n\ndef LinearSearch(arr,key):\n # we use a for loop to iterate through the array. \n for i in range(len(arr)):\n if arr[i]==key:\n return i # this returns the index if the key is found\n \n return -1 # this value is returned if the key is not found in the array\n\n\n\n# Starting with the main code\n# Creating array of the size n\n# Size would be taken into the variable n from user\ndef main():\n print(\"please enter the size of the array :\")\n n=int(input()) # takes size as input\n array=[]\n print(\"please enter the elements of the array :\")\n for j in range(n): # for loop for taking the elements as input\n array.append(int(input()))\n print(\"please enter the key element :\") \n x=int(input()) # the key is taken as input\n print()\n ans=LinearSearch(array,x) # linear search is called and the result is stored\n if ans==-1:\n print(\"element is not found\")\n else:\n print(f'the element is found at index {ans}') \n\n\nmain()\n\n\n\"\"\"\"\nExample Test Cases:\n1)\n\nplease enter the size of the array :\n5\nplease enter the elements of the array :\n1\n2\n3\n4\n5\nplease enter the key element :\n4\n\nthe element is found at index 3\n\n2)\n\nplease enter the size of the array :\n5\nplease enter the elements of the array :\n1\n2\n3\n4\n5\nplease enter the key element :\n7\n\nelement is not found\n\nTime Complexity : O(n)\nSpace Complexity : O(1)\n\"\"\" ","sub_path":"python/search/LinearSearch.py","file_name":"LinearSearch.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"598372046","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport rospy\nfrom geometry_msgs.msg import Twist\nfrom sensor_msgs.msg import LaserScan\n\nRATE = 5\nLIN_VEL = 0.2\nSAFETY_THRESHOLD = 1.5\n\n\nclass RobotState:\n def __init__(self):\n self.cmd_pub = rospy.Publisher(\"cmd_vel\", Twist, queue_size=0)\n self.scan_sub = rospy.Subscriber(\"scan\", LaserScan, self.scan_callback, queue_size=1)\n self.rate = rospy.Rate(RATE)\n self.state = 0 # 0: stopped, 1: move forward\n\n def scan_callback(self, msg):\n index = 0\n measurement = msg.ranges[index]\n if measurement 0:\n exit(2)\n except IOError:\n print(\"Could not open file '{}'.\".format(args.groovyFile))\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"groovystylechecker/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"559994445","text":"# !/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport os\nos.environ['KERAS_BACKEND'] = 'theano'\nimport numpy as np\nimport random\nimport h5py\n# import cv2\n\nclass ntu_rgbd(object):\n def __init__(self, data_path):\n self._data_path = data_path\n\n def skeleton_miss_list(self):\n lines = open('data/samples_with_missing_skeletons.txt', encoding='utf-8', mode = 'r').readlines()\n return [line.strip()+'.skeleton' for line in lines]\n\n # def get_multi_subject_list(self):\n # lines = open('data/samples_with_multi_subjects.txt', 'r').readlines()\n # return [line.strip() for line in lines]\n\n def filter_list(self, file_list):\n miss_list = self.skeleton_miss_list()\n return list(set(file_list)-set(miss_list))\n\n def check_list_by_frame_num(self):\n all_list = os.listdir(self._data_path)\n all_list = self.filter_list(all_list)\n for filename in all_list:\n lines = open(os.path.join(self._data_path, filename), 'r').readlines()\n step1 = int(lines[0].strip())\n step2 = lines.count('25\\r\\n')\n if step2 != step1 and step2 != 2*step1 and step2 != 3*step1:\n print(filename, step1, step2)\n\n def cross_subject_split(self):\n print ('cross subject evaluation ...')\n #ID of training subjects P 1-40 /20 for train, 20 for test\n trn_sub = [1, 2, 4, 5, 8, 9, 13, 14, 15, 16, 17, 18, 19, 25, 27, 28, 31, 34, 35, 38]\n all_list = os.listdir(self._data_path)\n trn_list = [file for file in all_list if int(file[9:12]) in trn_sub]\n tst_list = list(set(all_list) - set(trn_list))\n # filter file list with missing skeleton\n trn_list = self.filter_list(trn_list)\n tst_list = self.filter_list(tst_list)\n return trn_list, tst_list\n \n def get_all_name(self):\n all_list = os.listdir(self._data_path)\n all_list = self.filter_list(all_list)\n return all_list\n \n def get_test_name(self):\n self._data_path = 'test/AllSkeletonFiles_remove_nan_nolabel/'\n all_list = os.listdir(self._data_path)\n return all_list\n \n def cross_view_split(self):\n print('cross view evaluation ...')\n # Cxxx\n trn_view = [2, 3]\n all_list = os.listdir(self._data_path)\n trn_list = [file for file in all_list if int(file[5:8]) in trn_view]\n tst_list = list(set(all_list) - set(trn_list))\n # filter file list with missing skeleton\n trn_list = self.filter_list(trn_list)\n tst_list = self.filter_list(tst_list)\n return trn_list, tst_list\n \n def save_h5_file_skeleton_list(self, save_home, trn_list, split='train', angle=False):\n # save file list to txt\n save_name = os.path.join(save_home, 'new_file_list_' + split + '.txt')\n with open(save_name, 'w') as fid_txt: # fid.write(file+'\\n')\n # save array list to hdf5\n save_name = os.path.join(save_home, 'new_array_list_' + split + '.h5')\n with h5py.File(save_name, 'w') as fid_h5:\n number=0\n fall_number=0\n total=0\n for fn in trn_list:\n skeleton_set, pid_set, std_set = self.person_position_std(fn)\n # filter skeleton by standard value\n count = 0\n number=number+1\n #if 'A043' in fn or number%30==0:\n print('pid_set',pid_set)\n print('std_set',std_set)\n for idx2 in range(len(pid_set)):\n if (std_set[idx2][0] > 0.002 or std_set[idx2][1] > 0.002) and (std_set[idx2][0]!=0 and std_set[idx2][1]!=0):\n count = count + 1\n name=fn+pid_set[idx2]\n if angle:\n fid_h5[name] = skeleton_set[idx2][:,:, 3:]\n else:\n fid_h5[name] = skeleton_set[idx2][:,:, 0:3]\n print('original shape',len(skeleton_set),len(skeleton_set[0]),len(skeleton_set[0][0]),len(skeleton_set[0][0][0]))\n print('skeleton shape',(skeleton_set[idx2][:,:, 0:3]).shape)\n print('save per skeleton',skeleton_set[idx2][:,:, 0:3])\n # total=total+1\n fid_txt.write(name + '\\n')\n if 'A043' in name:\n fall_number=fall_number+1\n total=total+1\n if count == 0:\n std_sum = [np.sum(it) for it in std_set]\n idx2 = np.argmax(std_sum)\n name=fn+pid_set[idx2]\n if angle:\n fid_h5[name] = skeleton_set[idx2][:,:, 3:]\n else:\n fid_h5[name] = skeleton_set[idx2][:,:, 0:3]\n fid_txt.write(name + '\\n')\n if 'A043' in name:\n fall_number=fall_number+1\n total=total+1\n\n print(split+\" fall:\",fall_number)\n print(split+\" total:\",total)\n print(\"total file number\",number)\n\n def person_position_std(self, filename, num_joints=25):\n lines = open(os.path.join(self._data_path, filename), 'r').readlines()\n step = int(lines[0].strip())\n pid_set = [] #72057594037931368 文件里面的这串数字,不知道什么作用\n # idx_set length of sequence\n idx_set = []\n skeleton_set = []\n start = 1\n sidx = [0,1,2,7,8,9,10]\n while start < len(lines): # and idx < step\n if lines[start].strip()=='25':\n pid = lines[start-1].split()[0]\n # print('pid: '+str(pid))\n # for x in lines[start+1:start+26]:\n # print(np.asarray(list(map(float,np.array(x.strip().split())[sidx]))).shape)\n\n if pid not in pid_set:\n idx_set.append(0)\n pid_set.append(pid)\n skeleton_set.append(np.zeros((step, num_joints, 7)))\n # print(np.zeros((step, num_joints, 7)).shape)\n idx2 = pid_set.index(pid)\n # print(idx2,idx_set[idx2])\n# print(skeleton_set[idx2][idx_set[idx2]].shape) (25,7)\n\n skeleton_set[idx2][idx_set[idx2]] =np.asarray([list(map(float, np.array(line_per.strip().split())[sidx]))\n for line_per in lines[start+1:start+26]])\n idx_set[idx2] = idx_set[idx2] + 1\n start = start + 26\n else:\n start = start + 1\n std_set=[] #-0.06616542 0.07068557 这串数字也不知道是什么,好像是每个文件的平均值?\n for idx2 in range(len(idx_set)):\n skeleton_set[idx2] = skeleton_set[idx2][0:idx_set[idx2]]\n if 1:\n sx = np.average(np.std(skeleton_set[idx2][:,:,0], axis=0))\n sy = np.average(np.std(skeleton_set[idx2][:,:,1], axis=0))\n else:\n xm = np.abs(skeleton_set[idx2][1:idx_set[idx2],:,0] - skeleton[0:idx_set[idx2]-1,:,0])\n sx = np.average(np.std(xm, axis=0))\n ym = np.abs(skeleton[1:idx_set[idx2],:,1] - skeleton[0:idx_set[idx2]-1,:,1])\n sy = np.average(np.std(ym, axis=0))\n std_set.append((sx, sy))\n\n return skeleton_set, pid_set, std_set\n\n def save_h5_file_seq(self, save_home, trn_list, trn_label, split='train', num_sample_save = 10000, num_seq=100):\n skeleton_list = []\n label_list = []\n seq_len_list = []\n iter_idx = 0\n save_idx = 0\n for idx, name in enumerate(trn_list):\n # load and sample skeleton\n skeleton = self.load_skeleton_file(name)\n # only use postion or angele\n skeleton = skeleton[:,:, 0:3]\n # skeleton = skeleton[:,:, 3:7]\n if skeleton.shape[0] < num_seq:\n # pad zeros in front of skeleton data\n sample = np.concatenate((np.zeros((num_seq-skeleton.shape[0], skeleton.shape[1], skeleton.shape[2])),\n skeleton), axis=0)\n else:\n sidx = np.arange(num_seq)\n sample = skeleton[sidx]\n\n seq_len_list.append(skeleton.shape[0])\n skeleton_list.append(sample)\n label_list.append(trn_label[idx])\n\n iter_idx = iter_idx + 1\n if iter_idx== num_sample_save:\n # save skeleton\n skeleton_list = np.asarray(skeleton_list, dtype='float32')\n label_list = np.asarray(label_list, dtype='float32')\n seq_len_list = np.asarray(seq_len_list)\n save_name = os.path.join(save_home, 'seq' + str(num_seq) + '_' + split + str(save_idx) + '.h5')\n with h5py.File(save_name, 'w') as f:\n f['data'] = skeleton_list\n f['label'] = label_list\n f['seq_len_list'] = seq_len_list\n save_idx = save_idx + 1\n iter_idx = 0\n skeleton_list = []\n label_list = []\n seq_len_list = []\n if iter_idx > 0:\n skeleton_list = np.asarray(skeleton_list, dtype='float32')\n label_list = np.asarray(label_list, dtype='float32')\n seq_len_list = np.asarray(seq_len_list)\n save_name = os.path.join(save_home, 'seq' + str(num_seq) + '_' + split + str(save_idx) + '.h5')\n with h5py.File(save_name, 'w') as f:\n f['data'] = skeleton_list\n f['label'] = label_list\n f['seq_len_list'] = seq_len_list\n \n def calculate_height(self, skeleton):\n center1 = (skeleton[:,2,:] + skeleton[:,8,:] + skeleton[:,4,:] + skeleton[:,20,:])/4\n w1 = skeleton[:,23,:] - center1\n w2 = skeleton[:,22,:] - center1\n center2 = (skeleton[:,1,:] + skeleton[:,0,:] + skeleton[:,16,:] + skeleton[:,12,:])/4\n h0 = skeleton[:,3,:] - center2\n h1 = skeleton[:,19,:] - center2\n h2 = skeleton[:,15,:] - center2\n width = np.max([np.max(np.abs(w1[:,0])), np.max(np.abs(w2[:,0]))])\n heigh1 = np.max(h0[:,1])\n heigh2 = np.max([np.max(np.abs(h1[:,1])), np.max(np.abs(h2[:,1]))])\n return np.asarray([width, heigh1, heigh2])\n \n def caculate_person_height(self, h5_file, list_file):\n # average value of different person: 0.36026082 0.61363413 0.76827 (mean for each person)\n # average value of different person: 1.67054954 0.87844846 1.28303429 (max for each person)\n # average value of different person: 0.0680575 0.19834167 0.21219039 (min for each person)\n name_list = [line.strip() for line in open(list_file, 'r').readlines()]\n pid_list = np.array([int(name[9:12]) for name in name_list])\n with h5py.File(h5_file,'r') as hf:\n wh_set = []\n for pid in set(pid_list):\n sidx = np.where(pid_list==pid)[0]\n wh = np.zeros((len(sidx), 3))\n for i, idx in enumerate(sidx):\n name = name_list[idx]\n skeleton = np.asarray(hf.get(name))\n wh[i] = self.calculate_height(skeleton)\n wh_set.append(wh.max(axis=0)) # notice: mean or max for different position, view points\n wh_set = np.asarray(wh_set)\n print (wh_set.mean(axis=0))\n\nif __name__ == '__main__':\n data_path = '../../../nturgb+d_skeletons/'\n db = ntu_rgbd(data_path)\n subj=True\n if subj:\n trn_list, tst_list = db.cross_subject_split()\n db.save_h5_file_skeleton_list('data/subj_seq', trn_list, split='train')\n db.save_h5_file_skeleton_list('data/subj_seq', tst_list, split='test')\n else:\n trn_list, tst_list = db.cross_view_split()\n db.save_h5_file_skeleton_list('data/view_seq', trn_list, split='train')\n db.save_h5_file_skeleton_list('data/view_seq', tst_list, split='test')\n\n \n\n","sub_path":"BeyondJoints/ntu_rgbd.py","file_name":"ntu_rgbd.py","file_ext":"py","file_size_in_byte":12316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"270754867","text":"# 给定一副牌,每张牌上都写着一个整数。\n\n# 此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:\n\n# 每组都有 X 张牌。\n# 组内所有的牌上都写着相同的整数。\n# 仅当你可选的 X >= 2 时返回 true。\n\n#  \n\n# 示例 1:\n\n# 输入:[1,2,3,4,4,3,2,1]\n# 输出:true\n# 解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]\n# 示例 2:\n\n# 输入:[1,1,1,2,2,2,3,3]\n# 输出:false\n# 解释:没有满足要求的分组。\n# 示例 3:\n\n# 输入:[1]\n# 输出:false\n# 解释:没有满足要求的分组。\n# 示例 4:\n\n# 输入:[1,1]\n# 输出:true\n# 解释:可行的分组是 [1,1]\n# 示例 5:\n\n# 输入:[1,1,2,2,2,2]\n# 输出:true\n# 解释:可行的分组是 [1,1],[2,2],[2,2]\n\n# 提示:\n\n# 1 <= deck.length <= 10000\n# 0 <= deck[i] < 10000\n\n\nclass Solution:\n def hasGroupsSizeX(self, deck) -> bool:\n num2sum = [0]*10000\n for i in range(len(deck)):\n num2sum[deck[i]] += 1\n k = 0\n x = num2sum[k]\n while(x == 0 and k < 10000):\n k += 1\n x = num2sum[k]\n for i in range(k + 1, len(num2sum)):\n if(x != num2sum[i] and num2sum[i] != 0):\n return False\n if(x >= 2):\n return True\n return False\n\n\ns = Solution()\nnum = [1, 1, 2, 2, 2, 2]\nprint(s.hasGroupsSizeX(num))\n","sub_path":"LeetCode/914. 卡牌分组.py","file_name":"914. 卡牌分组.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"396729427","text":"#!/bin/python3\r\n\r\nimport sys\r\n\r\n\r\nn = int(input().strip())\r\nfor x in range(0,n):\r\n x = str(input())\r\n x_sp = list(x)\r\n even = ''\r\n odd = ''\r\n xy = ''\r\n y = len(x)\r\n for t in range(0,y):\r\n if x_sp[t].isupper() is 'True':\r\n x_sp[t].upper()\r\n else:\r\n x_sp[t].lower()\r\n for t in range(0, y):\r\n xy += x_sp[t]\r\n","sub_path":"Hakerrank/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"328546516","text":"import plotly\nimport plotly.graph_objs as go\nimport numpy as np\nfrom plotly import tools\nimport matrixDFT\nimport copy\n\ndef get_TranslateMatrix(vector):\n return np.array([[1, 0, 0, vector[0]],\n [0, 1, 0, vector[1]],\n [0, 0, 1, vector[2]],\n [0, 0, 0, 1]])\n\ndef get_RotationMatrix(fromMatrix, toMatrix):\n \"\"\"Get the transformation matrix from fromMatrix to toMatrix.\"\"\"\n rotation_Matrix = np.zeros((4, 4))\n rotation_Matrix[:3, :3] = toMatrix.dot(np.linalg.inv(fromMatrix))\n #rotation_Matrix[:, 3] = 1\n return rotation_Matrix\n\ndef transform(vertices, origin=np.array([0, 0, 0]), x_axis=None,\n y_axis=None, z_axis=None):\n \"\"\"Transform given vertices to another world space.\n @param vertices: vertices that should be transformed to new world.\n numpy array with shape (n, 3)\n @param origin: the new worlds' origin point. numpy array with shape (3,)\n @param x_axis: x axis of the new world. numpy array with shape (3,)\n @param y_axis: y axis of the new world. numpy array with shape (3,)\n @param z_axis: z axis of the new world. numpy array with shape (3,)\n @return: vertices after the transformation with shape (n, 3) and the same\n order.\n \"\"\"\n def generate_axis(a, b):\n # One of a/b should not be None\n rand_vector = np.random.rand(3)\n rand_vector /= np.linalg.norm(rand_vector)\n if a is None:\n a = np.cross(b, rand_vector)\n if b is None:\n b = np.cross(a, rand_vector)\n return np.cross(a, b), a, b\n \n if x_axis is None:\n x_axis, y_axis, z_axis = generate_axis(y_axis, z_axis)\n if y_axis is None:\n y_axis, x_axis, z_axis = generate_axis(x_axis, z_axis)\n if z_axis is None:\n z_axis, x_axis, y_axis = generate_axis(x_axis, y_axis)\n worldMatrix = np.concatenate((x_axis, y_axis, z_axis)).reshape(3, 3)\n\n # Find transformation matrix: translation*rotation\n translateMatrix = get_TranslateMatrix(origin)\n localMatrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n rotation_Matrix = get_RotationMatrix(localMatrix.T, worldMatrix.T)\n transform_Matrix = translateMatrix.dot(rotation_Matrix)\n\n vertices = np.insert(vertices, vertices.shape[0], 0, axis=0)\n vertices = np.insert(vertices, vertices.shape[1], 1, axis=1)\n vertices = transform_Matrix.dot(vertices.T).T[:, :-1]\n return vertices\n\n\ndef lineTo3DMesh(x_list, y_list):\n \"\"\"Generate 3D mesh from the 2D line.\n @param line_function: Given x, get the corresponding y\n @param x_start: starting x value.\n @param x_end: ending x value.\n @param sample: number of sample point.\n @return: (vertices, triangles) numpy array pair with shape (2*sample, 3)\n \"\"\"\n nv = 0 \n vertices = np.zeros((0, 3))\n triangles = np.zeros((0, 3))\n \n for i in range(len(x_list)):\n x = x_list[i]\n y = y_list[i]\n \n new_points = np.array(\n [[x, 0, 0], [x, y, 0]])\n vertices = np.append(vertices, new_points, axis=0)\n nv += 2\n if nv > 2:\n new_triangles = np.array(\n [[nv - 4, nv - 3, nv - 2], [nv - 3, nv - 1, nv - 2]])\n triangles = np.append(triangles, new_triangles, axis=0) \n return vertices, triangles\n\n\n\ndef make1DGaussian(s, sigma, ctr=None, x0 = 0.):\n #normalization?\n\n if ctr is None:\n ctr = s/2.0 \n \n x = np.linspace(-ctr+0.5, s-ctr-0.5, s)\n \n deg = -np.pi/180.0 \n\n array = np.exp(-(x-x0)**2./(2.*sigma**2.))\n return x, array\n\n\ndef add_linesurface(x_data, y_data, axis):\n vertices, triangles = lineTo3DMesh(x_data, y_data)\n\n if axis == 'y':\n worldVertices = transform(\n vertices, x_axis=np.array([1, 0, 0]), y_axis=np.array([0, 0, 1]))\n elif axis == 'z':\n worldVertices = transform(\n vertices, x_axis=np.array([1, 0, 0]), y_axis=np.array([0, 1, 0]))\n \n mesh = go.Mesh3d(x=worldVertices[:, 0], \n y=worldVertices[:, 1],\n z=worldVertices[:, 2], \n i=triangles[:, 0], \n j=triangles[:, 1],\n k=triangles[:, 2])\n\n return mesh\n\nTHRESHOLD = 10**14\ndef clean_value(complex_data):\n real_amp = np.sum(np.abs(complex_data.real))\n imag_amp = np.sum(np.abs(complex_data.imag))\n try:\n if real_amp > THRESHOLD * imag_amp:\n #print('imag part is tiny and set to 0')\n complex_data_copy = copy.deepcopy(complex_data)\n complex_data_copy.imag *= 0\n return complex_data_copy\n elif imag_amp > THRESHOLD * real_amp:\n #print ('real part is tiny set to 0')\n complex_data_copy = copy.deepcopy(complex_data)\n complex_data_copy.real *= 0\n return complex_data_copy\n else:\n return complex_data\n except ValueError:\n return complex_data\n\n\ndef complex_3dplot(x_data, complex_data, real_color='blue', imag_color='red', line_color='cyan', to_plot=True, **kwargs):\n\n\n #if np.iscomplex(complex_data[0]):\n complex_data = clean_value(complex_data)\n\n traces = []\n\n #add real surface\n mesh = add_linesurface(x_data, complex_data.real, axis='y')\n mesh.update(opacity=0.8, color=real_color)\n traces.append(mesh)\n \n #add imag surface\n mesh = add_linesurface(x_data, complex_data.imag, axis='z')\n mesh.update(opacity=0.8, color=imag_color)\n traces.append(mesh)\n\n #add the line\n traces.append(go.Scatter3d(x=x_data, \n y=complex_data.imag, \n z=complex_data.real, \n mode=\"lines\", \n line=dict(\n color=line_color,\n width=3\n )\n ))\n\n if to_plot:\n fig = go.Figure(data=traces, layout=go.Layout(\n showlegend=False,\n ))\n if kwargs.get('filename'):\n plotly.offline.plot(fig, filename=kwargs['filename'])\n else:\n plotly.offline.iplot(fig)\n \n if kwargs.get('return_traces'):\n return traces\n\n\ndef complex_3danimation(x_data, complex_data_list, changing_variable_list, real_color='blue', imag_color='red', line_color='cyan', to_plot=True, **kwargs):\n figure = {\n 'data': [],\n 'layout': {'xaxis': {'range': [-40, 40], 'autorange': False},\n 'yaxis': {'range': [-3, 3], 'autorange': False}\n },\n 'frames': []\n }\n\n sliders_dict = {\n 'active': 0,\n 'yanchor': 'top',\n 'xanchor': 'left',\n 'currentvalue':{\n 'font': {'size': 20},\n 'prefix': 'Shift:',\n 'visible': True,\n 'xanchor': 'right'\n },\n 'transition':{\n 'duration': 300,\n 'easing': 'cubic-in-out'\n },\n 'pad':{'b': 10, 't': 50},\n 'len': 0.9,\n 'x': 0.1, \n 'y': 0,\n 'steps': []\n }\n layout = go.Layout(\n scene = dict(\n xaxis = dict(\n range = [-40,40],),\n yaxis = dict(\n range = [-3,3],),\n zaxis = dict(\n range = [-3,3],),\n ),\n width=700,\n margin=dict(\n r=20, l=10,\n b=10, t=10)\n )\n\n for i in range(len(changing_variable_list)):\n changing_var = changing_variable_list[i]\n frame = {'data': [], 'name': str(changing_var)}\n data_dict = complex_3dplot(x_data, complex_data_list[i], real_color=real_color, imag_color=imag_color, line_color=line_color, to_plot=False, return_traces=True)\n\n if i == 0:\n figure['data'] = data_dict\n figure['layout'] = layout\n\n frame['data'] = data_dict\n frame['layout'] = layout\n figure['frames'].append(frame) \n\n slider_step = {\n 'args': [\n [changing_var],\n {'frame': \n {'duration': 300, 'redraw': False},\n 'mode': 'immediate',\n 'transition': {'duration': 300}\n }\n ],\n 'label': changing_var,\n 'method': 'animate'\n }\n sliders_dict['steps'].append(slider_step)\n\n figure['layout']['sliders'] = [sliders_dict] \n\n if to_plot:\n if kwargs.get('filename'):\n plotly.offline.plot(figure, filename=kwargs['filename'])\n else:\n plotly.offline.iplot(figure)\n\n\ndef example_FT_properties(plot_line=False, **kwargs):\n sigma = 10\n narray = 101\n \n #define the figure object \n fig = tools.make_subplots(\n rows=8, cols=2,\n specs=[[{'is_3d': True}, {'is_3d': True}] for i in range(8)],\n print_grid=False\n )\n ft = matrixDFT.MatrixFourierTransform()\n \n #subplot 1: real, even\n x, gaussian_array = make1DGaussian(narray, sigma, x0 = 10)\n gaussian_array = np.array([gaussian_array])\n ft_gaussian = ft.perform(gaussian_array, 9, (1, 81))\n \n x_data = np.linspace(-40, 40, 81)\n \n func1 = lambda x, x0, sigma: np.exp(-(x-x0)**2./(2.*sigma**2.))\n func2 = lambda x, x0, sigma: x * np.exp(-(x-x0)**2./(2.*sigma**2.))\n \n x_input = np.linspace(-50, 50, 101)\n \n y = func1(x_input, 0., sigma)\n #generate the complex_3dplot plot\n trace = complex_3dplot(x_input, y, to_plot=False, return_traces=True)\n #put the 3d objects into the subplot\n fig.append_trace(trace[0], 1, 1)\n fig.append_trace(trace[1], 1, 1)\n if plot_line:\n fig.append_trace(trace[2], 1, 1)\n \n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 1, 2)\n fig.append_trace(trace[1], 1, 2)\n if plot_line:\n fig.append_trace(trace[2], 1, 2)\n \n y = func2(x_input, 0., sigma)\n trace = complex_3dplot(x, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 2, 1)\n fig.append_trace(trace[1], 2, 1)\n if plot_line:\n fig.append_trace(trace[2], 2, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 2, 2)\n fig.append_trace(trace[1], 2, 2)\n if plot_line:\n fig.append_trace(trace[2], 2, 2)\n \n \n y = func1(x_input, 0., sigma) * 1j\n trace = complex_3dplot(x_input, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 3, 1)\n fig.append_trace(trace[1], 3, 1)\n if plot_line:\n fig.append_trace(trace[2], 3, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 3, 2)\n fig.append_trace(trace[1], 3, 2)\n if plot_line:\n fig.append_trace(trace[2], 3, 2)\n \n y = func2(x_input, 0., sigma) * 1j\n trace = complex_3dplot(x, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 4, 1)\n fig.append_trace(trace[1], 4, 1)\n if plot_line:\n fig.append_trace(trace[2], 4, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 4, 2)\n fig.append_trace(trace[1], 4, 2)\n if plot_line:\n fig.append_trace(trace[2], 4, 2)\n \n \n \n y = func1(x_input, 0., sigma) * (1. + 1j)\n trace = complex_3dplot(x_input, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 5, 1)\n fig.append_trace(trace[1], 5, 1)\n if plot_line:\n fig.append_trace(trace[2], 5, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 5, 2)\n fig.append_trace(trace[1], 5, 2)\n if plot_line:\n fig.append_trace(trace[2], 5, 2)\n \n y = func2(x_input, 0., sigma) * (1. + 1j)\n trace = complex_3dplot(x, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 6, 1)\n fig.append_trace(trace[1], 6, 1)\n if plot_line:\n fig.append_trace(trace[2], 6, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 6, 2)\n fig.append_trace(trace[1], 6, 2)\n if plot_line:\n fig.append_trace(trace[2], 6, 2)\n \n \n y = func1(x_input, 10., sigma)\n trace = complex_3dplot(x_input, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 7, 1)\n fig.append_trace(trace[1], 7, 1)\n if plot_line:\n fig.append_trace(trace[2], 7, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 7, 2)\n fig.append_trace(trace[1], 7, 2)\n if plot_line:\n fig.append_trace(trace[2], 7, 2)\n \n y = func1(x_input, 10., sigma) * 1j\n trace = complex_3dplot(x, y, to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 8, 1)\n fig.append_trace(trace[1], 8, 1)\n if plot_line:\n fig.append_trace(trace[2], 8, 1)\n \n ft_y = ft.perform(np.array([y]), 9, (1, 81))\n trace = complex_3dplot(x_data, ft_y[0], to_plot=False, return_traces=True)\n fig.append_trace(trace[0], 8, 2)\n fig.append_trace(trace[1], 8, 2)\n if plot_line:\n fig.append_trace(trace[2], 8, 2)\n \n \n fig['layout'].update(title='Properties of Fourier Transform',\n height=1600, width=600, showlegend=False)\n \n if kwargs.get('filename'):\n plotly.offline.plot(fig, filename=kwargs['filename'])\n else:\n plotly.offline.iplot(fig)\n","sub_path":"complex_demo.py","file_name":"complex_demo.py","file_ext":"py","file_size_in_byte":13677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"54720323","text":"from SRD.spell import Spell\nfrom SRD.equipment import Equipment\n\nclass SRD:\n async def query(self, args, message):\n query = args[0].split(' ', 1)\n\n #Expect 2 atoms in query\n if len(query) != 2:\n await message.channel.send(f\"\"\"{message.author.mention}, I didn't find anything to search for.\"\"\")\n else:\n [queryType, queryContent] = query\n if queryType == 'spell':\n spell = Spell()\n await spell.query(queryContent, message)\n elif queryType == 'equipment':\n equipment = Equipment()\n await equipment.query(queryContent, message)\n else:\n await message.channel.send(f\"\"\"{message.author.mention}, I didn't understand that SRD query.\"\"\")\n\n \n\n ","sub_path":"src/SRD/srd.py","file_name":"srd.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"561015254","text":"sequences=['ATTAGACCTG','CCTGCCGGAA','AGACCTGCCG','GCCGGAATAC']\nhalfway= len(sequences[0])/2\ngenome=sequences[0] # this is the string that will be added onto throughout the loop\nsequences.remove(sequences[0])\n\n\nfor j in range(len(sequences)):\n for sequence in sequences:\n front=[]\n back=[]\n for i in range(int(halfway),len(sequence)):\n\n if genome.endswith(sequence[:i]):\n genome=genome+sequence[i:]\n sequences.remove(sequence)\n\n elif genome.startswith(sequence[-i:]):\n genome=sequence[:i]+genome\n sequences.remove(sequence)\n'''\n elif not genome.startswith(sequence[-i:]) or not genome.endswith(sequence[:i]):\n\n sequences.remove(sequence) # this doesnt seem to work want to get rid of \n #sequences that are in the middle of the string and \n #already accounted for \n'''\nprint(sequence)","sub_path":"functions/looping_over_times.py","file_name":"looping_over_times.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"453100268","text":"# FuffyTuna\n# Version 0.2.0 bby\n# By Cat#5854\n\n# Make this into a command: despatomatone, https://www.youtube.com/watch?v=bQJU82Lk79g\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot\nimport asyncio\nimport random\nfrom random import sample\nimport re\nimport numpy as np\nimport pandas as pd\n\nclient = discord.Client()\nsentences = \"\"\ndadbot_censor = False # people on my server were not happy with the censoring of dadbot ( I love the censorship and but I begrudgingly obliged )\ntuna_chance = 150 # a one in five hundred chance\n\n@client.event\nasync def on_ready():\n\tprint (\"online\")\n\tprint (\"name: \" + client.user.name)\n\tprint (\"id: \" + client.user.id)\n\tprint (\"message of the day: your computer is now infected by ligma\")\n\n@client.event\nasync def on_message(ctx): # I replaced message with ctx since thats what all the cool kids are doing\n\n\tluck = random.randint(1,tuna_chance)\n\tprint(\"your lucky number is \" + str(luck))\n\t\n\tif ctx.content.lower() == 'this is so sad alexa play despacito' or ctx.content.lower() == 'despacito' or ctx.content.lower() == 'alex play despacito':\n\t\tprint(ctx.author.voice_channel)\n\t\tif ctx.author.voice_channel:\n\t\t\ttwochance = random.randint(1,20)\n\t\t\tprint(\"despacito roll: \" + str(twochance))\n\t\t\n\t\t\tif twochance == 2:\n\t\t\t\tawait client.send_message(ctx.channel, 'You have been selected by the Illuminati to listen to Despacito 2.\\nPlaying Despacito 2')\n\t\t\t\tvoice = await client.join_voice_channel(ctx.author.voice_channel)\n\t\t\t\tplayer = await voice.create_ytdl_player('https://www.youtube.com/watch?v=W3GrSMYbkBE')\n\t\t\t\tplayer.start()\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tawait client.send_message(ctx.channel, 'Playing Despacito')\n\t\t\t\tvoice = await client.join_voice_channel(ctx.author.voice_channel)\n\t\t\t\tplayer = await voice.create_ytdl_player('https://www.youtube.com/watch?v=kJQP7kiw5Fk')\n\t\t\t\tplayer.start()\n\t\n\t\telse:\n\t\t\tawait client.send_message(ctx.channel, 'ur not in a voice channel u dumb dumb')\n\t\t\n\t\n\tif ctx.content.lower() == 'this is so sad alexa play despayeeto' or ctx.content.lower() == 'despayeeto' or ctx.content.lower() == 'alex play despayeeto':\n\t\tprint(\"Playing Despayeeto\")\n\t\tawait client.send_message(ctx.channel, 'Playing Despayeeto')\n\t\ttry:\n\t\t\tvoice = await client.join_voice_channel(ctx.author.voice_channel)\n\t\texcept:\n\t\t\tpass\n\t\tplayer = await voice.create_ytdl_player('https://www.youtube.com/watch?v=jEddfV8Ts3g')\n\t\tplayer.start()\n\n\tif ctx.content.lower() == 'this is so sad alexa play despatomatone' or ctx.content.lower() == 'despatomatone' or ctx.content.lower() == 'alex play despatomatone':\n\t\tprint(\"Playing Despatomatone\")\n\t\tawait client.send_message(ctx.channel, 'Playing Despatomatone')\n\t\ttry:\n\t\t\tvoice = await client.join_voice_channel(ctx.author.voice_channel)\n\t\texcept:\n\t\t\tpass\n\t\tplayer = await voice.create_ytdl_player('https://www.youtube.com/watch?v=bQJU82Lk79g')\n\t\tplayer.start()\n\n\tif ctx.content.lower() == 'asdf':\n\t\tawait client.send_message(ctx.channel, 'fine... jeez')\n\t\tfor x in client.voice_clients:\t# I don't understand how this works, I just ripped it from stack overflow\n\t\t\tif(x.server == ctx.server):\n\t\t\t\treturn await x.disconnect()\n\t\t\n\tif ctx.content.lower() == 'fuffytuna please':\n\t\tawait client.send_message(ctx.channel, \"Have fun! \")\n\t\t\n\tif ctx.content.lower() == 'fuffytuna help':\n\t\tprint(\"Helping\")\n\t\tawait client.send_message(ctx.channel, \"\"\"\n\t\t...Heres FuffyTuna's commands! \n\t\tFuffyTuna help: \n\t\t...This \n\t\tthis is so sad alexa play despacito: \n\t\t...Plays despacito in your voice channel \n\t\tthis is so sad alexa play despayeeto: \n\t\t...Plays despayeeto in your voice channel \n\t\tasdf: \n\t\t...FuffyTuna leave the voice channel \n\t\tFuffyTuna please: \n\t\t...Gives you the whole original fanfic \n\t\tFuffyTuna make command # ;: \n\t\t...Gives you the whole original fanfic\n\t\tFuffyTuna help make command\n\t\t...More in depth explanation of command syntax\n\t\tFuffyTuna show commands:\n\t\t...Shows all custom commands\n\t\tFuffyTuna delete command:\n\t\t...Deletes that command (DO NOT LET COMMANDS BECOME LESS THAN TWO)\n\t\t\"\"\")\n\n\tif ctx.content.lower() == 'fuffytuna help make command':\n\t\tawait client.send_message(ctx.channel,\"\"\"\n\t\tFuffyTuna will let you make a automatic response to any word!\n\t\tTo create this 'command' simple type\n\t\tFuffyTuna make command ;\n\t\tExample:\n\t\tFuffyTuna make command oh hi mark;i did not hit her i did not\n\t\tWARNING:\n\t\tALWAYS HAVE AT LEAST TWO COMMANDS OR IT DOESN'T WORK\n\t\tHELP IT ISN'T WORKING!?\n\t\tDid you add a space after the command?\n\t\tIf that doesn't work ask Cat#5854\n\t\t\"\"\")\n\n\t# read custom commands\n\tprint(str(ctx.author.id))\n\tif ctx.author.id != client.user.id:\n\t\twith open(r'C:\\Users\\Cat\\Documents\\FuffyTunaBot\\commands.txt','r') as f: # short for command wink wink\n\t\t\tfor i, l in enumerate(f):\n\t\t\t\tpass\n\t\t\tcount = i + 1\n\t\t\tprint(str(count))\n\t\t\t\n\t\t\tcmd_array = np.genfromtxt('commands.txt', dtype='str', delimiter=';') # FINALLLLY I FIGURED IT OUT\n\t\t\tprint(str(cmd_array[:]))\n\t\n\t\t\ti = 0\n\t\t\tfor i in range(count):\n\t\t\t\tif ctx.content == cmd_array[i,0]:\n\t\t\t\t\tawait client.send_message(ctx.channel, cmd_array[i,1])\n\n\t# write custom commands\n\tif ctx.content.lower().startswith(\"fuffytuna make command\"):\n\t\tif ';' in ctx.content:\n\t\t\tspliced_ctx = ctx.content[23:]\n\t\t\tprint(spliced_ctx)\n\t\t\twith open(r'C:\\Users\\Cat\\Documents\\FuffyTunaBot\\commands.txt','a') as f:\n\t\t\t\tf.write('\\n' + spliced_ctx)\n\t\t\tsplit_ctx = ctx.content[23:].split(\";\")\n\t\t\tawait client.send_message(ctx.channel, \"MADE COMMAND!\\nCommand: \" + split_ctx[0] + \"\\nWith responcs: \" + split_ctx[1])\n\t\telse:\n\t\t\tawait client.send_message(ctx.channel, \"Improper syntax\")\n\n\t# show custom commands\n\tif ctx.content.lower() == 'fuffytuna show commands':\n\t\tcommand_listing = ''\n\t\twith open(r'C:\\Users\\Cat\\Documents\\FuffyTunaBot\\commands.txt') as f:\n\t\t\tfor line in f:\n\t\t\t\tcommand_listing += line\n\t\tawait client.send_message(ctx.channel, \"Custom commands available are:\\n\" + command_listing)\n\n\t# delete custom commands\n\tif ctx.content.lower().startswith(\"fuffytuna delete command\"): #25\n\t\tcommand = ctx.content[25:]\n\t\twith open(r'C:\\Users\\Cat\\Documents\\FuffyTunaBot\\commands.txt',\"r\") as f:\n\t\t\tlines = f.readlines()\n\t\twith open(r'C:\\Users\\Cat\\Documents\\FuffyTunaBot\\commands.txt',\"w\") as f:\n\t\t\tfor line in lines:\n\t\t\t\tif line.startswith(command) == False:\n\t\t\t\t\tf.write(line)\n\t\tawait client.send_message(ctx.channel, \"Deleted command: \" + command)\n\tif dadbot_censor == True:\n\t\tif ctx.content.lower().startswith(\"im\") or ctx.content.lower().startswith(\"i'm\"): # i wonder why .lower() has parenthesis for arguments even though it has none\n\t\t\tglobal victim # global bc i needed to use it in the next part the send message part\n\t\t\tvictim = ctx.author.mention\n\t\t\n\t\tif ctx.author.id == \"247852652019318795\" and ctx.content.startswith(\"Hi\"):\n\t\t\tawait client.delete_message(ctx)\n\t\t\tawait client.send_message(ctx.channel, \"don\\'t you fricking dare dadbot, trying to abuse poor \" + victim + \", your on thin ice \" + ctx.author.mention)\n\t\t\tvictim = \"\" \n\t\t\n\tif luck == 1:\n\t\tif ctx.author.bot == False:\n\t\t\tprint(\"You win!!\")\n\t\t\twith open('FuffyTunaWithXtraFullstops.txt') as fuffy:\n\t\t\t\tsentences = re.findall(r\".*?[\\.\\!\\?]+\", fuffy.read())\n\t\t\tbibleverse = sample(sentences, 1)\n\t\t\tawait client.send_message(ctx.channel, \"And I quoth from FuffyTuna.txt \\n\" + str(bibleverse) + \"\\n want to read more? Just say \\\"FuffyTuna please\\\"\")\n\nclient.run(\"\") # Fuck you Klasa","sub_path":"transcend.py","file_name":"transcend.py","file_ext":"py","file_size_in_byte":7475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"293645527","text":"import sys\nimport warnings\n\nimport torch\nimport torchsummary\n\nif \"google.colab\" in sys.modules:\n from tqdm import tqdm_notebook as tqdm\nelse:\n from tqdm import tqdm\n\n\ndef verify_model(args, model, loader, optimizer, criterion, device):\n \"\"\"\n Performs all necessary validation on your model to ensure correctness.\n You may need to change the batch_size or max_iters in overfit_example\n in order to overfit the batch.\n \"\"\"\n if not args.no_verify:\n model_summary(args, model, loader)\n check_batch_dimension(model, loader, optimizer)\n overfit_example(model, loader, optimizer, criterion, device, args.batch_dim)\n check_all_layers_training(model, loader, optimizer, criterion)\n detect_NaN_tensors(model)\n print(\"Verification complete - all tests passed!\")\n\n\ndef model_summary(args, model, loader):\n \"\"\"\n Prints out model using torchsummary.\n \"\"\"\n data, _ = next(loader)\n torchsummary.summary(model, data, batch_dim=args.batch_dim)\n\n\ndef check_batch_dimension(model, loader, optimizer, test_val=2):\n \"\"\"\n Verifies that the provided model loads the data correctly. We do this by setting the\n loss to be something trivial (e.g. the sum of all outputs of example i), running the\n backward pass all the way to the input, and ensuring that we only get a non-zero gradient\n on the i-th input.\n See details at http://karpathy.github.io/2019/04/25/recipe/.\n \"\"\"\n model.eval()\n data, _ = next(loader)\n optimizer.zero_grad()\n\n if not isinstance(data, (list, tuple)):\n data.requires_grad_()\n output = model(data)\n loss = output[test_val].sum()\n loss.backward()\n\n assert loss != 0, \"Loss should be greater than zero.\"\n assert (data.grad[test_val] != 0).any(), \"The gradient of the test input is not nonzero.\"\n assert (data.grad[:test_val] == 0.0).all() and (\n data.grad[test_val + 1 :] == 0.0\n ).all(), \"There are nonzero gradients in the batch, when they should all be zero.\"\n\n\ndef overfit_example(\n model, loader, optimizer, criterion, device, batch_dim=0, batch_size=2, max_iters=50\n):\n \"\"\"\n Verifies that the provided model can overfit a single batch or example.\n \"\"\"\n\n def batch_slice(input_data, batch_size, batch_dim):\n if isinstance(input_data, (list, tuple)):\n return [batch_slice(data, batch_size, batch_dim) for data in input_data]\n if input_data.ndim == 1:\n return input_data[:batch_size]\n none_slice = (slice(None),)\n batch_dim_slice = (\n none_slice * batch_dim\n + (slice(batch_size,),)\n + none_slice * (input_data.ndim - batch_dim - 1)\n )\n return input_data[batch_dim_slice]\n\n data, target = next(loader)\n data = batch_slice(data, batch_size, batch_dim)\n target = batch_slice(target, batch_size, batch_dim)\n\n with tqdm(desc=\"Verify Model\", total=max_iters, ncols=120) as pbar:\n for _ in range(max_iters):\n optimizer.zero_grad()\n output = model(*data) if isinstance(data, (list, tuple)) else model(data)\n loss = criterion(output, target)\n if torch.allclose(loss, torch.tensor(0.0).to(device)):\n break\n loss.backward()\n optimizer.step()\n pbar.set_postfix({\"Loss\": loss.item()})\n pbar.update()\n\n if not torch.allclose(loss, torch.tensor(0.0).to(device)):\n warnings.warn(\n f\"\\nOverfit Loss is not sufficiently close to 0: {loss}\\n\"\n f\"This may indicate an error with your model.\",\n RuntimeWarning,\n )\n\n\ndef detect_NaN_tensors(model):\n \"\"\"\n Verifies that the provided model does not have any exploding gradients.\n \"\"\"\n for name, param in model.named_parameters():\n assert torch.isfinite(param).all(), (\n f\"Detected NaN and/or inf values in model weights: {name}. \"\n f\"Check your forward pass for numerically unstable operations.\"\n )\n\n\ndef check_all_layers_training(model, loader, optimizer, criterion):\n \"\"\"\n Verifies that the provided model trains all provided layers.\n \"\"\"\n model.train()\n data, target = next(loader)\n before = [param.clone().detach() for param in model.parameters()]\n\n optimizer.zero_grad()\n output = model(*data) if isinstance(data, (list, tuple)) else model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n after = model.parameters()\n for start, end in zip(before, after):\n assert (start != end).any(), (\n \"Detected some layers that are not training. Did you freeze \"\n \"some layers or forget to set the model to train mode?\"\n )\n","sub_path":"example_cnn/src/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"140104726","text":"\"\"\"\n Req:\nPerson has id, name, age as instance variables\nEmployee has id, name, age, pan, pfNo as instance variables\n\ncreate obj and set data for person and employee.\n\nw/o inheritence\n------------------------------------------\nclass Person:\n id=None\n name=None\n age=None\n\n def showPersonalInfo(self):\n print(self.id)\n print(self.name)\n print(self.age)\n\n\nclass Employee :\n pan= None\n pfNo=None\n id=None\n name=None\n age=None\n\n def printEmp(self):\n print(self.pan)\n print(self.pfNo)\n print(self.id)\n print(self.name)\n print(self.age)\n\nWith Inheritence:\n--------------------------------------------------\n#Person class as parent\nclass Person:\n id=None\n name=None\n age=None\n\n def showPersonalInfo(self):\n print(self.id)\n print(self.name)\n print(self.age)\n\nclass Employee(Person):\n pan= None\n pfNo=None\n\n def printEmp(self):\n print(self.pan)\n print(self.pfNo)\n\n\"\"\"\n#Person class as parent\nclass Person:\n id=None\n name=None\n age=None\n \n def showPersonalInfo(self):\n print(self.id)\n print(self.name)\n print(self.age)\n\n\n#Employee class as child\nclass Employee(Person):\n pan= None\n pfNo=None\n \n def printEmp(self):\n print(self.pan)\n print(self.pfNo)\n\n# emp class is reusing id,name,age and showPersonalInfo() funtn\n\n# create obj ; set data and show\nprint(\"print person info\")\np = Person()\np.id = 2000\np.name = \"user1\"\np.age = 34\n\np.showPersonalInfo() # shows id,name, age for person\n\nprint(\"print employee info\")\nemp = Employee()\nemp.id = 4000\nemp.name = \"user2\"\nemp.age = 39\nemp.pan = \"testpan\"\nemp.pfNo = \"testpf\"\nemp.showPersonalInfo() # shows id,name, age for emp\nemp.printEmp() # show pan, pfNo of emp\n\n# emp obj is reusing id,name,age and showPersonalInfo() funtn\n#showPersonalInfo() can be called by parent obj and child obj\n\n","sub_path":"PythonBasics1/oopsInherit/SIngleInheri1.py","file_name":"SIngleInheri1.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"455112368","text":"#!/usr/bin/env python \nimport roslib\nroslib.load_manifest('learning_tf')\nimport rospy\nimport math\nimport tf\nimport geometry_msgs.msg\nimport turtlesim.srv\n\"\"\"\nif __name__ == '__main__':\n\trospy.init_node('tf_turtle')\n\n\tlistener = tf.TransformListener()\n\n\t#rospy.wait_for_service('spawn')\n\t#spawner = rospy.ServiceProxy('spawn', turtlesim.srv.Spawn)\n\t#spawner(4, 2, 0, 'turtle2')\n\n\t#turtle_vel = rospy.Publisher('turtle2/cmd_vel', geometry_msgs.msg.Twist,queue_size=1)\n\n\trate = rospy.Rate(10.0)\n\twhile not rospy.is_shutdown():\n\t\ttry:\n\t\t\t(trans,rot) = listener.lookupTransform('/turtle2', '/turtle1', rospy.Time(0))\n\t\texcept (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n\t\t\tcontinue\n\n\t\tangular = 4 * math.atan2(trans[1], trans[0])\n\t\tlinear = 0.5 * math.sqrt(trans[0] ** 2 + trans[1] ** 2)\n\t\tcmd = geometry_msgs.msg.Twist()\n\t\tcmd.linear.x = linear\n\t\tcmd.angular.z = angular\n\t\tturtle_vel.publish(cmd)\n\n\t\trate.sleep()\n\"\"\"\nn = 16\n\nclass DynamicTFBroadcaster:\n\n\tdef __init__(self):\n\t\tself.pub_tf = rospy.Publisher(\"/tf\", tf.msg.tfMessage, queue_size=1)\n\n\t\tchange = 0.0\n\n\t\tlistener = tf.TransformListener()\n\n\t\trate = rospy.Rate(500)\n\n\t\twhile not rospy.is_shutdown():\n\t\t\t# Run this loop at about 10Hz\n\t\t\t#rospy.sleep(0.1)\n\n\t\t\t\t#name = '/tag_' + str(i), '/usb_cam1'\n\t\t\ttry:\n\t\t\t\t(trans,rot) = listener.lookupTransform('/tag_1', '/usb_cam2', rospy.Time(0))\n\t\t\texcept (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n\t\t\t\tcontinue\n\t\t\t\t#print trans\n\t\t\t\t#print rot\n\t\t\t\n\t\t\t\"\"\"\n\t\t\tangular = 4 * math.atan2(trans[1], trans[0])\n\t\t\tlinear = 0.5 * math.sqrt(trans[0] ** 2 + trans[1] ** 2)\n\t\t\tcmd = geometry_msgs.msg.Twist()\n\t\t\tcmd.linear.x = linear\n\t\t\tcmd.angular.z = angular\n\t\t\tturtle_vel.publish(cmd)\n\t\t\t\"\"\"\n\n\t\t\tt = geometry_msgs.msg.TransformStamped()\n\t\t\tt.header.frame_id = \"tag_1_ideal\"\n\t\t\tt.header.stamp = rospy.Time.now()\n\t\t\tt.child_frame_id = \"tag_1_guess\"\n\n\t\t\tt.transform.translation.x = trans[0]\n\t\t\tt.transform.translation.y = trans[1]\n\t\t\tt.transform.translation.z = trans[2]\n\n\t\t\tt.transform.rotation.x = rot[0]\n\t\t\tt.transform.rotation.y = rot[1]\n\t\t\tt.transform.rotation.z = rot[2]\n\t\t\tt.transform.rotation.w = rot[3]\n\t\t\ttfm = tf.msg.tfMessage([t])\n\t\t\tself.pub_tf.publish(tfm)\n\n\t\t\t#print t\n\n\t\t\trate.sleep()\n\n\nif __name__ == '__main__':\n\trospy.init_node('tag_1_guess')\n\ttfb = DynamicTFBroadcaster()\n\trospy.spin()","sub_path":"learning_tf/nodes/tag_1_guess.py","file_name":"tag_1_guess.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"641482092","text":"import numpy as np\nimport h5py\nimport os\n\nHOME = os.path.expanduser(\"~\")\n\n\ndef layer_name_from_cv_url(cv_url):\n return cv_url.strip(\"/\").split(\"/\")[-2]\n\n\ndef dir_from_layer_name(layer_name):\n return HOME + \"/\" + layer_name + \"/\"\n\n\ndef read_edge_file_cv(cv_st, path):\n \"\"\" Reads the edge ids and affinities from an edge file \"\"\"\n\n if 'unbreakable' in path:\n dt = 'uint64, uint64'\n elif 'isolated' in path:\n dt = 'uint64'\n else:\n dt = 'uint64, uint64, float32, uint64'\n\n buf = cv_st.get_file(path)\n edge_data = np.frombuffer(buf, dtype=dt)\n\n if len(edge_data) == 0:\n if len(dt.split(\",\")) == 1:\n edge_data = np.array([], dtype=np.uint64)\n else:\n edge_data = {\"f0\": np.array([], dtype=np.uint64),\n \"f1\": np.array([], dtype=np.uint64),\n \"f2\": np.array([], dtype=np.float32),\n \"f3\": np.array([], dtype=np.uint64)}\n\n if 'isolated' in path:\n edge_dict = {\"node_ids\": edge_data}\n else:\n edge_ids = np.concatenate([edge_data[\"f0\"].reshape(-1, 1),\n edge_data[\"f1\"].reshape(-1, 1)], axis=1)\n\n edge_dict = {\"edge_ids\": edge_ids}\n\n if \"connected\" in path:\n edge_dict['edge_affs'] = edge_data['f2']\n edge_dict['edge_areas'] = edge_data['f3']\n\n return edge_dict\n\n\ndef read_edge_file_h5(path, layer_name=None):\n if not path.endswith(\".h5\"):\n path = path[:-4] + \".h5\"\n\n if layer_name is not None:\n path = dir_from_layer_name(layer_name) + path\n\n edge_dict = {}\n with h5py.File(path, \"r\") as f:\n for k in f.keys():\n edge_dict[k] = f[k].value\n\n return edge_dict\n\n\ndef download_and_store_edge_file(cv_st, path, create_dir=True):\n edge_dict = read_edge_file_cv(cv_st, path)\n\n dir_path = dir_from_layer_name(layer_name_from_cv_url(cv_st.layer_path))\n\n if not os.path.exists(dir_path) and create_dir:\n os.makedirs(dir_path)\n\n with h5py.File(dir_path + path[:-4] + \".h5\", \"w\") as f:\n for k in edge_dict.keys():\n f.create_dataset(k, data=edge_dict[k], compression=\"gzip\")\n\n\n# def read_mapping_cv(cv_st, path, olduint32=False):\n# \"\"\" Reads the mapping information from a file \"\"\"\n#\n# if olduint32:\n# mapping = np.frombuffer(cv_st.get_file(path),\n# dtype=np.uint64).reshape(-1, 2)\n# mapping_to = mapping[:, 1]\n# mapping_from = np.frombuffer(np.ascontiguousarray(mapping[:, 0]), dtype=np.uint32)[::2].astype(np.uint64)\n# return np.concatenate([mapping_from[:, None], mapping_to[:, None]], axis=1)\n# else:\n# return np.frombuffer(cv_st.get_file(path), dtype=np.uint64).reshape(-1, 2)\n#\n#\n# def read_mapping_h5(path, layer_name=None):\n# if not path.endswith(\".h5\"):\n# path = path[:-4] + \".h5\"\n#\n# if layer_name is not None:\n# path = dir_from_layer_name(layer_name) + path\n#\n# with h5py.File(path, \"r\") as f:\n# mapping = f[\"mapping\"].value\n#\n# return mapping\n#\n#\n# def download_and_store_mapping_file(cv_st, path, olduint32=False):\n# mapping = read_mapping_cv(cv_st, path, olduint32=olduint32)\n#\n# dir_path = dir_from_layer_name(layer_name_from_cv_url(cv_st.layer_path))\n#\n# if not os.path.exists(dir_path):\n# os.makedirs(dir_path)\n#\n# with h5py.File(dir_path + path[:-4] + \".h5\", \"w\") as f:\n# f[\"mapping\"] = mapping","sub_path":"pychunkedgraph/creator/creator_utils.py","file_name":"creator_utils.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"224808261","text":"from heapPriorityQueue import HeapPriorityQueue\nimport graph\nfrom queue import *\n\nparent = {}\nrank = {}\n\ndef make_set(vertex):\n parent[vertex] = vertex\n rank[vertex] = 0\n\ndef find(vertex):\n if parent[vertex] != vertex:\n parent[vertex] = find(parent[vertex])\n return parent[vertex]\n\ndef union(vertex1, vertex2):\n root1 = find(vertex1)\n root2 = find(vertex2)\n if root1 != root2:\n if rank[root1] > rank[root2]:\n parent[root2] = root1\n elif rank[root1] < rank[root2]:\n parent[root1] = root2\n else:\n parent[root2] = root1\n rank[root1] += 1\n\ndef maximum_st_kruskal(g, src, target):\n\n maximum_spanning_tree = graph.Graph() # list of edges in spanning tree\n pq = HeapPriorityQueue()\n \n for v in g.vertices():\n make_set(v)\n\n for e in g.edges():\n pq.add(e[2], e)\n\n while not pq.is_empty():\n weight, edge = pq.remove_max()\n u, v, w = edge\n root_of_u = find(u)\n root_of_v = find(v)\n if root_of_u != root_of_v:\n if u not in maximum_spanning_tree.vertices():\n maximum_spanning_tree.insert_vertex(u)\n if v not in maximum_spanning_tree.vertices():\n maximum_spanning_tree.insert_vertex(v)\n maximum_spanning_tree.insert_edge(*edge)\n union(u, v)\n\n path = bfs_find_path(maximum_spanning_tree,src,target)\n edge_on_path = []\n for i in range(len(path)-1):\n edge_on_path.append(g.get_edge(path[i], path[i+1])[2])\n max_bandwidth = min(edge_on_path)\n return path, max_bandwidth\n\ndef bfs_find_path(graph, start, end):\n q = Queue()\n temp_path = [start]\n q.put(temp_path)\n while not q.empty():\n temp_path = q.get()\n last_node = temp_path[len(temp_path) -1]\n if last_node == end:\n return temp_path\n for link_node in graph.neighbors(last_node):\n if link_node not in temp_path:\n new_path = temp_path + [link_node]\n q.put(new_path)","sub_path":"Kruskal.py","file_name":"Kruskal.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"74561304","text":"#!usr/bin/env python\n# coding: utf-8\n\n__author__ = \"Jérôme Kieffer\"\n__license__ = \"MIT\"\n__date__ = \"19/07/2021\"\n__copyright__ = \"2015-2021, ESRF\"\n\nimport logging\nlogger = logging.getLogger(\"utilstest\")\nfrom silx.resources import ExternalResources\ndownloader = ExternalResources(\"freesas\", \"http://www.silx.org/pub/freesas/testdata\", \"FREESAS_TESTDATA\")\n\n\ndef get_datafile(name):\n \"\"\"Provides the full path of a test file,\n downloading it from the internet if needed\n\n :param name: name of the file to get\n :return: full path of the datafile\n \"\"\"\n logger.info(f\"Download file {name}\")\n fullpath = downloader.getfile(name)\n return fullpath\n","sub_path":"freesas/test/utilstests.py","file_name":"utilstests.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"274366578","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# cell_metadata_filter: -all\n# formats: ipynb,md:myst,py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.6.0-dev\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n#\n\n# %%\nimport a301_lib\n#from sat_lib import radiation\nimport sys\nfrom sat_lib.radiation import calc_radiance, planck_invert\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Qt5agg')\n\n# %%\nimport numpy as np\ndomega=2/36000.**2.\nprint('domega: ',domega)\n\nH=10000.\nk=3.e-2\nrmix=6.e-3\ntau=k*rmix*H\nprint(\"tau: \",tau)\nTr=np.exp(-tau)\nprint(\"Tr: \",Tr)\n\nBsfc=calc_radiance(9.e-6,300.)*1.e-6\nBatm=calc_radiance(9.e-6,270.)*1.e-6\nprint('Bsfc, Batm ',Bsfc,Batm)\nTOA=Bsfc*Tr + (1 - Tr)*Batm\nprint('TOA radiance: ',TOA)\nTb=planck_invert(9.e-6,TOA*1.e6)\nprint('Tb: ',Tb)\nflux=TOA*domega*2.\nprint(\"flux: \",flux)\n\ncos35 = np.cos(35*np.pi/180.)\nprint('cos35: ',cos35)\nprint('omega: ',2*np.pi*(1. - cos35))\n\n\n# %%\nfrom sat_lib.radiation import sigma\n\nmicrons=np.linspace(0.1,700,500000)\nmeters=microns*1.e-6\ncms=microns*1.e-4\ninv_cms=1./cms\ninv_microns=1./microns\ninv_meters=1/meters\n\ntemp=280.\nplanck_len=calc_radiance(meters,temp)\n\nfig, ax2 = plt.subplots(1,1,figsize=(10,10))\ntemp=260.\nplanck_len=calc_radiance(meters,temp)\nl0=ax2.plot(microns,np.pi*planck_len*1.e-6,':',lw=4)\ntemp=270.\nplanck_len=calc_radiance(meters,temp)\nl1=ax2.plot(microns,np.pi*planck_len*1.e-6,'-',lw=4)\ntemp=280.\nplanck_len=calc_radiance(meters,temp)\nl2=ax2.plot(microns,np.pi*planck_len*1.e-6,'--',lw=3)\ntemp=290.\nplanck_len=calc_radiance(meters,temp)\nl3=ax2.plot(microns,np.pi*planck_len*1.e-6,'-.',lw=4)\ntemp=300.\nplanck_len=calc_radiance(meters,temp)\nl4=ax2.plot(microns,np.pi*planck_len*1.e-6,':',lw=4)\nax2.set_xlabel(r'wavelength ($\\mu m$)')\nax2.set_ylabel(r'Monochromatic blackbody flux $E_{bb\\lambda}$ ($W\\,m^{-2}\\,\\mu m^{-1}$)')\nax2.set_title(\"Blackbody flux vs. wavelength\")\n# Major ticks every 20, minor ticks every 5\nmajor_ticks = np.arange(0, 31, 5)\nminor_ticks = np.arange(0, 31, 1)\n\nax2.set_xticks(major_ticks)\nax2.set_xticks(minor_ticks, minor=True)\nmajor_ticks = np.arange(0, 36, 5)\nminor_ticks = np.arange(0, 36, 1)\nax2.set_yticks(major_ticks)\nax2.set_yticks(minor_ticks, minor=True)\n\n# And a corresponding grid\nax2.grid(which='both')\n\n# Or if you want different settings for the grids:\nax2.grid(which='minor', alpha=0.5)\nax2.grid(which='major', alpha=0.7)\nax2.grid(color='k', linestyle=':', linewidth=1)\nax2.set_xlim(0,30)\n#ax2.set_ylim()\nlegax=ax2.legend(('260 K','270 K','280 K','290 K','300 K'),loc='upper left')\nax2.figure.savefig('a301_planck.pdf')\nax2.figure.savefig('a301_planck.png')\nfig.tight_layout()\nfig.canvas.draw()\nplt.show()\nprint(f\"sb flux: {sigma*temp**4.}\")\ninteglen=np.sum(np.diff(meters)*planck_len[:-1])*np.pi\nprint(f\"integrated flux: {integlen}\")\nmicrons=np.array([10.,12.])\nmeters=microns*1.e-6\nplanck_len=calc_radiance(meters,temp)\nprint(np.mean(planck_len)*2.e-6)\n\n# %% [markdown]\n# Answer all four questions (note weights). Show all your work, using\n# extra blank pages if needed. Include the attached planck function figure\n# if used for the calculations.\n#\n# - (10) A satellite orbiting at an altitude of 36000 km observes the\n# surface in a thermal channel with a wavelength range of\n# $8\\ \\mu m < \\lambda < 10\\ \\mu m$.\n# \n# - Assuming that the atmosphere has density scale height of\n# $H_\\rho=10$ km and a surface air density of $\\rho_{air}=1$\n# and that the absorber has mass absorption coefficient of\n# $k_\\lambda = 3 \\times 10^{-2}\\ m^2/kg$ at $\\lambda=9\\ \\mu m$\n# and a mixing ratio $6 \\times 10^{-3}$ kg/kg, find the vertical\n# optical thickness $\\tau$ and transmittance of the atmosphere\n# directly beneath the satellite\n\n# %%\n1/15\n\n# %%\nimport math as m\nHrho = 11e3\nrho_air = 1.2\nk_lambda = 0.15\nztop = 20.e3\nrmix = 4.e-4\ndecay = (1 - m.exp(-ztop/Hrho))\ntau = Hrho*rho_air*k_lambda*rmix*decay\nprint(tau)\nprint(m.exp(-tau))\n\n# %% [markdown]\n# \n# - If the surface is black with a temperature of 290 K, and the\n# atmosphere has an average temperature of 270 K, find the\n# \n# - radiance observed by the satellite in at 9 $\\mu m$\n# \n\n# %%\nBsfc=calc_radiance(15.e-6,290.)*1.e-6\nBatm=calc_radiance(15.e-6,270.)*1.e-6\nprint('Bsfc, Batm ',Bsfc,Batm)\nTOA=Bsfc*Tr + (1 - Tr)*Batm\nprint('TOA radiance: ',TOA)\nTb=planck_invert(15.e-6,TOA*1.e6)\nprint('Tb: ',Tb)\nprint('Esfc, Eatm ',m.pi*Bsfc,m.pi*Batm)\nE_TOA=m.pi*(Bsfc*Tr + (1 - Tr)*Batm)\nprint('TOA flux: ',E_TOA)\n\n\n# %% [markdown]\n# \n# - Given a pixel size 4 $km^2$, what is the flux, in , reaching\n# the satellite in this channel?\n# \n\n\n# %%\nmicrons=np.linspace(14.,16.,5000)\nmeters=microns*1.e-6\nplanck_vals=calc_radiance(meters,temp)\ninteglen=np.sum(np.diff(meters)*planck_len[:-1])\narea = 4.\norbit = 36.e3\nfov = area/orbit**2.\nprint(f\"integrated radiance: {integlen}\")\nprint(f\"fov {fov}\")\nprint(f\"flux at satellite {integlen*fov}\")\n\n\n# %% [markdown]\n# Extra space for problem 1\n# \n# 2$ Short answer (6):\n# \n# - (3) A cone has a spreading angle of 35 degrees between its\n# center and its side. What is its subtended solid angle?\n# \n# - (3) Assuming that radiance is independent of the distance $d$\n# between an instrument and a surface, show that the flux from the\n# surface decreases as $1/d^2$\n#\n# - (5) Integrate the Schwartzchild equation\n# ([\\[eq:schwarz\\]](#eq:schwarz)) for constant temperature and show\n# you get ([\\[eq:isothermal\\]](#eq:isothermal))\n#\n# - Pyresample (10)\n# \n# Consider the following code:\n# \n# from pyresample import SwathDefinition, kd_tree, geometry\n# proj_params = get_proj_params(m5_file)\n# swath_def = SwathDefinition(lons_5km, lats_5km)\n# area_def_lr=swath_def.compute_optimal_bb_area(proj_dict=proj_params)\n# area_def_lr.name=\"ir wv retrieval modis 5 km resolution (lr=low resolution)\"\n# area_def_lr.area_id='modis_ir_wv'\n# area_def_lr.job_id = area_def_lr.area_id\n# fill_value=-9999.\n# image_wv_ir = kd_tree.resample_nearest(swath_def, wv_ir_scaled.ravel(),\n# area_def_lr, radius_of_influence=5000, \n# nprocs=2,fill_value=fill_value)\n# image_wv_ir[image_wv_ir < -9000]=np.nan\n# print(f'\\ndump area definition:\\n{area_def_lr}\\n')\n# print((f'\\nx and y pixel dimensions in meters:'\n# f'\\n{area_def_lr.pixel_size_x}\\n{area_def_lr.pixel_size_y}\\n'))\n# \n# In the context of this snippet, explain what the following objects\n# (i.e. their type, what some of their attributes are, etc.) and how\n# they are used to map a satellite image:\n# \n# - proj\\_params\n# \n# - swath\\_def\n# \n# - area\\_def\\_lr\n# \n# - wv\\_ir\\_scaled.ravel()\n# \n# - kd\\_tree.resample\\_nearest\n#\n# Extra space for problem 4\n#\n# ![image](a301_planck.pdf)\n#\n# **Useful Equations:**\n#\n# 2\n#\n# \\[\\begin{aligned}\n# \\label{eq:nu}\n# \\nu &=& c / \\lambda\\\\\n# E &=& h \\nu\\end{aligned}\\]\n#\n# \\[\\label{eq:omega}\n# d \\omega = \\sin \\theta d\\theta d\\phi = -d\\mu d\\phi \\approx \\frac{ A}{r^2}\\]\n#\n# \\[\\label{eq:cos}\n# S = S_0 \\cos(\\theta)\\]\n#\n# \\[\\label{eq:conservation}\n# a_\\lambda + r_\\lambda + t_\\lambda = 1\\]\n#\n# \\[\\label{eq:intensity}\n# L_\\lambda = \\frac{\\Delta E}{\\Delta \\omega \\Delta \\lambda}\\]\n#\n# \\[\\label{eq:flux_int}\n# E = \\int_0^{2 \\pi} \\int_0^{\\pi/2} L \\cos \\theta \\sin \\theta d \\theta d \\phi\\]\n#\n# \\[\\label{planck}\n# B_\\lambda(T) = \\frac{2 h c^2}{\\lambda^5 \\left [ \\exp (h c/(\\lambda k_B T )) -1 \\right ] }\\]\n#\n# \\[\\label{eq:pi}\n# E_{\\lambda\\,BB} = \\pi B_\\lambda\\]\n#\n# \\[\\label{eq:stefan}\n# E^* =\\sigma T^4\\]\n#\n# \\[\\label{eq:taylor}\n# E_\\lambda(T) \\approx E_{\\lambda\\, 0} + \\left .\\frac{dE_\\lambda}{dT} \\right |_{T_0,\\lambda} \\!\\!\\! (T - T_0) + \\ldots\\]\n#\n# \\[\\label{eq:exp}\n# \\exp(x) = 1 + x + \\frac{x^2}{2} + \\frac{x^3}{3!} + \\ldots\\]\n#\n# $~$\n#\n# Beer’s law for extinction: \\[\\begin{aligned}\n# \\label{eq:extinct}\n# \\frac{dL_\\lambda}{L_\\lambda} & = & - \\kappa_{\\lambda\\, s} \\rho_{g} ds - \n# \\kappa_{\\lambda\\,a } \\rho_{g} ds \\nonumber\\\\\n# &=& - \\kappa_{\\lambda e} \\rho_{g} ds = \\kappa_{\\lambda e} \\rho_{g} dz\\end{aligned}\\]\n# (assuming $\\rho_{a}$=$\\rho_{s}$=$\\rho_{g}$).\n#\n# Beer’s law integrated:\n#\n# \\[\\label{eq:binteg}\n# E= E_0 \\exp (- \\tau)\\]\n#\n# $~$\n#\n# Hydrostatic equation:\n#\n# \\[\\label{eq:hydro}\n# dp = -\\rho_{air}\\, g\\, dz\\]\n#\n# $~$\n#\n# Hydrostatic equation integrated:\n#\n# \\[\\label{eq:hydroint}\n# p = p_0 \\exp(-z/H)\\]\n#\n# Equation of state\n#\n# \\[\\label{eq:state}\n# p = R_d \\rho_{air} T\\]\n#\n# $~$\n#\n# vertical optical thickness:\n#\n# \\[\\label{eq:tauThick}\n# d \\tau = \\kappa_\\lambda \\rho_g dz = \\kappa_\\lambda r_{mix} \\rho_{air} dz = \\beta_a dz\\]\n#\n# integrate vertical optical thickness:\n#\n# \\[\\label{eq:tauup}\n# \\tau(z_1, z_2 ) = \\int_{z_1}^{z_{2}} k_\\lambda r_{mix} \\rho_{air}\\, dz^\\prime\\]\n#\n# Transmission function for upwelling radiation\n#\n# \\[\\begin{aligned}\n# \\hat{t} &=& \\exp ( - (\\tau - \\tau^\\prime) ) \\nonumber\\\\\\end{aligned}\\]\n#\n# $~$\n#\n# $~$\n#\n# Schwarzchild’s equation for an absorbing/emitting gas\n#\n# \\[\\label{eq:schwarz}\n# dL = -L\\, d\\tau + B_{\\lambda}(z) d \\tau\\]\n#\n# $~$\n#\n# Radiance an isothermal layer:\n#\n# \\[\\label{eq:isothermal}\n# L_\\uparrow(\\tau_T) = L_0 \\exp( - \\tau_T ) + (1 - \\exp( - \\tau_T)) B_\\lambda(T)\\]\n#\n# Integrated Schwartzchild I:\n#\n# \\[\\label{eq:integI}\n# \\begin{gathered}\n# L_\\lambda = B_\\lambda(T_{skin} ) \\hat{t}_{tot} + \\sum_{j=1}^n e_\\lambda B_\\lambda(T_j) \\hat{t}_{\\lambda,j}\n# \\end{gathered}\\]\n#\n# Integrated Schwartzchild II:\n#\n# \\[\\label{eq:integII}\n# \\begin{gathered}\n# L_\\lambda = B_\\lambda(T_{skin}) \\hat{t}_{\\lambda,tot} + \\sum_{j=1}^n \n# B_\\lambda(T_j) \\Delta \\hat{t}_{\\lambda,j}\n# \\end{gathered}\\]\n#\n# -----\n#\n# $~$\n#\n# Useful constants:\n#\n# $~$\n#\n# $c_{pd}=1004$ ,\n#\n# $\\sigma=5.67 \\times 10^{-8}$\n#\n# $k_b = 1.381 \\times 10^{-23}$\n#\n# $c=3 \\times 10^{8}$\n#\n# $h=6.626 \\times 10^{-34}$\n#\n# $\\pi \\approx 3.14159$\n#\n# $R_d=287 \\un{J\\,kg^{-1}\\,K^{-1}}$\n#\n# Solar radius=$7 \\times 10^8$ m\n#\n# Earth-sun distance =$1.5 \\times 10^{11}$ m\n","sub_path":"notebooks/week8/orig_mid.py","file_name":"orig_mid.py","file_ext":"py","file_size_in_byte":10461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"21853109","text":"class Robot:\n population = 0\n\n def __init__(self, name):\n self.name = name\n print('Initializing {}'.format(self.name))\n\n Robot.population += 1\n\n def die(self):\n print('Dying {}'.format(self.name))\n\n Robot.population -= 1\n\n if Robot.population == 0:\n print('{} was the last Robot'.format(self.name))\n else:\n print('There are still {:d} robots working.'.format(Robot.population))\n\n def say_hi(self):\n print('Hello, My masters call me {}'.format(self.name))\n\n @classmethod\n def how_many(cls):\n print('We have {:d} robots'.format(cls.population))\n\n\nif __name__ == '__main__':\n dr1 = Robot('R1')\n dr2 = Robot('R2')\n\n dr1.say_hi()\n dr2.say_hi()\n\n dr1.die()\n\n Robot.how_many()\n\n dr2.die()\n\n Robot.how_many()\n","sub_path":"python/concepts/OO_concepts/class_variables.py","file_name":"class_variables.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"564465653","text":"# -*-coding:utf-8 -*-\nimport theano\nimport numpy\nfrom theano import tensor as T\nfrom theano.tensor.nnet import conv\n\n\nrng = numpy.random.RandomState(23455)\n\n#以下定义只是为了能执行conv2d操作\ninput = T.tensor4(name = 'input',dtype = 'float32')\nW = theano.shared(value = numpy.asarray(\n rng.uniform(\n low = -1.0,\n high=1.0,\n size=(2,1,1,1)\n ),\n dtype = 'float32') ,name = \"W\")\n\nb = theano.shared(value = numpy.asarray(\n rng.uniform(low = -1 , high=1, size=(2,)),\n dtype = 'float32'),\n name = 'b')\n\nconv_out = conv.conv2d(input, W)\n\nb1 = theano.shared(numpy.arange(3).reshape(1,3),name='b1')\n\nbb = b1.dimshuffle('x',0,'x',1)\nbb_printed = theano.printing.Print('b_1.dimshuffle')(bb)\n\noutput = [T.nnet.sigmoid(conv_out + b.dimshuffle('x',0,'x','x')),bb_printed * 2,bb,b1]\n\nf = theano.function([input] , output)\nimg2 = numpy.arange(100,dtype=\"float32\").reshape(1,1,10,10)\nfiltered_img = f(img2)[3]\nprint(filtered_img)","sub_path":"ZQ/zq.py","file_name":"zq.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"398066411","text":"#!/usr/bin/env python\r\nfrom pygame.locals import *\r\nfrom operator import sub, div\r\nimport collections\r\nimport pygame\r\nimport random\r\n\r\nfrom config import GAME\r\nimport resources\r\nimport objects\r\nimport ai\r\n\r\nclass SnakeGroup(pygame.sprite.Group):\r\n \"\"\"\r\n Eine zus\\xe4tzliche Gruppe f\\xfcr Schlangen, damit beim Zeichnen\r\n der Gruppe auch die Segmente der Schlangen mit gezeichnet werden.\r\n\r\n Ansonsten identisch mit C{pygame.sprite.Group}.\r\n \"\"\"\r\n def draw(self, surface):\r\n \"\"\"Zeichnet alle Schlangen der Gruppe vollst\\xe4ndig.\r\n\r\n @type surface: C{pygame.Surface}\r\n @param surface: Die Oberfl\\xe4che auf welche die Schlangen \"geblitet\"\r\n werden sollen.\r\n \"\"\" \r\n for snake in self:\r\n snake.accessories_under.draw(surface)\r\n self.spritedict[snake] = surface.blit(snake.image, snake.rect)\r\n snake.segments.draw(surface)\r\n snake.accessories_over.draw(surface)\r\n self.lostsprites = []\r\n\r\n\r\nclass Segment(objects.Base):\r\n \"\"\"Ein einzelnes Teil aus dem die Schlangen bestehen.\r\n\r\n @type parent: C{Segment}\r\n @ivar parent: Das \\xfcbergeordnete bzw. vorherige Segment.\r\n\r\n @type segments: C{pygame.sprite.OrderedUpdates}\r\n @ivar segments: Eine Gruppe die alle Segmente der Schlange zusammenfasst.\r\n\r\n @type positions: C{collections.deque>}\r\n @ivar positions: Beinhaltet alle zentrale(center) Positionen der letzten\r\n Bewegungen.\r\n \"\"\" \r\n def __init__(self, parent, image, *groups):\r\n \"\"\"Initialisiert eine neue Instanz von C{Segment}.\r\n\r\n @type parent: C{Segment}\r\n @param parent: Das \\xfcbergeordnete bzw. vorherige Segment.\r\n\r\n @type image: C{pygame.Surface}\r\n @param image: Die Daten f\\xfcr die Bildoberfl\\xe4che.\r\n\r\n @type groups: C{tuple}\r\n @param groups: Die Gruppen welcher das Segment angeh\\xf6ren soll.\r\n \"\"\"\r\n objects.Base.__init__(self, image.copy(), *groups)\r\n self.parent = parent\r\n self.segments = pygame.sprite.OrderedUpdates()\r\n self.positions = collections.deque()\r\n\r\n def update(self):\r\n \"\"\"Aktualisiert die Position des Segmentes.\"\"\"\r\n self.position = self.parent.positions.popleft()\r\n self.positions.append(self.position)\r\n\r\n \r\nclass Snake(Segment):\r\n \"\"\"\r\n Ein Python, geh\\xf6rt zur Familie der Riesenschlangen und ist ein Raubtier,\r\n welches ununterbrochen ans Fressen denkt. Er w\\xe4chst linear zu dem was er\r\n fri\\xdft und erreicht schnell \\xfcberdimensionale Gr\\xf6\\xdfen.\r\n Doch Vorsicht ist geboten, denn er sollte nicht den Weg eines anderen\r\n Pythons kreuzen, denn dieser ist nicht geringer Gefr\\xe4\\xdfig.\r\n\r\n @type name: C{str}\r\n @param name: Der Names des Python.\r\n \r\n @type heading: C{int}\r\n @ivar heading: Die Richtung in welche die Schlange sich bewegt.\r\n\r\n @type immortal: C{bool}\r\n @ivar immortal: Ob die Schlange unsterblich ist.\r\n\r\n @type lifes: C{int}\r\n @ivar lifes: Die Leben der Schlange.\r\n\r\n @type movement: C{dict>}\r\n @ivar movement: Ordnet den Tastenwerten die Geschwindigkeit und Richtung,\r\n in die sich die Schlange beim bet\\xe4tigen der Tasten\r\n bewegen soll.\r\n \r\n @type opposite: C{dict}\r\n @ivar opposite: Ordnet den Tastenwerten die gegengesetzte Richtung zu,\r\n damit sich die Schlange sich nicht selbst umbringt.\r\n\r\n @type up: C{int}\r\n @ivar up: Der Tastenwert, f\\xfcr Oben.\r\n \r\n @type down: C{int}\r\n @ivar down: Der Tastenwert, f\\xfcr Unten.\r\n\r\n @type left: C{int}\r\n @ivar left: Der Tastenwert, f\\xfcr Links.\r\n \r\n @type right: C{int}\r\n @ivar right: Der Tastenwert, f\\xfcr Rechts.\r\n\r\n @type accessories_under: C{pygame.sprite.Group}\r\n @ivar accessories_under: Alle weiteren Sprites die unter der Schlage\r\n \"geblitet\" werden sollen.\r\n\r\n @type accessories_over: C{pygame.sprite.Group}\r\n @ivar accessories_over: Alle weiteren Sprites die \\xfcber der Schlage\r\n \"geblitet\" werden sollen.\r\n \"\"\"\r\n def __init__(self, name, *groups):\r\n \"\"\"Initialisiert eine neue Instanz von C{Snake}.\r\n \r\n @type groups: C{tuple}\r\n @param groups: Die Gruppen welcher die Schlange angeh\\xf6ren soll.\r\n \"\"\"\r\n Segment.__init__(self, None, resources.IMAGE_HEAD.copy(), *groups)\r\n self.__groups = groups\r\n self.name = name\r\n self.keys = K_UP, K_DOWN, K_LEFT, K_RIGHT\r\n self.heading = None\r\n self.immortal = False\r\n self.lifes = 3\r\n self.accessories_under = pygame.sprite.Group()\r\n self.accessories_over = pygame.sprite.Group()\r\n self._entrances = collections.deque()\r\n self._exits = collections.deque()\r\n\r\n def __len__(self):\r\n \"\"\"Gibt die L\\xe4nge der Schlange an.\r\n\r\n @rtype: C{int}\r\n @return: Die Anzahl der Segmente aus der die Schlange besteht.\r\n \"\"\"\r\n return len(self.segments)\r\n \r\n def __iter__(self):\r\n \"\"\"Erm\\xf6glicht das iterieren \\xfcber den Schlangenk\\xf6rper.\r\n \r\n @rtype: C{iterator}\r\n @return: Die einzelnen Segmente der Schlange.\r\n \"\"\"\r\n return iter(self.segments)\r\n \r\n def __getitem__(self, index):\r\n \"\"\"Erm\\xf6glicht das indizieren des Schlangenk\\xf6rpers.\r\n \r\n @rtype: C{Segment}\r\n @return: Ein Segment des Schlangenk\\xf6rpers.\r\n \"\"\"\r\n try:\r\n return list(self)[index]\r\n except IndexError:\r\n return None\r\n \r\n def __repr__(self):\r\n \"\"\"Gibt eine Beschreibung der Snake zur\\xfcck.\r\n \r\n @rtype: C{str}\r\n @return: Objektbeschreibung.\r\n \"\"\"\r\n return \"<{type.__module__}.{type.__class__} name=self.name, \" \\\r\n \"lifes=self.lifes>\"\r\n \r\n @property\r\n def head(self):\r\n \"\"\"Der Kopf der Schlange.\r\n \r\n @rtype: C{Snake}\r\n @return: Das Kopfsegment der Schlange.\r\n \"\"\"\r\n return self\r\n \r\n @property\r\n def tail(self):\r\n \"\"\"Der Schwanz der Schlange.\r\n \r\n @rtype: C{Segment}\r\n @return: Das letzte Segment der Schlange.\r\n \"\"\"\r\n return self[-1] if len(self) > 0 else self\r\n \r\n @property\r\n def size(self):\r\n \"\"\"Die Gr\\xf6\\xdfe des Schlangenkopfes.\r\n \r\n @rtype: C{tuple}\r\n @return: Die Gr\\xf6\\xdfe des Schlangenkopfes. \r\n \"\"\"\r\n return self.rect.size\r\n \r\n @property\r\n def keys(self):\r\n \"\"\"Getter f\\xfcr die Tasten-Steuerung der Schlange.\r\n\r\n @rtype: C{tuple}\r\n @return: Die Integer-Werte der Tasten. (Hoch, Runter, Links, Rechts)\r\n \"\"\"\r\n return self.up, self.down, self.left, self.right\r\n\r\n @keys.setter\r\n def keys(self, new_keys):\r\n \"\"\"Setter f\\xfcr die Tasten-Steuerung der Schlange.\r\n\r\n @type new_keys: C{tuple}\r\n @param new_keys: Die Integer-Werte der Tasten. (Hoch, Runter, Links,\r\n Rechts)\r\n \"\"\" \r\n self.up, self.down, self.left, self.right = new_keys\r\n self.movement = {self.up : (0, -GAME.speed), \r\n self.down : (0, GAME.speed),\r\n self.left : (-GAME.speed, 0),\r\n self.right: ( GAME.speed, 0)}\r\n self.opposite = {self.up : self.down, self.down : self.up,\r\n self.left : self.right, self.right : self.left}\r\n \r\n def add_segment(self):\r\n \"\"\"F\\xfcgt ein Segment hinten an die Schlange an.\"\"\"\r\n seg = self.tail\r\n # Startwerte, damit das Segment bis nach hinten faellt und das neue\r\n # Ende der Schlange bildet.\r\n seg.positions = collections.deque(\r\n seg.position for _ in range(seg.rect.width // GAME.speed))\r\n \r\n segment = Segment(seg, resources.IMAGE_BODYPART)\r\n segment.rect.topleft = objects.OUTSIDE\r\n if self.color is not None:\r\n segment.set_color(self.color)\r\n self.segments.add(segment)\r\n\r\n def add_segments(self, amount):\r\n \"\"\"F\\xfcgt der Schlange mehrere Segmente hinten an.\r\n \r\n @type amount: C{int}\r\n @param amount: Die Anzahl der Segmente,welche angehangen werden sollen.\r\n \"\"\"\r\n for _ in xrange(amount):\r\n self.add_segment()\r\n \r\n def remove_segments(self, slice_):\r\n \"\"\"Entfernt Segmente der Schlange.\r\n \r\n @type slice_: C{slice}\r\n @param slice_: Die St\\xfccke die von der Schlange abgehackt werden \r\n sollen.\r\n \"\"\"\r\n sprites = self[slice_]\r\n for sprite in sprites:\r\n self.segments.remove(sprite)\r\n \r\n def get_positions(self):\r\n \"\"\"Gibt alle Positionen der Schlangenbestandteile von Kopf bis Schwanz\r\n an.\r\n \r\n @rtype: C{list>}\r\n @return: Liste aller Positionen der Schlangensegmente.\r\n \"\"\"\r\n positions = [self.position]\r\n positions.extend(segment.position for segment in self)\r\n return positions\r\n \r\n def _dig_update(self):\r\n \"\"\"L\\xf6cher hinter der Schlange wieder zuschaufeln.\"\"\"\r\n self.immortal = False \r\n if len(self._entrances) > 0 and len(self._exits) > 0:\r\n if pygame.sprite.collide_circle(self._exits[0], self.tail):\r\n self._entrances.popleft().kill()\r\n self._exits.popleft().kill()\r\n \r\n def update(self):\r\n \"\"\"Aktualisiert die Position der Schlange.\r\n\r\n Zu erst wird der Kopf der Schlange bewegt und dessen neue Position\r\n gespeichert. Danach werden die Segmente der Schlange aktualisiert.\r\n Das Bewegungsprinzip der Schlange ist hierbei ein richtiges Nachziehen.\r\n Jedes Segment \\xfcbernimmt die Position seines Vorg\\xe4ngers in\r\n geordneter Reihenfolge. So zieht also der Kopf Segment1 auf seine\r\n vorherige Position, welches wiederum Segment2, welches Segment3 usw.\r\n nach sich zieht.\r\n \"\"\"\r\n self.rect.move_ip(self.movement.get(self.heading, (0, 0)))\r\n self.positions.append(self.position)\r\n self.segments.update()\r\n self._dig_update()\r\n \r\n # Damit die Schlange bei einer zu starken Drehung oder beim ausbuddeln\r\n # nicht stirb.\r\n if len(self) > 1:\r\n if pygame.sprite.collide_circle(self, self[1]):\r\n self.immortal = True \r\n \r\n def move(self, direction):\r\n \"\"\"Gibt das n\\xe4chste Feld auf das sich die Schlange zu bewegen \r\n k\\xf6nnte an.\r\n \r\n @type direction: C{int}\r\n @param direction: Die Richtung in welche die Schlange sich theoretisch\r\n bewegen soll.\r\n \r\n @rtype: C{pygame.Rect}\r\n @return: Das n\\xe4chste Feld des Schlangenkopfes.\r\n \"\"\"\r\n return self.rect.move(self.movement.get(direction, self.size))\r\n\r\n def valid_motion(self, direction):\r\n \"\"\"\\xdcberpr\\xfcft ob die Schlange sich in diese Richtung bewegen kann.\r\n \r\n @type direction: C{int}\r\n @param direction: Die Richtung in welche die Schlange sich bewegen soll.\r\n \r\n @rtype: C{bool}\r\n @return: Ob die Schlange sich in diese Richtung bewegenn kann.\r\n \"\"\"\r\n return direction in self.keys and \\\r\n direction != self.heading != self.opposite.get(direction, 0)\r\n \r\n def get_valid_directions(self):\r\n \"\"\"Gibt alle m\\xf6glichen Richtung an, in welche die Schlange sich \r\n bewegen kann.\r\n \r\n @rtype: C{tuple}\r\n @return: Die Richtungen, in welche die Schlange sich bewegen kann.\r\n \"\"\"\r\n return filter(self.valid_motion, self.keys)\r\n \r\n def wriggle(self, direction=None):\r\n \"\"\"Die Steuerung der Schlange um den Richtungswechsel zu erm\\xf6glichen.\r\n\r\n @type direction: C{int}\r\n @param direction: Der Tastenwert der Richtung in welche die Schlange\r\n sich schl\\xe4ngeln soll.\r\n \r\n @rtype: C{bool}\r\n @return: Ob die Schlange sich wenden konnte.\r\n \"\"\"\r\n if self.valid_motion(direction):\r\n random.choice(resources.SOUNDS_WRIGGLE).play()\r\n self.heading = direction\r\n return True\r\n return False\r\n \r\n def dig(self, to=None):\r\n \"\"\"L\\xe4st die Schlange frei vom Bewegungsmuster an eine andere Stelle\r\n graben. Ein Umplatzierung mit grafischem Effekt.\r\n \r\n @type to: C{tuple}\r\n @param to: Die Position auf welche der Schlangenkopf gesetzt werden \r\n soll.\r\n \"\"\"\r\n self._entrances.append(objects.Pit(self.position, \r\n self.accessories_under))\r\n if to is None:\r\n self.random_spawn()\r\n to = self.position\r\n else:\r\n self.position = to\r\n \r\n self._exits.append(objects.Pit(to, self.accessories_under))\r\n \r\n def eat(self, feed=None):\r\n \"\"\"Erm\\xf6glicht der Schlange das Essen.\r\n\r\n @type feed: C{Feed}\r\n @param feed: Das Futter, welches die Schlange verputzen soll.\r\n \"\"\"\r\n if feed is not None:\r\n random.choice(resources.SOUNDS_EAT).play()\r\n feed.kill()\r\n self.add_segments(feed.repletion)\r\n \r\n def die(self):\r\n \"\"\"Erm\\xf6glicht der Schlange zu sterben.\r\n \r\n Je nach Spielmodifikation gibt es beim Tot der Schlange eine Strafe:\r\n 0. Sofortiges Wiederauferstehen ohne Strafe.\r\n 1. Einen Lebenspunkt verlieren\r\n 2. Ein Segemt f\\xe4llt ab. Sind keine Segmente mehr\r\n da stirbt die Schlange.\r\n 3. Die Schlange verliert die h\\xe4lfte ihrer \r\n L\\xe4nge.\r\n 4. 1 + 2\r\n 5. 1 + 3 \r\n 6. 1 + Die Schlange verliert ihren ganzen K\\xf6rper\r\n \"\"\"\r\n modi = GAME.penalty_at_death\r\n length = len(self)\r\n if not self.immortal:\r\n if modi in (1, 4, 5, 6):\r\n self.lifes -= 1\r\n if modi in (2, 4):\r\n self.remove_segments(slice(-1, length))\r\n if modi in (3, 5):\r\n self.remove_segments(slice(length // 2, length))\r\n if modi == 6:\r\n self.segments.empty()\r\n resources.SOUND_DIE.play()\r\n self.respawn()\r\n \r\n if self.lifes == 0 or (modi in (2, 3, 4, 5, 6) and length == 0):\r\n self.kill()\r\n\r\n # ungetestet\r\n def revive(self):\r\n \"\"\"Bringt die Schlange nach der Entfernung aus dem Spiel wieder \r\n zur\\xfcck.\"\"\"\r\n self.add(self.__groups)\r\n self.lifes = 1\r\n \r\n def respawn(self):\r\n \"\"\"Schlange wird nach ihrem ableben wieder ins Spiel gebracht geholt.\"\"\"\r\n if not GAME.move_after_dead:\r\n self.heading = None \r\n self.immortal = True\r\n self.dig()\r\n\r\n def spawn(self, position):\r\n \"\"\"Setzt die Schlange auf eine bestimmte Position.\r\n \r\n @type position: C{tuple}\r\n @param position: Die Position auf welche die Schlange gesetzt werden \r\n soll.\r\n \r\n @rtype: C{bool}\r\n @return: Ob die Schlange positioniert werden konnte.\r\n \"\"\" \r\n if Segment.spawn(self, position):\r\n self.position = ai.align(self.position)\r\n return True\r\n return False\r\n \r\n def random_spawn(self, area=None):\r\n \"\"\"L\\xe4\\xdft die Schlange auf irgendeinem Punkt innerhalb der\r\n angegebenen Fl\\xe4che erscheinen.\r\n \r\n @type area: C{pygame.Rect}\r\n @param area: Die F\\xe4che in welcher die Schlange positioniert werden\r\n darf.\r\n \r\n @rtype: C{bool}\r\n @return: Ob die Schlange positioniert werden konnte. \r\n \"\"\"\r\n if Segment.random_spawn(self, area):\r\n self.position = ai.align(self.position)\r\n return True\r\n return False\r\n \r\n\r\nclass NonPlayerSnake(Snake):\r\n \"\"\"Ein KI-Spieler-Schlange.\r\n \r\n @type destination: C{tuple}\r\n @ivar destination: Das aktuelle Ziel der Schlange.\r\n \r\n @type path: C{list>}\r\n @ivar path: Der aktuelle Weg, den die KI noch bis zu ihrem Ziel hat.\r\n \"\"\"\r\n def __init__(self, name, *groups):\r\n Snake.__init__(self, name, *groups)\r\n self.keys = 1, 2, 3, 4\r\n self.destination = None\r\n self.path = []\r\n self._position = objects.OUTSIDE\r\n self._feed = None\r\n \r\n def has_order(self):\r\n \"\"\"Ob die Schlange gerade was tut.\r\n \r\n @rtype: C{bool}\r\n @return: Ob die Schlange einen Auftrag hat.\r\n \"\"\"\r\n return self.destination is not None\r\n \r\n def update(self): \r\n \"\"\"Aktualisiert die Position der Schlange.\r\n \r\n Hierbei wird gepr\\xfcft ob die Schlange in der N\\xe4he ihres Pfades oder\r\n Ziels ist. Dem entsprechend bewegt sie sich in dessen Richtung.\r\n \"\"\"\r\n position = self.position\r\n if self.has_order():\r\n if ai.distance(position, self.destination) <= min(ai.GRID_SIZE):\r\n self.destination = None\r\n #self.heading = None\r\n else: \r\n if ai.distance(position, self._position) <= GAME.speed - 1:\r\n if len(self.path) > 0:\r\n self._position = self.path.pop()\r\n self.position = ai.align(position)\r\n \r\n self.wriggle(self.direction_to(self._position))\r\n \r\n Snake.update(self)\r\n \r\n def direction_to(self, position):\r\n \"\"\"Gibt die ben\\xf6tigte der Richtung der Schlange an, um eine bestimmte\r\n Position zu erreichen.\r\n \r\n @type position: C{tuple}\r\n @param position: Die Position zu welcher die Schlange kriechen soll.\r\n \r\n @rtype: C{int}\r\n @return: Die Richtung, in welche die Schlange kriechen muss um den Punkt \r\n zu erreichen.\r\n \"\"\"\r\n x, y = map(sub, ai.align(self.position), position)\r\n if x > 0: return self.left\r\n elif x < 0: return self.right\r\n elif y > 0: return self.up\r\n elif y < 0: return self.down\r\n \r\n def move_to(self, destination, area, collision_layer):\r\n \"\"\"Ermittelt den k\\xfcrzesten der Schlange zu einem bestimmten Ziel,\r\n innerhalb einer Fl\\xe4che unter Ber\\xfccksichtigung anderer Objekte.\r\n \r\n @type destination: C{tuple}\r\n @param destination: Das Ziel, zu dem die Schlange kriechen soll.\r\n \r\n @type area: C{pygame.Rect}\r\n @param area: Die Fl\\xe4che in welcher die Schlange kriechen darf.\r\n \r\n @type collision_layer: C{list>}\r\n @param collision_layer: Alle Positionen welche f\\xfcr die Schlange tabu\r\n sind.\r\n \r\n @rtype: C{int}\r\n @return: Wie lang der ermittelte Pfad ist.\r\n \"\"\"\r\n self.path = ai.find_path(self.position, destination, area, \r\n collision_layer)\r\n if len(self.path) > 0:\r\n self.destination = destination\r\n self._position = self.path.pop()\r\n \r\n return len(self.path)\r\n \r\n def find_nearst(self, group): \r\n \"\"\"Findet ein Objekt aus einer bestimmten Gruppe, welches per \r\n euklidische Distanz am n\\xe4chsten liegt.\r\n \r\n TODO: K\\xfcrzesten Weg innerhalb der Distanz bestimmen.\r\n \r\n @type group: C{pygame.sprite.Group}\r\n @param group: Die Gruppe in welcher das Objekt gesucht werden soll.\r\n \r\n @rtype: C{pygame.sprite.Sprite} \r\n @return: Das Objekt welches gefunden wurde.\r\n \"\"\" \r\n distances = []\r\n for sprite in group:\r\n distance = ai.distance(self.position, sprite.position)\r\n if distance <= GAME.ai_detection_radius:\r\n distances.append((distance, sprite))\r\n \r\n return min(distances)[1] if len(distances) > 0 else None\r\n \r\n def respawn(self):\r\n \"\"\"Schlange wird nach ihrem ableben wieder ins Spiel gebracht geholt.\r\n Dabei wird das Ziel der Schlange entfernt.\r\n \"\"\"\r\n Snake.respawn(self)\r\n self.path = []\r\n self.destination = None\r\n self._feed = None\r\n \r\n def hunt(self, foodstuff, area, collision_layer):\r\n \"\"\"Schickt die Schlange auf jagt.\r\n \r\n @type foodstuff: C{objects.Feed}\r\n @param foodstuff: Die Gruppe in welcher sich das Futter befindet.\r\n \r\n @type area: C{pygame.Rect}\r\n @param area: Die Fl\\xe4che in welcher die Schlange jagen darf.\r\n \r\n @type collision_layer: C{list>}\r\n @param collision_layer: Alle Positionen welche f\\xfcr die Schlange tabu\r\n sind.\r\n \"\"\" \r\n if self._feed is None or self._feed not in foodstuff:\r\n self._feed = self.find_nearst(foodstuff)\r\n \r\n if self._feed is not None:\r\n if not self.move_to(self._feed.position, area, collision_layer):\r\n self._feed = None\r\n \r\n \r\n ","sub_path":"source/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":21761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"448879647","text":"def readGenome(filename):\r\n genome = ''\r\n with open(filename, 'r') as f:\r\n for line in f:\r\n # ignore header line with genome information\r\n if not line[0] == '>':\r\n genome += line.rstrip()\r\n return genome\r\ngenome = readGenome('lambda_virus.fa')\r\nprint(genome[:100])","sub_path":"read_genome.py","file_name":"read_genome.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"321413055","text":"\"\"\"noncollege URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import re_path\n\nfrom noncollege.composites.factories import (\n group_view,\n courses_view,\n materials_create_view,\n materials_manage_view,\n wardens_delete_view,\n wardens_create_view,\n homeworks_create_view,\n homeworks_manage_view,\n course_view,\n homework_submission_view,\n)\nfrom noncollege.users.factories import (\n user_registration_view,\n user_authentication_view,\n users_view,\n user_view,\n user_password_view,\n)\nfrom noncollege.views import ViewWrapper\n\nurlpatterns = [\n re_path(r'^admin/', admin.site.urls),\n re_path(r'^course/$', ViewWrapper.as_view(view_function=courses_view), name='view-courses'),\n re_path(r'^course/(?P[0-9]+)/$', ViewWrapper.as_view(view_function=course_view), name='view-course'),\n re_path(\n r'^course/(?P[0-9]+)/materials/$',\n ViewWrapper.as_view(view_function=materials_create_view),\n name='create-materials',\n ),\n re_path(\n r'^course/(?P[0-9]+)/materials/(?P[0-9]+)/$',\n ViewWrapper.as_view(view_function=materials_manage_view),\n name='manage-materials',\n ),\n re_path(\n r'^course/(?P[0-9]+)/wardens/$',\n ViewWrapper.as_view(view_function=wardens_create_view),\n name='create-wardens',\n ),\n re_path(\n r'^course/(?P[0-9]+)/wardens/(?P[0-9]+)/$',\n ViewWrapper.as_view(view_function=wardens_delete_view),\n name='delete-wardens',\n ),\n re_path(\n r'^course/(?P[0-9]+)/homeworks/$',\n ViewWrapper.as_view(view_function=homeworks_create_view),\n name='create-homeworks',\n ),\n re_path(\n r'^course/(?P[0-9]+)/homeworks/(?P[0-9]+)/$',\n ViewWrapper.as_view(view_function=homeworks_manage_view),\n name='manage-homeworks',\n ),\n re_path(r'^group/$', ViewWrapper.as_view(view_function=group_view), name='view-group'),\n re_path(\n r'^homeworks/(?P[0-9]+)/(?P[0-9]+)/',\n ViewWrapper.as_view(view_function=homework_submission_view),\n name='homework-submission',\n ),\n re_path(r'^user/$', ViewWrapper.as_view(view_function=user_view), name='view-user'),\n re_path(r'^user/(?P[0-9]+)/$', ViewWrapper.as_view(view_function=users_view), name='view-users'),\n re_path(r'^user/password/$', ViewWrapper.as_view(view_function=user_password_view), name='change-user-password'),\n re_path(r'^user/register/$', ViewWrapper.as_view(view_function=user_registration_view), name='register-user'),\n re_path(\n r'^user/authenticate/$', ViewWrapper.as_view(view_function=user_authentication_view), name='authenticate-user'\n ),\n]\n","sub_path":"noncollege/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"329907976","text":"# -*- coding:utf-8 -*-\n__author__ = 'DreamCathcer'\nfrom Service.MapService.BaiduMap.APIService import BaiduMapAPIService\nfrom DAO.BaiduMap.BaiduMapDAO import BaiduMapDAO\n\n\nclass BaiduMapSnatcherService(object):\n def __init__(self):\n self.baiduMapDAO = BaiduMapDAO()\n self.baiduAPIService = BaiduMapAPIService(\"DW2CwL3B3271CiVyw7GdBsfR\")\n\n def getPoi(self,lng0,lat0,lng1,lat1,query):\n # 使用矩形范围初始栈\n queue = [[lng0,lat0,lng1,lat1]]\n while len(queue)!=0:\n # 取出一个查询范围\n range = queue.pop()\n # 根据范围进行查询\n data = self.baiduAPIService.placeSearch(query=query,bounds=\"%lf,%lf,%lf,%lf\"%(range[1],range[0],range[3],range[2]))\n if data.has_key('results'):\n # 如果范围的poi等于20,就切割该范围,并将切割后的子范围置入栈中\n if len(data['results'])==20:\n splitX = (range[0]+range[2])/2\n splitY = (range[1]+range[3])/2\n if (range[2]-range[0])<0.001 or (range[3]-range[1])<0.001:\n continue\n queue.append([range[0],splitY,splitX,range[3]])\n queue.append([splitX,splitY,range[2],range[3]])\n queue.append([range[0],range[1],splitX,splitY])\n queue.append([splitX,range[1],range[2],splitY])\n continue\n # 如果查询结果小于20则存储\n else:\n self.baiduMapDAO.savePOIData(data)\n","sub_path":"Service/MapService/BaiduMap/SnatcherService.py","file_name":"SnatcherService.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"157776447","text":"class CleanText:\n def clean_text(self, text_content):\n clean_text_content = text_content.strip().replace('\\n', ' ').replace('\\t', ' ').replace('\\r', '')\n print(text_content)\n print(clean_text_content)\n return clean_text_content\n def get_sentence_count(self, text_count):\n dot_count = text_count.count('. ')\n semicolon_count = text_count.count('; ')\n question_mark_count = text_count.count('? ')\n exclamation_count = text_count.count('! ')\n sentence_count = dot_count + question_mark_count + exclamation_count + semicolon_count\n print(sentence_count)\n return sentence_count\n\n\nif __name__ == '__main__':\n a = '''\n In this work we propose a deep convolutional neural network that exploits from character- to sentencelevel\n information to perform sentiment analysis of short texts. The proposed network, named Character\n to Sentence Convolutional Neural Network (CharSCNN), uses two convolutional layers to extract relevant\n features from words and sentences of any size. The proposed network can easily explore the richness\n of word embeddings produced by unsupervised pre-training (Mikolov et al., 2013). We perform experiments\n that show the effectiveness of CharSCNN for sentiment analysis of texts from two domains: movie\n review sentences; and Twitter messages (tweets). CharSCNN achieves state-of-the-art results for the two\n domains. Additionally, in our experiments we provide information about the usefulness of unsupervised\n pre-training; the contribution of character-level features; and the effectiveness of sentence-level features\n to detect negation.'''\n c = CleanText()\n text = c.clean_text(a)\n count = c.get_sentence_count(text)","sub_path":"translate_tools/format_text.py","file_name":"format_text.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"376997332","text":"from django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom ekyam.models import Contact\nfrom ekyam.validators import contactValidator\n\n\ndef index(request):\n\n if request.method == 'GET':\n return render(request, 'ekyam/index.html')\n\n elif request.method == 'POST':\n data = contactValidator(request.POST)\n if data['valid']:\n Contact.objects.create(name=data['name'], email=data['email'], phone=data['phone'], message=data['message'])\n messages.add_message(request, messages.INFO, 'We got it!')\n else:\n messages.add_message(request, messages.WARNING, data['error'])\n return redirect('ekyam:index')\n\ndef contactData(request):\n\n if request.method == 'GET':\n if request.user.is_staff:\n print(request.user)\n context = {'contacts': Contact.objects.all()}\n return render(request, 'ekyam/contact-data.html', context)\n else:\n return render(request, 'ekyam/admin-form.html')\n\n if request.method == \"POST\":\n user = authenticate(username=request.POST['username'], password=request.POST['password'])\n if user:\n login(request, user)\n return redirect('ekyam:contact')\n else:\n return HttpResponse('Invalid Credentials.')\n\ndef signout(request):\n logout(request)\n return redirect('ekyam:index')\n","sub_path":"ekyam/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"23910508","text":"from lab3.geometry import Point, Area, Node\n\n\nclass node_index:\n def __init__(self):\n self._idx = 0\n\n def get_id(self):\n ret = str(self._idx)\n self._idx = self._idx + 1\n return ret\n\n\nclass Lab3:\n def __init__(self, path):\n self.points = []\n self.area = None\n self.__create_points_from_file(path)\n self.indexer = node_index()\n self.nodes_map = {}\n print(\"Added number of points: \", len(self.points))\n for pt in self.points:\n print(\"x: \", pt.x, \", y: \", pt.y)\n print(\"\")\n print(\"Area (min_x, min_y, max_x, max_y): \", self.area.min_x, \", \", self.area.min_y, \", \", self.area.max_x, \", \", self.area.max_y)\n print(\"------------- START -------------\")\n print(\"[1] Sort points by X, and by Y.\")\n sort_x = sorted(sorted(self.points, key=lambda pt: pt.y), key=lambda pt: pt.x)\n sort_y = sorted(sorted(self.points, key=lambda pt: pt.x), key=lambda pt: pt.y)\n print(\"[2] Build tree\")\n self.tree = self.build_tree(sort_x, sort_y, 0)\n print(\"[3] Search for nodes in given area.\")\n self.points_in_area = self.search_in_tree()\n print(\"Points in area (count: \" + str(len(self.points_in_area)) + \").\")\n for pt in self.points_in_area:\n print(\"x: \", pt.x, \", y: \", pt.y)\n print(\"------------- END -------------\")\n self.dump()\n pass\n\n def search_in_tree(self):\n current_area = Area(\n min_x=-float(\"inf\"),\n min_y=-float(\"inf\"),\n max_x=float(\"inf\"),\n max_y=float(\"inf\")\n )\n ret = []\n self.__reccurent_search(self.tree, current_area, ret)\n return ret\n\n def __reccurent_search(self, node, current_area, ret):\n # warunki wychodzace z rekurencji\n if node.split_axis == \"\":\n print(node.id)\n if node.point.x <= current_area.max_x and node.point.x >= current_area.min_x \\\n and node.point.y <= current_area.max_y and node.point.y >= current_area.min_y:\n ret.append(node.point)\n return\n elif node.split_axis == \"x\":\n if node.split_value < current_area.min_x or \\\n node.split_value > current_area.max_x:\n return\n else:\n if node.split_value < current_area.min_y or \\\n node.split_value > current_area.max_y:\n return\n if node.split_axis == \"x\":\n if self.area.max_x <= node.split_value:\n current_area.max_x = node.split_value\n if self.area.min_x >= node.split_value:\n current_area.min_x = node.split_value\n if node.split_axis == \"y\":\n if self.area.max_y <= node.split_value:\n current_area.max_y = node.split_value\n if self.area.min_y >= node.split_value:\n current_area.min_y = node.split_value\n\n\n self.__reccurent_search(node.left, current_area, ret)\n self.__reccurent_search(node.right, current_area, ret)\n\n def __calc_mediana(self, points, axis):\n size = len(points)\n if size % 2 != 0:\n if axis == \"x\":\n idx = int(size/2)\n return points[idx].x\n else:\n idx = int(size/2)\n return points[idx].y\n else:\n n_1_index = int(size/2)\n n_0_index = int(size/2)-1\n n_1 = points[n_1_index]\n n_0 = points[n_0_index]\n if axis == \"x\":\n return (n_1.x + n_0.x)/2\n else:\n return (n_1.y + n_0.y)/2\n\n def build_tree(self, sort_x, sort_y, d):\n tree = Node()\n tree.id = self.indexer.get_id()\n self.nodes_map[tree.id] = tree\n size = len(sort_x)\n #jeden punkt w puli punktow\n if size == 1:\n tree.point = sort_x[0] # the only point\n return tree\n half_size = int(size/2)\n #parzyste d\n if d % 2 == 0:\n d = d + 1\n tree.split_axis = \"x\"\n tree.split_value = self.__calc_mediana(sort_x, \"x\")\n s1_x = []\n s1_y = []\n s2_x = []\n s2_y = []\n\n for pt in sort_x:\n if pt.x <= tree.split_value:\n s1_x.append(pt)\n else:\n s2_x.append(pt)\n\n if len(s1_x) != 0 and len(s2_x) == 0:\n for i in range(0, int(len(s1_x) / 2)):\n s2_x.append(s1_x[-i-1])\n del s1_x[-i-1]\n\n for pt in sort_y:\n if pt.x <= s1_x[-1].x:\n s1_y.append(pt)\n else:\n s2_y.append(pt)\n\n if len(s1_y) != 0 and len(s2_y) == 0:\n for i in range(0, int(len(s1_y) / 2)):\n s2_y.append(s1_y[-i-1])\n del s1_y[-i-1]\n\n else:\n d = d + 1\n tree.split_axis = \"y\"\n tree.split_value = self.__calc_mediana(sort_y, \"y\")\n s1_x = []\n s2_x = []\n s1_y = []\n s2_y = []\n\n for pt in sort_y:\n if pt.y <= tree.split_value:\n s1_y.append(pt)\n else:\n s2_y.append(pt)\n\n if len(s1_y) != 0 and len(s2_y) == 0:\n for i in range(0, int(len(s1_y) / 2)):\n s2_y.append(s1_y[-i-1])\n del s1_y[-i-1]\n\n for pt in sort_x:\n if pt.y <= s1_y[-1].y:\n s1_x.append(pt)\n else:\n s2_x.append(pt)\n\n if len(s1_x) != 0 and len(s2_x) == 0:\n for i in range(0, int(len(s1_x) / 2)):\n s2_x.append(s1_x[-i-1])\n del s1_x[-i-1]\n\n tree.left = self.build_tree(s1_x, s1_y, d)\n tree.right = self.build_tree(s2_x, s2_y, d)\n return tree\n\n def __create_points_from_file(self, path_to_file):\n points = []\n with open(path_to_file, \"r\") as f:\n for line in f:\n line = line.strip('\\n')\n line = line.replace(',', '')\n floats = [float(value) for value in line.split()]\n if len(floats) != 2:\n if len(floats) != 4:\n raise Exception(\"Wrong line (not 2 values): \" + line)\n else:\n self.area = Area(\n min_x=floats[0],\n min_y=floats[1],\n max_x=floats[2],\n max_y=floats[3]\n )\n continue\n pt = Point(floats[0], floats[1])\n if pt in points:\n raise Exception(\"Error, point with cooridantes x: \", pt.x, \", y:\", pt.y, \"already exists!\")\n points.append(pt)\n self.points = points\n\n def dump(self):\n g_str = \"digraph G { \\n\"\n for node_id, node in self.nodes_map.items():\n g_str += node_id + \" \"\n g_str += \"[label=\\\"\" + node_id + \"\\\\n\"\n if node.split_axis != \"\":\n g_str += \"axis [\" + node.split_axis + \"]: \" + str(node.split_value)\n else:\n g_str += \"Leaf.\\\\n x: \" + str(node.point.x) + \", y: \" + str(node.point.y)\n g_str += \"\\\"]\\n\"\n if node.left != None:\n g_str += node_id + \" -> \" + node.left.id + \"\\n\"\n if node.right != None:\n g_str += node_id + \" -> \" + node.right.id + \"\\n\"\n g_str += \"}\"\n open('dump.graph', 'w').close()\n with open('dump.graph', 'w') as f:\n f.write(g_str)\n\n","sub_path":"lab3/functionality.py","file_name":"functionality.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"140893677","text":"\"\"\"\nGiven a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).\n\nFor example:\nGiven binary tree [3,9,20,null,null,15,7],\n 3\n / \\\n 9 20\n / \\\n 15 7\nreturn its bottom-up level order traversal as:\n[\n [15,7],\n [9,20],\n [3]\n]\n\"\"\"\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\ndef level_order_top_to_bottom(root):\n \"\"\"Runtime: 40 ms, faster than 99.36% of Python3 online submissions for Binary Tree Level Order\n Traversal II.\n But CAN YOU DO THIS PROBLEM WITH BOTTOM UP APPROACH without using [::] ??????\n\"\"\"\n level = 0\n arr = []\n return foo(root, level, arr)\n\n\ndef foo(root, level, arr):\n if root == None:\n return\n if level == 0 or level >= len(arr):\n arr.append([root.val])\n elif level < len(arr):\n arr[level].append(root.val)\n\n foo(root.left, level + 1, arr)\n foo(root.right, level + 1, arr)\n return arr[::-1]\n\n\nroot = TreeNode(3)\nroot.left = TreeNode(9)\nroot.right = TreeNode(20)\nroot.right.left = TreeNode(15)\nroot.right.right = TreeNode(7)\nprint(level_order_top_to_bottom(root))\n","sub_path":"8_training/bottom_up_tree.py","file_name":"bottom_up_tree.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"113226141","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import (\n absolute_import, division, print_function, unicode_literals\n)\n\nimport os\nimport sys\n\nfrom blockchain_rpc import Peer\nfrom blockchain_rpc.node_full import NodeFull\nfrom utils import dict_to_namedtuple, Verbosity\nfrom utils.console import Console\n\nDNS_SEED_HOST = \"localhost\"\nDNS_SEED_PORT = os.getenv(\"DNS_SEED_PORT\") or 54152\n\n\ndef main():\n host_port = sys.argv[1]\n host, port = host_port.split(\":\")\n host = host or \"localhost\"\n port = int(port) or 5000\n\n config = dict_to_namedtuple({\n \"host\": host,\n \"port\": port,\n \"mining\": False,\n \"gen_transactions\": True,\n \"known_peers\": [\n Peer(host=DNS_SEED_HOST, port=DNS_SEED_PORT)\n ],\n \"peer_discovery_interval\": 5,\n \"peer_sharing_interval\": 5,\n \"transaction_discovery_interval\": 5,\n \"transaction_sharing_interval\": 5,\n \"block_discovery_interval\": 5,\n \"block_sharing_interval\": 5,\n \"max_workers\": 3,\n \"key_path\": \"../.data/{:}_{:}/ecdsa_secp256k1.pem\".format(host, port)\n })\n\n # Console.verbosity = Verbosity.debug\n\n node = NodeFull(config)\n node.listen()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"partial_node/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"530489965","text":"# Linear Model : OK\n# MLP (1, 1) : OK\n\nfrom ctypes import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n\npathDLL = \"C:/Users/nico_/Documents/GitHub/ProjetAnnuel3IBD/projet/MLAlgorithms/ML_Library/x64/Release/ML_Library.dll\"\n#pathDLL = \"C:/Users/WT57/Documents/ProjetAnnuel3IBD-master/projet/MLAlgorithms/ML_Library/Release/ML_Library.dll\"\n#pathDLL = \"D:/CloudStation/Cours/3IBD/projetAnnuel/projet/MLAlgorithms/ML_Library/x64/Release/ML_Library.dll\"\n\nmyDll = CDLL(pathDLL)\n\n# Points Data\nX = [ 1, 2 ]\nY = [ 2, 3 ]\nXnp = np.array([ [1], [2] ])\nYnp = np.array([ 2, 3])\n\n# Parameters\ngamma = 0.5\nc_double_p = POINTER(c_double)\n\n# Load Matrix X\nmyDll.loadTestCase.argtypes = [ POINTER(ARRAY(c_double, len(X))), c_uint, c_uint, c_uint ]\nmyDll.loadTestCase.restype = c_void_p\npMatrixX = myDll.loadTestCase((c_double * len(X))(*X), Xnp.shape[0], Xnp.shape[1], 1)\n\n# Load Matrix Y\nmyDll.loadTestCase.argtypes = [ POINTER(ARRAY(c_double, len(Y))), c_uint, c_uint, c_uint ]\npMatrixY = myDll.loadTestCase((c_double * len(Y))(*Y), Ynp.shape[0], 1, 0)\n\n# Create & Allocate RBF Model\nmyDll.createRBFModel.argtypes = [ c_uint ]\nmyDll.createRBFModel.restype = c_void_p\npArrayWeight = myDll.createRBFModel(Xnp.shape[1])\n\n# Fit RBF with regression version\nmyDll.fitRBFRegression.argtypes = [ c_void_p, c_void_p, c_void_p, c_double ]\t\t\t\t\t\t\t\nerror = myDll.fitRBFRegression( pArrayWeight, pMatrixX, pMatrixY, gamma)\n\n# Prototyping the method Dataset to Vector ( double * => vectorXd)\nmyDll.datasetToVector.argtypes = [ c_double_p, c_uint, c_uint ]\nmyDll.datasetToVector.restype = c_void_p\n\n# Prototyping the method predict RBF\nmyDll.predictRBFRegression.argtypes = [ c_void_p, c_void_p]\nmyDll.predictRBFRegression.restype = c_double\n\n# Predict points to test if Model is working \nX1 = np.linspace(0, 4, 60)\nfor x1 in X1:\n\tpredictX = np.array([x1])\n\tarr_tmp = (c_double * 1)(*predictX)\n\tdatasetTmp = myDll.datasetToVector(arr_tmp, len(predictX), 1)\n\tvalue = myDll.predictRBFRegression(pArrayWeight, datasetTmp) \n\tplt.scatter(x1, value, color='#bbdefb')\n\nplt.scatter(X, Y, color='red')\nplt.show()\nplt.clf()\n\n# # delete / free PMC Model\n# myDll.deletePMCModel.argtypes = [ c_void_p ]\n# myDll.deletePMCModel( pArrayWeight )\n \n\n\n","sub_path":"projet/python/testCase/RBF/Regression/linearSimple2D.py","file_name":"linearSimple2D.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"484897553","text":"\"\"\"\nMax and Min in a Unsorted Array\n\nIn this problem, we will look for smallest and largest integer from a list of unsorted integers.\nThe code should run in O(n) time. Do not use Python's inbuilt functions to find min and max.\n\nBonus Challenge: Is it possible to find the max and min in a single traversal?\n\nSorting usually requires O(n log n) time Can you come up with a O(n) algorithm (i.e., linear time)?\n\"\"\"\nimport random\n\n\ndef get_min_max(ints):\n if len(ints) == 0:\n return None, None\n elif len(ints) == 1:\n return ints[0], ints[0]\n else:\n if ints[0] > ints[1]:\n maximum = ints[0]\n minimum = ints[1]\n else:\n maximum = ints[1]\n minimum = ints[0]\n\n for i in range(2, len(ints)):\n if ints[i] > maximum:\n maximum = ints[i]\n if ints[i] < minimum:\n minimum = ints[i]\n\n return minimum, maximum\n\n\nl = [i for i in range(0, 10)] # a list containing 0 - 9\nrandom.shuffle(l)\nl1 = [100, 23, -100, 32, 1000, 99, 999, 232]\n\nprint(get_min_max(l))\n# expected (0, 9)\nprint(get_min_max(l1))\n# expected (-100, 1000)\nprint(get_min_max([]))\n# expected (None, None)\nprint(get_min_max([1]))\n# expected (1, 1)\n","sub_path":"chapter_3/exam/problem_6.py","file_name":"problem_6.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"144084454","text":"import sys\nfrom sys import stdin\nimport csv\nimport collections\nimport socket\nimport re\n\n\ndef readInput(data):\n\n data_list = []\n\n for i in data:\n data_list.append(i)\n\n frames = []\n\n for i in data_list:\n frame = i.split(\",\")\n frames.append(frame)\n\n attack_type(frames)\n\n\ndef attack_type(frames):\n\n protocol_list = []\n\n for p in frames:\n protocol_list.append(p[4])\n\n protocol_count = collections.Counter(protocol_list)\n items = sorted(protocol_count.items(), key=lambda item: (-item[1]))\n protocol = items[0][0]\n\n if protocol == \"TCP\":\n tcp_attack(frames)\n\n elif protocol == \"UDP\":\n udp_attack(frames)\n\n elif protocol == \"HTTP\":\n http_attack(frames)\n\n elif protocol == \"ICMP\":\n icmp_attack(frames)\n\n else:\n print(\"None of the above\")\n\n\ndef tcp_attack(frames):\n\n flags = []\n\n for f in frames:\n flags.append(f[6])\n\n msg = []\n\n for j in flags:\n m = re.search(r\"\\[(\\w+)\\]\", j).group(1)\n msg.append(m)\n\n counter = collections.Counter(msg)\n items = sorted(counter.items(), key=lambda item: (-item[1]))\n\n types = []\n for i in items:\n types.append(i[0])\n\n # SYN flood - multiple hosts send SYN requests, and then never follows up with an ACK\n if (types[0] == \"SYN\") and (\"ACK\" not in types):\n tcp_frequency(frames)\n print(\"SYN Flood\")\n\n\ndef udp_attack(frames):\n flags = []\n\n for f in frames:\n flags.append(f[4])\n\n counter = collections.Counter(flags)\n items = sorted(counter.items(), key=lambda item: (-item[1]))\n\n types = []\n for i in items:\n types.append(i[0])\n\n # UDP flood - single host sends IP packets containing UDP datagrams to random ports on target.\n if types[0] == \"UDP\":\n udp_frequency(frames)\n print(\"UDP Flood\")\n\n\ndef icmp_attack(frames):\n flags = []\n lengths = []\n\n for f in frames:\n flags.append(f[6])\n lengths.append(f[5])\n\n count_length = collections.Counter(lengths)\n length_items = sorted(count_length.items(), key=lambda item: (-item[1]))\n\n # Ping of Death - Increase the size of ping packet when sending to cause buffer overflow when put together on target\n if int(length_items[0][0]) > 84:\n icmp_frequency(frames)\n print(\"Ping of Death\")\n\n else:\n msg = []\n\n for j in flags:\n m = re.search(r\"\\[(\\w+)\\]\", j).group(1)\n msg.append(m)\n\n counter = collections.Counter(msg)\n items = sorted(counter.items(), key=lambda item: (-item[1]))\n\n types = []\n for i in items:\n types.append(i[0])\n\n # ICMP flood - When the attacker attempts to overwhelm a target with ICMP echo-request packets\n if types[0] == \"ECHO\":\n icmp_frequency(frames)\n print(\"ICMP Flood\")\n\n\ndef http_attack(frames):\n flags = []\n\n for f in frames:\n flags.append(f[6])\n\n msg = []\n\n for j in flags:\n m = re.search(r\"\\[(\\w+)\\]\", j).group(1)\n msg.append(m)\n\n counter = collections.Counter(msg)\n items = sorted(counter.items(), key=lambda item: (-item[1]))\n\n types = []\n for i in items:\n types.append(i[0])\n\n # HTTP flood - When the attacker attempts to overwhelm a target with HTTP GET or POST requests\n if (types[0] == \"GET\") or (types[0] == \"POST\"):\n http_frequency(frames)\n print(\"ICMP Flood\")\n\n\ndef http_frequency(frames):\n addresses = []\n\n for i in frames:\n if i[4] == \"HTTP\":\n addresses.append(i[2])\n\n counter = collections.Counter(addresses)\n items = sorted(\n counter.items(), key=lambda item: (item[1], socket.inet_aton(item[0]))\n )\n\n results = []\n for i in items:\n results.append(i[0])\n\n top = results[-5:]\n top.reverse()\n for i in top:\n print(i)\n\n\ndef icmp_frequency(frames):\n addresses = []\n\n for i in frames:\n if i[4] == \"ICMP\":\n addresses.append(i[2])\n\n counter = collections.Counter(addresses)\n items = sorted(\n counter.items(), key=lambda item: (item[1], socket.inet_aton(item[0]))\n )\n\n results = []\n for i in items:\n results.append(i[0])\n\n top = results[-5:]\n top.reverse()\n for i in top:\n print(i)\n\n\ndef tcp_frequency(frames):\n\n addresses = []\n\n for i in frames:\n if i[4] == \"TCP\":\n addresses.append(i[2])\n\n counter = collections.Counter(addresses)\n items = sorted(\n counter.items(), key=lambda item: (item[1], socket.inet_aton(item[0]))\n )\n\n results = []\n for i in items:\n results.append(i[0])\n\n top = results[-5:]\n top.reverse()\n for i in top:\n print(i)\n\n\ndef udp_frequency(frames):\n\n addresses = []\n\n for i in frames:\n if i[4] == \"UDP\":\n addresses.append(i[2])\n\n counter = collections.Counter(addresses)\n items = sorted(\n counter.items(), key=lambda item: (item[1], socket.inet_aton(item[0]))\n )\n\n results = []\n for i in items:\n results.append(i[0])\n\n top = results[-5:]\n top.reverse()\n for i in top:\n print(i)\n\n\ndef main():\n\n file = open(\"input004.txt\")\n\n contents = []\n\n for i in file:\n contents.append(i)\n\n readInput(contents)\n\n\nmain()\n","sub_path":"_Job-Search/InterviewPractice-master/InterviewPractice-master/Python/coding_dos.py","file_name":"coding_dos.py","file_ext":"py","file_size_in_byte":5284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"559055769","text":"\"\"\"\nTest the torsiondrive json api interface.\n\"\"\"\nfrom typing import Any, Dict\n\nimport numpy as np\nimport pytest\n\nfrom qubekit.engines import TorsionDriver, optimise_grid_point\nfrom qubekit.molecules import Ligand\nfrom qubekit.utils import constants\nfrom qubekit.utils.datastructures import LocalResource, QCOptions, TorsionScan\nfrom qubekit.utils.file_handling import get_data\n\n\n@pytest.fixture\ndef ethane_state() -> Dict[str, Any]:\n \"\"\"\n build an initial state for a ethane scan.\n \"\"\"\n mol = Ligand.from_file(get_data(\"ethane.sdf\"))\n bond = mol.find_rotatable_bonds()[0]\n dihedral = mol.dihedrals[bond.indices][0]\n tdriver = TorsionDriver(grid_spacing=15)\n # make the scan data\n dihedral_data = TorsionScan(torsion=dihedral, scan_range=(-165, 180))\n qc_spec = QCOptions(program=\"rdkit\", basis=None, method=\"uff\")\n td_state = tdriver._create_initial_state(\n molecule=mol, dihedral_data=dihedral_data, qc_spec=qc_spec\n )\n return td_state\n\n\ndef test_get_initial_state(tmpdir):\n \"\"\"\n Make sure we can correctly build a starting state using the torsiondrive api.\n \"\"\"\n with tmpdir.as_cwd():\n mol = Ligand.from_file(get_data(\"ethane.sdf\"))\n bond = mol.find_rotatable_bonds()[0]\n dihedral = mol.dihedrals[bond.indices][0]\n tdriver = TorsionDriver()\n # make the scan data\n dihedral_data = TorsionScan(torsion=dihedral, scan_range=(-165, 180))\n td_state = tdriver._create_initial_state(\n molecule=mol, dihedral_data=dihedral_data, qc_spec=QCOptions()\n )\n assert td_state[\"dihedrals\"] == [\n dihedral,\n ]\n assert td_state[\"elements\"] == [atom.atomic_symbol for atom in mol.atoms]\n assert td_state[\"dihedral_ranges\"] == [\n (-165, 180),\n ]\n assert np.allclose(\n (mol.coordinates * constants.ANGS_TO_BOHR), td_state[\"init_coords\"][0]\n )\n\n\ndef test_optimise_grid_point_and_update(tmpdir, ethane_state):\n \"\"\"\n Try and perform a single grid point optimisation.\n \"\"\"\n with tmpdir.as_cwd():\n mol = Ligand.from_file(get_data(\"ethane.sdf\"))\n tdriver = TorsionDriver(n_workers=1)\n qc_spec = QCOptions(program=\"rdkit\", basis=None, method=\"uff\")\n local_ops = LocalResource(cores=1, memory=1)\n geo_opt = tdriver._build_geometry_optimiser()\n # get the job inputs\n new_jobs = tdriver._get_new_jobs(td_state=ethane_state)\n coords = new_jobs[\"-60\"][0]\n result = optimise_grid_point(\n geometry_optimiser=geo_opt,\n qc_spec=qc_spec,\n local_options=local_ops,\n molecule=mol,\n coordinates=coords,\n dihedral=ethane_state[\"dihedrals\"][0],\n dihedral_angle=-60,\n )\n new_state = tdriver._update_state(\n td_state=ethane_state,\n result_data=[\n result,\n ],\n )\n next_jobs = tdriver._get_new_jobs(td_state=new_state)\n assert \"-75\" in next_jobs\n assert \"-45\" in next_jobs\n\n\ndef test_full_tdrive(tmpdir):\n \"\"\"\n Try and run a full torsiondrive for ethane with a cheap rdkit method.\n \"\"\"\n with tmpdir.as_cwd():\n\n ethane = Ligand.from_file(get_data(\"ethane.sdf\"))\n # make the scan data\n bond = ethane.find_rotatable_bonds()[0]\n dihedral = ethane.dihedrals[bond.indices][0]\n dihedral_data = TorsionScan(torsion=dihedral, scan_range=(-165, 180))\n qc_spec = QCOptions(program=\"rdkit\", basis=None, method=\"uff\")\n local_ops = LocalResource(cores=1, memory=1)\n tdriver = TorsionDriver(\n n_workers=1,\n grid_spacing=60,\n )\n _ = tdriver.run_torsiondrive(\n molecule=ethane,\n dihedral_data=dihedral_data,\n qc_spec=qc_spec,\n local_options=local_ops,\n )\n\n\ndef test_get_new_jobs(ethane_state):\n \"\"\"\n Make sure that for a given initial state we can get the next jobs to be done.\n \"\"\"\n tdriver = TorsionDriver()\n new_jobs = tdriver._get_new_jobs(td_state=ethane_state)\n assert \"-60\" in new_jobs\n assert new_jobs[\"-60\"][0] == pytest.approx(\n [\n -1.44942051524959,\n 0.015117815022160003,\n -0.030235630044320005,\n 1.44942051524959,\n -0.015117815022160003,\n 0.030235630044320005,\n -2.2431058039129903,\n -0.18897268777700002,\n 1.8708296089923,\n -2.16562700192442,\n 1.78768162637042,\n -0.82203119182995,\n -2.1920831782132,\n -1.5325684978714702,\n -1.18863820611733,\n 2.1920831782132,\n 1.5306787709937002,\n 1.18863820611733,\n 2.2431058039129903,\n 0.18897268777700002,\n -1.8708296089923,\n 2.16562700192442,\n -1.78957135324819,\n 0.82014146495218,\n ]\n )\n","sub_path":"qubekit/tests/engines/torsiondrive_test.py","file_name":"torsiondrive_test.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"309128302","text":"import tensorflow as tf\nimport random, copy\nfrom os import path\nimport numpy as np\nimport pandas as pd\nimport cv2\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Input, Flatten, Dense, Dropout\nfrom keras.layers.convolutional import Convolution2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.models import Model\nfrom keras.optimizers import Adam\n\n\"\"\"\nAttribution:\n\nI took inspiration from https://github.com/dolaameng/Udacity-SDC_Behavior-Cloning/blob/master/sdc/data.py when constructing my preprocessing \n(DataSet) class, although I modified this class heavily. This was my first experience with pandas, which greatly simplified the parsing of\nCSV data, which I was doing manually before taking a cue from dolaameng's implementation.\n\nFor the generator class, I used the approach shown in https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9#.p5th2guac.\nI improved upon the shadow casting method by using the HSV rather than HLS color space, as the HLS color space was producing strange artifacts.\nFurthermore, I use every image generated by the simulator (center, left, and right) rather than randomly selecting one per sample.\n\n\"\"\"\n\n\"\"\"\nThis class represents all of the data in the training and cross-validation sets. It accepts a comma-delimited list of folder paths, each\nof which is expected to contain a CSV file called \"driving_log.csv\" and a folder called \"IMG\" containing images referred to in the driving log.\nThe driving log contains three image references per sample, corresponding to the center, left, and right dashboard camera images captured\nby the simulator. Each sample also contains numerical metrics, of which I used Speed during preprocessing. The SteeringAngle metric is the\noutput variable that should be predicted by the camera images.\n\nThe list of folders passed to the constructor makes adding and removing bits of training data easy. If a training run was poor and hurt performance,\nthat folder could be excluded from further training. Likewise if more training was needed, additional training data could be added incrementally.\n\nAll training data is merged, shuffled, and split into a training set (80%) and a cross-validaiton set (20%). In addition before merging, the\nsteering angles are passed through a low-pass filter to smooth out the sometimes jerky measurements from the control devices. I found empirically\nthat a window of 4 samples gave the best smoothing results.\n\nAfter merging, all low-speed measurements are filtered out, to avoid capturing times when the car is idling, stuck, or otherwise engaging in \nbehavior unlikely to be replicated in a testing run. (fingers crossed ;)\n\nThe preprocess() method returns two generators, one to be used for training and the other for cross-validation.\n\"\"\"\nclass DataSet(object):\n _headers = [\"CenterImage\", \"LeftImage\", \"RightImage\", \"SteeringAngle\", \"Throttle\", \"Brake\", \"Speed\"]\n _steering_angle_smoothing_window = 4\n _minimum_speed = 20.0\n _steering_angle_augmentation = 0.25\n _training_fraction = 0.8\n \n def __init__(self, data_paths):\n # A data path is the folder containing a file called \"driving_log.csv\"\n # and a folder called \"IMG\" containing the images referred to in that\n # log file\n logs = []\n \n for data_path in data_paths:\n image_folder = data_path + \"/IMG\"\n log = pd.read_csv(data_path + \"/driving_log.csv\", header=None, names=self._headers)\n for column in [\"CenterImage\", \"LeftImage\", \"RightImage\"]:\n log[column] = log[column].str.rsplit(\"/\", n=1).str[-1].apply(lambda p: path.join(image_folder, p))\n log = self._smooth_steering_angle(log)\n logs.append(log)\n \n self.log = pd.concat(logs, axis=0, ignore_index=True)\n\n def _smooth_steering_angle(self, log):\n log.SteeringAngle = log.SteeringAngle.rolling(window=self._steering_angle_smoothing_window, center=True).mean()\n log.SteeringAngle = log.SteeringAngle.fillna(0)\n return log\n \n def preprocess(self):\n self._remove_low_speeds()\n self._flatten()\n self._shuffle()\n self._validate()\n self._split()\n return (CloningGenerator(self.training_keys, self.samples), CloningGenerator(self.validation_keys, self.samples))\n \n def _remove_low_speeds(self):\n self.log = self.log[self.log.Speed >= self._minimum_speed]\n return self\n\n \"\"\"\n Only use image measurements whose image files exist.\n \"\"\"\n def _validate(self):\n self.sample_keys = [key for key in self.sample_keys if path.isfile(key)]\n return self\n\n \"\"\"\n The steering angle augmentation value was taken from https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9#.p5th2guac.\n \"\"\"\n def _flatten(self):\n self.samples = dict(zip(self.log.CenterImage, self.log.SteeringAngle))\n self.samples.update(zip(self.log.LeftImage, self.log.SteeringAngle + self._steering_angle_augmentation))\n self.samples.update(zip(self.log.RightImage, self.log.SteeringAngle - self._steering_angle_augmentation))\n return self\n \n def _shuffle(self):\n self.sample_keys = list(self.samples.keys())\n random.shuffle(self.sample_keys)\n return self\n\n def _split(self):\n self.training_keys, self.validation_keys = train_test_split(self.sample_keys, train_size=self._training_fraction)\n return self\n\n\"\"\"\n\nThis generator class creates training batches in a separate thread, to avoid loading all training images into memory.\n\nThis class will augment images taken from disk by:\n\n * adjusting the image brightness, \n * changing the image position along with the steering angle, \n * casting random shadows, \n * cropping the sky and dashboard from the image, \n * scaling the image to 64x64 pixels to improve memory use during training,\n * normalizing image depth to [-05,0.5], and\n * randomly flipping the image horizontally, and flipping the sign on the steering angle to match.\n \nThis augmentation enabled my model to pass the second course on the first try! (I am assuming reaching the insurmountable\nslope is as far as we're supposed to go. I tried increasing the throttle to no effect.)\n\n\"\"\"\nclass CloningGenerator(object):\n _trans_range = 100\n \n def __init__(self, sample_keys, samples):\n self._sample_keys = sample_keys\n self._samples = samples\n \n def augment_brightness(self, image):\n bright = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n random_bright = .5 + 0.5 * np.random.uniform()\n bright[:,:,2] = bright[:,:,2] * random_bright\n bright = cv2.cvtColor(bright, cv2.COLOR_HSV2RGB)\n return bright\n\n def translate_image(self, image, angle):\n height, width, depth = image.shape\n tr_x = self._trans_range * np.random.uniform() - self._trans_range / 2\n steer_angle = angle + tr_x / self._trans_range * 2 * .2\n tr_y = 5 * np.random.uniform() - 5 / 2\n Trans_M = np.float32([[1, 0, tr_x], [0, 1, tr_y]])\n image_tr = cv2.warpAffine(image, Trans_M, (width, height))\n return image_tr, steer_angle\n\n def add_random_shadow(self, image):\n height, width, depth = image.shape\n top_y = height * np.random.uniform()\n top_x = 0\n bot_x = width\n bot_y = height * np.random.uniform()\n image_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n shadow_mask = 0 * image_hsv[:,:,2]\n X_m = np.mgrid[0:height, 0:width][0]\n Y_m = np.mgrid[0:height, 0:width][1]\n\n shadow_mask[((X_m - top_x) * (bot_y - top_y) - (bot_x - top_x) * (Y_m - top_y) >= 0)] = 1\n \n if np.random.randint(2) == 1:\n bright = .5\n cond1 = shadow_mask == 1\n cond0 = shadow_mask == 0\n if np.random.randint(2) == 1:\n image_hsv[:,:,2][cond1] = image_hsv[:,:,2][cond1] * bright\n else:\n image_hsv[:,:,2][cond0] = image_hsv[:,:,2][cond0] * bright \n image = cv2.cvtColor(image_hsv, cv2.COLOR_HSV2RGB)\n\n return image\n\n def crop_image(self, image):\n height, width, depth = image.shape\n # Remove the sky\n bottom = int(height / 4.0)\n # Remove the hood and dashboard\n top = int(height / 8.0) * 7\n return image[bottom:top, 0:width]\n \n def scale_image(self, image):\n return cv2.resize(image, (64,64))\n\n def normalize_image(self, image):\n return image / 255. - 0.5\n\n def mirror_image(self, image, steering_angle):\n if np.random.randint(2) == 0:\n return cv2.flip(image,1), steering_angle * -1\n return image, steering_angle\n\n def transform_sample(self, image_path, steering_angle):\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = self.augment_brightness(image)\n image, steering_angle = self.translate_image(image, steering_angle)\n image = self.add_random_shadow(image)\n image = self.crop_image(image)\n image = self.scale_image(image)\n image, steering_angle = self.mirror_image(image, steering_angle)\n image = self.normalize_image(image)\n return image, steering_angle\n \n def generate_batches(self, batch_size):\n input_batch = np.empty((batch_size, 64, 64, 3))\n output_batch = np.empty((batch_size))\n batch_count = int(len(self._sample_keys) / batch_size)\n\n while True:\n for batch in range(batch_count):\n offset = batch*batch_size\n for sample_index in range(batch_size):\n key = self._sample_keys[offset + sample_index]\n\n image, steering_angle = self.transform_sample(key, self._samples[key])\n \n input_batch[sample_index] = image\n output_batch[sample_index] = steering_angle\n\n yield (input_batch, output_batch)\n\n def get_set_size(self, batch_size):\n return int(len(self._sample_keys) / batch_size) * batch_size\n\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n# command line flags\nflags.DEFINE_string('sources', \"data\", \"Folders to get data from.\")\nflags.DEFINE_integer('epochs', 1, \"The number of epochs.\")\nflags.DEFINE_integer('batch_size', 64, \"The batch size.\")\nflags.DEFINE_float('learning_rate', 0.001, \"The learning rate.\")\n\ndef main(_):\n \n model = Sequential()\n \n \"\"\"\n \n This model was inspired by https://chatbotslife.com/using-augmentation-to-mimic-human-driving-496b569760a9#.p5th2guac. \n \n The convolutional layers progressively flatten visual features, and drop 50% of them each layer to prevent overfitting.\n \n \"\"\"\n \n model.add(Convolution2D(32, 3, 3, border_mode='valid', input_shape=(64,64,3)))\n model.add(MaxPooling2D((2,2)))\n model.add(Dropout(0.5))\n\n model.add(Convolution2D(64, 3, 3, border_mode='valid'))\n model.add(MaxPooling2D((2,2)))\n model.add(Dropout(0.5))\n\n model.add(Convolution2D(128, 3, 3, border_mode='valid'))\n model.add(MaxPooling2D((2,2)))\n model.add(Dropout(0.5))\n\n model.add(Flatten())\n\n model.add(Dense(512, activation='relu'))\n model.add(Dense(64, activation='relu'))\n model.add(Dense(16, activation='relu'))\n \n \"\"\"\n A final layer with 1 output is used with a linear activation since we are outputting a single, continuous value.\n \"\"\"\n model.add(Dense(1, activation='linear'))\n \n \"\"\"\n Although the learning rate is a tunable hyperparameter, I left it as the default throughout training.\n \"\"\"\n adam = Adam(lr=FLAGS.learning_rate)\n \n \"\"\"\n A mean squared error loss function was used since this is linear rather than logistic regression.\n \"\"\"\n model.compile(optimizer=adam, loss='mse')\n\n data_set = DataSet(FLAGS.sources.split(','))\n training_set, validation_set = data_set.preprocess()\n \n training_set_size = training_set.get_set_size(FLAGS.batch_size)\n print(\"Training set size: \" + str(training_set_size))\n validation_set_size = validation_set.get_set_size(FLAGS.batch_size)\n print(\"Validation set size: \" + str(validation_set_size))\n \n model.fit_generator(training_set.generate_batches(FLAGS.batch_size),\n samples_per_epoch=training_set_size, nb_epoch=FLAGS.epochs,\n validation_data=validation_set.generate_batches(FLAGS.batch_size),\n nb_val_samples=validation_set_size)\n\n model.save('model.h5')\n\n# parses flags and calls the `main` function above\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"45152595","text":"#!/bin/env python3\n\nimport gzip\nimport tempfile\nfrom io import BytesIO\nimport shutil\nimport logging\nimport timeit\n\nimport h5py\nfrom tqdm import tqdm\n\n# Reading directly from fast5.gz is a bad idea as it's super-slow.\n# This version decompresses into /dev/shm and cleans up nicely.\n\n# An accumulator\nclass MinMax:\n def __init__(self):\n self.min = None\n self.max = None\n\n def add(self, v):\n if self.min is None:\n self.min = self.max = v\n elif v < self.min:\n self.min = v\n elif v > self.max:\n self.max = v\n\n def __repr__(self):\n if not self.min:\n return \"No values\"\n elif self.min == self.max:\n return \"{}\".format(self.min)\n else:\n return \"{}-{}\".format(self.min, self.max)\n\n\ndef read_fast5(fh):\n starts = MinMax()\n durations = MinMax()\n\n with tqdm() as pbar:\n with h5py.File(fh, 'r') as handle:\n\n # Version check!? In development the files are '1.0'\n # so maybe I should check for this?\n try:\n assert handle.attrs['file_version'] == b'1.0'\n except Exception:\n logging.exception(\"Version check failed\")\n\n # We need all the items matching Raw/Reads/{}. In the sample code we get\n # for read in handle['Raw/Reads'].keys():\n # read_group = handle['Raw/Reads/{}'.format(read)]\n\n # But I think we can just do this?\n for n, v in enumerate(handle.values()):\n attrs = v['Raw'].attrs\n\n # Note that the more attributes you actually read from the file the longer\n # it takes. Casting attrs to a dict (ie readign all values) triples the read time.\n starts.add(attrs['start_time'])\n durations.add(attrs['duration'])\n\n pbar.update()\n\n print(\"Extracted {} attrs from file ; start_time {} ; duration {}.\".format(n+1, starts, durations))\n\n# Now the tests.\n### With a temp file (fast)\n\nwith tempfile.TemporaryFile(dir='/dev/shm', suffix='.fast5' ) as tfh:\n with gzip.open('big.fast5.gz', 'rb') as zfh:\n shutil.copyfileobj(zfh, tfh)\n tfh.seek(0)\n\n print(timeit.timeit('read_fast5(tfh)', globals=globals(), number=4))\n\n### With a memory buffer (faster!)\nwith BytesIO() as tfh2:\n with gzip.open('big.fast5.gz', 'rb') as zfh:\n shutil.copyfileobj(zfh, tfh2)\n tfh2.seek(0)\n\n print(timeit.timeit('read_fast5(tfh2)', globals=globals(), number=4))\n\n### With nothing (this takes about half an hour!)\n\"\"\"\nwith gzip.open('big.fast5.gz', 'rb') as zfh:\n\n print(timeit.timeit('read_fast5(zfh)', globals=globals(), number=4))\n\"\"\"\n","sub_path":"lambda_error_rate/big5_test.py","file_name":"big5_test.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"419659039","text":"class Solution(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n candidates = sorted(candidates)\n self.res = []\n self.helper(candidates, target, [], 0)\n return self.res\n\n def helper(self, candidates, target, out, start):\n if target < 0:\n return\n elif target == 0:\n self.res.append(out[:])\n else:\n for index in range(start, len(candidates)):\n if index > start and candidates[index] == candidates[index-1]:\n continue\n target -= candidates[index]\n out.append(candidates[index])\n self.helper(candidates, target, out, index+1)\n target += candidates[index]\n out.pop()","sub_path":"Medium/CombinationSumII.py","file_name":"CombinationSumII.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"500104589","text":"import unittest\nimport random\n\n\"\"\"\nGiven two sorted arrays, combine them such that they are still sorted\nafter the function is finished.\n\n\"\"\"\n\n\ndef merge1(list1, list2):\n result = []\n\n arrow1 = 0\n arrow2 = 0\n\n temp1 = list1 + [float('inf')]\n temp2 = list2 + [float('inf')]\n\n length = len(temp1) + len(temp2) - 2\n\n for i in range(length):\n if temp1[arrow1] < temp2[arrow2]:\n result.append(temp1[arrow1])\n arrow1 += 1\n else:\n result.append(temp2[arrow2])\n arrow2 += 1\n\n return result\n\n\ndef merge2(list1, list2):\n result = []\n\n i, j = 0, 0\n\n while i < len(list1) and j < len(list2):\n if list1[i] < list2[j]:\n result.append(list1[i])\n i += 1\n else:\n result.append(list2[j])\n j += 1\n\n result += list1[i:]\n result += list2[j:]\n\n return result\n\n\ndef merge3(list1, list2):\n result = []\n\n temp1 = list1 + [float('inf')]\n temp2 = list2 + [float('inf')]\n\n for i in range(len(temp1) + len(temp2) - 2):\n if temp1[0] < temp2[0]:\n result.append(temp1.pop(0))\n else:\n result.append(temp2.pop(0))\n\n return result\n\n\nclass MergeTestCase(unittest.TestCase):\n def setUp(self):\n self.list1 = [random.randint(1, 100) for i in range(100)]\n self.list2 = [random.randint(1, 100) for i in range(100)]\n\n self.maxDiff = None\n\n self.list1.sort()\n self.list2.sort()\n\n def test_merge1(self):\n result = merge1(self.list1, self.list2)\n test = self.list1 + self.list2\n test.sort()\n\n self.assertEqual(result, test)\n\n def test_merge2(self):\n result = merge2(self.list1, self.list2)\n test = self.list1 + self.list2\n test.sort()\n\n self.assertEqual(result, test)\n\n def test_merge3(self):\n result = merge3(self.list1, self.list2)\n test = self.list1 + self.list2\n test.sort()\n\n self.assertEqual(result, test)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"merge/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"48844056","text":"import os\nimport random\n\n#Images are from opensourcegameart.com, and Google.com\nMAIN_FILE = os.path.dirname(__file__)\n\nWELCOME_SCREEN_FILE = os.path.join(MAIN_FILE, 'Welcome-Screen-Animation')\nWELCOME_SCREEN_ANIMATION = os.listdir(WELCOME_SCREEN_FILE)\nWELCOME_SCREEN_BANNER = os.path.join(MAIN_FILE,'welcome-gif.gif')\n\nHANDS_FOLDER = os.path.join(MAIN_FILE,'Hand-Icons')\nRIGHT_HAND_OPEN_IMG = os.path.join(HANDS_FOLDER, 'Hand-Right-Open.png')\nLEFT_HAND_OPEN_IMG = os.path.join(HANDS_FOLDER, 'Hand-Left-Open.png')\nRIGHT_HAND_CLOSED_IMG = os.path.join(HANDS_FOLDER,'Hand-Right-Closed.png')\nLEFT_HAND_CLOSED_IMG = os.path.join(HANDS_FOLDER, 'Hand-Left-Closed.png')\nRIGHT_HAND_LASSO_IMG = os.path.join(HANDS_FOLDER, 'Hand-Right-Lasso.png')\nLEFT_HAND_LASSO_IMG = os.path.join(HANDS_FOLDER, 'Hand-Left-Lasso.png')\n\nLEFT_IMG = os.path.join(MAIN_FILE,'left_hand_climbingV2.png')\nRIGHT_IMG = os.path.join(MAIN_FILE,'right_hand_climbingV2.png')\n\nOPPONENT_IMG = os.path.join(MAIN_FILE, 'scorpion-1.png')\nIN_GAME_FILE = os.path.join(MAIN_FILE, 'In-Game-Animation')\nIN_GAME_ANIMATION = os.listdir(IN_GAME_FILE)\n\n\n#All the in-game maps were drawn me :)\nMAPS_FOLDER = os.path.join(MAIN_FILE, 'Game-Mode-Walls')\nDIFFERENT_MAPS = os.listdir(os.path.join(MAIN_FILE, 'Game-Mode-Walls'))[1:]\nMAP_IMG = os.path.join(MAPS_FOLDER, random.choice(DIFFERENT_MAPS))\n\nARROWS_FOLDER = os.path.join(MAIN_FILE, 'Direction-Icons')\nNORTH_ARROW = os.path.join(ARROWS_FOLDER, 'north-arrow.png')\nSOUTH_ARROW = os.path.join(ARROWS_FOLDER, 'south-arrow.png')\nEAST_ARROW = os.path.join(ARROWS_FOLDER, 'east-arrow.png')\nWEST_ARROW = os.path.join(ARROWS_FOLDER, 'west-arrow.png')\n","sub_path":"images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"379217440","text":"import boto3\nfrom botocore.config import Config\nfrom exec_command import ParamikoClient \n\n#Function:遍历AWS所有机器执行命令获得所有机器执行命令的结果,此脚本可以在最下面修改成自己想要的命令\n#Author :李先生\n#Date :20190419\n#Version :V1.0\n\n# 指定区域\nregion = ['eu-west-1']\n#region = ['eu-west-1', 'us-west-2', 'ap-southeast-1']\n\n# 设置client的连接信息,不设置,默认值为3,超时的时候会报错,所以设置大一点\nconfig = Config(\n retries=dict(\n max_attempts=20\n )\n)\n\n# 遍历指定的几个区域,打印实例的instanceid\nfor each_region in region:\n # 这里client指定region_name的时候,在第一步的时候只设置了一个国家,这里可以用一个列表遍历\n client = boto3.client('ec2', region_name=each_region, config=config)\n # 调用client.describe_instance()得到一个返回值\n response = client.describe_instances(\n Filters=[\n {\n 'Name': 'instance-state-name',\n 'Values': [ \n 'running',\n ]\n },\n ],\n )\n\n # 对返回的结果做解析,一般都是列表和字典,根据自己想要的信息做获取\n for each_list in response['Reservations']:\n for device in each_list['Instances']:\n\n keyName = device['KeyName']\n\n instanceTag = device['Tags']\n\n instanceIp = device['PrivateIpAddress']\n\n# print(instanceIp)\n\n arch = device['Architecture']\n\n\n if arch == \"x86_64\":\n for name in instanceTag:\n if name['Key'] == \"Name\":\n instanceName = name['Value'] \n instanceMessage = instanceName + ' ' + keyName\n\n username = ['ec2-user','centos','ubuntu']\n \n for user in username:\n paramiko_config = {\n 'host': instanceIp,\n 'port': 22,\n 'username': user,\n 'key': keyName + '.pem',\n }\n\n paramik = ParamikoClient(paramiko_config)\n if paramik.connects() == True:\n result = paramik.exec_command(\"docker --version\")\n if result:\n #print(instanceName + ' ' + keyName + ' ' + bytes.decode(result))\n print(instanceName + ' ' + bytes.decode(result))\n\n \n\n","sub_path":"All_Ec2_Command.py","file_name":"All_Ec2_Command.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"429409406","text":"#coding=utf-8\nfrom vtk import *\nfrom regionGrowFunc import grow\nimport numpy as np\nimport vtk\nfrom vtk.util.numpy_support import vtk_to_numpy\nfrom otsu import otsu_threshold\nimport cv2\nfrom read_images import read_images\n\nstartNum=0\nendNum=1200\n# img_height=255\n# img_width=255\n\n\npath = r'D:\\carck_detect_system\\crack'\na,img_width,img_height,startNum,endNum=read_images(path,startNum,endNum)\nprint(\"img zise: \",img_height,\" ,\",img_width,startNum,endNum)\na=grow(a,(0,0,0),1)\n\n#numpy2vtk\ndataImporter = vtk.vtkImageImport()\n# The previously created array is converted to a string of chars and imported.\ndata_string = a.tostring()\ndataImporter.CopyImportVoidPointer(data_string, len(data_string))\n# The type of the newly imported data is set to unsigned char (uint8)\ndataImporter.SetDataScalarTypeToUnsignedChar()\n# Because the data that is imported only contains an intensity value\n# (it isnt RGB-coded or someting similar), the importer must be told this is the case.\ndataImporter.SetNumberOfScalarComponents(1)\n# The following two functions describe how the data is stored and the dimensions of the array it is stored in.\n# For this simple case, all axes are of length 75 and begins with the first element.\n# For other data, this is probably not the case.\n# I have to admit however, that I honestly dont know the difference between SetDataExtent()\n# and SetWholeExtent() although VTK complains if not both are used.\ndataImporter.SetDataExtent(0, img_height-1, 0, img_width-1, 0, endNum-startNum)\ndataImporter.SetWholeExtent(0, img_height-1, 0, img_width-1, 0, endNum-startNum)\nv16=dataImporter\nv16.SetDataSpacing(1,1,1)\n# v16.SetAllow8BitBMP(16)\nv16.Update()\n\n###############################################################################################\ncolors = vtk.vtkNamedColors()\n# This is a simple volume rendering example that\n# uses a vtkFixedPointVolumeRayCastMapper\n\n# Create the standard renderer, render window\n# and interactor.\nren1 = vtk.vtkRenderer()\n\nrenWin = vtk.vtkRenderWindow()\nrenWin.AddRenderer(ren1)\n\niren = vtk.vtkRenderWindowInteractor()\niren.SetRenderWindow(renWin)\n\n\n# Create transfer mapping scalar value to opacity.\nopacityTransferFunction = vtk.vtkPiecewiseFunction()\nopacityTransferFunction.AddPoint(0, 0.0)\nopacityTransferFunction.AddPoint(50, 0.0)\nopacityTransferFunction.AddPoint(150, 0.6)\nopacityTransferFunction.AddPoint(255, 0.0)\n\n# Create transfer mapping scalar value to color.\ncolorTransferFunction = vtk.vtkColorTransferFunction()\ncolorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0)\ncolorTransferFunction.AddRGBPoint(50, 0.0, 0.0, 0.0)\ncolorTransferFunction.AddRGBPoint(100, 0.0, 0.0, 0.0)\ncolorTransferFunction.AddRGBPoint(150, 0.0, 0.7, 0.7)\ncolorTransferFunction.AddRGBPoint(255, 0.0, 0.0, 0.0)\n\n#Creat opacity gradient function\ngradientTransferFunction=vtkPiecewiseFunction()\ngradientTransferFunction.AddPoint(0,0.0)\ngradientTransferFunction.AddPoint(255,2.0)\n# The property describes how the data will look.\nvolumeProperty = vtk.vtkVolumeProperty()\nvolumeProperty.SetColor(colorTransferFunction)\nvolumeProperty.SetScalarOpacity(opacityTransferFunction)\nvolumeProperty.SetGradientOpacity(gradientTransferFunction)\n\nvolumeProperty.ShadeOn()\nvolumeProperty.SetAmbient(0.5) #设置环境光系数\nvolumeProperty.SetDiffuse(1) #设置散射光系数\nvolumeProperty.SetSpecular(0.5) #设置反射光系数\nvolumeProperty.SetSpecularPower(50)\n#设置灯光\nmyLight2 = vtkLight()\nmyLight2.PositionalOn()\nmyLight2.SetColor(1, 1, 1)\nmyLight2.SetPosition(-9999999, -9999999, -9999999)\nmyLight2.SetFocalPoint(ren1.GetActiveCamera().GetFocalPoint())\n# ren1.AddLight(myLight2)\n\nvolumeProperty.SetInterpolationTypeToLinear()\n# volumeProperty.SetInterpolationTypeToNearest()\n\n# The mapper / ray cast function know how to render the data.\n# volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper()\n# volumeMapper=vtkGPUVolumeRayCastMapper()\nvolumeMapper=vtkSmartVolumeMapper()\nvolumeMapper.SetRequestedRenderModeToRayCast()\nvolumeMapper.SetRequestedRenderModeToGPU()\n# volumeMapper.SetInterpolationModeToLinear()\nvolumeMapper.SetInputConnection(v16.GetOutputPort())\n\n# The volume holds the mapper and the property and\n# can be used to position/orient the volume.\nvolume = vtk.vtkVolume()\nvolume.SetMapper(volumeMapper)\nvolume.SetProperty(volumeProperty)\n\nren1.AddVolume(volume)\nren1.SetBackground(colors.GetColor3d(\"White\"))\nren1.SetGradientBackground(True)\nren1.GetActiveCamera().Azimuth(45)\nren1.GetActiveCamera().Elevation(30)\nren1.ResetCameraClippingRange()\nren1.ResetCamera()\n\nrenWin.SetSize(600, 600)\nrenWin.Render()\n\niren.Start()","sub_path":"system/example/regionGrow.py","file_name":"regionGrow.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"558891002","text":"from faxreader.cli.cli_parser import parse\nfrom faxreader.core.handle_data import *\n\n\ndef handle(args):\n lines = read_lines_from_file(args.input_file)\n number_of_accounts = get_number_of_accounts(lines)\n for account_index in range(number_of_accounts):\n account = []\n for number_index in range(1, 10):\n digit = get_digit(account_index, number_index, lines)\n account.append(digit)\n checked_account = check_account_number(\"\".join(account))\n create_and_write_to_report_file(args.saveto,checked_account)\n\n\nif __name__ == \"__main__\":\n handle(parse())\n","sub_path":"faxreader/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"467792731","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\n#############################################\n# File Name: setup.py\n# Author: InfinityFuture\n# Mail: infinityfuture@foxmail.com\n# Created Time: 2018-09-06 10:00:00\n#############################################\n\nimport os\nfrom setuptools import setup, find_packages\n\nversion = os.path.join(\n os.path.realpath(os.path.dirname(__file__)),\n 'version.txt'\n)\n\nsetup(\n name = 'skcrf-tagger',\n version = open(version, 'r').read().strip(),\n keywords = ('pip', 'scikit-learn', 'sklearn-crfsuite', 'CRF', 'NER', 'tagger'),\n description = 'NLP tool',\n long_description = 'NLP tool, NER, POS',\n license = 'MIT Licence',\n\n url = 'https://github.com/infinity-future/skcrf-tagger',\n author = 'infinityfuture',\n author_email = 'infinityfuture@foxmail.com',\n\n packages = find_packages(),\n include_package_data = True,\n platforms = 'any',\n install_requires = ['sklearn-crfsuite', 'tqdm', 'scikit-learn', 'numpy', 'scipy']\n)\n","sub_path":"pypi_install_script/skcrf-tagger-0.0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"459723166","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\nimport ast\nimport codecs\n\nclass prepareData():\n\n def __init__(self, feature_dict, label_dict):\n\n self.feature_dict = feature_dict \n self.feat = {} \n self.labels = label_dict\n\n def separate_labelled_data(self):\n\n result_feature = codecs.open(\"data/labelled_feature.txt\", 'w', 'utf8')\n for word,clist in self.feature_dict.items(): \n if word in self.labels:\n self.feat[word] = clist\n result_feature.write(str(self.feat)) \n result_feature.close()\n \n\n\nif __name__ == '__main__':\n\n label_file = 'data/labelfile.txt'\n with codecs.open('data/populated_feature.txt', 'r', 'utf8') as fp:\n contents = fp.read()\n featuredict= ast.literal_eval(contents)\n\n with codecs.open('data/labels_dict.txt', 'r', 'utf8') as lp:\n contents = lp.read()\n labeldict= ast.literal_eval(contents)\n \n pd = prepareData(featuredict,labeldict)\n pd.separate_labelled_data()\n \n \n\n\n \n\n\n\n\n \n\n \n","sub_path":"prepareData.py","file_name":"prepareData.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"408558188","text":"\"\"\"empty message\n\nRevision ID: d632fa975355\nRevises: 0ead70782759\nCreate Date: 2018-12-04 15:42:57.201058\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'd632fa975355'\ndown_revision = '0ead70782759'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('products', 'earnings',\n existing_type=mysql.VARCHAR(length=80),\n nullable='0')\n op.create_foreign_key(None, 'roles', 'users', ['user_id'], ['id'])\n op.add_column('sm_user', sa.Column('is_admin111', sa.SmallInteger(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('sm_user', 'is_admin111')\n op.drop_constraint(None, 'roles', type_='foreignkey')\n op.alter_column('products', 'earnings',\n existing_type=mysql.VARCHAR(length=80),\n nullable=True)\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/d632fa975355_.py","file_name":"d632fa975355_.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"341382743","text":"from PIL import Image\nfrom argparse import ArgumentParser\n\nimport functools\nimport sys\nimport re\nimport os\nimport hashlib\n\n#####################################################\n\nem_exSlab = { \"src\": \"{0}/images/slabs/{1}-{2}.png\" , \"components\": [ \"slabStyle\", \"exSlabColour\" ] }\nem_inSlab = { \"src\": \"{0}/images/slabs/{1}-{2}.png\" , \"components\": [ \"slabStyle\", \"inSlabColour\" ] }\nem_exFrame = { \"src\": \"{0}/images/frames/{1}/external-{2}.png\" , \"components\": [ \"frame\" , \"exFrameColour\" ] }\nem_inFrame = { \"src\": \"{0}/images/frames/internal-{1}.png\" , \"components\": [ \"inFrameColour\" ] }\na_exSash = { \"src\": \"{0}/images/sash/external-{1}.png\" , \"components\": [ \"exSashColour\" ] }\na_inSash = { \"src\": \"{0}/images/sash/internal-{1}.png\" , \"components\": [ \"inSashColour\" ] }\na_exFrame = { \"src\": \"{0}/images/frames/external-{1}.png\" , \"components\": [ \"exFrameColour\" ] }\na_inFrame = { \"src\": \"{0}/images/frames/internal-{1}.png\" , \"components\": [ \"inFrameColour\" ] }\na_exSlab = { \"src\": \"{0}/images/slabs/{1}.png\" , \"components\": [ \"exSlabColour\" ] }\na_inSlab = { \"src\": \"{0}/images/slabs/{1}.png\" , \"components\": [ \"inSlabColour\" ] }\nhandle = { \"src\": \"shared/images/handles/{1}.png\" , \"components\": [ \"handle\" ] }\nletterplate = { \"src\": \"{0}/images/cassettes/{1}/letterplate-{2}.png\", \"components\": [ \"cassette\", \"letterplate\" ] }\nexCassette = { \"src\": \"{0}/images/cassettes/{1}/cassette-{2}.png\" , \"components\": [ \"cassette\", \"exSlabColour\" ] }\ninCassette = { \"src\": \"{0}/images/cassettes/{1}/cassette-{2}.png\" , \"components\": [ \"cassette\", \"inSlabColour\" ] }\nglass = { \"src\": \"{0}/images/cassettes/{1}/{2}.png\" , \"components\": [ \"cassette\", \"glass\" ] }\ndripbar = { \"src\": \"{0}/images/drip/{1}.png\" , \"components\": [ \"dripbar\" ] }\n\nparts = {\n \"eliteModern\": {\n \"ex\": [\n em_exFrame, handle , letterplate,\n dripbar , exCassette, glass,\n em_exSlab\n ],\n\n \"in\": [\n em_inFrame, handle, letterplate,\n inCassette, glass , em_inSlab\n ]\n },\n\n \"aluminium\": {\n \"ex\": [\n a_exFrame , a_exSash , handle,\n letterplate, dripbar , exCassette,\n glass , a_exSlab\n ],\n\n \"in\": [\n a_inFrame , a_inSash , handle,\n letterplate, inCassette, glass,\n a_inSlab\n ]\n }\n}\n\n#####################################################\n\ndef img_combine( img_a, img_b ):\n return Image.alpha_composite( img_a, img_b )\n\ndef img_compress( img, value=3 ):\n width, height = img.size\n\n width = int( width / value )\n height = int( height / value )\n\n return img.resize( ( width, height ), Image.BICUBIC )\n\n#####################################################\n\ndef to_camel( string ):\n split = string.split( \"-\" )\n class_ = string.__class__\n\n return split[0] + class_.join( \"\", map( class_.capitalize, split[1:] ) )\n\n#####################################################\n\ndef decode_str( raw ):\n kvArray = raw.split( \";\" )\n kvDict = {}\n\n for item in kvArray:\n if not item:\n continue\n\n k, v = item.split( \"|\" )\n kvDict[ k ] = v\n\n return kvDict\n\n#####################################################\n\ndef encode_str( data ):\n return \";\".join( [ \"{0}|{1}\".format( k,v ) for k,v in data.items() ] )\n\n#####################################################\n\ndef img_builder( raw_data, save_to ):\n try:\n data = decode_str( raw_data )\n filehash = hashlib.md5( raw_data.encode() )\n\n # Replace any colons with dashes so\n # the image file can be found.\n data[ \"glass\" ] = data[ \"glass\" ].replace( ':', \"-\" )\n\n # Convert the door range to camelCase\n # so that the dictionary key and image\n # folders can be accessed.\n dr = to_camel( data[ \"range\" ] )\n\n # Get the appropriate image parts\n # for the given range.\n doorParts = parts[ dr ]\n results = {}\n\n # Iterate over the sided components\n # from the parts dictionary.\n for side in doorParts:\n name = \"{0}:{1}.png\".format( filehash.hexdigest(), side )\n path = os.path.join( save_to, name )\n exists = os.path.exists( path )\n images = []\n\n results[ side ] = name\n\n if exists:\n continue\n\n for img in doorParts[ side ]:\n # For each part collect the data from the request\n # json and then replace the placeholders in part's src.\n items = map( lambda o: data[ o ], img[ \"components\" ] );\n src = img[ \"src\" ].format( dr, *items );\n\n # If there is a none present, then skip the image.\n match = re.search( r'none', src )\n if match:\n continue\n\n # Load the image and convert it to a useable\n # format.\n image = Image.open( src ).convert( \"RGBA\" )\n\n # If the current side is the internal, flip\n # the image.\n if side == \"in\":\n image = image.transpose( Image.FLIP_LEFT_RIGHT )\n\n # Add the image to the array.\n images.append( image )\n\n # Combine the image layers into a single image\n # and compress it.\n door = functools.reduce( img_combine, images[::-1] )\n door = img_compress( door )\n\n door.save( path )\n\n sys.stdout.write( encode_str( results ) )\n\n # If a file can't be opened then terminate the process.\n except Exception as e:\n sys.stderr.write( \"{0}\".format( e ) )\n\n#####################################################\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument( \"data\" )\n parser.add_argument( \"saveTo\" )\n args = parser.parse_args()\n\n img_builder( args.data, args.saveTo )","sub_path":"server/image_builder.py","file_name":"image_builder.py","file_ext":"py","file_size_in_byte":5848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"383288697","text":"from bs4 import BeautifulSoup\nimport sys\n\ndef download_pages(url_to_download):\n\timport urllib2\n\tuser_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'\n\theaders = { 'User-Agent' : user_agent }\n\treq = urllib2.Request(url_to_download, None, headers)\n\tresponse = urllib2.urlopen(req)\n\tpage = response.read()\n\treturn page\n\nif __name__ == \"__main__\":\n\tlinkedpage = sys.argv[1]\n\t#with open (\"/home/saumye/linkedin.html\",\"r\") as myfile:\n\t#\tdata = myfile.read()\n\tf = open('workfile', 'w')\n\t#f.write('[ ')\n\tdata = download_pages(linkedpage)\t\t\t#FOR NON LOCAL\n\tparsed_html = BeautifulSoup(data)\n\tpopular_stores = parsed_html.find(id = \"profile-skills\")\n\tpopular_stores = popular_stores.find_all('li')\n\tjsonobj = []\n\tcount = 0\n\tlength = len(popular_stores)\n\tfor list in popular_stores:\n\t\toutlet_link = list.span.span.text\n\t\t#jsonobj.append(outlet_link)\n\t\tif count <= (length-2):\n\t\t\tf.write(outlet_link)\n\t\tif count <= (length-3):\n\t\t\tf.write(',')\n\t\tcount += 1\n\t#f.write(' ]')","sub_path":"skills.py","file_name":"skills.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"190139795","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'profiles'\n\nurlpatterns = [\n path('myprofile/', my_profile_view, name='my-profile'),\n path('invites_received_view/', invites_received, name='invites_received_view'),\n path('profiles_list/', ProfileListView.as_view(), name='profiles_list'),\n path('invites_profiles_list/', invites_profiles_list, name='invites_profiles_list'),\n path('send_invitation/', send_invitation, name='send_invitation'),\n path('remove_from_friends/', remove_from_friends, name='remove_from_friends'),\n path('invites_received_view/accept/', accept_invitation, name='accept_invite'),\n path('invites_received_view/reject/', reject_invitation, name='reject_invite'),\n path('/', ProfileDetailView.as_view(), name='profile-detail-view'),\n]","sub_path":"profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"69504598","text":"import cv2\n\nface_cascade=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n\nimg = cv2.imread(\"news.jpg\")\n#using grayscale increases accuracy\n\ngray_img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n#after each search \n#decreasign scale for search i.e image scaled down\n#so bigger faces searched\n#how many neighbours to search around the window\nfaces=face_cascade.detectMultiScale(gray_img,\nscaleFactor=1.05,\nminNeighbors=5)\nprint(faces)\n\n#x,y gives top left corner of the face\n#w and h are width and heights \nfor x, y, w, h in faces:\n img=cv2.rectangle(img, (x,y),(x+w, y+h), (0, 255, 0), 3) \n #(x,y) is the starting point\n\n \nresized=cv2.resize(img, (int(img.shape[1]/3),int(img.shape[0]/3)))\n\n\ncv2.imshow(\"Gray\", resized)\ncv2.waitKey(0)\ncv2.destroyAllWindows\n\n#https://stackoverflow.com/questions/20801015/recommended-values-for-opencv-detectmultiscale-parameters/20805153","sub_path":"app6/Not_app/facedetection/facedetection.py","file_name":"facedetection.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"290310797","text":"#!/usr/bin/env python\n\n'''\nGeneric Scraper class to download the pdfs \nfrom any given link\n'''\n\n\nimport bs4, os, requests\nfrom selenium import webdriver\n\n\nclass Scraper(object):\n\tdef __init__(self,parser,pagelist,log):\n\t\t'''\n\t\tInitializes the required variables, and \n\t\tmakes the directory to store the pdfs\n\t\tif not present\n\t\t'''\n\t\tself._parser=parser\n\t\tself._pagelist=pagelist\n\t\tself._log=log\n\t\tself._count=0\n\n\t\ttry:\n\t\t\tif not os.path.exists('downloaded_pdfs'):\n\t\t\t\tos.makedirs('downloaded_pdfs')\n\t\texcept OSError as e:\n\t\t\tprint('Scraper Error : while checking/making directory : ' + e)\n\t\t\tself._log.write('Scraper Error : while checking/making directory : %s\\n'%e)\n\n\t\ttry:\t\t\n\t\t\tself._browser=webdriver.Firefox()\n\t\texcept:\n\t\t\tprint('Scraper Error : could not open firefox browser')\n\t\t\tself._log.write('Scraper Error : could not open firefox browser\\n')\n\n\n\n\tdef _download(self,page):\n\t\t'''\n\t\tGiven a page, downloads and returns \n\t\tthe source of that page\n\t\t'''\n\t\tprint('downloading page : %s'%page)\n\t\tself._log.write('downloading page : %s\\n'%page)\n\t\ttry:\n\t\t\tself._browser.get(page)\n\t\t\thtml_source=self._browser.page_source\n\t\t\treturn html_source\n\t\texcept:\n\t\t\tprint('could not download the page %s\\n'%page)\n\t\t\tself._log.write('could not download the page %s\\n'%page)\n\n\n\n\tdef _store(self,pdf_url):\n\t\t'''\n\t\tGiven a pdf url, downloads and stores the pdf\n\t\tin ./downloaded_pdfs folder\n\t\t'''\n\n\t\tself._count+=1\n\t\tprint('storing pdf %s'%pdf_url)\n\t\tself._log.write('storing pdf : %s\\n'%pdf_url)\n\n\t\tres=requests.get(pdf_url)\n\t\t\n\t\ttry:\n\t\t\tres.raise_for_status()\n\t\texcept:\n\t\t\tprint('Scraper error : error while storing the pdf %s'%pdf_url)\n\t\t\tself._log.write('Scraper error : error while storing the pdf %s\\n'%pdf_url)\n\t\t\treturn\n\n\t\tif res!=None:\n\t\t\tpdfFile=open(os.path.join('downloaded_pdfs',os.path.basename(pdf_url)),'wb')\n\t\t\tfor chunk in res.iter_content(1024):\n\t\t\t\tpdfFile.write(chunk)\n\t\t\tpdfFile.close()\n\t\t\n\n\n\tdef run(self):\n\t\t'''\n\t\tUse all the other functions of the module to \n\t\tdownload the pdfs, and works as the only public method \n\t\tof the class.\n\t\t'''\n\t\tfor page_list in self._pagelist:\n\n\t\t\tfor page in page_list:\n\n\t\t\t\thtml=self._download(page)\n\t\t\t\tpdf_url=self._parser.parse(html)\n\t\t\t\tself._store(pdf_url)\n\n\t\tself._browser.quit()\n\t\tself._log.write('\\n\\nNumber of pdfs downloaded : %s'%self._count)\n\n\n","sub_path":"webspider/generic_scraper.py","file_name":"generic_scraper.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"154550519","text":"# coding=utf-8\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.support.ui import Select\r\nimport time\r\nimport os\r\nimport pandas as pd\r\nimport datetime\r\nimport sys\r\nimport shutil\r\n\r\nOPATH = os.path.dirname(os.path.abspath(__name__))\r\nDOWNLOAD_PATH = OPATH\r\nURL = \"https://cbrecrm.my.salesforce.com/\"\r\nOPPO = \"oppo_data.csv\"\r\nSPOC = \"SPOC_data.csv.\"\r\nOPPO_PATH = os.path.join(OPATH, OPPO)\r\nSPOC_PATH = os.path.join(OPATH, SPOC)\r\n\r\nREPORT_IDS = [\"00O1Y000006cmFY\", \"00O1Y000006cifS\"]\r\nREPORT_NAME = {\r\n \"00O1Y000006cmFY\": OPPO, # 0:oppo_data\r\n \"00O1Y000006cifS\": SPOC,\r\n}\r\n\r\ndef download_report(report_id):\r\n chromeOptions = webdriver.ChromeOptions()\r\n prefs = {\"download.default_directory\": DOWNLOAD_PATH}\r\n chromeOptions.add_experimental_option(\"prefs\", prefs)\r\n driver = webdriver.Chrome(chrome_options=chromeOptions)\r\n\r\n driver.get(URL + report_id)\r\n tag = driver.find_element_by_xpath(\"//div[contains(@class, 'reportActions')]\")\r\n [btn for btn in tag.find_elements_by_xpath(\"//input[contains(@class, 'btn')]\")\r\n if btn.get_attribute('value') == u'詳細のエクスポート'][0].click()\r\n\r\n elem = driver.find_element_by_id('xf')\r\n select_obj = Select(elem)\r\n select_obj.select_by_visible_text(u'カンマ区切り形式(.csv)')\r\n\r\n # ダウンロード前にあるダウンロードファイルの数を数える\r\n n_files = len([f for f in os.listdir(DOWNLOAD_PATH) if f.startswith('report') and f.endswith('.csv')])\r\n\r\n tag = driver.find_element_by_xpath(\"//div[contains(@class, 'pbBottomButtons')]\")\r\n [btn for btn in tag.find_elements_by_xpath(\"//input[contains(@class, 'btn')]\")\r\n if btn.get_attribute('value') == u'エクスポート'][0].click()\r\n\r\n # ダウンロードファイルが増えない限り待つ\r\n while len([f for f in os.listdir(DOWNLOAD_PATH) if f.startswith('report') and f.endswith('.csv')]) == n_files:\r\n time.sleep(1)\r\n\r\n driver.quit()\r\n\r\ndef rename(REP_FILE,name):\r\n name = str(name)\r\n print (name)\r\n file_path_d = os.path.join(DOWNLOAD_PATH,'{}.csv'.format(name))\r\n print (file_path_d)\r\n old_file = os.path.join(DOWNLOAD_PATH, REP_FILE)\r\n new_file = os.path.join(DOWNLOAD_PATH, name)\r\n os.rename(old_file, new_file)\r\n return\r\n\r\ndef format_report(report_id,name):\r\n files = [f for f in os.listdir(DOWNLOAD_PATH) if f.startswith('report') and f.endswith('.csv')]\r\n print(files)\r\n REP_FILE = os.path.join(DOWNLOAD_PATH, files[0])\r\n print(REP_FILE)\r\n if os.path.isfile(REP_FILE):\r\n rename(REP_FILE,name)\r\n\r\ndef main():\r\n print (\"export report\")\r\n for report_id in REPORT_IDS:\r\n print(report_id)\r\n download_report(report_id)\r\n print('download ok')\r\n format_report(report_id,REPORT_NAME[report_id])\r\n print('format ok')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"PM/export_report.py","file_name":"export_report.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"287495558","text":"import sys, os, shutil\n\nfrom subprocess import call, Popen, PIPE, STDOUT\nimport subprocess\n\nfrom Bio import SeqIO\nfrom AAFTF.utility import execute\nfrom AAFTF.utility import calcN50\nfrom AAFTF.utility import fastastats\nfrom AAFTF.resources import DB_Links\nfrom AAFTF.utility import status\nfrom AAFTF.utility import printCMD\nfrom AAFTF.utility import SafeRemove\nfrom AAFTF.utility import checkfile\n\n# logging - we may need to think about whether this has \n# separate name for the different runfolder\ndef run(parser,args):\n\n if not args.workdir:\n args.workdir = 'aaftf-sourpurge_'+str(os.getpid()) \n if not os.path.exists(args.workdir):\n os.mkdir(args.workdir)\n\n bamthreads = 4\n if args.cpus < 4:\n bamthreads = 1\n\n #find reads\n forReads, revReads = (None,)*2\n if args.left:\n forReads = os.path.abspath(args.left)\n if args.right:\n revReads = os.path.abspath(args.right)\n if not forReads:\n status('Unable to located FASTQ raw reads, low coverage will be skipped. Provide -l,--left or -r,--right to enable low coverage filtering.')\n# sys.exit(1)\n \n #parse database locations\n if not args.sourdb:\n try:\n DB = os.environ[\"AAFTF_DB\"]\n except KeyError:\n if args.AAFTF_DB:\n SOUR = os.path.join(args.AAFTF_DB, 'genbank-k31.lca.json.gz')\n else:\n status(\"$AAFTF_DB/genbank-k31.lca.json.gz not found, pass --sourdb\")\n sys.exit(1)\n SOUR = os.path.join(DB, 'genbank-k31.lca.json.gz')\n if not os.path.isfile(SOUR):\n status(\"{:} sourmash database not found\".format(SOUR))\n # should we prompt it to download \n sys.exit(1)\n else:\n SOUR = os.path.abspath(args.sourdb)\n \n # hard coded tmpfile\n assembly_working = 'assembly.fasta'\n megablast_working = 'megablast.out'\n blobBAM = 'remapped.bam'\n shutil.copyfile(args.input, os.path.join(args.workdir,assembly_working))\n numSeqs, assemblySize = fastastats(os.path.join(args.workdir,\n assembly_working))\n status('Assembly is {:,} contigs and {:,} bp'.format(numSeqs, \n assemblySize))\n DEVNULL = open(os.devnull, 'w')\n\n #now filter for taxonomy with sourmash lca classify\n status('Running SourMash to get taxonomy classification for each contig')\n sour_sketch = os.path.basename(assembly_working)+'.sig'\n sour_compute = ['sourmash', 'compute', '-k', '31', '--scaled=1000',\n '--singleton', assembly_working]\n printCMD(sour_compute)\n subprocess.run(sour_compute, cwd=args.workdir, stderr=DEVNULL)\n sour_classify = ['sourmash', 'lca', 'classify', '--db', SOUR,'--query', sour_sketch]\n printCMD(sour_classify)\n # output csv: ID,status,superkingdom,phylum,class,order,family,genus,species,strain\n Taxonomy = {}\n UniqueTax = []\n sourmashTSV = os.path.join(args.workdir, 'sourmash.csv')\n with open(sourmashTSV, 'w') as sour_out:\n for line in execute(sour_classify, args.workdir):\n sour_out.write(line)\n if not line or line.startswith('\\n') or line.startswith('ID') or line.count(',') < 9:\n continue\n line = line.strip()\n cols = line.split(',')\n if 'found' in cols:\n idx = cols.index('found')\n Taxonomy[cols[0]] = cols[idx+1:]\n taxClean = [x for x in cols[idx+1:] if x]\n UniqueTax.append('{:}'.format(';'.join(taxClean)))\n elif 'nomatch' in cols:\n idx = cols.index('nomatch')\n Taxonomy[cols[0]] = cols[idx+1:]\n UniqueTax = set(UniqueTax)\n status('Found {:} taxonomic classifications for contigs:\\n{:}'.\n format(len(UniqueTax), '\\n'.join(UniqueTax)))\n if args.taxonomy:\n sys.exit(1)\n Tax2Drop = []\n for k,v in Taxonomy.items():\n v = [x for x in v if x] #remove empty items from list\n if args.debug:\n print('{:}\\t{:}'.format(k, v))\n if len(v) > 0:\n if not any(i in v for i in args.phylum):\n Tax2Drop.append(k)\n \n #drop contigs from taxonomy before calculating coverage\n status('Dropping {:} contigs from taxonomy screen'.format(len(Tax2Drop)))\n sourTax = os.path.join(args.workdir, 'sourmashed-tax-screen.fasta')\n with open(sourTax, 'w') as outfile:\n with open(os.path.join(args.workdir,assembly_working), 'rU') as infile:\n for record in SeqIO.parse(infile, 'fasta'):\n if not record.id in Tax2Drop:\n SeqIO.write(record, outfile, 'fasta')\n \n # only do coverage trimming if reads provided\n Contigs2Drop = [] # this will be empty if no reads given to gather by coverage\n if forReads:\n #check if BAM present, if so skip running\n if not os.path.isfile(os.path.join(args.workdir, blobBAM)): \n # index\n bwa_index = ['bwa','index', os.path.basename(sourTax)] \n status('Building BWA index')\n printCMD(bwa_index)\n subprocess.run(bwa_index, cwd=args.workdir, stderr=DEVNULL)\n #mapped reads to assembly using BWA\n bwa_cmd = ['bwa','mem',\n '-t', str(args.cpus),\n os.path.basename(sourTax), # assembly index base\n forReads] \n if revReads:\n bwa_cmd.append(revReads)\n\n #run BWA and pipe to samtools sort\n status('Aligning reads to assembly with BWA')\n printCMD(bwa_cmd)\n p1 = subprocess.Popen(bwa_cmd, cwd=args.workdir,\n stdout=subprocess.PIPE, stderr=DEVNULL)\n p2 = subprocess.Popen(['samtools', 'sort', \n '--threads', str(bamthreads),\n '-o', blobBAM, '-'], cwd=args.workdir,\n stdout=subprocess.PIPE, stderr=DEVNULL,\n stdin=p1.stdout)\n p1.stdout.close()\n p2.communicate()\n subprocess.run(['samtools', 'index', blobBAM], cwd=args.workdir)\n\n #now calculate coverage from BAM file\n status('Calculating read coverage per contig')\n FastaBed = os.path.join(args.workdir, 'assembly.bed')\n lengths = []\n with open(FastaBed, 'w') as bedout:\n with open(sourTax, 'rU') as SeqIn:\n for record in SeqIO.parse(SeqIn, 'fasta'):\n bedout.write('{:}\\t{:}\\t{:}\\n'.format(record.id, 0, len(record.seq)))\n lengths.append(len(record.seq))\n \n N50 = calcN50(lengths)\n Coverage = {}\n coverageBed = os.path.join(args.workdir, 'coverage.bed')\n cov_cmd = ['samtools', 'bedcov', os.path.basename(FastaBed), blobBAM] \n printCMD(cov_cmd)\n with open(coverageBed, 'w') as bed_out:\n for line in execute(cov_cmd, args.workdir):\n bed_out.write(line)\n\n if not line or line.startswith('\\n') or line.count('\\t') < 3:\n continue\n\n line = line.strip()\n cols = line.split('\\t')\n cov = int(cols[3]) / float(cols[2])\n Coverage[cols[0]] = (int(cols[2]), cov)\n \n #get average coverage of N50 contigs\n n50Cov = []\n for k,v in Coverage.items():\n if args.debug:\n print('{:}; Len: {:}; Cov: {:.2f}'.format(k, v[0], v[1]))\n if v[0] >= N50:\n n50Cov.append(v[1])\n n50AvgCov = sum(n50Cov) / len(n50Cov)\n minpct = args.mincovpct / 100\n # should we make this a variable? 5% was something arbitrary\n min_coverage = float(n50AvgCov * minpct) \n status('Average coverage for N50 contigs is {:}X'.format(int(n50AvgCov)))\n \n #Start list of contigs to drop \n for k,v in Coverage.items():\n if v[1] <= min_coverage:\n Contigs2Drop.append(k)\n status('Found {:,} contigs with coverage less than {:.2f}X ({:}%)'.\n format(len(Contigs2Drop), min_coverage, args.mincovpct))\n \n if args.debug:\n print('Contigs dropped due to coverage: {:,}'.format(','.join(Contigs2Drop)))\n print('Contigs dropped due to taxonomy: {:,}'.format(','.join(Tax2Drop)))\n \n DropFinal = Contigs2Drop + Tax2Drop\n DropFinal = set(DropFinal)\n status('Dropping {:,} total contigs based on taxonomy and coverage'.format(len(DropFinal)))\n with open(args.outfile, 'w') as outfile, open(sourTax, 'rU') as seqin:\n for record in SeqIO.parse(seqin, 'fasta'):\n if not record.id in DropFinal:\n SeqIO.write(record, outfile, 'fasta')\n \n numSeqs, assemblySize = fastastats(args.outfile)\n status('Sourpurged assembly is {:,} contigs and {:,} bp'.\n format(numSeqs, assemblySize))\n if '_' in args.outfile:\n nextOut = args.outfile.split('_')[0]+'.rmdup.fasta'\n elif '.' in args.outfile:\n nextOut = args.outfile.split('.')[0]+'.rmdup.fasta'\n else:\n nextOut = args.outfile+'.rmdup.fasta'\n \n if checkfile(sourmashTSV):\n baseinput = os.path.basename(args.input)\n if '.' in baseinput:\n baseinput = baseinput.rsplit('.',1)[0]\n\n os.rename(sourmashTSV, baseinput+'.sourmash-taxonomy.csv')\n \n if not args.debug:\n SafeRemove(args.workdir)\n \n if not args.pipe:\n status('Your next command might be:\\n\\tAAFTF rmdup -i {:} -o {:}\\n'.format(args.outfile, nextOut))\n","sub_path":"AAFTF/sourpurge.py","file_name":"sourpurge.py","file_ext":"py","file_size_in_byte":9815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"58748984","text":"########### Python 2.7 #############\nimport httplib, urllib, base64\n\nheaders = {\n # Request headers includes endpoint key\n # You can use the authoring key instead of the endpoint key.\n # The authoring key allows 1000 endpoint queries a month.\n 'Ocp-Apim-Subscription-Key': 'YOUR-KEY',\n}\n\nparams = urllib.urlencode({\n # Text to analyze\n 'q': 'turn on the left light',\n # Optional request parameters, set to default values\n 'verbose': 'false',\n})\n\n# HTTP Request\ntry:\n # LUIS endpoint HOST for westus region\n conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')\n\n # LUIS endpoint path\n # includes public app ID\n conn.request(\"GET\", \"/luis/v2.0/apps/df67dcdb-c37d-46af-88e1-8b97951ca1c2?%s\" % params, \"{body}\", headers)\n\n response = conn.getresponse()\n data = response.read()\n\n # print HTTP response to screen\n print(data)\n conn.close()\nexcept Exception as e:\n print(\"[Errno {0}] {1}\".format(e.errno, e.strerror))\n\n####################################","sub_path":"documentation-samples/endpoint-api-samples/python/quickstart-call-endpoint-2-7.py","file_name":"quickstart-call-endpoint-2-7.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"539567711","text":"# We've written some code below, but it's erroring out. Read\n# through the function code and the line where it's called,\n# and rewrite what is necessary to make it run. Remember,\n# you're not trying to change how the function works --\n# you're just trying to fix it!\n#\n# Hint: you can solve this by either changing the function\n# header or by changing the function call. You shouldn't\n# change the function body!\n#\n# Function name: cocaColaHabit\n# Parameters: cokesPerWeek (an integer)\n# pricePerCoke (a float)\n# flavor (a string)\n# Returns: a string, summarizing how bad the addiction is\ndef cocaColaHabit(flavor, cokesPerWeek, pricePerCoke):\n # Don't change the body of this function!\n moneySpent = cokesPerWeek * pricePerCoke\n summary = \"Eh, you're okay.\"\n\n if cokesPerWeek > 10:\n summary = \"You're spending $\" + str(moneySpent) + \" a week on Coke!\"\n\n elif flavor == \"Vanilla\":\n summary = \"You're so addicted you think Vanilla Coke is good...\"\n\n return summary\n\n\nresult = cocaColaHabit(\"Vanilla\", 1.75, 8)\nprint(result)\n\n\n","sub_path":"Unit3/Chapter 3.1 to 3.4/3.4.5 Coding Exercise 1.py","file_name":"3.4.5 Coding Exercise 1.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"391199251","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 11 21:27:48 2018\n\n@author: michi\n\"\"\"\n\nimport datetime as dt\nimport json\nimport os\nimport subprocess\nimport sys\nimport time\nimport urllib.request as url\n\nfrom ILoggable import ILoggable\n\n# In[]\nclass IDataProvider(ILoggable):\n \n\n rawJsonData = b'{\"id\":123,\"author\":\"Test Author\",\"start\":\"2018-04-23T17:15:00.000Z\",'\n rawJsonData += b'\"stop\":\"2018-04-23T18:15:00.000Z\",\"follower_id\":10,\"signalgraph_id\":9,'\n rawJsonData += b'\"signal_clioptions\":\"-t 10\",\"follower_clioptions\":\"-t 10\",'\n rawJsonData += b'\"created_at\":\"2018-04-22T14:15:47.415Z\",\"updated_at\":\"2018-04-22T15:13:34.688Z\",'\n rawJsonData += b'\"url\":\"http://127.0.0.1:3000/meassurements/123.json\"}'\n \n def __init__(self):\n raise NotImplementedError\n \n def requestMeasurement(self, measurementId):\n raise NotImplementedError\n \n def requestFollower(self):\n raise NotImplementedError\n \n def requestSignalGraph(self):\n raise NotImplementedError\n\n\n# In[]\nclass RubyOnRailsDataProvider(IDataProvider):\n _ip = None\n _port = None\n\n # In[] \n def __init__(self, ip, port):\n self._ip = ip\n self._port = port\n \n \n # In[]\n def requestMeasurement(self, measurementId): \n socketPath = \"http://\" + str(self._ip) + \":\"\n socketPath += str(self._port) + \"/meassurements/\" #typo\n socketPath += str(measurementId) + \".json\"\n self.log(socketPath)\n \n response = url.urlopen(socketPath)\n jsonResponse = response.read()\n responseContents = json.loads(jsonResponse)\n self.log(responseContents)\n \n dateTimeFormat = \"%Y-%m-%dT%H:%M:%S\"\n exactBegin = dt.datetime.strptime(responseContents[\"start\"].split(\".\")[0], dateTimeFormat)\n exactEnd = dt.datetime.strptime(responseContents[\"stop\"].split(\".\")[0], dateTimeFormat)\n \n returnInformation = {}\n returnInformation[\"id\"] = responseContents[\"id\"]\n returnInformation[\"exactBegin\"] = exactBegin\n returnInformation[\"exactEnd\"] = exactEnd\n returnInformation[\"followerId\"] = responseContents[\"follower_id\"]\n returnInformation[\"signalGraphId\"] = responseContents[\"signalgraph_id\"]\n self.log(returnInformation)\n return returnInformation\n\n\n # In[] \n def requestFollower(self):\n socketPath = \"http://\" + str(arguments.ip) + \":\" + str(arguments.port) + \"/followers/\"\n socketPath += str(followerId) + \".json\"\n \n response = url.urlopen(socketPath)\n jsonResponse = response.read()\n \n responseContents = json.loads(jsonResponse)\n debugLog(\"\\n\" + str(responseContents) + \"\\n\")\n debugLog(responseContents[\"filepath\"])\n \n return responseContents[\"filepath\"], responseContents[\"clioptions\"]\n \n\n # In[] \n def requestSignalGraph(self):\n socketPath = \"http://\" + str(arguments.ip) + \":\" + str(arguments.port) + \"/signalgraphs/\"\n socketPath += str(signalGraphId) + \".json\"\n \n response = url.urlopen(socketPath)\n jsonResponse = response.read()\n \n responseContents = json.loads(jsonResponse)\n debugLog(\"\\n\" + str(responseContents) + \"\\n\")\n debugLog(responseContents[\"filepath\"])\n \n return responseContents[\"filepath\"], responseContents[\"clioptions\"] \n ","sub_path":"dataproviders/SchedulerDataProvider.py","file_name":"SchedulerDataProvider.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"588545082","text":"# Copyright (c) 2019 fortiss GmbH\n#\n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\n\nimport os\nimport matplotlib\nmatplotlib.use('PS')\nimport unittest\nimport tensorflow as tf\nfrom tf_agents.environments import tf_py_environment\n\nfrom modules.runtime.scenario.scenario_generation.uniform_vehicle_distribution \\\n import UniformVehicleDistribution\nfrom modules.runtime.scenario.scenario_generation.deterministic \\\n import DeterministicScenarioGeneration\nfrom modules.runtime.commons.parameters import ParameterServer\nfrom modules.runtime.viewer.matplotlib_viewer import MPViewer\n\nfrom src.rl_runtime import RuntimeRL\nfrom src.observers.nearest_state_observer import ClosestAgentsObserver\nfrom src.wrappers.dynamic_model import DynamicModel\nfrom src.wrappers.tfa_wrapper import TFAWrapper\nfrom src.evaluators.goal_reached import GoalReached\nfrom src.agents.sac_agent import SACAgent\nfrom src.runners.tfa_runner import TFARunner\n\ntf.compat.v1.enable_v2_behavior()\n\nclass PyRunnerTests(unittest.TestCase):\n @staticmethod\n def test_runner():\n params = ParameterServer(\n filename=\"tests/data/deterministic_scenario_test.json\")\n base_dir = os.path.dirname(os.path.dirname(__file__))\n params[\"BaseDir\"] = base_dir\n scenario_generation = DeterministicScenarioGeneration(num_scenarios=3,\n random_seed=0,\n params=params)\n state_observer = ClosestAgentsObserver(params=params)\n action_wrapper = DynamicModel(params=params)\n evaluator = GoalReached(params=params)\n viewer = MPViewer(params=params,\n x_range=[-30,30],\n y_range=[-20,40],\n follow_agent_id=True)\n runtimerl = RuntimeRL(action_wrapper=action_wrapper,\n observer=state_observer,\n evaluator=evaluator,\n step_time=0.2,\n viewer=viewer,\n scenario_generator=scenario_generation,\n render=False)\n tfa_env = tf_py_environment.TFPyEnvironment(TFAWrapper(runtimerl))\n sac_agent = SACAgent(tfa_env,\n params=params)\n tfa_runner = TFARunner(tfa_env,\n sac_agent,\n params=params,\n unwrapped_runtime=runtimerl)\n tfa_runner.collect_initial_episodes()\n \n # main functionalities\n tfa_runner.train()\n tfa_runner.visualize()\n tfa_runner.evaluate()\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/py_runner_tests.py","file_name":"py_runner_tests.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"278964845","text":"# Chapter-3: Arrays\n# Array-Remove-At\n# Given array and an index into array, remove and return the array value at that index. Do this without using built-in methods except pop()\n\n# The built-in method to use for this is \"pop(idx)\" - array.pop(idx) will return the element at index 'idx'\n\n# assume the arguments passed are a non-empty array, index value within the length of the array\ndef removeAt(arr, idx):\n result = arr[idx]\n for i in range(idx, len(arr) - 1):\n arr[i] = arr[i + 1]\n arr.pop()\n return result\n\nmyArr = [1,2,3,4,5,6]\nmyIdx = 3\nprint(\"The original array is {}\").format(myArr)\nprint(\"The item at index {} = {} and the changed array is {}\").format(myIdx, removeAt(myArr, myIdx), myArr)\n","sub_path":"Chapter-03-Arrays/Array-Remove-At/Array-Remove-At.py","file_name":"Array-Remove-At.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"100211140","text":"import sys\nimport fileinput\nimport subprocess\nimport time\n\n# replace all occurences of 'sit' with 'SIT'\nprev = '0.07'\nfor i in range(31):\n\tbondLength = 0.70 + 0.01*i\n\tbondLength = \"{}\".format(bondLength)\n\tfor j, line in enumerate(fileinput.input('H2.com.tmp', inplace=1)):\n\t\tsys.stdout.write(line.replace(prev, bondLength))\n\n\tcommand = 'g16 H2.com.tmp'\n\tprocess = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\n\toutput, error = process.communicate()\n\n\twith open('testdata.txt', 'a') as f:\n\t\twith open('H2.com.log', 'r') as my_data_file:\n\t\t\tlines = my_data_file.readlines()\n\t\t\tfor i, line in enumerate(lines):\n\t\t\t\tif i == 358:\n\t\t\t\t\tline_len = len(line)\n\t\t\t\t\tfor j in range(line_len):\n\t\t\t\t\t\tif ord(line[j]) >= 48 and ord(line[j]) <= 57:\n\t\t\t\t\t\t\tstring = line[j:len(line)-1]\n\t\t\t\t\t\t\tstring = string.replace(\"D\", \"e\")\n\t\t\t\t\t\t\tf.write(bondLength)\n\t\t\t\t\t\t\tf.write(\"\\t\")\n\t\t\t\t\t\t\tf.write(string)\n\t\t\t\t\t\t\tf.write(\"\\n\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tbreak\n\tprev = bondLength\n","sub_path":"CompMat/hmc/H2/3-21G/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"289175077","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Feb 19 21:20:46 2019\r\n\r\n@author: share\r\n\"\"\"\r\n\r\nimport pyodbc\r\nimport pandas as pd\r\nimport numpy as np\r\nimport geopandas as gpd\r\nfrom shapely.geometry import Point\r\nfrom sqlalchemy import create_engine\r\n\r\n\r\nclass db():\r\n def __init__(self, database_name,driver = 'SQL Server Native Client 11.0', \r\n server = 'WIN-4NLQSKDG430\\DIDISERVER', user = \"sa\", \r\n password = \"gyjh123123#\", charset=\"utf-8\"):\r\n self.database = database_name\r\n self.driver = driver\r\n self.server = server\r\n self.user = user\r\n self.password = password\r\n self.charset = charset\r\n \r\n self.engin_url= 'mssql+pyodbc://sa:gyjh123123#@WIN-4NLQSKDG430\\DIDISERVER/{}?driver=SQL+Server+Native+Client+11.0'.format(self.database)\r\n self.engin = create_engine(self.engin_url, echo=False)\r\n self.conn = pyodbc.connect(driver=self.driver, server=self.server, user=self.user, \r\n password=self.password, database=self.database, charset=self.charset)\r\n self.cur = self.conn.cursor()\r\n \r\n def write_table(self, df, name, schema=None, if_exists='fail', index=False, index_label=None, chunksize=None, dtype=None):\r\n '''\r\n 将dataframe写入数据库\r\n args:\r\n df: 要写入的dataframe\r\n name: 数据库名\r\n '''\r\n df.to_sql(name, self.engin, schema, if_exists, index, index_label, chunksize, dtype)\r\n \r\n def fetch_sql(self, select_sql, columns=[]):\r\n '''\r\n 对链接的数据库执行select语句,并将结果list形式返回\r\n args:\r\n select_sql: sql语句,str格式\r\n \r\n '''\r\n data = self.cur.execute(select_sql).fetchall()\r\n return data\r\n \r\n def close(self):\r\n self.conn.close()\r\n \r\n \r\ndef ord2df(selected_list, columns=[], filename='C:/Users/share/Desktop/Project/Zhaocheng_Du/data/loc_order_sample/order_col.txt'):\r\n '''\r\n 将select出的order list转化成Dataframe\r\n args:\r\n columns: 为df赋予的列名\r\n '''\r\n if (not columns):\r\n columns = eval(open(filename).read())\r\n df = pd.DataFrame(np.array(selected_list), columns=columns)\r\n return df\r\n\r\ndef meg2df(selected_list, columns=[], filename='C:/Users/share/Desktop/Project/Zhaocheng_Du/data/loc_order_sample/meg_col.txt'):\r\n '''\r\n 将select出的order list转化成Dataframe\r\n args:\r\n columns: 为df赋予的列名\r\n '''\r\n if (not columns):\r\n columns = eval(open(filename).read())\r\n df = pd.DataFrame(np.array(selected_list), columns=columns)\r\n return df\r\n\r\ndef ana2df(selected_list, columns=[], filename='C:/Users/share/Desktop/Project/Zhaocheng_Du/data/loc_order_sample/analysis_col.txt'):\r\n '''\r\n 将select出的order list转化成Dataframe\r\n args:\r\n columns: 为df赋予的列名\r\n '''\r\n if (not columns):\r\n columns = eval(open(filename).read())\r\n df = pd.DataFrame(np.array(selected_list), columns=columns)\r\n return df\r\n\r\ndef loc2df(selected_list, columns=[], filename='C:/Users/share/Desktop/Project/Zhaocheng_Du/data/loc_order_sample/loc_col.txt'):\r\n '''\r\n 将select出的loc list转化成Dataframe\r\n args:\r\n columns: 为df赋予的列名\r\n '''\r\n if (not columns):\r\n columns = eval(open(filename).read())\r\n df = pd.DataFrame(np.array(selected_list), columns=columns)\r\n return df\r\n\r\ndef read_shp(file, path='C:/Users/share/Desktop/Project/Zhaocheng_Du/data/shenzhennet/'):\r\n '''\r\n 将shp文件读入成geopandas文件,并且返回该文件\r\n args:\r\n file: 读取的文件(不含路径)\r\n path: 文件的路径\r\n '''\r\n file_shp = path + file\r\n shp_gdf = gpd.GeoDataFrame.from_file(file_shp,encoding='gb18030')\r\n return shp_gdf\r\n\r\ndef df2gdf(dataframe, lon_col, lat_col):\r\n '''\r\n 将dataframe的点要素转成geodataframe的格式,并返回该文件\r\n args:\r\n lon_col: str类型,lon的列名\r\n lat_col: str类型,lat的列名\r\n '''\r\n lon = [float(i) for i in dataframe[lon_col]]\r\n lat = [float(i) for i in dataframe[lat_col]]\r\n point = pd.Series([Point(lon[i],lat[i]) for i in range(len(lon))])\r\n dataframe['geometry'] = point\r\n geodataframe = gpd.GeoDataFrame(dataframe)\r\n return geodataframe\r\n\r\ndef SaveGdf_as_Shp(gdf, filename, encoding='gb18030'):\r\n '''\r\n 将geodataframe保存成为shp文件\r\n args:\r\n filename: 保存的文件名\r\n '''\r\n gdf.to_file(filename)\r\n\r\ndef poly_pnt_count(poly, point, poly_id):\r\n '''\r\n 计算poly中有多少point\r\n args:\r\n poly: 多边形shp, gdf格式\r\n point: 点要素, gdf格式\r\n poly_id: 多边形要素的id, str格式\r\n return:\r\n geodataframe\r\n '''\r\n poly_with_pnt = gpd.sjoin(poly, point, how='inner',op='intersects')\r\n poly_with_pnt['pointnum'] = 1\r\n point_num = poly_with_pnt.groupby(poly_id)['pointnum'].sum()\r\n poly_with_pnt = poly_with_pnt.drop('pointnum', axis=1).set_index(poly_id)\r\n result = pd.concat([poly_with_pnt, point_num], axis=1)\r\n result = result.fillna({'pointnum':0})\r\n # result.plot(column='pointnum',cmap='OrRd', legend=True)\r\n return result\r\n\r\ndef make_buffer(gdf, distance):\r\n '''\r\n 对点要素/线要素制作缓冲区,返回polygon的gdf格式\r\n args:\r\n distance: 制作缓冲区的距离\r\n '''\r\n lat_meter = 111000\r\n lon_meter = 111000 * np.cos(np.pi * 22.55 / 180)\r\n gdf['geometry'] = gdf.geometry.buffer(distance / 111000)\r\n return gdf\r\n ","sub_path":"Project-Didi metro Analysis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"409188744","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 2 22:24:27 2017\n\n@author: Mikhail Belousov\n\"\"\"\nimport osa\n#%%\nurl = 'http://www.webservicex.net/ConvertTemperature.asmx?WSDL'\nclient = osa.client.Client(url)\nresponse = client.service.ConvertTemp(Temperature=12.5, FromUnit=\"degreeCelsius\", ToUnit = \"degreeFahrenheit\")\nprint(response)\n\n#%%\nurl2 = 'http://www.webservicex.net/ConvertSpeed.asmx?WSDL'\nclient2 = osa.client.Client(url2)\nresponse2 = client2.service.ConvertSpeed(speed=500, FromUnit=\"centimetersPersecond\", ToUnit = \"milesPerhour\")\nprint(response2)\n\n#%%\n\nurl3 = 'http://fx.currencysystem.com/webservices/CurrencyServer4.asmx?WSDL'\nclient3 = osa.client.Client(url3)\n#print (client3.types)\n#response3 = client3.service.CountryToCurrency(country='Germany', activeOnly=False)\nresponse3 = client3.service.ConvertToNum(fromCurrency='USD', toCurrency='RUB', amount=1, rounding=True)\nprint (response3)","sub_path":"Netology34/soap_practise.py","file_name":"soap_practise.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"220175615","text":"class Solution(object):\n def threeSum(self, nums):\n res = []\n nums.sort()\n for i in range(len(nums) - 2):\n if i > 0 and nums[i] == nums[i - 1]: continue\n if nums[i] > 0: break\n three_sum = self.twoSum(nums, i + 1, nums[i], 0 - nums[i])\n if len(three_sum) > 0: res.extend(three_sum)\n return res\n\n def twoSum(self, nums, i, first, target):\n res = []\n visited = set([])\n j = i\n while i < len(nums):\n if nums[i] in visited:\n res.append([first, target - nums[i], nums[i]])\n visited.remove(nums[i])\n elif nums[i] <= target / 2 and (i == j or nums[i] != nums[i - 1]):\n # situation when target = 4, list = [2,2,2,2...]\n # if i = j, means the first element, we must add it into the set\n visited.add(target - nums[i])\n i += 1\n return res","sub_path":"medium/mediumCode/Amazon_leetcode/ThreeSum_15.py","file_name":"ThreeSum_15.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"477931364","text":"from math import *\n\ndef p9():\n\tfor i in range(1,1000):\n\t\tfor j in range(i,1000):\n\t\t\tk = (sqrt(i**2+j**2))\n\t\t\tif isPyth(i,j) and i + j + k == 1000:\n\t\t\t\tprint (i,j,k)\n\t\t\t\tprint (i*j*k)\n\t\t\t\n\ndef isPyth(a,b):\n\tc= a**2+b**2\n\treturn c%sqrt(c)== 0\n\t\n\nif __name__ == \"__main__\":\n\tp9()\n","sub_path":"p9.py","file_name":"p9.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"572411239","text":"import numpy as np\nimport pandas as pd\nimport warnings\n\nfrom .forecast_models.ETS import ForecastETS\nfrom .forecast_models.ARIMA import ForecastARIMA\nfrom .forecast_models.TBATS import ForecastTBATS\nfrom .forecast_models.LGBM import ForecastLGBM\n\nfrom .utils.utils import split_weekends,compute_y_hat,_return_time_feats\nfrom .recon.recon import Reconciliation\n\nimport pdb\nclass TimeHierarchy():\n '''Empty docstring'''\n def __init__(self,df,n_nodes,col_name,\n time_name ='timestamp',\n sep_weekend = True,\n test_size = None,\n verbose = 0,\n features = [],\n time_features = []):\n '''Empty docstring'''\n max_node,min_node = max(n_nodes),min(n_nodes)\n self.verbose = verbose\n self.test_size = test_size\n self.n_nodes = [int(i/min_node) for i in np.sort(n_nodes)]\n ## make sure that n_nodes provides a coherent tree structure\n assert all(max(self.n_nodes) % n == 0 for n in self.n_nodes) \n self.k = [int(max_node/(i*min_node)) for i in self.n_nodes]\n \n self.time_name = time_name\n self.col_name = col_name\n self.features = features\n self.time_features = time_features\n #\n # if n_nodes specifies it we aggregate data before tree creation, \n # this is done to reduce the time-step in the bottom level of the tree\n if min_node>1:\n df2 = pd.DataFrame(df[self.time_name][::min_node]).reset_index(drop=True)\n df2[self.col_name] = df[self.col_name].groupby(df.index // min_node).sum()\n for f in features:\n df2[f] = df[f].groupby(df.index // min_node).mean()\n \n else:\n df2 = df.copy()\n \n if sep_weekend:\n self.df,self.df_end = split_weekends(df2)\n self.df,self.df_end = self.df.reset_index(drop=True),self.df_end.reset_index(drop=True)\n else:\n df2 = df2[:max(k)*(df2.shape[0]//max(k))]\n self.df,self.df_end = df2,pd.DataFrame()\n \n self.create_hierarchy(self.df,self.col_name) # create both short and long format hierarchies\n self.y_true_test = compute_y_hat(self.hierarchy_short_test)[1::][0]\n \n self.timedeltas = [] # time deltas between values for the hierarchy levels\n for k in self.hierarchy:\n self.timedeltas.append(self.hierarchy[k][self.time_name][1]-self.hierarchy[k][self.time_name][0])\n \n def __repr__(self):\n s = ''\n for k in self.hierarchy:\n s +='K = '+str(k) + ' --> nodes = '\n for i in np.unique(self.hierarchy[k]['group_id']):\n s += str(int(i))+' '\n s +='\\n'\n return s\n \n def create_hierarchy(self,df,col_name,k = None,time_name = None):\n '''Empty docstring'''\n k = k if k is not None else self.k\n time_name = time_name if time_name is not None else self.time_name\n df = df[:int(max(k)*(df.shape[0]//max(k)))].copy()\n \n self.hierarchy = {} # Dict[int,pd.Dataframe]\n for j,kk in enumerate(k):\n self.hierarchy[j] = pd.DataFrame(df[time_name][::kk].values,columns=[time_name])\n if self.verbose:\n print(len(df)//kk)\n \n _aux = np.arange(len(df))//kk\n self.hierarchy[j][col_name] = df[col_name].groupby(_aux).sum()\n for f in self.features:\n self.hierarchy[j][f] = df[f].groupby(_aux).mean()\n #create time features \n for f in self.time_features:\n self.hierarchy[j][f] = _return_time_feats(self.hierarchy[j][time_name],f) \n \n len_max = len(self.hierarchy[0])\n # create short hierarchy n values per node\n self.hierarchy_short = {} # Dict[int,Dict[int,pd.Dataframe]]\n for j in range(len(k)):\n self.hierarchy[j]['group_id'] = np.tile(np.arange(k[0]/k[j]),len_max)\n tmp = {}\n for i in np.unique(self.hierarchy[j]['group_id']):\n tmp[i] = self.hierarchy[j][self.hierarchy[j]['group_id'] == i].reset_index(drop=True)\n \n for f in self.features:\n tmp[i][f] = self.hierarchy[0][f]\n \n self.hierarchy_short[j] = tmp\n \n if self.test_size is not None: ## create test trees, in both formats\n self.hierarchy_short_test = {}\n self.hierarchy_test = {}\n for k,n in zip(self.hierarchy,self.n_nodes):\n self.hierarchy_test[k] = self.hierarchy[k][-self.test_size*int(n):] #long format test treee\n self.hierarchy[k] = self.hierarchy[k][:-self.test_size*int(n)]\n tmp_dict = {}\n for k2 in self.hierarchy_short[k]: #short format test tree\n tmp_dict[k2] = self.hierarchy_short[k][k2][-self.test_size:]\n self.hierarchy_short[k][k2] = self.hierarchy_short[k][k2][:-self.test_size]\n self.hierarchy_short_test[k] = tmp_dict\n self.len_max = len(self.hierarchy[0])\n \n \n \n def fit_ets(self,use_short=True,trend = 'add',seasonal = 'add',seasonal_periods = 100,**kwargs):\n '''Empty docstring'''\n self.ETS = ForecastETS(self.col_name,self.n_nodes,\n hierarchy = self.hierarchy,\n hierarchy_short = self.hierarchy_short,\n use_short = use_short)\n \n self.ETS.fit(trend = trend,seasonal = seasonal,seasonal_periods = seasonal_periods,**kwargs)\n \n def fit_arima(self,use_short=True,order = (1,0,0),seasonal_order = (0,0,0,0),**kwargs):\n '''Empty docstring'''\n self.ARIMA = ForecastARIMA(self.col_name,self.n_nodes,\n hierarchy = self.hierarchy,\n hierarchy_short = self.hierarchy_short,\n use_short = use_short)\n \n self.ARIMA.fit(order = order, seasonal_order = seasonal_order,**kwargs)\n \n def fit_tbats(self,use_short=True,seasonal_periods = None,**kwargs):\n '''Empty docstring'''\n self.TBATS = ForecastTBATS(self.col_name,self.n_nodes,\n hierarchy = self.hierarchy,\n hierarchy_short = self.hierarchy_short,\n use_short = use_short)\n \n self.TBATS.fit(seasonal_periods = seasonal_periods,**kwargs)\n \n def fit_lgbm(self,use_short=True,look_back = 24,features=None,**kwargs):\n '''Empty docstring'''\n \n self.LGBM = ForecastLGBM(self.col_name,self.n_nodes,\n hierarchy = self.hierarchy,\n hierarchy_short = self.hierarchy_short,\n use_short = use_short,\n look_back = look_back,\n features = features)\n \n self.LGBM.fit(**kwargs)\n \n def _get_forecast_model(self,forecast_method):\n assert forecast_method in dir(self)\n \n if forecast_method == 'ETS':\n return self.ETS\n elif forecast_method == 'LGBM':\n return self.LGBM\n elif forecast_method == 'ARIMA':\n return self.ARIMA\n elif forecast_method == 'TBATS':\n return self.TBATS\n \n def create_recon(self,\n recon_method,\n forecast_method,\n **kwargs):\n '''Wrapper Around Reconciliation class\n initialized the class and adds it as an attribute(.Recon) to the Time_Hierarchy class\n \n Possibel recon_method:\n GLS_methods : 'BU','COV','blockCOV','blockGLASSO','GLASSO','VAR','STR','OLS','CCS','markov'\n ML_methods = 'LGBM'\n \n forecast_method (must be already trained) : 'ETS','LGBM','TBATS','ARIMA' \n **kwargs are given to the Reconciliation class'''\n forecast_model = self._get_forecast_model(forecast_method)\n \n self.Recon = Reconciliation(self.n_nodes,self.col_name,\n method = recon_method,\n error_df = forecast_model.error_df,\n model_tree = forecast_model.model_tree,\n hierarchy_short = self.hierarchy_short,\n **kwargs)\n","sub_path":"TH/.ipynb_checkpoints/TH-checkpoint.py","file_name":"TH-checkpoint.py","file_ext":"py","file_size_in_byte":8373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"583912321","text":"from django.shortcuts import render, redirect,get_object_or_404, HttpResponseRedirect\nfrom django.contrib.auth.models import User,auth\nfrom django.contrib.auth import logout, authenticate, login\nfrom .models import Category, UnitMeasure,Product,Customer,ProductWishlist,CartItem,Address,Order,OrderTrack\nfrom .forms import ProductForm,CategoryForm\nfrom django.http import JsonResponse\nfrom django.db.models import Sum\nfrom django.utils.crypto import get_random_string\nimport datetime\n\n# password for test user is demo12345\n# Create your views here.\ndef index(request):\n # print(request.user) \n # print(User.objects.last().is_staff)\n category_name = request.GET.get('category')\n category = Category.objects.filter(name=category_name).last()\n \n if category_name == None:\n products = Product.objects.all()\n else:\n products = Product.objects.filter(category_id=category.id)\n # print(products.exists()) \n categories = Category.objects.all()\n \n context = { \n \"products\" : products,\n \"categories\" : categories,\n }\n \n if request.user.is_anonymous:\n return redirect(\"/login\") \n return render(request, 'index.html',context)\n\ndef loginUser(request):\n if request.method==\"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n print(username, password)\n\n # check if user has entered correct credentials\n user = authenticate(username=username, password=password)\n\n if user is not None:\n # A backend authenticated the credentials\n login(request, user)\n request.session['user_id'] = user.id\n customer = Customer.objects.filter(user_id=user.id).last()\n print(\"===========Customer ID=======\",customer.id)\n request.session['customer_id'] = customer.id\n return redirect(\"/\")\n else:\n # No backend authenticated the credentials\n return render(request, 'login.html')\n\n return render(request, 'login.html')\n\ndef logoutUser(request):\n logout(request)\n return redirect(\"/login\")\n\ndef registerUser(request):\n if request.method==\"POST\":\n first_name = request.POST.get('first_name')\n last_name = request.POST.get('last_name')\n username = request.POST.get('username')\n email = request.POST.get('email')\n password1 = request.POST.get('password1')\n password2 = request.POST.get('password2')\n \n if password1==password2:\n if User.objects.filter(username=username).exists():\n print(\"Username taken\")\n # messages.info(request,\"Username taken\")\n return redirect(\"register\")\n elif User.objects.filter(email=email).exists():\n print(\"Email taken\")\n # messages.info(request,\"Email taken\")\n return redirect(\"register\")\n else:\n user = User.objects.create_user(username=username,password=password1,first_name=first_name,last_name=last_name,email=email)\n user.save()\n customer = Customer(user_id=user.id)\n customer.save()\n print(\"customer created\")\n print('user created')\n else:\n print(\"password not matching..\")\n # messages.info(request,'password not matching..')\n return redirect(\"register\")\n return redirect(\"/login\")\n else:\n return render(request, 'register.html')\n \n \ndef add_show(request):\n if request.method == 'POST':\n fm = ProductForm(request.POST,request.FILES)\n print(request.FILES)\n print(fm.is_valid())\n if fm.is_valid():\n fm.save()\n return redirect(\"/\")\n else:\n fm = ProductForm()\n context = {\"form\": fm,}\n return render(request, 'addandshow.html', context)\n\n\ndef product_detail(request,id):\n product = Product.objects.get(id=id)\n # product_wishlist = ProductWishlist.objects.get(product_id=product.id)\n try:\n product_wishlist = ProductWishlist.objects.filter(product_id=product.id).last()\n except ObjectDoesNotExist:\n product_wishlist = None\n \n context = { \n \"product\" : product,\n \"product_wishlist\" : product_wishlist,\n }\n return render(request, 'product_detail.html',context)\n\ndef category_creation(request):\n if request.method == 'POST':\n fm = CategoryForm(request.POST,request.FILES)\n print(request.FILES)\n print(fm.is_valid())\n if fm.is_valid():\n fm.save()\n return redirect(\"/\")\n else:\n fm = CategoryForm()\n context = {\"form\": fm,}\n return render(request, 'add_category.html', context)\n\ndef add_to_wishlist(request,product_id):\n if request.method == 'GET':\n result = ''\n product_wishlist = ProductWishlist.objects.filter(product_id=product_id).last()\n if product_wishlist == None:\n wishlist = ProductWishlist(customer_id=request.session.get('customer_id'),product_id=product_id,is_favourite=True)\n wishlist.save()\n result = \"Favourite\"\n else:\n product_wishlist.delete()\n return JsonResponse({'result': result })\n \ndef remove_wishlist(request,id):\n if request.method == 'GET':\n product_wishlist = ProductWishlist.objects.filter(id=id).last()\n # product_wishlist.is_favourite = False\n # product_wishlist.save()\n product_wishlist.delete()\n \n return redirect(\"/shop_wishlist\")\n \ndef shop_wishlist(request):\n print(\"Request Customer ID==========\",request.session.get('customer_id'))\n customer = Customer.objects.filter(id=request.session.get('customer_id')).last()\n wishlist_products = ProductWishlist.objects.filter(customer_id=customer.id,is_favourite=True)\n \n context = { \n \"wishlist_products\" : wishlist_products,\n }\n \n return render(request, 'shop_wishlist.html',context)\n \ndef shop_cart(request):\n cart_products = CartItem.objects.filter(customer_id=request.session.get('customer_id'),ordered=False)\n \n calculated_price = cart_products.aggregate(Sum('total_price'))\n \n customer = Customer.objects.filter(user_id=request.session.get('user_id')).last() \n address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n \n context = { \n \"cart_products\" : cart_products,\n \"cart_products_count\" : cart_products.count(),\n \"calculated_price\" : calculated_price[\"total_price__sum\"],\n \"customer\" : customer,\n \"address\" : address,\n }\n return render(request, 'shop_cart.html',context)\n\ndef myaccount(request):\n return render(request, 'myaccount.html')\n\ndef profile_creation(request):\n print(request.method)\n if request.method == 'POST':\n user_id = request.POST.get('user_id')\n phone_no = request.POST.get('phone_no')\n date_of_birth = request.POST.get('date_of_birth')\n gender = request.POST.get('gender')\n \n customer = Customer(user_id=user_id,phone_no=phone_no,date_of_birth=date_of_birth,gender=gender)\n # customer = Customer(user_id=user_id,phone_no=phone_no,gender=gender)\n \n registered_customer = Customer.objects.filter(user_id=request.session.get('user_id')).last()\n \n if registered_customer == None:\n customer.save()\n else:\n registered_customer.phone_no = phone_no\n registered_customer.date_of_birth = date_of_birth\n registered_customer.gender = gender\n registered_customer.save()\n \n return redirect(\"/profile\")\n else:\n return redirect(\"/profile\")\n \ndef profile(request):\n registered_customer = Customer.objects.filter(user_id=request.session.get('user_id')).last() \n context = { \n \"customer\" : registered_customer,\n }\n return render(request, 'profile.html',context)\n\ndef add_to_cart(request):\n print(request.session.get('customer_id'))\n if request.method == 'POST':\n product_id = request.POST.get('product_id')\n \n product = Product.objects.filter(id=product_id).last()\n \n total_calculated_price = product.price\n \n cart_item = CartItem(customer_id=request.session.get('customer_id'),product_id=product_id,total_price=total_calculated_price)\n cart_item.save()\n \n return redirect(\"/\")\n \ndef remove_cart(request):\n cart_item_id = request.GET.get('cart_item_id')\n cart_type = request.GET.get('cart_type')\n print(request)\n if cart_type == \"single\":\n print(\"Single\")\n cart_item = CartItem.objects.get(id=cart_item_id)\n cart_item.delete()\n else:\n print(\"All\")\n cart_items = CartItem.objects.filter(customer_id=request.session.get('customer_id'),ordered=False)\n cart_items.delete()\n \n return redirect(\"/shop_cart\")\n\ndef dynamic_add_to_cart(request):\n print(request.method)\n if request.method == 'POST':\n calculated_price = ''\n cart_item_id = request.POST.get('cart_item_id')\n quantity = request.POST.get('quantity')\n \n cart_item = CartItem.objects.filter(id=cart_item_id).last()\n \n if cart_item != None:\n cart_item.quantity = quantity\n \n total_price_for_item = int(quantity) * cart_item.product.price\n cart_item.total_price = total_price_for_item\n cart_item.save()\n \n calculated_price = CartItem.objects.filter(customer_id=request.session.get('customer_id'),ordered=False).aggregate(Sum('total_price'))\n \n return JsonResponse({'calculated_price': calculated_price[\"total_price__sum\"]})\n\n\ndef address_listing(request):\n customer = Customer.objects.filter(user_id=request.session.get('user_id')).last() \n address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n context = { \n \"customer\" : customer,\n \"address\" : address,\n }\n return render(request, 'my_addresses.html',context)\n\ndef address_form(request):\n customer = Customer.objects.filter(user_id=request.session.get('user_id')).last() \n address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n context = { \n \"customer\" : customer,\n \"address\" : address,\n }\n return render(request, 'address_form.html',context)\n\ndef setup_address(request):\n print(request.method)\n if request.method == 'POST':\n customer_id = request.POST.get('customer_id')\n address_details = request.POST.get('address_details')\n state = request.POST.get('state')\n city = request.POST.get('city')\n country = request.POST.get('country')\n pincode = request.POST.get('pincode')\n landmark = request.POST.get('landmark')\n resident_type = request.POST.get('resident_type')\n \n address = Address(customer_id=customer_id,address_details=address_details,state=state,city=city,country=country,pincode=pincode,landmark=landmark,resident_type=resident_type)\n \n registered_address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n \n if registered_address == None:\n address.save()\n else:\n registered_address.address_details = address_details\n registered_address.state = state\n registered_address.city = city\n registered_address.country = country\n registered_address.pincode = pincode\n registered_address.landmark = landmark\n registered_address.resident_type = resident_type\n registered_address.save()\n \n return redirect(\"/address_listing\")\n else:\n return redirect(\"/address_form\")\n \ndef remove_address(request,id):\n if request.method == 'GET':\n address = Address.objects.filter(id=id).last()\n address.is_active = False\n address.save()\n \n return redirect(\"/address_listing\")\n\ndef order_listing(request):\n orders = Order.objects.filter(customer_id=request.session.get('customer_id')).order_by('-id')\n context = { \n \"orders\" : orders,\n }\n return render(request, 'order_listing.html',context)\n\ndef order_detail(request,order_code):\n order = Order.objects.get(order_code=order_code)\n cart_items = CartItem.objects.filter(order_id=order.id)\n \n customer = Customer.objects.filter(user_id=request.session.get('user_id')).last() \n address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n context = { \n \"order\" : order,\n \"cart_items\" : cart_items,\n \"customer\" : customer,\n \"address\" : address,\n }\n return render(request, 'order_detail.html',context)\n\ndef place_order(request):\n if request.method == 'POST':\n payment_type = request.POST.get('payment_type')\n customer_id = request.session.get('customer_id')\n \n calculated_price = CartItem.objects.filter(customer_id=request.session.get('customer_id'),ordered=False).aggregate(Sum('total_price'))\n total_price = calculated_price[\"total_price__sum\"]\n \n order_code = get_random_string(15)\n \n address = Address.objects.filter(customer_id=request.session.get('customer_id'),is_active=True).last()\n \n order = Order(order_code=order_code,payment_type=payment_type,total_price=total_price,address_id=address.id,customer_id=request.session.get('customer_id'),status=\"CONFIRMED\")\n\n order.save()\n \n if order.save() == None:\n cart_items = CartItem.objects.filter(customer_id=request.session.get('customer_id'),ordered=False).update(ordered=True,order_id=order.id)\n OrderTrack.objects.create(order_id=order.id,customer_id=request.session.get('customer_id'),status=order.status,track_period=datetime.datetime.now())\n \n return redirect(\"/shop_cart\")\n \ndef update_status(request):\n if request.method == 'POST':\n order_code = request.POST.get('order_code')\n status = request.POST.get('status')\n order_delivered_date = None\n \n if status == \"DELIVERED\":\n order_delivered_date = datetime.datetime.now()\n\n order = Order.objects.get(order_code=order_code)\n order.status = status\n order.order_delivered_date = order_delivered_date\n order.save()\n \n order_track = OrderTrack.objects.filter(customer_id=request.session.get('customer_id'),order_id=order.id,status=order.status)\n \n if order_track.exists() == False:\n OrderTrack.objects.create(order_id=order.id,customer_id=request.session.get('customer_id'),status=order.status,track_period=datetime.datetime.now())\n \n return HttpResponseRedirect('/order_detail/'+order_code+'/')\n \ndef cancel_order(request):\n if request.method == 'POST':\n order_code = request.POST.get('order_code')\n \n order = Order.objects.get(order_code=order_code)\n order.status = \"ORDER CANCELLED\" \n order.save()\n \n return HttpResponseRedirect('/order_detail/'+order.order_code+'/')","sub_path":"shoppingcart/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"396789990","text":"\"\"\"Fan platform for dyson.\"\"\"\n\nfrom homeassistant.const import CONF_NAME\nimport logging\nimport voluptuous as vol\n\nfrom typing import Callable, List, Optional\nfrom homeassistant.components.fan import FanEntity, SPEED_HIGH, SPEED_LOW, SPEED_MEDIUM, SUPPORT_OSCILLATE, SUPPORT_SET_SPEED\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers import entity_platform, config_validation as cv\n\nfrom libdyson import FanSpeed\nfrom libdyson.const import MessageType\n\nfrom . import DysonEntity, DOMAIN\nfrom .const import DATA_DEVICES\n\n_LOGGER = logging.getLogger(__name__)\n\nATTR_NIGHT_MODE = \"night_mode\"\nATTR_DYSON_SPEED = \"dyson_speed\"\nATTR_DYSON_SPEED_LIST = \"dyson_speed_list\"\nATTR_AUTO_MODE = \"auto_mode\"\n\nSERVICE_SET_AUTO_MODE = \"set_auto_mode\"\nSERVICE_SET_DYSON_SPEED = \"set_speed\"\n\nSET_AUTO_MODE_SCHEMA = {\n vol.Required(ATTR_AUTO_MODE): cv.boolean,\n}\n\nSET_DYSON_SPEED_SCHEMA = {\n vol.Required(ATTR_DYSON_SPEED): cv.positive_int,\n}\n\nSPEED_LIST_HA = [SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH]\n\nSPEED_LIST_DYSON = [\n int(FanSpeed.SPEED_1.value),\n int(FanSpeed.SPEED_2.value),\n int(FanSpeed.SPEED_3.value),\n int(FanSpeed.SPEED_4.value),\n int(FanSpeed.SPEED_5.value),\n int(FanSpeed.SPEED_6.value),\n int(FanSpeed.SPEED_7.value),\n int(FanSpeed.SPEED_8.value),\n int(FanSpeed.SPEED_9.value),\n int(FanSpeed.SPEED_10.value),\n]\n\nSPEED_DYSON_TO_HA = {\n FanSpeed.SPEED_1: SPEED_LOW,\n FanSpeed.SPEED_2: SPEED_LOW,\n FanSpeed.SPEED_3: SPEED_LOW,\n FanSpeed.SPEED_4: SPEED_LOW,\n FanSpeed.SPEED_AUTO: SPEED_MEDIUM,\n FanSpeed.SPEED_5: SPEED_MEDIUM,\n FanSpeed.SPEED_6: SPEED_MEDIUM,\n FanSpeed.SPEED_7: SPEED_MEDIUM,\n FanSpeed.SPEED_8: SPEED_HIGH,\n FanSpeed.SPEED_9: SPEED_HIGH,\n FanSpeed.SPEED_10: SPEED_HIGH,\n}\n\nSPEED_HA_TO_DYSON = {\n SPEED_LOW: FanSpeed.SPEED_4,\n SPEED_MEDIUM: FanSpeed.SPEED_7,\n SPEED_HIGH: FanSpeed.SPEED_10,\n}\n\n\nasync def async_setup_entry(\n hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: Callable\n) -> None:\n \"\"\"Set up Dyson fan from a config entry.\"\"\"\n device = hass.data[DOMAIN][DATA_DEVICES][config_entry.entry_id]\n entity = DysonPureCoolLinkEntity(device, config_entry.data[CONF_NAME])\n async_add_entities([entity])\n\n platform = entity_platform.current_platform.get()\n platform.async_register_entity_service(\n SERVICE_SET_AUTO_MODE, SET_AUTO_MODE_SCHEMA, \"set_auto_mode\"\n )\n platform.async_register_entity_service(\n SERVICE_SET_DYSON_SPEED, SET_DYSON_SPEED_SCHEMA, \"service_set_dyson_speed\"\n )\n\n\nclass DysonPureCoolLinkEntity(DysonEntity, FanEntity):\n\n _MESSAGE_TYPE = MessageType.STATE\n\n @property\n def is_on(self) -> bool:\n \"\"\"Return if the fan is on.\"\"\"\n return self._device.is_on\n\n @property\n def speed(self):\n \"\"\"Return the current speed.\"\"\"\n return SPEED_DYSON_TO_HA[self._device.speed]\n\n @property\n def speed_list(self) -> list:\n \"\"\"Get the list of available speeds.\"\"\"\n return SPEED_LIST_HA\n\n @property\n def dyson_speed(self):\n \"\"\"Return the current speed.\"\"\"\n if self._device.speed == FanSpeed.SPEED_AUTO:\n return \"AUTO\"\n return int(self._device.speed.value)\n\n @property\n def dyson_speed_list(self) -> list:\n \"\"\"Get the list of available dyson speeds.\"\"\"\n return SPEED_LIST_DYSON\n \n @property\n def auto_mode(self):\n \"\"\"Return auto mode.\"\"\"\n return self._device.auto_mode\n\n @property\n def oscillating(self):\n \"\"\"Return the oscillation state.\"\"\"\n return self._device.oscillation\n\n @property\n def night_mode(self) -> bool:\n \"\"\"Return if night mode is on.\"\"\"\n return self._device.night_mode\n\n @property\n def supported_features(self) -> int:\n \"\"\"Flag supported features.\"\"\"\n return SUPPORT_OSCILLATE | SUPPORT_SET_SPEED\n\n @property\n def device_state_attributes(self) -> dict:\n \"\"\"Return optional state attributes.\"\"\"\n return {\n ATTR_AUTO_MODE: self.auto_mode,\n ATTR_NIGHT_MODE: self.night_mode,\n ATTR_DYSON_SPEED: self.dyson_speed,\n ATTR_DYSON_SPEED_LIST: self.dyson_speed_list,\n }\n\n def turn_on(\n self,\n speed: Optional[str] = None,\n percentage: Optional[int] = None,\n preset_mode: Optional[str] = None,\n **kwargs,\n ) -> None:\n \"\"\"Turn on the fan.\"\"\"\n _LOGGER.debug(\"Turn on fan %s with percentage %s\", self.name, percentage)\n if preset_mode:\n self.set_preset_mode(preset_mode)\n elif speed is None:\n # percentage not set, just turn on\n self._device.turn_on()\n else:\n self.set_speed(speed)\n\n def turn_off(self, **kwargs) -> None:\n \"\"\"Turn off the fan.\"\"\"\n _LOGGER.debug(\"Turn off fan %s\", self.name)\n return self._device.turn_off()\n\n def set_speed(self, speed: str) -> None:\n \"\"\"Set the speed of the fan.\"\"\"\n if speed not in SPEED_LIST_HA:\n raise ValueError(f'\"{speed}\" is not a valid speed')\n _LOGGER.debug(\"Set fan speed to: %s\", speed)\n self.set_dyson_speed(SPEED_HA_TO_DYSON[speed])\n\n def set_dyson_speed(self, speed: FanSpeed) -> None:\n \"\"\"Set the exact speed of the fan.\"\"\"\n self._device.set_speed(speed)\n\n def service_set_dyson_speed(self, dyson_speed: str) -> None:\n \"\"\"Handle the service to set dyson speed.\"\"\"\n if dyson_speed not in SPEED_LIST_DYSON:\n raise ValueError(f'\"{dyson_speed}\" is not a valid Dyson speed')\n _LOGGER.debug(\"Set exact speed to %s\", dyson_speed)\n speed = FanSpeed(f\"{int(dyson_speed):04d}\")\n self.set_dyson_speed(speed)\n\n def oscillate(self, oscillating: bool) -> None:\n \"\"\"Turn on/of oscillation.\"\"\"\n _LOGGER.debug(\"Turn oscillation %s for device %s\", oscillating, self.name)\n self._device.set_oscillation(oscillating)\n\n def set_auto_mode(self, auto_mode: bool) -> None:\n \"\"\"Turn auto mode on/off.\"\"\"\n _LOGGER.debug(\"Turn auto mode %s for device %s\", auto_mode, self.name)\n if auto_mode:\n self._device.set_auto_mode(True)\n else:\n self._device.set_auto_mode(False)\n","sub_path":"custom_components/dyson_local/fan.py","file_name":"fan.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"139173127","text":"import os\nimport warnings\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nwarnings.filterwarnings(\"ignore\")\n\nimport tensorflow as tf\nimport pickle\nimport logging\nimport time\n\nimport dataset, decay, model, optim, util\n\nlogging.getLogger('tensorflow').setLevel(logging.CRITICAL)\nlogging.getLogger('numpy').setLevel(logging.CRITICAL)\n\n\nCIFAR10 = dataset.CIFAR10()\nCIFAR10_ResNet_20 = model.ResNet(num_blocks=3, num_layers=3, base_channels=16, num_classes=10)\nCIFAR10_WRN_16_8 = model.WideResNet(num_blocks=3, num_layers=2, base_channels=16, channel_scale=8, num_classes=10)\nCIFAR10_DenseNet_22 = model.DenseNet(num_blocks=3, num_layers=6, growth_rate=24, num_classes=10)\n\ndataset_and_model_pairs = [\n (CIFAR10, CIFAR10_ResNet_20, 'CIFAR10/ResNet20'),\n (CIFAR10, CIFAR10_WRN_16_8, 'CIFAR10/WRN-16-8'),\n (CIFAR10, CIFAR10_DenseNet_22, 'CIFAR10/DenseNet22'),\n]\n\n\nSGD = optim.SGD(weight_decay_rate=1e-4)\nMomentum = optim.Momentum(momentum=0.9, weight_decay_rate=1e-4)\nAdam = optim.Adam(beta_1=0.9, beta_2=0.999, weight_decay_rate=1e-4)\nELD = optim.ELD(gamma=0.99, weight_decay_rate=1e-4)\n\noptim_and_decay_pairs = [\n (SGD, decay.Constant(lr=1e-1), 'SGD/1e-1'),\n (SGD, decay.Constant(lr=1e-2), 'SGD/1e-2'),\n (SGD, decay.Constant(lr=1e-3), 'SGD/1e-3'),\n (SGD, decay.Step(lr=1e-1, decay_rate=1e-1, decay_steps=[0.5, 0.75]), 'SGD/(1e-1, 1e-2, 1e-3)'),\n (SGD, decay.Cosine(start_lr=1e-1, end_lr=1e-4), 'SGD/cos(1e-1, 1e-4)'),\n\n (Momentum, decay.Constant(lr=1e-1), 'Momentum/1e-1'),\n (Momentum, decay.Constant(lr=1e-2), 'Momentum/1e-2'),\n (Momentum, decay.Constant(lr=1e-3), 'Momentum/1e-3'),\n (Momentum, decay.Step(lr=1e-1, decay_rate=1e-1, decay_steps=[0.5, 0.75]), 'Momentum/(1e-1, 1e-2, 1e-3)'),\n (Momentum, decay.Cosine(start_lr=1e-1, end_lr=1e-4), 'Momentum/cos(1e-1, 1e-4)'),\n\n (Adam, decay.Constant(lr=1e-1), 'Adam/1e-1'),\n (Adam, decay.Constant(lr=1e-2), 'Adam/1e-2'),\n (Adam, decay.Constant(lr=1e-3), 'Adam/1e-3'),\n (Adam, decay.Constant(lr=1e-4), 'Adam/1e-4'),\n\n (ELD, decay.Constant(lr=1e-1), 'ELD/1e-1'),\n (ELD, decay.Constant(lr=1e-2), 'ELD/1e-2'),\n (ELD, decay.Step(lr=1e-1, decay_rate=1e-1, decay_steps=[0.5]), 'ELD/(1e-1, 1e-2)'),\n]\n\n\ntrain_args_pairs = [dm[:-1] + od[:-1] + (dm[-1] + '/' + od[-1],)\n for dm in dataset_and_model_pairs\n for od in optim_and_decay_pairs]\n\n\nif __name__ == '__main__':\n total_metrics = {}\n last_time_stamp = time.time()\n\n if os.path.exists('metrics.pkl'):\n print('[*] Resume training from [metrics.pkl]')\n\n with open('metrics.pkl', 'rb') as fp:\n total_metrics = pickle.load(fp)\n train_args_pairs = train_args_pairs[len(total_metrics):]\n\n print(f'[*] Total examples for training: {len(train_args_pairs)}')\n for pairs in train_args_pairs:\n print(f'[*] Start training [{pairs[-1]}]')\n\n estimator = util.train.Estimator(\n dataset=pairs[0],\n model=pairs[1],\n optimizer=pairs[2],\n use_fp16=True)\n metrics = estimator.train(\n train_batch_size=64,\n test_batch_size=512,\n total_steps=200 * 50000 // 64,\n test_steps=50000 // 64,\n lr_decay=pairs[3])\n\n total_metrics[pairs[-1]] = metrics\n\n print('[*] Save metrics to [metrics.pkl]')\n with open('metrics.pkl', 'wb') as fp:\n pickle.dump(total_metrics, fp)\n\n print(f'[*] Finish training all examples. ETA: {int(time.time() - last_time_stamp) // 3600} hours')\n\n # os.system('sudo poweroff')\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"3914983","text":"from collections import defaultdict\nimport logging\nfrom time import sleep\nfrom SPARQLWrapper import SPARQLWrapper, JSON\nimport operator\n\n\nclass DBpedia(object):\n def __init__(self):\n self.sparql = SPARQLWrapper(\"http://dbpedia.org/sparql\")\n self.sparql.setTimeout(500)\n self.sparql.setReturnFormat(JSON)\n\n def get_predicates(self):\n query = u\" SELECT DISTINCT ?p WHERE {\" \\\n u\" ?p a rdf:Property\" \\\n u\"}\" \\\n u\" ORDER BY ?p\"\n return set(self._retrieve(query, ['p']))\n\n def get_subject_object_pairs(self, p):\n query = u\" SELECT ?s ?o\" \\\n u\" WHERE {{ ?s {0} ?o }}\".format(p)\n return set(self._retrieve(query, ['s', 'o']))\n\n def get_predicate_object_pairs(self, s, filter_predicates=None):\n query = u\" SELECT ?p ?o WHERE {{\" \\\n u\" {0} ?p ?o \".format(s)\n\n if filter_predicates:\n query += u\" MINUS {\"\n for f in filter_predicates:\n query += u\" {0} {1} ?o .\".format(s, f)\n query += u\"}\"\n query += u\" FILTER( !isLiteral(?o) ) \"\n query += u\"}\"\n return self._retrieve(query, [\"p\", \"o\"])\n\n def most_common_types(self, prop, min_instances=50):\n types = defaultdict(int)\n query = u\"SELECT ?t count(distinct ?s) AS ?c\" \\\n u\" WHERE {{\" \\\n u\" ?s {0} ?o;\" \\\n u\" a ?t\" \\\n u\" FILTER(STRSTARTS(STR(?t), 'http://dbpedia.org/ontology'))\" \\\n u\" }}\" \\\n u\" GROUP BY ?t\" \\\n u\" ORDER BY DESC(?c)\".format(prop)\n for t, c in self._retrieve(query, ['t', 'c'], limit=50, filter=[lambda x: True, lambda x: int(x) > min_instances]):\n types[t] += int(c)\n\n types = sorted(types.items(), key=operator.itemgetter(1), reverse=True)\n return types\n\n def get_values_of_type(self, type, property):\n query = u\"SELECT ?o\" \\\n u\" WHERE {{\" \\\n u\" ?s {0} ?o;\" \\\n u\" a {1}\" \\\n u\" }}\".format(property, type)\n return [x[0] for x in self._retrieve(query, [\"o\"])]\n\n def get_types(self, s):\n query = u\"SELECT ?t\" \\\n u\" WHERE {{\" \\\n u\" {0} a ?t\" \\\n u\" }}\".format(s)\n return set([x[0] for x in self._retrieve(query, ['t'])])\n\n def get_subclasses(self, s):\n query = u\"SELECT ?t\" \\\n u\" WHERE {{\" \\\n u\" ?t rdfs:subClassOf {0}\" \\\n u\" }}\".format(s)\n return set([x[0] for x in self._retrieve(query, ['t'])])\n\n def get_subjects_by_predicate(self, p):\n query = u\"SELECT ?s\" \\\n u\" WHERE {{\" \\\n u\" ?s {0} ?o\" \\\n u\" }}\".format(p)\n return set([x[0] for x in self._retrieve(query, ['s'])])\n\n def get_subjects_by_predicate_type(self, p, t):\n query = u\"SELECT ?s\" \\\n u\" WHERE {{\" \\\n u\" ?s a {0}.\" \\\n u\" ?s {1} ?o\" \\\n u\" }}\".format(t, p)\n return set([x[0] for x in self._retrieve(query, ['s'])])\n\n def get_subjects_by_predicate_object_type(self, p, o, t):\n query = u\"SELECT ?s\" \\\n u\" WHERE {{\" \\\n u\" ?s a {0}.\" \\\n u\" ?s {1} {2}\" \\\n u\" }}\".format(t, p, o)\n return set([x[0] for x in self._retrieve(query, ['s'])])\n\n def get_triples_by_subject(self, s, literals=True):\n query = u\" SELECT ?p ?o WHERE {\"\n query += u\" {0} ?p ?o \".format(s)\n if not literals:\n query += u\" FILTER( !isLiteral(?o) ) \"\n query += u\"}\"\n return self._retrieve(query, ['p', 'o'])\n\n def _retrieve(self, query, params, limit=5000, filter=None, retries=10):\n try:\n logging.debug('DBpedia query: ' + query)\n res = []\n offset = 0\n has_next = True\n while has_next:\n q = query + u\" LIMIT {1} OFFSET {2}\".format(property, limit, offset)\n\n self.sparql.setQuery(q)\n resp = self.sparql.query().convert()\n results = resp[\"results\"][\"bindings\"]\n\n for result in results:\n tup = [result[p][\"value\"] for p in params]\n if filter:\n if all([f(t) for t, f in zip(tup, filter)]):\n res.append(tup)\n else:\n res.append(tup)\n\n offset += limit\n\n if len(res) < offset:\n has_next = False\n\n if offset % 10000 == 0:\n logging.debug('DBPedia results retrieved: ' + str(offset))\n\n return res\n except Exception as e:\n if retries > 0:\n logging.warning('DBpedia connection lost: ' + str(e) + '. Try again...(' + str(retries) + ')')\n sleep(20)\n return self._retrieve(query, params, limit, filter, retries - 1)\n logging.warning('DBpedia connection error: ' + str(e))\n raise e\n\n","sub_path":"utils/dbpedia_access.py","file_name":"dbpedia_access.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"170774639","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport mods.NOM.utils as ut\nimport mods.colormaps as cmps\nfrom scipy.stats import linregress\n\ndef plot_vels(bins, vels, CI, bw):\n\tvp = vels\n\tfor i in range(int(bw) - 1):\n\t\tvp = np.vstack((vp,vels))\n\tvp = vp.T.flatten()\n\n\tplt.figure(facecolor='white')\n\tplt.ion()\n\tplt.show()\n\tplt.clf()\n\n\t(_, caps, _) = plt.errorbar(bins+bw/2., vels, linestyle='',lw=1.5, yerr=abs(CI[:,0]-vels),color='k')\n\tfor cap in caps:\n\t\tcap.set_markeredgewidth(1.5)\n\tplt.plot(np.arange(0,360),vp,lw=2,color='b')\n\tplt.xlim([0,360])\n#\tplt.tick_params(axis='both',labelsize=14,width=2,length=7)\n#\tplt.xlabel('Azimuth [degrees]', fontsize=16)\n#\tplt.ylabel('Velocity [km/s]', fontsize=16)\n\tplt.xlabel('Azimuth [degrees]')\n\tplt.ylabel('Velocity [km/s]')\n\n\treturn\n\ndef plot_bingrad(bins, grad, bw):\n\tgr = grad\n\tfor i in range(int(bw) - 1):\n\t\tgr = np.vstack((gr,grad))\n\tgr = gr.T.flatten()\n\n\tplt.figure(facecolor='white')\n\tplt.ion()\n\tplt.show()\n\tplt.clf()\n\n\tplt.plot(np.arange(0,360),gr,lw=2)\n\tplt.xlim([0,360])\n#\tplt.tick_params(axis='both',labelsize=14,width=2,length=7)\n#\tplt.xlabel('Azimuth [degrees]', fontsize=16)\n#\tplt.ylabel('Velocity gradient [1/s]', fontsize=16)\n\tplt.xlabel('Azimuth [degrees]')\n\tplt.ylabel('Velocity gradient [1/s]')\n\n\treturn\n\ndef plot_binvg(bins,vels,grad,CI,bw):\n\tvp = vels\n\tfor i in range(int(bw) - 1):\n\t\tvp = np.vstack((vp,vels))\n\tvp = vp.T.flatten()\n\n\tgr = grad\n\tfor i in range(int(bw) - 1):\n\t\tgr = np.vstack((gr,grad))\n\tgr = gr.T.flatten()\n\n\tfig,(ax1,ax2) = plt.subplots(2,sharex=True,facecolor='white',gridspec_kw= {'height_ratios':[2,1]})\n\tplt.ion()\n\tplt.show()\n\tax1.plot(np.arange(0,360),vp,lw=2,color='b')\n#\tax1.set_ylabel('Velocity [km/s]',fontsize=16)\n\tax1.set_ylabel('Velocity [km/s]')\n#\tax1.tick_params(axis='both',labelsize=14,width=2,length=7)\n\n\n\tax2.plot(np.arange(0,360),gr,lw=2,color='g')\n#\tax2.set_ylabel('Vel. gradient [1/s]',fontsize=16)\n\tax2.set_ylabel('Vel. gradient [1/s]')\n\tax2.set_ylim(-0.005,0.030)\n#\tax2.tick_params(axis='both',labelsize=14,width=2,length=7)\n#\tax2.set_xlabel('Azimuth [degrees]',fontsize=16)\n\tax2.set_xlabel('Azimuth [degrees]')\n\n\tplt.xlim(0,360)\n\tplt.subplots_adjust(hspace=0)\n\n\treturn\n\n\n\ndef plot_picks(pk,fit,di='dV',xcrust = 18.):\n\n\tplt.figure(facecolor='white')\n\tplt.ion()\n\tplt.show()\n\tplt.clf()\n\n\tmx = int(max(pk['xoff'].abs() + xcrust))\n\tux = int(min(pk['xoff'].abs() + xcrust))\n\tbd = np.arange(ux-5,mx+15,10)\n\ttk = np.arange(ux,mx+10,20)\n\tcmap = plt.get_cmap(cmps.viridis,int(mx-ux)+1)\n\tplt.scatter(pk['azi'],pk[di],c=pk['xoff'].abs() + xcrust,cmap=cmap,lw=0.3)\n\tcb = plt.colorbar(fraction=0.04,boundaries=bd,ticks=tk)\n#\tcb.set_label('Offset [km]',fontsize=14)\n\tcb.set_label('Offset [km]')\n\tplt.xlim([0,360])\n\tplt.ylim([-0.51,0.51])\n#\tplt.tick_params(axis='both',labelsize=14,width=2,length=7)\n#\tplt.xlabel('Azimuth [degrees]', fontsize=16)\n#\tplt.ylabel('%s [km/s]' % di, fontsize=16)\n\tplt.xlabel('Azimuth [degrees]')\n\tplt.ylabel('%s [km/s]' % di)\n\n\ttheta = np.arange(0,360)\n\tplt.plot(theta,ut.backus_4(theta,fit),'-',linewidth=2,color='red')\n\tplt.draw()\n\n\n\treturn\n\ndef plot_xhist(pk):\n\tplt.figure(facecolor='white')\n\tplt.ion()\n\tplt.show()\n\tplt.clf()\n\tplt.hist(pk['xoff'].abs(),30,alpha=0.5)\n\treturn\n\ndef plot_resids(pk,fit,ln=-1,rec=-1,azi=-1,pma=5,di='dT',xcrust=18.):\n\tpsel,res = ut.get_residuals(pk,fit,ln=ln,rec=rec,azi=azi,pma=pma,di=di)\n\n\tif len(psel) > 1:\n\n\t\tplt.figure(figsize=(6.5,3))\n\t\tplt.ion()\n\t\tplt.show()\n\t\tplt.clf()\n\n\t\tplt.scatter(psel['xoff'].abs() + xcrust,res,marker='+',color='grey')\n\n\t\tplt.plot([min(psel['xoff'].abs())+ xcrust,max(psel['xoff'].abs())+ xcrust],[0,0],'--',color='k',lw=2)\n\t\tplt.xlim(min(psel['xoff'].abs())+ xcrust,max(psel['xoff'].abs())+ xcrust)\n\n\t\tslope,inter,rval,pval,stdr = linregress(psel['xoff'].abs(),res)\n\t\tif pval < 0.05:\n\t\t\tplt.plot(psel['xoff'].abs()+ xcrust,inter + slope*(psel['xoff'].abs()+ xcrust), color='r',lw=2)\n\n\treturn\n","sub_path":"mods/NOM/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"624488449","text":"import tflearn\nimport tensorflow as tf\nimport numpy as np\nimport json\nfrom pyvi import ViTokenizer, ViPosTagger\nimport pickle\nimport nltk\nimport random\n\nwith open('data/intents.json',encoding=\"utf-8\") as json_data:\n\tintents = json.load(json_data)\n\nwords = []\nwords1= []\ndocuments = []\nclasses = []\nstop_words = ['bị', 'bởi', 'cả', 'các', 'cái', 'cần', 'càng', 'chỉ', 'chiếc', 'cho', 'chứ', 'chưa', 'chuyện', 'có',\n 'có_thể', 'cứ', 'của', 'cùng', 'cũng', 'đã', 'đang', 'đây', 'để', 'đến nỗi', 'đều', 'điều', 'do', 'đó',\n 'được', 'dưới', 'gì', 'khi', 'không', 'là', 'lại', 'lên', 'lúc', 'mà', 'mỗi', 'một_cách', 'này', 'nên',\n 'nếu', 'ngay', 'nhiều', 'như', 'nhưng', 'những', 'nơi', 'nữa', 'phải', 'qua', 'ra', 'rằng', 'rất',\n 'theo', 'thì', 'sẽ', 'rồi', 'sau', 'tại', 'trên', 'trước', 'từ', 'từng', 'và', 'vẫn', 'vào', 'vậy',\n 'vừa', 'với', 'vì', '?', 'à', 'ừ', 'ạ']\n\nfor intent in intents['intents']:\n for pattern in intent['patterns']:\n w = ViPosTagger.postagging(ViTokenizer.tokenize(pattern))[0]\n # print(w)\n words.extend(w)\n documents.append((w, intent['tag']))\n if intent['tag'] not in classes:\n classes.append(intent['tag'])\n\nfor w in words:\n if w not in stop_words:\n words1.append(w)\nwords = sorted(list(set(words1)))\n\n# Create training data\n\ntraining = []\noutput = []\noutput_empty = [0] * len(classes)\n\nfor doc in documents:\n bag = []\n pattern_words = doc[0]\n\n for w in words:\n if w in pattern_words:\n bag.append(1)\n else:\n bag.append(0)\n\n # output is a '0' for each tag and '1' for current tag\n output_row = list(output_empty)\n output_row[classes.index(doc[1])] = 1\n\n training.append([bag, output_row])\n\n# shuffle our features and turn into np.array\nrandom.shuffle(training)\ntraining = np.array(training)\n\ntrain_x = list(training[:, 0])\ntrain_y = list(training[:, 1])\n\ntf.reset_default_graph()\n\nnet = tflearn.input_data(shape=[None, len(train_x[0])])\nnet = tflearn.fully_connected(net, 8)\nnet = tflearn.fully_connected(net, 8)\nnet = tflearn.fully_connected(net, len(train_y[0]), activation='softmax')\nnet = tflearn.regression(net, optimizer='adam', loss='categorical_crossentropy')\n\nmodel = tflearn.DNN(net, tensorboard_dir='tflearn_logs')\n\nmodel.fit(train_x, train_y, n_epoch=1000, batch_size=8, show_metric=True)\nmodel.save('models/model.tflearn')\n\npickle.dump({'words': words, 'classes': classes, 'train_x': train_x, 'train_y': train_y},\n open(\"models/training_data\", \"wb\"))","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"257056626","text":"import json\nimport os\n\n\ndef load_data(filepath):\n if not os.path.exists(filepath):\n return None\n with open(filepath, 'r', encoding=\"utf-8-sig\") as handle:\n data = json.load(handle) \n return data\n \n \ndef get_biggest_bar(data):\n seats = data[0]['Cells']['SeatsCount']\n for d in data:\n if d['Cells']['SeatsCount'] > seats:\n seats = d['Cells']['SeatsCount']\n biggest_bar = d\n return biggest_bar \n\n\ndef get_smallest_bar(data):\n seats = data[0]['Cells']['SeatsCount']\n for d in data:\n if d['Cells']['SeatsCount'] < seats:\n seats = d['Cells']['SeatsCount']\n biggest_bar = d\n return biggest_bar \n\n\ndef get_closest_bar(data, longitude, latitude):\n dist = ((longitude-data[0]['Cells']['geoData']['coordinates'][0])**2 +\n (latitude-data[0]['Cells']['geoData']['coordinates'][1])**2)\n for i in data:\n long = i['Cells']['geoData']['coordinates'][0]\n lat = i['Cells']['geoData']['coordinates'][1]\n new_dist = ((longitude-long)**2 +\n (latitude-lat)**2)\n if new_dist < dist:\n dist = new_dist\n closest_bar = i\n return closest_bar\n\nif __name__ == '__main__':\n path = '/projects/3_bars/bars.json'\n file = load_data(path)\n try:\n latitude = float(input('Введите широту: '))\n longitude = float(input('Введите долготу: '))\n except ValueError:\n print('Некорректые координаты!')\n \n big_bar = get_biggest_bar(file)\n small_bar = get_smallest_bar(file)\n closest_bar = get_closest_bar(file, longitude, latitude)\n print('Самый большой бар: ' + big_bar['Cells']['Name'] + ', ' + big_bar['Cells']['Address'] + ', Количество мест: ' + str(big_bar['Cells']['SeatsCount']))\n print('Самый маленький бар: ' + small_bar['Cells']['Name'] + ', ' + small_bar['Cells']['Address'] + ', Количество мест: ' + str(small_bar['Cells']['SeatsCount']))\n print('Ближайший бар: ' + closest_bar['Cells']['Name'] + ', ' + closest_bar['Cells']['Address'] + ', Количество мест: ' + str(closest_bar['Cells']['SeatsCount']))\n \n \n \n","sub_path":"bars.py","file_name":"bars.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"131736469","text":"from django.db import models\n\nfrom wagtail.core.models import Page\nfrom wagtail.core import blocks\nfrom wagtail.images.blocks import ImageChooserBlock\nfrom wagtail.core.fields import RichTextField, StreamField\nfrom wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel\nfrom common.blocks import Spotlight, TwoColGridImage\nfrom blog.blocks import FeaturedContents, PromotedNewsList, PromotedSpotlightWithList\nfrom shop.blocks import FeaturedProducts, ProductBlock\nfrom common.blocks import WebsiteHeader, WebsiteFooter, EmptyBlock, Carousel\nfrom wagtailstreamforms.blocks import WagtailFormBlock\nfrom wagtail.embeds.blocks import EmbedBlock\nfrom common.blocks import TwoColTextLeft, TwoColTextRight, IntroduceBlock, HRBlock\nfrom wagtailmetadata.models import MetadataPageMixin\n\nclass Homepage(MetadataPageMixin, Page):\n max_count = 1\n header = StreamField([\n ('header', WebsiteHeader()),\n ('empty', EmptyBlock()),\n ], blank=True, null=True)\n body = StreamField([\n ('spotlight', Spotlight()),\n ('featured_products', FeaturedProducts()),\n ('featured_contents', FeaturedContents()),\n ('promoted_news_list', PromotedNewsList()),\n ('promoted_spotlight_with_list', PromotedSpotlightWithList()),\n ('heading', blocks.CharBlock(classname=\"full title\")),\n ('paragraph', blocks.RichTextBlock()),\n ('image', ImageChooserBlock()),\n ('form', WagtailFormBlock()),\n ('embed', EmbedBlock()),\n ('HTML', blocks.RawHTMLBlock()),\n ('Carousel', Carousel()),\n ('TwoColGridImage', TwoColGridImage()),\n ('TwoColTextLeft', TwoColTextLeft()),\n ('TwoColTextRight', TwoColTextRight()),\n ('Introduce', IntroduceBlock()),\n ('product', ProductBlock()),\n ('line', HRBlock()),\n ],blank=True, null=True)\n footer = StreamField([\n ('footer', WebsiteFooter()),\n ('empty', EmptyBlock()),\n ], blank=True, null=True)\n\n content_panels = Page.content_panels + [\n StreamFieldPanel('header'),\n StreamFieldPanel('body'),\n StreamFieldPanel('footer'),\n ]","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"15921694","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n\n\ndef layer_1(x):\n \"\"\"\n consist of convolution, followed by max pooling\n :return:\n \"\"\"\n # 1 => 5x5 => 32\n W_conv1 = weight_variable([5, 5, 1, 32])\n b_conv1 = bias_variable([32])\n\n # reshape x to a 4d tensor, _,width,height,channel\n x_image = tf.reshape(x, [-1, 28, 28, 1])\n\n # convolve with the weight tensor, add the bias, apply the ReLU function\n h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n # and finally max pool\n h_pool1 = max_pool_2x2(h_conv1)\n\n return h_pool1\n\n\ndef layer_2(x):\n \"\"\"\n The second layer will have 64 features for each 5x5 patch\n :return:\n \"\"\"\n W_conv2 = weight_variable([5, 5, 32, 64])\n b_conv2 = bias_variable([64])\n\n # the same as layer relu\n h_conv2 = tf.nn.relu(conv2d(layer_1(x), W_conv2) + b_conv2)\n h_pool2 = max_pool_2x2(h_conv2)\n\n return h_pool2\n\n\ndef fc_1(x):\n \"\"\"\n fully-connected layer with 1024 neurons,processing on the entire image\n :param x:\n :return:\n \"\"\"\n W_fc1 = weight_variable([7 * 7 * 64, 1024])\n b_fc1 = bias_variable([1024])\n\n # reshape the tensor from the pooling layer into a batch of vectors\n h_pool2_flat = tf.reshape(layer_2(x), [-1, 7 * 7 * 64])\n\n # multiply by a weight matrix, add a bias, and apply a ReLU\n h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n\n return h_fc1\n\n\ndef dropout_layer(x):\n \"\"\"\n To reduce overfitting\n dropout on during training, and turn it off during testing\n :param x:\n :return:\n \"\"\"\n # create a placeholder for the probability\n keep_prob = tf.placeholder(tf.float32)\n h_fc1_drop = tf.nn.dropout(fc_1(x), keep_prob)\n\n return h_fc1_drop, keep_prob\n\n\ndef readout_layer(x):\n \"\"\"\n conv 1024 to 10, by matmul\n :param x:\n :return:\n \"\"\"\n W_fc2 = weight_variable([1024, 10])\n b_fc2 = bias_variable([10])\n\n h_fc1_drop, keep_prob = dropout_layer(x)\n y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\n return y_conv, keep_prob\n\n\ndef train(mnist, x, y_):\n y_conv, keep_prob = readout_layer(x)\n\n cross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)\n )\n train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for i in range(2000):\n batch = mnist.train.next_batch(50)\n if i % 100 == 0:\n train_accuracy = accuracy.eval(\n feed_dict={\n x: batch[0],\n y_: batch[1],\n keep_prob: 1.0\n }\n )\n print('step %d, training accuracy %g' % (i, train_accuracy))\n\n train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})\n\n print('test accuracy %g' % accuracy.eval(\n feed_dict={\n x: mnist.test.images,\n y_: mnist.test.labels,\n keep_prob: 1.0\n }\n ))\n\ndef load_data():\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n return mnist\n\nif __name__ == '__main__':\n mnist = load_data()\n\n # placeholder\n x = tf.placeholder(tf.float32, [None, 784])\n y_ = tf.placeholder(tf.float32, [None, 10])\n\n train(mnist, x, y_)\n","sub_path":"deep_mnist.py","file_name":"deep_mnist.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"477277338","text":"#!/usr/bin/env python\n\nimport os, sys, json, logging\nimport webapp2\nfrom google.appengine.api import users\nfrom webapp2_extras import jinja2\nfrom datetime import datetime\nimport utils, models\n\nclass main(utils.BaseHandler):\n def get(self):\n self.render_template('index.html')\n \n \nclass signin(utils.BaseHandler):\n def get(self):\n self.session.pop(\"tid\",None)\n self.render_template('signin.html')\n def post(self):\n data = json.loads(self.request.body)\n email = data.get('email')\n pwd = data.get('pwd')\n self.session[\"tid\"]=1\n self.session[\"user\"]=email\n self.return_msg('Login Sucessfull')\n \n \nclass customers(utils.BaseHandler):\n @utils.login_required\n def get(self):\n rows = [e.to_dict() for e in models.Customers.query()]\n self.return_json(rows)\n \n @utils.login_required\n def post(self):\n try:\n data = json.loads(self.request.body)\n \n id = utils.toInt(data.get(\"id\"))\n if id:\n e = models.Customers.get_by_id(id)\n if e is None:\n raise Exception('Specified customer was not found!')\n else:\n e = models.Customers()\n \n e.name = data.get(\"name\")\n e.contact = data.get(\"contact\")\n e.contactTitle = data.get(\"contactTitle\")\n e.email = data.get(\"email\")\n e.mobile = data.get(\"mobile\")\n e.landline = data.get(\"landline\")\n e.addr = data.get(\"addr\")\n e.notes = data.get(\"notes\")\n e.active = data.get(\"active\") or False\n e.put()\n \n self.return_json(e.to_dict()) \n except:\n self.return_msg()\n \n def delete(self):\n try:\n id = utils.toInt(self.request.get(\"id\"))\n e = models.Customers.get_by_id(id)\n e.key.delete()\n self.return_msg('Customer was deleted') \n except:\n self.return_msg()\n\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {'secret_key': 'CCF893A0-6C2A-4C3D-9D19-4AD2A4C4AC45', 'cookie_args': {'max_age':86400} }\n \napp = webapp2.WSGIApplication([\n ('/', main),\n ('/signin', signin),\n ('/customers', customers),\n], debug=True, config=config)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"327309191","text":"from __future__ import unicode_literals, division, absolute_import\nimport os\n\n__author__ = 'paranoidi'\n\nimport sys\nfrom flexget.utils.simple_persistence import SimplePersistence\nfrom flexget.plugin import register_plugin\nimport logging\n\nlog = logging.getLogger('welcome')\n\n\nclass WelcomePlugin(object):\n\n def __init__(self, ):\n self.executed = False\n self.persistence = SimplePersistence(plugin='welcome')\n\n def on_process_start(self, task, entries):\n if self.executed or not task.manager.options.quiet:\n return\n count = self.persistence.setdefault('count', 5)\n if not count:\n return\n\n # check for old users, assume old user if db larger than 2 MB\n if count == 5 and os.stat(task.manager.db_filename).st_size / 1024 / 1024 >= 2:\n log.debug('Looks like old user, skipping welcome message')\n self.persistence['count'] = 0\n return\n\n count -= 1\n scheduler = 'scheduler' if sys.platform.startswith('win') else 'crontab'\n if not count:\n log.info('FlexGet has been successfully started from %s (--cron). '\n 'I hope you have %s under control now. This message will not be repeated again.' %\n (scheduler, scheduler))\n else:\n log.info('%sFlexGet has been successfully started from %s (--cron). '\n 'This message will be repeated %i times for your set up verification conveniences.' %\n ('Congratulations! ' if count == 4 else '',\n scheduler, count))\n self.persistence['count'] = count\n self.executed = True\n\nregister_plugin(WelcomePlugin, 'welcome', builtin=True, api_ver=2)\n","sub_path":"flexget/plugins/generic/welcome.py","file_name":"welcome.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"448887942","text":"import spacy\nimport textacy\nimport numpy as np\nfrom utils.utils import normalize\nfrom collections import Counter\nfrom scipy.stats import entropy\nfrom nltk.stem.snowball import SnowballStemmer\nfrom functools import lru_cache\n# from cytoolz import itertoolz\n\nstemmer = SnowballStemmer(language='english')\n\n\ndef to_terms_list(doc, ngrams=1, **kwargs):\n normalize = kwargs.get('normalize', 'lemma')\n del kwargs['normalize']\n terms = textacy.extract.ngrams(doc, ngrams, **kwargs)\n if normalize == 'lemma':\n for term in terms:\n yield term.lemma_\n elif normalize == 'lower':\n for term in terms:\n yield term.lower_\n elif callable(normalize):\n for term in terms:\n yield normalize(term)\n else:\n for term in terms:\n yield term.text\n\n\n@lru_cache(maxsize=32)\ndef bag_of_terms(doc, ngrams=1, **kwargs):\n kwargs['normalize'] = stem\n if isinstance(doc, spacy.tokens.doc.Doc):\n return doc._.to_bag_of_terms(ngrams=ngrams, as_strings=True, **kwargs)\n return Counter(to_terms_list(doc, ngrams, **kwargs))\n\n\ndef stem(token):\n return stemmer.stem(token.lemma_)\n\n\ndef brunet_measure(bot, n, v):\n a = 0.17\n if n == 0 or n == 1:\n return 0\n return (v - a) / (np.log(n))\n\n\ndef hapax_dislegemena(bot, n, v):\n v2 = len([word for word, count in bot.items() if count == 2])\n if n == 0:\n return 0\n return v2 / n\n\n\ndef hapax_legomena(bot, n, v):\n v1 = len([word for word, count in bot.items() if count == 1])\n if n == 0:\n return 0\n return v1 / n\n\n\ndef honore_measure(bot, n, v):\n v1 = len([word for word, count in bot.items() if count == 1])\n if n == 0:\n return 0\n return 100 * np.log(n) / max(1, (1 - v1 / v))\n\n\ndef shannon_entropy(bot, n, v):\n if n == 0:\n return 0\n freqs = np.array(list(bot.values())) / n\n return entropy(freqs, base=2)\n\n\ndef sichel_measure(bot, n, v):\n v2 = len([word for word, count in bot.items() if count == 2])\n if n == 0:\n return 0\n return v2 / v\n\n\ndef simpsons_index(bot, n, v):\n s = sum([1.0 * i * (i - 1) for i in bot.values()])\n if n == 0 or n == 1:\n return 0\n return 1 - (s / (n * (n - 1)))\n\n\ndef type_token_ratio(bot, n, v):\n if n == 0:\n return 0\n return v / n\n\n\ndef yule_characteristic(bot, n, v):\n freqs = Counter(bot.values())\n s = sum([(i ** 2) * vi for i, vi in freqs.items()])\n if n == 0:\n return 0\n return 10000 * (s - n) / (n ** 2)\n\n\ndef vocabulary_richness_vec(seg, f_index):\n bot = bag_of_terms(seg)\n n = sum(bot.values())\n v = len(bot)\n feature_vector = [feature_func[i](bot, n, v) for i in f_index]\n return feature_vector\n\n\ndef extract_features(segmentation, segments):\n f_index = seg_feature[segmentation]\n X = np.empty((len(segments), len(f_index)))\n for i, seg in enumerate(segments):\n X[i] = vocabulary_richness_vec(seg, f_index)\n return normalize(X)\n\n\nfeature_name = ['Brunet_Measure', 'Hapax_DisLegemena', 'Hapax_Legomena',\n 'Honore_Measure', 'Shannon_Entropy', 'Sichel_Measure',\n 'Simpsons_Index', 'Type_Token_Ratio', 'Yule_Characteristic']\n\nfeature_func = [brunet_measure, hapax_dislegemena, hapax_legomena,\n honore_measure, shannon_entropy, sichel_measure,\n simpsons_index, type_token_ratio, yule_characteristic]\n\nseg_feature = {'g11-05': [3, 4],\n 'g20-10': [0, 1, 2, 3, 4, 7],\n 'g30-10': [0, 1, 2, 3, 4, 5, 6, 7, 8],\n 'g09-00': [0, 3, 4, 6],\n 'g05-00': [],\n 's': [0, 1, 2, 3, 4, 5, 6, 7, 8]}\n","sub_path":"features/lexical.py","file_name":"lexical.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"536515894","text":"import numpy as np\nimport socket\nimport sys\nimport ctypes\nimport os\nfrom PyQt5 import QtWidgets, uic, QtCore, QtGui\n\nfrom pylabnet.network.core.generic_server import GenericServer\nfrom pylabnet.network.client_server.external_gui import Service, Client\nfrom pylabnet.gui.pyqt.external_gui import Window\nfrom pylabnet.utils.helper_methods import get_ip, show_console, hide_console, create_server\n\n# Should help with scaling issues on monitors of differing resolution\nif hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'):\n QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)\nif hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'):\n QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)\n\n\ndef launch(logger=None, port=None, name=None):\n \"\"\" Instantiates a default main window + server\n\n :param logger: (LogClient) instance of LogClient for logging purposes\n :param port: (int) port number for the GUI server\n :param name: (str) name of server to display\n \"\"\"\n\n # # Create app and instantiate main window\n ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('pylabnet')\n app = QtWidgets.QApplication(sys.argv)\n app.setWindowIcon(\n QtGui.QIcon(os.path.join(os.path.dirname(os.path.dirname(\n os.path.realpath(__file__)\n )), 'devices.ico'))\n )\n show_console()\n ui = input('Please enter the .ui file to use as a template:\\n>> ')\n hide_console()\n try:\n main_window = Window(app, gui_template=ui)\n except FileNotFoundError:\n print('Could not find .ui file, '\n 'please check that it is in the pylabnet/gui/pyqt/gui_templates directory')\n raise\n gui_service = Service()\n gui_service.assign_module(module=main_window)\n gui_service.assign_logger(logger=logger)\n\n if port is None:\n gui_server, port = create_server(\n service=gui_service,\n logger=logger,\n host=get_ip()\n )\n else:\n gui_server = GenericServer(\n service=gui_service,\n host=get_ip(),\n port=port\n )\n logger.update_data(data=dict(ui=ui, port=port))\n\n gui_server.start()\n\n # Update GUI with server-specific details\n main_window.ip_label.setText('IP Address: {}'.format(\n get_ip()\n ))\n main_window.port_label.setText('Port: {}'.format(port))\n\n # Run the GUI until the stop button is clicked\n while not main_window.stop_button.isChecked():\n main_window.configure_widgets()\n main_window.update_widgets()\n main_window.force_update()\n gui_server.stop()\n","sub_path":"pylabnet/launchers/servers/external_gui.py","file_name":"external_gui.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"616606684","text":"import menudownloader\n\nimport argparse\nimport pdf_table_parser as parser\nimport os\nimport slack\nimport subprocess\n\nfrom google.cloud import secretmanager\n\ndef handleMenu(path=None, directory=None, useFullWeek=False, sendToSlack=False, notify=False, debug=False):\n if (path == None):\n success, filename = menudownloader.downloadCurrentMenu(directory)\n if (success == False):\n err = 'Failed to download menu!'\n print(err)\n return err\n path = filename\n\n week = parser.parsePdfMenu(path, debug)\n if week == None: \n err = 'Failed to parse menu!'\n print(err)\n return err\n\n notification = getNotificationMessage(week, useFullWeek)\n \n if sendToSlack:\n sendNotificationToSlack(notification, debug)\n\n if notify:\n sendNotification(notification)\n\n menudownloader.cleanup()\n return notification\n\ndef getNotificationMessage(week, useFullWeek):\n msgObject = week if useFullWeek else week.getTodaysMenu()\n \n if msgObject == None:\n err = 'No menu available for {}!'.format('this week' if useFullWeek else 'today')\n print('{} \\n But you could view the current week menu with the -w flag'.format(err))\n return err\n\n return str(msgObject)\n\ndef sendNotificationToSlack(text, debug):\n slackToken, channel = getSlackSecrets()\n client = slack.WebClient(token=slackToken)\n \n client.chat_postMessage(\n channel = channel, \n text = text\n )\n\ndef getSlackSecrets():\n gcpProjectId = os.environ.get(\"GCP_PROJECT\")\n gcpTokenSecret = os.environ.get(\"GCP_SLACK_API_SECRET\")\n gcpChannelSecret = os.environ.get(\"GCP_SLACK_CHANNEL_SECRET\")\n\n if gcpProjectId != None and gcpTokenSecret != None and gcpChannelSecret != None :\n print('Loading GCP Secrets...')\n client = secretmanager.SecretManagerServiceClient()\n slackToken = getGCPSecret(client, gcpProjectId, gcpTokenSecret)\n channel = getGCPSecret(client, gcpProjectId, gcpChannelSecret)\n else :\n print('Loading ENV var Secrets...')\n slackToken = os.environ.get(\"SLACK_API_TOKEN\")\n channel = os.environ.get(\"SLACK_CHANNEL\")\n\n return slackToken, channel\n\ndef getGCPSecret(client, projectId, secretId, versionId=\"latest\"):\n identifier = client.secret_version_path(projectId, secretId, versionId)\n\n secret = client.access_secret_version(identifier)\n\n return secret.payload.data.decode('UTF-8')\n\ndef sendNotification(text):\n subprocess.Popen(['notify-send', '-i', 'Genusswerk Menu', text])\n\nif __name__ == '__main__': \n argParser = argparse.ArgumentParser(description='Parse the Genusswerk weekly menu')\n argParser.add_argument('--file','-f', help='The Genusswerk menu pdf you want to parse')\n argParser.add_argument('--directory', '-d', help='The folder downloaded menus will be stored in. Default is subfolder menu where run')\n argParser.add_argument('--week','-w', action='store_true', help='Return complete week, instead of todays menu')\n argParser.add_argument('--send-to-slack', '-s', action='store_true', help='Send parsed menu to slack')\n argParser.add_argument('--send-notification', '-n', action='store_true', help='Show parsed menu as notification')\n argParser.add_argument('--debug','-db', action='store_true', help='Show parsing debug information')\n args = argParser.parse_args()\n \n handleMenu(args.file, args.directory, args.week, args.send_to_slack, args.send_notification, args.debug)\n","sub_path":"genusswerkparser.py","file_name":"genusswerkparser.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499188877","text":"import discord\nfrom discord.ext import commands\nfrom discord_slash import SlashCommand, SlashContext\n\nbot = commands.Bot(command_prefix=\"!\", intents=discord.Intents.all())\nslash = SlashCommand(bot)\n\n@slash.slash(name=\"test\",\n description=\"This is just a test command, nothing more.\",\n options=[\n create_option(\n name=\"optone\",\n description=\"This is the first option we have.\",\n option_type=3,\n required=False\n )\n ])\nasync def test(ctx, optone: str):\n await ctx.send(content=f\"I got you, you said {optone}!\")\n\nbot.run(\"ODIxNDM1NzExODMxODAxODU2.YFDrnw.la8G5wac2NYpR5YX9EnimbGo5cg\")","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"3472583","text":"from django.contrib import admin\r\nfrom django.urls import path\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('', views.home_page, name='home'),\r\n path('admin/', admin.site.urls),\r\n path('generate-time-table/', views.generate_time_table_page, name='generate_time_table'),\r\n path('view-time-table/', views.view_time_table_page, name='view_time_table'),\r\n path('test-ajax/', views.test_ajax),\r\n path('generate-time-table-api/', views.generate_time_table_api),\r\n\r\n # path('', views.home, name='home'),\r\n # path('tt/', views.main, name='main'),\r\n path('unallocate/', views.unalloc_func, name='unalloc_func'),\r\n path('unallocate/unallocate', views.unalloc_func, name='unalloc_func'),\r\n path('try/', views.try_sft, name='try_sft'),\r\n]\r\n","sub_path":"mysite/general_timetable/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"39042988","text":"import sys\nimport traceback\nimport socket\nimport sqlite3\nimport os\nimport sys\nimport requests\nimport json\nimport discord\nfrom discord.ext import commands as comm\nimport asyncio\nimport threading\nfrom datetime import datetime\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nimport update_stats\nimport constants\nfrom osuapi import OsuApi, ReqConnector\nfrom irc_commands import commands\nfrom irc_sender import UsoIrc_sender\n\nconn = sqlite3.connect(constants.Paths.beatmapDatabase)\ncursor = conn.cursor()\n\nirc_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nusername = constants.Api.IRCusername\npassword = constants.Api.IRCpassword\nRunDiscord = True\n\nprint(\"\\nConnecting to irc.ppy.sh:6667\")\nirc_socket.connect((\"irc.ppy.sh\", 6667))\n\nirc_socket.send(bytes(\"PASS \" + password + \"\\n\", \"UTF-8\"))\nirc_socket.send(bytes(\"NICK \" + username + \"\\n\", \"UTF-8\"))\nirc_socket.send(bytes(\"USER \" + username + \" \" + username + \" \" + username + \" \" + username + \"\\n\", \"UTF-8\"))\n\nirc_msg = irc_socket.recv(2048).decode(\"UTF-8\")\nirc_msg = irc_msg.strip('\\n\\r').split(\"\\r\\n\")\n\nlogsList = [] #sender_name, sender_message, date, error\n\nfor msg in irc_msg:\n\tif(\"464\" in msg):\n\t\tprint(\"Bad Authorization. Please check your login details\")\n\t\tsys.exit(0)\n\nprint(\"Connected...\\n\")\n\nirc_socket.send(bytes(\"PRIVMSG Renondedju :Connected to bancho !\\n\", \"UTF-8\"))\nirc_socket.send(bytes(\"PRIVMSG NaAb_AsD :Connected to bancho !\\n\", \"UTF-8\"))\n\nsender = UsoIrc_sender(irc_socket)\nirc_commands = commands(irc_socket, conn, sender)\nclient = comm.Bot(command_prefix='£', command_not_found='No such command !')\n\n@client.command(pass_context=True)\nasync def reboot(ctx):\n\tif str(ctx.message.author.id) == constants.Settings.ownerDiscordId:\n\t\tawait client.send_message(ctx.message.channel, \"Rebooting ...\")\n\t\tos.system('sudo sh /root/UsoBot/IRC/reboot_irc.sh')\n\telse:\n\t\tawait client.send_message(ctx.message.channel, \"I'm sorry, you can't do that\")\n\nasync def send_logs():\n\tglobal logsList, RunDiscord\n\tawait client.wait_until_ready()\n\tbotOwner = await client.get_user_info(str(constants.Settings.ownerDiscordId))\n\tchannel = client.get_channel(constants.Settings.logsChannelId)\n\twhile not client.is_closed and RunDiscord:\n\t\tif logsList:\n\t\t\tlog = logsList.pop(0)\n\t\t\tif log[3] == \"\":\n\t\t\t\tembed = discord.Embed(description = 'Bancho IRC : ' + log[1])\n\t\t\t\tembed.set_footer(text = log[2])\n\t\t\t\tembed.set_author(name = log[0] + \" - IRC\", icon_url = \"https://a.ppy.sh/\" + str(log[4]))\n\t\t\t\tawait client.send_message(channel, embed=embed)\n\t\t\telse:\n\t\t\t\tif len(log[3]) > 1900:\n\t\t\t\t\tlog[3] = log[3][0:1900] + '\\nMessage truncated ...'\n\t\t\t\tembed = discord.Embed(description = \"Message:\\n{0}\\n\\n```{1}```\".format(log[1], log[3]), colour = discord.Colour.red())\n\t\t\t\tembed.set_footer(text = log[2])\n\t\t\t\tembed.set_author(name = log[0] + \" - IRC\", icon_url = \"https://a.ppy.sh/\" + str(log[4]))\n\t\t\t\tawait client.send_message(channel, embed=embed)\n\t\t\t\tawait client.send_message(botOwner, embed=embed)\n\t\tawait asyncio.sleep(1)\n\tif not RunDiscord:\n\t\tsys.exit(0)\n\ndef start_discord_bot():\n\tclient.loop.create_task(send_logs())\n\tclient.run(constants.Api.discordIRCToken)\n\ndef log(sender_name, sender_message, osu_id, error = \"\"):\n\tdate = datetime.now().strftime('%Y/%m/%d at %H:%M:%S')\n\tlog = open(\"/root/UsoBot/IRC/logs.log\", \"a\")\n\tlog.write(date + \" - \" + sender_name + \": \" + sender_message + '\\n')\n\tlog.close()\n\tlogsList.append([sender_name, sender_message, date, error, osu_id])\n\ndef check_for_stats(osu_name):\n\tcursor.execute(\"SELECT osuId FROM users WHERE osuName = ?\", (osu_name,))\n\tosu_id = cursor.fetchall()\n\tif not osu_id:\n\n\t\tsender.send_message(osu_name, \"Hey ! Nice to meet you, it seems to be your first time here ! Remember that this bot is also available on discord [https://discord.gg/Qsw3yD5 server] [https://discordapp.com/oauth2/authorize?client_id=318357311951208448&scope=bot&permissions=8 add the bot to your server] ! Oh and also, if you need a list of the commands avaiable, type : o!help. GL & HF\")\n\n\t\tresponse = requests.get(\"https://osu.ppy.sh/api/get_user?k=\" + constants.Api.osuApiKey + \"&u=\" + osu_name, verify=True)\n\t\tdata = response.json()\n\t\tosu_id = data[0][\"user_id\"]\n\n\t\tcursor.execute(\"INSERT INTO users (osuId, osuName) VALUES (?, ?)\", (osu_id, osu_name,))\n\t\tconn.commit()\n\t\tapi = OsuApi(constants.Api.osuApiKey, connector=ReqConnector())\n\t\tupdate_stats.update_stats(0, conn, api, username = osu_name)\n\t\treturn osu_id\n\telse:\n\t\treturn osu_id[0][0]\n\ndiscordThread = threading.Thread(target=start_discord_bot)\ndiscordThread.start()\n\nrunning = True\nwhile running:\n\ttry:\n\t\t# Receive Message\n\t\tirc_messages = irc_socket.recv(2048).decode(\"UTF-8\")\n\t\t# Strip message\n\t\tirc_messages = irc_messages.strip('\\r\\n').split(\"\\n\")\n\t\t#print (irc_messages)\n\n\t\tsender.check_buffer()\n\n\t\tfor irc_msg in irc_messages:\n\t\t\t#print(irc_msg)\n\t\t\tif (\"PRIVMSG\" in irc_msg):\n\n\t\t\t\tsender_name = irc_msg.split('!', 1)[0][1:]\n\t\t\t\tsender_message = irc_msg.split('PRIVMSG', 1)[1].split(':', 1)[1]\n\t\t\t\tprivate = not \"cho@ppy.sh PRIVMSG #osu\" in irc_msg.split(\"!\", 1)[1]\n\n\t\t\t\tif private:\n\t\t\t\t\t#Logs in the console + file\n\n\t\t\t\t\tosu_id = check_for_stats(sender_name)\n\n\t\t\t\t\tprint (sender_name + \": \" + sender_message)\n\t\t\t\t\tlog(sender_name, sender_message, osu_id)\n\n\t\t\t\t\tirc_commands.message_check(sender_name, sender_message)\n\n\t\t\t# Check for Pings\n\t\t\tif (\"PING\" in irc_msg):\n\t\t\t\tsender_message = irc_msg.split(' ')[1]\n\t\t\t\tirc_socket.send(bytes(\"PONG \" + sender_message + \"\\n\", \"UTF-8\"))\n\t\t\t\tprint ('\\x1b[1;32;40m' + \"PONG \" + sender_message + '\\x1b[0m')\n\n\texcept Exception as e:\n\t\tex_type, ex, tb = sys.exc_info()\n\t\terrors = traceback.format_tb(tb)\n\t\terr = open(\"/root/UsoBot/IRC/errors.log\", \"a\")\n\n\t\tdate = datetime.now().strftime('%Y/%m/%d at %H:%M:%S')\n\n\t\terrorReport = '\\n\\n---ERROR REPORT--- ' + date + '\\n'\n\t\tfor error in errors:\n\t\t\terrorReport += error\n\t\terrorReport += '{0} : {1}'.format(type(ex).__name__, ex.args)\n\t\terrorReport += '\\nFrom {0} : {1}'.format(sender_name, sender_message)\n\n\t\terr.write(errorReport)\n\t\tprint('\\x1b[1;31;40m' + errorReport + '\\x1b[0m')\n\n\t\terr.close()\n\t\tlog(sender_name, sender_message, osu_id, error=errorReport)\n\t\tsender.send_message(sender_name, \"Oops, an error occured ... Don't worry i created a report for the devs to fix this !\")\n\texcept KeyboardInterrupt:\n\t\tRunDiscord = False\n\t\tsys.exit(0)","sub_path":"Uso!bot/IRC/irc_socket.py","file_name":"irc_socket.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"317977021","text":"# coding: utf-8\nimport os,sys,glob,re\n\nbase=os.getcwd()\nos.chdir(base)\nprint(\"typical usage1: python 02_box_SOL_ions_MM.py\\nypical usage2:python 02_box_SOL_ions_MM.py xx_tmp_fold\\nypical usage3: python 02_box_SOL_ions_MM.py restrict_MM xx_tmp_fold\")\n\n# ===== set parameter below ====================\nscript_path = '/home/phzd/g09E/gmx'\n\n# ====== end set parameter ======================\n\ndef check_determine_tmpfile(): ## using 'tmp{:0>2}'.format(), this is better, eliminating \n\t\"\"\"\n\tos.chdir(base)\n\ttmp_list = ['tmp'+str(i) for i in range(100)]\n\tfor f in tmp_list:\n\t\tif not os.path.exists(f):\n\t\t\tos.mkdir(f)\n\t\t\tprint('new tmp fold: {} was just created'.format(f))\n\t\t\treturn f\n\traise Exception('error: tmp fold seems exceed 100, need del some')\n\t\"\"\"\n\tos.chdir(base)\n\ttmp_current_list = glob.glob('tmp*')\n\tif tmp_current_list == []: \t\t\n\t\tos.mkdir('tmp00')\n\t\tprint('new tmp fold: {} was just created'.format('tmp00'))\n\t\treturn 'tmp00'\n\t\"\"\"\t\t\t\n\ttmp_max_fold = sorted(tmp_current_list)[-1]\n\tnum = int(tmp_max_fold[3:])\n\t\"\"\"\n\ttmp_list_txt = ' '.join(tmp_current_list)\n\tpattern = re.compile(\"tmp(\\d+)\")\n\tmatch = re.findall(pattern, tmp_list_txt)\n\tnum_list = [int(i) for i in match]\t\n\tnum = max(num_list)\n\tif num > 99: raise IOError('error: tmp fold seems exceed 100, need del some')\n\tnew_tmp = 'tmp{:0>2}'.format(str(num+1))\n\tos.mkdir(new_tmp)\n\tprint('new tmp fold: {} was just created'.format(new_tmp))\t\n\treturn new_tmp\n\ndef check_determine_tmpfile(): ## using 'tmp{:0>2}'.format(), this is better, eliminating \n\t\"\"\"\n\tos.chdir(base)\n\ttmp_list = ['tmp'+str(i) for i in range(100)]\n\tfor f in tmp_list:\n\t\tif not os.path.exists(f):\n\t\t\tos.mkdir(f)\n\t\t\tprint('new tmp fold: {} was just created'.format(f))\n\t\t\treturn f\n\traise Exception('error: tmp fold seems exceed 100, need del some')\n\t\"\"\"\n\tos.chdir(base)\n\ttmp_current_list = glob.glob('tmp*')\n\tif tmp_current_list == []: \t\t\n\t\tos.mkdir('tmp00')\n\t\tprint('new tmp fold: {} was just created'.format('tmp00'))\n\t\treturn 'tmp00'\n\t\"\"\"\t\t\t\n\ttmp_max_fold = sorted(tmp_current_list)[-1]\n\tnum = int(tmp_max_fold[3:])\n\t\"\"\"\n\ttmp_list_txt = ' '.join(tmp_current_list)\n\tpattern = re.compile(\"tmp(\\d+)\")\n\tmatch = re.findall(pattern, tmp_list_txt)\n\tnum_list = [int(i) for i in match]\t\n\tnum = max(num_list)\n\tif num > 99: raise IOError('error: tmp fold seems exceed 100, need del some')\n\tnew_tmp = 'tmp{:0>2}'.format(str(num+1))\n\tos.mkdir(new_tmp)\n\tprint('new tmp fold: {} was just created'.format(new_tmp))\t\n\treturn new_tmp\n\ndef read_restrict_MM_threads_from_parameters(xx_path): \n\t\"\"\"\nligand_charge: \nrestrict_MM_threads: \nem_mdp_file: \n\t\"\"\"\n\tos.chdir(xx_path)\n\tprint('read_restrict_MM_threads_from_parameters')\n\tf = open('gmx_run_parameters','r')\n\ttxt = f.read()\n\tf.close()\n\tpattern1 = re.compile('restrict_MM_threads: *(\\d+)')\n\tpattern2 = re.compile('em_mdp_file: *([+-]*\\d+)')\n\tpattern3 = re.compile('-conc *(\\d+\\.\\d+)')\n\tmatch1 = re.findall(pattern1,txt)\n\tmatch3 = re.findall(pattern3,txt)\n\t#match2 = \n\tif match1: restrict_MM_threads = int(match1[0])\n\telse: \n\t\tprint('no restrict_MM_threads was found in gmx_run_parameters file, will use 10 as default')\n\t\trestrict_MM_threads = 10\n\tion_conc = match3[0] if match3 else \"\"\n\treturn restrict_MM_threads, ion_conc\n\n# ========= begin tmp_fold below =====================\t\ndef deal_with_tmp_fold(xx_tmp_fold):\n\tprint('checking tmp fold ...')\t\n\ttmp_full_path = base + '/' + xx_tmp_fold\n\tos.chdir(base)\n\t#os.system('cp mdp/*.mdp {0}/ && cp complex.gro topol.top ligand_GMX.itp posre.itp posre_ligand.itp gmx_run_parameters {0}/'.format(tmp_full_path))\n\tos.system('cp mdp/*.mdp {0}/ && cp complex.gro topol.top ligand_GMX.itp posre*.itp topol_Protein*.itp gmx_run_parameters {0}/'.format(tmp_full_path))\n\tos.chdir(tmp_full_path)\n\t#for f in ['complex.gro', 'topol.top', 'ligand_GMX.itp', 'posre.itp', 'posre_ligand.itp']:\n\tfor f in ['complex.gro', 'topol.top', 'ligand_GMX.itp', 'posre_ligand.itp']:\n\t\tif not os.path.exists(f):raise Exception('error: key necessary file: {} was not found in the new tmp fold: {}'.format(f,xx_tmp_fold))\n\tif len(glob.glob('posre.itp')) + len(glob.glob('posre_Protein*.itp')) ==0:raise Exception('error: key necessary file posre missing')\n\treturn tmp_full_path\n\n# ========= end tmp_fold below =====================\t\n\n\n# ========= begin box, solvate, .tpr, ions steps below =====================\t\ndef box_solvate_tpr_ions(xx_tmp_full_path):\n\tos.chdir(xx_tmp_full_path)\n\tprint('now processing box, solvate, .tpr, ions steps')\n\n\tos.system(\"source /opt/gmx2018.4/bin/GMXRC\")\n\t## set box\n\tfor f in ['complex.gro']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file was missing in box step'.format(f))\n\tos.system('/opt/gmx2018.4/bin/gmx editconf -f complex.gro -o complex_box.gro -d 1.0 -bt cubic')\n\n\t# solvate\n\tfor f in ['complex_box.gro']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file was missing in solvate step'.format(f))\n\tos.system('/opt/gmx2018.4/bin/gmx solvate -cp complex_box.gro -o complex_SOL.gro -p topol.top')\n\n\t# Use grompp to assemble a .tpr file, using any .mdp file. such as em.mdp energy minimization, \n\tfor f in ['complex_SOL.gro']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file was missing in grompp to assemble a .tpr file step'.format(f))\n\tos.system('/opt/gmx2018.4/bin/gmx grompp -f em.mdp -c complex_SOL.gro -p topol.top -o em.tpr -maxwarn 5')\n\n\t## add ions: pass our .tpr file to genion: \n\tion_conc = read_restrict_MM_threads_from_parameters(xx_tmp_full_path)[1]\n\tconc_txt = '-conc {}'.format(ion_conc) if ion_conc != '' else ''\n\tif conc_txt: print('will use NaCl in {}'.format(conc_txt))\n\tfor f in ['em.tpr']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file was missing in add ions step'.format(f))\n\tos.system(\"echo 'SOL' |/opt/gmx2018.4/bin/gmx genion -s em.tpr -p topol.top -o system.gro -neutral {}\".format(conc_txt)) # -pname NA -nname CL; 0.15M NaCl, would be better in principle\n\tprint('done with: tmp_fold, box, solvate, .tpr, ions steps')\n\treturn\n# ========= end tmp_fold, box, solvate, .tpr, ions steps =====================\t\n\n\n# ========= begin minimization below =====================\t\n## minimization\ndef minimization(xx_tmp_full_path):\n\tprint('now minimization ...')\n\tos.chdir(xx_tmp_full_path)\n\tfor f in ['em.mdp','system.gro']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file was missing in add ions step'.format(f))\n\tos.system(\"/opt/gmx2018.4/bin/gmx grompp -f em.mdp -c system.gro -p topol.top -o em.tpr && /opt/gmx2018.4/bin/gmx mdrun -v -deffnm em -nt 6\")\n\t## will generate 4 new files: em.log, em.gro, em.trr, em.edr\n\tfor f in ['em.log', 'em.gro', 'em.trr', 'em.edr']:\n\t\tif not os.path.exists(f):raise Exception('error: minimization failed, no {} file was not generated after this minimization step'.format(f))\n\treturn\n# ========= end minimization ===========================\t\n\n\n# ========= begin restricted MM below =====================\t\ndef restricted_MM(xx_tmp_full_path):\n\tprint('now restricted MM ...')\n\tos.chdir(xx_tmp_full_path)\n\tfor f in ['pr.mdp','em.gro','topol.top']:\n\t\tif not os.path.exists(f):raise Exception('error: no {} file as required was found in restricted MM step '.format(f))\n\trestrict_MM_threads = 10\n\tos.chdir(xx_tmp_full_path)\n\tif os.path.exists('gmx_run_parameters'):restrict_MM_threads = read_restrict_MM_threads_from_parameters(xx_tmp_full_path)[0]\n\tos.chdir(xx_tmp_full_path)\n\tbashline = '/opt/gmx2018.4/bin/gmx grompp -f pr.mdp -c em.gro -r em.gro -p topol.top -o pr.tpr' # \n\tbashline1 = '/opt/gmx2018.4/bin/gmx mdrun -v -deffnm pr -nt {} -pin on '.format(str(restrict_MM_threads))\n\tos.system(bashline)\n\tos.system(bashline1)\n\tprint('done with restict_MM, and the fold is :{}'.format(xx_tmp_full_path))\n# ========= end restricted MM below =====================\t\n\ndef main():\n\ttry:\n\t\targs = sys.argv[1:]\n\t\tprint('args = ',args)\n\texcept:\n\t\tprint('no args was found')\n\ttmp_fold = ''\n\tif len(args) == 0: # normal process\n\t\ttmp_fold = check_determine_tmpfile()\n\t\ttmp_full_path = deal_with_tmp_fold(tmp_fold)\n\t\tbox_solvate_tpr_ions(tmp_full_path)\n\t\tminimization(tmp_full_path)\n\t\trestricted_MM(tmp_full_path)\t\t\n\t\treturn\n\tif len(args) > 0 and ('restrict' in args[0]) and ('MM' in args[0]):\n\t\tif len(args) == 1: raise Exception('error, to run restrict_MM only, please specify tmp_fold')\n\t\tif len(args) >= 1: \n\t\t\ttmp_fold = args[1]\n\t\t\ttmp_full_path = '{}/{}'.format(base,tmp_fold)\n\t\t\tprint('tmp_full_path is:{}, will use this do only estrict_MM step'.format(tmp_full_path))\n\t\t\trestricted_MM(tmp_full_path)\n\t\t\treturn\n\telse: ## specify tmp_fold, and do box_solvate_tpr_ions, minimization and restricted_MM\n\t\ttmp_fold = args[0]\n\t\ttmp_full_path = '{}/{}'.format(base,tmp_fold)\n\t\tbox_solvate_tpr_ions(tmp_full_path)\n\t\tminimization(tmp_full_path)\n\t\trestricted_MM(tmp_full_path)\n\t\treturn\t\t\n\t\t\nif __name__ == '__main__':\n\tmain()\n\n\n","sub_path":"02_box_SOL_ions_MM.py","file_name":"02_box_SOL_ions_MM.py","file_ext":"py","file_size_in_byte":8763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"389582896","text":"import sys\nfrom PyQt4 import QtCore, QtGui\nfrom common.lib.clients.qtui.switch import QCustomSwitchChannel\nfrom common.lib.clients.qtui.QCustomSpinBox import QCustomSpinBox\nimport sys\nfrom common.lib.clients.qtui.q_custom_text_changing_button import TextChangingButton\n\n\nclass StretchedLabel(QtGui.QLabel):\n def __init__(self, *args, **kwargs):\n QtGui.QLabel.__init__(self, *args, **kwargs)\n self.setMinimumSize(QtCore.QSize(500, 300))\n\n def resizeEvent(self, evt):\n font = self.font()\n font.setPixelSize(self.width() * 0.14 - 14)\n self.setFont(font)\n\n\nclass QCustomWindfreakSubGui(QtGui.QFrame):\n def __init__(self, parent=None, title=\"Windfreak\"):\n QtGui.QWidget.__init__(self, parent)\n self.setFrameStyle(0x0001 | 0x0030)\n self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n self.title = title\n self.makeLayout()\n self.font = QtGui.QFont('MS Shell Dlg 2', pointSize=16)\n\n def makeLayout(self):\n qBoxLayout = QtGui.QVBoxLayout()\n qBox = QtGui.QGroupBox(self.title)\n layout = QtGui.QGridLayout()\n\n self.freq_input = QCustomSpinBox('Frequency (MHz)', (53.0, 14800.0), parent=self)\n self.power_input = QCustomSpinBox('Power (dBm)', (-80.0, 17.0), parent=self)\n\n self.onoff_button = TextChangingButton('RF output', parent=self)\n\n self.sweep_low_freq_input = QCustomSpinBox('Sweep Low Freq (MHz)', (53.0, 14800.0), parent=self)\n self.sweep_high_freq_input = QCustomSpinBox('Sweep High Freq (MHz)', (53.0, 14800.0), parent=self)\n\n self.sweep_freq_step_input = QCustomSpinBox('Sweep Freq Step (MHz)', (0.001, 50.0), parent=self)\n self.sweep_time_step_input = QCustomSpinBox('Sweep Time Step (ms)', (4.0, 10000.0), parent=self)\n\n self.sweep_low_power_input = QCustomSpinBox('Sweep Low Power (dBm)', (-80.0, 17.0), parent=self)\n self.sweep_low_power_input.setDecimals(1)\n self.sweep_high_power_input = QCustomSpinBox('Sweep High Power (dBm)', (-80.0, 17.0), parent=self)\n self.sweep_high_power_input.setDecimals(1)\n\n self.sweep_onoff_button = TextChangingButton('Sweep', parent=self)\n self.sweep_single_onoff_button = TextChangingButton('Sweep Single', parent=self)\n\n # layout 1 row at a time\n layout.addWidget(self.freq_input, 1, 0, 1, 1)\n layout.addWidget(self.power_input, 1, 1, 1, 1)\n\n layout.addWidget(self.onoff_button, 2, 0, 1, 2)\n\n layout.addWidget(self.sweep_low_freq_input, 3, 0, 1, 1)\n layout.addWidget(self.sweep_high_freq_input, 3, 1, 1, 1)\n\n layout.addWidget(self.sweep_low_power_input, 4, 0, 1, 1)\n layout.addWidget(self.sweep_high_power_input, 4, 1, 1, 1)\n\n layout.addWidget(self.sweep_freq_step_input, 5, 0, 1, 1)\n layout.addWidget(self.sweep_time_step_input, 5, 1, 1, 1)\n\n layout.addWidget(self.sweep_onoff_button, 6, 0, 1, 1)\n layout.addWidget(self.sweep_single_onoff_button, 6, 1, 1, 1)\n\n layout.minimumSize()\n qBox.setLayout(layout)\n qBoxLayout.addWidget(qBox)\n\n self.setLayout(qBoxLayout)\n\n\nclass QCustomWindfreakGui(QtGui.QFrame):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.setFrameStyle(0x0001 | 0x0030)\n self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.MinimumExpanding)\n self.makeLayout()\n\n def makeLayout(self):\n layout = QtGui.QGridLayout()\n qBox = QtGui.QGroupBox('Windfreak SynthHD')\n sublayout = QtGui.QHBoxLayout()\n self.a = QCustomWindfreakSubGui(title=\"Channel A\")\n self.b = QCustomWindfreakSubGui(title=\"Channel B\")\n sublayout.addWidget(self.a)\n sublayout.addWidget(self.b)\n qBox.setLayout(sublayout)\n layout.addWidget(qBox, 0, 0)\n\n layout.minimumSize()\n\n self.setLayout(layout)\n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n icon = QCustomWindfreakGui()\n icon.show()\n app.exec_()\n","sub_path":"clients/windfreak_client/windfreak_gui.py","file_name":"windfreak_gui.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"1170392","text":"import os\nimport shutil\n\n\nrootDir = \"../data/\"\n\nempty = 0\nnotEmpty = 0\nsingleEntry = 0\n\nfor folder in os.scandir(rootDir):\n path = os.path.join(rootDir, folder.name)\n print(path)\n path = os.path.join(path, \"HTML\")\n size = os. listdir(path)\n length = len(size)\n print(\"{} contains {} files\".format(folder.name, length))\n if length == 0:\n print(\"folder is empty\")\n empty += 1\n elif length == 1:\n print(\"folder has a single entry\")\n singleEntry += 1\n else:\n notEmpty += 1\n print(\"============================\")\n\n\nprint(\"{} empty files\".format(empty))\n\nprint(\"{} files are not empty\".format(notEmpty))\n\nprint(\"{} files have a single entry\".format(singleEntry))\n\n# for subdir, dirs, files in os.walk(rootDir):\n\n","sub_path":"scraper/serializeEmptyDirs.py","file_name":"serializeEmptyDirs.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"590629155","text":"import discord\nfrom discord.ext import commands\nfrom discord.utils import get\n\nclass Voice(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_voice_state_update(self, member, before, after): # just for fun strictly joining and disconnecting.\n\n voice = get(self.client.voice_clients, guild=member.guild)\n if voice and not member.bot:\n if not voice.is_playing() and not voice.is_paused():\n if before.channel and not after.channel:\n if before.channel == voice.channel:\n voice.stop()\n voice.play(discord.FFmpegPCMAudio(\"UserDC.mp3\"))\n voice.source = discord.PCMVolumeTransformer(voice.source)\n voice.source.volume = 0.200\n elif after.channel and not before.channel:\n if after.channel == voice.channel:\n voice.stop()\n voice.play(discord.FFmpegPCMAudio(\"UserJC.mp3\"))\n voice.source = discord.PCMVolumeTransformer(voice.source)\n voice.source.volume = 0.200\n\n\ndef setup(client):\n client.add_cog(Voice(client))","sub_path":"cogs/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"114639552","text":"#! C:\\Python36\\python.exe\n# coding:utf-8\n'''\n·使用gevent的睡眠机制,联合四个协程函数,打印一首小诗(gevent.sleep())\n·使用gevent的睡眠机制,联合四个写成函数,讲述浏览器的故事\n----------\n@笔记\n·gevent一旦阻塞/睡眠,就会自动让出CPU执行权\n·执行权会优先传递给不阻塞/不睡眠或阻塞睡眠时间较短的协程函数\n·对于阻塞/睡眠时间相同的协程函数,按照joinall的顺序分配CPU执行权\n'''\nimport gevent\n\n\ndef geventFunc1():\n gevent.sleep(0)\n print(\"红军不怕远征难\")\n gevent.sleep(5) # 模拟阻塞\n\n print(\"金沙水拍云崖暖\")\n\n\ndef geventFunc2():\n gevent.sleep(1)\n print(\"万水千山只等闲\")\n gevent.sleep(5) # 模拟阻塞\n\n print(\"大渡桥横铁索寒\")\n\n\ndef geventFunc3():\n gevent.sleep(2)\n print(\"五岭逶迤腾细浪\")\n gevent.sleep(5) # 模拟阻塞\n\n print(\"更喜岷山千里雪\")\n\n\ndef geventFunc4():\n gevent.sleep(3)\n print(\"乌蒙磅礴走泥丸\")\n gevent.sleep(5) # 模拟阻塞\n\n print(\"三军过后尽开颜\")\n\n\ndef helloGevent():\n # 没有阻塞/睡眠的时候,按顺序执行\n gevent.joinall([\n gevent.spawn(geventFunc1),\n gevent.spawn(geventFunc3),\n gevent.spawn(geventFunc2),\n gevent.spawn(geventFunc4),\n ])\n\n\ndef chrome(request):\n gevent.sleep(1)\n print(\"chrome:\", questionDict[request])\n\n\ndef firefox(request):\n gevent.sleep(1)\n print(\"firefox:\", questionDict[request])\n\n\ndef safari(request):\n gevent.sleep(1)\n print(\"safari:\", questionDict[request])\n\n\ndef ie(request):\n gevent.sleep(9)\n print(\"ie:\", questionDict[request])\n\n\nquestionDict = {\n \"我们是什么?\": \"浏览器\",\n \"我们要什么?\": \"速度\",\n \"什么时候要?\": \"现在\",\n}\n\n\ndef browserStory():\n questions = list(questionDict.keys())\n for i in range(len(questions)):\n question = questions[i]\n print(question)\n gevent.joinall([\n gevent.spawn(ie, question),\n gevent.spawn(firefox, question),\n gevent.spawn(safari, question),\n gevent.spawn(chrome, question),\n ], timeout=3)\n\n\nif __name__ == \"__main__\":\n # helloGevent()\n # browserStory()\n\n print(\"main over\")\n","sub_path":"day1/1025/demos/W4/day4/04Gevent.py","file_name":"04Gevent.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"275767703","text":"#!usr/bin/env python\r\n# coding=utf-8\r\n\"\"\"\r\n@author: holens\r\n@time: 2018/09/02\r\n@desc: 日志配置\r\n\"\"\"\r\nimport os\r\n\r\nLOG_PATH = os.getenv(\"LOG_PATH\", \"\")\r\nFILE_FORMAT = (\r\n \"%(asctime)s | %(levelname)s | %(process)s | %(threadName)s\"\r\n \" | %(name)s | %(pathname)s:%(funcName)s | %(lineno)s | %(message)s\"\r\n)\r\nCONSOLE_FORMAT = (\r\n \"%(asctime)s, %(levelname)s - \"\r\n \"%(name)s %(filename)s:%(funcName)s - %(lineno)s: %(message)s\"\r\n)\r\nLOG_FILE_PATH = os.path.join(LOG_PATH, \"{server_name}.log\")\r\nROTATE_FILE_SIZE = 10000000\r\nN_BACKUP_FILE = 5\r\nDATEFMT = \"%Y-%m-%d %H:%M:%S\"\r\n","sub_path":"xxw/chaos/src/config/logconfig.py","file_name":"logconfig.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"558671612","text":"import RPi.GPIO as GPIO\nfrom time import sleep\n\nclass Servo:\n\n pin = 0\n pwm = \"\"\n sleepInterval = 0.02\n frequency = 50\n __constFactor = 0.05556\n resetValue = 0\n\n\n def __init__ (self, pin, resetValue):\n\n self.pin = pin\n GPIO.setup(self.pin, GPIO.OUT)\n \n self.pwm = GPIO.PWM(self.pin, self.frequency)\n self.resetValue = resetValue\n self.pwm.start(self.resetValue)\n\n\n def __del__(self):\n self.rotate(self.resetValue)\n self.pwm.stop()\n\n\n def reset(self):\n self.rotate(self.resetValue)\n\n\n def rotate(self, degree):\n cycle = self.__convertFromDegreeToCycle(degree)\n self.pwm.ChangeDutyCycle(cycle)\n sleep(self.sleepInterval)\n\n\n def __convertFromDegreeToCycle(self, degree):\n \n if degree < 0:\n degree += 180\n\n if degree > 180:\n degree -= 180\n \n return round(2.5 + (degree*self.__constFactor), 2)\n \n","sub_path":"py/servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"240218137","text":"\"\"\"\nThe chart showing the details of the participants in the study\n\"\"\"\nprint(\"Loading patients\") \n\nfrom plotly.graph_objs import *\nimport plotly.io as pio\nimport pandas as pd\nfrom plotly import graph_objs as go\nfrom plotly.graph_objs import *\nimport time\nimport re\nimport datetime\nfrom django_plotly_dash import DjangoDash\nfrom dash.dependencies import Input, Output\nimport dash_html_components as html\nimport dash_core_components as dcc\n\n# General notes: I've only checked a few points to see if this works. One issue is that dots in the same year for the same patient overlap each othe\n# this can be solved by offsetting them slightly or a better way would be for the Y axis to show the full date rather than just the year\n# since every swab will have a diff day and none should overlap\n# will upload dataset with full dates soon. If you need help with filtering dataframes or whatever check the other visualisations \n# minor things: more space between patients, order patients numerically \n\napp = DjangoDash('patients')\ndf = pd.DataFrame(pd.read_csv('static/data/patientData.csv'))\n# another dataframe to keep patient IDs without unicode symbols\ndf2 = pd.DataFrame(pd.read_csv('static/data/patientData.csv'))\ndef patient_load():\n\n\n for i in range(len(df)):\n if (df.loc[i, \"HIVexposed\"]==True):\n df.loc[i, \"participant_id\"]=df.loc[i, \"participant_id\"]+\" \"+'\\U0001f397'\n\n for i in range(len(df)):\n if (df.loc[i, \"sex\"]==\"Male\"):\n df.loc[i, \"participant_id\"]=df.loc[i, \"participant_id\"]+\" \"+'\\u2642'\n\n for i in range(len(df)):\n if (df.loc[i, \"sex\"]==\"Female\"):\n df.loc[i, \"participant_id\"]=df.loc[i, \"participant_id\"]+\" \"+'\\u2640'\n\n for i in range(len(df)):\n if (df.loc[i, \"DateVaccinated\"]!=\" \"):\n df.loc[i, \"participant_id\"]=df.loc[i, \"participant_id\"]+\" \"+'\\uD83D\\uDC89'\n\n for i in range(len(df)):\n if (df.loc[i, \"SmokingExposed\"]==\"True\"):\n df.loc[i, \"participant_id\"]=df.loc[i, \"participant_id\"]+\" \"+'\\uD83D\\uDEAC'\n\n\ndef gen_graph(dfName):\n \n if dfName.empty:\n raise Exception(\"Empty dataframe given\")\n\n trace1 = {\n \"mode\": \"markers\", \n \"type\": \"scatter\", \n \"x\": dfName[\"participant_id\"], \n \"y\": dfName[\"swabDate\"],\n # \"hoverinfo\": \"text\",\n # \"hovertext\": [[\"participant_id: {}
Serotype: {}
Date: {}\".format(i,j,k)]\n # for i,j,k in zip(df2[\"participant_id\"],df[\"serotype\"],df[\"swabDate\"])],\n #I think the above doesn't show up because the graph space is so small, fix somehow\n \"name\": \"Date of Serotype Colonization\",\n \n } #you would need to do this for every serotype present in the file using a loop. Make sure the x and y vals still correspond though \n trace2 = {\n \"mode\": \"markers\", \n \"type\": \"scatter\", \n \"x\": dfName[\"participant_id\"], \n \"y\": dfName[\"DateVaccinated\"],\n \"name\": \"Vaccination Date\"\n }\n\n return {\n \"data\" : [trace1, trace2],\n\n \"layout\": layout\n }\n\n\n\nlayout = dict(\n title = 'Patient Timelines',\n yaxis = go.layout.YAxis(title = 'Year',type='date',range=['2011-01-01','2017-01-01']),\n xaxis = go.layout.XAxis(title = 'Patient',type='category'\n ),\n yaxis_range=[datetime.datetime(2012,1,1),\n datetime.datetime(2017,1,1)],\n\n\n annotations= [{\n \"text\": \" \\U0001f397 = HIV Exposed \\uD83D\\uDEAC = Smoking Exposed \\u2642 = Male \\u2640 = Female \\uD83D\\uDC89 = Vaccinated \",\n \"font\": {\n \"size\": 13,\n \"color\": 'rgb(116, 101, 130)',\n },\n \"showarrow\": False,\n \"align\": 'center',\n \"x\": 0.5,\n \"y\": 1,\n \"xref\": 'paper',\n \"yref\": 'paper',\n }]\n\n )\n\n\n\n\napp.layout = html.Div(\n children=[\n html.H1(\"Filter patients by sex: \"),\n # html.Div(children=''''''),\n dcc.Checklist(\n id='filter',\n options=[\n {'label': 'Male'+'\\u2642', 'value': 'Male'},\n {'label': 'Female'+'\\u2640', 'value': 'Female'}\n ],\n value=['Male', 'Female'],\n labelStyle={'display': 'inline-block'}\n ),\n dcc.Graph(\n id='patient-graph',\n figure={\n \n }),\n\n ],\n style={'padding-bottom': '0%', 'height': 0,'font-family':'sans-serif'},\n)\n\n\n@app.callback(\n Output('patient-graph', 'figure'),\n [Input('filter','value')]\n)\ndef update_graph(filters):\n \"\"\" apply patient filters \"\"\"\n \n temp_df=df.loc[df['sex'].isin(filters)]\n\n if temp_df.empty:\n temp_df=df\n\n\n return gen_graph(temp_df)\nprint(\"Finished loading patients\")\n\n\nimport threading\npatient_thread = threading.Thread(target=patient_load, args=(), kwargs={})\npatient_thread.setDaemon(True)\npatient_thread.start()","sub_path":"pneumovis/pages/dash_app_dir/patients.py","file_name":"patients.py","file_ext":"py","file_size_in_byte":4673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"442742064","text":"#!/usr/bin/env python\n\nimport rospy\nfrom sensor_msgs.msg import PointCloud2, PointField\nimport numpy as np\nfrom sensor_msgs.point_cloud2 import create_cloud\nfrom std_msgs.msg import Header\n\ndef draw_branch(start, end, n, scatter=0.0):\n \"\"\"\n Creates a set of points\n :param start: (x,y,z) coord of where to start the branch\n :param end: (x,y,z) coord of where to end the branch\n :param n:\n :return:\n \"\"\"\n\n pt_array = np.linspace(start, end, n)\n if scatter:\n normals = np.random.randn(*pt_array.shape)\n rads = np.random.uniform(0, scatter, normals.shape[0])\n\n noise = normals / np.linalg.norm(normals, axis=1)[:,None] * rads[:,None]\n pt_array += noise\n\n points = pt_array.tolist()\n return points\n\n\nif __name__ == '__main__':\n\n trunk = draw_branch([0,0,0], [0,0,1], 400, 0.01)\n branch_1 = draw_branch([0,0,1], [0.5, 0, 1.5], 300, 0.01)\n branch_2 = draw_branch([0, 0, 1], [-0.5, 0, 1.5], 300, 0.01)\n\n all_pts = trunk + branch_1 + branch_2\n header = Header()\n header.frame_id = 'base_link'\n\n fields = [\n PointField('x', 0, PointField.FLOAT32, 1),\n PointField('y', 4, PointField.FLOAT32, 1),\n PointField('z', 8, PointField.FLOAT32, 1),\n ]\n\n pc = create_cloud(header, fields, all_pts)\n\n rospy.init_node('sample_pc_publisher')\n\n pub = rospy.Publisher('sample_pc', PointCloud2, queue_size=1)\n\n rate = rospy.Rate(10)\n rospy.loginfo('Now publishing PC!')\n while not rospy.is_shutdown():\n pub.publish(pc)\n rate.sleep()\n\n\n\n\n","sub_path":"src/sample_pc_broadcaster.py","file_name":"sample_pc_broadcaster.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"211269435","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 18 20:57:37 2021\n\n@author: USER\n\"\"\"\n\nimport pydot\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndata_ku = pd.read_csv('data_kartu_kredit.csv');\ndata_ku.shape\n\nfrom sklearn.preprocessing import StandardScaler\ndata_ku['standar'] = StandardScaler().fit_transform(data_ku['Amount'].values.reshape(-1,1))\n\ny = np.array(data_ku.iloc[:,-2])\nX = np.array(data_ku.drop(['Time','Amount','Class'], axis=1))\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2 ,\n random_state=111)\n\nX_train, X_validate, y_train, y_validate = train_test_split(X_train,y_train,\n test_size=0.2,\n random_state=111)\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nclassifier = Sequential()\nclassifier.add(Dense(units=16, input_dim=29, activation='relu'))\nclassifier.add(Dense(units=24, activation='relu'))\nclassifier.add(Dropout(0.25))\nclassifier.add(Dense(units=20, activation='relu'))\nclassifier.add(Dense(units=24, activation='relu'))\nclassifier.add(Dense(units=1, activation='sigmoid'))\nclassifier.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=('accuracy'))\nclassifier.summary()\n\nfrom keras.utils.vis_utils import plot_model\nplot_model(classifier, to_file ='model_ann.png', show_shapes=True,\n show_layer_names=False)\n\nrun_model = classifier.fit(X_train, y_train,\n batch_size = 32,\n epochs= 5,\n verbose = 1,\n validation_data = (X_validate, y_validate))\n\nprint(run_model.history.keys())\n\nplt.plot(run_model.history['accuracy'])\nplt.plot(run_model.history['val_accuracy'])\nplt.title('model accuracy')\nplt.xlabel('accuracy')\nplt.ylabel('epoch')\nplt.legend(['train','validate'], loc ='upper left')\nplt.show()\n\nplt.plot(run_model.history['loss'])\nplt.plot(run_model.history['val_loss'])\nplt.title('model loss')\nplt.xlabel('loss')\nplt.ylabel('epoch')\nplt.legend(['train','validate'], loc ='upper left')\nplt.show()\n\nevaluasi = classifier.evaluate(X_test,y_test)\nprint('akurasi:{:.2f}'.format(evaluasi[1]*100))\n\nhasil_prediksi = classifier.predict_classes(X_test)\n\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, hasil_prediksi)\ncm_label = pd.DataFrame(cm, columns=np.unique(y_test),index=np.unique(y_test))\ncm_label.index.name = 'aktual'\ncm_label.columns.name = 'prediksi'\n\nsns.heatmap(cm_label, annot=True, Cmap='Reds', fmt='g')\n\n\nfrom sklearn.metrics import classification_report\njumlah_kategori = 2\ntarget_names = ['class{}'.format(i) for i in range(jumlah_kategori)]\nprint(classification_report(y_test, hasil_prediksi,target_names=target_names))\n\n\n\n\n\n#under sampling method\n\n\n\nindex_fraud = np.array(data_ku[data_ku.Class == 1].index)\nn_fraud = len(index_fraud)\nindex_normal = np.array(data_ku[data_ku == 0].index)\nindex_data_normal = np.random.choice(index_normal, n_fraud, replace=False )\nindex_data_baru = np.concatenate([index_fraud, index_data_normal])\ndata_baru = data_ku.iloc[index_data_baru,:]\n\ny_baru = np.array(data_baru.iloc[:,-2])\nX_baru = np.array(data_baru.drop(['Time','Amount','Class'], axis=1))\n\n\nX_train2, X_test_final, y_train2, y_test_final = train_test_split(X_baru,y_baru,\n test_size = 0.1,\n random_state=111)\n\nX_train2, X_test2, y_train2, y_test2 = train_test_split(X_train2,y_train2,\n test_size = 0.1 ,\n random_state=111)\n\n\nX_train2, X_validate2, y_train2, y_validate2 = train_test_split(X_train2,y_train2,\n test_size=0.2,\n random_state=111)\n\n\nclassifier2 = Sequential()\nclassifier2.add(Dense(units=16, input_dim=29, activation='relu'))\nclassifier2.add(Dense(units=24, activation='relu'))\nclassifier2.add(Dropout(0.25))\nclassifier2.add(Dense(units=20, activation='relu'))\nclassifier2.add(Dense(units=24, activation='relu'))\nclassifier2.add(Dense(units=1, activation='sigmoid'))\nclassifier2.compile(optimizer='adam', loss='binary_crossentropy',\n metrics=('accuracy'))\nclassifier.summary()\n\n\nrun_model2 = classifier2.fit(X_train2, y_train2,\n batch_size = 8,\n epochs= 5,\n verbose = 1,\n validation_data = (X_validate2, y_validate2))\n\nprint(run_model2.history.keys())\n\nplt.plot(run_model2.history['accuracy'])\nplt.plot(run_model2.history['val_accuracy'])\nplt.title('model accuracy')\nplt.xlabel('accuracy')\nplt.ylabel('epoch')\nplt.legend(['train','validate'], loc ='upper left')\nplt.show()\n\nplt.plot(run_model2.history['loss'])\nplt.plot(run_model2.history['val_loss'])\nplt.title('model loss')\nplt.xlabel('loss')\nplt.ylabel('epoch')\nplt.legend(['train','validate'], loc ='upper left')\nplt.show()\n\nevaluasi2 = classifier2.evaluate(X_test2,y_test2)\nprint('akurasi:{:.2f}'.format(evaluasi2[1]*100))\n\nhasil_prediksi2 = classifier2.predict_classes(X_test2)\n\ncm2 = confusion_matrix(y_test2, hasil_prediksi2)\ncm_label2 = pd.DataFrame(cm2, columns=np.unique(y_test2),index=np.unique(y_test2))\ncm_label2.index.name = 'aktual'\ncm_label2.columns.name = 'prediksi'\n\nsns.heatmap(cm_label2, annot=True, Cmap='Reds', fmt='g')\n\n\nprint(classification_report(y_test2, hasil_prediksi2,target_names=target_names))\n\n#pengujian model standart dan under sampling\n\nhasil_prediksi3 = classifier2.predict_classes(X_test_final)\ncm3 = confusion_matrix(y_test_final, hasil_prediksi3)\ncm_label3 = pd.DataFrame(cm3, columns=np.unique(y_test_final),index=np.unique(y_test_final))\ncm_label3.index.name = 'aktual'\ncm_label3.columns.name = 'prediksi'\nsns.heatmap(cm_label3, annot=True, Cmap='Reds', fmt='g')\n\nprint(classification_report(y_test_final, hasil_prediksi3,target_names=target_names))\n\n#save model\nclassifier2.save('model_ann_kartu_kredit.hd5',include_optimizer=True)\nprint('alhamdulillah model sudah disimpan :) have an nice day')\n\n","sub_path":"pengklasifikasian data kartu kredit menggunakan metode ann.py","file_name":"pengklasifikasian data kartu kredit menggunakan metode ann.py","file_ext":"py","file_size_in_byte":6422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"304774981","text":"# -*- coding: utf-8 -*-\r\n# utf8ize.py - usage: python utf8ize.py root_dir\r\n# to decode all text files in root_dir and encoding with utf-8\r\n# author: xiao yang \r\n# date: 2016.Feb.26\r\nimport os\r\nimport sys\r\nimport re\r\nimport chardet\r\n\r\nfrom traverse import traverse\r\n\r\n# sub_parser = re.compile('^([\\s\\w]+?\\.pcm\\s*\\n)+', re.MULTILINE)\r\nblank_parser = (re.compile('^.*\\.pcm\\s*\\n', re.MULTILINE), '')\t# remove line with pcm and empty ones\r\n\r\n# remove lines with pcm names and insert correct names into the first line\r\ndef encode(src_file, _):\r\n\twith open(src_file, 'rb') as f:\r\n\t\traw_data = f.read()\r\n\t\tcoding = chardet.detect(raw_data)['encoding']\r\n\r\n\tif coding != 'utf-8':\r\n\t\tdata = raw_data.decode(coding)\r\n\t\twith open(src_file, 'w') as f:\r\n\t\t\tf.write(data.encode('utf-8'))\r\n\t\t\tprint(\"encoded %s from %s \" % (src_file, coding))\r\n\r\n\r\ndef main():\r\n\troot_dir = sys.argv[1]\r\n\ttraverse(root_dir, '', encode, '.txt')\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"utils/utf8ize.py","file_name":"utf8ize.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"613680436","text":"# -*- coding: utf-8 -*-\nimport re\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nimport random\n\ntorch.manual_seed(233)\nrandom.seed(233)\n\n\ndef create_batch_iter(data, batch_size, shuffle=True):\n data_size = len(data)\n if shuffle:\n np.random.shuffle(data)\n\n # 排序\n src_ids = sorted(range(data_size), key=lambda src_id: len(data[src_id][0]), reverse=True)\n data = [data[src_id] for src_id in src_ids]\n\n batched_data = []\n instances = []\n for instance in data:\n instances.append(instance)\n if len(instances) == batch_size:\n batched_data.append(instances)\n instances = []\n\n if len(instances) > 0:\n batched_data.append(instances)\n\n for batch in batched_data:\n yield batch\n\n\ndef pair_data_variable(batch, vocab_srcs, vocab_tgts, config):\n batch_size = len(batch)\n\n src_lengths = [len(batch[i][0]) for i in range(batch_size)]\n # 因为之前排序了,是递减的顺序\n max_src_length = int(src_lengths[0])\n\n src_words = Variable(torch.LongTensor(max_src_length, batch_size).zero_(), requires_grad=False)\n tgt_words = Variable(torch.LongTensor(batch_size).zero_(), requires_grad=False)\n\n start = []\n end = []\n\n for idx, instance in enumerate(batch):\n sentence = vocab_srcs.word2id(instance[0])\n for idj, value in enumerate(sentence):\n src_words.data[idj][idx] = value\n tgt_words[idx] = vocab_tgts.word2id(instance[3])\n start.append(instance[1])\n end.append(instance[2])\n\n if config.use_cuda:\n src_words = src_words.cuda()\n tgt_words = tgt_words.cuda()\n\n return src_words, tgt_words, src_lengths,start,end\n","sub_path":"handle_data/batch_iter.py","file_name":"batch_iter.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"103221926","text":"#!/usr/bin/python3\nfrom datetime import datetime\nfrom functools import partial\nfrom multiprocessing.pool import ThreadPool\nfrom multiprocessing import cpu_count\nfrom json import loads\nfrom toolz.dicttoolz import get_in\nfrom yaml import load\nfrom aws_operations import awsOperations\nfrom project_utils import utils\nfrom spotify_stream import iSpotify\n\n\nclass spotifyProject(object):\n def __init__(self):\n self.curr_datetime_as_str = datetime.now().strftime('%Y/%m/%d/%H/%M/')\n self.return_code = 0\n\n def loadConstants(self):\n self.util = utils()\n self.util.setConstants()\n\n def loadYaml(self):\n self.cred = load(open(self.util.d_constants['credentials_file']))\n\n def setAwsUp(self):\n self.aws=awsOperations()\n self.aws.connectS3(self.cred, self.util.d_constants['service_aws'])\n\n def createS3Bucket(self):\n self.aws.createS3Bucket(self.util.d_constants['s3_bucket'], self.util.d_constants['aws_user_email'])\n\n def setSpotifyUp(self):\n self.spotify=iSpotify()\n self.spotify.connectSpotify(self.cred, self.util.d_constants['service_spotify'])\n\n def uploadCategories(self):\n self.spotify.getCategories(self.util.d_constants['country'], self.util.d_constants['locale'], self.util.d_constants['limit'], self.util.offset)\n self.aws.createS3Key('categories/' + self.curr_datetime_as_str + 'category', self.spotify.categories)\n self.util.writeSearchParams('catid', self.get_cat_ids())\n\n def uploadCategoryNewReleases(self, tup_cat_id):\n try:\n self.spotify.getCategoryNewReleases(tup_cat_id[1])\n self.aws.createS3Key('catnewreleases/' + self.curr_datetime_as_str + 'catnewrelease' + str(tup_cat_id[0] + 1), self.spotify.category_new_releases)\n SearchParams = [i+\"~\"+v for i, v in zip(self.get_rel_playlist_owner(), self.get_rel_playlist_id())]\n self.util.writeSearchParams('patt', SearchParams)\n except:\n self.util.logFailedSearch( \"error_\"+ self.curr_datetime_as_str, \"Cat New Rel \"+ tup_cat_id[1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n\n def poolCategoryNewReleases(self):\n cat_id = self.util.readSearchParams('catid')\n cat_id = [(i,v) for i, v in enumerate(cat_id)]\n pool = ThreadPool(processes=min(cpu_count(), len(cat_id)))\n pool.map(self.uploadCategoryNewReleases, cat_id)\n pool.close()\n\n def uploadPlaylistTracks(self, tup_p_att):\n try:\n self.spotify.getPlaylistTracks(tup_p_att[1][0], tup_p_att[1][1], self.util.d_constants['limit'], self.util.d_constants['country'], self.util.offset)\n self.aws.createS3Key('playlisttracks/' + self.curr_datetime_as_str + 'playlisttrack' + str(tup_p_att[0]+1), self.spotify.playlist_tracks)\n self.util.writeSearchParams('ptrack', self.get_rel_playlist_album_ids())\n except:\n self.util.logFailedSearch(\"error_\" + self.curr_datetime_as_str, \"Playlist Track \" + tup_p_att[1][0] + tup_p_att[1][1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n\n def poolPlaylistTracks(self):\n p_att = self.util.readSearchParams('patt')\n p_att = [(i,v) for i, v in enumerate(p_att)]\n pool = ThreadPool(processes=min(cpu_count(), len(p_att)))\n pool.map(self.uploadPlaylistTracks, p_att)\n pool.close()\n\n def uploadAlbums(self, tup_al):\n try:\n self.spotify.getAlbums(tup_al[1])\n self.aws.createS3Key('albums/' + self.curr_datetime_as_str + 'album' + str(tup_al[0]+1), self.spotify.albums)\n self.util.writeSearchParams('album', self.get_rel_playlist_album_ids())\n search_params = self.get_album_artist_track_info()\n self.util.writeSearchParams('atrack', [i[0] for i in search_params])\n self.util.writeSearchParams('artist', [i[1] for i in search_params])\n except:\n self.util.logFailedSearch(\"error_\" + self.curr_datetime_as_str, \"Album \" + tup_al[1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n\n def poolAlbums(self):\n al = self.util.readSearchParams('ptrack')\n sub_al = [(i, al[i:i + 10]) for i in range(0, len(al), 10)]\n pool = ThreadPool(processes=min(cpu_count(), len(sub_al)))\n pool.map(self.uploadAlbums, sub_al)\n pool.close()\n\n def uploadArtists(self, tup_ar):\n try:\n self.spotify.getArtists(tup_ar[1])\n try:\n self.spotify.getAudioAnalysis(tup_track_id[1])\n self.aws.createS3Key('audioanalysis/'+ self.curr_datetime_as_str + 'audioanalysis' + str(tup_track_id[0]+1), self.spotify.audio_analysis)\n except:\n self.util.logFailedSearch(\"error_\" + self.curr_datetime_as_str, \"Audio Analysis \" + tup_track_id[1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n self.aws.createS3Key('artists/'+ self.curr_datetime_as_str + 'artist' + str(tup_ar[0]+1), self.spotify.artists)\n except:\n self.util.logFailedSearch(\"error_\" + self.curr_datetime_as_str, \"Artist \" + tup_ar[1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n\n def poolArtists(self):\n ar = self.util.readSearchParams('artist')\n sub_ar = [(i, ar[i:i + 10]) for i in range(0, len(ar), 10)]\n pool = ThreadPool(processes=min(cpu_count(), len(sub_ar)))\n pool.map(self.uploadArtists, sub_ar)\n pool.close()\n\n def uploadAudioFeatures(self, tup_track_id):\n try:\n self.spotify.getAudioFeatures(tup_track_id[1])\n self.aws.createS3Key('audiofeatures/' + self.curr_datetime_as_str + 'audiofeature' + str(tup_track_id[0]+1), self.spotify.audio_features)\n except:\n self.util.logFailedSearch(\"error_\" + self.curr_datetime_as_str, \"Audio Feat \" + tup_track_id[1] + datetime.now().strftime('%Y/%m/%d/%H/%M/%S'))\n\n def poolAudioFeatures(self):\n track_id = self.util.readSearchParams('atrack')\n track_id = [(i,v) for i, v in enumerate(track_id)]\n pool = ThreadPool(processes=min(cpu_count(), len(track_id)))\n pool.map(self.uploadAudioFeatures, track_id)\n pool.close()\n\n def uploadAudioAnalysis(self, tup_track_id):\n pass\n\n def poolAudioAnalysis(self):\n track_id = self.util.readSearchParams('atrack')\n track_id = [(i,v) for i, v in enumerate(track_id)]\n pool = ThreadPool(processes=min(cpu_count(), len(track_id)))\n pool.map(self.uploadAudioAnalysis, track_id)\n pool.close()\n\n def get_cat_ids(self):\n return map(partial(get_in, ['id']),\n get_in(['categories', 'items'], loads(self.spotify.categories), []))\n\n def get_user_playlist_owner(self):\n return map(partial(get_in, ['owner', 'id']),\n get_in(['items'], loads(self.spotify.category_new_releases), []))\n\n def get_user_playlist_id(self):\n return map(partial(get_in, ['id']),\n get_in(['items'], loads(self.spotify.category_new_releases), []))\n\n def get_rel_playlist_album_ids(self):\n return map(partial(get_in, ['track', 'album', 'id']),\n get_in(['items'], loads(self.spotify.playlist_tracks), []))\n\n def get_album_artist_track_info(self):\n return [(get_in(['id'], i[0], []), get_in(['id'], j, []))\n for i in map(partial(get_in, ['tracks', 'items']),\n get_in(['albums'], loads(self.spotify.albums), []))\n for j in get_in(['artists'], i[0], [])]\n\n\ndef do_it_all():\n sp = spotifyProject()\n sp.loadConstants()\n sp.loadYaml()\n sp.setAwsUp()\n sp.createS3Bucket()\n sp.setSpotifyUp()\n with open(sp.util.homedir + 'user_playlist', 'r') as f:\n self.d_constants = dict(x.rstrip().split(\":\", 1) for x in f)\n\n sp.uploadCategories()\n sp.poolCategoryNewReleases()\n sp.poolPlaylistTracks()\n sp.poolAlbums()\n sp.poolArtists()\n sp.poolAudioFeatures()\n sp.poolAudioAnalysis()\n sp.util.updateOffset()\n sp.util.delSearchParams()\n\n\ndo_it_all()\n","sub_path":"1_2_stream_store/run_stream.py","file_name":"run_stream.py","file_ext":"py","file_size_in_byte":8018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"202282565","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n1. li.append(data)\n任意类型数据,li操作不能直接放在print()中\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# li.append('666')\n# print(li)\n# li.append(['henry'])\n# print(li)\n\n\"\"\"\n2. li.insert(index, data)\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# li.insert(3, 'henry')\n# print(li)\n\n\"\"\"\n3. li.remove('aa')\n\"\"\"\n# li = ['aa', 'a', 'aacde']\n# li.remove('aa')\n# print(li)\n# li.remove('bb')\n# print(li)\n\n\"\"\"\n4. li.pop(index)\n\"\"\"\n\nli = [1, 2, 3, 4, 5, 6]\n# li.pop()\n# print(li)\n# li.pop(3)\n# print(li)\n# del li[6]\n# print(li)\n\n\n\"\"\"\n5. li.clear()\n\"\"\"\n\n# li = [1, 2, 3, 4, 5, 6]\n# li.clear()\n# print(li)\n\n\n\"\"\"\n6. li.reverse()\n\"\"\"\n\n# li = [1, 2, 3, 4, 5, 6]\n# li.reverse()\n# print(li)\n\n\n\"\"\"\n7. li.sort(reverse = True)\n\"\"\"\n# # reverse = True 从大到小\n# # 只能是同一类型的元素\n# # dict,tuple不支持排序\n# li = [6, 2, 3, 1, 5, 4]\n# li.sort()\n# print(li)\n# li = ['ba', 'ab', 'c', 'd']\n# li.sort(reverse=True)\n# print(li)\n# li = [[6], [2, 3], [1, 5, 4]]\n# li.sort()\n# print(li)\n#\n# li = [(6, 2, 3, 1, 5, 4)]\n# li.sort()\n# print(li)\n\n\n\"\"\"\n8. li.extend(s)\n\"\"\"\n# # 把s中的元素,循环取出,逐个追加到list中\n# # s可以是str, list, tuple, dict, set\n# # dict只取keys 追加到list中\n# s = 'henry'\n# li = [1, 2, 3, 4, 5, 6]\n# li.extend(s)\n# print(li)\n# s = {'a': 'e', 'b': 'c', 'c': 'h', 'd': 'o'}\n# li.extend(s)\n# print(li)\n\n\"\"\"\n9. len(li)\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# print(len(li))\n\n\n\"\"\"\n10. index\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# print(li[2])\n\n\n\"\"\"\n11. 切片\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# print(li[2:5])\n\n\"\"\"\n12. step\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# print(li[2::2])\n\n\n\"\"\"\n13. for 循环\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# for i in li:\n# print(i)\n\n\"\"\"\n14. 修改\n# 使用index修改,如果只是一个值,则正常修改\n# 使用index修改,如果是多个值,认为是一个tuple\n# 使用切片[]修改,则循环取值加入\n\"\"\"\n# li = [1, 2, 3, 4, 5, 6]\n# li[2] = 'henry'\n# print(li)\n# li[2] = 'a', 'b', 'c'\n# print(li)\n# li[2:3] = 'a', 'b', 'c', 0\n# print(li)\n\n\n\"\"\"\n15. 删除del\n\"\"\"\n# # del 也不能放在print()里面\n# li = [1, 2, 3, 4, 5, 6]\n# del li[2]\n# print(li)\n# del li[2:]\n# print()","sub_path":"007 深浅拷贝&文件操作/summary/数据类型总结/2. list 5 + 3 + 7.py","file_name":"2. list 5 + 3 + 7.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"297382769","text":"def sommeMax(tableau):\n maxi1 = tableau[0]\n maxi2 = tableau[1]\n for j in tableau:\n if j >= maxi2 and j!= maxi1:\n maxi2 = j\n if j >= maxi1 and j!=maxi2:\n maxi1 = j\n return maxi2,maxi1\ndef getIndexOfMaxValues(tableau):\n maxi1 = sommeMax(tableau)[0] #prendre l'index des deux valeurs pour faire la somme des éléments à l'intérieur\n maxi2 = sommeMax(tableau)[1]\n indexMaxi1 = tableau.index(maxi1)\n indexMaxi2 = tableau.index(maxi2)\n somme = 0\n for i in range(indexMaxi1,indexMaxi2+1):\n somme += tableau[i]\n print(somme)\ngetIndexOfMaxValues([-2, -5, 6, -2, -3, 1, 5, -6])\n\"\"\"\n Complexité:\nAlgorithme de recherche pour valeurs max ==> O(n)\n\"\"\"","sub_path":"Exercice3.py","file_name":"Exercice3.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"140227998","text":"import ast\nimport pytest\nfrom testfixtures import compare\n\nfrom kale.static_analysis import ast as kale_ast\n\n\n_numpy_snippet = '''\nimport os\nimport numpy as np\na = np.random.random((10, 10))\nb = a.sum()\nprint(b)\n'''\n\n_numpy2_snippet = '''\nimport os\nimport numpy as np\nb = a.sum()\nprint(b)\n'''\n\n_foos_snippet = '''\ndef _test(a):\n pass\n\ndef _test2(b, *args, **kwargs):\n var = b\n'''\n\n_class_snippet = '''\nclass test:\n def __init__(self, a):\n self.a = a\n\n def foo(self, b):\n self.a = b\n'''\n\n_ctx_mngr_snippet = '''\nwith my_context(param) as ctx:\n res = ctx.use()\n'''\n\n_wrong_code_snippet = '''\ndef fun()\n pass\n'''\n\n\n@pytest.mark.parametrize(\"code,target\", [\n ('', []),\n (_numpy_snippet, ['a', 'b', 'np', 'os', 'print']),\n (_numpy2_snippet, ['a', 'b', 'np', 'os', 'print']),\n (_foos_snippet, ['_test', '_test2', 'var', 'b']),\n (_class_snippet, ['test', '__init__', 'self', 'a', 'foo', 'b']),\n (_ctx_mngr_snippet, ['my_context', 'param', 'res', 'ctx'])\n])\ndef test_get_all_names(code, target):\n \"\"\"Tests get_all_names function.\"\"\"\n res = kale_ast.get_all_names(code)\n assert sorted(res) == sorted(target)\n\n\ndef test_get_all_names_exc():\n \"\"\"Tests exception when passing a wrong code snippet to get_all_names.\"\"\"\n with pytest.raises(SyntaxError):\n kale_ast.get_all_names(_wrong_code_snippet)\n\n\n@pytest.mark.parametrize(\"code,target\", [\n ('()', []),\n ('[]', []),\n ('(a,)', ['a']),\n ('[a,]', ['a']),\n ('(a,(b,))', ['a', 'b']),\n ('[a,[b,]]', ['a', 'b']),\n])\ndef test_get_list_tuple_names(code, target):\n \"\"\"Test list_tuple_names function.\"\"\"\n tree = ast.parse(code)\n res = kale_ast.get_list_tuple_names(tree.body[0].value)\n assert sorted(res) == sorted(target)\n\n\n@pytest.mark.parametrize(\"code,target\", [\n ('', []),\n (_foos_snippet, ['_test', '_test2']),\n (_class_snippet, ['__init__', 'foo', 'test'])\n])\ndef test_get_function_and_class_names(code, target):\n \"\"\"Test get_function_and_class_names function.\"\"\"\n res = kale_ast.get_function_and_class_names(code)\n assert sorted(res) == sorted(target)\n\n\n@pytest.mark.parametrize(\"code,target\", [\n ('', {}),\n ('a = \"a\"', {'a': (type('').__name__, \"a\")}),\n ('a = 3', {'a': (type(0).__name__, 3)}),\n ('a = 2.', {'a': (type(0.).__name__, 2.)}),\n ('a = True', {'a': (type(True).__name__, True)}),\n])\ndef test_parse_assignments_expressions(code, target):\n \"\"\"Test parse_assignments_expressions function.\"\"\"\n res = kale_ast.parse_assignments_expressions(code)\n compare(res, target)\n\n\n@pytest.mark.parametrize(\"code\", [\n 'a = None',\n 'a + 1',\n 'a, b = 3',\n 'a = b = 3',\n 'a = [2]',\n 'a = b',\n])\ndef test_parse_assignments_expressions_exc(code):\n \"\"\"Test parse_assignments_expressions function.\"\"\"\n with pytest.raises(ValueError):\n kale_ast.parse_assignments_expressions(code)\n\n\n@pytest.mark.parametrize(\"code, target\", [\n ('', {}),\n (' ', {}),\n ('print(a)', {'a': 'a'}),\n ('print(a)\\nprint(var)\\nprint(test_var)', {'a': 'a',\n 'var': 'var',\n 'test-var': 'test_var'}),\n])\ndef test_parse_metrics_print_statements(code, target):\n \"\"\"Tests parse_metrics_print_statements function.\"\"\"\n res = kale_ast.parse_metrics_print_statements(code)\n assert res == target\n\n\n@pytest.mark.parametrize(\"code\", [\n 'print(foo())',\n 'def',\n 'variable',\n 'print(var)\\nname',\n '_variable'\n])\ndef test_parse_metrics_print_statements_exc(code):\n \"\"\"Tests a exception cases for parse_metrics_print_statements function.\"\"\"\n with pytest.raises(ValueError):\n kale_ast.parse_metrics_print_statements(code)\n","sub_path":"kale/tests/unit_tests/test_ast.py","file_name":"test_ast.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"460163741","text":"import logging\n\nfrom django.contrib import auth\nfrom django.db.models import Min, Q\nfrom django.db.transaction import atomic\n\nfrom river.config import app_config\nfrom river.models.proceeding import Proceeding, PENDING\nfrom river.models.proceeding_meta import ProceedingMeta\nfrom river.models.state import State\n\n__author__ = 'ahmetdal'\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass ProceedingService(object):\n @staticmethod\n def init_proceedings(workflow_object):\n\n content_type = app_config.CONTENT_TYPE_CLASS.objects.get_for_model(workflow_object)\n for proceeding_meta in ProceedingMeta.objects.filter(content_type=content_type):\n proceeding, created = Proceeding.objects.update_or_create(\n meta=proceeding_meta,\n workflow_object=workflow_object,\n defaults={\n 'order': proceeding_meta.order,\n 'status': PENDING,\n }\n )\n proceeding.permissions.add(*proceeding_meta.permissions.all())\n proceeding.groups.add(*proceeding_meta.groups.all())\n\n workflow_object.save()\n LOGGER.debug(\"Proceedings are initialized for workflow object %s\" % workflow_object)\n\n @staticmethod\n def get_available_proceedings(workflow_object, source_states, user=None, destination_state=None,\n god_mod=False):\n\n def get_proceeding(proceedings):\n min_order = proceedings.aggregate(Min('order'))['order__min']\n proceedings = proceedings.filter(order=min_order)\n\n if destination_state:\n proceedings = proceedings.filter(meta__transition__destination_state=destination_state)\n\n return proceedings\n\n def authorize_proceedings(proceedings):\n group_q = Q()\n for g in user.groups.all():\n group_q = group_q | Q(groups__in=[g])\n\n permissions = []\n for backend in auth.get_backends():\n permissions.extend(backend.get_all_permissions(user))\n\n permission_q = Q()\n for p in permissions:\n label, codename = p.split('.')\n permission_q = permission_q | Q(permissions__content_type__app_label=label,\n permissions__codename=codename)\n\n return proceedings.filter(\n (\n (Q(transactioner__isnull=True) | Q(transactioner=user)) &\n (Q(permissions__isnull=True) | permission_q) &\n (Q(groups__isnull=True) | group_q)\n )\n )\n\n proceedings = Proceeding.objects.filter(\n workflow_object=workflow_object,\n meta__transition__source_state__in=source_states,\n status=PENDING,\n enabled=True\n )\n\n suitable_proceedings = get_proceeding(proceedings.filter(skip=False))\n\n if user and not god_mod:\n suitable_proceedings = authorize_proceedings(suitable_proceedings)\n\n skipped_proceedings = get_proceeding(proceedings.filter(skip=True))\n if skipped_proceedings:\n source_state_pks = list(skipped_proceedings.values_list('meta__transition__destination_state', flat=True))\n suitable_proceedings = suitable_proceedings | ProceedingService.get_available_proceedings(workflow_object,\n State.objects.filter(\n pk__in=source_state_pks),\n user=user,\n destination_state=destination_state,\n god_mod=god_mod)\n return suitable_proceedings\n\n @staticmethod\n def get_next_proceedings(workflow_object, proceeding_pks=None, current_states=None, index=0, limit=None):\n if not proceeding_pks:\n proceeding_pks = []\n index += 1\n current_states = list(current_states.values_list('pk', flat=True)) if current_states else [workflow_object.get_state()]\n next_proceedings = Proceeding.objects.filter(workflow_object=workflow_object, meta__transition__source_state__in=current_states)\n if workflow_object.proceeding:\n next_proceedings = next_proceedings.exclude(pk=workflow_object.proceeding.pk)\n if next_proceedings.exists() and not next_proceedings.filter(pk__in=proceeding_pks).exists() and (\n not limit or index < limit):\n proceedings = ProceedingService.get_next_proceedings(\n workflow_object,\n proceeding_pks=proceeding_pks + list(next_proceedings.values_list('pk', flat=True)),\n current_states=State.objects.filter(\n pk__in=next_proceedings.values_list('meta__transition__destination_state', flat=True)),\n index=index,\n limit=limit\n )\n else:\n proceedings = Proceeding.objects.filter(pk__in=proceeding_pks)\n\n return proceedings\n\n @staticmethod\n @atomic\n def cycle_proceedings(workflow_object):\n \"\"\"\n Finds next proceedings and clone them for cycling if it exists.\n \"\"\"\n proceeded_next_proceedings = ProceedingService.get_next_proceedings(workflow_object).exclude(\n status=PENDING).exclude(cloned=True)\n for p in proceeded_next_proceedings:\n clone_p, c = Proceeding.objects.get_or_create(\n meta=p.meta,\n content_type=p.content_type,\n object_id=p.object_id,\n skip=p.skip,\n order=p.order,\n enabled=p.enabled,\n status=PENDING)\n\n if c:\n clone_p.permissions.add(*p.permissions.all())\n clone_p.groups.add(*p.groups.all())\n proceeded_next_proceedings.update(cloned=True)\n\n return True if proceeded_next_proceedings.count() else False\n\n @staticmethod\n def has_user_any_action(content_type, user):\n \"\"\"\n :param content_type_id:\n :param field_id:\n :param user_id:\n :return: Boolean value indicates whether the user has any role for the content type are sent. Any elements existence\n accepted, rejected or pending for the user, means the user in active for the content type.\n \"\"\"\n proceedings = Proceeding.objects.filter(\n Q(transactioner=user) | Q(permissions__in=user.user_permissions.all()) | Q(groups__in=user.groups.all())).filter(content_type=content_type)\n return proceedings.count() != 0\n\n @staticmethod\n def override_permissions(proceeding, permissions):\n proceeding.permissions.clear()\n proceeding.permissions.add(*permissions)\n\n @staticmethod\n def override_groups(proceeding, groups):\n proceeding.groups.clear()\n proceeding.groups.add(*groups)\n\n @staticmethod\n def get_initial_proceedings(content_type):\n return Proceeding.objects.filter(meta__parents__isnull=True, content_type=content_type)\n\n @staticmethod\n def get_final_proceedings(content_type):\n return Proceeding.objects.filter(meta__children__isnull=True, content_type=content_type)\n","sub_path":"venv/Lib/site-packages/river/services/proceeding.py","file_name":"proceeding.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"51877664","text":"# -*- coding : utf-8 -*-\r\n\r\nfrom bs4 import BeautifulSoup as bs\r\nfrom pprint import pprint\r\nimport requests as req\r\nimport pandas as pd\r\nimport sys, os\r\n\r\nresponse = req.get('http://watch.peoplepower21.org/Euian')\r\nhtml = response.text\r\nsoup = bs(html, 'lxml')\r\n\r\nbody = soup.body\r\nea_list = body.find(id = 'ea_list')\r\ntable = ea_list.table\r\ntbody = table.tbody\r\n\r\nbill_list = []\r\nlines = tbody.find_all('tr')\r\nfor line in lines:\r\n td_list = line.find_all('td')\r\n\r\n bill_list.append(\r\n [ td_list[0].text, td_list[1].text, td_list[2].text, td_list[4].text ])\r\n\r\nthead = table.thead\r\nth_list = thead.find_all('th')\r\n\r\ndf = pd.DataFrame(bill_list, columns = [th_list[0].text,\r\n th_list[1].text,\r\n th_list[2].text,\r\n th_list[4].text] )\r\n\r\ndf.to_csv('bill.csv')","sub_path":"Study_from_Windows/Beautiful_Soup/bs4_prac5_lxml_practice.py","file_name":"bs4_prac5_lxml_practice.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"107227206","text":"# Copyright (c) 2020-2021, NVIDIA CORPORATION.\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 gc\nimport pytest\nimport cugraph\nfrom cugraph.tests import utils\nfrom pathlib import PurePath\n\n\ndef test_bfs_paths():\n with pytest.raises(ValueError) as ErrorMsg:\n gc.collect()\n\n graph_file = PurePath(utils.RAPIDS_DATASET_ROOT_DIR)/\"karate.csv\"\n\n cu_M = utils.read_csv_file(graph_file)\n\n G = cugraph.Graph()\n G.from_cudf_edgelist(cu_M, source='0', destination='1', edge_attr='2')\n\n # run BFS starting at vertex 17\n df = cugraph.bfs(G, 16)\n\n # Get the path to vertex 1\n p_df = cugraph.utils.get_traversed_path(df, 0)\n\n assert len(p_df) == 3\n\n # Get path to vertex 0 - which is not in graph\n p_df = cugraph.utils.get_traversed_path(df, 100)\n\n assert \"not in the result set\" in str(ErrorMsg)\n\n\ndef test_bfs_paths_array():\n with pytest.raises(ValueError) as ErrorMsg:\n gc.collect()\n\n graph_file = PurePath(utils.RAPIDS_DATASET_ROOT_DIR)/\"karate.csv\"\n\n cu_M = utils.read_csv_file(graph_file)\n\n G = cugraph.Graph()\n G.from_cudf_edgelist(cu_M, source='0', destination='1', edge_attr='2')\n\n # run BFS starting at vertex 17\n df = cugraph.bfs(G, 16)\n\n # Get the path to vertex 1\n answer = cugraph.utils.get_traversed_path_list(df, 0)\n\n assert len(answer) == 3\n\n # Get path to vertex 0 - which is not in graph\n answer = cugraph.utils.get_traversed_path_list(df, 100)\n\n assert \"not in the result set\" in str(ErrorMsg)\n","sub_path":"python/cugraph/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"223415388","text":"import itertools\nfrom string import ascii_lowercase\n\n\ndef enumerate_(x, count = 0):\n return zip(itertools.count(count), x)\n\n\nif __name__ == '__main__':\n print(\"Test\")\n alphabet = ascii_lowercase\n a = enumerate_(alphabet, 1)\n\n for _ in a:\n print(_)","sub_path":"filter_4.py","file_name":"filter_4.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"573788744","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pickle\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.autograd import Variable\r\nimport torch.nn.functional as F\r\nimport torch.utils.data as Data\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime\r\nfrom lstm_train_02 import trainDataGen, MaxMinNorm, MaxMinNorm_re, mape, toV, LSTM\r\n\r\npath = os.path.abspath('..')\r\n\r\npd.set_option('display.width',1000)\r\npd.set_option('display.max_rows',1000)\r\npd.set_option('display.max_columns',500)\r\n\r\n\r\ndef main(STATION_ID):\r\n print('reading data ...')\r\n infile = path + '/data/true_data/metroData_ODflow_15.csv'\r\n raw_flow = pd.read_csv(infile)\r\n # print(raw_flow)\r\n station_flow = raw_flow[raw_flow[' station'] == STATION_ID]\r\n # print(station_flow)\r\n trainData_x, trainData_y = trainDataGen(station_flow, N_TS, N_DAY, N_WEEK)\r\n trainData_x, mao_x, mio_x = MaxMinNorm(trainData_x, 6864, 1)\r\n trainData_y, mao_y, mio_y = MaxMinNorm(trainData_y, 6864, 1)\r\n\r\n trainData_x = toV(trainData_x).view(len(trainData_x),1,N_TS+N_DAY+N_WEEK)\r\n trainData_y = toV(trainData_y).view(len(trainData_y),1,1)\r\n # print(trainData_x, len(trainData_x))\r\n # print(trainData_y, len(trainData_y))\r\n lll = len(trainData_x)\r\n test_x = trainData_x[int(0.75*lll):]\r\n test_y = trainData_y[int(0.75*lll):]\r\n # print(test_x, len(test_x))\r\n # print(test_y, len(test_y))\r\n\r\n # ==== restore net\r\n print('restoring net ...')\r\n lstm = LSTM(N_TS+N_DAY+N_WEEK, 10)\r\n lstm = torch.load('net_lstm_2.pkl')\r\n loss_func = nn.MSELoss()\r\n\r\n # ==== test\r\n print('testing data ...')\r\n lstm = lstm.eval()\r\n pred_outs = lstm(test_x)\r\n loss = loss_func(pred_outs, test_y)\r\n print('Test loss: {:.5f}'.format(loss.item()))\r\n\r\n # print(type(test_y), type(mao_y))\r\n # print(type(MaxMinNorm_re(test_y, mao_y, mio_y)))\r\n # mao_y = toV(mao_y)\r\n # mio_y = toV(mio_y)\r\n # test_y = MaxMinNorm_re(test_y, mao_y, mio_y).view(-1).data.numpy()\r\n # print(test_y)\r\n # print(all(test_y))\r\n # pred_outs = MaxMinNorm_re(pred_outs, mao_y, mio_y).view(-1).data.numpy()\r\n # mape_sta = mape(pred_outs, test_y)\r\n\r\n\r\n test_y = MaxMinNorm_re(test_y.view(-1).data.numpy(), 6864, 1)\r\n pred_outs = MaxMinNorm_re(pred_outs.view(-1).data.numpy(), 6864, 1)\r\n # print(test_y,type(test_y))\r\n mape_sta = mape(pred_outs, test_y)\r\n\r\n print('station id:', STATION_ID, 'mape:', mape_sta)\r\n\r\n # fig = plt.figure(figsize=(10, 5))\r\n # plt.plot(range(len(test_y)), test_y, ls='--', label='true data')\r\n # plt.plot(range(len(test_y)), pred_outs, label='prediction data')\r\n # plt.text(0, 0, 'Loss=%.5f' % loss.item(), fontdict={'size': 10, 'color': 'red'})\r\n # plt.title('Predict result of %s' % STATION_ID)\r\n # plt.legend(loc='best')\r\n # plt.tight_layout()\r\n # plt.savefig(path + r'/result/station_flow_prediction_%s.png' % STATION_ID, dpi=150)\r\n\r\n # plt.show()\r\n return mape_sta\r\n\r\n\r\ndef main_2():\r\n infile3 = path + '/data/raw_data/metroStations.csv'\r\n station_id_df = pd.read_csv(infile3)\r\n # print(station_id_df)\r\n # mape_everySta_ls = []\r\n stationMape_df = pd.DataFrame(0, index=station_id_df['stationID'], columns=['mape'])\r\n # for i in range(len(station_id_df)):\r\n # STATION_ID = station_id_df.iloc[i, 0]\r\n # mape_sta = main(STATION_ID)\r\n # mape_everySta_ls.append(mape_sta)\r\n print(stationMape_df)\r\n # stationMape_df.to_csv(path + r'/result/station_mape.csv')\r\n\r\n\r\ndef test():\r\n # infile = path + '/data/true_data/metroData_ODflow_15.csv'\r\n # raw_flow = pd.read_csv(infile)\r\n # # print(raw_flow)\r\n # station_flow = raw_flow[raw_flow[' station'] == STATION_ID]\r\n # # print(station_flow)\r\n # print('inFlow max:', max(station_flow[' inFlow']))\r\n # print('inFlow min:', min(station_flow[' inFlow']))\r\n\r\n # trainData_x, trainData_y = trainDataGen(station_flow, N_TS, N_DAY, N_WEEK)\r\n # trainData_x = MaxMinNorm(trainData_x)\r\n # trainData_y = MaxMinNorm(trainData_y)\r\n #\r\n # trainData_x = toV(trainData_x).view(len(trainData_x),1,N_TS+N_DAY+N_WEEK)\r\n # trainData_y = toV(trainData_y).view(len(trainData_y),1,1)\r\n # # print(trainData_x, len(trainData_x))\r\n # # print(trainData_y, len(trainData_y))\r\n # test_x = trainData_x[60*64:]\r\n # test_y = trainData_y[60*64:]\r\n # print(test_x, len(test_x))\r\n # print(test_y, len(test_y))\r\n\r\n infile2 = path + '/data/raw_data/transferStations.pkl'\r\n transferStation_info = pickle.load(open(infile2, 'rb'))\r\n # print(transferStation_info[0])\r\n # print(transferStation_info[0].keys())\r\n # print(transferStation_info[0].values())\r\n transferstation_df = pd.DataFrame(data=transferStation_info[0].values(),index=transferStation_info[0].keys(),columns=['includeStation','name'])\r\n print(transferstation_df)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n print('system start')\r\n starttime = datetime.now()\r\n\r\n # interval = 15\r\n # HOUR_INTERVAL = 16\r\n\r\n N_TS = 3\r\n N_DAY = 3\r\n N_WEEK = 3\r\n\r\n # STATION_ID = 1060 # 2011 2035 2010 2040 113 633\r\n # main(STATION_ID)\r\n main_2()\r\n # test()\r\n\r\n endtime = datetime.now()\r\n usetime = (endtime - starttime).seconds\r\n h = int(usetime / 3600)\r\n m = int((usetime - 3600 * h) / 60)\r\n s = usetime - 3600 * h - 60 * m\r\n print('time:', h, 'h', m, 'm', s, 's')\r\n print('system end')\r\n","sub_path":"code/lstm_test_01.py","file_name":"lstm_test_01.py","file_ext":"py","file_size_in_byte":5416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"538699515","text":"import tensorflow as tf\nfrom baselines.common.process_manager import ProcessManager\n\nimport numpy as np\nimport yaml\nimport zmq\nimport os\nfrom tqdm import tqdm\n\nfrom rl_msg_pb2 import *\n\ntry:\n from mpi4py import MPI\nexcept ImportError:\n MPI = None\n\nclass ProcessRunner(object):\n \"\"\"\n We use this object to make a mini batch of experiences\n __init__:\n - Initialize the runner\n\n run():\n - Make a mini batch\n \"\"\"\n def __init__(self, env, model, n_env, n_steps, gamma, lam, password,\n verbose=0, **network_kwargs):\n self.env = env\n # assume env spec looks like DummyNAME-v0\n self.env_name = env.unwrapped.spec.id.split('-')[0][5:]\n self.model = model\n self.ob_space = env.observation_space\n self.ac_space = env.action_space\n self.lam = lam\n self.gamma = gamma\n self.n_env = n_env\n self.n_steps = n_steps\n self.verbose = verbose\n self.n_layer = network_kwargs['num_layers']\n self.n_hidden = network_kwargs['num_hidden']\n act_fn = network_kwargs['activation']\n if act_fn == None:\n self.act_fn = NeuralNetworkParam.NONE\n elif act_fn == tf.tanh:\n self.act_fn = NeuralNetworkParam.Tanh\n elif act_fn == tf.nn.relu:\n self.act_fn = NeuralNetworkParam.ReLU\n else:\n print(\"Wrong activation function\")\n self.mpi_rank = MPI.COMM_WORLD.Get_rank()\n\n self.parameter_setting()\n self.process_manager_list = { str(env_id): ProcessManager(self.ip_control_pc,\n self.username, password,\n self.execute_cmd+str(env_id), self.exit_cmd+str(env_id) + \"'\",\n self.verbose) for env_id in range(self.n_env) }\n if self.verbose >= 1:\n print(\"[[Process Manager created]]\")\n\n self.context_list = { str(env_id): zmq.Context.instance() for env_id in range(self.n_env)}\n self.data_socket_list = { str(env_idx):None for env_idx in range(self.n_env) }\n self.policy_valfn_socket_list = { str(env_idx):None for env_idx in range(self.n_env) }\n if self.verbose >= 1:\n print(\"[[Context created]]\")\n\n def create_zmq_sockets(self, env_idx):\n self.data_socket_list[str(env_idx)] = self.context_list[str(env_idx)].socket(zmq.SUB)\n self.data_socket_list[str(env_idx)].setsockopt_string(zmq.SUBSCRIBE, \"\")\n self.data_socket_list[str(env_idx)].connect(self.ip_sub_pub_list[str(env_idx)])\n self.policy_valfn_socket_list[str(env_idx)] = self.context_list[str(env_idx)].socket(zmq.REQ)\n self.policy_valfn_socket_list[str(env_idx)].connect(self.ip_req_rep_list[str(env_idx)])\n if self.verbose >= 1:\n print(\"[[Socket created for %d th Env]]\" % env_idx)\n\n def parameter_setting(self):\n cfg_path = os.getcwd() + '/Config/' + self.env_name + '/TEST/RL_WALKING_TEST.yaml'\n with open(cfg_path) as f:\n config = yaml.safe_load(f)\n ip_sub_pub_first = config['test_configuration']['protocol']['ip_sub_pub_prefix']\n ip_req_rep_first = config['test_configuration']['protocol']['ip_req_rep_prefix']\n self.username = config['test_configuration']['protocol']['username']\n self.ip_control_pc = config['test_configuration']['protocol']['ip_control_pc']\n self.execute_cmd = config['test_configuration']['protocol']['execute_cmd']\n self.execute_cmd += ' ' + str(self.mpi_rank) + ' '\n self.exit_cmd = config['test_configuration']['protocol']['exit_cmd']\n self.exit_cmd += ' ' + str(self.mpi_rank) + ' '\n self.ip_sub_pub_list = { str(env_id): ip_sub_pub_first + str(self.mpi_rank) + str(env_id) for env_id in range(self.n_env)}\n self.ip_req_rep_list = { str(env_id): ip_req_rep_first + str(self.mpi_rank) + str(env_id) for env_id in range(self.n_env)}\n\n def run_experiment(self, env_idx, policy_param, valfn_param):\n assert( ( len(policy_param) - 1 ) / 2 == self.n_layer+1)\n assert( ( len(valfn_param) / 2 ) == self.n_layer+1)\n self.process_manager_list[str(env_idx)].execute_process()\n self.pair_and_sync(self.policy_valfn_socket_list[str(env_idx)],\n self.data_socket_list[str(env_idx)])\n # ==================================================================\n # send policy\n # ==================================================================\n pb_policy_param = NeuralNetworkParam()\n for l_idx in range(self.n_layer + 1):\n weight = policy_param[2*l_idx]\n bias = policy_param[2*l_idx+1]\n layer = pb_policy_param.layers.add()\n layer.num_input = weight.shape[0]\n layer.num_output = weight.shape[1]\n for w_row in range(weight.shape[0]):\n for w_col in range(weight.shape[1]):\n layer.weight.append(weight[w_row, w_col])\n for b_idx in range(bias.shape[0]):\n layer.bias.append(bias[b_idx])\n if l_idx == self.n_layer:\n layer.act_fn = NeuralNetworkParam.NONE\n else:\n layer.act_fn = self.act_fn\n for action_idx in range(policy_param[-1].shape[-1]):\n pb_policy_param.logstd.append((policy_param[-1])[0, action_idx])\n pb_policy_param_serialized = pb_policy_param.SerializeToString()\n self.policy_valfn_socket_list[str(env_idx)].send(pb_policy_param_serialized)\n self.policy_valfn_socket_list[str(env_idx)].recv()\n if self.verbose >= 1:\n print(\"[[Policy is set for %d th Env]]\" % env_idx)\n\n # ==================================================================\n # send value function\n # ==================================================================\n pb_valfn_param = NeuralNetworkParam()\n for l_idx in range(self.n_layer + 1):\n weight = valfn_param[2*l_idx]\n bias = valfn_param[2*l_idx+1]\n layer = pb_valfn_param.layers.add()\n layer.num_input = weight.shape[0]\n layer.num_output = weight.shape[1]\n for w_row in range(weight.shape[0]):\n for w_col in range(weight.shape[1]):\n layer.weight.append(weight[w_row, w_col])\n for b_idx in range(bias.shape[0]):\n layer.bias.append(bias[b_idx])\n if l_idx == self.n_layer:\n layer.act_fn = NeuralNetworkParam.NONE\n else:\n layer.act_fn = self.act_fn\n pb_valfn_param_serialized = pb_valfn_param.SerializeToString()\n self.policy_valfn_socket_list[str(env_idx)].send(pb_valfn_param_serialized)\n self.policy_valfn_socket_list[str(env_idx)].recv()\n if self.verbose >= 1:\n print(\"[[Value function is set for %d th Env]]\" % env_idx)\n\n def pair_and_sync(self, req_rep_socket, sub_pub_socket):\n while True:\n try:\n zmq_msg = sub_pub_socket.recv(zmq.DONTWAIT)\n except zmq.ZMQError as e:\n if e.errno == zmq.EAGAIN:\n req_rep_socket.send(b\"nope\")\n req_rep_socket.recv()\n else:\n raise\n else:\n req_rep_socket.send(b\"world\")\n req_rep_socket.recv()\n break;\n if self.verbose >= 1 :\n print(\"[[Sockets are all paired and synced]]\")\n\n def run(self, policy_param, valfn_param):\n\n counts = np.zeros(shape=(self.n_steps, self.n_env), dtype=int)\n mb_obs = np.zeros(shape=(self.n_steps, self.n_env, self.ob_space.shape[0]), dtype=np.float32)\n mb_rewards = np.zeros(shape=(self.n_steps, self.n_env), dtype=np.float32)\n mb_actions = np.zeros(shape=(self.n_steps, self.n_env, self.ac_space.shape[0]), dtype=np.float32)\n actions_mean = np.zeros(shape=(self.n_steps, self.n_env, self.ac_space.shape[0]), dtype=np.float32)\n mb_values = np.zeros(shape=(self.n_steps, self.n_env), dtype=np.float32)\n mb_dones = np.zeros(shape=(self.n_steps, self.n_env), dtype=bool)\n mb_neglogpacs = np.zeros(shape=(self.n_steps, self.n_env), dtype=np.float32)\n mb_states = None\n last_values = np.zeros(shape=(self.n_env))\n epinfos=[]\n dataset_total_rew=0\n cur_ep_ret = np.zeros(shape=(self.n_env), dtype=np.float32)\n b_first = np.ones(shape=(self.n_env), dtype=bool)\n\n for env_idx in range(self.n_env):\n self.create_zmq_sockets(env_idx)\n self.run_experiment(env_idx, policy_param, valfn_param)\n\n for step_idx in tqdm(range(self.n_steps), ncols=80, desc=\"[Trajectory Roll Out]\"):\n for env_idx in range(self.n_env):\n pb_data = Data()\n while(True):\n zmq_msg = self.data_socket_list[str(env_idx)].recv()\n if not (zmq_msg == b'hello'):\n pb_data.ParseFromString(zmq_msg)\n if pb_data.ListFields() == []:\n assert(False)\n else:\n break\n counts[step_idx, env_idx] = pb_data.count\n if b_first[env_idx]:\n assert(pb_data.count == 0)\n b_first[env_idx] = False\n mb_obs[step_idx, env_idx] = pb_data.observation\n mb_rewards[step_idx, env_idx] = pb_data.reward\n mb_actions[step_idx, env_idx] = pb_data.action\n actions_mean[step_idx, env_idx] = pb_data.action_mean\n mb_values[step_idx, env_idx] = pb_data.value\n mb_dones[step_idx, env_idx] = pb_data.done\n mb_neglogpacs[step_idx, env_idx] = pb_data.neglogp\n cur_ep_ret[env_idx] += pb_data.reward\n dataset_total_rew += pb_data.reward\n if pb_data.done:\n epinfos.append({'r':cur_ep_ret[env_idx],\n 'l':pb_data.count})\n cur_ep_ret[env_idx] = 0\n self.process_manager_list[str(env_idx)].quit_process()\n self.create_zmq_sockets(env_idx)\n self.run_experiment(env_idx, policy_param, valfn_param)\n b_first[env_idx] = True\n\n last_values = np.multiply(mb_values[-1], mb_dones[-1])\n\n for env_idx in range(self.n_env):\n self.process_manager_list[str(env_idx)].quit_process()\n\n # __import__('ipdb').set_trace()\n # discount/bootstrap off value fn\n mb_returns = np.zeros_like(mb_rewards)\n mb_advs = np.zeros_like(mb_rewards)\n lastgaelam = 0\n for t in reversed(range(self.n_steps)):\n if t == self.n_steps - 1:\n nextnonterminal = 1.0 - mb_dones[-1]\n nextvalues = last_values\n else:\n nextnonterminal = 1.0 - mb_dones[t+1]\n nextvalues = mb_values[t+1]\n delta = mb_rewards[t] + self.gamma * nextvalues * nextnonterminal - mb_values[t]\n mb_advs[t] = lastgaelam = delta + self.gamma * self.lam * nextnonterminal * lastgaelam\n mb_returns = mb_advs + mb_values\n\n return (*map(sf01, (mb_obs, mb_rewards, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs, actions_mean)),\n mb_states, epinfos, dataset_total_rew)\n\ndef sf01(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n \"\"\"\n s = arr.shape\n return arr.swapaxes(0, 1).reshape(s[0] * s[1], *s[2:])\n","sub_path":"baselines/ppo2/process_runner.py","file_name":"process_runner.py","file_ext":"py","file_size_in_byte":11687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"326457654","text":"\n\n\n# 587. Erect the Fence\n\n# There are some trees, where each tree is represented by (x,y) coordinate in a two-dimensional garden.\n# Your job is to fence the entire garden using the minimum length of rope as it is expensive.\n# The garden is well fenced only if all the trees are enclosed.\n# Your task is to help find the coordinates of trees which are exactly located on the fence perimeter.\n\n# Example 1:\n# Input: [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n# Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]\n# Explanation:\n\n# Example 2:\n# Input: [[1,2],[2,2],[4,2]]\n# Output: [[1,2],[2,2],[4,2]]\n# Explanation:\n\n\n# Note:\n\n# All trees should be enclosed together. You cannot cut the rope to enclose trees that will separate them\n# in more than one group.\n# All input integers will range from 0 to 100.\n# The garden has at least one tree.\n# All coordinates are distinct.\n# Input points have NO order. No order required for output.\n\n\n# Definition for a point.\nclass Point(object):\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\n\n\nclass OuterTrees(object):\n\n # Monotone Chain Convex Hull\n # http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull\n #\n # Andrew's monotone chain convex hull algorithm constructs the convex hull of a set of 2-dimensional\n # points in O(nlogn) time.\n\n # It does so by first sorting the points lexicographically (first by x-coordinate, and in case of a tie,\n # by y-coordinate), and then constructing upper and lower hulls of the points in O(n) time.\n\n # An upper hull is the part of the convex hull, which is visible from the above.\n # It runs from its rightmost point to the leftmost point in counterclockwise order.\n # Lower hull is the remaining part of the convex hull.\n\n # the points in O(n) time.\n\n # An upper hull is the part of the convex hull, which is visible from the above.\n # It runs from its rightmost point to the leftmost point in counterclockwise order.\n # Lower hull is the remaining part of the convex hull.\n\n # Pseudo-code\n # Input: a list P of points in the plane.\n\n # Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate).\n\n # Initialize U and L as empty lists.\n # The lists will hold the vertices of upper and lower hulls respectively.\n\n # for i = 1, 2, ..., n:\n # while L contains at least two points and the sequence of last two points\n # of L and the point P[i] does not make a counter-clockwise turn:\n # remove the last point from L\n # append P[i] to L\n\n # for i = n, n-1, ..., 1:\n # while U contains at least two points and the sequence of last two points\n # of U and the point P[i] does not make a counter-clockwise turn:\n # remove the last point from U\n # append P[i] to U\n\n # Remove the last point of each list (it's the same as the first point of the other list).\n # Concatenate L and U to obtain the convex hull of P.\n # Points in the result will be listed in counter-clockwise order.\n def doit(self, points):\n \"\"\"\n :type points: List[Point]\n :rtype: List[Point]\n \"\"\"\n if len(points) < 2:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)\n\n lowerHull, upperHull = [], []\n points = sorted(set(points), key=lambda p: (p.x, p.y))\n\n for i in reversed(range(len(points))):\n while len(upperHull) > 1 and cross(upperHull[-2], upperHull[-1], points[i]) < 0:\n upperHull.pop()\n upperHull.append(points[i])\n\n for i in range(len(points)):\n while len(lowerHull) > 1 and cross(lowerHull[-2], lowerHull[-1], points[i]) < 0:\n lowerHull.pop()\n lowerHull.append(points[i])\n\n return list(set(lowerHull[:-1] + upperHull[:-1]))\n\n def doit2(self, points):\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n # points = sorted(set(points))\n points = sorted(points, key=lambda p: (p.x, p.y))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n # return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)\n\n # Build lower hull\n lower = []\n for p in points:\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:\n lower.pop()\n lower.append(p)\n\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) < 0:\n upper.pop()\n upper.append(p)\n\n # Concatenation of the lower and upper hulls gives the convex hull.\n # Last point of each list is omitted because it is repeated at the\n # beginning of the other list.\n # return lower[:-1] + upper[:-1]\n return list(set(lower[:-1] + upper[:-1]))\n\ndef convex_hull(points):\n \"\"\"Computes the convex hull of a set of 2D points.\n\n Input: an iterable sequence of (x, y) pairs representing the points.\n Output: a list of vertices of the convex hull in counter-clockwise order,\n starting from the vertex with the lexicographically smallest coordinates.\n Implements Andrew's monotone chain algorithm. O(n log n) complexity.\n \"\"\"\n\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n points = sorted(set(points))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n\n # Build lower hull\n lower = []\n for p in points:\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\n lower.pop()\n lower.append(p)\n\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\n upper.pop()\n upper.append(p)\n\n # Concatenation of the lower and upper hulls gives the convex hull.\n # Last point of each list is omitted because it is repeated at the beginning of the other list.\n return lower[:-1] + upper[:-1]\n\n\n# Example: convex hull of a 10-by-10 grid.\n# assert convex_hull([(i / 10, i % 10) for i in range(100)]) == [(0, 0), (9, 0), (9, 9), (0, 9)]\n\n\nif __name__ == \"__main__\":\n\n L = []\n for c in [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]:\n L.append(Point(c[0], c[1]))\n\n res = OuterTrees().doit(L) # [[1,1],[2,0],[4,2],[3,3],[2,4]]\n\n pass","sub_path":"PythonLeetcode/Leetcode/587_ErecttheFence.py","file_name":"587_ErecttheFence.py","file_ext":"py","file_size_in_byte":7656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"102848488","text":"import tensorflow as tf\nimport pathlib\nimport numpy as np\n\n\nclass Dataset:\n def __init__(self, data_dir, width, height, batch_size, loss_func='SparseCategoricalCrossentropy'):\n self.width = width\n self.height = height\n self.batch_size = batch_size\n self.loss_func = loss_func\n self.data_dir = pathlib.Path(data_dir)\n self.image_count = len(list(self.data_dir.glob('*/*.jpg')))\n self.steps_per_epoch = np.ceil(self.image_count/batch_size)\n self.class_name = np.array([item.name for item in self.data_dir.glob('*')])\n\n def __get_label(self, path):\n parts = tf.strings.split(path, '\\\\')\n return parts[-2] == self.class_name\n\n def __labeled_for_loss(self, label):\n if self.loss_func == 'SparseCategoricalCrossentropy':\n return tf.reshape(tf.where(label), [1])[0]\n elif self.loss_func == 'CategoricalCrossentropy':\n return label\n else:\n raise ValueError('loss_func required the value of \"SparseCategoricalCrossentropy\" \\\n or \"CategoricalCrossentropy\", but got %s.' % self.loss_func)\n\n def __decode_img(self, img):\n img = tf.image.decode_jpeg(img, channels=3)\n img = tf.image.convert_image_dtype(img, tf.float32)\n img = img / 255.\n return tf.image.resize(img, [self.width, self.height])\n\n def __process_path(self, path):\n label = self.__get_label(path)\n label = self.__labeled_for_loss(label)\n img = tf.io.read_file(path)\n img = self.__decode_img(img)\n return img, label\n\n def __prepare_for_training(self, ds, cache=True, shuffle_buffer_size=1000):\n if cache:\n if isinstance(cache, str):\n ds = ds.cache(cache)\n else:\n ds = ds.cache()\n\n ds = ds.shuffle(buffer_size=shuffle_buffer_size)\n # ds = ds.repeat(epochs)\n ds = ds.batch(self.batch_size)\n ds = ds.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n return ds\n\n @property\n def data(self):\n list_ds = tf.data.Dataset.list_files(str(self.data_dir/'*/*'))\n labeled_ds = list_ds.map(self.__process_path,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n return self.__prepare_for_training(labeled_ds)\n","sub_path":"make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"546736075","text":"import cv2, time\n\nvideo_file = cv2.VideoCapture(\"sample_video.mp4\")\n\nno_of_frames = 1 \n\nwhile True : \n \n check, frame = video_file.read() #video captures first image check = boolean \n \n no_of_frames = no_of_frames + 1\n \n print(\"check is = {}\".format(check))\n print(frame)\n\n gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n \n cv2.imshow(\"capturing\",gray_frame)\n \n key = cv2.waitKey(500)\n \n if key==ord('q') or check is not True : \n break\n \nvideo_file.release()\ncv2.destroyAllWindows()\n\nprint(\"total frame read is = {}\".format(no_of_frames))\n","sub_path":"video Processing/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"488275628","text":"import pickle,os,glob\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom common import tflogs2pandas\n\nwith open(\"output_data/tmp/to_confirm.pickle\", \"rb\") as f:\n all_str_md5 = pickle.load(f) # This list is produced in 27.5.1.read_search_9xx_results.py, in plot_best_vs_worst().\n\ncache_path = \"output_data/tmp/9xx_tb_confirm_results.pandas\"\nbodies = np.arange(900,908).tolist()\n\ndef load_tb(force=0):\n try:\n if force:\n raise FileNotFoundError\n df = pd.read_pickle(cache_path)\n except FileNotFoundError:\n dfs = []\n for name, str_md5 in all_str_md5.items():\n for run_seed in range(10):\n tb_path = f\"output_data/tensorboard_9xx_confirm/9xx_mutate_confirm/model-900-901-902-903-904-905-906-907-CustomAlignWrapper-md{str_md5}-sd{run_seed}/PPO_1\"\n print(f\"Loading {tb_path}\")\n _df = tflogs2pandas.tflog2pandas(tb_path)\n _df = _df[_df[\"metric\"].str.startswith(\"eval/\")]\n _tmp = name.split(\"_\")\n _df[\"exp\"] = _tmp[-1]\n _df[\"alignment\"] = _tmp[0]\n _df[\"name\"] = name\n _df[\"str_md5\"] = str_md5\n _df[\"run_seed\"] = run_seed\n dfs.append(_df)\n df = pd.concat(dfs)\n df.to_pickle(cache_path)\n return df\n\ndf = load_tb(1)\nprint(df)\ndef check_finished():\n sns.countplot(data=df, x=\"name\") # check every run is here\n plt.show()\n plt.close()\n# check_finished()\n\ndef learning_curve():\n g = sns.FacetGrid(data=df, col=\"exp\", hue=\"alignment\", legend_out=True)\n g.map(sns.lineplot, \"step\", \"value\")\n g.add_legend()\n g.fig.suptitle(f\"Confirm search result by independently perform 10 additional runs.\")\n plt.tight_layout()\n # plt.show()\n plt.savefig(\"output_data/plots/9xx_confirm.png\")\n plt.close()\nlearning_curve()\n\n","sub_path":"project/experiments/exp_033_diff_in_random_alignmnets/src/27.5.3.read_confirm_exp.py","file_name":"27.5.3.read_confirm_exp.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"645738465","text":"# from os import listdir\nfrom collections import OrderedDict\nimport re\n\nclass House:\n\n def __init__(self, html, filename):\n \"\"\"\n Recibe una cadena (str) con el contenido de un archivo con extesión \".html\".\n \n Idealmente utiliza expresiones regulares para leer de esta cadena todas las \n características que se retornan a través del método get_feats().\n \"\"\"\n self.html = html\n self.filename = filename\n\n def get_feats(self):\n \"\"\"\n Retorna un dict() que contiene los atributos de la casa leídos desde \n la cadena con el código html de la página reciba en el constructor. \n \n El diccionario contendrá las siguientes cadenas como claves: \n price (precio), location (localización), size (tamaño), \n num_bedrooms (número de habitaciones), num_bathrooms (número de baños), \n inner_feats (características interiores), \n outer_feats (características exteriores) y environmental_feats (entorno). \n \n Es posible que alguna casa no tenga características \n interiores (inner_feats), exteriores (outer_feats) o ambientales (environ_feats), \n es decir estas tres últimas son opcionales y en caso de no existir \n se retorna un conjunto vacío (conjunto NO lista).\n\n A continuación se muestra un ejemplo:\n\n {\n \"price\": \"6370597\",\n \"location\": \"Colonia Alameda, Tegucigalpa, Francisco Morazán\",\n \"size\": \"267\",\n \"num_bedrooms\": \"4\",\n \"num_bathrooms\": \"3.5\",\n \"inner_feats\": {\"cisterna\", \"comedor\", \"sistema de alarma\"},\n \"outer_feats\": {\"garaje: si\", \"cuarto de servidumbre\", \"estudio\", \"sala\"},\n \"environ_feats: {\"area social\"}\n }\n \"\"\"\n ## == Expresiones regulares == ##\n ## prog = re.compile(pattern)\n ## result = prog.match(string)\n\n re_price = re.compile('^

')\n re_location = re.compile('^')\n re_size = re.compile('^

  • ')\n re_num_bedrooms = re.compile('^
  • ')\n re_num_bathrooms = re.compile('^
  • ')\n \n re_inner_feats = re.compile('^

    Características interiores

    ')\n re_outer_feats = re.compile('^

    Caracteristicas exteriores

    ')\n re_environ_feats = re.compile('^

    Entorno

    ')\n\n ## == Lectura string que contiene el html linea a linea == ##\n lines = self.html.split('\\n')\n\n ## == Inicio de banderas == ##\n ## == Necesarias para capturar todas las caracteristicas de las casas == ##\n bool_inner_feats = False\n bool_outer_feats = False\n bool_environ_feats = False\n\n price = ''\n location = ''\n size = ''\n num_bedrooms = ''\n num_bathrooms = ''\n inner_feats = ''\n outer_feats = ''\n environ_feacts = ''\n\n #print(\"------------------------------------------------------\")\n ## Recorre todo el html y al hallar un match, lo guarda en la respectiva variable ##\n for line in lines:\n #bool_inner_feats = False\n #bool_outer_feats = False\n #bool_environ_feats = False\n\n line = line.lstrip() #lstrip borra spacios en blanco a la izquierda de una cadena\n \n if re_price.match(line): \n price = line\n\n if re_location.match(line):\n location = line\n\n if re_size.match(line):\n size = line\n\n if re_num_bedrooms.match(line):\n num_bedrooms = line\n\n if re_num_bathrooms.match(line):\n num_bathrooms = line\n\n # --------------------------- #\n if re_inner_feats.match(line):\n bool_inner_feats = True\n bool_outer_feats = False\n bool_environ_feats = False\n\n if bool_inner_feats:\n if \"tick\" in line:\n inner_feats = inner_feats + line + '\\n' # Guarda linea por linea \n \n # --------------------------- #\n if re_outer_feats.match(line):\n bool_inner_feats = False\n bool_outer_feats = True\n bool_environ_feats = False\n\n if bool_outer_feats:\n if \"tick\" in line:\n outer_feats = outer_feats + line + '\\n' # Guarda linea por linea\n #print(outer_feats)\n\n # --------------------------- #\n if re_environ_feats.match(line):\n bool_inner_feats = False\n bool_outer_feats = False\n bool_environ_feats = True\n\n if bool_environ_feats:\n if \"tick\" in line:\n environ_feacts = environ_feacts + line + '\\n' # Guarda linea por linea\n\n ## ======== TEST Variables De Extraccion ======== ## \n # print(price)\n # print(location)\n # print(size)\n # print(num_bedrooms)\n # print(num_bathrooms)\n # print(inner_feats)\n # print(outer_feats)\n # print(environ_feacts)\n\n # price = price.replace('

    ','') #Busca '

    ' y todas las apariciones #las reemplaza por --> ''\n # price = price.rstrip('

    ') #Elimina la cadena '

    ' al final del str\n\n ### =========== Reemplazo de texto =============== ###\n\n ## === Metodo para remplazar texto === ##\n def replace_all(text, dic):\n for i, j in dic.items():\n text = text.replace(i, j)\n return text\n\n ## ============ Diccionario ordenados: contiene pares de reemplazos ================== ##\n dic_replace_txt_price = OrderedDict([('L.', ''),('

    ', ''),('

    ',''),(',',''),(' ','')])\n\n dic_replace_txt_location = OrderedDict([('',''), ('','')])\n\n dic_replace_txt_size = OrderedDict([('

  • ',''), ('
  • ',''),(',',''), ('m2',''),(' ','')])\n\n dic_replace_txt_num_bedrooms = OrderedDict([('
  • ',''), ('
  • ',''), ('Habitaciones',''), (' ','')])\n\n dic_replace_txt_num_bathrooms = OrderedDict([('
  • ',''), ('
  • ',''),('Baños',''), ('Baño',''), (' ','')])\n\n dic_replace_txt_feats = OrderedDict([('
  • ',''), ('
  • ','')])\n\n ## ============ Reemplazo de varibles ============== ##\n list_inner = []\n list_outer = []\n list_environ = []\n\n if price != '':\n price = replace_all(price , dic_replace_txt_price)\n\n if location != '':\n location = replace_all(location , dic_replace_txt_location)\n\n if size != '':\n size = replace_all(size , dic_replace_txt_size)\n\n if num_bathrooms != '':\n num_bedrooms = replace_all(num_bedrooms , dic_replace_txt_num_bedrooms) \n\n if num_bathrooms != '':\n num_bathrooms = replace_all(num_bathrooms , dic_replace_txt_num_bathrooms)\n\n ######## =========== Insertar caracteristicas en una lista ============== ########\n ## ======= Establecer un conjunto a partir de una lista ---> set_feats = set(lista) === ##\n if inner_feats != '':\n inner_feats = replace_all(inner_feats , dic_replace_txt_feats)\n lines = inner_feats.split('\\n')\n for line in lines:\n if line != '':\n list_inner.append(line)\n\n if outer_feats != '':\n outer_feats = replace_all(outer_feats , dic_replace_txt_feats)\n lines = outer_feats.split('\\n')\n for line in lines:\n if line != '':\n list_outer.append(line)\n\n if environ_feacts != '':\n environ_feacts = replace_all(environ_feacts , dic_replace_txt_feats)\n lines = environ_feacts.split('\\n')\n for line in lines:\n if line != '':\n list_environ.append(line)\n\n #### ============= Test de variables ==========####\n # print(price)\n # print(location)\n # print(size)\n # print(num_bedrooms)\n # print(num_bathrooms)\n # print(list_inner)\n # print(list_outer)\n # print(list_environ)\n\n dic = {\n 'price': price,\n 'location': location,\n 'size': size,\n 'num_bedrooms': num_bedrooms,\n 'num_bathrooms': num_bathrooms,\n 'inner_feats': set(list_inner),\n 'outer_feats': set(list_outer),\n 'environ_feats': set(list_environ)\n }\n\n return dic\n","sub_path":"house.py","file_name":"house.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"95783511","text":"#!/opt/miniconda37/bin/python\n\nimport os\n\nimport numpy as np\nimport pandas as pd\nimport iris\nfrom iris.analysis.cartography import unrotate_pole\nimport readline\nimport json\n'''\n# exemplary rotation_angles\npath = '/na/gpfs1/ARCHIWUM/MM/IRIS/Sample_data'\nstashes = ['m01s03i225', 'm01s03i226']\npath_to_save = '/na/gpfs1/ARCHIWUM/MM/IRIS'\nname_to_save = 'winds.pp'\n'''\n\n# read selected stashes from files from given directory and return list of cubes\n# necessary - path to save, selected stashes\n\n\ndef read_selected_stashes(path, stashes):\n os.chdir(path)\n files = os.listdir()\n\n stash_list = iris.AttributeConstraint(\n STASH=lambda stash: np.isin(str(stash), stashes))\n data = iris.load(files, stash_list)\n\n return data\n\n# read selected stashes from files from given directory and save them in the chosen directory\n# necessary - path to read, path to save, selected stashes, name to save\n\n\ndef read_and_save(path, stashes, path_to_save, name_to_save):\n os.chdir(path)\n files = os.listdir()\n\n stash_list = iris.AttributeConstraint(\n STASH=lambda stash: np.isin(str(stash), stashes))\n data = iris.load(files, stash_list)\n\n print(data)\n iris.save(data, os.path.join(path_to_save, name_to_save))\n\n\n#########\n# calculate and return absolute velocity and direction angle in radians from a given u,v components\n# arguments:u,v\ndef to_V_angle(u, v, mode='d'):\n V = np.sqrt(u**2+v**2)\n angle = np.arctan2(u, v)+np.pi\n angle = np.where(angle >= 0, angle, angle+2*np.pi)\n angle = np.where(V != 0.0, angle, 0.0)\n if mode == 'd':\n return V, np.degrees(angle)\n if mode == 'r':\n return V, angle\n else:\n print('bad mode')\n\n\ndef to_u_v(V, a):\n a = np.radians(a+180.)\n u = V*np.sin(a)\n v = V*np.cos(a)\n return u, v\n\n\n# calculate and return absolute velocity and direction angle from a given u,v components\n# another version with np.nditer\n# arguments:u,v\n\n# TODO\n# radians/degrees\n# optimize\ndef to_V_angle_it(u, v):\n V = None\n angle = None\n it = np.nditer([u, v, V, angle], flags=['external_loop'], op_flags=[\n ['readonly'], ['readonly'], ['writeonly', 'allocate'], ['writeonly', 'allocate']])\n with it:\n for x, y, X, A in it:\n X[...] = np.sqrt(x**2+y**2)\n A[...] = np.arctan2(x, y)\n return it.operands[2], it.operands[3]\n\n\n# print history from the interactive python session\ndef print_history(n=None):\n l = readline.get_current_history_length()\n if n == None:\n n = l\n for i in range(l-n, l):\n print(readline.get_history_item(i + 1))\n\n#####################\n####\n\n\ndef to_unrotated_coords(cube):\n lon1D = cube.coord('grid_longitude').points # np.ndarray\n lat1D = cube.coord('grid_latitude').points # np.ndarray\n cs = cube.coord_system()\n pole_lon = cs.grid_north_pole_longitude\n pole_lat = cs.grid_north_pole_latitude\n lon2D, lat2D = np.meshgrid(lon1D, lat1D)\n unrotated_lons, unrotated_lats = unrotate_pole(\n lon2D, lat2D, pole_lon, pole_lat)\n return unrotated_lons, unrotated_lats\n\n\n# return tuple of coords for a given point in grid\n# for wind grid: x:<1;448>, y:<1:617>\n# for pressure grid: x:<1,448>, y:<1:616>\n\n# args: x,y (points in grid); lons, lats -> 2D array of coordinates (output from to unrotated coords)\ndef get_coords(x, y, lons, lats):\n return lats[x-1][y-1], lons[x-1][y-1]\n\n\n# rotate winds according to coords\n# arguments - u_cube, v_cube -> cubes with wind x and y direction\n# default coord system is GeogCS(6371229.0)\ndef rotate_winds_iris(u_cube, v_cube, cs=iris.coord_systems.GeogCS(6371229.0)):\n u_transformed, v_transformed = iris.analysis.cartography.rotate_winds(\n u_cube, v_cube, cs)\n return u_transformed, v_transformed\n\n\ndef rotate_winds(u, v, mode='uv'):\n # correction - array of angles' defferences\n correction_path = '/na/gpfs1/ARCHIWUM/MM/rotation/rotation_angles/rotation_angle_wind_p5_deg'\n correction = np.fromfile(correction_path, dtype=np.float32).byteswap()\n correction = correction.reshape(-1, 448)\n V, angle_rotated = to_V_angle(u, v)\n angle = angle_rotated + correction\n\n # condition 1: when V is 0.0, then angle does not exist -> 0.0\n angle = np.where(V != 0, angle, 0.0)\n # condition 2: bigger than 360: i.e. new angle is 355+8 = 363 -> 3\n angle = np.where(angle <= 360.0, angle, angle-360.0)\n # condition 3: less than 0: i.e. new angle is 3-8 = -5 -> 355\n angle = np.where(angle >= 0., angle, angle+360.0)\n if mode == 'uv':\n u1, v1 = to_u_v(V, angle)\n return u1, v1\n if mode == 'Va':\n return V, angle\n else:\n print('bad mode!')\n\n\n##########\n# READING AND SAVING BINARY DATA\ndef read_binary(filename):\n X = np.fromfile(filename, dtype=np.float32).byteswap()\n X = X.reshape((-1, 448)) # size (in case of the wind 617,448!)\n return X\n\n\ndef save_binary(data, name_out):\n np.ravel(data).astype(np.float32).byteswap().tofile(name_out)\n\n\n# TODO\n# replacing coords\n# cube.replace_coord(iris.coords.AuxCoord.from_coord(cube.coord('longitude')))\n# create a ndarray of tuples (lon,lat)\n'''\nfor i in range(len(coordinates_array)):\n for j in range(len(coordinates_array[i])):\n coordinates_array[i][j]=(latr[i][j],lonr[i][j])\n'''\n\ndef read_SM(mode='full'):\n assert mode == 'merged' or mode == 'full' or mode == 'short', 'Mode should be one of merged/full/short!'\t\n if mode == 'full':\n path = '/na/gpfs1/ARCHIWUM/MM/archutils_dev/stashmaster/stash_master.csv'\n if mode == 'short':\n path = '/na/gpfs1/ARCHIWUM/MM/archutils_dev/stashmaster/stash_master_short.csv'\n if mode == 'merged':\n path = '/na/gpfs1/ARCHIWUM/MM/archutils_dev/stashmaster/merged_sm.csv'\n return pd.read_csv(path,index_col = 0)\n\n\ndef find_SM(SM,name):\n return SM[SM['Name'].str.contains(name)]\n\ndef find_SM_re(SM,pattern):\n return SM[SM['Name'].str.match(pattern).str.len()>0]\n\ndef readInfo():\n infoPath = '/na/gpfs1/ARCHIWUM/MM/archutils_dev/fields/info_dict.json'\n with open(infoPath,'r') as f:\n info = json.load(f)\n return info\n\nif __name__ == '__main__':\n print('main')\n","sub_path":"UM_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"73884427","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport inventory.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('inventory', '0026_product_user'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='csv',\n name='name',\n field=models.FileField(max_length=200, upload_to=b'/home/ranjeet/PycharmProjects/esales_api/esales_api/media/csv/%Y-%m-%d', validators=[inventory.models.validate_file_extension]),\n preserve_default=True,\n ),\n ]\n","sub_path":"inventory/migrations/0027_auto_20150728_1119.py","file_name":"0027_auto_20150728_1119.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"333645649","text":"from copy import copy\nimport json\nfrom couchdbkit import ResourceNotFound\nfrom couchdbkit.ext.django.schema import Document, StringListProperty, BooleanProperty\nfrom couchdbkit.ext.django.schema import StringProperty, DictProperty, ListProperty\nfrom jsonobject import JsonObject\nfrom corehq.apps.cachehq.mixins import CachedCouchDocumentMixin\nfrom corehq.apps.userreports.exceptions import BadSpecError\nfrom corehq.apps.userreports.expressions.factory import ExpressionFactory\nfrom corehq.apps.userreports.filters.factory import FilterFactory\nfrom corehq.apps.userreports.indicators.factory import IndicatorFactory\nfrom corehq.apps.userreports.indicators import CompoundIndicator\nfrom corehq.apps.userreports.reports.factory import ReportFactory, ChartFactory, ReportFilterFactory\nfrom corehq.apps.userreports.reports.specs import FilterSpec\nfrom django.utils.translation import ugettext as _\nfrom corehq.apps.userreports.specs import EvaluationContext\nfrom dimagi.utils.couch.database import iter_docs\nfrom dimagi.utils.decorators.memoized import memoized\nfrom dimagi.utils.mixins import UnicodeMixIn\nfrom django.conf import settings\n\n\nDELETED_DOC_TYPES = {\n 'CommCareCase': [\n 'CommCareCase-Deleted',\n ],\n 'XFormInstance': [\n 'XFormInstance-Deleted',\n 'XFormArchived',\n 'XFormDeprecated',\n ],\n}\n\n\nclass DataSourceConfiguration(UnicodeMixIn, CachedCouchDocumentMixin, Document):\n \"\"\"\n A data source configuration. These map 1:1 with database tables that get created.\n Each data source can back an arbitrary number of reports.\n \"\"\"\n domain = StringProperty(required=True)\n referenced_doc_type = StringProperty(required=True)\n table_id = StringProperty(required=True)\n display_name = StringProperty()\n base_item_expression = DictProperty()\n configured_filter = DictProperty()\n configured_indicators = ListProperty()\n named_filters = DictProperty()\n\n def __unicode__(self):\n return u'{} - {}'.format(self.domain, self.display_name)\n\n def filter(self, document):\n filter_fn = self._get_main_filter()\n return filter_fn(document, EvaluationContext(document))\n\n def deleted_filter(self, document):\n filter_fn = self._get_deleted_filter()\n return filter_fn and filter_fn(document, EvaluationContext(document))\n\n def _get_main_filter(self):\n return self._get_filter([self.referenced_doc_type])\n\n def _get_deleted_filter(self):\n if self.referenced_doc_type in DELETED_DOC_TYPES:\n return self._get_filter(DELETED_DOC_TYPES[self.referenced_doc_type])\n return None\n\n def _get_filter(self, doc_types):\n extras = (\n [self.configured_filter]\n if self.configured_filter else []\n )\n built_in_filters = [\n self._get_domain_filter_spec(),\n {\n 'type': 'or',\n 'filters': [\n {\n 'type': 'property_match',\n 'property_name': 'doc_type',\n 'property_value': doc_type,\n }\n for doc_type in doc_types\n ],\n },\n ]\n return FilterFactory.from_spec(\n {\n 'type': 'and',\n 'filters': built_in_filters + extras,\n },\n context=self.named_filter_objects,\n )\n\n def _get_domain_filter_spec(self):\n return {\n 'type': 'property_match',\n 'property_name': 'domain',\n 'property_value': self.domain,\n }\n\n @property\n @memoized\n def named_filter_objects(self):\n return {name: FilterFactory.from_spec(filter, {})\n for name, filter in self.named_filters.items()}\n\n @property\n def indicators(self):\n doc_id_indicator = IndicatorFactory.from_spec({\n \"column_id\": \"doc_id\",\n \"type\": \"expression\",\n \"display_name\": \"document id\",\n \"datatype\": \"string\",\n \"is_nullable\": False,\n \"is_primary_key\": True,\n \"expression\": {\n \"type\": \"root_doc\",\n \"expression\": {\n \"type\": \"property_name\",\n \"property_name\": \"_id\"\n }\n }\n }, self.named_filter_objects)\n return CompoundIndicator(\n self.display_name,\n [doc_id_indicator] + [\n IndicatorFactory.from_spec(indicator, self.named_filter_objects)\n for indicator in self.configured_indicators\n ]\n )\n\n @property\n def parsed_expression(self):\n if self.base_item_expression:\n return ExpressionFactory.from_spec(self.base_item_expression, context=self.named_filter_objects)\n return None\n\n def get_columns(self):\n return self.indicators.get_columns()\n\n def get_items(self, document):\n if self.filter(document):\n if not self.base_item_expression:\n return [document]\n else:\n result = self.parsed_expression(document)\n if result is None:\n return []\n elif isinstance(result, list):\n return result\n else:\n return [result]\n else:\n return []\n\n def get_all_values(self, doc):\n context = EvaluationContext(doc)\n return [self.indicators.get_values(item, context) for item in self.get_items(doc)]\n\n def validate(self, required=True):\n super(DataSourceConfiguration, self).validate(required)\n # these two properties implicitly call other validation\n self._get_main_filter()\n self._get_deleted_filter()\n self.indicators\n self.parsed_expression\n\n\n @classmethod\n def by_domain(cls, domain):\n return sorted(\n cls.view('userreports/data_sources_by_domain', key=domain, reduce=False, include_docs=True),\n key=lambda config: config.display_name\n )\n\n @classmethod\n def all(cls):\n ids = [res['id'] for res in cls.get_db().view('userreports/data_sources_by_domain',\n reduce=False, include_docs=False)]\n for result in iter_docs(cls.get_db(), ids):\n yield cls.wrap(result)\n\n\nclass ReportConfiguration(UnicodeMixIn, CachedCouchDocumentMixin, Document):\n \"\"\"\n A report configuration. These map 1:1 with reports that show up in the UI.\n \"\"\"\n domain = StringProperty(required=True)\n visible = BooleanProperty(default=True)\n config_id = StringProperty(required=True)\n title = StringProperty()\n description = StringProperty()\n aggregation_columns = StringListProperty()\n filters = ListProperty()\n columns = ListProperty()\n configured_charts = ListProperty()\n\n def __unicode__(self):\n return u'{} - {}'.format(self.domain, self.title)\n\n @property\n @memoized\n def config(self):\n try:\n return DataSourceConfiguration.get(self.config_id)\n except ResourceNotFound:\n raise BadSpecError(_('The data source referenced by this report could not be found.'))\n\n @property\n @memoized\n def ui_filters(self):\n return [ReportFilterFactory.from_spec(f) for f in self.filters]\n\n @property\n @memoized\n def charts(self):\n return [ChartFactory.from_spec(g._obj) for g in self.configured_charts]\n\n @property\n def table_id(self):\n return self.config.table_id\n\n def get_ui_filter(self, filter_slug):\n for filter in self.ui_filters:\n if filter.name == filter_slug:\n return filter\n return None\n\n def validate(self, required=True):\n def _check_for_duplicate_slugs(filters):\n slugs = [FilterSpec.wrap(f).slug for f in filters]\n # http://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-python-list\n duplicated_slugs = set(\n [slug for slug in slugs if slugs.count(slug) > 1]\n )\n if len(duplicated_slugs) > 0:\n raise BadSpecError(\n _('Filters cannot contain duplicate slugs: %s')\n % ', '.join(sorted(duplicated_slugs))\n )\n\n super(ReportConfiguration, self).validate(required)\n\n # these calls implicitly do validation\n ReportFactory.from_spec(self)\n self.ui_filters\n self.charts\n\n _check_for_duplicate_slugs(self.filters)\n\n @classmethod\n def by_domain(cls, domain):\n return sorted(\n cls.view('userreports/report_configs_by_domain', key=domain, reduce=False, include_docs=True),\n key=lambda report: report.title,\n )\n\n @classmethod\n def all(cls):\n ids = [res['id'] for res in cls.view('userreports/report_configs_by_domain',\n reduce=False, include_docs=False)]\n for result in iter_docs(cls.get_db(), ids):\n yield cls.wrap(result)\n\n\nclass CustomDataSourceConfiguration(JsonObject):\n _datasource_id_prefix = 'custom-'\n domains = ListProperty()\n config = DictProperty()\n\n @classmethod\n def get_doc_id(cls, table_id):\n return '{}{}'.format(cls._datasource_id_prefix, table_id)\n\n @classmethod\n def all(cls):\n for path in settings.CUSTOM_DATA_SOURCES:\n with open(path) as f:\n wrapped = cls.wrap(json.load(f))\n for domain in wrapped.domains:\n doc = copy(wrapped.config)\n doc['domain'] = domain\n doc['_id'] = cls.get_doc_id(doc['table_id'])\n yield DataSourceConfiguration.wrap(doc)\n\n @classmethod\n def by_domain(cls, domain):\n return [ds for ds in cls.all() if ds.domain == domain]\n\n @classmethod\n def by_id(cls, config_id):\n matching = [ds for ds in cls.all() if ds.get_id == config_id]\n if not matching:\n return None\n return matching[0]\n","sub_path":"corehq/apps/userreports/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"332362616","text":"def a():\n print(\"****************\")\n\n# 普通函数调用\ndef func():\n a()\n\n\"\"\"\n递归调用:一个函数,调用了自身,称为递归调用\n递归函数:一个会调用自身的函数称为递归函数\n\n凡是循环能干的事,递归都能干\n\n方式:\n1、写出临界条件\n2、找这一次和上一次的关系\n3、假设当前函数已经能用,调用自身计算上一次的结果,再次求出本次的结果\n\"\"\"\n\n# 输入一个数(大于等于1),求1+2+3+......+n的和\ndef sum1(n):\n sum = 0\n for x in range(1, n + 1):\n sum += x\n return sum\n\n\nresult = sum1(100)\nprint(\"result = \", result)\nprint(\"=======================\")\n\n\"\"\"\n1+2+3+4+5\nsum2(1) + 0 = sum2(1)\nsum2(1) + 2 = sum2(2)\nsum2(2) + 3 = sum2(3)\nsum2(3) + 4 = sum2(4)\nsum2(4) + 5 = sum2(5)\n\n5 + sum2(4)\n5 + 4 + sum2(3)\n5 + 4 + 3 + sum2(2)\n5 + 4 + 3 + sum2(1)\n5 + 4 + 3 + 2 + 1\n\n5 * multiply(4)\n5 * 4 * multiply(3)\n5 * 4 * 3 * multiply(2)\n5 * 4 * 3 * 2 * multiply(1)\n5 * 4 * 3 * 2 * 1\n\"\"\"\ndef sum2(n):\n if n == 1:\n return 1\n else:\n return n + sum2(n - 1)\n\n\nresult2 = sum2(100)\nprint(\"result2 = \", result2)\n\n\ndef multiply(n):\n if n == 1:\n return 1\n else:\n return n * multiply(n - 1)\n\n\nresult3 = multiply(5)\nprint(\"result3 = \", result3)","sub_path":"pers/cyj/day09/01-递归/递归.py","file_name":"递归.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"255675227","text":"from django.urls import path\n\nfrom social import views as social_views\n\nurlpatterns = [\n path('', social_views.PostListView.as_view(), name='home'),\n path('new/', social_views.PostCreateView.as_view(), name='post-create'),\n path('post//',\n social_views.PostDetail.as_view(),\n name='post-detail'),\n path('post//update/',\n social_views.PostUpdateView.as_view(),\n name='post-update'),\n path('post//delete/',\n social_views.PostDeleteView.as_view(),\n name='post-delete'),\n path('search/', social_views.search, name='search'),\n path('tags//', social_views.search_tags, name='search-tags'),\n # AJAX\n path('like/', social_views.like_post, name='like-post'),\n path('follow/', social_views.follow_user, name='follow-user'),\n\n # Modals\n # Posts\n path('new-modal/',\n social_views.PostCreateViewModal.as_view(),\n name='post-create-modal'),\n path('post//update-modal/',\n social_views.PostUpdateViewModal.as_view(),\n name='post-update-modal'),\n path('post//delete-modal/',\n social_views.PostDeleteViewModal.as_view(),\n name='post-delete-modal'),\n # Comments\n path('post//comment-new-modal/',\n social_views.CommentCreateViewModal.as_view(),\n name='comment-create-modal'),\n path('post//comment-delete-modal/',\n social_views.CommentDeleteViewModal.as_view(),\n name='comment-delete-modal'),\n # Followers\n path('/followers/',\n social_views.FollowersView.as_view(),\n name='followers'),\n path('/following/',\n social_views.FollowingView.as_view(),\n name='following'),\n]\n","sub_path":"social/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"522938662","text":"# Input: 2d matrix of state probabilities\n# Output: list of neumerators and a denominator\n\ndef getGCD(a,b):\n if (b == 0):\n return a\n else:\n return getGCD(b, a % b)\n\ndef getGCDList(matrix):\n\t# Returns the greatest common denominator of a list (or matrix)\n legnth = len(matrix)\n output = 0\n for i in range(0, legnth):\n output = getGCD(output, matrix[i])\n return output\n\ndef fuse(matrix, row, col):\n\t\n # Get the size of the data passed in\n row_legnth=len(matrix[row])\n col_legnth=sum(matrix[col])\n \n # Get the indices\n indices=(set(range(row_legnth))-{row,col})\n \n # Create a new blank matrix of the same width as the origional matrix\n output_matrix = [0 for i in matrix[row]]\n \n # Iterate through every index\n for i in indices:\n \t# Populate the new matrix using back propagated distribution\n output_matrix[i]= col_legnth*matrix[row][i]+matrix[row][col]*matrix[col][i]\n \n # Get greatest common denominator\n gc=getGCDList(output_matrix)\n \n # Return a list of GCDs\n output = [int( i / gc ) for i in output_matrix ]\n return output\n\ndef answer(m):\n\t# Find the size\n\theight = len(m)\n\twidth = len(m[0])\n\t\n\t# Duplicate m for modification\n\tmatrix = list(m)\n\t\n\t# Clear the matrix\n\tfor i,form in enumerate(matrix):\n\t\tform[i] = 0\n\t\n\t# Get the sum of each state's probability\n\tstate_sums = []\n\tfor state in matrix:\n\t\tstate_sums.append(sum(state))\n\t\n\t# Find all terminal states, then store them in a list\n\tterminal_states = [i for i,item in enumerate(state_sums) if item==0]\n\t\n\t# Find all non-terminal states, then store them in a list\n\tnonterminal_states = list((set(range(height)) - set(terminal_states)))\n\t\n\t# How many non-terminal states are there?\n\tnonterminal_states_count = len(nonterminal_states)\n\t\n\t# Iterate through each non-terminal state\n\tfor i in range(0, nonterminal_states_count - 1):\n\t\tindex_col = nonterminal_states[ nonterminal_states_count -i -1 ]\n\t\t# Iterate through each probability\n\t\tfor j in range(0, nonterminal_states_count -1):\n\t\t\tindex_row = nonterminal_states[j]\n\t\t\t# Replace matrix with new generated data\n\t\t\tmatrix[index_row] = fuse( matrix, index_row, index_col)\n\toutput = []\n\tfor i in terminal_states:\n\t\toutput.append(matrix[0][i])\n\t\n\t# append the base tothe end of the list\n\ttotal = sum(output)\n\toutput.append(total)\n\t\n\tif not total:\n\t\t# Fill output with 1\n\t\toutput = [1 for i in terminal_states]\n\t\toutput.append(len(terminal_states))\n\t\n\treturn output\n\n\n\n# mat=[\n# [1, 2, 3, 0, 0, 0],\n# [4, 5, 6, 0, 0, 0],\n# [7, 8, 9, 1, 0, 0],\n# [0, 0, 0, 0, 1, 2],\n# [0, 0, 0, 0, 0, 0],\n# [0, 0, 0, 0, 0, 0]\n \n# ]\n\n# print answer(mat)","sub_path":"Test-3/doomsday_fuel.py","file_name":"doomsday_fuel.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"620235643","text":"from django.core.management.base import BaseCommand\nfrom geo.models import Map\nfrom geo.models import District, Palika\nimport utils.topojson\n\nimport json\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n print('Loading districts')\n self.load_districts()\n print('Done')\n print('Loading Palikas')\n self.load_palikas()\n print('Done')\n\n def load_districts(self):\n map = Map.objects.filter(key='districts').first()\n if not map:\n return\n\n topojson = json.loads(map.file.read().decode('utf-8'))\n scale = topojson['transform']['scale']\n trans = topojson['transform']['translate']\n arcs = topojson['arcs']\n geometries = list(topojson['objects'].values())[0]['geometries']\n\n for geometry in geometries:\n properties = geometry['properties']\n name = properties['DISTRICT'].capitalize()\n\n District.objects.update_or_create(\n name=name,\n defaults={\n 'geojson': utils.topojson.geometry(\n geometry, arcs, scale, trans\n ),\n },\n )\n\n def load_palikas(self):\n map = Map.objects.filter(key='palikas').first()\n if not map:\n return\n\n topojson = json.loads(map.file.read().decode('utf-8'))\n scale = topojson['transform']['scale']\n trans = topojson['transform']['translate']\n arcs = topojson['arcs']\n geometries = list(topojson['objects'].values())[0]['geometries']\n\n for geometry in geometries:\n properties = geometry['properties']\n name = properties['FIRST_GaPa'].capitalize()\n district_name = properties['FIRST_DIST'].capitalize()\n\n if not name or not district_name:\n continue\n\n district = District.objects.filter(name=district_name).first()\n if not district:\n print(\n 'Skipping palika {} because district {} not found'.format(\n name, district_name\n )\n )\n continue\n\n Palika.objects.update_or_create(\n name=name,\n defaults={\n 'district': district,\n 'geojson': json.dumps(utils.topojson.geometry(\n geometry, arcs, scale, trans\n )),\n },\n )\n","sub_path":"server/apps/geo/management/commands/load_map_areas.py","file_name":"load_map_areas.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"616307623","text":"# coding=utf-8\nimport time\nimport xlrd\nimport os\nimport glob\nfrom ..common import conf\nfrom ..common import logoutput\n\nclass Time():\n '''\n 工具模块,时间类\n '''\n def get_now_time(self):\n '''\n 获取当前时间,以字符串格式返回\n :return:\n '''\n nowtime = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))\n return nowtime\n\nclass Excel():\n '''\n 用来操作Excel\n '''\n def __init__(self):\n self.lg=logoutput.Logger()\n\n def excelRead(self,path):\n CONF_NAME_EXCELPATH=\"ExcelPath\"\n CONF_NAME_XLSNAME=\"xlsname\"\n CONF_NAME_SHEETNAME=\"sheetname\"\n\n '''\n\n :param path: 配置文件所在路径\n :return:返回table\n '''\n try:\n cf=conf.Conf()\n d=cf.get_conf_data(CONF_NAME_EXCELPATH)\n # os.chdir(d[\"xfpath\"])\n data = xlrd.open_workbook(CONF_NAME_XLSNAME)\n table = data.sheet_by_name(CONF_NAME_SHEETNAME) #通过名称获取\n return table\n except Exception as e:\n self.lg.error(e)\n\nclass ResultChinese():\n\n def get_report_dir(self):\n pyfiles=glob.glob(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+\"\\\\report\\\\*.xml\")\n if not pyfiles:\n return False\n else:\n return pyfiles\n\n def switch_result(self):\n pathList=self.get_report_dir()\n if pathList:\n p=list(pathList)[0]\n f=open(p,\"r\",encoding=\"utf-8\")\n r=f.read()\n r=r.encode(\"unicode_escape\")\n r=r.replace(b\"\\\\\\\\u\",b\"\\\\u\")\n r=r.decode(\"unicode_escape\",\"ignore\")\n f.close()\n f1=open(p,\"w\",encoding=\"utf-8\")\n f1.write(str(r))\n f1.close()\n else:\n lg=logoutput.Logger()\n lg.error(\"未找到测试结果文件!\")\n\nif __name__ == '__main__':\n rc=ResultChinese()\n rc.switch_result()\n # print(a)","sub_path":"common/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"92430817","text":"from hivepy import *\nimport math\n\ndef echoList(lst):\n for key in lst:\n print(key + \":\", lst[key])\n\ndef playerTest(username='Jam2400'):\n \n print(\" \")\n player = getPlayer(username)\n stats = {'Name' : player.getName(),\n 'Rank' : player.getRank(),\n 'Tokens' : player.getTokens(),\n 'Credits' : player.getCredits(),\n 'First Login' : player.getFirstLogin(),\n 'Last Login' : player.getLastLogin()\n }\n \n #echoList(stats)\n for achv in player.getAchievements():\n print('Name: ' + achv)\n print(' ')\n\n print(\" \")\n\ndef minigameTest():\n minigame = str(input('Minigame: '))\n mg = getMinigame(minigame)\n stats = {'Unique Players' : mg.getUniquePlayers(),\n }\n\n for achv in mg.getAchievements():\n print('Name: ' + achv['publicname'] +\n '\\nDescription: ' + str(achv['description']))\n print('Progress: ' + str(achv['stages']))\n print(' ')\n\n #echoList(stats)\n\ndef hiveStatsTest():\n hive = getHiveStats()\n stats = {'Unique Players' : hive.getUniquePlayers(),\n 'Online Players' : hive.getOnlinePlayers()\n }\n\n echoList(stats)\n\ndef percentageTest():\n\n total = 0\n\n hive = getHiveStats()\n totalPlayers = hive.getUniquePlayers()\n players = {\n 'sg' : getMinigame('survivalgames').getUniquePlayers(),\n 'timv' : getMinigame('timv').getUniquePlayers(),\n 'sp' : getMinigame('splegg').getUniquePlayers(),\n 'oitc' : getMinigame('oitc').getUniquePlayers(),\n 'cai' : getMinigame('cowboys').getUniquePlayers(),\n 'cr' : getMinigame('cranked').getUniquePlayers(),\n 'bp' : getMinigame('blockparty').getUniquePlayers(),\n 'dr' : getMinigame('deathrun').getUniquePlayers(),\n }\n \n for key in players:\n number = players[key]\n print(key + ': ' + str(players[key]))\n total += number\n \n\n for key in players:\n number = players[key]\n percentage = math.ceil((number / total) * 100)\n print(percentage)\n\n\n\n print('Total: ' + str(total))\n\n \n \n\n \n\n \n\n \n \n \n\n#playerTest() #ok\nminigameTest() #ok\n#hiveStatsTest() #ok\n\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"529006346","text":"import pandas as pd\nimport glob,os\nimport warnings\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import normalize\nwarnings.filterwarnings(\"ignore\")\n\n\ndef pca(data):\n pca = PCA()\n pca.fit(data)\n X_pca = pca.transform(normalize(data,axis=0))\n return X_pca\n\ndef concat_pca(data,split=5):\n pca = PCA()\n \n data=normalize(data,axis=0)\n idx=data.shape[1]//split\n temp=[]\n for i in range(split):\n _data=data[:,i*idx:(i+1)*idx]\n \n _pca = pca.fit_transform(_data)\n temp.append(_pca)\n concat = np.hstack(temp)\n return concat\n\n\nclass KnobsDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, train_shot=5, test_shot=5, way=5, dataset_type='train',transform='pca',feature_type='curve'):\n \"\"\"\n Args:\n train_shot : train시에 shot의 개수를 지정 이에 따라서 sample된 데이터에서 몇개를 뽑을지 지정됨\n \n test_shot : train시에 shot의 개수를 지정 이에 따라서 sample된 데이터에서 몇개를 뽑을지 지정됨\n way : 몇개의 task를 한번의 meta learning 시에 볼지를 정함\n ex : 5 shot 4way 라면 4개의 task 를 무작위로 4번 sample 하여 학습 진행 \n # https://www.borealisai.com/en/blog/tutorial-2-few-shot-learning-and-meta-learning-i/ 참조\n dataset_type : evaluation을 gpu dataset에서 한다.\n transform : 어떤 방식으로 feature를 가공할 건지 현재는 pca만 지원\n type: code의 representation을 할 방법을 정함 curve,iterval,knob가 있음\n \"\"\"\n _dataset = []\n num = 0\n self.size = 1000000\n if transform=='pca':\n self.transform = pca\n elif transform=='concat':\n self.transform = concat_pca\n elif transform==None:\n self.transform = None\n else :\n raise NotImplementedError\n self.train_shot = train_shot\n self.test_shot = test_shot\n self.way = way\n self.dataset_type = dataset_type\n if dataset_type == 'train':\n root=os.path.join(os.getcwd(),'data/result_cpu.pkl')\n elif dataset_type == 'test':\n root=os.path.join(os.getcwd(),'data/result_cuda.pkl')\n elif dataset_type == 'val':\n root=os.path.join(os.getcwd(),'data/result_cuda.pkl')\n else:\n raise Exception('please chice dataset type train,test and val')\n df=pd.read_pickle(root, compression='gzip')\n df['targets'] = df['targets'].apply(str)\n if feature_type=='curve':\n extract_column='vectors_curve'\n elif feature_type=='iterval':\n extract_column='vectors_itervar'\n elif feature_type=='knob':\n extract_column='vectors_knob'\n else:\n raise Exception('please chice feature type iterval,knob and curve')\n\n for idx, value in df.groupby(['shots']):\n # idx로 task를 구분 len은 feature의 크기가 달라지는 것을 대응하기 위하여(그럴 경우 pca를 할 수 없음)\n # vgg ,resnet만을 이용하여 만들시에 \n # itervar Counter({679: 18000, 595: 11400})\n # curve Counter({481: 18000, 321: 11400})\n # knobs Counter({7: 29400})\n value['idx'] = num\n value['len'] = value[extract_column].map(lambda x: len(x))\n _dataset.append(value[['idx', extract_column, 'cost', 'len']].values)\n num += 1\n\n self.dataset = np.concatenate(_dataset)\n del _dataset\n\n def __len__(self):\n return self.size\n\n def __getitem__(self, idx):\n batch = dict()\n\n\n train_data = []\n train_labels = []\n test_data = []\n test_labels = []\n\n # ways=np.random.default_rng().choice(_max+1, size=5, replace=False)\n len_vector = np.random.choice(self.dataset[:, 3])\n # uniform dis에서 길이 제한을 선택 => 개수가 많은 비율이 선택확률이 됨\n selected_dataset = self.dataset[self.dataset[:, 3] == len_vector]\n # 위에서 선택한 백터 길이을 이용하려 dataset을 필터링\n ways = np.random.default_rng().choice(np.unique(selected_dataset[:, 0]), size=self.way, replace=False)\n # 위 필터링된 데이터가 존재하는 idx를 unique로 뽑고(특정 idx에서는 하나 또는 두개의 len 만\n # 존재하는 경우가 있음 그것을 way size 만큼 뽑는다.\n \n for way in ways:\n idx = np.random.choice(np.where(selected_dataset[:, 0] == way)[0], self.train_shot)\n # np.where로 way에 해당하는 selected data array idx 반환 5개 추출\n # N-shot 을 진행할 idx 추출\n train_data.append(np.array(np.vstack(selected_dataset[idx][:, 1])))\n train_labels.append(selected_dataset[idx][:, 2])\n # test의 경우 idx를 다시 sample\n idx = np.random.choice(np.where(selected_dataset[:, 0] == way)[0], self.test_shot)\n test_data.append(np.array(np.vstack(selected_dataset[idx][:, 1])))\n test_labels.append(selected_dataset[idx][:, 2])\n\n train_data = np.vstack(train_data)\n train_labels = np.concatenate(train_labels)\n train_labels=train_labels.astype(np.float32)\n test_data = np.vstack(test_data)\n test_labels = np.concatenate(test_labels)\n test_labels = test_labels.astype(np.float32)\n\n if self.transform:\n train_data = self.transform(train_data)\n test_data = self.transform(test_data)\n train_data = torch.tensor(train_data, dtype=torch.float32)\n test_data = torch.tensor(test_data, dtype=torch.float32)\n train_labels = torch.tensor(train_labels, dtype=torch.float32)\n test_labels = torch.tensor(test_labels, dtype=torch.float32)\n batch['train'] = (train_data, train_labels)\n batch['test'] = (test_data, test_labels)\n return batch\nif __name__ == \"__main__\":\n t = KnobsDataset()\n import torch\n\n dataset_loader = torch.utils.data.DataLoader(t,\n batch_size=4, shuffle=False,\n num_workers=4)\n for i in dataset_loader:\n print(i)","sub_path":"maml/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"481338400","text":"import json\nimport os\nfrom collections import defaultdict\nimport pandas as pd\nimport numpy as np\n\nclass PokeData(): \n \"\"\"\n CLASS TO CREATE DATAFRAMES FOR \n 1. Total Battle Counts on Pokemon Showdown\n 2. Pokemon Usage Rates\n 3. Pokemon Abilities\n 4. Pokemon Teammates \n 5. Pokemon Counters \n 6. Pokemon Natures \n 7. Pokemon Items\n 8. Pokemon ID reference\n 9. Nature ID reference\n 10. Ability ID reference\n 11. Item ID reference\n\n Parent class that gives some high-level functionality to parse 2 different dictionary structures\n Popularity child targets one sublevel for one the total number of users that month\n Usage child targets complete matchup data\n \"\"\"\n def __init__(self, columns=[]):\n self.columns = columns\n self.df = pd.DataFrame(columns=columns) \n \n def _add_new_data(**kwargs):\n #new_data = defaultdict(list)\n return\n \n def update_df(self, **kwargs):\n new_data = self._add_new_data(**kwargs)\n self.df = pd.concat([self.df, new_data], sort=False, ignore_index=True)\n \n## MONTHLY POPULARITY EXTRACTION \nclass Popularity(PokeData):\n \"\"\"\n Specific to outer layer of JSON file containing all user statistics\n \"\"\"\n def __init__(self, columns=['month', 'num_battles']):\n PokeData.__init__(self, columns)\n \n def _add_new_data(self, month=str, value=int):\n out = pd.DataFrame([[month, value]], columns=self.columns)\n return out\n\nclass PokeReference():\n \"\"\"\n Counter, dictionary and df data storage Class to track reference codes for database values\n Used within Usage Class (pokemon, abilities, natures, items) \n INPUT\n dict_label => str, the target data key for the Showdown JSON file\n id_label => str \n (i.e. 'Abilities' & 'ability_id')\n \"\"\"\n def __init__(self, dict_label=None, id_label='id', columns=[]):\n self.next_id = 0\n self.info = dict()\n self.dict_label = dict_label \n self.id_label = id_label\n self.df = pd.DataFrame(columns=columns)\n \n def update_ids(self, name):\n \"\"\"\n Method checks if name is not in self.info (id reference dictionary)\n & Updates accordingly\n \"\"\"\n if name not in self.info:\n self.info[name] = self.next_id\n self.next_id += 1 \n \n def update_df(self):\n self.df = pd.concat([self.df, pd.DataFrame(self.new_data)],\n sort=False, ignore_index=True)\n return\n \n def _initialize_new_data(self):\n \"\"\"\n Initializes a new object to clean/store a new month's worth of data\n \"\"\"\n self.new_data = defaultdict(list)\n return\n \n def _add_new_data(self, month, dic, id_=None, key=None):\n \"\"\"\n Method to update self.new_data object\n INPUT\n month => str\n dic => dict containing nebulus usage data on a single pokemon\n id_ => int or none, relating to outer for/loop of data cleaning \n key => str or none, relating to outer for/loop for data cleaning\n OUTPUT\n None if id_ is given, otherwise id_ (int) \n *IMPORTANT* id_ should only passed when using this Class for Pokemon \n as this value is what ties the whole dataset together\n \"\"\"\n if id_ != None:\n if self.dict_label == 'Spreads':\n #transform spreads into simple count of natures\n sub_dict = defaultdict(int)\n for spread, count in dic[self.dict_label].items():\n nature = spread.split(':')[0]\n self.update_ids(nature)\n sub_dict[nature] += count\n dic[self.dict_label] = sub_dict\n \n for item, count in dic[self.dict_label].items():\n self.update_ids(item)\n self.new_data['id'].append(id_)\n self.new_data[self.id_label].append(self.info[item])\n self.new_data['count'].append(count)\n self.new_data['month'].append(month)\n return\n \n else:\n self.update_ids(key)\n id_ = self.info[key] #primary pokemon key\n self.new_data['id'].append(id_)\n self.new_data['month'].append(month) \n self.new_data['count'].append(dic['Raw count'])\n self.new_data['usage'].append(dic['usage'])\n return id_\n \n def pandify(self):\n df = pd.DataFrame(self.info.items(), columns=['name', 'id'])[['id', 'name']]\n return df\n \n## MONTHLY POKEMON USAGE EXTRACTION \nclass Usage(PokeData):\n \"\"\"\n Child class that stores: \n Pokemon usage data as it's primary df\n Teammate statistics as teammate_df\n Checks and counter statistics as counter_df\n Ability statistics as ability_df\n Spread statistics (parsed for only the ability name) as nature_df\n Reference dictionary storing unique keys for each Pokemon, Ability, Nature\n *NOTE* While the variable structure is a bit hairy, \n it helps greatly reduce runtime\n \"\"\"\n def __init__(self, columns=['id', 'month', 'count', 'usage']):\n PokeData.__init__(self, columns)\n\n self.ids = PokeReference()\n self.abilities = PokeReference(dict_label='Abilities', id_label='ability_id',\n columns=['id', 'ability_id', 'count', 'month'])\n self.items = PokeReference(dict_label='Items', id_label='item_id',\n columns=['id', 'item_id', 'count', 'month'])\n self.natures = PokeReference(dict_label='Spreads', id_label='nature_id',\n columns=['id', 'nature_id', 'count', 'month'])\n \n self.counter_df = pd.DataFrame(columns=['id', 'counter_id', 'num_battles', 'check_pct', 'month'])\n self.counter_func = lambda dic, k, v: k in dic.keys() and v[1] > 0.5\n \n self.teammate_df = pd.DataFrame(columns=['id', 'mate_id', 'x', 'month'])\n self.teammate_func = lambda dic, k, v: k in dic.keys() and dic[k]['usage'] > 0.005\n \n def _combine_data(self, new_counters, new_teammates):\n self.counter_df = pd.concat([self.counter_df, pd.DataFrame(new_counters)],\n sort=False, ignore_index=True)\n self.teammate_df = pd.concat([self.teammate_df, pd.DataFrame(new_teammates)],\n sort=False, ignore_index=True)\n self.abilities.update_df()\n self.items.update_df()\n self.natures.update_df() \n out = pd.DataFrame(self.ids.new_data)\n \n return out\n \n \n def _add_new_counter_mates(self, month, dic, new_data, id_, key, label, func, check):\n for k, v in dic[key].items():\n if func(check, k, v):\n self.ids.update_ids(k)\n else:\n continue\n new_data['id'].append(id_)\n new_data[label].append(self.ids.info[k])\n if label == 'counter_id':\n new_data['num_battles'].append(v[0])\n new_data['check_pct'].append(v[1])\n else:\n new_data['x'].append(v)\n new_data['month'].append(month)\n return new_data\n \n def _add_new_data(self, dic=dict, month=str):\n \n self.ids._initialize_new_data()\n self.abilities._initialize_new_data()\n self.items._initialize_new_data()\n self.natures._initialize_new_data()\n new_counters = defaultdict(list)\n new_teammates = defaultdict(list)\n\n for key, sub in dic.items():\n #the dictionary to be passed in uses pokemon names as keys\n if sub['usage'] < 0.005:\n continue\n \n id_ = self.ids._add_new_data(month, sub, key=key)\n\n self.abilities._add_new_data(month, sub, id_=id_)\n self.items._add_new_data(month, sub, id_=id_)\n self.natures._add_new_data(month, sub, id_=id_)\n \n new_counters = self._add_new_counter_mates(month, sub, new_counters,\n id_, 'Checks and Counters',\n 'counter_id', self.counter_func,\n dic)\n \n new_teammates = self._add_new_counter_mates(month, sub, new_teammates,\n id_, 'Teammates', \n 'mate_id', self.teammate_func,\n dic)\n \n return self._combine_data(new_counters, new_teammates)\n\ndef save_to_folder(df, wp, name):\n full_path = f'{wp}{name}.csv'\n df.to_csv(full_path, header=True, index=False)\n return\n\nif __name__ == '__main__':\n\n popularity = Popularity()\n usage = Usage()\n \n read_folder = '~/Pokestars/data/raw/chaos/'\n \n for fp in sorted(os.listdir(read_folder)):\n try: #this try, except just helps to ignore any '.' sys files \n with open(read_folder+fp, 'r') as f:\n d = json.load(f)\n month = fp[-7:-5] + '-' + fp[:4]\n print(f'\\n>> Parsing Pokemon data from {month}') \n dic = d['data']\n num_battles = d['info']['number of battles']\n\n popularity.update_df(month=month, value=num_battles)\n usage.update_df(dic=dic, month=month)\n except:\n pass\n \n write_folder = 'data/clean/'\n try:\n os.mkdir(write_folder)\n except:\n pass\n \n df_list = [ref.pandify() for ref in [usage.ids, usage.natures, \n usage.abilities, usage.items]]\n df_list.extend([popularity.df, usage.df, usage.abilities.df, usage.items.df, \n usage.natures.df, usage.counter_df, usage.teammate_df])\n df_names = [name+'_reference' for name in ['pokemon', 'nature', 'ability', 'item']]\n df_names.extend(['monthly_popularity', 'battle_counts', 'ability_counts', \n 'item_counts', 'nature_counts', 'counter_stats', 'teammate_stats'])\n \n for df, name in zip(df_list, df_names):\n save_to_folder(ref, write_folder, name)","sub_path":"src/json_clean_to_csv.py","file_name":"json_clean_to_csv.py","file_ext":"py","file_size_in_byte":10435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"542875366","text":"x = input()\ny = input()\n\ntry:\n print(\"Resultado de la división: \" + str(x / y))\nexcept ZeroDivisionError:\n print(\"Error: Se intentó dividir por 0\")\nexcept (ValueError, TypeError):\n print(\"Error: Valor o tipo no válido\")\nexcept:\n print(\"Ocurrió un error inesperado\")","sub_path":"codigo/excepciones/try_except_3.py","file_name":"try_except_3.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"281557573","text":"import os\n\nfrom cache import load_from_pickle\nfrom data_generator.job_runner import JobRunner, sydney_working_dir\nfrom tlm.alt_emb.add_alt_emb import MatchTree, convert_alt_emb2\n\n\nclass Worker:\n def __init__(self, match_tree: MatchTree, out_path):\n self.out_dir = out_path\n self.match_tree = match_tree\n\n def work(self, job_id):\n input_path = os.path.join(sydney_working_dir, \"clueweb12_13B_no_short\", str(job_id))\n output_file = os.path.join(self.out_dir, \"{}\".format(job_id))\n convert_alt_emb2(input_path, output_file, self.match_tree)\n\n\nif __name__ == \"__main__\":\n def worker_gen(out_dir):\n match_tree = load_from_pickle(\"match_tree_nli_dev\")\n return Worker(match_tree, out_dir)\n\n runner = JobRunner(sydney_working_dir, 1000, \"alt_emb_13\", worker_gen)\n runner.start()\n\n\n\n","sub_path":"src/tlm/alt_emb/runner/alt_emb_gen/clueweb12_13_nli_dev.py","file_name":"clueweb12_13_nli_dev.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"385702690","text":"from django.conf.urls.defaults import *\nfrom views import hello\nfrom books import views #链接views导入函数\nfrom django.conf import settings\n#settings.configure()\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', views.begin), #welcome to the bookdb\n url(r'^search-form/$',views.search_form), #查询函数\n url(r'^search/$',views.search),#查询结果页面\n url(r'^show/$',views.show),#所有书的信息展示页面\n url(r'^delete/$',views.delete),#删除某一本书\n url(r'^book_author/$',views.book_author),#显示某本书的详细信息\n url(r'^welcome/$',views.begin), #welcome to the bookdb\n url(r'^add/$',views.bookinsert),#新增某本书\n url(r'^add_author/$',views.authorinsert),#新增作者\n url(r'^ask/$',views.add_ask),#超链接,用于询问新增的书是否需要新增作者\n url(r'^book_modify/$',views.bookmodify),#修改图书信息\n url(r'^showauthor/$',views.showauthor),#显示作者信息\n url(r'^author_modify/$',views.authormodify),#修改作者信息\n # Example:\n # (r'^mysite/', include('mysite.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # (r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"30805095","text":"import math,string,itertools,fractions,heapq,collections,re,array,bisect,random\n\nclass GUMIAndSongsDiv2:\n def maxSongs(self, duration, tone, T):\n n = len(duration)\n if n == 0:\n return 0\n\n songs = [self.Song(d=duration[i], t=tone[i]) for i in range(n)]\n songs.sort(key = lambda x: x.t)\n\n ans = 0\n for i in range(n):\n for j in range(i, n):\n total = songs[j].t - songs[i].t\n cnt = 0\n song_duration = sorted([x.d for x in songs[i:j+1]])\n for k in range(len(song_duration)):\n if total + song_duration[k] <= T:\n total += song_duration[k]\n cnt += 1\n else:\n break\n\n ans = max(ans, cnt)\n\n return ans\n\n class Song:\n def __init__(self, d=0, t=0):\n self.d = d\n self.t = t\n\n# BEGIN KAWIGIEDIT TESTING\n# Generated by KawigiEdit-pf 2.3.0\nimport sys\nimport time\ndef KawigiEdit_RunTest(testNum, p0, p1, p2, hasAnswer, p3):\n\tsys.stdout.write(str(\"Test \") + str(testNum) + str(\": [\") + str(\"{\"))\n\tfor i in range(len(p0)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(p0[i]))\n\t\n\tsys.stdout.write(str(\"}\") + str(\",\") + str(\"{\"))\n\tfor i in range(len(p1)):\n\t\tif (i > 0):\n\t\t\tsys.stdout.write(str(\",\"))\n\t\t\n\t\tsys.stdout.write(str(p1[i]))\n\t\n\tsys.stdout.write(str(\"}\") + str(\",\") + str(p2))\n\tprint(str(\"]\"))\n\tobj = GUMIAndSongsDiv2()\n\tstartTime = time.clock()\n\tanswer = obj.maxSongs(p0, p1, p2)\n\tendTime = time.clock()\n\tres = True\n\tprint(str(\"Time: \") + str((endTime - startTime)) + str(\" seconds\"))\n\tif (hasAnswer):\n\t\tprint(str(\"Desired answer:\"))\n\t\tprint(str(\"\\t\") + str(p3))\n\t\n\tprint(str(\"Your answer:\"))\n\tprint(str(\"\\t\") + str(answer))\n\tif (hasAnswer):\n\t\tres = answer == p3\n\t\n\tif (not res):\n\t\tprint(str(\"DOESN'T MATCH!!!!\"))\n\telif ((endTime - startTime) >= 2):\n\t\tprint(str(\"FAIL the timeout\"))\n\t\tres = False\n\telif (hasAnswer):\n\t\tprint(str(\"Match :-)\"))\n\telse:\n\t\tprint(str(\"OK, but is it right?\"))\n\t\n\tprint(str(\"\"))\n\treturn res\n\nall_right = True\ntests_disabled = False\n\n\n# ----- test 0 -----\ndisabled = False\np0 = (3,5,4,11)\np1 = (2,1,3,1)\np2 = 17\np3 = 3\nall_right = (disabled or KawigiEdit_RunTest(0, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 1 -----\ndisabled = False\np0 = (100,200,300)\np1 = (1,2,3)\np2 = 10\np3 = 0\nall_right = (disabled or KawigiEdit_RunTest(1, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 2 -----\ndisabled = False\np0 = (1,2,3,4)\np1 = (1,1,1,1)\np2 = 100\np3 = 4\nall_right = (disabled or KawigiEdit_RunTest(2, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 3 -----\ndisabled = False\np0 = (10,10,10)\np1 = (58,58,58)\np2 = 30\np3 = 3\nall_right = (disabled or KawigiEdit_RunTest(3, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 4 -----\ndisabled = False\np0 = (8,11,7,15,9,16,7,9)\np1 = (3,8,5,4,2,7,4,1)\np2 = 14\np3 = 1\nall_right = (disabled or KawigiEdit_RunTest(4, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\n# ----- test 5 -----\ndisabled = False\np0 = (5611,39996,20200,56574,81643,90131,33486,99568,48112,97168,5600,49145,73590,3979,94614)\np1 = (2916,53353,64924,86481,44803,61254,99393,5993,40781,2174,67458,74263,69710,40044,80853)\np2 = 302606\np3 = 8\nall_right = (disabled or KawigiEdit_RunTest(5, p0, p1, p2, True, p3) ) and all_right\ntests_disabled = tests_disabled or disabled\n# ------------------\n\nif (all_right):\n\tif (tests_disabled):\n\t\tprint(str(\"You're a stud (but some test cases were disabled)!\"))\n\telse:\n\t\tprint(str(\"You're a stud (at least on given cases)!\"))\n\t\nelse:\n\tprint(str(\"Some of the test cases had errors.\"))\n\n# PROBLEM STATEMENT\n# Gumi loves singing.\n# She knows N songs.\n# The songs are numbered 0 through N-1.\n# She now has some time and she would love to sing as many different songs as possible. \n# \n# You are given a tuple (integer) duration.\n# For each i, duration[i] is the duration of song i in Gumi's time units. \n# \n# Gumi finds it difficult to sing songs with quite different tones consecutively.\n# You are given a tuple (integer) tone with the following meaning:\n# If Gumi wants to sing song y immediately after song x, she will need to spend |tone[x]-tone[y]| units of time resting between the two songs.\n# (Here, || denotes absolute value.) \n# \n# You are also given an integer T.\n# Gumi has T units of time for singing.\n# She can start singing any song she knows immediately at the beginning of this time interval.\n# Compute the maximal number of different songs she can sing completely within the given time.\n# \n# DEFINITION\n# Class:GUMIAndSongsDiv2\n# Method:maxSongs\n# Parameters:tuple (integer), tuple (integer), integer\n# Returns:integer\n# Method signature:def maxSongs(self, duration, tone, T):\n# \n# \n# CONSTRAINTS\n# -duration and tone will each contain between 1 and 15 elements, inclusive.\n# -duration and tone will contain the same number of elements.\n# -Each element of duration will be between 1 and 100,000, inclusive.\n# -Each element of tone will be between 1 and 100,000, inclusive.\n# -T will be between 1 and 10,000,000, inclusive.\n# \n# \n# EXAMPLES\n# \n# 0)\n# {3, 5, 4, 11}\n# {2, 1, 3, 1}\n# 17\n# \n# Returns: 3\n# \n# There are four songs. \n# Two songs have tone 1 and their durations are 5 and 11, respectively.\n# One song has tone 2 and its duration is 3.\n# One song has tone 3 and its duration is 4.\n# Gumi has 17 units of time to sing. \n# \n# It is impossible for Gumi to sing all four songs she knows within the given time: even without the breaks the total length of all songs exceeds 17. \n# \n# Here is one way how she can sing three songs:\n# First, she sings song 0 in 3 units of time.\n# Second, she waits for |2-3|=1 unit of time and then sings song 2 in 4 units of time.\n# Finally, she waits for |3-1|=2 units of time and then sings song 1 in 5 units of time.\n# The total time spent is 3+1+4+2+5 = 15 units of time.\n# \n# \n# 1)\n# {100, 200, 300}\n# {1, 2, 3}\n# 10\n# \n# Returns: 0\n# \n# In this case, T is so small that she can't sing at all.\n# \n# 2)\n# {1, 2, 3, 4}\n# {1, 1, 1, 1}\n# 100\n# \n# Returns: 4\n# \n# There is plenty of time, so she can sing all 4 songs.\n# \n# \n# 3)\n# {10, 10, 10}\n# {58, 58, 58}\n# 30\n# \n# Returns: 3\n# \n# \n# \n# 4)\n# {8, 11, 7, 15, 9, 16, 7, 9}\n# {3, 8, 5, 4, 2, 7, 4, 1}\n# 14\n# \n# Returns: 1\n# \n# \n# \n# 5)\n# {5611,39996,20200,56574,81643,90131,33486,99568,48112,97168,5600,49145,73590,3979,94614}\n# {2916,53353,64924,86481,44803,61254,99393,5993,40781,2174,67458,74263,69710,40044,80853}\n# 302606\n# \n# Returns: 8\n# \n# \n# \n# END KAWIGIEDIT TESTING\n#Powered by KawigiEdit-pf 2.3.0!\n","sub_path":"topcoder/GUMIAndSongsDiv2.py","file_name":"GUMIAndSongsDiv2.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"493919731","text":"from django.conf.urls import patterns, include, url\nfrom views import *\nfrom preview import views\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n (r'^', include('catolog.urls')),\n ('^many/$', many ), \n ('^boot/$', boot ),\n ('^jeka_start/$', jeka_start),\n ('^novigation/$', novigation),\n ('^carusel/$', carusel),\n ('^shadow/$', shadow),\n ('^extend/$', extend),\n ('^base/$', base),\n (r'^catolog/$', views.home),\n# (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root' : 'home/lpkn/tatu/static'})\n # Examples:\n # url(r'^$', 'tatu.views.home', name='home'),\n # url(r'^tatu/', include('tatu.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n\n","sub_path":"tatu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"301954918","text":"import numpy as np\n\ndef match_labels(ys, iou_threshold=0):\n \"\"\"\n Matches object ids in a list of label images based on a matching criterion.\n\n For i=0..len(ys)-1 consecutively matches ys[i+1] with ys[i], \n matching objects retain their id, non matched objects will be assigned a new id \n\n Example\n -------\n \n import numpy as np\n from stardist.data import test_image_nuclei_2d\n from stardist.matching import match_labels\n\n _y = test_image_nuclei_2d(return_mask=True)[1]\n labels = np.stack([_y, 2*np.roll(_y,10)], axis=0)\n\n labels_new = match_labels(labels)\n\n Parameters\n ----------\n ys : np.ndarray, tuple of np.ndarray\n list/array of integer labels (2D or 3D)\n \"\"\"\n \n from stardist.matching import matching\n from skimage.measure import regionprops\n \n ys = np.asarray(ys)\n if not ys.ndim in (3,4):\n raise ValueError('label image y should be 3 or 4 dimensional!')\n\n def _match_single(x, y):\n res = matching(x,y, report_matches=True, thresh=0)\n\n pairs = tuple(p for p,s in zip(res.matched_pairs, res.matched_scores) if s>= iou_threshold)\n map_dict = dict((i2,i1) for i1,i2 in pairs)\n\n y2 = np.zeros_like(y)\n y_labels = set(np.unique(y)) - {0}\n\n # labels that can be used for non-matched objects\n label_reservoir = list(set(np.arange(1,len(y_labels)+1)) - set(map_dict.values()))\n for r in regionprops(y):\n m = (y[r.slice] == r.label)\n if r.label in map_dict:\n y2[r.slice][m] = map_dict[r.label]\n else:\n y2[r.slice][m] = label_reservoir.pop(0)\n\n return y2\n\n ys_new = ys.copy()\n\n for i in range(len(ys)-1):\n ys_new[i+1] = _match_single(ys_new[i], ys[i+1])\n\n return ys_new\n\n \n \n","sub_path":"stardist_napari/match_labels.py","file_name":"match_labels.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"283819115","text":"import cv2, base64, json, os, requests\nimport numpy as np\nfrom fileTools import *\nfrom trainTools import *\nfrom imgTools import *\nfrom eightPuzzle import *\nfrom interface import *\n\nteamInformation = {\"teamid\":40,\"token\":\"4ffaa044-e49a-4b85-b667-39076c7f9e90\"}\nheaders = {'content-type': \"application/json\"}\ncharDict = readJsonFile('./record/charDict.json')\nnoDict = readJsonFile('./record/noDict.json')\nblackPictureNo = readJsonFile('./record/BlackPictureNo.json')\nwith np.load('./record/knnTrainData.npz') as data:\n trainData = data['trainData']\n responses = data['responses']\nknn = cv2.ml.KNearest_create()\nknn.train(trainData,cv2.ml.ROW_SAMPLE,responses)\n\ndef solveProblem(challenge_uuid):\n startUrl = 'http://47.102.118.1:8089/api/challenge/start/' + challenge_uuid\n submitUrl = 'http://47.102.118.1:8089/api/challenge/submit'\n submitData = {\n \"uuid\": \"\",\n \"teamid\": teamInformation[\"teamid\"],\n \"token\": teamInformation[\"token\"],\n \"answer\": {\n \"operations\": \"\",\n \"swap\": []\n }\n }\n problem = requests.post(startUrl,data=json.dumps(teamInformation),headers = headers)\n problemJson = problem.json()\n writeBase64Image('./problem.jpg',problemJson['data']['img'])\n problemImage = cv2.imread('./problem.jpg')\n cutImage(problemImage,'./target')\n\n problemWhiteImageNo = -1\n problemBlackImageNo = []\n match = {}\n for i in range(1,10):\n image = cv2.imread('./target'+'/'+str(i)+'.jpg')\n corners = getImageTrainData(image)\n if(corners.size < 1):\n if(isWhiteImage(image)):\n problemWhiteImageNo = i\n else:\n problemBlackImageNo.append(i)\n else:\n ret,results,neighbours,dist = knn.findNearest(corners,k=1)\n result = getClosestResult(results)\n match[i] = noDict[str(result)]\n\n cur = np.full((3,3),0)\n goalChar = ''\n matchNo = []\n notMatchNo = []\n location = ([-1,-1],[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2])\n\n for value in match.values():\n goalChar += value[0]\n matchNo.append(int(value[1]))\n for i in range(1,10):\n if i not in matchNo:\n notMatchNo.append(i)\n notMatchCnt = len(notMatchNo)\n\n for i in range(1,10):\n if i not in match.keys():\n continue\n x,y = location[i]\n cur[x,y] = int(match[i][1])\n wx,wy = location[problemWhiteImageNo]\n if(goalChar[0] != 'F'):\n if(notMatchCnt == 1):\n whiteNo = notMatchNo[0]\n goal = getGoal(whiteNo)\n e = eightDigitalCode(wx,wy,cur,goal)\n elif(notMatchCnt == 2):\n bNo = int(blackPictureNo[goalChar[0]][0])\n bx,by = location[int(problemBlackImageNo[0])]\n cur[bx,by] = bNo\n for no in notMatchNo:\n if (no != bNo):\n whiteNo = no\n break\n goal = getGoal(whiteNo)\n e = eightDigitalCode(wx,wy,cur,goal)\n else:\n print('Failed!')\n\n operations,swap = e.solve(problemJson['data']['step'],problemJson['data']['swap'])\n submitData['uuid'] = problemJson['uuid']\n submitData['answer']['operations'] = operations\n if(swap[0] != 0):\n submitData['answer']['swap'] = swap\n ansPost = requests.post(submitUrl ,data = json.dumps(submitData),headers = headers)\n # 测试使用\n if(ansPost): \n content = ansPost.json() \n print('\\n')\n print(content)\n print('\\n')\n print(submitData)\n# print('\\nnotMatchCnt = ',notMatchCnt)\n# print('goalChar = ',goalChar)\n## print('\\n')\n\n # for key,value in match.items():\n # print(str(key) + ' = ' + value)\n # print(e.status())\n # print('\\n')\n # print('step = ',problemJson['data']['step'])\n # print('swap = ',problemJson['data']['swap'])\n # print('uuid = ',problemJson['uuid'])\n # print('\\n')\n\n# print(json.dumps(submitData))\n#\n# with open('./test/time.txt','r') as fp:\n# tstr = fp.read()\n# t = int(tstr)\n# writeBase64Image('./test/'+str(t)+'.jpg',problemJson['data']['img'])\n# saveDictFile(problemJson,'./test/'+str(t)+'.json')\n# saveDictFile(content,'./test/'+str(t)+'ans.json')\n# with open('./test/time.txt','w') as fp:\n# fp.write(str(t+1)) \ndef solveAll():\n probInfo = getUnfinishedProblem(40)\n for info in probInfo:\n print('\\nauthor = ',info['author'])\n solveProblem(info['uuid'])\n\ndef solveSomeProblem(cnt):\n n = 0\n probInfo = getUnfinishedProblem(40)\n for info in probInfo:\n if(n>=cnt):\n break;\n print('\\nauthor = ',info['author'])\n solveProblem(info['uuid'])\n n += 1\nif __name__ == '__main__':\n #solveSomeProblem(10)\n solveAll()","sub_path":"aiBattleSolveAll.py","file_name":"aiBattleSolveAll.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"149972225","text":"import os\n#os.environ['R_HOME']=r'C:\\Users\\MaineD1\\AppData\\Local\\R\\R-3.5.0'\n\nfrom re import findall\n#imports for plotting\nimport math, datetime\nimport warnings\nimport readLogsOld as readLogs\nimport tableClasses\n\ntable_data = tableClasses.TableMeta()\nLOG_DIRECTORY = 'logs/'\n\ndef readlogs(directory):\n log_files = os.listdir(directory)\n #build table data\n for log_file_name in log_files: \n log_file = open(directory + log_file_name)\n log_contents = log_file.read()\n table_properties = readLogs.readTables(log_contents)\n table_data.addTableData(log_file_name, table_properties)\n\n #build linkage data\n for log_file_name in log_files: \n log_file = open(directory + log_file_name)\n log_contents = log_file.read()\n table_links = readLogs.readLinks(log_contents)\n table_data.addLinkData(log_file_name, table_links)\n\n\nreadlogs(LOG_DIRECTORY)\nreadlogs('wobLog/')\ndata = table_data.getJSON()\ndata = \"var data = \" + str(data)\n\nfile = open(\"data.js\", \"w\")\nfile.write(data)\n\n\n\n","sub_path":"exportData.py","file_name":"exportData.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"645947841","text":"from threading import Thread\nimport websocket \nimport json\nimport random\nfrom time import sleep\n\nclass Bot(Thread):\n\n dir_table = {\n \"north\" : \"n\",\n \"north_east\" : \"ne\",\n \"east\" : \"e\",\n \"south_east\" : \"se\",\n \"south\" : \"s\",\n \"south_west\" : \"sw\",\n \"west\" : \"w\",\n \"north_west\" : \"nw\"\n }\n\n def __init__(self, ip):\n Thread.__init__(self)\n\n self.socket = None\n self.addr = \"ws://\" + ip + \":8080/socket\"\n\n def connect(self):\n '''\n '''\n try:\n self.socket = websocket.create_connection(self.addr)\n except ConnectionRefusedError:\n print(\"[!] websocket connection error\")\n exit(1)\n\n def send(self, msg):\n '''\n '''\n assert(self.socket)\n\n if msg is None:\n return\n\n d = {}\n d[\"body\"] = msg\n j = json.dumps(d)\n\n try:\n self.socket.send(j)\n except websocket.WebSocketConnectionClosedException:\n print(\"[!] send fail - websocket closed\")\n exit(1)\n except KeyboardInterrupt:\n exit(1)\n\n def recv(self):\n '''\n '''\n assert(self.socket)\n\n try:\n raw = self.socket.recv()\n except websocket.WebSocketConnectionClosedException:\n print(\"[!] send failure - websocket closed\")\n exit(1)\n except KeyboardInterrupt:\n exit(1)\n \n return json.loads(raw)[\"body\"]\n\n def parse(self, msg):\n if msg == \"What is your name?\":\n return \"jon\"\n elif msg == \"What is the password?\":\n return \"jon\"\n elif msg == \"Authenticated\":\n pass\n elif msg and msg[0] == \"{\":\n msg = msg.replace(\"'\", \"\\\"\")\n return self.direction(list(json.loads(msg)))\n\n def direction(self, l):\n rand = random.randint(0, len(l) - 1)\n\n return Bot.dir_table[l[rand]]\n\n def run(self):\n '''\n '''\n self.connect()\n\n for i in range(0, 20):\n msg = self.recv()\n\n sleep(1)\n\n self.send(self.parse(msg))\n\n self.socket.close()\n","sub_path":"tools/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"488714608","text":"import wx\nimport wx.xrc\n\nfrom db.get_classes import getClassNamesWithForm\nfrom db.get_subjects import getOptionalSubjects, getNumberOfCompulsorySubjects\nfrom db.subject_selection import *\nfrom db.login import getSchoolDetails\n\n###########################################################################\n# Class SubjectSelection\n###########################################################################\n\n\nclass SubjectSelection(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n self.m_staticText98 = wx.StaticText(self, wx.ID_ANY, u\"Subject Selection\", wx.DefaultPosition, wx.DefaultSize,\n wx.ALIGN_CENTRE)\n self.m_staticText98.Wrap(-1)\n self.m_staticText98.SetFont(wx.Font(16, 70, 90, 92, False, wx.EmptyString))\n\n container.Add(self.m_staticText98, 0, wx.EXPAND | wx.TOP, 25)\n\n horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n left_sizer = wx.BoxSizer(wx.VERTICAL)\n\n form_sizer = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u\"Fill in the following details\"), wx.VERTICAL)\n\n self.class_label = wx.StaticText(form_sizer.GetStaticBox(), wx.ID_ANY, u\"Select Class\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.class_label.Wrap(-1)\n form_sizer.Add(self.class_label, 0, wx.ALL, 10)\n\n self.classes = getClassNamesWithForm()\n\n class_nameChoices = self.classes['names']\n\n self.class_name = wx.ComboBox(form_sizer.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, class_nameChoices, wx.CB_READONLY)\n form_sizer.Add(self.class_name, 0, wx.ALL | wx.EXPAND, 10)\n\n self.subject_label = wx.StaticText(form_sizer.GetStaticBox(), wx.ID_ANY, u\"Select Subject\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.subject_label.Wrap(-1)\n form_sizer.Add(self.subject_label, 0, wx.ALL, 10)\n\n self.subjects = getOptionalSubjects()\n\n subjectChoices = self.subjects['names']\n self.subject = wx.ComboBox(form_sizer.GetStaticBox(), wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, subjectChoices, wx.CB_READONLY)\n form_sizer.Add(self.subject, 0, wx.ALL | wx.EXPAND, 10)\n\n btns_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.cancel_button = wx.Button(form_sizer.GetStaticBox(), wx.ID_ANY, u\"Cancel\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n btns_sizer.Add(self.cancel_button, 0, wx.TOP, 10)\n\n self.get_list_btn = wx.Button(form_sizer.GetStaticBox(), wx.ID_ANY, u\"Get Student List\", wx.DefaultPosition,\n wx.DefaultSize, 0)\n btns_sizer.Add(self.get_list_btn, 0, wx.TOP, 10)\n\n form_sizer.Add(btns_sizer, 1, wx.ALL | wx.EXPAND, 10)\n\n left_sizer.Add(form_sizer, 1, wx.LEFT | wx.TOP | wx.RIGHT | wx.EXPAND, 30)\n\n horizontal_sizer.Add(left_sizer, 0, wx.ALL | wx.EXPAND, 5)\n\n right_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n #\n #\n # ADD SELECTION PANEL\n self.selection_panel_added = 0\n\n self.selection_sizer = wx.BoxSizer(wx.VERTICAL)\n\n sample_data = {\n \"class_id\": 0,\n \"class_name\": \"\",\n \"subject_id\": 0,\n \"subject_name\": \"\",\n }\n\n self.selection_panel = SelectionPanel(self, [], sample_data)\n self.selection_panel.Hide()\n\n self.selection_sizer.Add(self.selection_panel, 1, wx.ALL, 5)\n\n right_sizer.Add(self.selection_sizer, 1, wx.EXPAND, 5)\n #\n #\n # ------------------------------------------------------\n\n #\n #\n # ADD PREVIEW PANEL\n self.preview_sizer = wx.BoxSizer(wx.VERTICAL)\n\n self.preview_panel = PreviewPanel(self, [], sample_data)\n self.preview_panel.Hide()\n\n self.preview_sizer.Add(self.preview_panel, 1, wx.ALL, 5)\n\n right_sizer.Add(self.preview_sizer, 1, wx.EXPAND, 5)\n #\n #\n # ------------------------------------------------------\n\n #\n horizontal_sizer.Add(right_sizer, 1, wx.EXPAND, 5)\n\n container.Add(horizontal_sizer, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n # Connect Events\n self.class_name.Bind(wx.EVT_COMBOBOX, self.classChanged)\n self.subject.Bind(wx.EVT_COMBOBOX, self.subjectChanged)\n self.cancel_button.Bind(wx.EVT_BUTTON, self.cancelSubjectSelection)\n self.get_list_btn.Bind(wx.EVT_BUTTON, self.getStudentList)\n\n def __del__(self):\n pass\n\n # Virtual event handlers, overide them in your derived class\n def classChanged(self, event): # To reload student list if class is changed when a list has already been loaded\n subjectIndex = self.subject.GetCurrentSelection()\n if subjectIndex != -1:\n self.getStudentList(\"\")\n\n self.Layout()\n\n # -------------------------------------\n def subjectChanged(self, event):\n classIndex = self.class_name.GetCurrentSelection()\n if classIndex != -1: # To reload student list if subject is changed when a list has already been loaded\n self.getStudentList(\"\")\n\n self.Layout()\n\n # -------------------------------------\n def cancelSubjectSelection(self, event):\n self.class_name.SetSelection(-1)\n self.subject.SetSelection(-1)\n\n self.selection_panel.Hide()\n self.preview_panel.Hide()\n\n # -------------------------------------\n def getStudentList(self, event):\n classIndex = self.class_name.GetCurrentSelection()\n subjectIndex = self.subject.GetCurrentSelection()\n\n error = \"\"\n\n if classIndex == -1:\n error = error + \"The class field is required.\\n\"\n if subjectIndex == -1:\n error = error + \"The subject field is required.\\n\"\n\n if error:\n dlg = wx.MessageDialog(None, error, 'Validation Error', wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n\n else:\n class_id = self.classes['ids'][classIndex]\n form = self.classes['forms'][classIndex]\n class_name = self.class_name.GetStringSelection()\n subject_id = self.subjects['ids'][subjectIndex]\n subject_name = self.subject.GetStringSelection()\n\n students = getStudentList(class_id, subject_id)\n preview_students = students['students_present']\n selection_students = students['student_list']\n\n # Calculate the limit of subject choices\n schDets = getSchoolDetails()\n\n # Get number of compulsory subjects in system\n compulsory_subjects = getNumberOfCompulsorySubjects(form)\n\n # Subjects must be 8 for upper forms, for lower forms we get from the system\n if int(form) < 3:\n # Get number of subjects done by lower forms\n subjects_lower_forms = schDets['lower_subjects']\n subject_limit = int(subjects_lower_forms) - compulsory_subjects\n\n else:\n subject_limit = 8 - int(compulsory_subjects)\n\n data = {\n \"class_id\": class_id,\n \"class_name\": class_name,\n \"subject_id\": subject_id,\n \"subject_name\": subject_name,\n \"subject_limit\": subject_limit\n }\n\n self.selection_panel.Hide()\n self.selection_panel = SelectionPanel(self, selection_students, data)\n self.selection_panel.Show()\n\n self.selection_sizer.Add(self.selection_panel, 1, wx.ALL, 5)\n\n self.Layout()\n\n #\n #\n\n self.preview_panel.Hide()\n self.preview_panel = PreviewPanel(self, preview_students, data)\n self.preview_panel.Show()\n\n self.preview_sizer.Add(self.preview_panel, 1, wx.ALL, 5)\n\n self.Layout()\n\n # -------------------------------------\n def reRenderPreviewPanel(self, data):\n\n if data in self.preview_panel.preview_students: # If it's there remove it\n self.preview_panel.preview_students.remove(data)\n else:\n self.preview_panel.preview_students.append(data) # If not it's added\n\n # Re-render the panel\n self.preview_panel.Hide()\n self.preview_panel = PreviewPanel(self, self.preview_panel.preview_students, self.preview_panel.data)\n self.preview_panel.Show()\n\n self.preview_sizer.Add(self.preview_panel, 1, wx.ALL, 5)\n\n self.Layout()\n\n\n#\n#\nclass SelectionPanel(wx.Panel):\n\n def __init__(self, parent, students, data):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n\n self.parent = parent\n self.students = students\n self.data = data\n\n self.subject_id = self.data['subject_id']\n\n self.title = \"Form \" + self.data['class_name'] + \" Tick student to add to the \" + self.data['subject_name'] + \" option\"\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n titles_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.spacer = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.spacer.Wrap(-1)\n titles_sizer.Add(self.spacer, 0, wx.ALL, 5)\n\n self.title_text = wx.StaticText(self, wx.ID_ANY, self.title, wx.DefaultPosition, wx.DefaultSize, 0)\n self.title_text.Wrap(-1)\n self.title_text.SetFont(wx.Font(10, 70, 90, 92, False, wx.EmptyString))\n titles_sizer.Add(self.title_text, 0, wx.ALL, 5)\n\n container.Add(titles_sizer, 0, wx.EXPAND, 5)\n\n #\n #\n #\n\n student_list = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, wx.EmptyString), wx.VERTICAL)\n\n self.student_fields = {}\n for key, value in enumerate(self.students): # adding student list dynamically\n self.student_fields[str(value['user_id'])] = OneStudent(self, value['student_name'], value['user_id'], value['subject_ticked'], value['subjects'])\n student_list.Add(self.student_fields[str(value['user_id'])], 0, wx.EXPAND, 5)\n\n self.buttons = SaveSubjectsChosenButtons(self)\n student_list.Add(self.buttons, 1, wx.EXPAND, 5)\n\n container.Add(student_list, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n def __del__(self):\n pass\n\n def callRenderPreviewPanel(self, data):\n self.parent.reRenderPreviewPanel(data)\n\n def cancelChosenSubjects(self, event):\n self.parent.cancelSubjectSelection(\"\")\n\n def saveChosenSubjects(self, event):\n student_data = self.student_fields\n\n subject_id = self.subject_id\n\n stud_subject_data = []\n\n for (key, value) in student_data.iteritems():\n\n # Check if subjects had been chosen before, ie the subjects array is not empty\n if value.subjects != \"\":\n\n # If subject chosen is already saved in db so it's already ticked\n if value.subjects.count(str(subject_id)) != 0:\n\n # check if subject has been de-selected\n if not value.selected.GetValue(): # Subject has been de-selected\n # print \"remove subject - \" + value.student_name\n subjects_taken = value.subjects[:]\n\n subjects_taken.remove(str(subject_id))\n\n data = {\n \"user_id\": key,\n \"subject_taken\": subjects_taken\n }\n\n stud_subject_data.append(data)\n\n else: # if subject is new to subjects array, ie needs to be added\n\n # check that all slots aren't filled, ie if the student needs to drop one first\n if len(value.subjects) < 4:\n # print \"add to array - \" + value.student_name\n\n # Add to array if subject got ticked ie value.selected == True\n if value.selected.GetValue():\n subjects_taken = value.subjects[:] # Copy value.subjects to new array\n subjects_taken.append(subject_id)\n\n data = {\n \"user_id\": key,\n \"subject_taken\": subjects_taken\n }\n\n stud_subject_data.append(data)\n else:\n # print \"add first subject - \" + value.student_name\n\n # Add first subject if it got ticked ie value.selected == True\n if value.selected.GetValue():\n\n subjects_taken = [subject_id]\n\n data = {\n \"user_id\": key,\n \"subject_taken\": subjects_taken\n }\n\n stud_subject_data.append(data)\n\n # Check if there's data to be updated\n if stud_subject_data:\n dlg = wx.MessageDialog(None, \"Save changes?\", 'Confirm Action.',\n wx.YES_NO | wx.ICON_INFORMATION)\n retCode = dlg.ShowModal()\n\n if retCode == wx.ID_YES:\n if chooseSubjects(stud_subject_data):\n dlg = wx.MessageDialog(None, \"Students' subjects updated successfully.\",\n 'Success Message.',\n wx.OK | wx.ICON_INFORMATION)\n dlg.ShowModal()\n dlg.Destroy()\n self.cancelChosenSubjects(\"\")\n else:\n dlg = wx.MessageDialog(None, \"Some students' subjects may not have been saved. Try again later.\",\n 'Warning Message.',\n wx.OK | wx.ICON_WARNING)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n dlg.Close()\n dlg.Destroy()\n\n\n#\n#\n# Called for every student in the selection list. == one list item\nclass OneStudent(wx.Panel):\n\n def __init__(self, parent, student_name, user_id, subject_ticked, subjects):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n\n self.parent = parent\n self.student_name = student_name\n self.user_id = user_id\n self.subject_ticked = subject_ticked\n self.subjects = subjects\n\n student_name_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.selected = wx.CheckBox(self, wx.ID_ANY, \" \" + self.student_name, wx.DefaultPosition, wx.DefaultSize, 0)\n self.selected.SetValue(self.subject_ticked)\n student_name_sizer.Add(self.selected, 0, wx.ALL, 5)\n\n self.SetSizer(student_name_sizer)\n self.Layout()\n\n self.selected.Bind(wx.EVT_CHECKBOX, self.checkboxClicked)\n\n def __del__(self):\n pass\n\n # If there's no slot to add subject, and the subject in question isn't in array so one needs to be dropped first\n def checkboxClicked(self, event):\n if len(self.subjects) == self.parent.data['subject_limit'] and self.subjects.count(str(self.parent.subject_id)) == 0:\n dlg = wx.MessageDialog(None, \"Maximum number of subjects chosen for student, drop some to continue.\",\n 'Error Message.',\n wx.OK | wx.ICON_ERROR)\n dlg.ShowModal()\n dlg.Destroy()\n\n self.selected.SetValue(False)\n else:\n \"\"\"Add/remove from preview panel\"\"\"\n data = {\n \"user_id\": self.user_id,\n \"student_name\": self.student_name\n }\n\n self.parent.callRenderPreviewPanel(data)\n\n\n#\n#\nclass SaveSubjectsChosenButtons(wx.Panel):\n\n def __init__(self, parent):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n self.parent = parent\n\n btns_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.left_spacer = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.left_spacer.Wrap(-1)\n btns_sizer.Add(self.left_spacer, 4, wx.ALL, 5)\n\n self.cancel_btn = wx.Button(self, wx.ID_ANY, u\"Cancel\", wx.DefaultPosition, wx.DefaultSize,\n 0)\n btns_sizer.Add(self.cancel_btn, 0, wx.ALL, 5)\n\n self.save_button = wx.Button(self, wx.ID_ANY, u\"Save\", wx.DefaultPosition, wx.DefaultSize, 0)\n btns_sizer.Add(self.save_button, 0, wx.BOTTOM | wx.LEFT | wx.TOP, 5)\n\n self.right_spacer = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition,\n wx.DefaultSize, 0)\n self.right_spacer.Wrap(-1)\n btns_sizer.Add(self.right_spacer, 1, wx.ALL, 5)\n\n self.SetSizer(btns_sizer)\n self.Layout()\n\n # Connect Events\n self.cancel_btn.Bind(wx.EVT_BUTTON, self.parent.cancelChosenSubjects)\n self.save_button.Bind(wx.EVT_BUTTON, self.parent.saveChosenSubjects)\n\n\n#\n#\nclass PreviewPanel(wx.Panel):\n def __init__(self, parent, preview_students, data):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n\n self.preview_students = preview_students\n self.data = data\n\n self.subject_id = self.data['subject_id']\n\n self.title = \"Form \" + self.data['class_name'] + \" \" + self.data['subject_name'] + \" option students\"\n\n container = wx.BoxSizer(wx.VERTICAL)\n\n titles_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.spacer = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.spacer.Wrap(-1)\n titles_sizer.Add(self.spacer, 1, wx.ALL, 5)\n\n self.title_text = wx.StaticText(self, wx.ID_ANY, self.title, wx.DefaultPosition, wx.DefaultSize, 0)\n self.title_text.Wrap(-1)\n self.title_text.SetFont(wx.Font(10, 70, 90, 92, False, wx.EmptyString))\n titles_sizer.Add(self.title_text, 1, wx.ALL, 5)\n\n self.spacer = wx.StaticText(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)\n self.spacer.Wrap(-1)\n titles_sizer.Add(self.spacer, 1, wx.ALL, 5)\n\n container.Add(titles_sizer, 0, wx.EXPAND, 5)\n\n #\n #\n #\n\n student_list = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, wx.EmptyString), wx.VERTICAL)\n\n self.preview_student_fields = {}\n\n count = 1\n\n for key, value in enumerate(self.preview_students): # adding student list dynamically\n self.preview_student_fields[str(value['user_id'])] = OnePreviewStudent(self, str(count) + \". \" + value['student_name'])\n\n student_list.Add(self.preview_student_fields[str(value['user_id'])], 0, wx.EXPAND, 5)\n\n count = count + 1\n\n # self.buttons = SaveSubjectsChosenButtons(self)\n # student_list.Add(self.buttons, 1, wx.EXPAND, 5)\n\n container.Add(student_list, 1, wx.EXPAND, 5)\n\n self.SetSizer(container)\n self.Layout()\n\n def __del__(self):\n pass\n\n\n#\n# Called for every student in the preview list. == one list item\nclass OnePreviewStudent(wx.Panel):\n\n def __init__(self, parent, student_name):\n wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,\n style=wx.TAB_TRAVERSAL)\n\n self.parent = parent\n self.student_name = student_name\n\n student_name_sizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.student_text = wx.StaticText(self, wx.ID_ANY, self.student_name, wx.DefaultPosition, wx.DefaultSize, 0)\n self.student_text.Wrap(-1)\n student_name_sizer.Add(self.student_text, 0, wx.ALL, 5)\n\n self.SetSizer(student_name_sizer)\n self.Layout()\n\n def __del__(self):\n pass","sub_path":"SubjectSelection.py","file_name":"SubjectSelection.py","file_ext":"py","file_size_in_byte":20481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"636610059","text":"# -*- coding: utf-8 -*-\nimport sys\nsys.path.append(\"../..\")\nimport game\n\ncoef = [1]\ncaseVal = [[100, -20, 10, 5, 5, 10, -20, 100],\n [-20, -50, -2, -2, -2, -2, -50, -20],\n [10, -2, -1, -1, -1, -1, -2, 10],\n [5, -2, -1, -1, -1, -1, -2, 5],\n [5, -2, -1, -1, -1, -1, -2, 5],\n [10, -2, -1, -1, -1, -1, -2, 10],\n [-20, -50, -2, -2, -2, -2, -50, -20],\n [100, -20, 10, 5, 5, 10, -20, 100]]\ndepth = 1\nMAX=5000\nMIN=-5000\nn=0\n\ndef saisieCoup(jeu):\n \"\"\" jeu -> coup\n retourne le coup choisi par décision\n \"\"\"\n if (len(game.getCoupsValides(jeu))==1):\n return game.getCoupsValides(jeu)[0]\n else:\n return decision(jeu)\n\ndef decision(jeu):\n \"\"\" jeu -> coup\n retourne le coup qui a le score le plus élevé pour une itération du jeu\n Hypothèse: si tous les coups on le même score, alors on joue le premier coup valide\n \"\"\"\n listeCoups = game.getCoupsValides(jeu)\n maxVal = MIN\n maxCoup = None\n alpha=MIN\n beta=MAX\n for c in listeCoups:\n val = estimation(jeu, c, depth-1, jeu[1],alpha,beta)\n if(val>maxVal):\n maxVal = val\n maxCoup = c\n alpha=max(maxVal,alpha)\n return maxCoup\n\ndef estimation(jeu, coup, profondeur, joueur, alpha, beta):\n global n\n n+=1\n saveJeu = game.getCopieJeu(jeu)\n game.joueCoup(saveJeu, coup)\n if(game.finJeu(saveJeu)):\n return getFinPartie(saveJeu,joueur)\n if (profondeur == 0):\n return evaluation(saveJeu,joueur)\n listeCoups = game.getCoupsValides(saveJeu)\n if(joueur == saveJeu[1]):\n #max\n maxVal = MIN\n for c in listeCoups:\n val = estimation(saveJeu, c, profondeur-1, joueur,alpha,beta)\n maxVal = max (val, maxVal)\n if(beta <= maxVal):\n return maxVal\n alpha = max(alpha,maxVal)\n return maxVal\n else:\n #min\n minVal = MAX\n for c in listeCoups:\n val = estimation(saveJeu, c, profondeur-1, joueur,alpha,beta)\n minVal= min (val, minVal)\n if(alpha >= minVal):\n return minVal\n beta = min(beta,minVal)\n return minVal\n\n\ndef dot(l1,l2):\n res=0\n for i in range(len(l1)):\n res+=l1[i]*l2[i]\n return res\n\ndef evals(jeu, joueur):\n return [getCoupsOfferts(jeu,joueur)]\n\ndef evaluation(jeu, joueur):\n return dot(evals(jeu,joueur),coef)\n\n\ndef getCoupsOfferts(jeu,joueur):\n #on triche si c'est pas a lui de jouer\n #du coup pas sur que la fonction soit utile\n #quand c'est pas a l'adversaire de jouer\n jeu[1]=joueur%2 +1\n res=0\n l=game.getCoupsValides(jeu)\n jeu[1]=joueur\n nbCoup = len(l)\n if(nbCoup==0):\n #s'il n'a pas de coup possible on renvoie le score de fin de game\n #peut etre que c'est pareil si on renvoie 0\n return getFinPartie(jeu, joueur)\n for c in l:\n #on evalue la valeur de ses coups\n res -= caseVal[c[0]][c[1]]\n #on renvoie la valeur d'un coup moyen\n #peut etre pas ouf a tester avec la valeur max\n return res*1.0/nbCoup\n\n\ndef getFinPartie(jeu, joueur):\n g=game.getGagnant(jeu)\n if(g==joueur):\n return 1000\n elif (g==0):\n return -100\n else:\n return -1000\n\n\n# def getValCase(jeu,joueur):\n# res=0\n# for i in range(8):\n# for j in range(8):\n# if(jeu[0][i][j]==joueur):\n# res+=caseVal[i][j]\n# elif(jeu[0][i][j]==joueur%2+1):\n# res-=caseVal[i][j]\n# return res\n","sub_path":"2I013 PYTON AI/Othello/Joueurs/joueur_alphabeta_tricheP1.py","file_name":"joueur_alphabeta_tricheP1.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"193428873","text":"def solution(A):\n N = len(A)\n sum1 = 0\n sum2 = sum(A)\n #print(\"the sum of the array is: \" + str(sum2))\n min_diff = abs(sum(A[1:N]) - A[0])\n #print(\"the first difference is: \" + str(min_diff))\n for i in range(N-1): # 0 < P < N\n #print(str(i))\n sum1 += A[i]\n sum2 -= A[i]\n #print(\"first sum is: \" + str(sum1))\n #print(\"second sum is: \" + str(sum2))\n if abs(sum2 - sum1) < min_diff:\n min_diff = abs(sum2 - sum1)\n #print(\"the new min_diff is: \" + str(min_diff))\n return min_diff\n","sub_path":"Codility/tape_equilibrium.py","file_name":"tape_equilibrium.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"600015777","text":"import urllib\nfrom urllib import request\nfrom bs4 import BeautifulSoup\nimport re\n\n#Based heavily on http://stackoverflow.com/questions/18916616/get-first-link-of-wikipedia-article-using-wikipedia-api\n\nbase = 'http://starwars.wikia.com'\n\ndef valid_link(ref, paragraph):\n if '.ogg' in ref:\n return False\n if ref[0] == '#':\n return False\n if 'Help:' in ref:\n return False\n if 'Wikipedia:' in ref:\n return False\n if ref.startswith('http'):\n return False\n if 'For other uses, see' in paragraph:\n return False\n if 'This article is about' in paragraph:\n return False\n if 'id=\"coordinates\"' in paragraph:\n return False\n for paren in re.findall(r'\\([^)]*\\)', paragraph):\n if ref in paren:\n return False\n #print(base + ref)\n return True\n\n\ndef valid_paragraph(paragraph):\n name = paragraph.name\n return name in ['p', 'ul']\n\ndef get_first_link(wikipage):\n #print('Page: ', base + wikipage)\n req = request.Request(base + wikipage, headers={'User-Agent' : 'Python Browser'})\n try:\n page = request.urlopen(req)\n except urllib.error.HTTPError as e:\n print(\"ERRROROROROROR\")\n print(e)\n print(req.get_full_url())\n print(\"ERRROROROROROR\")\n return False\n data = page.read()\n soup = BeautifulSoup(data)\n content = soup.find(id='mw-content-text')\n for paragraph in content.find_all(valid_paragraph, recursive=False):\n #print(paragraph.prettify())\n for link in paragraph.find_all('a'):\n ref = link.get('href')\n print(ref)\n if valid_link(str(ref), str(paragraph)):\n return link\n print(soup.prettify())\n #print(soup)\n return False\n\ndef get_random():\n req = request.Request(base + '/wiki/Special:Random', headers={'User-Agent' : 'Python Browser'})\n page = request.urlopen(req)\n url = page.geturl()\n url = url[len(base):]\n print(base + url)\n return url\n\ndef main():\n #visited = ['/wiki/New_Mexico_Institute_of_Mining_and_Technology']\n #visited = [get_random()]\n for visited in [get_random() for x in range(1)]:\n #visited = ['/wiki/' + visited]\n visited = [visited]\n while True:\n next_link = get_first_link(visited[-1])\n if next_link is False:\n print('Broke after {}.'.format(visited[-1]))\n break\n next_link = next_link.get('href')\n if 'Philosophy' in next_link:\n print('{} reached Philosophy in {} jumps.'.format(visited[0], len(visited)))\n break\n elif next_link in visited:\n print('Cycled back to {} after {} jumps.'.format(next_link, len(visited)))\n break\n elif next_link is False:\n print('Found no link in {}.'.format(visited[-1]))\n else:\n visited.append(next_link)\n print(base + next_link)\n #print(visited)\n\n\nif __name__ == '__main__':\n main()","sub_path":"labs/attic/scraping/wookieclicker_plus.py","file_name":"wookieclicker_plus.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"532278427","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\User\\Documents\\GitHub\\fourMs\\MGT-python\\musicalgestures\\_videoadjust.py\n# Compiled at: 2020-04-26 14:44:11\n# Size of source mod 2**32: 5172 bytes\nimport numpy as np, cv2\nfrom musicalgestures._utils import scale_num, scale_array, MgProgressbar\n\ndef mg_contrast_brightness(of, fex, vidcap, fps, length, width, height, contrast, brightness):\n \"\"\"\n Applies contrast and brightness to a video.\n\n Parameters\n ----------\n - of : str\n\n 'Only filename' without extension (but with path to the file).\n - fex : str\n\n File extension.\n - vidcap : \n\n cv2 capture of video file, with all frames ready to be read with `vidcap.read()`.\n - fps : int\n\n The FPS (frames per second) of the input video capture.\n - length : int\n\n The number of frames in the input video capture.\n - width : int\n\n The pixel width of the input video capture. \n - height : int\n\n The pixel height of the input video capture. \n - contrast : int or float, optional\n\n Applies +/- 100 contrast to video.\n - brightness : int or float, optional\n\n Applies +/- 100 brightness to video.\n\n Outputs\n -------\n - A video file with the name `of` + '_cb' + `fex`.\n\n Returns\n -------\n - cv2 video capture of output video file.\n \"\"\"\n pb = MgProgressbar(total=length,\n prefix='Adjusting contrast and brightness:')\n count = 0\n if brightness != 0 or contrast != 0:\n contrast = np.clip(contrast, -100.0, 100.0)\n brightness = np.clip(brightness, -100.0, 100.0)\n contrast *= 1.27\n brightness *= 2.55\n fourcc = (cv2.VideoWriter_fourcc)(*'MJPG')\n out = cv2.VideoWriter(of + '_cb' + fex, fourcc, fps, (width, height))\n success, image = vidcap.read()\n if success:\n success, image = vidcap.read()\n if not success:\n pb.progress(length)\n break\n image = np.int16(image) * (contrast / 127 + 1) - contrast + brightness\n image = np.clip(image, 0, 255)\n out.write(image.astype(np.uint8))\n pb.progress(count)\n count += 1\n else:\n out.release()\n vidcap = cv2.VideoCapture(of + '_cb' + fex)\n return vidcap\n\n\ndef mg_skip_frames(of, fex, vidcap, skip, fps, length, width, height):\n \"\"\"\n Time-shrinks the video by skipping (discarding) every n frames determined by `skip`.\n\n Parameters\n ----------\n - of : str\n\n 'Only filename' without extension (but with path to the file).\n - fex : str\n\n File extension.\n - vidcap : \n\n cv2 capture of video file, with all frames ready to be read with `vidcap.read()`.\n - skip : int\n\n Every n frames to discard. `skip=0` keeps all frames, `skip=1` skips every other frame.\n - fps : int\n\n The FPS (frames per second) of the input video capture.\n - length : int\n\n The number of frames in the input video capture.\n - width : int\n\n The pixel width of the input video capture. \n - height : int\n\n The pixel height of the input video capture.\n\n Outputs\n -------\n - A video file with the name `of` + '_skip' + `fex`.\n\n Returns\n -------\n - videcap :\n\n cv2 video capture of output video file.\n - length : int\n\n The number of frames in the output video file.\n - fps : int\n\n The FPS (frames per second) of the output video file.\n - width : int\n\n The pixel width of the output video file. \n - height : int\n\n The pixel height of the output video file. \n \"\"\"\n pb = MgProgressbar(total=length, prefix='Skipping frames:')\n count = 0\n if skip != 0:\n fourcc = (cv2.VideoWriter_fourcc)(*'MJPG')\n out = cv2.VideoWriter(of + '_skip' + fex, fourcc, int(fps), (width, height))\n success, image = vidcap.read()\n if success:\n success, image = vidcap.read()\n if not success:\n pb.progress(length)\n break\n if count % (skip + 1) == 0:\n out.write(image.astype(np.uint8))\n pb.progress(count)\n count += 1\n else:\n out.release()\n vidcap = cv2.VideoCapture(of + '_skip' + fex)\n length = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))\n fps = int(vidcap.get(cv2.CAP_PROP_FPS))\n width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n return (\n vidcap, length, fps, width, height)\n\n\n# NOTE: have internal decompilation grammar errors.\n# Use -t option to show full context.\n# not in loop:\n#\tbreak\n# L. 68 158 BREAK_LOOP 242 'to 242'\n# not in loop:\n#\tbreak\n# L. 148 108 BREAK_LOOP 164 'to 164'","sub_path":"pycfiles/musicalgestures-1.0.6-py3-none-any/_videoadjust.cpython-38.py","file_name":"_videoadjust.cpython-38.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"91327276","text":"from __future__ import absolute_import\nimport re\n\n# Environment.OSVersion (GetVersionEx) or RuntimeInformation.OSDescription, on Windows\n_windows_re = re.compile('^(Microsoft )?Windows (NT )?(?P\\d+\\.\\d+\\.\\d+).*$')\n# Environment.OSVersion or RuntimeInformation.OSDescription (uname)\n# on Mono and CoreCLR on macOS, iOS, Linux, etc\n_uname_re = re.compile('^(?P[a-zA-Z]+) (?P\\d+\\.\\d+\\.\\d+(\\.[1-9]+)?).*$')\n\n\ndef normalize(data):\n raw_description = data.get('raw_description')\n # If there's no name and version, attempts to infer from raw_description\n if raw_description is not None \\\n and data.get('name') is None \\\n and data.get('version') is None:\n r = _windows_re.search(raw_description)\n if r:\n data['name'] = 'Windows'\n data['version'] = r.group('version')\n else:\n r = _uname_re.search(raw_description)\n if r:\n data['name'] = r.group('name')\n data['kernel_version'] = r.group('version')\n","sub_path":"src/sentry/utils/os_normalization.py","file_name":"os_normalization.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"79568809","text":"import numpy \nimport matplotlib.pyplot as pyplot\nimport PIL.Image as Image\nimport pickle\n\nfrom os import listdir\nfrom os.path import isfile, join\n\n\ndef images_to_pickle(path, s_name):\n onlyfiles = [fil for fil in listdir(path) if isfile(join(path, fil))]\n # iterate said array so we get all files into Black white arrays\n print('found: ' + str(len(onlyfiles)) + ' files')\n # new array of images\n images_vector = []\n for fil in onlyfiles:\n # open a image\n filename = fil\n img = Image.open(path+'\\\\'+filename)\n # get the image into an array of bytes\n # convert the image to pure Blackwhite (Not RGB)\n gray = img.convert('L')\n # Numpy for comverting the pixels into pure white (255) and black (0)\n black_white = numpy.asarray(gray).copy()\n # using the grays\n \n # < -------------- 0 or 255 IMPORTANT ---------------- >\n\n # black_white[black_white < 128] = 0\n # black_white[black_white >= 128] = 255\n\n # make sure that the image is exactly the 28*28 size (784)\n # print(black_white.size)\n # concatenate every column of the image into a single array\n single_array = numpy.concatenate(black_white, axis=None)\n # add the image to the images array\n images_vector.append(single_array)\n # dump the compelte data for acess later\n pickle.dump(images_vector, open(s_name, \"wb\"))\n\n# Another try for a neuralnet forward back gradientdescent\n\n\n# funcion de activacion ReLU\ndef ReLU(vector_tbw):\n return numpy.maximum(0, vector_tbw)\n\n\n# derivada de funcion de activacion ReLU\ndef derivada_ReLU(vector_tbw):\n vector_tbw[vector_tbw < 0] = 0\n vector_tbw[vector_tbw > 1] = 1\n return vector_tbw\n\n\ndef feed_forward2(input_matrix, weight_HL, weight_OL, bias_HL, bias_OL):\n # input con peso hidden layer = IHL\n # activacion de el hidden layer = HLA\n\n # predicciones de output layer\n # output con peso = OCP\n\n # hidden layer\n IHL = numpy.dot(input_matrix, weight_HL) + bias_HL\n # cambiar fucnion de activacion si truena\n HLA = ReLU(IHL)\n\n # output layer\n OCP = numpy.dot(HLA, weight_OL) + bias_OL\n # func act cambiar \n predicciones = ReLU(OCP)\n\n return (IHL, HLA, OCP, predicciones)\n\n\n# rate = alfa\ndef backpropagation2(input_matrix, output_layer, weight_HL, weight_OL, rate, HLA, outputs, b_HL, b_OL):\n # utilizar predicciones\n # Error de la layer de la output layer\n # error_OL = (outputs - output_layer) * derivada_ReLU(OL)\n\n # Error basado en brilliant\n error_OL = (output_layer - outputs)\n\n # Error Hidden layer brilliant\n error_HL = HLA * (1 - HLA) * numpy.dot(error_OL, weight_OL)\n\n # Derivadas de pesos para weights\n cost_derivOL = HLA.T @ error_OL\n cost_derivHL = input_matrix.T @ error_HL\n\n # Actualizar weights\n\n weight_OL -= rate * cost_derivOL\n weight_HL -= rate * cost_derivHL\n\n # UPDATING THE BIAS\n # except that there's no input from a previous layer\n # caused by input from a neuron with a fixed activation of 1\n m = numpy.ones((1, 20418))\n # b_OL -= rate * m @ derivada_ReLU(outputs)\n # b_HL -= rate * m @ derivada_ReLU(HLA)\n b_OL -= rate * derivada_ReLU(b_OL)\n b_HL -= rate * derivada_ReLU(b_HL)\n # b_OL -= rate * error_OL\n # b_HL -= rate * error_HL\n\n return (weight_OL, weight_HL, b_OL, b_HL)\n\n\ndef softmax(A):\n expA = numpy.exp(A)\n expA = numpy.nan_to_num(expA)\n # print(expA)\n return expA / expA.sum()\n\n\ndef sigmoid(x):\n x = numpy.nan_to_num(x)\n return 1/(1+numpy.exp(-x))\n\n\ndef sigmoid_der(x):\n x = numpy.nan_to_num(x)\n return sigmoid(x) * (1-sigmoid(x))\n\n\ndef feedforward(feature_set, wh, bh, wo, bo):\n # Phase 1\n zh = numpy.dot(feature_set, wh) + bh\n ah = sigmoid(zh)\n\n # Phase 2\n zo = numpy.dot(ah, wo) + bo\n ao = softmax(zo)\n\n return (ao, ah, zo, zh)\n\n\ndef backpropagation(feature_set, one_hot_labels, ao, ah, wo, zh):\n # Phase 1\n dcost_dzo = ao - one_hot_labels\n dzo_dwo = ah\n\n dcost_wo = numpy.dot(dzo_dwo.T, dcost_dzo)\n\n dcost_bo = dcost_dzo\n\n # Phase 2\n dzo_dah = wo\n dcost_dah = numpy.dot(dcost_dzo, dzo_dah.T)\n dah_dzh = sigmoid_der(zh)\n dzh_dwh = feature_set\n\n dcost_wh = numpy.dot(dzh_dwh.T, dah_dzh * dcost_dah)\n\n dcost_bh = dcost_dah * dah_dzh\n\n return (dcost_wo, dcost_bo, dcost_wh, dcost_bh)\n\n\ndef weight_update(wh, dcost_wh, bh, dcost_bh, wo, dcost_wo, bo, dcost_bo, lr):\n wh -= lr * dcost_wh\n bh -= lr * dcost_bh.sum(axis=0)\n\n wo -= lr * dcost_wo\n bo -= lr * dcost_bo.sum(axis=0)\n\n return (wh, bh, wo, bo)\n\n\ndef starter_bias(H_size, O_size):\n Hidden_bias = numpy.full((1 ,H_size), 0.1)\n Output_bias = numpy.full((1 ,O_size), 0.1)\n return Hidden_bias, Output_bias\n\n\ndef costo(predicciones, output_layer):\n costo = numpy.sum((predicciones - output_layer) ** 2 / y.size)\n return costo\n\n\ndef derivda_costo(predicciones, output_layer):\n return predicciones - output_layer\n\n\ndef feed_forward3(X, t1, t2):\n m, n = X.shape\n # A1 = numpy.hstack((numpy.ones(m).reshape(m, 1), X))\n print(X.shape)\n # matrix multiplication\n Z2 = X @ t1.T\n A2 = sigmoid(Z2)\n m2, _n2 = A2.shape\n # A2 = numpy.hstack((numpy.ones(m2).reshape(m2, 1), A2))\n Z3 = A2 @ t2.T \n A3 = sigmoid(Z3)\n return (Z2, A2, Z3, A3)\n\n\ndef descenso_gradiente(m, b, X, Y, rate):\n deriv_m = 0\n deriv_b = 0\n N = len(X)\n for i in range(N):\n deriv_m += -2*X[i] * (Y[i] - (m*X[i] + b))\n deriv_b += -2*(Y[i] - (m*X[i] + b))\n \n # restar la derivada en la direccion del decenso\n m -= (deriv_m / float(N)) * rate\n b -= (deriv_b / float(N)) * rate\n\n return m, b","sub_path":"neural_lib.py","file_name":"neural_lib.py","file_ext":"py","file_size_in_byte":5684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"44367506","text":"from pyneval.model.swc_node import SwcTree\nMAX_DIS = 0x3fffffff\n\n\ndef mse_metric(gold_swc_tree, test_swc_tree):\n gold_swc_list = gold_swc_tree.get_node_list()\n test_swc_list = test_swc_tree.get_node_list()\n\n avg_dis_1 = 0\n for gold_node in gold_swc_list:\n if gold_node.is_virtual():\n continue\n dis = MAX_DIS\n for test_node in test_swc_list:\n if test_node.is_virtual():\n continue\n dis = min(dis, gold_node.distance(test_node))\n avg_dis_1 += dis\n avg_dis_1 /= (len(gold_swc_list)-1)\n return avg_dis_1\n\n\nif __name__==\"__main__\":\n gold_swc_tree = SwcTree()\n test_swc_tree = SwcTree()\n\n # gold_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\gold\\\\branch.swc\")\n # test_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\\\test\\\\branch.swc\")\n test_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\\\test\\\\34_23_10_test.swc\")\n gold_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\gold\\\\34_23_10_gold.swc\")\n # test_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\\\test\\\\2_18_test.swc\")\n # gold_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\gold\\\\2_18_gold.swc\")\n\n\n # gold_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\gold\\mse_hunter.swc\")\n # test_swc_tree.load(\"D:\\gitProject\\mine\\PyNeval\\\\test\\data_example\\\\test\\mse_hunter.swc\")\n print(mse_metric(gold_swc_tree, test_swc_tree))\n print(mse_metric(test_swc_tree, gold_swc_tree))\n\n\n","sub_path":"test/test_model/compare_metric/mse.py","file_name":"mse.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"307013628","text":"\"\"\"\nGiven a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.\n\nExample 1:\n\nInput: [5,7]\nOutput: 4\nExample 2:\n\nInput: [0,1]\nOutput: 0\nhttps://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/531/week-4/3308/\n\n\"\"\"\n\n\nclass Solution:\n def rangeBitwiseAnd(self, m: int, n: int) -> int:\n # 64 ms\n \"\"\"\n if m != n:\n return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1\n else:\n return m\n \"\"\"\n # 32 ms\n total = 0\n while m != n:\n m >>= 1\n n >>= 1\n total += 1\n return m << total\n\n\n# Main Call\nsolution = Solution()\nm = 5\nn = 7\nresult = solution.rangeBitwiseAnd(m, n)\nprint(result)\n","sub_path":"src/integers/rangeBitwiseAnd.py","file_name":"rangeBitwiseAnd.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"628596695","text":"import webapp2\nimport json\nfrom google.appengine.ext import ndb\nfrom followerfollowing import followerfollowing\n\nclass newUserApi(webapp2.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n self.redirect('/')\n\n def post(self):\n self.response.headers['Content-Type'] = 'application/json'\n\n Json_Data = json.loads(self.request.body)\n Data = {}\n email_address = Json_Data[\"email_address\"]\n newUsersEmail = Json_Data[\"newUsersEmail\"]\n\n collection = []\n Caption = []\n experience = []\n hotel = []\n visa = []\n flight = []\n from_location = []\n to_location = []\n length = 0\n oldUsersEmail = \"\"\n\n if(newUsersEmail != \"\" and email_address == newUsersEmail):\n Data['ResponseStatus'] = \"NewUserIsCurrentlyLoggedIn\"\n elif(newUsersEmail != \"\" and email_address != \"\"):\n collection_key = ndb.Key('timelinepost',newUsersEmail).get()\n if collection_key != None:\n i = len(collection_key.caption) - 1\n while i > -1:\n collection.append(collection_key.photo_url[i])\n Caption.append(collection_key.caption[i])\n experience.append(collection_key.experience[i])\n hotel.append(collection_key.hotel[i])\n flight.append(collection_key.flight[i])\n visa.append(collection_key.visa[i])\n from_location.append(collection_key.from_location[i])\n to_location.append(collection_key.to_location[i])\n i = i - 1\n length = len(collection)\n\n Data['ResponseStatus'] = \"GivingNewUserData\"\n Data['photo_url'] = collection\n Data['caption'] = Caption\n Data['experience'] = experience\n Data['hotel'] = hotel\n Data['flight'] = flight\n Data['visa'] = visa\n Data['from_location'] = from_location\n Data['to_location'] = to_location\n\n elif(email_address != \"\" and newUsersEmail == \"\"):\n Data['ResponseStatus'] = \"newUserEmpty\"\n else:\n Data['ResponseStatus'] = \"NotHandled\"\n\n self.response.write(json.dumps(Data))\n\napp = webapp2.WSGIApplication([\n ('/newUserApi',newUserApi),\n], debug=True)\n","sub_path":"newUserApi.py","file_name":"newUserApi.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"132423219","text":"# coding=utf-8 设定编码形式\nimport re #包含正则表达式\nimport codecs\ndict = {}\nz = re.compile(u'[\\u4e00-\\u9fa5]+')#将所有的中文字符全部都包含里面\nwith open('../中科院分词/result.txt', 'rb') as f:#自己的文件可以根据自己的具体需要更改路径\n mylist=f.readlines()\n for row in mylist:\n row= row.strip().decode('utf-8')\n row.strip(' ')#这里可以更改为其他的条件,比如说逗号或者其他的,根据自己语料库的需要设置即可\n i = z.findall(row) #Z1统计单字,Z4表示统计四字高频\n for j in i: \n if (j in dict):\n dict[j] += 1\n else:\n dict[j] = 1\ndict = sorted(dict.items(), key=lambda d: d[1],reverse=True) #安装value排序\nwith open('result.txt', 'w',encoding='utf-8') as f:\n for a, b in dict: #a是中文,b是词出现的次数\n if b > 0:\n #print(a,b)\n f.write(a + \",\" + str(b) + \"\\n\")\n","sub_path":"词频/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"270211329","text":"from params import getParams\nfrom scipy.stats import laplace, norm\nfrom ystockquote import get_price\nfrom operator import mul\nfrom numpy import exp\nfrom bs import BlackScholes\nfrom functools import reduce\n\n\nclass futurePrice():\n\n def __init__(self, ticker):\n self.ticker = ticker\n params = getParams(ticker)\n self.mean = params[0][0]\n self.var = params[0][1]\n self.vol = params[1]\n self.price = get_price(self.ticker)\n\n def futurePrice(self, days, strike, flag='C', model = 'laplace'):\n if 'laplace' in model:\n changes = laplace.rvs(0, self.var, size=days)\n elif 'norm' in model:\n changes = norm.rvs(0, self.var, size=days)\n values = exp(changes)\n self.daily = [float(self.price) * prod(values[0:i + 1])\n for i in range(len(values))]\n self.bs = [BlackScholes(flag, float(price), float(strike), .005, self.vol, float(\n days - i) / 365) for i, price in enumerate(self.daily)]\n\n\ndef prod(iterable):\n return reduce(mul, iterable, 1)\n\n# functional version for parallel proccessing\n\n\ndef price(futurePrice, days, strike, flag='C', model = 'laplace'):\n if 'laplace' in model:\n changes = laplace.rvs(0, futurePrice.var, size=days*5/7)\n elif 'norm' in model:\n changes = norm.rvs(0, futurePrice.var, size=days*5/7)\n\n values = exp(changes)\n daily = [float(futurePrice.price) * prod(values[0:i + 1])\n for i in range(len(values))]\n bs = [\n BlackScholes(\n flag, float(price), strike, .005, futurePrice.vol, float(\n days - i) / 365) for i, price in enumerate(daily)]\n return sum(bs) / len(bs)\n","sub_path":"web/main/monte/futurePrice.py","file_name":"futurePrice.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"390867445","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# Gráficos em python\nimport matplotlib.pyplot as plt\n\n\n# In[2]:\n\n\n# Bibliotecas\nimport numpy as np #funções numéricas\n\n\n# In[4]:\n\n\n# valores de x,y,z:\n\n\n#x, y, z = #função importar ////// #DADOS DEVEM ENTRAR AQUI (X,Y,Z)\n\n\n# - EXEMPLO DE GRÁFICO\n\n# In[7]:\n\n\n## PRECISAMOS ACHAR COMANDOS/BIBLIOTECAS AS QUAIS PLOTAM 3D\nx = np.linspace(-100 , 100, 4000)\ny = (x+3) /(x**2+7)\nplt.figure()\nplt.plot(x, y, 'r') ##y2=x\nplt.xlabel(\"x\")\nplt.ylabel(\"y=cos(x) e y=x\")\nplt.grid()\n#plt.xlim(0.2 , 0.3) ##MONSTRA LUGARES ESPECÍFICOS DO GRÁFICO\nplt.show()\n\n","sub_path":"PROJETO_PYTHON.py","file_name":"PROJETO_PYTHON.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"640937673","text":"from flask import Blueprint,request,render_template\r\nfrom app.utilities.forms import SearchForm\r\nfrom app.adapters.repository import repo_instance as repo\r\n\r\nbp = Blueprint('home', __name__, url_prefix='/')\r\n\r\n@bp.route('/', methods=('GET',))\r\ndef index():\r\n form = SearchForm(request.args, meta={'csrf': False})\r\n data = None\r\n if form.validate():\r\n page = form.page.data\r\n size = form.size.data\r\n key = form.key.data\r\n by = form.by.data\r\n data = repo.search_movies(key, by, page, size)\r\n\r\n return render_template('index.html', data=data, form=form)","sub_path":"app/home/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"340839382","text":"from flask import Flask, abort, request\n\nfrom req import get_weather\n\nfrom news_list import all_news\n\n\ncity_name = 'London'\napi_key = '9fb3b0685690c2d66ef8be49d0fe3c81'\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n url = 'http://api.openweathermap.org/data/2.5/weather?APPID={0}&q={1}&units=metric'.format(api_key, city_name)\n weather = get_weather(url)\n result = '
    ' + 'Температура {} \\n'.format(weather['main']['temp'])\n result += '
    Город: {}'.format(weather['name'])\n return result\n\n\n# @app.route(\"/news\")\n# def all_the_news():\n# for item in request.args:\n# print(item)\n# print(request.args.get(item))\n# return 'News'\n@app.route(\"/news\")\ndef all_the_news():\n limit = request.args.get('limit', 'all')\n color = request.args.get('color', 'black')\n return '

    News: {1}

    '.format(color, limit)\n\n\n\n\n@app.route(\"/news/\")\ndef news_by_id(news_id):\n news_to_show = [news for news in all_news if news['id'] == news_id]\n html_text = '

    {title}

    {date}

    {text}

    '.format(**news_to_show[0])\n # print(html_text)\n if len(news_to_show) == 1:\n return html_text\n else:\n abort(404)\n\n\nif __name__ == \"__main__\":\n app.run(port=5008)\n\n\n","sub_path":"Lesson3_2/env/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"544753113","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport cv2\nfrom skimage import morphology\nfrom skimage import measure\nfrom ..utils import resize_image, parallel_map\nimport numpy\nfrom scipy import ndimage\n\n\nclass ManualFeatures(object):\n\n def __init__(self, verbose=True):\n self.verbose = verbose\n\n def fit(self, images, y=None):\n pass\n\n def transform(self, images):\n return numpy.vstack(parallel_map(features, images))\n\n def fit_transform(self, X, y=None):\n self.fit(X)\n return self.transform(X)\n\n#\n# SKLearn region props features\n#\n\ndef get_largest_region(regions, labels, image):\n regionmaxprop = None\n for regionprop in regions:\n if regionmaxprop is None:\n regionmaxprop = regionprop\n if regionmaxprop.filled_area < regionprop.filled_area:\n regionmaxprop = regionprop\n return regionmaxprop\n\n\ndef get_max_region(image, image_thr):\n labels = measure.label(image)\n labels = image_thr * labels\n labels = labels.astype(int)\n\n # calculate common region properties for each region within the segmentation\n regions = measure.regionprops(labels)\n regionmax = get_largest_region(regions, labels, image_thr)\n return regionmax\n\n\ndef shape_features(image):\n # Add a border to image to avoid empty regions\n image = cv2.copyMakeBorder(\n image,\n 1,\n 1,\n 1,\n 1,\n cv2.BORDER_CONSTANT,\n value=(255, 255, 255))\n\n # Treshold\n mean = numpy.mean(image.flatten())\n image_thr = numpy.where(image > mean, 0.0, 1.0)\n # TODO: try with different kernels\n image_dil = morphology.dilation(image_thr, numpy.ones((5, 5)))\n regionmax = get_max_region(image_dil, image_thr)\n\n if regionmax is None:\n regionmax = get_max_region(image_thr, image_thr)\n\n return numpy.concatenate((\n regionmax.moments_hu,\n regionmax.moments_normalized.flatten(),\n regionmax.bbox,\n regionmax.inertia_tensor.flatten(),\n regionmax.inertia_tensor_eigvals,\n [\n regionmax.area,\n regionmax.perimeter,\n regionmax.minor_axis_length / max(regionmax.major_axis_length, 1.0),\n regionmax.solidity,\n regionmax.eccentricity,\n regionmax.equivalent_diameter,\n regionmax.euler_number,\n regionmax.extent,\n regionmax.filled_area\n ]\n ))\n\n\n#\n# Simple statistics from numpy\n#\n\ndef numpy_features(image):\n image_1d = image.flatten()\n\n # Compute grey-scale histogram\n # TODO: to delete?\n # histo, _ = numpy.histogram(image)\n # histo = histo.flatten()\n\n height, width = image.shape[0], image.shape[1]\n\n # Median\n median = numpy.median(image_1d)\n\n # Average\n avg = numpy.average(image_1d)\n\n # Mean\n mean = numpy.mean(image_1d)\n\n # Standard deviation\n std = numpy.std(image_1d)\n\n # Variance\n var = numpy.var(image_1d)\n\n return [\n height,\n width,\n median,\n avg,\n mean,\n std,\n var\n ]\n\n\ndef scipy_features(image):\n histo = ndimage.measurements.histogram(image, 0, 255, 10)\n mini, maxi, minpos, maxpos = ndimage.extrema(image)\n return numpy.concatenate((\n histo,\n minpos,\n maxpos,\n ndimage.measurements.center_of_mass(image),\n [\n mini,\n maxi,\n ]\n ))\n\n\ndef features(image):\n # Convert to grayscale\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image_resize = resize_image(image, (10, 10)).flatten()\n\n features = numpy.concatenate((\n image_resize,\n numpy_features(image),\n scipy_features(image),\n shape_features(image)\n ))\n # normalize\n mini = numpy.finfo(numpy.float32).min\n maxi = numpy.finfo(numpy.float32).max\n features[features <= mini] = 0.0\n features[features >= maxi] = 0.0\n features[numpy.isnan(features)] = 0.0\n\n return features\n","sub_path":"ndsbkaggle/features/manual.py","file_name":"manual.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"380021719","text":"# a sprite is a name for a single two-dimensional image that is used as partof the graphics\nimport pygame,sys,random\nfrom pygame.locals import *\n\n# setup pygame\npygame.init()\nmainclock = pygame.time.Clock()\n# set up the window\nwindowwidth,windowheight = 400,400\nwindowsurface = pygame.display.set_mode((windowwidth,windowheight),0,32)\npygame.display.set_caption('Sprites and Sound')\n# set up the colors\nblack = 0,0,0\n\n# set up the block data\nplayer = pygame.Rect(300,100,40,40)\nplayerimage = pygame.image.load('player.png')\nplayerstretchedimage = pygame.transform.scale(playerimage,(40,40))\nfoodimage = pygame.image.load('cherry.png')\nfoods = list()\nfor i in range(20):\n foods.append(pygame.Rect(random.randint(0,windowwidth-20), random.randint(0,windowheight-20),20,20))\nfoodcounter = 0\nnewfood = 40\n\n# set up the keyboard variables\nmoveleft,moveright,moveup,movedown = False,False,False,False\nmovespeed = 6\n\n# set up music\npickupsound = pygame.mixer.Sound('pickup.wav')\npygame.mixer.music.load('background.mid')\npygame.mixer.music.play(-1,0.0)\nmusicplaying = True\n\n\n# run the game loop\nwhile True:\n # check for the QUIT event\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == KEYDOWN:\n # change the keyboard variable\n if event.key == K_LEFT or event.key == ord('a'):\n moveright = False\n moveleft = True\n if event.key == K_RIGHT or event.key == ord('s'):\n moveleft = False\n moveright = True\n if event.key == K_UP or event.key == ord('d'):\n movedown = False\n moveup = True\n if event.key == K_DOWN or event.key == ord('f'):\n moveup = False\n movedown = True\n if event.type == KEYUP:\n if event.key == K_ESCAPE:\n pygame.quit()\n sys.exit()\n if event.key == K_LEFT or event.key == ord('a'):\n moveleft = False\n if event.key == K_RIGHT or event.key == ord('s'):\n moveright = False\n if event.key == K_UP or event.key == ord('d'):\n moveup = False\n if event.key == K_DOWN or event.key == ord('f'):\n movedown = False\n if event.key == ord('x'):\n # teleport player\n player.top = random.randint(0,windowheight-player.height)\n player.left = random.randint(0,windowwidth-player.width)\n if event.key == ord('m'):\n if musicplaying:\n pygame.mixer.music.stop()\n else:\n pygame.mixer.music.play(-1,0.0)\n musicplaying = not musicplaying\n\n if event.type == MOUSEBUTTONUP:\n foods.append(pygame.Rect(event.pos[0]-10,event.pos[1]-10,20,20))\n\n foodcounter += 1\n if foodcounter >= newfood:\n # add new food\n foodcounter = 0\n foods.append(pygame.Rect(random.randint(0,windowwidth-20),random.randint(0,windowheight-20),20,20))\n # draw the black background\n windowsurface.fill(black)\n # move the player\n if movedown and player.bottom < windowheight:\n player.top += movespeed\n if moveup and player.top > 0:\n player.top += -movespeed\n if moveleft and player.left > 0:\n player.left += -movespeed\n if moveright and player.right < windowwidth:\n player.right += movespeed\n # draw the block\n windowsurface.blit(playerstretchedimage,player)\n # check if the block has intersected with any food squares\n for food in foods[:]:\n if player.colliderect(food):\n foods.remove(food)\n player = pygame.Rect(player.left,player.top,player.width+2, player.height+2)\n playerstrectedimage = pygame.transform.scale(playerimage, (player.width,player.height))\n if musicplaying:\n pickupsound.play()\n # draw the food\n for food in foods:\n windowsurface.blit(foodimage, food)\n # draw the window\n pygame.display.update()\n mainclock.tick(40)\n\n\n\n","sub_path":"inventwithpython/spritesandsounds.py","file_name":"spritesandsounds.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"185198249","text":"import time\r\nimport pygame\r\nimport random\r\nimport math\r\nfrom .gameobject import GameObject\r\n\r\nclass Emitter(GameObject):\r\n def __init__(self, name, position, lifetime, amount, bursts, rate):\r\n super().__init__(name, position, (0,0))\r\n self.position = position\r\n self.lifetime = lifetime\r\n self.amount = amount\r\n self.bursts = bursts\r\n self.created_bursts = 0\r\n self.rate = rate\r\n self.particles = []\r\n self.can_emit = True\r\n self.last_emit = 0\r\n self.dt = 1/60\r\n self.gravity = (0, 1)\r\n self.base_velocity = (0, 0)\r\n self.base_color = (255, 255, 255)\r\n self.base_size = 16\r\n self.base_lifetime = 5\r\n\r\n def emit(self):\r\n if self.created_bursts >= self.bursts:\r\n self.can_emit = False\r\n if self.can_emit:\r\n self.can_emit = False\r\n for i in range(self.amount):\r\n self.particles.append(Particle(\r\n self.position,\r\n self.base_color,\r\n (8*math.cos(random.uniform(0, 2*math.pi)), 8*math.sin(random.uniform(0, 2*math.pi))),\r\n self.base_lifetime + random.uniform(-self.base_lifetime, self.base_lifetime),\r\n self.gravity,\r\n self.base_size + random.uniform(0, self.base_size/4)\r\n ))\r\n self.created_bursts += 1\r\n self.last_emit = time.time()\r\n\r\n def draw(self, surface):\r\n if self.lifetime >= 0 and self.lifetime != -1:\r\n self.lifetime -= self.dt\r\n self.emit()\r\n if not self.can_emit and (time.time() > self.last_emit + self.rate):\r\n self.can_emit = True\r\n for particle in self.particles:\r\n particle.update(self.dt)\r\n particle.draw(surface)\r\n if particle.lifetime <= 0:\r\n self.particles.remove(particle)\r\n\r\n def set_gravity_modifier(self, gravity:tuple):\r\n self.gravity = gravity\r\n\r\n def is_emitting(self):\r\n if self.lifetime == -1 or self.lifetime>0:\r\n return True\r\n return False\r\n \r\nclass Particle():\r\n def __init__(self, position, color, velocity, base_lifetime, gravity_modifier, size):\r\n self.position = position\r\n self.color = color\r\n self.velocity = velocity\r\n self.base_lifetime = base_lifetime\r\n self.lifetime = base_lifetime\r\n self.size = size\r\n self.gravity_modifier = gravity_modifier\r\n self.alpha = 10\r\n\r\n def update(self, dt):\r\n if self.lifetime >= 0:\r\n self.lifetime -= dt\r\n lifetime_factor = self.lifetime/self.base_lifetime\r\n if(lifetime_factor>=0):self.size *= lifetime_factor\r\n else : self.lifetime = 0\r\n \r\n if(self.size < 1 ):\r\n self.lifetime = 0\r\n self.gravity_modifier = (self.gravity_modifier[0]*(1+dt), self.gravity_modifier[1]*(1+dt))\r\n self.position = (self.position[0] + self.velocity[0]*lifetime_factor + self.gravity_modifier[0] , self.position[1] + self.velocity[1]*lifetime_factor + self.gravity_modifier[1])\r\n\r\n def draw(self, surface):\r\n pygame.draw.rect(surface, (30, 30, 30), (self.position[0]+6, self.position[1]+6, self.size, self.size))\r\n pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], self.size, self.size))\r\n ","sub_path":"utils/particles.py","file_name":"particles.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"383433604","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2011-2014 - Simon Conseil\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\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell 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\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\nimport codecs\nimport os\nimport shutil\nfrom markdown import Markdown\nfrom subprocess import Popen, PIPE\n\nfrom . import compat\n\n\nclass Devnull(object):\n \"\"\"'Black hole' for output that should not be printed\"\"\"\n\n def write(self, *_):\n pass\n\n def flush(self, *_):\n pass\n\n\ndef copy(src, dst, symlink=False):\n \"\"\"Copy or symlink the file.\"\"\"\n func = os.symlink if symlink else shutil.copy2\n if symlink and os.path.lexists(dst):\n os.remove(dst)\n func(src, dst)\n\n\ndef check_or_create_dir(path):\n \"Create the directory if it does not exist\"\n\n if not os.path.isdir(path):\n os.makedirs(path)\n\n\ndef url_from_path(path):\n \"\"\"Transform path to url, converting backslashes to slashes if needed.\"\"\"\n\n if os.sep == '/':\n return path\n else:\n return '/'.join(path.split(os.sep))\n\n\ndef read_markdown(filename):\n \"\"\"Reads markdown file, converts output and fetches title and meta-data for\n further processing.\n \"\"\"\n # Use utf-8-sig codec to remove BOM if it is present. This is only possible\n # this way prior to feeding the text to the markdown parser (which would\n # also default to pure utf-8)\n with codecs.open(filename, 'r', 'utf-8-sig') as f:\n text = f.read()\n\n md = Markdown(extensions=['meta'], output_format='html5')\n output = {'description': md.convert(text)}\n\n try:\n meta = md.Meta.copy()\n except AttributeError:\n pass\n else:\n output['meta'] = meta\n output['title'] = md.Meta.get('title', [''])[0]\n\n return output\n\n\ndef call_subprocess(cmd):\n \"\"\"Wrapper to call ``subprocess.Popen`` and return stdout & stderr.\"\"\"\n p = Popen(cmd, stdout=PIPE, stderr=PIPE)\n stdout, stderr = p.communicate()\n\n if not compat.PY2:\n stderr = stderr.decode('utf8')\n stdout = stdout.decode('utf8')\n return p.returncode, stdout, stderr\n\n\nclass cached_property(object):\n '''Decorator for read-only properties evaluated only once.\n\n © 2011 Christopher Arndt, MIT License\n https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties\n\n The value is cached in the '_cache' attribute of the object instance that\n has the property getter method wrapped by this decorator. The '_cache'\n attribute value is a dictionary which has a key for every property of the\n object which is wrapped by this decorator. Each entry in the cache is\n created only when the property is accessed for the first time and is a\n two-element tuple with the last computed property value and the last time\n it was updated in seconds since the epoch.\n\n '''\n\n def __call__(self, fget, doc=None):\n self.fget = fget\n self.__doc__ = doc or fget.__doc__\n self.__name__ = fget.__name__\n self.__module__ = fget.__module__\n return self\n\n def __get__(self, inst, owner):\n try:\n value = inst._cache[self.__name__]\n except (KeyError, AttributeError):\n value = self.fget(inst)\n try:\n cache = inst._cache\n except AttributeError:\n cache = inst._cache = {}\n cache[self.__name__] = value\n return value\n","sub_path":"sigal/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"535288172","text":"import DrawFrame\nimport storyFetch\nimport json\nfrom PIL import Image, ImageDraw, ImageFont\n\"\"\"\n\tNaming variable for stories which titles are not compatible with OS file naming requirments,\n\tso they will be named e.g. \"Dadjoke0\"\n\"\"\"\nexternalDadjokecounter = 0\nsubreddit = \"entitledparents\"\nmode = \"top\"\nlimit = 10\n\n\nif __name__ == '__main__':\n\n\tDrawFrame.settings = DrawFrame.TextFrame(TitleFont = ImageFont.truetype(\"fonts/Futura Bold font.ttf\", 35), TextFont = ImageFont.truetype(\"fonts/Futura Light font.ttf\", 35))\n\t\"\"\"Download .json file from specified subreddit\"\"\"\n\tstories = json.loads(storyFetch.GetStories(subreddit, mode, limit))\n\tprint(\"fetched \" + str(storyFetch.NoOfStories(stories)) + \" stories:\")\n\t\"\"\"Generate TextFrames for each post, some will not be generated due to errors\"\"\"\n\tfor story in stories.get(\"data\").get(\"children\"):\n\t\tDrawFrame.GenerateFrames(story.get(\"data\").get(\"title\"), story.get(\"data\").get(\"selftext\"), story.get(\"data\").get(\"author\"), externalDadjokecounter)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"478424899","text":"\"\"\" Binary Search Algorithm \r\n----------------------------------------\r\n\"\"\"\r\n# // iterative implementation of binary search in Python\r\nimport random\r\n\r\n\r\ndef binary_search(a_list, item):\r\n \"\"\"Performs iterative binary search to find the position of an integer in a given, sorted, list.\r\n a_list -- sorted list of integers\r\n item -- integer you are searching for the position of\r\n \"\"\"\r\n first = 0\r\n last = len(a_list) - 1\r\n while first <= last:\r\n # i = int((first + last) / 2)\r\n # if a_list[i] == item:\r\n # return '{} found at position {}'.format(item=item, i=i)\r\n # elif a_list[i] > item:\r\n # last = i - 1\r\n # elif a_list[i] < item:\r\n # first = i + 1\r\n # else:\r\n # return '{} not found in the list'.format(item=item)\r\n\r\n for i in range(len(a_list)):\r\n if a_list[i] == item:\r\n return '{} found at position {}'.format(item, i)\r\n elif a_list[i] > item:\r\n last = i - 1\r\n elif a_list[i] < item:\r\n first = i + 1\r\n else:\r\n return '{} not found in the list'.format(item)\r\n\r\n# // recursive implementation of binary search in Python\r\n\r\n\r\ndef binary_search_recursive(a_list, item):\r\n \"\"\"Performs recursive binary search of an integer in a given, sorted, list.\r\n a_list -- sorted list of integers\r\n item -- integer you are searching for the position of\r\n \"\"\"\r\n first = 0\r\n last = len(a_list) - 1\r\n if len(a_list) == 0:\r\n return '{} was not found in the list'.format(item)\r\n else:\r\n i = (first + last) // 2\r\n if item == a_list[i]:\r\n return '{} was found in list at index {}'.format(item, i)\r\n else:\r\n if a_list[i] < item:\r\n return binary_search_recursive(a_list[i + 1:], item)\r\n else:\r\n return binary_search_recursive(a_list[:i], item)\r\n\r\n\r\na = [n for n in range(1, 100, 2)]\r\nprint(binary_search(a, random.choice(a)))\r\nprint(binary_search_recursive(a, random.choice(a)))\r\n\r\n# for items, index in enumerate(a):\r\n# print(items,'--->', index)\r\n","sub_path":"binary_search_algorithm.py","file_name":"binary_search_algorithm.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"588139878","text":"from typing import Union, Tuple\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom objective_functions.abstract_objective_function import ObjectiveFunction\nfrom objective_functions.parameter_category import TypeVariable\n\n\nclass SixHumpCamelObjectiveFunction(ObjectiveFunction):\n def evaluate_without_noise(self,\n data_points: np.ndarray\n ) -> Union[np.ndarray, float]:\n \"\"\"\n Same as evaluate(data_points) but does not apply any additional noise to the results\n :param data_points: numpy array of dimension n x m where n is the number of elements to evaluate\n and m is the number of variables used to calculate the objective function\n :return: a numpy array of dimension n x 1 representing all the evaluations for all the n elements.\n \"\"\"\n x = data_points[:, 0]\n y = data_points[:, 1]\n\n x2 = x ** 2\n x4 = x ** 4\n y2 = y ** 2\n\n return (4.0 - 2.1 * x2 + (x4 / 3.0)) * x2 \\\n + x * y \\\n + (-4.0 + 4.0 * y2) * y2\n\n @property\n def dataset_bounds(self) -> Tuple[Tuple[Tuple[float, float],\n TypeVariable],\n ...]:\n \"\"\"\n Defines the bounds and the types of variables for the objective function\n\n Example:\n if dataset_bounds is equal to\n (\n ((1, 2), TypeVariable.REAL),\n ((5, 10), TypeVariable.INTEGER),\n )\n then it means the objective function depends on 2 variables:\n - the first one is a real number between 1 and 2\n - the second one is an integer between 5 (included) and 10 (excluded)\n \"\"\"\n\n return (\n ((-3., 3.), TypeVariable.REAL),\n ((-2., 2.), TypeVariable.REAL),\n )\n\n def plot(self, list_number_points_per_axis):\n mesh_grid = self.get_mesh_grid(list_number_points_per_axis)\n xx, yy = mesh_grid\n xx, yy = xx.flatten(), yy.flatten()\n data_points = np.asarray([\n [x, y]\n for y in yy\n for x in xx\n ])\n\n evaluations = self.evaluate(data_points)\n evaluations = evaluations.reshape((xx.size, yy.size))\n levels = np.arange(-1.5, 10, 0.5)\n plt.contourf(mesh_grid[0].flatten(),\n mesh_grid[1].flatten(),\n evaluations,\n levels=levels)\n plt.show()\n","sub_path":"objective_functions/six_hump_camel.py","file_name":"six_hump_camel.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"3605099","text":"from django.shortcuts import redirect\nfrom django.http import Http404, HttpResponseForbidden\nfrom hknweb.events.models import Rsvp\nfrom hknweb.utils import get_access_level\n\n\ndef confirm_rsvp(request, id, operation):\n if request.method != \"POST\":\n raise Http404()\n\n access_level = get_access_level(request.user)\n if access_level > 0:\n return HttpResponseForbidden()\n\n rsvp = Rsvp.objects.get(id=id)\n rsvp.confirmed = operation == 0 # { confirmed: 0, unconfirmed: 1 }\n rsvp.save()\n\n next_page = request.POST.get(\"next\", \"/\")\n return redirect(next_page)\n","sub_path":"hknweb/events/views/rsvp_transactions/confirm_rsvp.py","file_name":"confirm_rsvp.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"254323646","text":"import unittest\n\nimport mock\n\nfrom mopidy_spotify import Extension, backend as backend_lib\n\n\nclass ExtensionTest(unittest.TestCase):\n\n def test_get_default_config(self):\n ext = Extension()\n\n config = ext.get_default_config()\n\n self.assertIn('[spotify]', config)\n self.assertIn('enabled = true', config)\n\n def test_get_config_schema(self):\n ext = Extension()\n\n schema = ext.get_config_schema()\n\n self.assertIn('username', schema)\n self.assertIn('password', schema)\n self.assertIn('bitrate', schema)\n self.assertIn('timeout', schema)\n self.assertIn('cache_dir', schema)\n\n def test_setup(self):\n registry = mock.Mock()\n\n ext = Extension()\n ext.setup(registry)\n\n registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)\n","sub_path":"tests/test_extension.py","file_name":"test_extension.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"314377987","text":"import logging\n\nimport celery\n\n\n_log = logging.getLogger(__name__)\n\napp = celery.Celery('tasks', broker='amqp://guest@localhost//')\n\n\n@app.task\ndef add(x, y):\n result = x + y\n _log.info(\"Add {} + {} = {}\".format(x, y, result))\n return result\n\n","sub_path":"src/depopprep/depopprep/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"257042970","text":"import pandas as pd\nimport numpy as np\nimport cv2\nimport torch\nimport scipy.io as sio\nimport os\n\ndef gen_gauss(pic, gaze):\n x_grid, y_grid = np.meshgrid(np.linspace(1, pic.shape[1], pic.shape[1]), np.linspace(1,pic.shape[0], pic.shape[0]))\n sigma = 20\n mu = np.array([gaze[0]*pic.shape[1], gaze[1]*pic.shape[0]])\n d = np.sqrt((x_grid-mu[0])*(x_grid-mu[0])+(y_grid-mu[1])*(y_grid-mu[1]))\n g = np.exp(-( (d)**2 / ( 2.0 * sigma**2 ) ) )\n #g = 1*(d < 20)\n g = g/np.max(g)\n return g\n\ndescr_file = '/local_scratch/vsushko/heatmaps_with_new_net/heatmaps/data_descript/train_annotations.txt'\nroot_folder = '/local_scratch/vsushko/heatmaps_with_new_net/heatmaps/'\nface_path = '/local_scratch/vsushko/heatmaps_with_new_net/heatmaps/train_face/'\nmodel_path = '/local_scratch/vsushko/heatmaps_with_new_net/heatmaps/model'\ndescription = pd.read_csv(descr_file, header=None)\n\nimage_mean = sio.loadmat(model_path+'/places_mean_resize.mat')['image_mean']\nimage_mean1 = sio.loadmat(model_path+'/imagenet_mean_resize.mat')['image_mean']\n\nfor idx in range(0, len(description)):\n\n img_path = description.iloc[idx, 0]\n gaze = (description.iloc[idx, 8], description.iloc[idx, 9])\n eyes = (description.iloc[idx, 6], description.iloc[idx, 7])\n image = cv2.imread(root_folder+img_path)\n face = cv2.imread(face_path+'face'+str(idx)+'.jpg')\n ground_truth = gen_gauss(image, gaze)\n\n image_mean_tmp = cv2.resize(image_mean, (image.shape[1], image.shape[0]), interpolation=cv2.INTER_CUBIC)\n image = image - image_mean_tmp\n image = np.transpose(image, (2, 0, 1))\n\n face = np.transpose(face, (2, 0, 1))\n\n dim = image.shape\n image = torch.tensor(image).view(3, dim[1], dim[2]).float(),\n #face = torch.tensor(face).view(3, dim[1], dim[2]).float(),\n #ground_truth = torch.tensor(ground_truth).view(1, dim[1], dim[2]).float()\n\n os.makedirs(os.path.dirname(\"images_torch1/\"+\"{:03d}\".format(int(idx/1000))+\"/image_torch\"+\"{:06d}\".format(idx)), exist_ok=True)\n #os.makedirs(\n # os.path.dirname(\"faces_torch2/\"+\"{:03d}\".format(int(idx/1000))+\"/face_torch\"+\"{:06d}\".format(idx)),\n # exist_ok=True)\n #os.makedirs(\n # os.path.dirname(\"grounds_torch2/\"+\"{:03d}\".format(int(idx/1000))+\"/ground_torch\" + \"{:06d}\".format(idx)),\n # exist_ok=True)\n torch.save(image, \"images_torch1/\"+\"{:03d}\".format(int(idx/1000))+\"/image_torch\"+\"{:06d}\".format(idx))\n #torch.save(face, \"faces_torch2/\"+\"{:03d}\".format(int(idx/1000))+\"/face_torch\"+\"{:06d}\".format(idx))\n #torch.save(ground_truth, \"grounds_torch2/\"+\"{:03d}\".format(int(idx/1000))+\"/ground_torch\" + \"{:06d}\".format(idx))\n\n if idx % 500 == 0:\n print(idx)\n","sub_path":"heatmaps1_resnet/data_wrangle.py","file_name":"data_wrangle.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"334519447","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 15 13:02:56 2018\n\n@author: OH YEA\n\"\"\"\n\nimport numpy as np\n\n#******************************\ndef UpdateET(theE, theGamma, theLamb, thePhi):\n tE = theE\n gamma = theGamma\n lamb = theLamb\n \n tE = gamma * lamb * tE + thePhi\n \n return tE\n\n#******************************\ndef GetNextAction(x, v, theC, theW, epsilon):\n \n tX = x\n tV = v\n \n posActions = np.array([-1, 0, 1])\n tempQ = ExploreQ(tX, tV, theW, theC)\n \n aIndex = GetAction(tempQ, epsilon)\n \n chosenAction = posActions[aIndex]\n return chosenAction\n \n \ndef GetAction (tQ, theEp):\n epsilon = theEp\n tempA = tQ\n if (CheckEntriesEqual(tempA)):\n tempChoice = np.array([0, 1, 2])\n theThing = np.random.choice(tempChoice)\n return theThing\n else: \n theMax = tempA[np.argmax(tempA)]\n theIndices = GetIndices(tempA, theMax, EpsilonGreedy(epsilon))\n return np.random.choice(theIndices)\n \n\ndef GetIndices(theArray, maxValue, whichOne):\n maxIndices = []\n otherIndices = []\n iCounter = 0\n for x in theArray:\n if (x == maxValue):\n maxIndices.append(iCounter)\n else:\n otherIndices.append(iCounter)\n iCounter += 1\n \n if (whichOne == 0):\n return maxIndices\n else:\n return otherIndices\n\ndef EpsilonGreedy(theEp):\n dice = np.random.rand()\n epsilon = theEp\n if (dice < epsilon):\n return 0\n else:\n return 1\n\ndef CheckEntriesEqual(tArray):\n checkArray = tArray\n for x in range(len(checkArray)-1):\n if (checkArray[x+1] != checkArray[x]):\n return False\n return True\n#******************************\ndef ExploreQ(x, v, theW, theC):\n \n theX = x\n theV = v\n \n tempQ = np.zeros(3)\n \n x1, v1 = GetNextState(theX, theV, -1)\n x2, v2 = GetNextState(theX, theV, 0)\n x3, v3 = GetNextState(theX, theV, 1)\n \n tempQ[0], phi1 = GetQ(x1, v1, theC, theW)\n tempQ[1], phi2 = GetQ(x2, v2, theC, theW)\n tempQ[2], phi2 = GetQ(x3, v3, theC, theW)\n \n return tempQ\n \n#******************************\ndef UpdateWeights(w, tAlpha, tTDE, thePhi, theE):\n theAlpha = tAlpha\n theTDE = tTDE\n tPhi = thePhi\n eT = theE\n \n tempW = w\n tempW += theAlpha * theTDE * eT\n \n return tempW\n\ndef CalculateTDE(x1, v1, x2, v2, currentReward, theC, theW):\n \n q1, phi1 = GetQ(x1, v1, theC, theW)\n q2, phi2 = GetQ(x2, v2, theC, theW)\n \n TDE = currentReward + q2 * 1 - q1\n \n return TDE, phi1\n\ndef GetQ(x, v, tC, tW):\n \n tX = x\n tV = v\n \n nState = NormalizeState(tX, tV)\n \n tempW = tW\n tempC = tC\n \n tPhi = np.zeros(tempC.shape[0])\n \n for u in range(tempC.shape[0]):\n tInside = np.dot(tempC[u,:], nState)\n tPhi[u] = np.cos(tInside)\n \n q = np.dot(tempW, tPhi)\n \n return q, tPhi\n \n \ndef NormalizeState(x, v):\n \n minX = -1.2\n maxX = 0.5\n minV = -0.07\n maxV = 0.07\n \n theX = x\n theV = v\n \n theX = (theX - minX)/(maxX - minX)\n theV = (theV - minV)/(maxV - minV)\n \n stateVect = np.array([theX, theV])\n \n return stateVect\n\n\n\n\n\n#*******************************\ndef ResetC(order):\n \n tempOrder = order + 1\n c = np.zeros((tempOrder**2,2), dtype=int)\n counter = 0\n \n for i in range(tempOrder):\n for j in range(tempOrder):\n c[counter, :] = np.array([i, j])\n counter += 1\n c = c * np.pi\n \n w = np.zeros(c.shape[0])\n \n return c, w\n \n\ndef GetNextState (x, v, a):\n tempX = x\n tempV = v\n tempA = a\n vNext = tempV + 0.001 * tempA - 0.0025 * np.cos(3*tempX)\n xNext = tempX + vNext\n \n if (vNext > 0.07):\n vNext = 0.07\n elif (vNext < -0.07):\n vNext = -0.07\n \n if (xNext > 0.5):\n xNext = 0.5\n vNext = 0\n elif (xNext < -1.2):\n xNext = -1.2\n vNext = 0\n \n return xNext, vNext\n\n \ndef GetReward(x):\n tempX = x\n endIt = False\n tempReward = -1\n if (tempX == 0.5):\n endIt = True\n tempReward = 0\n \n return endIt, tempReward\n\n\ndef RunEpisode(alpha, order, theC, theW, epsilon, theLamb):\n x = -0.5\n v = 0\n c = theC\n w = theW\n lamb = theLamb\n endEpisode = False\n totalReward = 0\n eT = np.zeros(w.size)\n tCount = 0\n while (endEpisode == False):\n a = GetNextAction(x, v, c, w, epsilon)\n x2, v2 = GetNextState(x, v, a)\n endEpisode, r = GetReward(x2)\n \n tempTDE, tempPhi = CalculateTDE(x, v, x2, v2, r, c, w)\n eT = UpdateET(eT, 1, theLamb, tempPhi)\n w = UpdateWeights(w, alpha, tempTDE, tempPhi, eT)\n\n totalReward += r\n tCount += 1\n x = x2\n v = v2\n \n \n return totalReward, w\n \ndef RunSimulation(nEpisodes, alpha, order, epsilon, theLamb):\n \n theReturns = []\n c, w = ResetC(order)\n \n for episode in range(nEpisodes):\n tempReturn, w = RunEpisode(alpha, order, c, w, epsilon, theLamb)\n theReturns.append(tempReturn)\n return theReturns\n\n\n\n\n ","sub_path":"sarsa-lamb/mountaincar.py","file_name":"mountaincar.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"306496248","text":"from selenium import webdriver\nimport time\nfrom bs4 import BeautifulSoup\nfrom datetime import date, timedelta\nimport csv\n\ndef login(driver):\n elem = driver.find_element_by_xpath(\"//*[@id='doc']/div/div[1]/div[1]/div[2]/div[2]/div/a[2]\")\n elem.click()\n\n elem = driver.find_element_by_xpath(\"//*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input\")\n elem.send_keys(\"rafaqfigueiredo\")\n elem = driver.find_element_by_xpath(\"//*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input\")\n elem.send_keys(\"cggtatTdnv\")\n elem.submit()\n\ndef goto_explore_recent(driver, account, since, until):\n time.sleep(5)\n elem = driver.find_element_by_xpath(\"//*[@id='react-root']/div/div/div[2]/main/div/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div/form/div[1]/div/div/div[2]/input\")\n elem.send_keys(\"(\" + account + \") until:\" + until + \" since:\" + since)\n elem.submit()\n\n elem = driver.find_element_by_xpath(\"//*[@id='react-root']/div/div/div[2]/main/div/div/div/div/div/div[1]/nav/div[2]/div[2]/a\")\n elem.click()\n\n return driver\n\ndef get_daily_tweets(driver, account):\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n tweets = list()\n\n while True:\n # Scroll down to bottom\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n\n # Wait to load page\n time.sleep(3)\n\n html = driver.page_source\n soup = BeautifulSoup(html, 'html.parser')\n\n elems = soup.select(\"#react-root > div > div > div > main > div > div > div > div > div > div:nth-child(2) > div > div > section > div > div > div > div\")\n\n for elem in elems:\n try:\n author = elem.select_one(\"div > article > div > div > div > div:nth-child(1) > div > div > a > div > div:nth-child(2) > div > span\").get_text()\n date = elem.select_one(\"div > article > div > div > div > div:nth-child(1) > div > a > time\")[\"datetime\"]\n tweets.append({ \"author\": str(author), \"date\": str(date), \"about\": account})\n except:\n continue\n\n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n # break condition\n if new_height == last_height:\n break\n last_height = new_height\n\n unique_tweets = [dict(y) for y in set(tuple(t.items()) for t in tweets)]\n\n return (driver, unique_tweets)\n\ndef get_tweets(driver, account, since, until):\n driver = goto_explore_recent(driver, account, since, until)\n (driver, tweets) = get_daily_tweets(driver, account)\n\n print(\"done for \" + account + \" with \" + str(len(tweets)) + \" tweets\")\n\n driver.get('https://twitter.com/')\n\n return tweets\n\ndef save_tweets(tweets):\n with open(\"/Users/figueiredo/Desktop/legislativas/csv/TWEETS.csv\", 'a', encoding='utf-8') as f:\n w = csv.writer(f, delimiter =';')\n w.writerows([(tweet['author'], tweet['date'], tweet['about']) for tweet in tweets])\n\ndef main():\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--window-size=1920,1080\")\n driver = webdriver.Chrome(\"/Users/figueiredo/Downloads/chromedriver\", options=chrome_options)\n\n driver.implicitly_wait(10)\n driver.get('https://twitter.com/')\n\n login(driver)\n\n today = date.today()\n yesterday = today - timedelta(days=1)\n\n tweets = get_tweets(driver, account=\"@psocialista\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@ppdpsd\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@EsquerdaNet\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@Partido_PAN\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@CDUPCPPEV\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@_CDSPP\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@LIVREpt\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@LiberalPT\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@pnr\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@PCTPMRPP\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@PartidoCHEGA\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@Partido_Alianca\", since=str(yesterday), until=str(today))\n tweets = tweets + get_tweets(driver, account=\"@NOSCIDADAOS\", since=str(yesterday), until=str(today))\n\n save_tweets(tweets)\n\n driver.quit()\n \nif __name__== \"__main__\":\n main()","sub_path":"scripts/socials.py","file_name":"socials.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"248269874","text":"from utils.BasicPage import BasicPage\nfrom locator.web_locator import login_page as login\nfrom utils.Config import ConfigLoader\nimport allure\n\n\nclass login_page(BasicPage):\n\n @allure.step(\"点击首页登录按钮\")\n def click_login(self):\n handles = self.get_handles()\n if ConfigLoader().get_basic_conf() == 'PRO':\n # 如果配置是正式环境执行这行代码\n self.click_element(login.welcome_page, login.element_index_login)\n else:\n self.click_element(login.welcome_page, login.element_test_index_login)\n return handles\n\n @allure.step(\"句柄切换\")\n def login_page_swich(self, handles):\n self.swich_window(handles)\n\n @allure.step(\"登陆功能-输入用户名 密码点击登陆\")\n def login(self, username, pwd):\n self.input_text(model=login.describe, locator=login.element_username, content=username)\n self.input_text(model=login.describe, locator=login.element_password, content=pwd)\n self.click_element(model=login.describe, locator=login.element_login_button)\n\n @allure.step(\"获取错误提示-用户名密码错误\")\n def get_error_msg(self):\n error_msg = self.get_element_text(model=login.describe, locator=login.element_error_msg)\n return error_msg\n","sub_path":"PageObjects/web_PageObject/login_page.py","file_name":"login_page.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"602179597","text":"from common import MyLogger\nfrom datetime import datetime\nfrom vnpy.trader.utility import extract_vt_symbol\nfrom vnpy.trader.object import HistoryRequest\nfrom vnpy.trader.constant import Interval, Exchange\nfrom vnpy.trader.rqdata import rqdata_client\nfrom vnpy.trader.database import database_manager\nimport traceback\nimport rqdatac as rq \nfrom rqdatac import get_price\nfrom vnpy.trader.object import BarData\nfrom typing import List\n\n\"\"\"vpn.trade.rqdata.py\"\"\"\ndef run_downloading(\n rq_symbol: str,\n exchange: str,\n interval: str,\n start: datetime,\n end: datetime\n ):\n \"\"\"\n vpn.trade.rqdata.query_history()\n \"\"\"\n myLogger = MyLogger()\n myLogger.info(f\"{rq_symbol}-{interval} starting download\")\n\n try:\n df = get_price(\n rq_symbol,\n frequency=interval,\n fields=[\"open\", \"high\", \"low\", \"close\", \"volume\", \"open_interest\"],\n start_date=start,\n end_date=end,\n adjust_type=\"none\"\n )\n myLogger.info(f\"finished download row={df.shape[0]};fieds={df.shape[1]}\")\n\n data: List[BarData] = []\n if df is not None:\n for ix, row in df.iterrows():\n #myLogger.info(f\"rq_symbol={rq_symbol};exchange={exchange}\")\n bar = BarData(\n symbol=rq_symbol,\n exchange=exchange,\n interval=Interval(interval),\n datetime=row.name.to_pydatetime() ,\n open_price=row[\"open\"],\n high_price=row[\"high\"],\n low_price=row[\"low\"],\n close_price=row[\"close\"],\n volume=row[\"volume\"],\n open_interest=row[\"open_interest\"],\n gateway_name=\"RQ\"\n )\n data.append(bar)\n \n \n if data:\n database_manager.save_bar_data(data)\n myLogger.info(f\"{rq_symbol}-{interval} download finished\")\n else:\n myLogger.info(f\"download failed, cannot get {rq_symbol} history data\")\n except Exception:\n msg = f\"download exception :\\n{traceback.format_exc()}\"\n myLogger.info(msg)\n\n\nmyLogger = MyLogger()\nrq.init()\nmyLogger.info(\"download 01\")\nrun_downloading(\"TA2001\",Exchange.CZCE,\"1m\",\"2019-01-04\",\"2020-02-15\")\nmyLogger.info(\"download 02\")\nrun_downloading(\"TA2002\",Exchange.CZCE,\"1m\",\"2019-01-04\",\"2020-02-15\")\nmyLogger.info(\"download 03\")\nrun_downloading(\"TA2003\",Exchange.CZCE,\"1m\",\"2019-01-04\",\"2020-02-15\")\nmyLogger.info(\"download 04\")\nrun_downloading(\"TA2004\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 05\")\nrun_downloading(\"TA2005\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 06\")\nrun_downloading(\"TA2006\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 07\")\nrun_downloading(\"TA2007\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 08\")\nrun_downloading(\"TA2008\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 09\")\nrun_downloading(\"TA2009\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 10\")\nrun_downloading(\"TA2010\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 11\")\nrun_downloading(\"TA2011\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download 12\")\nrun_downloading(\"TA2012\",Exchange.CZCE,\"1m\",\"2020-01-01\",\"2020-02-15\")\nmyLogger.info(\"download finished\")\n\n\n\n","sub_path":"examples/liansheng/download_rqdata_to_database.py","file_name":"download_rqdata_to_database.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"69762240","text":"\"\"\"A number guessing game.\"\"\"\nfrom random import randint \n\"\"\"Above and beyond: Instead of simply adding a flat amount of points when the player guesses the \nnumber correctly,I introduced a condition that bases the amount of points rewarded on the number \nof attempts it takes the player to guess the number correctly. The less attempts it takes them, \nthe more points they get. Further, I included two versions of this game with one having a wider \nrange of numbers to guess from, thereby increasing the possible points that the player can receive.\"\"\"\n\n\n__author__ = \"730407570\"\n\n\npoints: int = 0\nhappy_face = \"\\U0001F600\"\nplayer: str = \"\"\n\n\ndef main() -> None:\n \"\"\"Entrypoint of the program and starts the game.\"\"\" \n str_1: str = \"years old and you answered\"\n str_2: str = \"Thanks for checking us out. We hope to see you again.\"\n global points\n points = 0\n greet()\n # custom procedure\n print(\"Now, let's get to know you a little better. For each response, you will receive 10 points.\")\n age: str = input(\"How old are you? \")\n if age != \"\":\n points += 10\n print(f\"Total points: {points}\")\n guessing: str = input(\"Are you good at guessing? \")\n if guessing != \"\":\n points += 10\n print(f\"Total points: {points}\")\n print(f\"So, {player}, you're {age} {str_1} {guessing} to whether or not you are good at guessing.\")\n print(\"Even if you aren't at least you got some points here before you start!\")\n is_playing: bool = True\n while is_playing:\n print(\"Now, you have three options: Exit (type 0), Play version 1 (type 1), Play version 2 (type 2)\")\n option: int = int(input(\"Type in your choice (0, 1, 2): \"))\n \n if option == 0:\n print(f\"{str_2} {player,} you accrued a total of {points} points. Great job!\")\n \n elif option == 1:\n print(f\"Let's begin. Total points: {points}\")\n points += game(points)\n \n print(f\"Total points: {points}\")\n else:\n print(f\"Let's begin. Points: {points}\")\n points += other_game(points)\n print(f\"Total points: {points}\")\n play_again: str = input(\"Play again? yes/no \")\n if play_again == \"no\":\n is_playing = False\n print(f\"{str_2} {player}, you accrued a total of {points} points. Great job!\")\n return None\n\n\ndef greet() -> None:\n \"\"\"Greets the player and prompts them for their name. Gives instructions to the game.\"\"\"\n global player\n print(f\"Welcome to guess the number! A game where you, the user, guesses a number {happy_face}!\")\n player = input(\"What is your name? \")\n ver_1: str = \"In version one, you guess a number between 1-10.\"\n ver_2: str = \"In version two, you guess a number between 1-20!\"\n point_rules: str = \"The less attempts it takes you to guess the number, the more points you get!\"\n print(f\"{player}, there are two versions for you to play.\")\n print(f\"{ver_1} {ver_2}\")\n print(f\"{point_rules}\")\n return None\n\n\n# custom function 1\ndef game(a: int) -> int:\n \"\"\"Generates a random integer 1-10 and returns the final point value to the function.\"\"\"\n attempts: int = 1\n a = 0\n i = 100\n answer: int = randint(1, 10)\n \n while attempts < i: \n user_guess: int = int(input(f\"Take a guess {player}: \"))\n if user_guess != answer:\n print(f\"Incorrect, {player}. Try again.\")\n attempts += 1\n else: \n print(f\"Correct, {player} you guessed the correct number in {attempts} attempts.\")\n break\n if attempts <= 5:\n a += 20\n elif attempts > 5:\n a += 10\n print(f\"{player}, you have received {a} points.\")\n return a\n\n\n# custom function 2\ndef other_game(a: int) -> int:\n \"\"\"Guess the number between 1-20, outputs the updated points value.\"\"\"\n attempts: int = 1\n i = 100\n answer: int = randint(1, 20)\n a = 0\n while attempts < i: \n user_guess: int = int(input(\"Take a guess: \"))\n if user_guess != answer: \n print(f\"Incorrect, {player}. Try again.\")\n attempts += 1\n else:\n print(f\"Correct, {player} you guessed the correct number in {attempts} attempts.\")\n break\n if attempts <= 5: \n a += 40\n elif attempts > 5 and attempts <= 10:\n a += 30\n elif attempts > 10 and attempts <= 15:\n a += 20\n else:\n a += 10\n print(f\"{player}, you have received {a} points.\")\n return a\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"projects/cyoa.py","file_name":"cyoa.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"415849763","text":"import pygame\nimport sys\nimport GridModel\nimport math\nfrom pygame.locals import *\n\n# Config\nwindowCaption = \"Game of Life - David Samuelson\"\ncolorAlive = pygame.Color(0, 0, 0)\ncolorDead = pygame.Color(255, 255, 255)\ngridSize = (100, 100) # Size in Cells\ncellSize = 10 #Size in Pixels\nfps = 4\n\n\ndef drawGridModel(window, grid):\n\tfor x in range(grid.getWidth()):\n\t\tfor y in range(grid.getHeight()):\n\t\t\trect = pygame.Rect(x * cellSize, y * cellSize, cellSize, cellSize)\n\t\t\tcolor = colorAlive if grid.getCell(x, y) else colorDead\n\t\t\tpygame.draw.rect(window, color, rect)\n\ndef main():\n\tgrid = GridModel.createRandomGrid(gridSize[0], gridSize[1])\n\n\tpygame.init()\n\tfpsClock = pygame.time.Clock()\n\t\n\twindowDimensions = (gridSize[0] * cellSize, gridSize[1] * cellSize)\n\twindow = pygame.display.set_mode(windowDimensions)\n\tpygame.display.set_caption(windowCaption)\n\n\tpaused = True\n\t\t\t\n\twhile True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tsys.exit()\n\t\t\telif event.type == MOUSEBUTTONDOWN:\n\t\t\t\tif not paused:\n\t\t\t\t\tpaused = True\n\t\t\t\tmouseX, mouseY = event.pos\n\t\t\t\tx = int(math.floor(mouseX / cellSize))\n\t\t\t\ty = int(math.floor(mouseY / cellSize))\n\t\t\t\tgrid.toggleCell(x, y)\n\t\t\t\tdrawGridModel(window, grid)\n\t\t\t\tpygame.display.update()\n\t\t\telif event.type == KEYDOWN:\n\t\t\t\tif event.key == K_SPACE:\n\t\t\t\t\tpaused = False\n\n\t\tif not paused:\n\t\t\tdrawGridModel(window, grid)\n\t\t\tpygame.display.update()\n\t\t\tgrid.step()\n\t\t\tfpsClock.tick(fps)\n\nmain()","sub_path":"GameOfLife.py","file_name":"GameOfLife.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"449273870","text":"import cv2\nimport os\nimport argparse\n\n\ndef labelDicFromFile(name):\n label_dic = {}\n with open(name) as f:\n for line in f:\n (val, key) = line.split()\n label_dic[key] = int(val)\n return label_dic\n\ndef dirToVideoLabel(data_dir, label_dic):\n labels = []\n filenames = []\n for label_name in os.listdir(data_dir):\n label_dir = os.path.join(data_dir, label_name)\n for video in os.listdir(label_dir):\n videoFile = os.path.join(label_dir, video)\n filenames.append(videoFile)\n labels.append(int(label_dic[label_name]) - 1)\n return filenames, labels\n\n\n\ndef loadPaths(data_dir=\"/data/nvidia-docker/data\", dataset='UCF-101', train_set_number='all', test_set_number='all'):\n \"\"\"\n Load the data\n\n Arguments:\n dataset -- the name of the dataset\n train_set_number -- '1', '2', '3' or 'all'\n test_set_number -- '1', '2', '3' or 'all'\n \"\"\"\n\n # TODO: Add a check with some warning message if the dataset is not found\n res = {\n \"train\": {\n \"paths\": [],\n \"labelnames\": [],\n \"labels\": []\n },\n \"test\": {\n \"paths\": [],\n \"labelnames\": [],\n \"labels\": []\n }\n }\n ucf_lists = os.path.join(data_dir,'ucfTrainTestlist')\n ucf101 = os.path.join(data_dir,'UCF-101')\n classMapFile = os.path.join(data_dir,\"ucfTrainTestlist/classInd.txt\")\n if (dataset == 'UCF-101'):\n label_dic = labelDicFromFile(classMapFile)\n train_set_names = []\n test_set_names = []\n if (train_set_number != 'all'):\n train_set_names.append('trainlist0{}.txt'.format(train_set_number))\n else:\n [train_set_names.append('trainlist0{}.txt'.format(i)) for i in range(1,4)]\n if (test_set_number != 'all'):\n test_set_names.append('testlist0{}.txt'.format(test_set_number))\n else:\n [test_set_names.append('testlist0{}.txt'.format(i)) for i in range(1,4)]\n\n for train_set_name in train_set_names:\n train_list = open('{}/{}'.format(ucf_lists,train_set_name), 'r')\n num = os.path.splitext(train_set_name)[0].split('list')[1]\n for line in train_list:\n filepath = line.split(' ')[0]\n label = filepath.split(\"/\")[0]\n res[\"train\"][\"paths\"].append(os.path.join(data_dir,'UCF-101',filepath))\n res[\"train\"][\"labelnames\"].append(label)\n res[\"train\"][\"labels\"].append(label_dic[label]-1)\n\n\n\n for test_set_name in test_set_names:\n test_list = open('{}/{}'.format(ucf_lists,test_set_name), 'r')\n num = os.path.splitext(test_set_name)[0].split('list')[1]\n # test_dir = '{}_test{}'.format(ucf101, num)\n for line in test_list:\n filepath = line[:-1]\n label = filepath.split(\"/\")[0]\n res[\"test\"][\"paths\"].append(os.path.join(data_dir,'UCF-101',filepath))\n res[\"test\"][\"labelnames\"].append(label)\n res[\"test\"][\"labels\"].append(label_dic[label]-1)\n return res\n# r = loadPaths()\n# for i in zip(r[\"train\"][\"labels\"],r[\"train\"][\"paths\"],r[\"train\"][\"labelnames\"]):\n# print(i)\n# trains\n# tests\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', nargs='?', const='UCF-101',\n default='UCF-101')\n parser.add_argument('--train_number', nargs = '?', const='all',\n default = 'all')\n parser.add_argument('--test_number', nargs = '?', const='all',\n default = 'all')\n args = parser.parse_args()\n\n dataset = args.dataset\n train_number = args.train_number\n test_number = args.test_number\n load_data(dataset, train_number, test_number)\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"405543381","text":"#!/usr/bin/env python\nfrom datetime import *\nfrom calendar import monthrange\nimport functools\nimport re\n\n#Constants list:\ndate_time_pattern = {\n# \n# full day, month, year\n\t\"day_month_year\":\n\t[\n\t\t\"ngày (\\\\d\\\\d?) tháng (\\\\d\\\\d?) năm (\\\\d\\\\d\\\\d?\\\\d?)\",\n\t\t\"ngày (\\\\d\\\\d?)[/-](\\\\d\\\\d?)[/-](\\\\d\\\\d\\\\d?\\\\d?)\",\n\t\t\"(\\\\d\\\\d?)[/-](\\\\d\\\\d?)[/-](\\\\d\\\\d\\\\d?\\\\d?)\"\n\t],\n# month, year\n\t\"month_year\":\n\t[\n\t\t\"tháng (\\\\d\\\\d?) năm (\\\\d\\\\d\\\\d?\\\\d?)\",\n\t\t\"tháng (\\\\d\\\\d?)[/-](\\\\d\\\\d\\\\d?\\\\d?)\",\n\t\t\"(\\\\d\\\\d?)[/-](\\\\d\\\\d\\\\d\\\\d)\"\n\t],\n\t\n# day, month\n\t\"day_month\":\n\t[\n\t\t\"ngày (\\\\d\\\\d?) tháng (\\\\d\\\\d?)\",\n\t\t\"ngày (\\\\d\\\\d?)[/-](\\\\d\\\\d?)\",\n\t\t\" (\\\\d\\\\d?)[/-](\\\\d\\\\d?)\"\n\t],\n\t\n# single day | month | year\n\t\"day\":\n\t[\n\t\t\"ngày (\\\\d\\\\d?)\"\n\t],\n\n\t\"month\":\n\t[\n\t\t\"tháng (\\\\d\\\\d?)\"\n\t],\n\t\"year\":\n\t[\n\t\t\"năm (\\\\d\\\\d\\\\d?\\\\d?)\"\n\t],\n\n#full hour, minute, second\n\t\"hour_minute_second\":\n\t[\n\t\t\"(\\\\d\\\\d?) giờ (\\\\d\\\\d?) phút (\\\\d\\\\d?) giây\",\n\t\t\"(\\\\d\\\\d?)[hg:](\\\\d\\\\d?)[mp:](\\\\d\\\\d?)[s]?\"\n\t],\n\n#hour, minute\n\t\"hour_minute\":\n\t[\n\t\t\"(\\\\d\\\\d?) giờ (\\\\d\\\\d?) phút\",\n\t\t\"(\\\\d\\\\d?)[hg:](\\\\d\\\\d?)[mp]?\"\n\t],\t\n\n\t#single hour \n\t\"hour\":\n\t[\n\t\t\"(\\\\d\\\\d?) giờ\",\n\t\t\"(\\\\d\\\\d?)[hg]\"\n\t]\n\t\n\t\n}\n\nlist_pattern_time_new = []\natomic = {\n\t\"head\": [\"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\"],\n\t\"navigate\": [\"next\", \"previous\"],\n\t\"next\": [\"tới\", \"sau\", \"kế\", \"tiếp\"],\n\t\"previous\": [\"trước\", \"vừa\", \"qua\"],\n\t\"week\": [\"tuần\", \"\"],\n\t\"monday\": [\"thứ hai\", \"thứ 2\"],\n\t\"tuesday\": [\"thứ ba\", \"thứ 3\"],\n\t\"wednesday\": [\"thứ tư\", \"thứ 4\"],\n\t\"thursday\": [\"thứ năm\", \"thứ 5\"],\n\t\"friday\": [\"thứ sáu\", \"thứ 6\"],\n\t\"saturday\": [\"thứ bảy\", \"thứ 7\"],\n\t\"sunday\": [\"chủ nhật\", \"cn\"]\n}\nadvance_time = {\n\t\"end_of_next_month\": [\"cuối tháng tới\", \"cuối tháng sau\", \"cuối tháng kế tiếp\",\"cuối tháng tiếp\"],\n\t\"end_of_next_year\": [\"cuối năm tới\", \"cuối năm sau\", \"cuối năm kế tiếp\", \"cuối năm tiếp\"],\n\t\"end_of_next_week\": [\"cuối tuần tới\", \"cuối tuần sau\", \"cuối tuần kế tiếp\", \"cuối tuần tiếp\"],\n\t\"monday_of_next_week\": [\"cuối tuần tới\", \"cuối tuần sau\", \"cuối tuần kế tiếp\", \"cuối tuần tiếp\"],\n\t\n\t\"end_of_previous_month\":[\"cuối tháng trước\", \"cuối tháng vừa\", \"cuối tháng qua\"],\n\t\"end_of_previous_year\":[\"cuối năm trước\", \"cuối năm vừa\", \"cuối năm ngoái\", \"cuối năm qua\"],\n\t\"end_of_previous_week\":[\"cuối tuần trước\", \"cuối tuần vừa\", \"cuối tuần qua\"],\n\t\"end_of_month_number\" : [\"cuối tháng (\\\\d\\\\d?)\", \"cuối tháng (một|giêng|hai|ba|tư|bốn|năm|sáu|bảy|tám|chín|mười|mười một|mười hai|chạp)\"],\n\t\"end_of_year_number\": [\"cuối năm (\\\\d\\\\d\\\\d\\\\d)\"],\n\t\"end_of_week\": [\"cuối tuần\"],\n\t\"end_of_month\": [\"cuối tháng\"],\n\t\"end_of_year\": [\"cuối năm\"],\n\n\t\"begin_of_next_month\": [\"đầu tháng tới\", \"đầu tháng sau\", \"đầu tháng kế tiếp\",\"đầu tháng tiếp\"],\n\t\"begin_of_next_year\": [\"đầu năm tới\", \"đầu năm sau\", \"đầu năm kế tiếp\", \"đầu năm tiếp\"],\n\t\"begin_of_next_week\": [\"đầu tuần tới\", \"đầu tuần sau\", \"đầu tuần kế tiếp\", \"đầu tuần tiếp\"],\n\t\"begin_of_previous_month\": [\"đầu tháng trước\", \"đầu tháng vừa\", \"đầu tháng qua\"],\n\t\"begin_of_previous_year\": [\"đầu năm trước\", \"đầu năm vừa\", \"đầu năm ngoái\", \"đầu năm qua\"],\n\t\"begin_of_previous_week\": [\"đầu tuần trước\", \"đầu tuần vừa\", \"đầu tuần qua\"],\n\t\"begin_of_month_number\" : [\"đầu tháng (\\\\d\\\\d?)\", \"đầu tháng (một|giêng|hai|ba|tư|bốn|năm|sáu|bảy|tám|chín|mười|mười một|mười hai|chạp)\"],\n\t\"begin_of_year_number\": [\"đầu năm (\\\\d\\\\d\\\\d\\\\d)\"],\n\t\"begin_of_week\": [\"đầu tuần\"],\n\t\"begin_of_month\": [\"đầu tháng\"],\n\t\"begin_of_year\": [\"đầu năm\"],\n\n\t\"middle_of_next_month\": [\"giữa tháng tới\", \"giữa tháng sau\", \"giữa tháng kế tiếp\",\"giữa tháng tiếp\"],\n\t\"middle_of_next_year\": [\"giữa năm tới\", \"giữa năm sau\", \"giữa năm kế tiếp\", \"giữa năm tiếp\"],\n\t\"middle_of_next_week\": [\"giữa tuần tới\", \"giữa tuần sau\", \"giữa tuần kế tiếp\", \"giữa tuần tiếp\"],\n\t\"middle_of_previous_month\": [\"giữa tháng trước\", \"giữa tháng vừa\", \"giữa tháng qua\"],\n\t\"middle_of_previous_year\": [\"giữa năm trước\", \"giữa năm vừa\", \"giữa năm ngoái\", \"giữa năm qua\"],\n\t\"middle_of_previous_week\": [\"giữa tuần trước\", \"giữa tuần vừa\", \"giữa tuần qua\"],\n\t\"middle_of_month_number\" : [\"giữa tháng (\\\\d\\\\d?)\", \"giữa tháng (một|giêng|hai|ba|tư|bốn|năm|sáu|bảy|tám|chín|mười|mười một|mười hai|chạp)\"],\n\t\"middle_of_year_number\": [\"giữa năm (\\\\d\\\\d\\\\d\\\\d)\"],\n\t\"middle_of_week\": [\"giữa tuần\"],\n\t\"middle_of_month\": [\"giữa tháng\"],\n\t\"middle_of_year\": [\"giữa năm\"],\n\n\t\"next_day\": [\"ngày mai\", \"sáng mai\", \"trưa mai\", \"tối mai\", \"chiều mai\", \"ngày sau\", \"hôm sau\", \"bữa sau\", \"1 ngày nữa\"],\n\t\"previous_day\": [\"hôm qua\", \"hôm trước\", \"hôm vừa\", \"ngày qua\"],\n\t\"double_next_day\": [\"ngày mốt\"],\n\t\"triple_next_day\": [\"ngày kia\"],\n\t\n\t\"number_next_day\": [\"(\\\\d\\\\d?) ngày nữa\", \"(\\\\d\\\\d?) ngày tới\", \"(\\\\d\\\\d?) ngày sắp tới\", \"(\\\\d\\\\d?) ngày sau\"],\n\t\"number_previous_day\":[\"(\\\\d\\\\d?) ngày trước\"]\n\n}\nmonth_mapping = {\n\t\"1\":\"1\", \"một\":\"1\",\"giêng\":\"1\",\n\t\"2\":\"2\", \"hai\":\"2\",\n\t\"3\":\"3\", \"ba\":\"3\",\n\t\"4\":\"4\", \"bốn\":\"4\", \"tư\":\"4\",\n\t\"5\":\"5\", \"năm\":\"5\",\n\t\"6\":\"6\", \"sáu\":\"6\",\n\t\"7\":\"7\", \"bảy\":\"7\",\n\t\"8\":\"8\", \"tám\":\"8\",\n\t\"9\":\"9\", \"chín\":\"9\",\n\t\"10\":\"10\", \"mười\":\"10\",\n\t\"11\":\"11\", \"mười một\":\"11\",\n\t\"12\":\"12\", \"mười hai\":\"12\", \"chạp\":\"12\"\n}\n\nfor day in atomic[\"head\"]:\n\tfor week in atomic[\"week\"]:\n\t\tif week != \"\":\n\t\t\tfor navigate in atomic[\"navigate\"]:\n\t\t\t\tadvance_time[\"{0}_of_{1}_week\".format(day, navigate)] = [\"{0} tuần {1}\".format(dayValue, navigateValue) for dayValue in atomic[day] for navigateValue in atomic[navigate]]\n\t\t\t\t# for dayValue in atomic[day]:\n\t\t\t\t# \tfor navigateValue in atomic[navigate]:\n\n\t\telse:\n\t\t\tfor navigate in atomic[\"navigate\"]:\n\t\t\t\tadvance_time[\"{0}_of_{1}_week\".format(day, navigate)] += [\"{0} {1}\".format(dayValue, navigateValue) for dayValue in atomic[day] for navigateValue in atomic[navigate]]\n\t\t\tadvance_time[\"{0}_of_week\".format(day)] = [\"{}\".format(dayValue) for dayValue in atomic[day]]\n\nadvance_time_range = {\n\t\"month\":{\n\t\t\"begin\": [10, 1, 5],\n\t\t\"middle\": [20, 11, 15],\n\t\t\"end\": {\n\t\t\t\"1\": [31, 21, 26],\"một\": [31, 21, 26],\"giêng\": [31, 21, 26],\n\t\t\t\"2\": [monthrange(int(datetime.today().year),2)[1], 21, 24],\"hai\": [monthrange(int(datetime.today().year),2)[1], 21, 24],\n\t\t\t\"3\": [31, 21, 26],\"ba\": [31, 21, 26],\n\t\t\t\"4\": [30, 21, 25],\"bốn\": [30, 21, 25],\"tư\": [30, 21, 25],\n\t\t\t\"5\": [31, 21, 26],\"năm\": [31, 21, 26],\n\t\t\t\"6\": [30, 21, 25],\"sáu\": [30, 21, 25],\n\t\t\t\"7\": [31, 21, 26],\"bảy\": [31, 21, 26],\n\t\t\t\"8\": [31, 21, 26],\"tám\": [31, 21, 26],\n\t\t\t\"9\": [30, 21, 25],\"chín\": [30, 21, 25],\n\t\t\t\"10\": [31, 21, 26],\"mười\": [31, 21, 26],\n\t\t\t\"11\": [30, 21, 25],\"mười một\": [30, 21, 25],\n\t\t\t\"12\": [31, 21, 26],\"mười hai\": [31, 21, 26],\"chạp\": [31, 21, 26]\n\t\t}\n\t},\n\t\"year\": {\n\t\t\"begin\": [4, 1, 2],\n\t\t\"middle\": [8, 5, 6],\n\t\t\"end\": [12, 9, 10]\n\t},\n\t# begin with the first day of week\n\t\"week\": {\n\t\t\"begin\": [1, 0, 0],\n\t\t\"middle\": [4, 2, 3],\n\t\t\"end\": [-1, 5, -1],\n\t\t\"monday\": [0, 0, 0],\n\t\t\"tuesday\": [1, 1, 1],\n\t\t\"wednesday\": [2, 2, 2],\n\t\t\"thursday\": [3, 3, 3],\n\t\t\"friday\": [4, 4, 4],\n\t\t\"saturday\": [5, 5, 5],\n\t\t\"sunday\": [-1, -1, -1]\n\t}\n}\n\nseparator_list = [\n# 1st priority\n\n\t\"bắt đầu.*?({0}).*?kết thúc.*?{1}\",\n\t\"khởi đầu.*?({0}).*?kết thúc.*?{1}\",\n# 2nd priority\n\t\"sáng.*?({0}).*?chiều.*?{1}\",\n\t\"sáng.*?({0}).*?trưa.*?{1}\",\n\t\"sáng.*?({0}).*?tối.*?{1}\",\n\t\"trưa.*?({0}).*?chiều.*?{1}\",\n\t\"trưa.*?({0}).*?tối.*?{1}\",\n\n\t\"từ.*?({0}).*?đến.*?{1}\",\n\t\"từ.*?({0}).*?tới.*?{1}\",\n# # 3rd priority\n# \t# \"từ (\"\n# \t\"({0}).*?đến.*?{1}\",\n# \t\"({0}).*?cho tới.*?{1}\",\n# \t\"từ.*?({0}).*?-.*?{1}\",\n# # 4th priority\n# \t\"({0}).*?-.*?{1}\"\n\n]\nclass ActivityDateTime:\n\tdef __init__(self, day=int(datetime.today().day), month=int(datetime.today().month), year=int(datetime.today().year), hour=0, minute=0, second=0):\n\t\tself.day = day\n\t\tself.month = month\n\t\tself.year = year\n\t\tself.hour = hour\n\t\tself.minute = minute\n\t\tself.second = second\n\t\tself.others = {\n\t\t\t\"day\": {\"priority\": 0, \"values\": []},\n\t\t\t\"month\": {\"priority\": 0, \"values\": []},\n\t\t\t\"year\": {\"priority\": 0, \"values\": []},\n\t\t\t\"hour\": {\"priority\": 0, \"values\": []},\n\t\t\t\"minute\": {\"priority\": 0, \"values\": []},\n\t\t\t\"second\": {\"priority\": 0, \"values\": []}\n\t\t}\n\tdef __getitem__(self, key):\n\t\treturn self.__getattribute__(key)\n\tdef __setitem__(self, key, value):\n\t\tself.__setattr__(key, value)\n\tdef extractAllValue(self):\n\t\t# print(\"{0}/{1}/{2} {3}:{4}:{5}\".format(self.day, self.month, self.year, self.hour, self.minute, self.second))\n\t\tprint(self.others)\n\t\treturn \"{0}/{1}/{2} {3}:{4}:{5}\".format(self.day, self.month, self.year, self.hour, self.minute, self.second)\n\tdef convertToUnix(self):\n\t\tdt = datetime(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second)\n\t\treturn int(dt.replace(tzinfo=timezone(timedelta(hours=7))).timestamp())\n\t\n\tdef validAndSetDay(self, dayString, priority=2):\n\t\tif priority <= self.others[\"day\"][\"priority\"]:\n\t\t\tself.others[\"day\"][\"values\"].append(dayString)\n\t\t\t\n\t\t\t# print(\"\\\"{}\\\" archived\".format(dayString))\n\t\t\treturn\n\t\tdayInt = int(dayString)\n\t\tif 1 <= dayInt <= 31:\n\t\t\tself.day = dayInt\n\t\t\tself.others[\"day\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid day!\")\n\tdef validAndSetMonth(self, monthString, priority=2):\n\t\tif priority <= self.others[\"month\"][\"priority\"]:\n\t\t\tself.others[\"month\"][\"values\"].append(monthString)\n\t\t\t\n\n\t\t\t# print(\"\\\"{}\\\" archived\".format(monthString))\n\t\t\treturn\n\t\tmonthInt = int(monthString)\n\t\tif 1 <= monthInt <= 12:\n\t\t\tself.month = monthInt\n\t\t\tself.others[\"month\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid month\")\n\tdef validAndSetYear(self, yearString, priority=2):\n\t\tif priority <= self.others[\"year\"][\"priority\"]:\n\t\t\tself.others[\"year\"][\"values\"].append(yearString)\n\t\t\t\n\n\t\t\t# print(\"\\\"{}\\\" archived\".format(yearString))\n\t\t\treturn\n\t\tyearInt = int(yearString)\n\t\tif MINYEAR <= yearInt <= MAXYEAR:\n\t\t\tself.year = yearInt\n\t\t\tself.others[\"year\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid year\")\n\tdef validAndSetHour(self, hourString, priority=2):\n\t\tif priority <= self.others[\"hour\"][\"priority\"]:\n\t\t\tself.others[\"hour\"][\"values\"].append(hourString)\n\t\t\t\n\n\t\t\t# print(\"\\\"{}\\\" archived\".format(hourString))\n\t\t\treturn\n\t\thourInt = int(hourString)\n\t\tif 0 <= hourInt < 24:\n\t\t\tself.hour = hourInt\n\t\t\tself.others[\"hour\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid hour\")\n\tdef validAndSetMinute(self, minuteString, priority=2):\n\t\tif priority <= self.others[\"minute\"][\"priority\"]:\n\t\t\tself.others[\"minute\"][\"values\"].append(minuteString)\n\t\t\t\n\n\t\t\t# print(\"\\\"{}\\\" archived\".format(minuteString))\n\t\t\treturn\n\t\tminuteInt = int(minuteString)\n\t\tif 0 <= minuteInt < 60:\n\t\t\tself.minute = minuteInt\n\t\t\tself.others[\"minute\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid minute\")\n\tdef validAndSetSecond(self, secondString, priority=2):\n\t\tif priority <= self.others[\"second\"][\"priority\"]:\n\t\t\tself.others[\"second\"][\"values\"].append(secondString)\n\t\t\t\n\n\t\t\t# print(\"\\\"{}\\\" archived\".format(secondString))\n\t\t\treturn\n\t\tsecondInt = int(secondString)\n\t\tif 0 <= secondInt < 60:\n\t\t\tself.second = secondInt\n\t\t\tself.others[\"second\"][\"priority\"] = priority\n\t\telse:\n\t\t\tprint(\">>>>>>>>>>>ERR: invalid second\")\n\nclass ActivityDateTimeToUnixFactory:\n\tdef constraintTwoTimestamp(self, activityDateTime1, activityDateTime2):\n\t\t#constraint day, month, year\n\t\tfor key in [\"day\", \"month\", \"year\"]:\n\t\t\tif activityDateTime1.others[key][\"priority\"] * activityDateTime2.others[key][\"priority\"] == 0:\n\t\t\t\tif activityDateTime1.others[key][\"priority\"] == 0:\n\t\t\t\t\tactivityDateTime1[key] = activityDateTime2[key]\n\t\t\t\telse:\n\t\t\t\t\tactivityDateTime2[key]= activityDateTime1[key]\n\tdef test_processRawDatetimeInput(self, inputDict):\n\t\tpassnum = 0\n\t\tfailnum = 0\n\t\tfor index, value in enumerate(inputDict):\n\t\t\tdatetimeObjects = self.processRawDatetimeInput(inputDict[index][\"rawDatetime\"])\n\t\t\toutput = \";\".join([datetimeObject.extractAllValue() for datetimeObject in datetimeObjects])\n\t\t\tif output == inputDict[index][\"expectedOutput\"]:\n\t\t\t\tprint(\"test case {0}: PASS\".format(index))\n\t\t\t\tpassnum += 1\n\t\t\t\t# print(\"utc: {}\".format(datetimeObject.convertToUnix()))\n\n\t\t\telse:\n\t\t\t\tfailnum += 1\n\t\t\t\tprint(\"test case {0}: FAIL\".format(index))\n\t\t\t\tprint(\"rawDatetime: {0}\\n expectedOutput: {1}\\n currentOutput: {2}\".format(inputDict[index][\"rawDatetime\"],\n\t\t\t\t\tinputDict[index][\"expectedOutput\"], output))\n\t\tprint(\"PASSED: {0}/{1}\".format(passnum, passnum + failnum))\n\t\t\n\tdef processRawDatetimeInput(self, rawDatetime):\n\t\trawValueSplitted = self.splitRawValues(rawDatetime)\n\t\tprint(rawValueSplitted)\n\t\tif len(rawValueSplitted) > 1:\n\t\t\tslot1 = self.processSingleDatetimeInput(rawValueSplitted[0], 0)\n\t\t\tslot2 = self.processSingleDatetimeInput(rawValueSplitted[1], 1)\n\t\t\t# print(slot1.extractAllValue())\n\t\t\t# print(slot2.extractAllValue())\n\t\t\tself.constraintTwoTimestamp(slot1, slot2)\n\t\t\treturn [slot1, slot2]\n\t\t\t# activityDateTime = self.processSingleDatetimeInput(rawDatetime)\n\t\telif len(rawValueSplitted) == 1:\n\t\t\tslot1 = self.processSingleDatetimeInput(rawValueSplitted[0], 2)\n\t\t\t# print(slot1.extractAllValue())\n\t\t\treturn [slot1]\n\t\t\t\n\t\t\t# unixFormat = self.convertToUnixFormat(activityDateTime)\n\t\t\t# return unixFormat\n\t\telse:\n\t\t\tprint(\"ERROR: cannot extract any value\")\n\t\t\treturn []\n\n\tdef splitRawValues(self, rawDatetime):\n\t\tglobal list_pattern_time_new\n\t\tdate_time_pattern_joined = \"(({0}).*)+\".format(\"|\".join([pattern for key in date_time_pattern for pattern in date_time_pattern[key]] + [pattern for key in advance_time for pattern in advance_time[key]]))\n# print(len(list_pattern_time_new))\n\t\tfor separator in separator_list:\n\t\t\t# date_time_pattern = single_date_regex_list + single_time_regex_list\n\n\t\t\t# print(date_time_pattern_joined)\n\t\t\tfull_pattern = separator.format(date_time_pattern_joined, date_time_pattern_joined)\n\t\t\t# print(full_pattern.split(\"|\"))\n\t\t\t# list_pattern_time_new = full_pattern.split(\"|\")\n\t\t\t# print(len(list_pattern_time_new))\n\t\t\t# print(full_pattern)\n\t\t\tseparator_search_result = re.findall(full_pattern, rawDatetime, re.IGNORECASE)\n\t\t\t# print(separator_search_result)\n\t\t\tif len(separator_search_result) > 0:\n\t\t\t\t# print(full_pattern)\n\t\t\t\tprint(separator_search_result)\n\n\t\t\t\tsecondIdx = functools.reduce(lambda x,y: x + y, list(map(lambda x: (\" \".join(x[1])).count('(') , {**date_time_pattern, **advance_time}.items())))\n\t\t\t\tprint(secondIdx)\n\t\t\t\t# print(separator_search_result[0][0])\n\t\t\t\t# print(separator_search_result[0][secondIdx + 3])\n\t\t\t\treturn [separator_search_result[0][0], separator_search_result[0][secondIdx + 3]]\n\t\t\t# print(\"({0})\".format(date_time_pattern_joined))\n\t\t\n\t\tsingle_search_result = re.findall(\"({0})\".format(date_time_pattern_joined), rawDatetime, re.IGNORECASE)\n\t\t# print(single_search_result)\n\t\tif len(single_search_result) > 0:\n\t\t\tprint(\"SINGLE DETECTED: {}\".format(single_search_result))\n\t\t\treturn [single_search_result[0][0]]\n\t\telse:\n\t\t\t# print(\"Trying advance pattern...\")\n\t\t\t# advance_datetime_pattern_joined = \"(({0}).*)+\".format(\"|\".join([pattern for key in advance_time for pattern in advance_time[key]]))\n\t\t\t# for separator in separator_list:\n\t\t\t# \tadvance_datetime_full_pattern = separator.format(advance_datetime_pattern_joined, advance_datetime_pattern_joined)\n\t\t\t# \tadvance_datetime_full_result = re.findall(advance_datetime_full_pattern, rawDatetime, re.IGNORECASE)\n\t\t\t# \tif len(advance_datetime_full_result) > 0:\n\t\t\t# \t\tsecondIdx = functools.reduce(lambda x,y: x + y, list(map(lambda x: len(x[1]) if \"number\" in x[0].split(\"_\") else 0, advance_time.items())))\n\t\t\t# \t\t# print(\"secondIdx: {}\".format(secondIdx))\n\t\t\t# \t\tprint(advance_datetime_full_result)\n\t\t\t# \t\treturn [advance_datetime_full_result[0][0], advance_datetime_full_result[0][secondIdx + 3]]\n\t\t\t# advance_datetime_single_result = re.findall(\"({0})\".format(advance_datetime_pattern_joined), rawDatetime, re.IGNORECASE)\n\t\t\t# if len(advance_datetime_single_result) > 0:\n\t\t\t# \tprint(advance_datetime_single_result)\n\t\t\t# \treturn [advance_datetime_single_result[0][0]]\n\t\t\treturn []\t\t\n\t\t\n\n\t\t\n\n\t\t\t# if (search_result):\n\t\t\t# \tprint(search_result)\n\t\t\t# \t# print(search_result.group(0))\n\t\t\t# \tprint(search_result.group(1).split())\n\t\t\t# \tprint(search_result.group(2).split())\n\t\t\t# \treturn\n\t\t\t# else:\n\t\t\t# \tprint(\"not found pattern\")\t\n\t\t\t# for date_pattern in single_date_regex_list:\n\t\t\t\t\n\t\t\t# \tfor time_pattern in single_time_regex_list:\n\t\t\t\t\t\n\tdef test_splitRawValues(self, inputDict):\n\t\tpassnum = 0\n\t\tfailnum = 0\n\t\tfor index, value in enumerate(inputDict):\n\t\t\toutput = \";\".join(self.splitRawValues(inputDict[index][\"rawDatetime\"]))\n\t\t\t\n\t\t\tif output == inputDict[index][\"expectedOutput\"]:\n\t\t\t\tprint(\"test case {0}: PASS\".format(index))\n\t\t\t\tpassnum += 1\n\t\t\telse:\n\t\t\t\tfailnum += 1\n\t\t\t\tprint(\"test case {0}: FAIL\".format(index))\t\n\t\t\t\tprint(\"rawDatetime: {0}\\n expectedOutput: {1}\\n currentOutput: {2}\".format(inputDict[index][\"rawDatetime\"],\n\t\t\t\t\tinputDict[index][\"expectedOutput\"], output))\t\t\n\t\tprint(\"PASSED: {0}/{1}\".format(passnum, passnum + failnum))\n\tdef test_processSingleDatetimeInput(self, inputDict):\n\t\tpassnum = 0\n\t\tfailnum = 0\n\t\tfor index, value in enumerate(inputDict):\n\t\t\tdatetimeObject = self.processSingleDatetimeInput(inputDict[index][\"rawDatetime\"])\n\t\t\toutput = datetimeObject.extractAllValue()\n\t\t\tif output == inputDict[index][\"expectedOutput\"]:\n\t\t\t\tpassnum += 1\n\t\t\t\tprint(\"test case {0}: PASS\".format(index))\n\t\t\t\tprint(\"utc: {}\".format(datetimeObject.convertToUnix()))\n\n\t\t\telse:\n\t\t\t\tfailnum += 1\n\t\t\t\tprint(\"test case {0}: FAIL\".format(index))\n\t\t\t\tprint(\"rawDatetime: {0}\\n expectedOutput: {1}\\n currentOutput: {2}\".format(inputDict[index][\"rawDatetime\"],\n\t\t\t\t\tinputDict[index][\"expectedOutput\"], output))\n\t\tprint(\"PASSED: {0}/{1}\".format(passnum, passnum + failnum))\n\n\tdef processSingleDatetimeInput(self, datetime, boundIdx):\n\t\tactivityDateTime = ActivityDateTime()\n\t\t\n\t\tself.catchAdvancePattern(datetime, activityDateTime, boundIdx)\n\n\t\tphraseOneOutput = self.phraseOne(datetime, activityDateTime)\n\t\tprint(\"phrase 1 output: {}\".format(phraseOneOutput))\n\t\t\n\t\tphraseTwoOutput = self.phraseTwo(phraseOneOutput, activityDateTime)\n\t\tprint(\"phrase 2 output: {}\".format(phraseTwoOutput))\n\n\t\tphraseThreeOutput = self.phraseThree(phraseTwoOutput, activityDateTime)\n\t\tprint(\"phrase 3 output: {}\".format(phraseThreeOutput))\n\t\t# activityDateTime.extractAllValue()\n\t\treturn activityDateTime\n\t\t\n\tdef test_catchAdvancePattern(self, inputDict):\n\t\tpassnum = 0\n\t\tfailnum = 0\n\t\tfor index, value in enumerate(inputDict):\n\t\t\tactivityDateTime = ActivityDateTime()\n\t\t\n\t\t\tself.catchAdvancePattern(inputDict[index][\"rawDatetime\"], activityDateTime, inputDict[index][\"boundIdx\"])\n\t\t\t# datetimeObject = self.processSingleDatetimeInput(inputDict[index][\"rawDatetime\"])\n\t\t\toutput = activityDateTime.extractAllValue()\n\t\t\tif output == inputDict[index][\"expectedOutput\"]:\n\t\t\t\tpassnum += 1\n\t\t\t\tprint(\"test case {0}: PASS\".format(index))\n\t\t\t\tprint(\"utc: {}\".format(activityDateTime.convertToUnix()))\n\n\t\t\telse:\n\t\t\t\tfailnum += 1\n\t\t\t\tprint(\"test case {0}: FAIL\".format(index))\n\t\t\t\tprint(\"rawDatetime: {0}\\n expectedOutput: {1}\\n currentOutput: {2}\".format(inputDict[index][\"rawDatetime\"],\n\t\t\t\t\tinputDict[index][\"expectedOutput\"], output))\n\t\tprint(\"PASSED: {0}/{1}\".format(passnum, passnum + failnum))\n\t\t\n\n\tdef catchAdvancePattern(self, rawDatetime, activityDateTime, boundIdx):\n\t\tcurrentDatetime = datetime.today() \n\t\tcurrentDay = int(currentDatetime.day)\n\t\tcurrentMonth = int(currentDatetime.month)\n\t\tcurrentYear = int(currentDatetime.year)\n\t\tfor key, advancePatternList in advance_time.items():\n\t\t\t# TODO: find the pattern in advance pattern list\n\t\t\t# if find, handle key: keyNameList = key.split(\"_\")\n\t\t\tfor advancePattern in advancePatternList:\n\t\t\t\tadvance_result = re.findall(advancePattern, rawDatetime, re.IGNORECASE)\n\t\t\t\tif advance_result:\n\t\t\t\t\tkeyNameList = key.split(\"_\")\n\n\t\t\t\t\t# if \"month\" exists in keyNameList:\n\t\t\t\t\tif \"month\" in keyNameList:\n\t\t\t\t\t\tif \"next\" in keyNameList:\n\t\t\t\t\t\t\tif currentMonth + 1 < 13: \n\t\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(currentMonth + 1, priority=1) \n\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(1, priority=1)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\telif \"previous\" in keyNameList:\n\t\t\t\t\t\t\tif currentMonth - 1 > 0: \n\t\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(currentMonth - 1, priority=1) \n\t\t\t\t\t\t\telse: \n\t\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(12, priority=1)\n\t\t\t\t\t\telif \"number\" in keyNameList and advance_result[0] in month_mapping.keys():\n\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(month_mapping[advance_result[0]], priority=1)\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif keyNameList[0] == \"end\":\n\t\t\t\t\t\t\tactivityDateTime.validAndSetDay(advance_time_range[\"month\"][keyNameList[0]][str(activityDateTime.month)][boundIdx], priority=1)\t\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetDay(advance_time_range[\"month\"][keyNameList[0]][boundIdx], priority=1)\n\t\t\t\t\telif \"year\" in keyNameList:\n\t\t\t\t\t\tif \"next\" in keyNameList:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetYear(currentYear + 1, priority=1)\n\t\t\t\t\t\telif \"previous\" in keyNameList:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetYear(currentYear - 1, priority=1)\n\t\t\t\t\t\telif \"number\" in keyNameList:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetYear(advance_result[0], priority=1)\n\n\n\t\t\t\t\t\tactivityDateTime.validAndSetMonth(advance_time_range[\"year\"][keyNameList[0]][boundIdx], priority=1)\n\n\t\t\t\t\telif \"week\" in keyNameList:\n\t\t\t\t\t\tweek = int(datetime.today().isocalendar()[1]) - 1\n\t\t\t\t\t\tif \"next\" in keyNameList:\n\t\t\t\t\t\t\tweek += 1\n\t\t\t\t\t\telif \"previous\" in keyNameList:\n\t\t\t\t\t\t\tweek -= 1\n\n\t\t\t\t\t\tdayOfWeek = 1\n\t\t\t\t\t\tnewDate = datetime.strptime(\"{0}-W{1}-{2}\".format(currentYear, week, dayOfWeek + advance_time_range[\"week\"][keyNameList[0]][boundIdx]),\"%Y-W%W-%w\")\n\t\t\t\t\t\tactivityDateTime.validAndSetDay(newDate.day, priority=1)\n\t\t\t\t\t\tif int(newDate.month) != currentMonth:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(newDate.month, priority=1)\n\t\t\t\t\t\tif int(newDate.year) != currentYear:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetYear(newDate.year, priority=1)\n\t\t\t\t\telif \"day\" in keyNameList:\n\t\t\t\t\t\tnumOfDays = 1\n\t\t\t\t\t\tnewDate = currentDatetime\n\t\t\t\t\t\tif \"double\" in keyNameList:\n\t\t\t\t\t\t\tnumOfDays = 2\n\t\t\t\t\t\telif \"triple\" in keyNameList:\n\t\t\t\t\t\t\tnumOfDays = 3\n\t\t\t\t\t\telif \"number\" in keyNameList:\n\t\t\t\t\t\t\tnumOfDays = int(advance_result[0])\n\t\t\t\t\t\t\n\t\t\t\t\t\tif \"next\" in keyNameList:\n\t\t\t\t\t\t\tnewDate = newDate + timedelta(days=numOfDays)\n\t\t\t\t\t\telif \"previous\" in keyNameList:\n\t\t\t\t\t\t\tnewDate = newDate - timedelta(days=numOfDays)\n\n\t\t\t\t\t\tactivityDateTime.validAndSetDay(newDate.day, priority=1)\n\t\t\t\t\t\tif int(newDate.month) != currentMonth:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetMonth(newDate.month, priority=1)\n\t\t\t\t\t\tif int(newDate.year) != currentYear:\n\t\t\t\t\t\t\tactivityDateTime.validAndSetYear(newDate.currentYear, priority=1)\n\n\n\t\t\t\t# if \"next\" in keyNameList:\n\t\t\t\t\t# change month += 1\n\n\t\t\t\t# elif \"previous\" in keyNameList:\n\t\t\t\t\t# change month -= 1\n\t\t\t\t# else:\n\t\t\t\t\t# pass\n\t\t\t\t# # change day by lookup in advance_time_range[\"month\"][keyNameList[0]]\n\n\n\t\t\t# if \"year\" in keyNameList:\n\n\n\t\t\t# if \"week\" in keyNameList:\n\t\t\t\t# if \"next\" in keyNameList:\n\t\t\t\t\t\t# get week by current datetime\n\t\t\t\t\t\t# increase week\n\t\t\t\t\t\t# convert to new datetime\n\t\t\t\t\t\t# set new day\n\tdef phraseOne(self, datetime, activityDateTime):\n\t\t# find all full pattern: day-month-year, hour-minute-second\n\t\tinputDatetime = datetime\n\n\t\t# for full day-month-year\n\t\tfor pattern in date_time_pattern[\"day_month_year\"]:\n\t\t\tdate_full_pattern = \"({0})\".format(pattern)\n\t\t\tdate_full_result = re.findall(date_full_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(date_full_result)\n\t\t\tif date_full_result:\n\t\t\t\tfor result in date_full_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\n\t\t\t\t\tactivityDateTime.validAndSetDay(result[1])\n\t\t\t\t\tactivityDateTime.validAndSetMonth(result[2])\n\t\t\t\t\tactivityDateTime.validAndSetYear(result[3])\n\n\t\t\t\tbreak\n\n\t\t# for full hour-minute-second\n\t\t\n\t\tfor pattern in date_time_pattern[\"hour_minute_second\"]:\n\t\t\ttime_full_pattern = \"({0})\".format(pattern)\n\t\t\ttime_full_result = re.findall(time_full_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(time_full_result)\n\t\t\tif time_full_result:\n\t\t\t\tfor result in time_full_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\n\t\t\t\t\tactivityDateTime.validAndSetHour(result[1])\n\t\t\t\t\tactivityDateTime.validAndSetMinute(result[2])\n\t\t\t\t\tactivityDateTime.validAndSetSecond(result[3])\n\n\t\t\t\tbreak\n\n\t\treturn inputDatetime\n\n\tdef phraseTwo(self, datetime, activityDateTime):\n\t\tinputDatetime = datetime\n\n\t\t# for month-year\n\t\tfor pattern in date_time_pattern[\"month_year\"]:\n\t\t\tmonth_year_pattern = \"({0})\".format(pattern)\n\t\t\tmonth_year_result = re.findall(month_year_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(date_full_result)\n\t\t\tif month_year_result:\n\t\t\t\tfor result in month_year_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\t\t\t\t\n\t\t\t\t\tactivityDateTime.validAndSetMonth(result[1])\n\t\t\t\t\tactivityDateTime.validAndSetYear(result[2])\n\n\t\t\t\tbreak\n\n\t\t# for day-month\n\t\tfor pattern in date_time_pattern[\"day_month\"]:\n\t\t\tday_month_pattern = \"({0})\".format(pattern)\n\t\t\tday_month_result = re.findall(day_month_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(date_full_result)\n\t\t\tif day_month_result:\n\t\t\t\tfor result in day_month_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\t\n\t\t\t\t\tactivityDateTime.validAndSetDay(result[1])\n\t\t\t\t\tactivityDateTime.validAndSetMonth(result[2])\n\n\t\t\t\tbreak\n\n\t\t# for full hour-minute\n\t\t\n\t\tfor pattern in date_time_pattern[\"hour_minute\"]:\n\t\t\ttime_full_pattern = \"({0})\".format(pattern)\n\t\t\ttime_full_result = re.findall(time_full_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(time_full_result)\n\t\t\tif time_full_result:\n\t\t\t\tfor result in time_full_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\n\t\t\t\t\tactivityDateTime.validAndSetHour(result[1])\n\t\t\t\t\tactivityDateTime.validAndSetMinute(result[2])\n\t\t\t\t\n\n\t\t\t\tbreak\n\n\t\treturn inputDatetime\n\n\tdef phraseThree(self, datetime, activityDateTime):\n\t\tinputDatetime = datetime\n\n\t\t# for year\n\t\tfor pattern in date_time_pattern[\"year\"]:\n\t\t\tyear_pattern = \"({0})\".format(pattern)\n\t\t\tyear_result = re.findall(year_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(date_full_result)\n\t\t\tif year_result:\n\t\t\t\tfor result in year_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\t\n\t\t\t\t\tactivityDateTime.validAndSetYear(result[1])\n\n\t\t\t\tbreak\n\n\t\t# for month\n\t\tfor pattern in date_time_pattern[\"month\"]:\n\t\t\tmonth_pattern = \"({0})\".format(pattern)\n\t\t\tmonth_result = re.findall(month_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t\n\t\t\tif month_result:\n\t\t\t\tfor result in month_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\t\n\t\t\t\t\tactivityDateTime.validAndSetMonth(result[1])\n\n\t\t\t\tbreak\n\t\t# for day\n\t\tfor pattern in date_time_pattern[\"day\"]:\n\t\t\tday_pattern = \"({0})\".format(pattern)\n\t\t\tday_result = re.findall(day_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t\n\t\t\tif day_result:\n\t\t\t\tfor result in day_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\t\n\t\t\t\t\tactivityDateTime.validAndSetDay(result[1])\n\n\t\t\t\tbreak\n\t\t# for hour\n\t\t\n\t\tfor pattern in date_time_pattern[\"hour\"]:\n\t\t\thour_pattern = \"({0})\".format(pattern)\n\t\t\thour_result = re.findall(hour_pattern, inputDatetime, re.IGNORECASE)\n\t\t\t# print(time_full_result)\n\t\t\tif hour_result:\n\t\t\t\t\n\t\t\t\tfor result in hour_result:\n\t\t\t\t\tinputDatetime = inputDatetime.replace(result[0], \"\")\n\t\t\t\t\tactivityDateTime.validAndSetHour(result[1])\n\t\t\t\t\n\t\t\t\tbreak\n\n\t\treturn inputDatetime\n\nfactory = ActivityDateTimeToUnixFactory()\n\nimport json\n\n# \n\n# factory.test_splitRawValues(\n# \t\t[\n# \t\t\t{\"rawDatetime\":\"từ 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ 9h30-10h30 ngày 24/12/2019 - 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ 9h30-10h30 ngày 24/12/2019-16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ khung giờ 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ ngày 24/12/2019 khung giờ 9h30-10h30 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"ngày 24/12/2019 khung giờ 9h30-10h30 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ thứ năm lúc 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"từ một ngày thứ năm lúc 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"vào lúc 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"vào lúc 9h30-10h30 ngày 24/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian dự thi: vào lúc 9h30-10h30 ngày 24/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30 ngày 24/12/2019\", \"expectedOutput\":\"9g30 ngày 24/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: buổi sáng 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019, buổi ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: buổi sáng thứ năm 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019, buổi ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: buổi sáng từ 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019, buổi ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: sáng từ 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019, buổi ;16h ngày 25/12/2019\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: bắt đầu từ 9h30-10h30 ngày 24/12/2019 và sau đó kết thúc vào 16h ngày 25/12/2019\", \"expectedOutput\":\"9h30-10h30 ngày 24/12/2019 và sau đó ;16h ngày 25/12/2019\"}\n\n# \t\t]\n# \t)\n\n\n# factory.test_processSingleDatetimeInput(\n# \t[\n# \t\t{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30 ngày 24/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0\"},\n# \t\t{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30 - 10g ngày 24/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0\"},\n# \t\t{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30-10g ngày 24/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0\"},\n# \t\t{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30-10g ngày 24 và 8h ngày 25/12/2019\", \"expectedOutput\":\"25/12/2019 9:30:0\"}\n\n\n# \t])\n\n# factory.test_catchAdvancePattern(\n# \t[\n# \t\t\t{\"rawDatetime\":\"thời gian vào cuối tháng này\", \"boundIdx\": 0, \"expectedOutput\":\"31/{0}/{1} 0:0:0\".format(datetime.today().month, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng tới\", \"boundIdx\": 0, \"expectedOutput\":\"30/{0}/{1} 0:0:0\".format(int(datetime.today().month) + 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng tới\", \"boundIdx\": 1, \"expectedOutput\":\"21/{0}/{1} 0:0:0\".format(int(datetime.today().month) + 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng tới\", \"boundIdx\": 2, \"expectedOutput\":\"25/{0}/{1} 0:0:0\".format(int(datetime.today().month) + 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng 2\", \"boundIdx\": 0, \"expectedOutput\":\"29/2/{0} 0:0:0\".format(datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tháng tới\", \"boundIdx\": 0, \"expectedOutput\":\"10/{0}/{1} 0:0:0\".format(int(datetime.today().month) + 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tháng tư\", \"boundIdx\": 0, \"expectedOutput\":\"10/4/{0} 0:0:0\".format(datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào giữa tháng chạp\", \"boundIdx\": 0, \"expectedOutput\":\"20/12/{0} 0:0:0\".format(datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tháng chạp\", \"boundIdx\": 0, \"expectedOutput\":\"10/12/{0} 0:0:0\".format(datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng trước\", \"boundIdx\": 0, \"expectedOutput\":\"30/{0}/{1} 0:0:0\".format(int(datetime.today().month) - 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tháng vừa qua\", \"boundIdx\": 0, \"expectedOutput\":\"30/{0}/{1} 0:0:0\".format(int(datetime.today().month) - 1, datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian diễn ra vào đầu năm nay\", \"boundIdx\": 0, \"expectedOutput\":\"{0}/4/{1} 0:0:0\".format(int(datetime.today().day), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian diễn ra vào đầu năm ngoái\", \"boundIdx\": 0, \"expectedOutput\":\"{0}/4/{1} 0:0:0\".format(int(datetime.today().day), int(datetime.today().year) - 1)}\n# \t\t\t,{\"rawDatetime\":\"thời gian diễn ra vào đầu năm tới\", \"boundIdx\": 0, \"expectedOutput\":\"{0}/4/{1} 0:0:0\".format(int(datetime.today().day), int(datetime.today().year) + 1)}\n# \t\t\t,{\"rawDatetime\":\"thời gian diễn ra vào đầu năm tới\", \"boundIdx\": 1, \"expectedOutput\":\"{0}/1/{1} 0:0:0\".format(int(datetime.today().day), int(datetime.today().year) + 1)}\n# \t\t\t,{\"rawDatetime\":\"thời gian diễn ra vào giữa năm tới\", \"boundIdx\": 1, \"expectedOutput\":\"{0}/5/{1} 0:0:0\".format(int(datetime.today().day), int(datetime.today().year) + 1)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tuần sau\", \"boundIdx\": 0, \"expectedOutput\":\"19/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tuần sau\", \"boundIdx\": 1, \"expectedOutput\":\"18/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào cuối tuần sau\", \"boundIdx\": 0, \"expectedOutput\":\"24/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tuần này\", \"boundIdx\": 0, \"expectedOutput\":\"12/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào đầu tuần trước\", \"boundIdx\": 0, \"expectedOutput\":\"5/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian vào 5 ngày tới\", \"boundIdx\": 0, \"expectedOutput\":\"18/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào ngày mai\", \"boundIdx\": 0, \"expectedOutput\":\"14/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào thứ 5\", \"boundIdx\": 0, \"expectedOutput\":\"14/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào thứ 5 tuần sau\", \"boundIdx\": 0, \"expectedOutput\":\"21/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào thứ ba tuần trước\", \"boundIdx\": 0, \"expectedOutput\":\"5/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào chủ nhật tuần này\", \"boundIdx\": 0, \"expectedOutput\":\"17/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n# \t\t\t,{\"rawDatetime\":\"thời gian bắt đầu vào thứ 5 tuần kế nhé\", \"boundIdx\": 0, \"expectedOutput\":\"21/{0}/{1} 0:0:0\".format(int(datetime.today().month), datetime.today().year)}\n\n# \t]\n# )\n\n# result = factory.processRawDatetimeInput(\"ngọc trinh\")\nresult_1 = factory.processRawDatetimeInput(\"14/5/2020\")\nresult_2 = factory.processRawDatetimeInput(\"14/5/2020 13:23:43\")\n\n# time = [obj.extractAllValue() for obj in result]\nunix_1 = [obj.convertToUnix() for obj in result_1]\nunix_2 = [obj.convertToUnix() for obj in result_2]\nprint(unix_1)\nprint(unix_2)\n\n\ndef convert_atom_time(time_str):\n\tlst_result_obj = factory.processRawDatetimeInput(time_str)\n\tresult_unix = None\n\tif lst_result_obj != []:\n\t\tresult_unix = [obj.convertToUnix() for obj in lst_result_obj]\n\t\treturn result_unix[0]\n\treturn result_unix\n\nprint(convert_atom_time(\"14/5/2020\"))\n\n# import datetime\n# print(\n# datetime.datetime.fromtimestamp(\n# unix[0]\n# ).strftime('%Y-%m-%d %H:%M:%S')\n# )\n# print(unix)\n\n# factory.test_processRawDatetimeInput(\n# \t[\n# \t\t\t{\"rawDatetime\":\"từ 9h30-10h30 ngày 24/12/2019 đến 16h ngày 25/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;25/12/2019 16:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian dự thi: vào lúc 9g30 ngày 24/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: buổi sáng 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;25/12/2019 16:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: sáng từ 9h30-10h30 ngày 24/12/2019, buổi chiều: 16h ngày 25/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;25/12/2019 16:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: bắt đầu từ 9h30-10h30 ngày 24/12/2019 và sau đó kết thúc vào 16h ngày 25/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;25/12/2019 16:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: 9h sáng 15/01\", \"expectedOutput\":\"15/1/2020 9:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"thời gian: từ sáng thứ 4 lúc 9h30-10h30 ngày 24/12/2019 đến trưa sau 12h ngày 25/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;25/12/2019 12:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"cuối tháng 8 năm 2019\", \"expectedOutput\":\"26/8/2019 0:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"lúc 9h30-10h30\", \"expectedOutput\":\"14/5/2020 9:30:0;14/5/2020 10:30:0\"}\n# \t\t\t,{\"rawDatetime\":\"lúc 9h30- 10h30\", \"expectedOutput\":\"14/5/2020 9:30:0;14/5/2020 10:30:0\"}\n# \t\t\t,{\"rawDatetime\":\"lúc 9h30- 10h30 ngày 24/12/2019\", \"expectedOutput\":\"24/12/2019 9:30:0;24/12/2019 10:30:0\"}\n# \t\t\t,{\"rawDatetime\":\"trong 2 ngày 24-25/12/2019\", \"expectedOutput\":\"24/12/2019 0:0:0;25/12/2019 0:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"từ ngày 24 đến 25/12/2019\", \"expectedOutput\":\"24/12/2019 0:0:0;25/12/2019 0:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"từ 10h ngày 24 đến 25/12/2019\", \"expectedOutput\":\"24/12/2019 10:0:0;25/12/2019 0:0:0\"}\n# \t\t\t,{\"rawDatetime\":\"lúc 10h ngày 24 đến 25/12/2019\", \"expectedOutput\":\"24/12/2019 10:0:0;25/12/2019 0:0:0\"}\n# \t])\n\n\n# TODO: pattern \"cuối ... \", split by \"-\"\n# factory.processRawDatetimeInput(\"thời gian bắt đầu vào thứ 5 tuần kế nhé\")","sub_path":"time_normalizer.py","file_name":"time_normalizer.py","file_ext":"py","file_size_in_byte":38795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"28832663","text":"#!python\n\nimport string\n# Hint: Use these string constants to encode/decode hexadecimal digits and more\n# string.digits is '0123456789'\n# string.hexdigits is '0123456789abcdefABCDEF'\n# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'\n# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n# string.ascii_letters is ascii_lowercase + ascii_uppercase\n# string.printable is digits + ascii_letters + punctuation + whitespace\n# string.printable = '0123456789abcdefghijklmnopqrstuvwxyz'\n\ndef decode(digits: str, base: int) -> int:\n '''\n DIGITS IN GIVEN BASE -> DIGITS IN BASE10\n '''\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base <= 36, 'base is out of range: {}'.format(base)\n \n power = len(digits)\n output = 0\n for digit in digits:\n # INDEX() GIVES BACK INDEX OF THE DIGIT ACCORDING TO STRING.PRINTABLE\n power -= 1\n value_of_digit = string.printable.index(digit)\n output += (base ** power) * value_of_digit\n return output\n\ndef encode(number: int, base: int) -> str:\n '''\n GIVEN NUMBER (BASE10) -> DIGITS IN GIVEN BASE\n '''\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base <= 36, 'base is out of range: {}'.format(base)\n # Handle unsigned numbers only for now\n assert number >= 0, 'number is negative: {}'.format(number)\n \n \n output = \"\"\n while number > 0:\n remainder = number % base\n # VALUE BY INDEX: 0 => '0', 1 => '1', 13 => 'd'\n digit_for_value = string.printable[remainder]\n # output = output + digit_for_value # append new digit to right side of output string\n output = digit_for_value + output # prepend new digit to left side of output string\n # ROUNDED DIVISION\n number = number // base\n return output\n\ndef convert(bits: str, base1: int, base2: int) -> str:\n '''\n GIVEN DIGITS IN BASE1 -> DIGITS IN BASE2\n '''\n # Handle up to base 36 [0-9a-z]\n assert 2 <= base1 <= 36, 'base1 is out of range: {}'.format(base1)\n assert 2 <= base2 <= 36, 'base2 is out of range: {}'.format(base2)\n \n # DECODE TO BASE1 - RETURNS BASE10 NUM\n decoded = decode(bits, base1)\n # ENCODE BASE10 NUM TO BASE2\n encoded = encode(decoded, base2)\n return encoded\n\ndef main():\n '''Read command-line arguments and convert given digits between bases.'''\n import sys\n args = sys.argv[1:] # Ignore script file name\n if len(args) == 3:\n digits = args[0]\n base1 = int(args[1])\n base2 = int(args[2])\n # Convert given digits between bases\n result = convert(digits, base1, base2)\n print('{} in base {} is {} in base {}'.format(digits, base1, result, base2))\n else:\n print('Usage: {} digits base1 base2'.format(sys.argv[0]))\n print('Converts digits from base1 to base2')\n\nif __name__ == '__main__':\n main()\n decode('c9',16)","sub_path":"Old-T4/source/bases.py","file_name":"bases.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"16040771","text":"from price_interface import *\nfrom django.views.generic import ListView,DetailView,TemplateView\nfrom desinfapp.views import Base \n\nclass PriceList(Base,TemplateView):\n\ttemplate_name=\"pricelist.html\"\n\n\tdef get_context_data(self, **kwargs):\n\t context = super(PriceList, self).get_context_data(**kwargs)\n\t context['groupped_prices'] = {x:{\"types\":get_types(tp=x).order_by(\"place\",\"name\"),\n\t \t\t\t\t\"objects\":get_groupped_items(tp=x,type_ordering=[\"place\",\"name\"])} \n\t \t\t\t\tfor x in DesType.objects.all()}\n\t return context\n\n# class PriceObj(DetailView):\n# \tcontext_object_name=\"price\"\n# \tmodel=ServicePrice\n# \ttemplate_name=\"priceobj.html\"\n\n\n","sub_path":"pricelist/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"46837787","text":"#!/usr/bin/env python3\nfrom mitmproxy import ctx\nfrom mitmproxy import http\nfrom mitm_logging import log_error\nfrom simple_flow import SimpleFlow\nfrom threading import Thread, Lock\nimport sys\nimport time\nfrom threading import Timer\n\n\nclass ReplayResurrect:\n\n def __init__(self, replayer):\n self.last_pending_id = None\n self.replayer = replayer\n self.refresh_thread = None\n self.resurect_count = 0\n\n def handle_request(self, simple_flow: SimpleFlow) -> None:\n if self.resurect_count > 0:\n log_error(f\"[-] Resurection count: {self.resurect_count}\")\n self.refresh_timer()\n\n def handle_response(self, simple_flow: SimpleFlow) -> None:\n pass\n\n def refresh_timer(self):\n if self.refresh_thread:\n self.refresh_thread.cancel()\n self.last_pending_id = self.replayer.pending_id\n\n self.refresh_thread = Timer(10, self.try_resurrect)\n self.refresh_thread.start()\n\n def try_resurrect(self):\n if not self.replayer.isIdle():\n log_error(\"[-] Something went wrong. Try to resurrect the replayer\")\n if self.last_pending_id != self.replayer.pending_id:\n log_error(\n f\"[-] self.last_pending_id({self.last_pending_id}) != self.replayer.pending_id({self.replayer.pending_id}). How can this happen? Can this even happen?\")\n self.replayer.reset(self.replayer.pending_id)\n\n self.resurect_count += 1\n log_error(\n f\"[-] is resurrected ? : IsIdle == {self.replayer.isIdle()}\")\n\n self.refresh_timer()\n","sub_path":"2019_4/dungeon_crusher/resurrect_replayer.py","file_name":"resurrect_replayer.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"145379660","text":"tax_rates = {\r\n 'Ukraine': 0.13,\r\n 'USA' : 0.2,\r\n 'England' : 0.3,\r\n 'Germany' : 0.1,\r\n 'France' : 0.05\r\n}\r\ndef calculate_tax_rate():\r\n print('Do you want to enter tax rate[1] or country[2]?')\r\n option = int(input())\r\n\r\n cost = float(input('Input enter a cost: '))\r\n if option == 2:\r\n country = input('Enter a country: ')\r\n tax = tax_rates[country]\r\n tuple_for_print = (country, tax_rates[country], cost + tax * cost)\r\n else :\r\n tax = float(input('Enter a tax rate '))\r\n tuple_for_print = (tax, cost + tax * cost)\r\n\r\n return tuple_for_print\r\n\r\n","sub_path":"python_project_list/numbers_tasks/src/tax_calculator.py","file_name":"tax_calculator.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"366729626","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nfrom drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"home\"),\n path('admin/', admin.site.urls),\n path(\"api/\", include('diseases.urls', namespace='diseases')),\n path('api-auth/', include('rest_framework.urls')),\n path('api/schema/', SpectacularAPIView.as_view(), name='schema'),\n path('api/schema/swagger-ui/',\n SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),\n path('api/schema/redoc/',\n SpectacularRedocView.as_view(url_name='schema'), name='redoc'),\n]\n","sub_path":"docapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"638851645","text":"import json\nfrom storefrontconfig import StorefrontConfig\n\n\nclass FileController:\n @staticmethod\n def read_file(file_name):\n with open(file_name) as file:\n data = json.load(file)\n return StorefrontConfig(data)\n\n @staticmethod\n def write_file(obj, file_name):\n with open(file_name, \"w\") as file:\n file.write(json.dumps(obj.data))\n","sub_path":"Problem4/FileController.py","file_name":"FileController.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"517672612","text":"# encoding: UTF-8\n\n\"\"\"\nImplement phylib command 'impact-vastart'.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport sys, logging, traceback\n\nfrom argparse import ArgumentParser\n\nfrom common import loadMachineConfig, loadLatticeConfig\nfrom common import loadLayout, loadSettings, loadChannels\n\nfrom ..machine.frib.virtaccel.impact import build_virtaccel\n\n\nparser = ArgumentParser(description=\"Start the virtual accelerator using IMPACT simulation\")\nparser.add_argument(\"-v\", dest=\"verbosity\", nargs='?', type=int, const=1, default=0, help=\"set the amount of output\")\nparser.add_argument(\"--mach\", dest=\"machine\", help=\"name of machine or path of machine directory\")\nparser.add_argument(\"--subm\", dest=\"submach\", help=\"name of submachine\")\nparser.add_argument(\"--layout\", dest=\"layoutpath\", help=\"path of accelerator layout file (.csv)\")\nparser.add_argument(\"--settings\", dest=\"settingspath\", help=\"path to accelerator settings file (.json)\")\nparser.add_argument(\"--config\", dest=\"configpath\", help=\"path to accelerator configuration file (.ini)\")\nparser.add_argument(\"--cfsurl\", help=\"url of channel finder service or local sqlite file\")\nparser.add_argument(\"--cfstag\", help=\"tag to query for channels\")\nparser.add_argument(\"--start\", help=\"name of accelerator element to start processing\")\nparser.add_argument(\"--end\", help=\"name of accelerator element to end processing\")\nparser.add_argument(\"--data\", dest=\"datapath\", help=\"path to directory with IMPACT data\")\nparser.add_argument(\"--work\", dest=\"workpath\", help=\"path to directory for executing IMPACT\")\n\n\nprint_help = parser.print_help\n\n\ndef main():\n \"\"\"\n Entry point for command 'impact-vastart'.\n \"\"\"\n args = parser.parse_args(sys.argv[2:])\n\n if args.verbosity == 1:\n logging.getLogger().setLevel(logging.INFO)\n elif args.verbosity > 1:\n logging.getLogger().setLevel(logging.DEBUG)\n\n\n try:\n mconfig, submach = loadMachineConfig(args.machine, args.submach)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error readings machine configuration:\", e, file=sys.stderr)\n return 1\n\n\n try:\n layout = loadLayout(args.layoutpath, mconfig, submach)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error loading layout:\", e, file=sys.stderr)\n return 1\n\n\n try:\n settings = loadSettings(args.settingspath, mconfig, submach)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error loading settings:\", e, file=sys.stderr)\n return 1\n\n\n try:\n config = loadLatticeConfig(args.configpath, mconfig, submach)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error loading configuration:\", e, file=sys.stderr)\n return 1\n\n\n channels = loadChannels(args.cfsurl, None, mconfig, submach)\n\n\n try:\n va = build_virtaccel(layout, config=config, channels=channels, settings=settings,\n start=args.start, end=args.end, data_dir=args.datapath, work_dir=args.workpath)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error building virtual accelerator:\", e, file=sys.stderr)\n return 1\n\n\n try:\n va.start(True)\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error starting virtual accelerator:\", e, file=sys.stderr)\n return 1\n\n\n try:\n va.wait()\n except KeyboardInterrupt:\n va.stop()\n va.wait()\n except Exception as e:\n if args.verbosity > 0: traceback.print_exc()\n print(\"Error executing virtual accelerator:\", e, file=sys.stderr)\n return 1\n\n\n return 0\n\n","sub_path":"phyutil/phytool/impact_vastart.py","file_name":"impact_vastart.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"445347044","text":"from cgl.core.path import PathObject\n\ncompany = 'NewCo'\nproject = 'Branches'\n\n\n\n# String Tests\n\"\"\"\ntest_path = r'Z:/Projects/NewCo'\ntest_path = r'Z:/Projects/NewCo/source'\ntest_path = r'Z:/Projects/NewCo/source/Branches'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim/default'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim/default/cab18n'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim/default/cab18n/002.000'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim/default/cab18n/002.000/high'\ntest_path = r'Z:/Projects/NewCo/source/Branches/master/shots/003/0100/anim/default/cab18n/002.000/high/003_0100_anim.mb'\nprint('Test Path {}'.format(test_path))\npath_object = PathObject(test_path)\nprint('Company {}'.format(path_object.company))\nprint('Context {}'.format(path_object.context))\nprint('Project {}'.format(path_object.project))\nprint('Branch {}'.format(path_object.branch))\nprint('Scope {}'.format(path_object.scope))\nprint('Seq {}'.format(path_object.seq))\nprint('Shot {}'.format(path_object.shot))\nprint('Variant {}'.format(path_object.variant))\nprint('User {}'.format(path_object.user))\nprint('Version {}'.format(path_object.version))\nprint('Resolution {}'.format(path_object.resolution))\nprint('filename {}'.format(path_object.filename))\n\"\"\"\n\n# # dict Tests\n# d_ = {\"company\": company,\n# \"context\": 'source',\n# \"project\": project,\n# \"scope\": 'shots',\n# \"seq\": '003',\n# \"shot\": '0100',\n# \"task\": 'anim',\n# \"user\": 'cab18n',\n# \"version\": '002.000',\n# \"resolution\": 'high',\n# \"filename\": '003_0100_anim.mb'\n# }\n\npath_ = r'C:\\CGLUMBERJACK\\COMPANIES\\cmpa-animation\\config\\master'\n\npath_object = PathObject(path_)\nprint(path_object.path_root)","sub_path":"cgl/core/path_tests.py","file_name":"path_tests.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"23190941","text":"\"\"\"\nMatcher searching for co-occurences according to syntactic patterns.\n\"\"\"\n\nimport anatomize.pattern.compiler as pattern_compiler\nimport anatomize.pattern.base as pattern\nimport anatomize.sentence.base as sentence_base\nimport anatomize.matcher.base as base\n\nclass Matcher(base.AbstractMatcher):\n\n def test_compatibility(self, sentence_stream):\n if not issubclass(\n sentence_stream.element_class,\n sentence_base.AbstractDependencySentence):\n raise TypeError(\"Incompatible sentence stream\")\n\n def extract_from_sentence(\n self,\n sentence,\n target_list, context_list,\n matrix):\n \"\"\"\n Extract co-occurence of target/context words for the provided sentence\n\n Args:\n sentence: a Sentence object\n \"\"\"\n\n # just check for every word in the sentence...\n for word in sentence:\n self.extract_from_word(word, target_list, context_list, matrix)\n\n def __init__(self, istream):\n \"\"\"\n Add the patterns readed from the stream\n\n Args:\n istream: stream from which the patterns will be read\n \"\"\"\n self.parser = pattern_compiler.Parser()\n # will contains the list of syntactic patterns\n self.patterns = pattern.List()\n self.patterns.extend(self.parser.parse(istream))\n\n\n\n def extract_from_word(self, word, target_list, context_list, matrix):\n \"\"\"\n If the word is a target word, try to extract co-occurences according\n to the context words and the patterns\n \"\"\"\n\n target_matches = target_list.find_matches(word)\n\n for target_match in target_matches:\n\n # so let's check for patterns\n \n matched_pattern_list = \\\n self.patterns.match_forward(\n word,\n # on ne veut pas que un des mots\n # du target soit dans le context\n #unwanted_words = target_match.getWords()\n )\n\n context_words = []\n for matched_pattern in matched_pattern_list:\n context_words.append(matched_pattern.last_word)\n\n to_inc = []\n \n\n for context_word in context_words:\n context_matches = context_list.find_matches(\n context_word,\n unwanted_words=target_match.words)\n\n for context_match in context_matches:\n # if we have a target_id and a context_id,\n # we juste increment the corresponding cell\n cell = (target_match.key, context_match.key)\n if not cell in to_inc:\n to_inc.append(cell)\n\n\n for i, j in to_inc:\n matrix.inc(i, j)\n\n","sub_path":"src/anatomize/matcher/syntactic_pattern.py","file_name":"syntactic_pattern.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499885314","text":"from enum import Enum\n\n\nclass Status(Enum):\n \"\"\"\n A network interface can be in one of this three states.\n \"\"\"\"\"\n up = 1\n down = 2\n unknown = 3\n\n\nclass NetworkInterface:\n \"\"\"\n This class represents a Network Interface, with a name, a mac address and two lists of IPs.\n \"\"\"\"\"\n\n def __init__(self, name: str):\n \"\"\"\n This class represents a Network Interface.\n\n :param name: The name of the interface\n \"\"\"\n self._name = name\n self._status = Status.unknown\n self._mac = \"00:00:00:00:00:00\"\n self.ipv4_lst = list()\n self.ipv6_lst = list()\n\n @property\n def name(self) -> str:\n \"\"\"\n The name of the network interface\n :return: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, value: str):\n \"\"\"\n :type value: str\n \"\"\"\n assert isinstance(value, str)\n self._name = value\n\n @property\n def status(self) -> Status:\n \"\"\"\n The status of the network interface\n :return: Status\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, value: Status):\n \"\"\"\n :type value: Status\n \"\"\"\n assert isinstance(value, Status)\n self._status = value\n\n @property\n def mac(self) -> str:\n \"\"\"\n The mac addresses of the network interface\n :return: str\n \"\"\"\n return self._mac\n\n @mac.setter\n def mac(self, value: str):\n \"\"\"\n :type value: str\n \"\"\"\n assert isinstance(value, str)\n self._mac = value\n\n def __str__(self):\n ipv4 = \"[\"\n for ip in self.ipv4_lst:\n ipv4 = ipv4 + \" \" + str(ip)\n ipv4 += \" ]\"\n ipv6 = \"[\"\n for ip in self.ipv6_lst:\n ipv6 = ipv6 + \" \" + str(ip)\n ipv6 += \" ]\"\n return self.name + \", \" + self.mac + \", \" + str(self.status) + \", \" + str(ipv4) + \", \" + str(ipv6)\n","sub_path":"router/network_interface.py","file_name":"network_interface.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"2704269","text":"\"\"\"empty message\n\nRevision ID: ed606cc52034\nRevises: \nCreate Date: 2018-08-16 21:49:31.959217\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ed606cc52034'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('cal123asdas',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('enterpriseagreement',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=8), nullable=True),\n sa.Column('min_periods', sa.Integer(), nullable=True),\n sa.Column('max_periods', sa.Integer(), nullable=True),\n sa.Column('max_periods_overtime', sa.Integer(), nullable=True),\n sa.Column('wage', sa.Float(), nullable=True),\n sa.Column('wage_overtime', sa.Float(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('period',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('start_time', sa.Time(), nullable=True),\n sa.Column('end_time', sa.Time(), nullable=True),\n sa.Column('day', sa.String(length=10), nullable=True),\n sa.Column('week', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('skill',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=8), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.create_table('employee',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=64), nullable=True),\n sa.Column('password_hash', sa.String(length=64), nullable=True),\n sa.Column('agreement', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['agreement'], ['enterpriseagreement.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('email'),\n sa.UniqueConstraint('username')\n )\n op.create_table('schedule_requirement',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('period', sa.Integer(), nullable=False),\n sa.Column('requirement', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['period'], ['period.id'], ),\n sa.ForeignKeyConstraint(['requirement'], ['skill.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('shift',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('start_period', sa.Integer(), nullable=True),\n sa.Column('shift_length', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['start_period'], ['period.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('preference',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('employee', sa.Integer(), nullable=False),\n sa.Column('shift', sa.Integer(), nullable=False),\n sa.Column('preference_level', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['employee'], ['employee.id'], ),\n sa.ForeignKeyConstraint(['shift'], ['shift.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('schedule_allocation',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('employee', sa.Integer(), nullable=False),\n sa.Column('shift', sa.Integer(), nullable=False),\n sa.Column('skills', sa.Integer(), nullable=False),\n sa.Column('period', sa.Integer(), nullable=False),\n sa.Column('is_overtime', sa.Boolean(), nullable=True),\n sa.ForeignKeyConstraint(['employee'], ['employee.id'], ),\n sa.ForeignKeyConstraint(['period'], ['period.id'], ),\n sa.ForeignKeyConstraint(['shift'], ['shift.id'], ),\n sa.ForeignKeyConstraint(['skills'], ['skill.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('shift_periods',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('period', sa.Integer(), nullable=True),\n sa.Column('shift', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['period'], ['period.id'], ),\n sa.ForeignKeyConstraint(['shift'], ['shift.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('skill_assignment',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('skill', sa.Integer(), nullable=False),\n sa.Column('employee', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['employee'], ['employee.id'], ),\n sa.ForeignKeyConstraint(['skill'], ['skill.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('skill_assignment')\n op.drop_table('shift_periods')\n op.drop_table('schedule_allocation')\n op.drop_table('preference')\n op.drop_table('shift')\n op.drop_table('schedule_requirement')\n op.drop_table('employee')\n op.drop_table('skill')\n op.drop_table('period')\n op.drop_table('enterpriseagreement')\n op.drop_table('cal123asdas')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/ed606cc52034_.py","file_name":"ed606cc52034_.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"637678006","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport os\nimport sys\nimport shlex\nimport subprocess\nimport json\nfrom prettytable import PrettyTable\nimport argparse\nfrom argparse import RawTextHelpFormatter\n\n# Init ENV\nrwResult = {}\n#Color\nR = \"\\033[0;31;40m\" #RED\nG = \"\\033[0;32;40m\" # GREEN\nY = \"\\033[0;33;40m\" # Yellow\nB = \"\\033[0;34;40m\" # Blue\nN = \"\\033[0m\" # Reset\n\n\ndef bash(cmd):\n return shlex.os.system(cmd)\n\n\ndef format_bytes(size):\n size = float(size)\n power = 2**10\n n = 1\n power_labels = {0: 'B/s', 1: 'KB/s', 2: 'MB/s', 3: 'GB/s', 4: 'TB/s'}\n while size > power:\n size /= power\n n += 1\n value = size\n unit = \"{}\".format(power_labels[n])\n return value, unit\n\n\ndef cleanup(filename=None):\n os.remove(filename)\n\n\ndef printResult():\n print(G + \"\\nTest Results:\" + N)\n table = PrettyTable(\n [\"Test Item\", \"Read IOPS\", \"Read Speed\", \"Write IOPS\", \"Write Speed\"])\n for k, v in rwResult.items():\n list = [k, v[\"read_iops\"], v[\"read_bw\"], v[\"write_iops\"], v[\"write_bw\"]]\n table.add_row(list)\n table.align[\"Test Item\"] = \"l\"\n table.align[\"Write IOPS\"] = \"r\"\n table.align[\"Write Speed\"] = \"r\"\n table.align[\"Read IOPS\"] = \"r\"\n table.align[\"Read Speed\"] = \"r\"\n print(table.get_string(sortby=\"Test Item\", reversesort=True))\n\ndef outputResult(filename=None):\n if os.path.exists(filename):\n os.remove(filename)\n with open(filename, 'w+', encoding='utf-8') as fo:\n fo.write(\"Test Results:\\n\")\n table = PrettyTable(\n [\"Test Item\", \"Read IOPS\", \"Read Speed\", \"Write IOPS\", \"Write Speed\"])\n for k, v in rwResult.items():\n list = [k, v[\"read_iops\"], v[\"read_bw\"], v[\"write_iops\"], v[\"write_bw\"]]\n table.add_row(list)\n table.align[\"Test Item\"] = \"l\"\n table.align[\"Write IOPS\"] = \"r\"\n table.align[\"Write Speed\"] = \"r\"\n table.align[\"Read IOPS\"] = \"r\"\n table.align[\"Read Speed\"] = \"r\"\n fo.write(table.get_string(sortby=\"Test Item\", reversesort=True))\n fo.write(\"\\n\")\n print((G + \"\\nThe test results saved in: {}\" + N).format(filename))\n\n\nclass FioTest(object):\n\n def __init__(self,\n name,\n filename,\n rw,\n bs,\n size,\n direct=1,\n iodepth=1,\n ioengine=\"libaio\",\n runtime=60):\n self.name = name\n self.filename = filename\n self.direct = direct\n self.rw = rw\n self.bs = bs\n self.size = size\n self.iodepth = iodepth\n self.ioengine = ioengine\n self.runtime = runtime\n\n def exprCmd(self):\n cmd = \"fio --name=\" + self.name + \" --rw=\" + self.rw + \" --iodepth=\" + str(\n self.iodepth\n ) + \" --ioengine=\" + self.ioengine + \" --thread --direct=\" + str(\n self.direct\n ) + \" --norandommap --bs=\" + self.bs + \" --size=\" + self.size + \" --runtime=\" + str(\n self.runtime\n ) + \" --filename=\" + self.filename + \" --minimal --output-format=json\"\n return cmd\n\n def runCmd(self, cmd):\n result_str = ''\n process = subprocess.Popen(cmd,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out = process.stdout\n errors = process.stderr\n err = errors.read()\n if err:\n print(R + \"Run ERROR!\" + N)\n os._exit(1)\n result_str = out.read().strip()\n if out:\n out.close()\n if errors:\n errors.close()\n\n return result_str.decode('utf8')\n\n def explain(self, result):\n\n if self.rw == \"read\" or self.rw == \"randread\":\n r = json.loads(result)\n iops = r[\"jobs\"][0][\"read\"][\"iops\"]\n bw = r[\"jobs\"][0][\"read\"][\"bw\"]\n return iops, bw\n else:\n if self.rw == \"write\" or self.rw == \"randwrite\":\n r = json.loads(result)\n iops = r[\"jobs\"][0][\"write\"][\"iops\"]\n bw = r[\"jobs\"][0][\"write\"][\"bw\"]\n return iops, bw\n\n def expResult(self, iops, bw):\n name = self.name\n rw_iops = \"\"\n rw_bw = \"\"\n\n if self.rw == \"write\":\n rw_iops = \"write_iops\"\n rw_bw = \"write_bw\"\n elif self.rw == \"read\":\n rw_iops = \"read_iops\"\n rw_bw = \"read_bw\"\n elif self.rw == \"randwrite\":\n rw_iops = \"write_iops\"\n rw_bw = \"write_bw\"\n elif self.rw == \"randread\":\n rw_iops = \"read_iops\"\n rw_bw = \"read_bw\"\n io_speed, unit = format_bytes(bw)\n\n if name in rwResult.keys():\n rwResult[name][rw_iops] = \"{:d}\".format(int(iops))\n rwResult[name][rw_bw] = \"{:.2f} {}\".format(io_speed, unit) if (\n unit == \"GB/s\" or unit == \"TB/s\") else \"{:d} {}\".format(\n int(io_speed), unit)\n else:\n rwResult[name] = {}\n rwResult[name][rw_iops] = \"{:d}\".format(int(iops))\n rwResult[name][rw_bw] = \"{:.2f} {}\".format(io_speed, unit) if (\n unit == \"GB/s\" or unit == \"TB/s\") else \"{:d} {}\".format(\n int(io_speed), unit)\n\n def saveResult(self):\n cmd = self.exprCmd()\n result = self.runCmd(cmd)\n iops, bw = self.explain(result)\n self.expResult(iops, bw)\n\n\nif __name__ == '__main__':\n\n defult_path = os.getcwd() + '/fio_test.bin'\n # read parameters\n parser = argparse.ArgumentParser(\n prog='fio Benchmark tool',\n description='Use fio to Measure Hard Drive and SSD Performance',\n formatter_class=RawTextHelpFormatter)\n parser.add_argument(\n '-a',\n '--all',\n dest='alltest',\n action='store_true',\n required=False,\n help=\n 'Perform a full test [R/W in Seq Q32T1, 4K Q32T1, Seq, 4K] (Default).')\n parser.add_argument(\n '-t',\n '--test',\n metavar='integer',\n dest='test_num',\n type=int,\n default=None,\n required=False,\n nargs='+',\n help='Available test [1. Seq Q32T1], [2. 4K Q32T1], [3. Seq], [4. 4K].')\n parser.add_argument('-s',\n '--size',\n metavar='String',\n dest='test_size',\n type=str,\n default=None,\n required=False,\n nargs='+',\n help='IO test file size (Default 2g)')\n parser.add_argument(\n '-f',\n '--file',\n metavar='String',\n dest='test_file',\n type=str,\n default=None,\n required=False,\n nargs='+',\n help='IO test file path (Default {})'.format(defult_path))\n parser.add_argument('-o',\n '--output',\n metavar='String',\n dest='output_file',\n type=str,\n default=None,\n required=False,\n nargs='+',\n help='Save result to file instead of stdout')\n args = parser.parse_args()\n\n # get opts.\n test1 = False\n test2 = False\n test3 = False\n test4 = False\n\n if args.test_num is None or args.alltest:\n test1 = True\n test2 = True\n test3 = True\n test4 = True\n else:\n if not all(elem in range(1, 4) for elem in args.test_num):\n raise ValueError('invalid test number')\n else:\n if 1 in args.test_num: test1 = True\n if 2 in args.test_num: test2 = True\n if 3 in args.test_num: test3 = True\n if 4 in args.test_num: test4 = True\n if args.test_size is None:\n test_size = '2g'\n else:\n test_size = \"\".join(args.test_size)\n if args.test_file is None:\n test_file = defult_path\n else:\n test_file = \"\".join(args.test_file)\n if args.output_file is None:\n to_file=False\n else:\n to_file=True\n output_file = \"\".join(args.output_file)\n\n print(R + 'Following item will be test:\\n' + N)\n if test1: print('- Seq Q32T1')\n if test2: print('- 4K Q32T1')\n if test3: print('- Seq')\n if test4: print('- 4K')\n print\n\n if test1:\n print(\n Y +\n 'Test Sequential (Block Size=128KiB) Read with Queuedepth=32 Thread=1'\n + N)\n cmd = FioTest(name=\"Seq-Q32T1\",\n rw=\"read\",\n iodepth=32,\n ioengine=\"libaio\",\n direct=1,\n bs=\"128k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n print(\n Y +\n 'Test Sequential (Block Size=128KiB) Write with Queuedepth=32 Thread=1'\n + N)\n cmd = FioTest(name=\"Seq-Q32T1\",\n rw=\"write\",\n iodepth=32,\n ioengine=\"libaio\",\n direct=1,\n bs=\"128k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n\n if test2:\n print(Y + 'Test Random 4KiB Read with Queuedepth=32 Thread=1' + N)\n cmd = FioTest(name=\"4K-Q32T1\",\n rw=\"randread\",\n iodepth=32,\n ioengine=\"libaio\",\n direct=1,\n bs=\"4k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n print(Y + 'Test Random 4KiB Write with Queuedepth=32 Thread=1' + N)\n cmd = FioTest(name=\"4K-Q32T1\",\n rw=\"randwrite\",\n iodepth=32,\n ioengine=\"libaio\",\n direct=1,\n bs=\"4k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n\n if test3:\n print(\n Y +\n 'Test Sequential (Block Size=1MiB) Read with Queuedepth=1 Thread=1'\n + N)\n cmd = FioTest(name=\"Seq\",\n rw=\"read\",\n iodepth=1,\n ioengine=\"libaio\",\n direct=1,\n bs=\"1m\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n print(\n Y +\n 'Test Sequential (Block Size=1MiB) Write with Queuedepth=1 Thread=1'\n + N)\n cmd = FioTest(name=\"Seq\",\n rw=\"write\",\n iodepth=1,\n ioengine=\"libaio\",\n direct=1,\n bs=\"1m\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n\n if test4:\n print(Y + 'Test Random 4KiB Read with Queuedepth=1 Thread=1' + N)\n cmd = FioTest(name=\"4K\",\n rw=\"randread\",\n iodepth=1,\n ioengine=\"libaio\",\n direct=1,\n bs=\"4k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n print(Y + 'Test Random 4KiB Write with Queuedepth=1 Thread=1' + N)\n cmd = FioTest(name=\"4K\",\n rw=\"randwrite\",\n iodepth=1,\n ioengine=\"libaio\",\n direct=1,\n bs=\"4k\",\n size=test_size,\n runtime=60,\n filename=test_file)\n cmd.saveResult()\n cleanup(filename=test_file)\n if to_file:\n outputResult(filename=output_file)\n else:\n printResult()\n","sub_path":"fio-bench.py","file_name":"fio-bench.py","file_ext":"py","file_size_in_byte":12173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"186488310","text":"import argparse\r\nimport torch\r\nimport time\r\nimport fnmatch\r\nimport os, sys, shutil, glob\r\nimport pickle\r\nimport numpy as np\r\nimport SimpleITK as sitk\r\nimport skimage.io as tif\r\nimport statsmodels.api as sm\r\n\r\nimport multiprocessing as mp\r\nfrom multiprocessing import Pool\r\n\r\ndef add_path(path):\r\n if path not in sys.path:\r\n sys.path.insert(0, path)\r\n\r\nadd_path(os.path.join('/home/junhong/UHR_OCT_Segmentation', 'furnace'))\r\nfrom utils.file_utils import glob_on_server, get_file_from_server, save_file_to_server\r\nfrom utils.mat_utils import loadmat\r\nfrom utils.pyt_utils import ensure_dir\r\n\r\ndef bscan_worker(flatten):\r\n for i in range(flatten.shape[0]):\r\n for j in range(flatten.shape[2]):\r\n mask = flatten[i, :, j] > np.mean(flatten[i, :, j])\r\n estimated_position = np.matmul(np.arange(height)[mask], flatten[i, mask, j]) / np.sum(flatten[i, mask, j])\r\n estimated_position = int(np.rint(estimated_position.item()))\r\n center[i, j] = estimated_position\r\n\r\n newx = np.arange(width)\r\n for i in range(flatten.shape[0]):\r\n lowess = sm.nonparametric.lowess(center[i, :], newx, frac=0.2)\r\n center[i, :] = lowess[:, 1]\r\n\r\n for i in range(flatten.shape[0]):\r\n for j in range(flatten.shape[2]):\r\n flatten[i, :, j] = np.roll(flatten[i, :, j], center_position - center[i, j], axis=0)\r\n return (flatten, center)\r\n\r\nif __name__ == \"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--input_file', '-i', default=r\"./\", type=str)\r\n parser.add_argument('--output_folder', '-o', default=r'NEEC_UHR-OCT_Clean/NEEC_UHR-OCT_Volumes_6x_IntensityFlatten')\r\n args = parser.parse_args()\r\n\r\n TEMPPATH = r'/nobackup/users/junhong/AMD_Data/TempT'\r\n SAVEPATH = args.output_folder\r\n\r\n path = args.input_file\r\n basename = os.path.basename(path)\r\n\r\n # print('Preparing raw data:', path)\r\n # st = time.time()\r\n # data_path = os.path.join(TEMPPATH, basename)\r\n # get_file_from_server(path, data_path)\r\n # image = tif.imread(data_path)\r\n #\r\n # os.remove(data_path)\r\n # print('IO Time:', time.time() - st)\r\n # print('Done.')\r\n image = tif.imread(path)\r\n\r\n flatten = image.copy()\r\n center_position = image.shape[1] // 2\r\n height, width = image.shape[1], image.shape[2]\r\n center = np.zeros((image.shape[0], image.shape[2]), dtype=np.int) # (241, 1800)\r\n\r\n st = time.time()\r\n num_process = 12\r\n chunk_size = flatten.shape[0] // num_process\r\n chunks = [[] for _ in range(num_process)]\r\n for i in range(num_process):\r\n if (i < num_process - 1):\r\n chunks[i] = flatten[i * chunk_size: (i + 1) * chunk_size, :, :]\r\n else:\r\n chunks[i] = flatten[i * chunk_size:, :, :]\r\n\r\n p = Pool(processes=num_process)\r\n output = p.starmap(bscan_worker, [(chunks[i],) for i in range(len(chunks))])\r\n flatten = np.vstack([i[0] for i in output])\r\n center = np.vstack([i[1] for i in output])\r\n print('Flatten Time:', time.time() - st)\r\n\r\n print('Saving Flatten to disk...')\r\n save_path = os.path.join(TEMPPATH, basename[:-4] + '_Flatten.tif')\r\n tif.imsave(save_path, flatten, imagej=True)\r\n print('Saved to disk, transmitting to server...')\r\n save_file_to_server(save_path, os.path.join(SAVEPATH, 'Flatten', basename[:-4] + '_Flatten.tif'))\r\n os.remove(save_path)\r\n print('Saved.')\r\n\r\n print('Saving center position to disk...')\r\n save_path = os.path.join(TEMPPATH, basename[:-4] + '_Flatten.pkl')\r\n with open(save_path, 'wb') as handle:\r\n pickle.dump(center, handle)\r\n print('Saved to disk, transmitting to server...')\r\n save_file_to_server(save_path, os.path.join(SAVEPATH, 'Pickle', basename[:-4] + '_Flatten.pkl'))\r\n os.remove(save_path)\r\n print('Saved.')\r\n\r\n # with open('filename.pickle', 'rb') as handle:\r\n # b = pickle.load(handle)\r\n\r\n\r\n","sub_path":"preprocessing/flattenVolume.py","file_name":"flattenVolume.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"553564376","text":"from magpie.security import authomatic_setup, get_provider_names\nfrom magpie.definitions.pyramid_definitions import (\n view_config,\n forget,\n remember,\n Authenticated,\n IAuthenticationPolicy,\n Request,\n Response,\n HTTPOk,\n HTTPFound,\n HTTPTemporaryRedirect,\n HTTPBadRequest,\n HTTPUnauthorized,\n HTTPForbidden,\n HTTPNotFound,\n HTTPConflict,\n HTTPInternalServerError,\n HTTPException,\n NO_PERMISSION_REQUIRED,\n)\nfrom magpie.definitions.ziggurat_definitions import (\n ExternalIdentityService,\n UserService,\n ZigguratSignInSuccess,\n ZigguratSignInBadAuth,\n ZigguratSignOut,\n)\nfrom magpie.api import generic as ag, exception as ax, schemas as s\nfrom magpie.api.requests import get_multiformat_post, get_value_multiformat_post_checked\nfrom magpie.api.management.user.user_formats import format_user\nfrom magpie.api.management.user.user_utils import create_user\nfrom magpie.constants import get_constant\nfrom magpie import models\nfrom magpie.utils import get_magpie_url, convert_response, get_logger, CONTENT_TYPE_JSON\nfrom authomatic.adapters import WebObAdapter\nfrom authomatic.core import LoginResult, Credentials, resolve_provider_class\nfrom authomatic.exceptions import OAuth2Error\nfrom six.moves.urllib.parse import urlparse\nLOGGER = get_logger(__name__)\n\n\n# dictionaries of {'provider_id': 'provider_display_name'}\nMAGPIE_DEFAULT_PROVIDER = get_constant(\"MAGPIE_DEFAULT_PROVIDER\")\nMAGPIE_INTERNAL_PROVIDERS = {MAGPIE_DEFAULT_PROVIDER: MAGPIE_DEFAULT_PROVIDER.capitalize()}\nMAGPIE_EXTERNAL_PROVIDERS = get_provider_names()\nMAGPIE_PROVIDER_KEYS = list(MAGPIE_INTERNAL_PROVIDERS.keys()) + list(MAGPIE_EXTERNAL_PROVIDERS.keys())\n\n\n# FIXME: use provider enum\ndef process_sign_in_external(request, username, provider):\n provider_name = provider.lower()\n if provider_name == \"openid\":\n query_field = dict(id=username)\n elif provider_name == \"github\":\n query_field = None\n # query_field = dict(login_field=username)\n elif provider_name == \"wso2\":\n query_field = {}\n else:\n query_field = dict(username=username)\n\n came_from = request.POST.get(\"came_from\", \"/\")\n request.response.set_cookie(\"homepage_route\", came_from)\n external_login_route = request.route_url(s.ProviderSigninAPI.name, provider_name=provider_name, _query=query_field)\n return HTTPTemporaryRedirect(location=external_login_route, headers=request.response.headers)\n\n\ndef verify_provider(provider_name):\n ax.verify_param(provider_name, paramName=u\"provider_name\", paramCompare=MAGPIE_PROVIDER_KEYS, isIn=True,\n httpError=HTTPNotFound, msgOnFail=s.ProviderSignin_GET_NotFoundResponseSchema.description)\n\n\n@s.SigninAPI.post(schema=s.Signin_POST_RequestSchema(), tags=[s.LoginTag], response_schemas=s.Signin_POST_responses)\n@view_config(route_name=s.SigninAPI.name, request_method=\"POST\", permission=NO_PERMISSION_REQUIRED)\ndef sign_in(request):\n \"\"\"\n Signs in a user session.\n \"\"\"\n provider_name = get_value_multiformat_post_checked(request, \"provider_name\", default=MAGPIE_DEFAULT_PROVIDER)\n provider_name = provider_name.lower()\n user_name = get_value_multiformat_post_checked(request, \"user_name\")\n password = get_multiformat_post(request, \"password\") # no check since password is None for external login\n verify_provider(provider_name)\n\n if provider_name in MAGPIE_INTERNAL_PROVIDERS.keys():\n # obtain the raw path, without any '/magpie' prefix (if any), let 'application_url' handle it\n signin_internal_path = request.route_url(\"ziggurat.routes.sign_in\", _app_url=\"\")\n signin_internal_data = {u\"user_name\": user_name, u\"password\": password, u\"provider_name\": provider_name}\n signin_sub_request = Request.blank(signin_internal_path, base_url=request.application_url,\n headers={\"Accept\": CONTENT_TYPE_JSON}, POST=signin_internal_data)\n signin_response = request.invoke_subrequest(signin_sub_request, use_tweens=True)\n if signin_response.status_code == HTTPOk.code:\n return convert_response(signin_response)\n login_failure(request, s.Signin_POST_UnauthorizedResponseSchema.description)\n\n elif provider_name in MAGPIE_EXTERNAL_PROVIDERS.keys():\n return ax.evaluate_call(lambda: process_sign_in_external(request, user_name, provider_name),\n httpError=HTTPInternalServerError,\n content={u\"user_name\": user_name, u\"provider_name\": provider_name},\n msgOnFail=s.Signin_POST_External_InternalServerErrorResponseSchema.description)\n\n\n# swagger responses referred in `sign_in`\n@view_config(context=ZigguratSignInSuccess, permission=NO_PERMISSION_REQUIRED)\ndef login_success_ziggurat(request):\n # headers contains login authorization cookie\n return ax.valid_http(httpSuccess=HTTPOk, httpKWArgs={\"headers\": request.context.headers},\n detail=s.Signin_POST_OkResponseSchema.description)\n\n\n# swagger responses referred in `sign_in`\n@view_config(context=ZigguratSignInBadAuth, permission=NO_PERMISSION_REQUIRED)\ndef login_failure(request, reason=None):\n http_err = HTTPUnauthorized\n if reason is None:\n reason = s.Signin_POST_UnauthorizedResponseSchema.description\n try:\n user_name = get_value_multiformat_post_checked(request, \"user_name\", default=None)\n get_value_multiformat_post_checked(request, \"password\", default=None)\n except HTTPException:\n http_err = HTTPBadRequest\n reason = s.Signin_POST_BadRequestResponseSchema.description\n else:\n user_name_list = ax.evaluate_call(\n lambda: [user.user_name for user in UserService.all(models.User, db_session=request.db)],\n fallback=lambda: request.db.rollback(), httpError=HTTPForbidden,\n msgOnFail=s.Signin_POST_ForbiddenResponseSchema.description)\n if user_name in user_name_list:\n http_err = HTTPInternalServerError\n reason = s.Signin_POST_Internal_InternalServerErrorResponseSchema.description\n content = ag.get_request_info(request, default_message=s.Signin_POST_UnauthorizedResponseSchema.description)\n content.update({u\"reason\": str(reason)})\n ax.raise_http(httpError=http_err, content=content, detail=s.Signin_POST_UnauthorizedResponseSchema.description)\n\n\ndef new_user_external(external_user_name, external_id, email, provider_name, db_session):\n \"\"\"\n Create new user with an External Identity.\n \"\"\"\n internal_user_name = external_id + \"_\" + provider_name\n internal_user_name = internal_user_name.replace(\" \", \"_\")\n group_name = get_constant(\"MAGPIE_USERS_GROUP\")\n create_user(internal_user_name, password=None, email=email, group_name=group_name, db_session=db_session)\n\n user = UserService.by_user_name(internal_user_name, db_session=db_session)\n # noinspection PyArgumentList\n ex_identity = models.ExternalIdentity(external_user_name=external_user_name, external_id=external_id,\n local_user_id=user.id, provider_name=provider_name)\n ax.evaluate_call(lambda: db_session.add(ex_identity), fallback=lambda: db_session.rollback(),\n httpError=HTTPConflict, msgOnFail=s.Signin_POST_ConflictResponseSchema.description,\n content={u\"provider_name\": str(provider_name),\n u\"internal_user_name\": str(internal_user_name),\n u\"external_user_name\": str(external_user_name),\n u\"external_id\": str(external_id)})\n user.external_identities.append(ex_identity)\n return user\n\n\ndef login_success_external(request, external_user_name, external_id, email, provider_name):\n # find possibly already registered user by external_id/provider\n user = ExternalIdentityService.user_by_external_id_and_provider(external_id, provider_name, request.db)\n if user is None:\n # create new user with an External Identity\n user = new_user_external(external_user_name=external_user_name, external_id=external_id,\n email=email, provider_name=provider_name, db_session=request.db)\n # set a header to remember user (set-cookie)\n headers = remember(request, user.id)\n\n # redirect to 'Homepage-Route' header only if corresponding to Magpie host\n if \"homepage_route\" in request.cookies:\n homepage_route = str(request.cookies[\"homepage_route\"])\n elif \"Homepage-Route\" in request.headers:\n homepage_route = str(request.headers[\"Homepage-Route\"])\n else:\n homepage_route = \"/\"\n header_host = urlparse(homepage_route).hostname\n magpie_host = get_magpie_url(request)\n if header_host and header_host != magpie_host:\n ax.raise_http(httpError=HTTPForbidden, detail=s.ProviderSignin_GET_ForbiddenResponseSchema.description)\n if not header_host:\n homepage_route = magpie_host + (\"/\" if not homepage_route.startswith(\"/\") else \"\") + homepage_route\n return ax.valid_http(httpSuccess=HTTPFound, detail=s.ProviderSignin_GET_FoundResponseSchema.description,\n content={u\"homepage_route\": homepage_route},\n httpKWArgs={\"location\": homepage_route, \"headers\": headers})\n\n\n@s.ProviderSigninAPI.get(schema=s.ProviderSignin_GET_RequestSchema, tags=[s.LoginTag],\n response_schemas=s.ProviderSignin_GET_responses)\n@view_config(route_name=s.ProviderSigninAPI.name, permission=NO_PERMISSION_REQUIRED)\ndef authomatic_login(request):\n \"\"\"\n Signs in a user session using an external provider.\n \"\"\"\n\n provider_name = request.matchdict.get(\"provider_name\", \"\").lower()\n response = Response()\n verify_provider(provider_name)\n try:\n authomatic_handler = authomatic_setup(request)\n\n # if we directly have the Authorization header, bypass authomatic login and retrieve 'userinfo' to signin\n if \"Authorization\" in request.headers and \"authomatic\" not in request.cookies:\n provider_config = authomatic_handler.config.get(provider_name, {})\n provider_class = resolve_provider_class(provider_config.get(\"class_\"))\n provider = provider_class(authomatic_handler, adapter=None, provider_name=provider_name)\n # provide the token user data, let the external provider update it on login afterwards\n token_type, access_token = request.headers.get(\"Authorization\").split()\n data = {\"access_token\": access_token, \"token_type\": token_type}\n cred = Credentials(authomatic_handler.config, token=access_token, token_type=token_type, provider=provider)\n provider.credentials = cred\n result = LoginResult(provider)\n # noinspection PyProtectedMember\n result.provider.user = result.provider._update_or_create_user(data, credentials=cred)\n\n # otherwise, use the standard login procedure\n else:\n result = authomatic_handler.login(WebObAdapter(request, response), provider_name)\n if result is None:\n if response.location is not None:\n return HTTPTemporaryRedirect(location=response.location, headers=response.headers)\n return response\n\n if result:\n if result.error:\n # Login procedure finished with an error.\n error = result.error.to_dict() if hasattr(result.error, \"to_dict\") else result.error\n LOGGER.debug(\"Login failure with error. [{!r}]\".format(error))\n return login_failure(request, reason=result.error.message)\n elif result.user:\n # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,\n # update the user to get more info.\n if not (result.user.name and result.user.id):\n try:\n response = result.user.update()\n # this error can happen if providing incorrectly formed authorization header\n except OAuth2Error as exc:\n LOGGER.debug(\"Login failure with Authorization header.\")\n ax.raise_http(httpError=HTTPBadRequest, content={u\"reason\": str(exc.message)},\n detail=s.ProviderSignin_GET_BadRequestResponseSchema.description)\n # verify that the update procedure succeeded with provided token\n if 400 <= response.status < 500:\n LOGGER.debug(\"Login failure with invalid token.\")\n ax.raise_http(httpError=HTTPUnauthorized,\n detail=s.ProviderSignin_GET_UnauthorizedResponseSchema.description)\n # create/retrieve the user using found details from login provider\n return login_success_external(request,\n external_id=result.user.username or result.user.id,\n email=result.user.email,\n provider_name=result.provider.name,\n external_user_name=result.user.name)\n except Exception as exc:\n exc_msg = \"Unhandled error during external provider '{}' login. [{!s}]\".format(provider_name, exc)\n LOGGER.exception(exc_msg, exc_info=True)\n ax.raise_http(httpError=HTTPInternalServerError, detail=exc_msg)\n\n LOGGER.debug(\"Reached end of login function. Response: {!r}\".format(response))\n return response\n\n\n@s.SignoutAPI.get(tags=[s.LoginTag], response_schemas=s.Signout_GET_responses)\n@view_config(context=ZigguratSignOut, permission=NO_PERMISSION_REQUIRED)\ndef sign_out(request):\n \"\"\"\n Signs out the current user session.\n \"\"\"\n return ax.valid_http(httpSuccess=HTTPOk, httpKWArgs={\"headers\": forget(request)},\n detail=s.Signout_GET_OkResponseSchema.description)\n\n\n@s.SessionAPI.get(tags=[s.LoginTag], response_schemas=s.Session_GET_responses)\n@view_config(route_name=s.SessionAPI.name, permission=NO_PERMISSION_REQUIRED)\ndef get_session(request):\n \"\"\"\n Get information about current session.\n \"\"\"\n def _get_session(req):\n authn_policy = req.registry.queryUtility(IAuthenticationPolicy)\n principals = authn_policy.effective_principals(req)\n if Authenticated in principals:\n user = request.user\n json_resp = {u\"authenticated\": True, u\"user\": format_user(user)}\n else:\n json_resp = {u\"authenticated\": False}\n return json_resp\n\n session_json = ax.evaluate_call(lambda: _get_session(request), httpError=HTTPInternalServerError,\n msgOnFail=s.Session_GET_InternalServerErrorResponseSchema.description)\n return ax.valid_http(httpSuccess=HTTPOk, detail=s.Session_GET_OkResponseSchema.description, content=session_json)\n\n\n# noinspection PyUnusedLocal\n@s.ProvidersAPI.get(tags=[s.LoginTag], response_schemas=s.Providers_GET_responses)\n@view_config(route_name=s.ProvidersAPI.name, request_method=\"GET\", permission=NO_PERMISSION_REQUIRED)\ndef get_providers(request):\n \"\"\"\n Get list of login providers.\n \"\"\"\n return ax.valid_http(httpSuccess=HTTPOk, detail=s.Providers_GET_OkResponseSchema.description,\n content={u\"providers\": {u\"internal\": sorted(MAGPIE_INTERNAL_PROVIDERS.values()),\n u\"external\": sorted(MAGPIE_EXTERNAL_PROVIDERS.values()), }})\n","sub_path":"magpie/api/login/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":15670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"282797878","text":"# 螺旋矩阵, leetcodes 54\n# https://leetcode.com/problems/spiral-matrix/discuss/20579/Simple-Python-solution-by-mutating-the-matrix\n\n# @param matrix int整型二维数组\n# @return int整型一维数组\n#\nclass Solution:\n def SpiralMatrix(self , matrix ):\n # write code here\n ans = []\n while matrix:\n ans += matrix.pop(0)\n if matrix and matrix[0]:\n for r in matrix:\n ans.append(r.pop())\n if matrix:\n ans += matrix.pop()[::-1]\n if matrix and matrix[0]:\n for r in matrix[::-1]:\n ans.append(r.pop(0))\n return ans","sub_path":"bilibili2020秋招后端第二场/bilibili2.py","file_name":"bilibili2.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"493126602","text":"import multiprocessing as mp\nfrom timeit import default_timer\nfrom datetime import timedelta\nfrom itertools import repeat\nimport ctypes\nimport sys\nfrom textwrap import dedent\nimport warnings\n\nfrom pathlib import Path\nimport shutil\n\nimport pandas as pd\nfrom numpy.random import randint as np_randint\n\nfrom .general_functions import dt_to_hms, update_progress\nfrom .rtparse import RT1_configparser\nfrom .rtfits import load\n\n\ntry:\n import xarray as xar\nexcept ModuleNotFoundError:\n print('xarray could not be imported,',\n 'NetCDF-features of RT1_results will not work!')\n\ntry:\n from netCDF4 import Dataset\nexcept ModuleNotFoundError:\n print('netCDF4.Dataset could be not imported,',\n 'some NetCDF-features of RT1_results will not work!')\n\n\ndef _confirm_input(msg='are you sure?', stopmsg='STOP', callbackdict=None):\n '''\n Parameters\n ----------\n msg : str, optional\n The prompt message. The default is 'are you sure?'.\n stopmsg : str, optional\n The message displayed if the answer is False. The default is 'STOP'.\n callbackdict : dict, optional\n A dict of the form {key: [msg, callback]} . The default is None.\n '''\n default_answers = {\"YES\": True, \"Y\": True, \"NO\": False, \"N\": False}\n\n # prompt input\n inp = str(input(msg)).upper()\n\n # in case the input is found in the callback-dict, ask for confirmation\n # and execute the callback\n if inp in callbackdict:\n cbmsg, cb = callbackdict[inp]\n inp2 = str(input(cbmsg)).upper()\n print()\n answer2 = default_answers.get(inp2, False)\n if answer2 is False:\n print(stopmsg)\n sys.exit(0)\n return\n cb()\n else:\n answer = default_answers.get(inp, False)\n if answer is False:\n print(stopmsg)\n print()\n sys.exit(0)\n return\n\n\ndef _make_folderstructure(save_path, subfolders):\n if save_path is not None:\n # generate \"save_path\" directory if it does not exist\n if not save_path.exists():\n print(f'\"{save_path}\"\\ndoes not exist... creating directory')\n save_path.mkdir(parents=True, exist_ok=True)\n\n for folder in subfolders:\n # generate subfolder if it does not exist\n mkpath = save_path / folder\n if not mkpath.exists():\n print(f'\"{mkpath}\"\\ndoes not exist... creating directory')\n mkpath.mkdir(parents=True, exist_ok=True)\n\n\ndef _setup_cnt(N_items, ncpu):\n\n manager = mp.Manager()\n lock = manager.Lock()\n p_totcnt = manager.Value(ctypes.c_ulonglong, 0)\n p_meancnt = manager.Value(ctypes.c_ulonglong, 0)\n p_time = manager.Value(ctypes.c_float, 0)\n\n process_cnt = [p_totcnt, p_meancnt, N_items, p_time, ncpu, lock]\n return process_cnt\n\n\ndef _start_cnt():\n return default_timer()\n\n\ndef _increase_cnt(process_cnt, start, err=False):\n if process_cnt is None:\n return\n\n p_totcnt, p_meancnt, p_max, p_time, p_ncpu, lock = process_cnt\n # ensure that only one process is allowed to write simultaneously\n lock.acquire()\n try:\n if err is False:\n end = default_timer()\n # increase the total counter\n p_totcnt.value += 1\n\n # update the estimate of the mean time needed to process a site\n p_time.value = (p_meancnt.value * p_time.value\n + (end - start)) / (p_meancnt.value + 1)\n # increase the mean counter\n p_meancnt.value += 1\n # get the remaining time and update the progressbar\n remain = timedelta(\n seconds=(p_max - p_totcnt.value) / p_ncpu * p_time.value)\n d, h, m, s = dt_to_hms(remain)\n\n update_progress(\n p_totcnt.value, p_max,\n title=f\"approx. {d} {h:02}:{m:02}:{s:02} remaining\",\n finalmsg=(\n \"finished! \" +\n f\"({p_max} [{p_totcnt.value - p_meancnt.value}] fits)\"),\n progress2=p_totcnt.value - p_meancnt.value)\n else:\n # only increase the total counter\n p_totcnt.value += 1\n if p_meancnt.value == 0:\n title = f\"{'estimating time ...':<28}\"\n else:\n # get the remaining time and update the progressbar\n remain = timedelta(\n seconds=(p_max - p_totcnt.value\n ) / p_ncpu * p_time.value)\n d, h, m, s = dt_to_hms(remain)\n title = f\"approx. {d} {h:02}:{m:02}:{s:02} remaining\"\n\n update_progress(\n p_totcnt.value, p_max,\n title=title,\n finalmsg=(\n \"finished! \" +\n f\"({p_max} [{p_totcnt.value - p_meancnt.value}] fits)\"),\n progress2=p_totcnt.value - p_meancnt.value)\n # release the lock\n lock.release()\n except Exception:\n # release the lock in case an error occured\n lock.release()\n pass\n\n\nclass RTprocess(object):\n def __init__(self, config_path=None, autocontinue=False,\n proc_cls=None, parent_fit=None, init_kwargs=None):\n '''\n A class to perform parallelized processing.\n\n Parameters\n ----------\n config_path : str, optional\n The path to the config-file to be used. The default is None.\n autocontinue : bool, optional\n indicator if user-input should be raised (True) in case the\n dump-folder already exists. The default is False.\n proc_cls : class, optional\n the processing-class. (if None it will be imported use the\n 'module__processing_cfg' from the 'CONFIGFILES' section of\n the .ini file).\n\n NOTICE:\n All parsed arguments from the 'PROCESS_SPECS' section of\n the config-file will be used in the initialization of\n the processing class! The call-signature is equivalent to:\n\n >>> from rt1.rtparse import RT1_configparser\n ... cfg = RT1_configparser(config_path)\n ... proc_cls = proc_cls(**cfg.get_process_specs(),\n **init_kwargs)\n\n For details on how to specify a processing-class, have look at\n the `rt1_processing_config` class in `rt1.processing_config`.\n The default is None.\n parent_fit : rt1.rtfits.Fits, optional\n a parent fit-object. (if None it will be set-up\n using the specifications of the .ini file) The default is None.\n init_kwargs : dict, optional\n Additional keyword-arguments passed to the initialization of the\n 'proc_cls' class. (used to append-to or partially overwrite\n definitions passed via the config-file). The default is None.\n\n\n '''\n self._config_path = config_path\n self.autocontinue = autocontinue\n\n self._proc_cls = proc_cls\n self._parent_fit = parent_fit\n if init_kwargs is None:\n self.init_kwargs = dict()\n else:\n\n assert all([isinstance(i, str) for i in init_kwargs.values()]), (\n 'the values of \"init_kwargs\" MUST be strings !')\n self.init_kwargs = init_kwargs\n\n def setup(self, copy=True):\n '''\n perform necessary tasks to run a processing-routine\n - initialize the folderstructure (only from MainProcess!)\n - copy modules and .ini files (if copy=True) (only from MainProcess!)\n - load modules and set parent-fit-object\n\n Parameters\n ----------\n copy : bool\n indicator if '.ini' files and modules should be copied to\n the dumppath/cfg folder or not. The default is True.\n '''\n if self._config_path is not None and self._proc_cls is None:\n\n self.config_path = Path(self._config_path)\n assert self.config_path.exists(), (f'the file {self.config_path} '\n + 'does not exist!')\n\n self.cfg = RT1_configparser(self.config_path)\n\n # update specs with init_kwargs\n for key, val in self.init_kwargs.items():\n if key in self.cfg.config['PROCESS_SPECS']:\n warnings.warn(\n f'\"{key} = {self.cfg.config[\"PROCESS_SPECS\"][key]}\"' +\n 'will be overwritten by the definition provided via' +\n f'\"init_kwargs\": \"{key} = {val}\" ')\n # update the parsed config (for import of modules etc.)\n self.cfg.config['PROCESS_SPECS'][key] = val\n\n specs = self.cfg.get_process_specs()\n\n self.dumppath = specs['save_path'] / specs['dumpfolder']\n\n if mp.current_process().name == 'MainProcess':\n # init folderstructure and copy files only from main process\n if self.autocontinue is False:\n\n if self.dumppath.exists():\n def remove_folder():\n shutil.rmtree(\n specs['save_path'] / specs['dumpfolder'])\n warnings.warn(\n f'\"{specs[\"save_path\"]/specs[\"dumpfolder\"]}\"' +\n '\\nhas successfully been removed.\\n')\n\n _confirm_input(\n msg=(f'the path \\n \"{self.dumppath}\"\\n' +\n ' already exists...' +\n '\\n- to continue type YES or Y' +\n '\\n- to abort type NO or N' +\n '\\n- to remove the existing directory and ' +\n 'all subdirectories type REMOVE \\n \\n'),\n callbackdict={'REMOVE': [\n (f'\\n\"{self.dumppath}\"\\n will be removed!' +\n ' are you sure? (y, n): '),\n remove_folder]})\n\n # initialize the folderstructure\n _make_folderstructure(specs['save_path'] / specs['dumpfolder'],\n ['results', 'cfg', 'dumps'])\n\n if copy is True:\n self._copy_cfg_and_modules()\n\n # load the processing-class\n if 'processing_cfg_module' in specs:\n proc_module_name = specs['processing_cfg_module']\n else:\n proc_module_name = 'processing_cfg'\n\n if 'processing_cfg_class' in specs:\n proc_class_name = specs['processing_cfg_class']\n else:\n proc_class_name = 'processing_cfg'\n\n # load ALL modules to ensure that the importer finds them\n procmodule = self.cfg.get_all_modules(\n load_copy=copy)[proc_module_name]\n\n warnings.warn(f'processing config class \"{proc_class_name}\"' +\n f' will be imported from \\n\"{procmodule}\"')\n\n self.proc_cls = getattr(procmodule, proc_class_name)(**specs)\n\n # get the parent fit-object\n if self._parent_fit is None:\n self.parent_fit = self.cfg.get_fitobject()\n else:\n self.parent_fit = self._parent_fit\n else:\n self.dumppath = None\n\n # check if all necessary functions are defined in the processing-class\n for key in ['preprocess', 'reader', 'postprocess', 'finaloutput',\n 'exceptfunc']:\n assert hasattr(self.proc_cls, key), (\n f'a function {key}() MUST be provided in the config-class!')\n\n assert self.parent_fit is not None, (\n 'you MUST provide a valid config-file or a parent_fit-object!')\n\n def _copy_cfg_and_modules(self):\n # if copy is True, copy the config-file and re-import the cfg\n # from the copied file\n copypath = self.dumppath / 'cfg' / self.cfg.configpath.name\n if (copypath).exists():\n warnings.warn(\n f'the file \\n\"{copypath / self.cfg.configpath.name}\"\\n' +\n 'already exists... NO copying is performed and the ' +\n 'existing one is used!\\n')\n else:\n if len(self.init_kwargs) == 0:\n # if no init_kwargs have been provided, copy the\n # original file\n shutil.copy(self.cfg.configpath, copypath.parent)\n warnings.warn(f'\"{self.cfg.configpath.name}\" copied to\\n' +\n f'\"{copypath.parent}\"')\n else:\n # if init_kwargs have been provided, write the updated\n # config to the folder\n with open(copypath.parent /\n self.cfg.configpath.name, 'w') as file:\n self.cfg.config.write(file)\n\n warnings.warn(\n f'the config-file \"{self.cfg.configpath}\" has been' +\n ' updated with the init_kwargs and saved to' +\n f'\"{copypath.parent / self.cfg.configpath.name}\"')\n\n # remove the config and re-read the config from the copied path\n del self.cfg\n self.cfg = RT1_configparser(copypath)\n\n # copy modules\n for key, val in self.cfg.config['CONFIGFILES'].items():\n if key.startswith('module__'):\n modulename = key[8:]\n\n module_path = self.cfg.config[\n 'CONFIGFILES'][f'module__{modulename}']\n\n location = Path(module_path.strip())\n\n copypath = self.dumppath / 'cfg' / location.name\n\n if copypath.exists():\n warnings.warn(f'the file \\n\"{copypath}\" \\nalready ' +\n 'exists ... NO copying is performed ' +\n 'and the existing one is used!\\n')\n else:\n shutil.copy(location, copypath)\n warnings.warn(\n f'\"{location.name}\" copied to \\n\"{copypath}\"')\n\n def _evalfunc(self, reader_arg=None, process_cnt=None):\n \"\"\"\n Initialize a Fits-instance and perform a fit.\n (used for parallel processing)\n\n Parameters\n ----------\n reader_arg : dict\n A dict of arguments passed to the reader.\n process_cnt : list\n A list of shared-memory variables that are used to update the\n progressbar\n Returns\n -------\n The used 'rt1.rtfit.Fits' object or the output of 'postprocess()'\n \"\"\"\n if process_cnt is not None:\n start = _start_cnt()\n try:\n # if a reader (and no dataset) is provided, use the reader\n read_data = self.proc_cls.reader(reader_arg)\n # check for multiple return values and split them accordingly\n # (any value beyond the first is appended as aux_data)\n if isinstance(read_data, pd.DataFrame):\n dataset = read_data\n aux_data = None\n elif (isinstance(read_data, (list, tuple))\n and isinstance(read_data[0], pd.DataFrame)):\n if len(read_data) == 2:\n dataset, aux_data = read_data\n elif len(read_data) > 2:\n dataset = read_data[0]\n aux_data = read_data[1:]\n else:\n raise TypeError('the first return-value of reader function ' +\n 'must be a pandas DataFrame')\n # initialize a new fits-object and perform the fit\n fit = self.parent_fit.reinit_object(dataset=dataset)\n fit.performfit()\n\n # append auxiliary data\n if aux_data is not None:\n fit.aux_data = aux_data\n\n # append reader_arg\n fit.reader_arg = reader_arg\n _increase_cnt(process_cnt, start, err=False)\n\n # if a post-processing function is provided, return its output,\n # else return the fit-object directly\n if callable(self.proc_cls.postprocess):\n ret = self.proc_cls.postprocess(fit, reader_arg)\n else:\n ret = fit\n\n return ret\n\n except Exception as ex:\n\n if callable(self.proc_cls.exceptfunc):\n ex_ret = self.proc_cls.exceptfunc(ex, reader_arg)\n if ex_ret is None or ex_ret is False:\n _increase_cnt(process_cnt, start, err=True)\n else:\n _increase_cnt(process_cnt, start, err=False)\n\n return ex_ret\n else:\n raise ex\n\n def processfunc(self, ncpu=1, print_progress=True,\n reader_args=None, pool_kwargs=None,\n preprocess_kwargs=None):\n \"\"\"\n Evaluate a RT-1 model on a single core or in parallel using\n\n - a list of datasets or\n - a reader-function together with a list of arguments that\n will be used to read the datasets\n\n Notice:\n On Windows, if multiprocessing is used, you must protect the call\n of this function via:\n (see for example: )\n\n >>> if __name__ == '__main__':\n fit.processfunc(...)\n\n In order to allow pickling the final rt1.rtfits.Fits object,\n it is required to store ALL definitions within a separate\n file and call processfunc in the 'main'-file as follows:\n\n >>> from specification_file import fit reader lsq_kwargs ... ...\n if __name__ == '__main__':\n fit.processfunc(ncpu=5, reader=reader,\n lsq_kwargs=lsq_kwargs, ... ...)\n\n Parameters\n ----------\n ncpu : int, optional\n The number of kernels to use. The default is 1.\n print_progress : bool, optional\n indicator if a progress-bar should be printed to stdout or not\n that looks like this:\n\n >>> approx. 0 00:00:02 remaining ################------ 3 (2) / 4\n ...\n ... (estimated time day HH:MM:SS)( progress bar )( counts )\n ... ( counts ) = finished fits [actually fitted] / total\n\n The default is True.\n reader_args : list, optional\n A list of dicts that will be passed to the reader-function.\n I `None`, the `reader_args` will be taken from the return of the\n `preprocess()`-function via:\n\n >>> reader_args = preprocess(**preprocess_kwargs)['reader_args']\n\n The default is None.\n pool_kwargs : dict, optional\n A dict with additional keyword-arguments passed to the\n initialization of the multiprocessing-pool via:\n\n >>> mp.Pool(ncpu, **pool_kwargs)\n\n The default is None.\n preprocess_kwargs : dict, optional\n A dict with keyword-arguments passed to the call of the preprocess\n function via:\n\n >>> preprocess(**preprocess_kwargs)\n\n The default is None.\n Returns\n -------\n res : list\n A list of rt1.rtfits.Fits objects or a list of outputs of the\n postprocess-function.\n\n \"\"\"\n\n if callable(self.proc_cls.preprocess):\n setupdict = self.proc_cls.preprocess(**preprocess_kwargs)\n if setupdict is None:\n setupdict = dict()\n assert isinstance(setupdict, dict), (\n 'the preprocess() function must return a dict!')\n else:\n setupdict = dict()\n\n # check if reader args is provided in setupdict\n if reader_args is None:\n assert 'reader_args' in setupdict, (\n 'if \"reader_args\" is not passed directly to processfunc() ' +\n ', the preprocess() function must return a key \"reader_args\"!')\n\n reader_args = setupdict['reader_args']\n else:\n assert 'reader_args' not in setupdict, (\n '\"reader_args\" is provided as argument to processfunc() ' +\n 'AND via the return-dict of the preprocess() function!')\n\n print(f'processing {len(reader_args)} features')\n\n if 'pool_kwargs' in setupdict:\n pool_kwargs = setupdict['pool_kwargs']\n\n if pool_kwargs is None:\n pool_kwargs = dict()\n\n if self.parent_fit.int_Q is True:\n # pre-evaluate the fn-coefficients if interaction terms are used\n self.parent_fit._fnevals_input = self.parent_fit.R._fnevals\n\n if print_progress is True:\n # initialize shared values that will be used to track the number\n # of completed processes and the mean time to complete a process\n process_cnt = _setup_cnt(N_items=len(reader_args), ncpu=ncpu)\n else:\n process_cnt = None\n\n if ncpu > 1:\n print('start of parallel evaluation')\n with mp.Pool(ncpu, **pool_kwargs) as pool:\n # loop over the reader_args\n res_async = pool.starmap_async(self._evalfunc,\n zip(reader_args,\n repeat(process_cnt)))\n\n pool.close() # Marks the pool as closed.\n pool.join() # Waits for workers to exit.\n res = res_async.get()\n else:\n print('start of single-core evaluation')\n\n # call the initializer if it has been provided\n if 'initializer' in pool_kwargs:\n if 'initargs' in pool_kwargs:\n pool_kwargs['initializer'](*pool_kwargs['initargs'])\n else:\n pool_kwargs['initializer']()\n res = []\n for reader_arg in reader_args:\n res.append(self._evalfunc(reader_arg=reader_arg,\n process_cnt=process_cnt))\n\n if callable(self.proc_cls.finaloutput):\n return self.proc_cls.finaloutput(res)\n else:\n return res\n\n def run_processing(self, ncpu=1, copy=True, print_progress=True,\n reader_args=None, pool_kwargs=None,\n preprocess_kwargs=None):\n '''\n Start the processing\n\n Parameters\n ----------\n ncpu : int\n The number of cpu's to use. The default is 1.\n copy : bool, optional\n Indicator if the used config-file and all modules specified in the\n \"CONFIGFILES\" section of the config-file should be copied to\n \"/dumpfolder/cfg\" or not. The default is True.\n print_progress : bool, optional\n Indicator if a progress-bar should be printed or not.\n If True, it might be wise to suppress warnings during runtime\n to avoid unwanted outputs. This can be achieved by using:\n\n >>> import warnings\n ... warnings.simplefilter('ignore')\n\n The default is True.\n reader_args : list, optional\n A list of dicts that will be passed to the reader-function.\n I `None`, the `reader_args` will be taken from the return of the\n `preprocess()`-function via:\n\n >>> reader_args = preprocess(**preprocess_kwargs)['reader_args']\n\n The default is None.\n pool_kwargs : dict, optional\n A dict with additional keyword-arguments passed to the\n initialization of the multiprocessing-pool via:\n\n >>> mp.Pool(ncpu, **pool_kwargs)\n\n The default is None.\n preprocess_kwargs : dict, optional\n A dict with keyword-arguments passed to the call of the preprocess\n function via:\n\n >>> preprocess(**preprocess_kwargs)\n\n The default is None.\n\n '''\n print('############################################################\\n')\n\n # initialize all necessary properties\n self.setup(copy=copy)\n\n if preprocess_kwargs is None:\n preprocess_kwargs = dict()\n\n # save the used model-definition string to a file\n if self.dumppath is not None:\n with open(self.dumppath / 'cfg' / 'model_definition.txt',\n 'w') as file:\n\n outtxt = ''\n if hasattr(self.proc_cls, 'description'):\n outtxt += dedent(self.proc_cls.description)\n outtxt += '\\n\\n'\n outtxt += '_'*77\n outtxt += '\\n\\n'\n\n outtxt += self.parent_fit._model_definition\n\n print(outtxt, file=file)\n\n _ = self.processfunc(ncpu=ncpu, print_progress=print_progress,\n reader_args=reader_args, pool_kwargs=pool_kwargs,\n preprocess_kwargs=preprocess_kwargs)\n\n\nclass RTresults(object):\n '''\n A class to provide easy access to processed results.\n On initialization the class will traverse the provided \"parent_path\"\n and recognize any sub-folder that matches the expected folder-structure\n as a sub-result.\n\n\n Assuming a folder-structure as indicated below, the class can be used via:\n\n >>> ../../RESULTS (parent_path)\n ... results/.. (.nc files)\n ... dumps/.. (.dump files)\n ... cfg/.. (.ini files)\n ...\n ... sub_RESULT1\n ... results/.. (.nc files)\n ... dumps/.. (.dump files)\n ... cfg/.. (.ini files)\n ...\n ... sub_RESULT2\n ... ....\n\n\n >>> results = RT1_results(parent_path)\n ... # print available NetCDF files and variables\n ... x.RESULTS.NetCDF_variables\n ... x.sub_RESULT_1.NetCDF_variables\n ...\n ... # load some dump-files\n ... fit_random = results.sub_RESULT_1.load_fit()\n ... fit1_0 = results.RESULT.load_fit('id_of_fit_1')\n ... fit1_1 = results.sub_RESULT_1.load_fit('id_of_fit_1')\n ... fit1_2 = results.sub_RESULT_2.load_fit('id_of_fit_1')\n ...\n ... # access a NetCDF file\n ... with results.sub_RESULT_2.load_nc() as ncfile:\n ... --- read something from the ncfie ---\n ...\n ... # get a generator for the paths of all available dump-files\n ... dump-files = results.sub_RESULT_1.dump_files\n ...\n ... # load the configfile of a given fit\n ... cfg_01 = results.sub_RESULT_1.load_cfg()\n\n\n Parameters\n ----------\n parent_path : str\n the parent-path where the results are stored.\n '''\n\n def __init__(self, parent_path):\n self._parent_path = Path(parent_path)\n\n self._paths = dict()\n\n if all(i in [i.stem for i in self._parent_path.iterdir()]\n for i in ['cfg', 'results', 'dumps']):\n self._paths[self._parent_path.stem] = self._parent_path\n print('... adding result', self._parent_path.stem)\n setattr(self, self._parent_path.stem,\n self._RT1_fitresult(self._parent_path.stem,\n self._parent_path))\n\n for p in self._parent_path.iterdir():\n if p.is_dir():\n if all(i in [i.stem for i in p.iterdir()]\n for i in ['cfg', 'results', 'dumps']):\n self._paths[p.stem] = p\n print('... adding result', p.stem)\n setattr(self, p.stem,\n self._RT1_fitresult(p.stem, p))\n\n class _RT1_fitresult(object):\n def __init__(self, name, path):\n self.name = name\n self.path = Path(path)\n self._result_path = self.path / 'results'\n self._dump_path = self.path / 'dumps'\n self._cfg_path = self.path / 'cfg'\n\n def _get_results(self, ending):\n assert self._result_path.exists(), f'{self._result_path}' + \\\n ' does not exist'\n\n results = {i.stem: i for i in self._result_path.iterdir()\n if i.suffix == ending}\n\n assert len(results) > 0, f'there is no \"{ending}\" file' + \\\n f' in \"{self._result_path}\"'\n\n return results\n\n def load_nc(self, result_name=None, use_xarray=True):\n '''\n open a NetCDF file stored in the \"results\"-folder\n\n can be used as context-manager, e.g.:\n\n >>> with result.load_nc() as ncfile:\n ... --- do something ---\n\n\n Parameters\n ----------\n result_name : str, optional\n The name of the NetCDF-file (without a .nc extension).\n If None, and only 1 file is available, the available file\n will be laoded. The default is None.\n use_xarray : bool, optional\n Indicator if NetCDF4 or xarray should be used to\n laod the NetCDF file. The default is True.\n\n Returns\n -------\n file : a file-handler for the NetCDF file\n the return of either xarray.Dataset or NetCDF4.Dataset\n '''\n results = self._get_results('.nc')\n\n assert len(results) == 1 or result_name in results, (\n ('there is more than 1 result... ' +\n 'provide \"result_name\":\\n - ' +\n '\\n - '.join(results.keys())))\n\n if result_name is None:\n result_name = list(results.keys())[0]\n\n # print(f'loading nc-file for {result_name}')\n if use_xarray is True:\n file = xar.open_dataset(results[result_name])\n else:\n file = Dataset(results[result_name])\n return file\n\n def load_fit(self, ID=None, return_ID=False):\n '''\n load one of the available .dump-files located in the \"dumps\"\n folder. (using rt1.rtfits.load() )\n\n Notice: the dump-files are generated using cloudpickle.dump()\n and might be platform and environment-specific!\n\n Parameters\n ----------\n ID : str, optional\n The name of the dump-file to be loaded (without the .dump\n extension). If None, a random file will be selected.\n The default is None.\n return_ID : bool, optional\n If True, a tuple (fit, ID) is returned, otherwise only\n the fit is returned\n\n Returns\n -------\n fit : rt1.rtfits.Fits\n the loaded rt1.rtfits.Fits result.\n '''\n\n if ID is None:\n allfiles = list(self.dump_files)\n Nid = np_randint(0, len(allfiles) - 1)\n\n ID = allfiles[Nid].stem\n print(f'loading random ID ({ID}) from {len(allfiles)} ' +\n 'available files')\n\n fit = load(self._dump_path / (ID + '.dump'))\n\n if return_ID is True:\n return (fit, ID)\n else:\n return fit\n\n def load_cfg(self, cfg_name=None):\n '''\n load the configfile stored in the \"cfg\" folder\n\n Parameters\n ----------\n cfg_name : str, optional\n The name of the config-file to laod in case more than 1\n \".ini\"-files are found. The default is None.\n\n Returns\n -------\n cfg : rt1.rtparse.RT1_configparser\n a configparser instance of the selected configuration.\n\n '''\n cfgfiles = list(self._cfg_path.glob('*.ini'))\n assert len(cfgfiles) > 0, 'NO \".ini\"-file found!'\n\n if cfg_name is None:\n assert len(cfgfiles) == 1, (\n 'there is more than 1 .ini file in the cfg folder...' +\n 'provide a \"cfg_name\":\\n' +\n ' - ' + '\\n - '.join([i.name for i in cfgfiles]))\n\n cfg_name = cfgfiles[0].name\n\n cfg = RT1_configparser(self._cfg_path / cfg_name)\n return cfg\n\n @property\n def dump_files(self):\n '''\n a generator of the available dump-files\n '''\n return (i for i in self._dump_path.iterdir()\n if i.suffix == '.dump' and 'error' not in i.stem)\n\n @property\n def NetCDF_variables(self):\n '''\n print all available NetCDF-files and their variables\n '''\n results = self._get_results('.nc')\n\n for r in results:\n print('\\nresult: ', r)\n with self.load_nc(r, use_xarray=False) as ncfile:\n space = len(max(ncfile.variables.keys(), key=len))\n for key, val in ncfile.variables.items():\n if key in ncfile.dimensions.keys():\n print('dimension: ', *zip(val.dimensions,\n val.shape))\n else:\n print(f'{key:<{space + 7}}', val.dimensions)\n","sub_path":"rt1/rtprocess.py","file_name":"rtprocess.py","file_ext":"py","file_size_in_byte":33539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"447184241","text":"#\n# @lc app=leetcode id=86 lang=python3\n#\n# [86] Partition List\n#\n# https://leetcode.com/problems/partition-list/description/\n#\n# algorithms\n# Medium (46.13%)\n# Likes: 2694\n# Dislikes: 437\n# Total Accepted: 300.5K\n# Total Submissions: 650.7K\n# Testcase Example: '[1,4,3,2,5,2]\\n3'\n#\n# Given the head of a linked list and a value x, partition it such that all\n# nodes less than x come before nodes greater than or equal to x.\n# \n# You should preserve the original relative order of the nodes in each of the\n# two partitions.\n# \n# \n# Example 1:\n# \n# \n# Input: head = [1,4,3,2,5,2], x = 3\n# Output: [1,2,2,4,3,5]\n# \n# \n# Example 2:\n# \n# \n# Input: head = [2,1], x = 2\n# Output: [1,2]\n# \n# \n# \n# Constraints:\n# \n# \n# The number of nodes in the list is in the range [0, 200].\n# -100 <= Node.val <= 100\n# -200 <= x <= 200\n# \n# \n#\n\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n # solution: Your runtime beats 63.21 % of python3 submissions\n def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n if not head or not head.next:\n return head \n\n first, second = ListNode(0),ListNode(0)\n left, right = first, second\n while head:\n if head.val < x:\n left.next = head\n left = left.next \n else:\n right.next = head\n right = right.next \n \n head = head.next \n \n right.next = None\n left.next = second.next\n return first.next\n \n\n \n# @lc code=end\n\n","sub_path":"Python/86.partition-list.py","file_name":"86.partition-list.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"641484475","text":"def miniMaxSum(a):\r\n p = a.split()\r\n n = []\r\n s = []\r\n for each in p:\r\n n.append(int(each))\r\n s.append(int(each))\r\n # print(n)\r\n \r\n x = []\r\n for i in range(4):\r\n biggest = max(n)\r\n x.append(biggest)\r\n #print(x)\r\n n.remove(biggest)\r\n\r\n totmax = 0\r\n for each in x:\r\n totmax += each\r\n\r\n y = []\r\n for i in range(4):\r\n smallest = min(s)\r\n y.append(smallest)\r\n #print(y)\r\n s.remove(smallest)\r\n\r\n totmin = 0\r\n for each in y:\r\n totmin += each\r\n print(str(totmin) + \" \" + str(totmax))\r\n\r\n\r\na = input()\r\nminiMaxSum(a)","sub_path":"minimaxsum.py","file_name":"minimaxsum.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"176427103","text":"# You are given the current stock prices. You have to find out which stocks cost more.\n#\n# Input:\n# The dictionary where the market identifier code is a key and the value is a stock price.\n#\n# Output:\n# A string and the market identifier code.\n#\n# Example:\n# best_stock({\n# 'CAC': 10.0,\n# 'ATX': 390.2,\n# 'WIG': 1.2\n# }) == 'ATX'\n# best_stock({\n# 'CAC': 91.1,\n# 'ATX': 1.01,\n# 'TASI': 120.9\n# }) == 'TASI'\n# Preconditions:\n# All the prices are unique.\n\ndef best_stock(data: dict) -> str:\n\tkey_list = list(data.keys())\n\tvalue_list = list(data.values())\n\tmax_value = max(data.values())\n\tvalue_index = value_list.index(max_value)\n\treturn key_list[value_index]\n\nif __name__ == '__main__':\n\tprint(\"Example:\")\n\tprint(best_stock({\n\t\t'CAC': 10.0,\n\t\t'ATX': 390.2,\n\t\t'WIG': 1.2\n\t}))\n\n\t# These \"asserts\" are used for self-checking and not for an auto-testing\n\tassert best_stock({\n\t\t'CAC': 10.0,\n\t\t'ATX': 390.2,\n\t\t'WIG': 1.2\n\t}) == 'ATX', \"First\"\n\tassert best_stock({\n\t\t'CAC': 91.1,\n\t\t'ATX': 1.01,\n\t\t'TASI': 120.9\n\t}) == 'TASI', \"Second\"\n\tprint(\"Coding complete? Click 'Check' to earn cool rewards!\")","sub_path":"2_Elementary/02_Best_Stock.py","file_name":"02_Best_Stock.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"398694104","text":"\"\"\"\nDefinition of views.\n\"\"\"\n\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpRequest\nfrom django.template import RequestContext\nfrom datetime import datetime\nfrom .forms import Feedback\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.db import models\nfrom .models import Blog\nfrom .models import Comment\nfrom .forms import CommentForm\nfrom .forms import BlogForm\n\ndef home(request):\n \"\"\"Renders the home page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/index.html',\n {\n 'title':'Главная',\n 'year':datetime.now().year,\n }\n )\n\ndef contact(request):\n \"\"\"Renders the contact page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/contact.html',\n {\n 'title':'Контакты',\n 'message':'Страница с нашими контактами',\n 'year':datetime.now().year,\n }\n )\n\ndef about(request):\n \"\"\"Renders the about page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/about.html',\n {\n 'title':'О Нас',\n 'message':'Сведения о нас',\n 'year':datetime.now().year,\n }\n )\n\ndef blog(request):\n \"\"\"Renders the blog page.\"\"\"\n assert isinstance(request, HttpRequest)\n posts = Blog.objects.all() #запрос всех статей из модели\n return render(\n request,\n 'app/blog.html',\n {\n 'title':'Блог',\n 'posts':posts, #передача списка статей в шаблон\n 'year':datetime.now().year,\n }\n )\n\ndef blogpost(request, parametr):\n \"\"\"Renders the blog page.\"\"\"\n post_1 = Blog.objects.get(id=parametr) # запрос нужного поста\n comments = Comment.objects.filter(post=parametr)\n\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment_f = form.save(commit = False)\n comment_f.author = request.user\n comment_f.date = datetime.now()\n comment_f.post = Blog.objects.get(id=parametr)\n comment_f.save()\n\n return redirect('blogpost', parametr=post_1.id)\n else:\n form = CommentForm()\n\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/blogpost.html',\n {\n 'post_1':post_1, #передача конкретной статьи в шаблон веб страницы\n 'comments' :comments,\n 'form' :form,\n 'year' :datetime.now().year,\n }\n )\n\ndef links (request):\n \"\"\"Renders the links page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/links.html',\n {\n 'title':'Полезные ресурсы',\n 'message':'Переход по этим ссылкам поможет вам набраться опыта по ремонту, а так же послушать хорошую музыку во время этого!',\n 'year':datetime.now().year,\n }\n )\n\ndef feedback(request):\n \"\"\"Renders the links page.\"\"\"\n assert isinstance(request, HttpRequest)\n data = None\n gender = {'1':'Мужчина', '2': 'Женщина'}\n usage = {'1':'Месяц','2':'Полгода',\n '3':'Год', '4':'Два года',\n '5':'Три года','6':'Четыре года',\n '7':'Пять и более лет'}\n if request.method == 'POST':\n form = Feedback(request.POST)\n if form.is_valid():\n data = dict()\n data['name'] = form.cleaned_data['name']\n data['city'] = form.cleaned_data['city']\n data['gender'] = gender[ form.cleaned_data['gender'] ]\n data['usage'] = usage[ form.cleaned_data['usage'] ]\n if(form.cleaned_data['notice'] == True):\n data['notice'] = 'Да'\n else:\n data['notice'] = 'Нет'\n data['email'] = form.cleaned_data['email']\n data['message'] = form.cleaned_data['message']\n form = None\n else:\n form = Feedback()\n return render(\n request,\n 'app/feedback.html',\n {\n 'form':form,\n 'data':data\n }\n )\n\ndef registration(request):\n \"\"\"Renders the registration page.\"\"\"\n if request.method == \"POST\": # после отправки формы\n regform = UserCreationForm (request.POST)\n if regform.is_valid(): #валидация полей формы\n reg_f = regform.save(commit=False) # не сохраняем автоматически данные формы\n reg_f.is_staff = False # запрещен вход в административный раздел\n reg_f.is_active = True # активный пользователь\n reg_f.is_superuser = False # не является суперпользователем\n reg_f.date_joined = datetime.now() # дата регистрации\n reg_f.last_login = datetime.now() # дата последней авторизации\n reg_f.save() # сохраняем изменения после добавления данных\n return redirect('home') # переадресация на главную страницу после регистрации\n else:\n regform = UserCreationForm() # создание объекта формы для ввода данных нового пользователя\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/registration.html',\n {\n 'regform': regform, # передача формы в шаблон веб-страницы\n 'year':datetime.now().year,\n }\n )\n\ndef newpost(request):\n \"\"\"Render the newpost page\"\"\"\n\n if request.method == \"POST\":\n blogform = BlogForm(request.POST, request.FILES)\n if blogform.is_valid():\n blog_f = blogform.save(commit = False)\n blog_f.posted = datetime.now()\n blog_f.save()\n\n return redirect('blog')\n else:\n blogform = BlogForm()\n\n assert isinstance (request, HttpRequest)\n return render(\n request,\n 'app/newpost.html',\n {\n 'blogform':blogform,\n 'year':datetime.now().year,\n }\n )\n\ndef videopost(request):\n \"\"\"Renders the about page.\"\"\"\n assert isinstance(request, HttpRequest)\n return render(\n request,\n 'app/videopost.html',\n {\n 'year':datetime.now().year,\n }\n )\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"52189077","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 4 23:38:16 2017\n\n@author: Siddharth\n\"\"\"\n\nimport numpy as np\nimport os\nimport cv2\nimport tensorflow as tf\n\n#Student Information\nprint('UBitName = vvasanth')\nprint('personNumber = 50248708')\nprint('UBitName = ss623')\nprint('personNumber = 50247317')\nprint('UBitName = rajvinod')\nprint('personNumber = 50247214')\n\ntest=[]\na=[]\ntrain_labels=[]\ntest_labels=[]\nval_labels=[]\n\n#eyeglass labels into array\nlabelnew=np.zeros(shape=(202599,2))\nf=open('CelebA\\\\Anno\\\\list_attr_celeba','r') \ntestsite_array=f.readlines() \nfor i in range(2,len(testsite_array)):\n test=testsite_array[i].split()\n a.append(test[15])\nresults = [int(j) for j in a]\nlabels = np.asarray(results)\nfor i in range (len(labels)):\n if (labels[i] == 1):\n labelnew[i]= [1,0] \n else:\n\t labelnew[i]= [0,1] \nlabelnew=np.asarray(labelnew)\n\n#partitioning labels\ntrain_n=int(0.8*len(labelnew))\ny=int(0.1*len(labelnew))\ntest_n=train_n+y\nval_n=test_n+y\n\nfor i in range(0,train_n):\n train_labels.append(labelnew[i])\ntrain_labels=np.asarray(train_labels)\n\nfor i in range(train_n,test_n):\n test_labels.append(labelnew[i])\ntest_labels=np.asarray(test_labels)\n\nfor i in range(test_n,len(labels)):\n val_labels.append(labelnew[i])\nval_labels=np.asarray(val_labels)\n\n\n#image resize function\ndef resize_scale(img, size):\n img=cv2.resize(img, size)\n return np.array(img,\"float32\")\n\n#images into array\ndata=[]\nlabel=[]\nattribute=[]\ntrain_data=[]\ntest_data=[]\nval_data=[]\nsample_data=[]\npath_to_data=\"CelebA\\\\Img\\\\img_align_celeba\\\\\"\nimg_list=os.listdir(path_to_data)\nsz=(28,28)\nfor name in sorted(img_list):\n if '.jpg' in name:\n img=cv2.imread(path_to_data + name)\n img=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n padded_img=cv2.copyMakeBorder(img,1,1,1,1,cv2.BORDER_CONSTANT)\n resized_img=resize_scale(padded_img, sz)\n data.append(resized_img.flatten())\ndata=np.array(data)\n\n#partitioning images\ntrain_d=int(0.8*len(labelnew))\nz=int(0.1*len(labelnew))\ntest_d=train_d+z\nval_d=test_d+z\n\nfor i in range(0,train_d):\n train_data.append(data[i])\ntrain_data=np.asarray(train_data)\n\nfor i in range(train_d,test_d):\n test_data.append(data[i])\ntest_data=np.asarray(test_data)\n\nfor i in range(test_d,len(data)):\n val_data.append(data[i])\nval_data=np.asarray(val_data)\n\n#next_batch function\ndef next_batch(num, data_, labels_):\n\n idx = np.arange(0 , len(data_))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = data_[idx]\n labels_shuffle = labels_[idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\nbatch_x, batch_y = next_batch(5, test_data, test_labels)\n\n# Training Parameters\nlearning_rate = 0.001\nnum_steps = 200\nbatch_size = 50\ndisplay_step = 10\n\n# Network Parameters\nnum_input = 784# celebA data input (img shape: 28*28)\nnum_classes = 2 # celebA total classes (0-9 digits)\ndropout = 0.75 # Dropout, probability to keep units\n\n# tf Graph input\nX = tf.placeholder(tf.float32, [None, num_input])\nY = tf.placeholder(tf.float32, [None, num_classes])\nkeep_prob = tf.placeholder(tf.float32) # dropout (keep probability)\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\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],\n padding='SAME')\n\n#next_batch function\ndef next_batch(num, data_, labels_):\n\n \n #Return a total of `num` random samples and labels. \n \n idx = np.arange(0 , len(data_))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = data_[idx]\n labels_shuffle = labels_[idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n \n\n# Create model\ndef conv_net(x, weights, biases, dropout):\n # celebA data input is a 1-D vector of 784 features (28*28 pixels)\n # Reshape to match picture format [Height x Width x Channel]\n # Tensor input become 4-D: [Batch Size, Height, Width, Channel]\n x = tf.reshape(x, shape=[-1, 28, 28, 1])\n\n # Convolution Layer\n conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n # Max Pooling (down-sampling)\n conv1 = maxpool2d(conv1, k=2)\n\n # Convolution Layer\n conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n # Max Pooling (down-sampling)\n conv2 = maxpool2d(conv2, k=2)\n\n # Fully connected layer\n # Reshape conv2 output to fit fully connected layer input\n fc1 = tf.reshape(conv2, [-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 # Output, class prediction\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out\n\n# Store layers weight & bias\nweights = {\n # 5x5 conv, 1 input, 32 outputs\n 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n # 5x5 conv, 32 inputs, 64 outputs\n 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n # fully connected, 7*7*64 inputs, 1024 outputs\n 'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),\n # 1024 inputs, 10 outputs (class prediction)\n 'out': tf.Variable(tf.random_normal([1024, num_classes]))\n}\n\nbiases = {\n 'bc1': tf.Variable(tf.random_normal([32])),\n 'bc2': tf.Variable(tf.random_normal([64])),\n 'bd1': tf.Variable(tf.random_normal([1024])),\n 'out': tf.Variable(tf.random_normal([num_classes]))\n}\n\n# Construct model\nlogits = conv_net(X, weights, biases, keep_prob)\nprediction = tf.nn.softmax(logits)\n\n# Define loss and optimizer\nloss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n logits=logits, labels=Y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\ntrain_op = optimizer.minimize(loss_op)\n\n\n# Evaluate model\ncorrect_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n\n# Initialize the variables (i.e. assign their default value)\ninit = tf.global_variables_initializer()\n\n# Start training\nwith tf.Session() as sess:\n\n # Run the initializer\n sess.run(init)\n\n for step in range(1, num_steps+1):\n batch_x, batch_y = next_batch(batch_size, train_data, train_labels)\n # Run optimization op (backprop)\n sess.run(train_op, feed_dict={X: batch_x, Y: batch_y, keep_prob: 0.8})\n if step % display_step == 0 or step == 1:\n # Calculate batch loss and accuracy\n loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,\n Y: batch_y,\n keep_prob: 1.0})\n print(\"Step \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.4f}\".format(loss) + \", Training Accuracy= \" + \\\n \"{:.3f}\".format(acc))\n\n print(\"\\n\")\n \n # Calculate accuracy for celebA test images\n print(\"Testing Accuracy:\", \\\n sess.run(accuracy, feed_dict={X: test_data ,Y: test_labels,keep_prob: 1.0}))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"85597805","text":"# -*- coding: utf-8 -*-\nfrom tkinter import Grid\n\nfrom kivy.app import App\nfrom kivy.graphics.vertex_instructions import Line\nfrom kivy.lang import Builder\nfrom kivy.properties import StringProperty, ObjectProperty, BooleanProperty, Clock\nfrom kivy.core.text import Label as CoreLabel\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.spinner import SpinnerOption\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.button import Button\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.graphics import Color, Rectangle\n\nfrom kivy.config import Config\nConfig.set('graphics', 'width', 600)\nConfig.set('graphics', 'height', 800)\nConfig.set('graphics', 'resizable', 0)\n\nConfig.write()\n\n\nclass ChatWidget(GridLayout):\n\n def __init__(self, **kwargs):\n super(ChatWidget, self).__init__(**kwargs)\n\n self.bind(minimum_height=self.setter('height'), size=self._update_rect, pos=self._update_rect)\n self.size_hint=(1, None)\n self.cols=1\n self.padding = 10\n self.spacing = 10\n with self.canvas.before:\n Color(.3,.3,.3,1)\n self.rect = Rectangle(size=self.size, pos=self.pos)\n\n def _update_rect(self, instance, value):\n self.rect.pos = instance.pos\n self.rect.size = instance.size\n\n\nclass RootWidget(BoxLayout):\n\n def __init__(self, **kwargs):\n super(RootWidget, self).__init__(**kwargs)\n self.orientation = 'vertical'\n\n\nclass ScrollViewWidget(ScrollView):\n\n def __init__(self,**kwargs):\n super(ScrollViewWidget, self).__init__(**kwargs)\n self.bind(size=self._update_rect, pos=self._update_rect)\n self.size_hint = (1, .7)\n self.do_scroll_x = False\n with self.canvas.before:\n Color(.3,.3,.3,1)\n self.rect = Rectangle(size=self.size, pos=self.pos)\n\n def _update_rect(self, instance, value):\n self.rect.pos = instance.pos\n self.rect.size = instance.size\n\n def scroll_down(self):\n self.scroll_y = 0\n\n\nclass ChatLabel(Label):\n\n def __init__(self, **kwargs):\n super(ChatLabel, self).__init__(**kwargs)\n\n self.font_name = 'KoPubDotumBold'\n self.rect = Rectangle(size=self.size, pos=self.pos)\n self.size_hint_y = None\n self.text_size = (580, None)\n self.padding = (10,10)\n self.halign = 'left'\n self.valign = 'bottom'\n self.shorten = False\n self.markup = True\n self.bind(size=self._update_rect, pos=self._update_rect)\n with self.canvas.before:\n Color(.2, .2, .2, 1)\n self.rect = Rectangle(size=self.size, pos=self.pos)\n\n def _update_rect(self, instance, value):\n self.rect.pos = instance.pos\n self.rect.size = instance.texture_size\n\n def setText(self, msg):\n self.text = msg\n self.texture_update()\n self.size = self.texture_size\n\nclass TextInputMsg(TextInput):\n\n def __init__(self, **kwargs):\n super(TextInputMsg, self).__init__(**kwargs)\n self.chatManager = None\n self.size_hint = (1, .1)\n self.padding = 15\n self.font_name = 'KoPubDotumBold'\n self.multiline = False\n self.focus = True\n self.bind(on_text_validate=self.on_enter)\n Clock.schedule_once(self._refocus_text_input, 0)\n\n def setChat(self, chatManager):\n self.chatManager = chatManager\n\n def on_enter(self ,instance):\n print(self.cursor_col)\n self.chatManager.add(self.text)\n Clock.schedule_once(self._refocus_text_input, 0)\n self.text = ''\n\n def _refocus_text_input(self, arg1):\n self.focus = True\n\n\nclass ChatManager(object):\n\n def __init__(self, view, scroll):\n self.chats = []\n self.view = view\n self.scroll = scroll\n\n def add(self, msg):\n\n label = ChatLabel()\n label.setText(msg)\n self.chats.append(label)\n self.view.add_widget(label)\n\n if len(self.chats) > 10:\n self.remove()\n\n self.scroll.scroll_down()\n\n def remove(self):\n tmp = self.chats[0]\n self.chats.remove(tmp)\n self.view.remove_widget(tmp)\n\n\nclass MyApp(App):\n\n\n def build(self):\n\n\n root = RootWidget()\n chat = ChatWidget()\n scroll = ScrollViewWidget()\n chatManager = ChatManager(chat, scroll)\n\n scroll.add_widget(chat)\n root.add_widget(scroll)\n\n txtInput = TextInputMsg()\n txtInput.setChat(chatManager)\n root.add_widget(txtInput)\n\n # for i in range(30):\n # btn = Button(text=str(i), size=(400, 40),\n # size_hint=(None, None))\n # chat.add_widget(btn)\n\n\n # label1 = ChatLabel()\n # label1.setText(\"[size=20][color=#f5ad16]정세훈[/color][/size]\\nIt was the best of times, it was the worst of times,it was the age of wisdom, it was the age of foolishness, it was the epoch ofbelief, it was the epoch of incredulity, it was the season of Light, it wasthe season of Darkness, it was the spring of hope, it was the winter of despair,we had everything before us, we had nothing before us, we were all goingdirect to Heaven, we were all going direct the other way - in short,the period was so far like the present period, that some of its noisiestauthorities insisted on its being received, for good or for evil, in thesuperlative degree of comparison only.\")\n # chat.add_widget(label1)\n #\n # label2 = ChatLabel()\n # label2.setText(\"Hello WorldIt was the best of times, it was the worst of times,it was the age of wisdom, it was the age of foolishness, it was the epoch ofbelief, it was the epoch of incredulity, it was the season of Light, it wasthe season of Darkness, it was the spring of hope, it was the winter of despair,we had everything before us, we had nothing before us, we were all goingdirect to Heaven, we were all going direct the other way - in short,the period was so far like the present period, that some of its noisiestauthorities insisted on its being received, for good or for evil, in thesuperlative degree of comparison only.\")\n # chat.add_widget(label2)\n\n\n\n\n\n return root\n\n\n","sub_path":"Print.py","file_name":"Print.py","file_ext":"py","file_size_in_byte":6271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"447616991","text":"# coding: utf-8\n\"\"\"\nData module\n\"\"\"\nimport sys\nimport random\nimport os\nimport os.path\nfrom typing import Optional\nimport torch\nfrom torchtext.datasets import TranslationDataset\nfrom torchtext import data\nfrom torchtext.data import Dataset, Iterator, Field\nimport torchaudio # new\n\nfrom joeynmt.constants import UNK_TOKEN, EOS_TOKEN, BOS_TOKEN, PAD_TOKEN\nfrom joeynmt.vocabulary import build_vocab, Vocabulary\nfrom torchtext.data import get_tokenizer\nfrom torch.utils.data import DataLoader\nfrom .datasets.commonvoice import COMMONVOICE\n\n\nclass Noprocessfield(Field):\n def process(self, batch, device):\n return batch\n\ndef prepare_audio(input_audio, input_samplerate, type, letter_width=0.02, hop_length=400):\n letter_sample_rate = int(hop_length/letter_width)\n downsampler = torchaudio.transforms.Resample(input_samplerate, letter_sample_rate, resampling_method='sinc_interpolation')\n spectrogram = torchaudio.transforms.MelSpectrogram(sample_rate=letter_sample_rate, n_mels=128, n_fft=hop_length, hop_length=hop_length)\n return spectrogram(downsampler(input_audio))\n\ndef preprocess_data_single_entry(input_tuple, type=\"train\", letter_width=0.02, hop_length=400):\n # letter_width=length of single spoken letter in s\n # hop_length = frequency resolution of spectrogram (also determines the letter width)\n\n input_audio, input_samplerate, input_dict = input_tuple[0], input_tuple[1], input_tuple[2]\n spectrogram = prepare_audio(input_audio, input_samplerate, type, letter_width, hop_length)\n sentence = input_dict['sentence']\n\n return spectrogram, sentence\n\n\ndef preprocess_data(input_list, type=\"train\", letter_width=0.02, hop_length=400):\n data = []\n for i in input_list:\n data.append(preprocess_data_single_entry(i, type=type, letter_width=letter_width, hop_length=hop_length))\n return data\n\n\ndef reformat_data(data, data_torchaudio, trg_min_freq, trg_max_size, tok_fun, trg_vocab_file=None, trg_vocab=None, lowercase=True):\n train_iter = data\n\n src_field = Noprocessfield(sequential=False, use_vocab=False, dtype=torch.double, include_lengths=True)\n trg_field = Field(init_token=BOS_TOKEN, eos_token=EOS_TOKEN,\n pad_token=PAD_TOKEN, tokenize=tok_fun,\n unk_token=UNK_TOKEN,\n batch_first=True, lower=lowercase,\n include_lengths=True)\n if trg_vocab is None:\n trg_vocab = build_vocab(min_freq=trg_min_freq, max_size=trg_max_size, dataset=data_torchaudio, trg_field=trg_field, vocab_file=trg_vocab_file)\n trg_field.vocab = trg_vocab\n\n entry_list = []\n for i, batch in enumerate(iter(train_iter)):\n # reactivate training\n entry_list.append(Entry(batch[0][0].squeeze(), batch[0][1]))\n train_data = Dataset(entry_list, [('src', src_field), ('trg', trg_field)])\n return train_data, trg_vocab, src_field, trg_field\n\n\ndef load_data(data_cfg: dict) -> (Dataset, Dataset, Optional[Dataset],\n Vocabulary, Vocabulary):\n \"\"\"\n Load train, dev and optionally test data as specified in configuration.\n Vocabularies are created from the training set with a limit of `voc_limit`\n tokens and a minimum token frequency of `voc_min_freq`\n (specified in the configuration dictionary).\n\n The training data is filtered to include sentences up to `max_sent_length`\n on source and target side.\n\n If you set ``random_train_subset``, a random selection of this size is used\n from the training set instead of the full training set.\n\n :param data_cfg: configuration dictionary for data\n (\"data\" part of configuation file)\n :return:\n - train_data: training dataset\n - dev_data: development dataset\n - test_data: testdata set if given, otherwise None\n - src_vocab: source vocabulary extracted from training data\n - trg_vocab: target vocabulary extracted from training data\n \"\"\"\n # load data from files\n train_path = data_cfg[\"train\"]\n dev_path = data_cfg[\"dev\"]\n test_path = data_cfg.get(\"test\", None)\n level = data_cfg[\"level\"]\n lowercase = data_cfg[\"lowercase\"]\n\n tok_fun = lambda s: list(s) if level == \"char\" else s.split()\n\n trg_max_size = data_cfg.get(\"trg_voc_limit\", sys.maxsize)\n trg_min_freq = data_cfg.get(\"trg_voc_min_freq\", 1)\n trg_vocab_file = data_cfg.get(\"trg_vocab\", None)\n language = data_cfg.get(\"language\", \"interlingua\")\n\n print(\"Loading and processing\", language, \"language data, this may take a while\")\n\n train_data_torchaudio = COMMONVOICE('CommonVoice', language=language, download=True, tsv=train_path)\n # changed the dataset from a Translation Dataset to torchaudio dataset.\n # created DataLoader which can be used in existing data training loop\n # made preprocessing function\n # Done: make vocabulary manually, using Vocabulary class (only for target)\n train_data = DataLoader(train_data_torchaudio, batch_size=1, shuffle=False, collate_fn= lambda x: preprocess_data(x, type=\"train\"))\n train_data, trg_vocab, src_field, trg_field = reformat_data(train_data, train_data_torchaudio, trg_min_freq, trg_max_size, trg_vocab_file=trg_vocab_file, tok_fun=tok_fun, lowercase=lowercase)\n\n dev_data_torchaudio = COMMONVOICE('CommonVoice', language=language, tsv=dev_path)\n dev_data = DataLoader(dev_data_torchaudio, batch_size=1, shuffle=False, collate_fn= lambda x: preprocess_data(x, type=\"dev\"))\n dev_data, dev_trg_vocab, dev_src_field, dev_trg_field = reformat_data(dev_data, dev_data_torchaudio, trg_min_freq, trg_max_size, trg_vocab=trg_vocab, tok_fun=tok_fun, lowercase=lowercase)\n\n test_data = None\n if test_path is not None:\n # check if target exists\n test_data_torchaudio = COMMONVOICE('CommonVoice', language=language, tsv=test_path)\n test_data = DataLoader(test_data_torchaudio, batch_size=1, shuffle=False, collate_fn=lambda x: preprocess_data(x, type=\"test\"))\n test_data, test_trg_vocab, test_src_field, test_trg_field = reformat_data(test_data, test_data_torchaudio,\n trg_min_freq, trg_max_size,\n trg_vocab=trg_vocab, tok_fun=tok_fun, lowercase=lowercase)\n\n return train_data, dev_data, test_data, trg_vocab\n\n\n# pylint: disable=global-at-module-level\nglobal max_src_in_batch, max_tgt_in_batch\n\n\n# pylint: disable=unused-argument,global-variable-undefined\ndef token_batch_size_fn(new, count, sofar):\n \"\"\"Compute batch size based on number of tokens (+padding).\"\"\"\n global max_src_in_batch, max_tgt_in_batch\n if count == 1:\n max_src_in_batch = 0\n max_tgt_in_batch = 0\n max_src_in_batch = max(max_src_in_batch, len(new.src))\n src_elements = count * max_src_in_batch\n if hasattr(new, 'trg'): # for monolingual data sets (\"translate\" mode)\n max_tgt_in_batch = max(max_tgt_in_batch, len(new.trg) + 2)\n tgt_elements = count * max_tgt_in_batch\n else:\n tgt_elements = 0\n return max(src_elements, tgt_elements)\n\n\ndef make_data_iter(dataset: Dataset,\n batch_size: int,\n batch_type: str = \"sentence\",\n train: bool = False,\n shuffle: bool = False) -> Iterator:\n \"\"\"\n Returns a torchtext iterator for a torchtext dataset.\n\n :param dataset: torchtext dataset containing src and optionally trg\n :param batch_size: size of the batches the iterator prepares\n :param batch_type: measure batch size by sentence count or by token count\n :param train: whether it's training time, when turned off,\n bucketing, sorting within batches and shuffling is disabled\n :param shuffle: whether to shuffle the data before each epoch\n (no effect if set to True for testing)\n :return: torchtext iterator\n \"\"\"\n\n batch_size_fn = token_batch_size_fn if batch_type == \"token\" else None\n\n if train:\n # optionally shuffle and sort during training\n data_iter = data.BucketIterator(\n repeat=False, sort=False, dataset=dataset,\n batch_size=batch_size, batch_size_fn=batch_size_fn,\n train=True, sort_within_batch=True,\n sort_key=lambda x: len(x.src), shuffle=shuffle)\n else:\n # don't sort/shuffle for validation/inference\n data_iter = data.BucketIterator(\n repeat=False, dataset=dataset,\n batch_size=batch_size, batch_size_fn=batch_size_fn,\n sort_key=lambda x: len(x.src),\n train=False, sort=False)\n\n return data_iter\n\n# Todo: Neue Audiotextdaten-Klasse schreiben, damit wir nicht alle Abhängigkeiten ändern müssen\n\n\nclass Entry():\n def __init__(self, src, trg):\n self.src = src\n self.trg = trg\n\n\nclass MonoDataset(Dataset):\n \"\"\"Defines a dataset for machine translation without targets.\"\"\"\n\n @staticmethod\n def sort_key(ex):\n return len(ex.src)\n\n def __init__(self, path: str, ext: str, field: Field, **kwargs) -> None:\n \"\"\"\n Create a monolingual dataset (=only sources) given path and field.\n\n :param path: Prefix of path to the data file\n :param ext: Containing the extension to path for this language.\n :param field: Containing the fields that will be used for data.\n :param kwargs: Passed to the constructor of data.Dataset.\n \"\"\"\n\n fields = [('src', field)]\n\n src_path = os.path.expanduser(path + ext)\n\n waveform, sample_rate = torchaudio.load(src_path)\n spectrogram = prepare_audio(waveform, sample_rate, \"predict\")\n examples = [Entry(spectrogram.squeeze(), None)]\n\n super(MonoDataset, self).__init__(examples, fields, **kwargs)\n","sub_path":"joeynmt/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":9774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"554112316","text":"class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n \"\"\"\n s[i] == t[j]\n dp[i][j] = dp[i-1][j-1]\n otherwise\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1\n \"\"\"\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m+1)]\n\n for i in range(0, m+1):\n for j in range(0, n+1):\n if i == 0 or j == 0:\n dp[i][j] = i + j\n elif word1[i-1] == word2[j-1]:\n dp[i][j] = dp[i-1][j-1]\n else:\n dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1\n return dp[-1][-1]","sub_path":"leetcode/501-600/T583_minDistance.py","file_name":"T583_minDistance.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"537676113","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Authority',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.CharField(verbose_name='权限名称', max_length=32)),\n ],\n ),\n migrations.CreateModel(\n name='Group',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('name', models.CharField(verbose_name='组名称', max_length=32)),\n ],\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),\n ('username', models.CharField(verbose_name='用户名称', max_length=32)),\n ('password', models.CharField(verbose_name='用户密码', max_length=32)),\n ('email', models.EmailField(verbose_name='用户邮箱', max_length=254)),\n ('phone', models.CharField(verbose_name='用户手机', max_length=18, blank=True, null=True)),\n ('photo', models.ImageField(upload_to='image/userphoto', verbose_name='用户头像', blank=True, null=True)),\n ],\n ),\n ]\n","sub_path":"ProjOMMP/User/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"69139482","text":"'''\nTools for documenting the SF interface.\n'''\n\n# from enum import Enum\nfrom collections import namedtuple\nimport typing as tp\n\nimport numpy as np\n\nfrom static_frame.core.frame import Frame\nfrom static_frame.core.bus import Bus\n\nfrom static_frame.core.util import _DT64_S\n\nfrom static_frame.core.container import ContainerBase\nfrom static_frame.core.container import ContainerMeta\nfrom static_frame.core.container import ContainerOperand\n\nfrom static_frame.core.type_blocks import TypeBlocks\nfrom static_frame.core.index_base import IndexBase\n\nfrom static_frame.core.index_datetime import IndexDate\nfrom static_frame.core.index_datetime import IndexYearMonth\nfrom static_frame.core.index_datetime import IndexYear\n\nfrom static_frame.core.index_hierarchy import IndexHierarchy\nfrom static_frame.core.display import Display\n\n# from static_frame.core.iter_node import IterNode\nfrom static_frame.core.iter_node import IterNodeDelegate\nfrom static_frame.core.iter_node import IterNodeNoArg\nfrom static_frame.core.iter_node import IterNodeAxis\nfrom static_frame.core.iter_node import IterNodeGroup\nfrom static_frame.core.iter_node import IterNodeGroupAxis\nfrom static_frame.core.iter_node import IterNodeDepthLevel\nfrom static_frame.core.iter_node import IterNodeDepthLevelAxis\nfrom static_frame.core.iter_node import IterNodeWindow\n\n# from static_frame.core.container import ContainerMeta\nfrom static_frame.core.container import _UFUNC_BINARY_OPERATORS\nfrom static_frame.core.container import _RIGHT_OPERATOR_MAP\nfrom static_frame.core.container import _UFUNC_UNARY_OPERATORS\n\n# from static_frame.core.util import InterfaceSelection1D # used on index.drop\nfrom static_frame.core.selector_node import InterfaceSelection2D\nfrom static_frame.core.selector_node import InterfaceAssign2D\n\nfrom static_frame.core.selector_node import InterfaceAsType\nfrom static_frame.core.selector_node import InterfaceGetItem\n\n\nInterface = namedtuple('Interface', (\n 'cls',\n 'group',\n 'name',\n 'doc'\n ))\n\nclass InterfaceGroup:\n Attribute = 'Attribute'\n Constructor = 'Constructor'\n DictLike = 'Dictionary-Like'\n Display = 'Display'\n Exporter = 'Exporter'\n Iterator = 'Iterator'\n Method = 'Method'\n OperatorBinary = 'Operator Binary'\n OperatorUnary = 'Operator Unary'\n Selector = 'Selector'\n\n\nclass InterfaceSummary:\n\n DOC_CHARS = 100\n\n EXCLUDE_PRIVATE = {\n '__class__',\n '__class_getitem__',\n '__annotations__',\n '__doc__',\n '__delattr__',\n '__dir__',\n '__dict__',\n '__format__',\n '__getattribute__',\n '__hash__',\n '__init_sbclass__',\n '__lshift__',\n '__module__',\n '__init_subclass__',\n '__new__',\n '__setattr__',\n '__setstate__',\n '__setitem__',\n '__slots__',\n '__slotnames__',\n '__subclasshook__',\n '__weakref__',\n '__reduce__',\n '__reduce_ex__',\n '__sizeof__',\n }\n\n DICT_LIKE = {\n 'get',\n 'keys',\n 'values',\n 'items',\n '__contains__',\n '__iter__',\n '__reversed__'\n }\n\n DISPLAY = {\n 'display',\n 'display_tall',\n 'display_wide',\n '__repr__',\n '__str__',\n 'interface',\n }\n\n ATTR_ITER_NODE = (\n 'apply',\n 'apply_iter',\n 'apply_iter_items',\n 'apply_pool',\n 'map_all',\n 'map_all_iter',\n 'map_all_iter_items',\n 'map_any',\n 'map_any_iter',\n 'map_any_iter_items',\n 'map_fill',\n 'map_fill_iter',\n 'map_fill_iter_items',\n )\n\n GETITEM = '__getitem__'\n\n # must all be members of InterfaceSelection2D\n ATTR_SELECTOR_NODE = ('__getitem__', 'iloc', 'loc',)\n ATTR_SELECTOR_NODE_ASSIGN = ('__getitem__', 'iloc', 'loc', 'bloc')\n\n _CLS_TO_INSTANCE_CACHE: tp.Dict[int, int] = {}\n\n # astype is a normal function in Series, is a selector in Frame\n\n @classmethod\n def is_public(cls, field: str) -> bool:\n if field.startswith('_') and not field.startswith('__'):\n return False\n if field in cls.EXCLUDE_PRIVATE:\n return False\n return True\n\n @classmethod\n def scrub_doc(cls, doc: tp.Optional[str]) -> str:\n if not doc:\n return ''\n doc = doc.replace('`', '')\n doc = doc.replace(':py:meth:', '')\n doc = doc.replace(':obj:', '')\n doc = doc.replace('static_frame.', '')\n\n # split and join removes contiguous whitespace\n msg = ' '.join(doc.split())\n if len(msg) <= cls.DOC_CHARS:\n return msg\n return msg[:cls.DOC_CHARS].strip() + Display.ELLIPSIS\n\n\n @classmethod\n def get_instance(cls, target: tp.Type[ContainerBase]) -> ContainerBase:\n '''\n Get a sample instance from any ContainerBase; cache to only create one per life of process.\n '''\n if target not in cls._CLS_TO_INSTANCE_CACHE:\n if target is TypeBlocks:\n instance = target.from_blocks(np.array((0,)))\n elif target is Bus:\n f = Frame.from_elements((0,), name='frame')\n instance = target.from_frames((f,))\n elif issubclass(target, IndexHierarchy):\n instance = target.from_labels(((0,0),))\n elif issubclass(target, (IndexYearMonth, IndexYear, IndexDate)):\n instance = target(np.array((0,), dtype=_DT64_S))\n elif target in (ContainerOperand, ContainerBase, IndexBase):\n instance = target()\n elif issubclass(target, Frame):\n instance = target.from_elements((0,))\n else:\n instance = target((0,))\n cls._CLS_TO_INSTANCE_CACHE[target] = instance\n return cls._CLS_TO_INSTANCE_CACHE[target]\n\n @classmethod\n def name_obj_iter(cls, target: tp.Type[ContainerBase]):\n instance = cls.get_instance(target=target)\n\n for name_attr in dir(target.__class__): # get metaclass\n if name_attr == 'interface':\n # getting interface off of the class will recurse\n yield name_attr, None, ContainerBase.__class__.interface\n\n for name_attr in dir(target):\n if name_attr == 'interface':\n continue # skip, provided by class\n if not cls.is_public(name_attr):\n continue\n yield name_attr, getattr(instance, name_attr), getattr(target, name_attr)\n\n @classmethod\n def interrogate(cls,\n target: tp.Type[ContainerBase]\n ) -> tp.Iterator[Interface]:\n\n for name_attr, obj, obj_cls in sorted(cls.name_obj_iter(target)):\n # properties resdie on the class\n doc = ''\n if isinstance(obj_cls, property):\n doc = cls.scrub_doc(obj_cls.__doc__)\n elif hasattr(obj, '__doc__'):\n doc = cls.scrub_doc(obj.__doc__)\n\n if hasattr(obj, '__name__'):\n name = obj.__name__\n else: # some attributes yield objects like arrays, Series, or Frame\n name = name_attr\n\n cls_name = target.__name__\n\n if name in cls.DICT_LIKE:\n display = f'{name}()' if name != 'values' else name\n yield Interface(cls_name, InterfaceGroup.DictLike, display, doc)\n\n elif name in cls.DISPLAY:\n display = f'{name}()' if name != 'interface' else name\n yield Interface(cls_name, InterfaceGroup.Display, display, doc)\n\n elif name == 'astype':\n yield Interface(cls_name, InterfaceGroup.Method, name, doc)\n if isinstance(obj, InterfaceAsType): # an InterfaceAsType\n display = f'{name}[]'\n doc = cls.scrub_doc(getattr(InterfaceAsType, cls.GETITEM).__doc__)\n yield Interface(cls_name, InterfaceGroup.Method, display, doc)\n\n elif name.startswith('from_') or name == '__init__':\n display = f'{name}()'\n yield Interface(cls_name, InterfaceGroup.Constructor, display, doc)\n\n elif name.startswith('to_'):\n display = f'{name}()'\n yield Interface(cls_name, InterfaceGroup.Exporter, display, doc)\n\n elif name.startswith('iter_'):\n # assert isinstance(obj, IterNode)\n if isinstance(obj, IterNodeNoArg):\n display = f'{name}()'\n elif isinstance(obj, IterNodeAxis):\n display = f'{name}(axis)'\n elif isinstance(obj, IterNodeGroup):\n display = f'{name}()'\n elif isinstance(obj, IterNodeGroupAxis):\n display = f'{name}(key, axis)'\n elif isinstance(obj, IterNodeDepthLevel):\n display = f'{name}(depth_level)'\n elif isinstance(obj, IterNodeDepthLevelAxis):\n display = f'{name}(depth_level, axis)'\n elif isinstance(obj, IterNodeWindow):\n display = f'{name}(size, step, axis, ...)'\n else:\n display = f'{name}()'\n\n yield Interface(cls_name, InterfaceGroup.Iterator, display, doc)\n for field in cls.ATTR_ITER_NODE:\n display_sub = f'{display}.{field}()'\n doc = cls.scrub_doc(getattr(IterNodeDelegate, field).__doc__)\n yield Interface(cls_name, InterfaceGroup.Iterator, display_sub, doc)\n\n elif isinstance(obj, InterfaceGetItem) or name == cls.GETITEM:\n display = f'{name}[]' if name != cls.GETITEM else '[]'\n yield Interface(cls_name, InterfaceGroup.Selector, display, doc)\n\n elif isinstance(obj, InterfaceSelection2D):\n for field in cls.ATTR_SELECTOR_NODE:\n display = f'{name}.{field}[]' if field != cls.GETITEM else f'{name}[]'\n doc = cls.scrub_doc(getattr(InterfaceSelection2D, field).__doc__)\n yield Interface(cls_name, InterfaceGroup.Selector, display, doc)\n\n elif isinstance(obj, InterfaceAssign2D):\n for field in cls.ATTR_SELECTOR_NODE_ASSIGN:\n display = f'{name}.{field}[]' if field != cls.GETITEM else f'{name}[]'\n doc = cls.scrub_doc(getattr(InterfaceAssign2D, field).__doc__)\n yield Interface(cls_name, InterfaceGroup.Selector, display, doc)\n\n elif callable(obj):\n display = f'{name}()'\n if name_attr in _UFUNC_UNARY_OPERATORS:\n yield Interface(cls_name, InterfaceGroup.OperatorUnary, display, doc)\n elif name_attr in _UFUNC_BINARY_OPERATORS or name_attr in _RIGHT_OPERATOR_MAP:\n yield Interface(cls_name, InterfaceGroup.OperatorBinary, display, doc)\n else:\n yield Interface(cls_name, InterfaceGroup.Method, display, doc)\n else:\n yield Interface(cls_name, InterfaceGroup.Attribute, name, doc)\n\n @classmethod\n def to_frame(cls, target: ContainerMeta) -> Frame:\n f = Frame.from_records(cls.interrogate(target), name=target.__name__)\n f = f.sort_values(('cls', 'group', 'name'))\n f = f.set_index('name', drop=True)\n return f\n\n","sub_path":"static_frame/core/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":11434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"607184046","text":"# ============================================================================\n# FILE: matcher/denite_migemo.py\n# AUTHOR: nekowasabi\n# License: MIT license\n# ============================================================================\n\nimport subprocess\n\nfrom denite.base.filter import Base\n\n\nclass Filter(Base):\n def __init__(self, vim):\n super().__init__(vim)\n\n self.debug('migemo start')\n\n self.name = \"matcher/migemo\"\n self.description = \"migemo matcher\"\n\n def filter(self, context):\n if context[\"input\"] == \"\":\n return context[\"candidates\"]\n candidates = context[\"candidates\"]\n self.debug(candidates)\n\n try:\n dict_path = \"/usr/local/share/migemo/utf-8/migemo-dict\"\n process = subprocess.call(\n [\"/usr/local/bin/cmigemo\", \"-w\", context[\"input\"], \"-d\", dict_path],\n stdout=subprocess.PIPE,\n )\n p = process.stdout.read().decode(\"utf-8\")\n self.debug(p)\n\n except Exception:\n return []\n candidates = [x for x in candidates if x[\"word\"] in p]\n\n return candidates\n","sub_path":"rplugin/python3/denite/filter/matcher/denite_migemo.py","file_name":"denite_migemo.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"40542467","text":"from tkinter import *\r\nfrom PIL import Image, ImageTk\r\njanela = Tk()\r\n\r\ndef bt_click():\r\n num1 = int(ed1.get())\r\n num2 = int(ed2.get())\r\n op = ed3.get()\r\n if op=='soma':\r\n lb[\"text\"] = num1+num2\r\n if op=='subtracao':\r\n lb[\"text\"] = num1-num2\r\n if op=='divisao':\r\n lb[\"text\"] = num1/num2\r\n if op=='multiplicacao':\r\n lb[\"text\"] = num1*num2\r\ndef bt_sair():\r\n janela.destroy()\r\n\r\nimage = Image.open('cal.png')\r\nimage = image.resize((130, 130))\r\nphoto = ImageTk.PhotoImage(image)\r\nlabel = Label(image=photo)\r\nlabel.image = photo \r\nlabel.place(x=650, y=10)\r\n\r\nlbt = Label(janela,text='Calculadora',bg='blue',font=\"Arial 30\")\r\nlbt.place(x=600, y=150)\r\n\r\nlb1 = Label(janela,text='Digite o primeiro valor: ',bg='blue',font=\"Arial 30\")\r\nlb1.place(x=10, y=200)\r\ned1 = Entry(janela)\r\ned1.insert(INSERT, 'Insira um valor')\r\ned1.place(x=420,y=220)\r\n\r\nlb2 = Label(janela,text='Digite o primeiro valor: ',bg='blue',font=\"Arial 30\")\r\nlb2.place(x=10, y=300)\r\ned2 = Entry(janela)\r\ned2.place(x=420,y=320)\r\n\r\nlb3 = Label(janela,text='Escolha a operação: ',bg='blue',font=\"Arial 30\")\r\nlb3.place(x=10, y=400)\r\ned3 = Entry(janela)\r\ned3.place(x=400,y=420)\r\n\r\nbt = Button(janela, width=20, text=\"Calcular\",command=bt_click)\r\nbt.place(x=650, y=500)\r\n\r\nlbres = Label(janela,text='A resposta é:',bg='blue',font=\"Arial 24\")\r\nlbres.place(x=630, y=580)\r\nlb = Label(janela,text=\"\",bg='blue',font=\"Arial 24\")\r\nlb.place(x=820, y=580)\r\n\r\nbt = Button(janela, width=20, text=\"Sair\",command=bt_sair)\r\nbt.place(x=650, y=650)\r\n\r\njanela.geometry('1366x768+200+200')\r\njanela.title('Calculadora')\r\n\r\njanela.iconbitmap('calc.ico')\r\njanela['bg'] = 'blue'\r\njanela.mainloop()\r\n","sub_path":"Programas com Tkinter/Calculadora_TKINTER/CalculadoraTela.py","file_name":"CalculadoraTela.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"501815658","text":"import sigpy as sp\r\nimport sigpy.mri as mr\r\nimport sigpy.plot as pl\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\n# Set parameters and load dataset\r\nmax_iter = 30\r\nmax_cg_iter = 5\r\nlamda = 0.001\r\n\r\nksp_file = 'data/liver/ksp.npy'\r\ncoord_file = 'data/liver/coord.npy'\r\n\r\ndevice = sp.Device(-1)\r\n\r\nxp = device.xp\r\ndevice.use()\r\n\r\n# Load datasets.\r\nksp = xp.load(ksp_file)\r\ncoord = xp.load(coord_file)\r\n\r\nprint(f'K-space shape: {ksp.shape}')\r\nprint(f'K-space dtype: {ksp.dtype}')\r\nprint(f'K-space (min, max): ({np.abs(ksp).min()}, {np.abs(ksp).max()})')\r\nprint(f'Coord shape: {coord.shape}') # (na, ns, 2)\r\nprint(f'Coord shape: {coord.dtype}')\r\nprint(f'Coord (min, max): ({coord.min()}, {coord.max()})')\r\n\r\nplt.ion()\r\nf, ax = plt.subplots(1, 1)\r\nax.scatter(coord[:15, :, -1], coord[:15, :, -2])\r\n\r\n# Use JSENSE to estimate sensitivity maps\r\nmps = mr.app.JsenseRecon(ksp, coord=coord, device=device).run()\r\n\r\nprint(f'Shape of coil sensitivity maps: {mps.shape}')\r\n\r\npl.ImagePlot(mps)\r\n\r\n# Primal dual hybrid gradient reconstruction\r\npdhg_app = mr.app.TotalVariationRecon(ksp, mps, lamda=lamda, coord=coord,\r\n max_iter=max_iter,\r\n device=device,\r\n save_objective_values=True)\r\nprint(f'Name of solver: {pdhg_app.alg_name}')\r\npdhg_img = pdhg_app.run()\r\n\r\nprint(f'Image shape: {pdhg_img.shape}')\r\nprint(f'Image dtype: {pdhg_img.dtype}')\r\n\r\npl.ImagePlot(pdhg_img)\r\n\r\n# PDHG with dcf\r\n# Compute preconditioner\r\nprecond_dcf = mr.pipe_menon_dcf(coord, device=device)\r\n\r\nprint(f'DCF shape: {precond_dcf.shape}')\r\nprint(f'DCF dtype: {precond_dcf.dtype}')\r\n\r\nf, ax = plt.subplots(1, 1)\r\nax.imshow(precond_dcf)\r\n\r\nprecond_dcf = xp.tile(precond_dcf, [len(mps)] + [1] * (mps.ndim - 1))\r\nimg_shape = mps.shape[1:]\r\nG = sp.linop.FiniteDifference(img_shape)\r\nmax_eig_G = sp.app.MaxEig(G.H * G).run()\r\nsigma2 = xp.ones([sp.prod(img_shape) * len(img_shape)],\r\n dtype=ksp.dtype) / max_eig_G\r\nsigma = xp.concatenate([precond_dcf.ravel(), sigma2.ravel()])\r\n\r\npdhg_dcf_app = mr.app.TotalVariationRecon(ksp, mps, lamda=lamda, coord=coord,\r\n sigma=sigma, max_iter=max_iter,\r\n device=device,\r\n save_objective_values=True)\r\nprint(f'Name of solver: {pdhg_dcf_app.alg_name}')\r\npdhg_dcf_img = pdhg_dcf_app.run()\r\n\r\npl.ImagePlot(pdhg_dcf_img)\r\n\r\n# PDHG with single-channel k-space preconditioning\r\n# Compute preconditioner\r\nones = np.ones_like(mps)\r\nones /= len(mps)**0.5\r\nprecond_sc = mr.kspace_precond(ones, coord=coord, device=device)\r\n\r\nprint(f'Shape of k-space precond: {precond_sc.shape}')\r\nprint(f'Dtype of k-space precond: {precond_sc.dtype}')\r\n\r\npl.ImagePlot(precond_sc)\r\n\r\nimg_shape = mps.shape[1:]\r\nmax_eig_G = sp.app.MaxEig(G.H * G).run()\r\nsigma2 = xp.ones([sp.prod(img_shape) * len(img_shape)],\r\n dtype=ksp.dtype) / max_eig_G\r\nsigma = xp.concatenate([precond_sc.ravel(), sigma2.ravel()]) / 2\r\n\r\npdhg_sc_app = mr.app.TotalVariationRecon(ksp, mps, lamda=lamda, coord=coord,\r\n sigma=sigma, max_iter=max_iter,\r\n device=device,\r\n save_objective_values=True)\r\nprint(f'Name of solver: {pdhg_sc_app.alg_name}')\r\npdhg_sc_img = pdhg_sc_app.run()\r\n\r\npl.ImagePlot(pdhg_sc_img)\r\n\r\n# PDHG with multi-channel k-space preconditioning\r\n# Compute preconditioner\r\nprecond_mc = mr.kspace_precond(mps, coord=coord, device=device)\r\n\r\nprint(f'Shape of k-space precond: {precond_mc.shape}')\r\nprint(f'Dtype of k-space precond: {precond_mc.dtype}')\r\n\r\npl.ImagePlot(precond_mc)\r\n\r\nimg_shape = mps.shape[1:]\r\nmax_eig_G = sp.app.MaxEig(G.H * G).run()\r\nsigma2 = xp.ones([sp.prod(img_shape) * len(img_shape)],\r\n dtype=ksp.dtype) / max_eig_G\r\nsigma = xp.concatenate([precond_mc.ravel(), sigma2.ravel()])\r\n\r\npdhg_mc_app = mr.app.TotalVariationRecon(ksp, mps, lamda=lamda, coord=coord,\r\n sigma=sigma, max_iter=max_iter,\r\n device=device,\r\n save_objective_values=True)\r\nprint(f'Name of solver: {pdhg_mc_app.alg_name}')\r\npdhg_mc_img = pdhg_mc_app.run()\r\n\r\npl.ImagePlot(pdhg_mc_img)\r\n\r\n# Plot convergence curves\r\nplt.figure(figsize=(8, 3))\r\nplt.semilogy(pdhg_app.objective_values,\r\n marker='+', color='C3')\r\nplt.semilogy(pdhg_dcf_app.objective_values,\r\n marker='s', color='C4')\r\nplt.semilogy(pdhg_sc_app.objective_values,\r\n marker='*', color='C5')\r\nplt.semilogy(pdhg_mc_app.objective_values,\r\n marker='x', color='C6')\r\nplt.legend(['PDHG',\r\n 'PDHG w/ density comp.',\r\n 'PDHG w/ SC k-space precond.',\r\n 'PDHG w/ MC k-space precond.'])\r\nplt.ylabel('Objective Value [a.u.]')\r\nplt.xlabel('Iteration Number')\r\nplt.title(r\"Total Variation Regularized Reconstruction\")\r\nplt.tight_layout()\r\n","sub_path":"test_precond.py","file_name":"test_precond.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"11301147","text":"import os\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nfrom huy_project_test2.data import *\n\n\ndef get_driver():\n chrome_driver = r\"../Tools/chromedriver.exe\"\n chrome_options = Options()\n outputs = os.popen('wmic process get CommandLine').readlines()\n check = 0\n for line in outputs:\n if \"remote-debugging-port\" in line:\n print(\"get_driver(): Found: remote-debugging-port, add_experimental_option: debuggerAddress\", \"127.0.0.1:9223\")\n chrome_options.add_experimental_option(\"debuggerAddress\", \"127.0.0.1:9223\")\n check = 1\n break\n if check == 0:\n print(\"get_driver(): Not found: remote-debugging-port, add_argument: --remote-debugging-port=9223\")\n chrome_options.add_argument(\"--remote-debugging-port=9223\")\n # remove image\n chrome_options.add_experimental_option(\"prefs\", {\"profile.managed_default_content_settings.images\": 2})\n # set developer mode\n chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])\n driver = webdriver.Chrome(executable_path=chrome_driver, chrome_options=chrome_options)\n driver.implicitly_wait(implicitly_wait)\n driver.set_page_load_timeout(set_page_load_timeout)\n return driver\n","sub_path":"_python_sources/p1/huy_project_test2/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"540664394","text":"import tensorflow as tf\nimport tensorlayer as tl\nfrom tensorlayer.layers import *\nimport numpy as np\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n\ndef generator(inputs, is_train=True, reuse=False):\n image_size = 28\n s2, s4 = int(image_size/2), int(image_size/4)\n # Dimension of gen filters in first conv layer. [64]\n gf_dim = 64\n c_dim = FLAGS.c_dim # n_color 1\n batch_size = FLAGS.batch_size # 64\n w_init = tf.random_normal_initializer(stddev=0.02)\n gamma_init = tf.random_normal_initializer(1., 0.02)\n with tf.variable_scope(\"generator\", reuse=reuse):\n tl.layers.set_name_reuse(reuse)\n\n net_in =InputLayer(inputs, name='g/in')\n # shape=[64, 100]\n # full connection layer\n net_h0 = DenseLayer(net_in, n_units=1024, W_init=w_init,\n act=tf.identity, name='g/h0/fc')\n net_h0 = BatchNormLayer(net_h0, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h0/batch_norm')\n # shape=[64, 1024]\n net_h1 = DenseLayer(net_h0, n_units=gf_dim*2*s4*s4, act=tf.identity, name='g/h1/fc')\n # shape=[64, 6272]\n net_h1 = ReshapeLayer(net_h1, shape=(-1, s4, s4, gf_dim*2), name='g/h1/reshape')\n net_h1 = BatchNormLayer(net_h1, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h1/batch_norm')\n # shape=[64, 7, 7, 128]\n net_h2 = DeConv2d(net_h1, gf_dim*2, (5, 5), out_size=(s2, s2), strides=(2, 2),\n padding='SAME', batch_size=batch_size, act=tf.identity, W_init=w_init, name='g/h2/decon2d')\n net_h2 = BatchNormLayer(net_h2, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h2/batch_norm')\n # shape=[64, 14, 14, 128]\n net_h3 = Conv2d(net_h2, 64, (5, 5), act=tf.identity, padding='SAME', W_init=w_init,\n name='g/h3/conv2d')\n net_h3 = BatchNormLayer(net_h3, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h3/batch_norm')\n # shape=[64, 14, 14, 64]\n net_h4 = DeConv2d(net_h3, gf_dim, (5, 5), out_size=(image_size, image_size),\n strides=(2, 2), padding='SAME', batch_size=batch_size, W_init=w_init,\n name='g/h4/decon2d')\n net_h4 = BatchNormLayer(net_h4, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='g/h4/batch_norm')\n # shape=[64, 28, 28, 64]\n net_h5 = Conv2d(net_h4, c_dim, (5, 5), act=tf.identity, padding='SAME', W_init=w_init,\n name='g/h5/conv2d')\n # shape = [64, 28, 28, 1]\n logits = net_h5.outputs\n net_h5.outputs = tf.nn.tanh(net_h5.outputs)\n return net_h5, logits\n\n\ndef discriminator(inputs, is_train=True, reuse=False):\n df_dim = 64\n c_dim = FLAGS.c_dim\n batch_size = FLAGS.batch_size\n w_init = tf.random_normal_initializer(stddev=0.02)\n gamma_init = tf.random_normal_initializer(1., 0.02)\n with tf.variable_scope('discriminator', reuse=reuse):\n tl.layers.set_name_reuse(reuse)\n\n net_in = InputLayer(inputs, name='d/in')\n # shape = [64, 28, 28, 1]\n net_h0 = Conv2d(net_in, df_dim, (5, 5), (1, 1), act=None,\n padding='SAME', W_init=w_init, name='d/h0/conv2d')\n # shape=[64, 28, 28, 64]\n net_h0 = BatchNormLayer(net_h0, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='d/h0/batch_norm')\n # shape=[64, 28, 28, 64]\n\n net_h1 = MaxPool2d(net_h0, filter_size=(2, 2), name='d/h1/maxpool')\n # shape = [64, 14, 14, 64]\n net_h1 = BatchNormLayer(net_h1, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='d/h1/batch_norm')\n # shape=[64, 14, 14, 64]\n\n net_h2 = Conv2d(net_h1, df_dim*2, (5, 5), (1, 1), act=None,\n padding='SAME', W_init=w_init, name='d/h2/conv2d')\n # shape=[64, 14, 14, 128]\n net_h2 = BatchNormLayer(net_h2, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='d/h2/batch_norm')\n # shape=[64, 14, 14, 128]\n\n net_h3 = MaxPool2d(net_h2, filter_size=(2, 2), name='d/h3/maxpool')\n # shape=[64, 7, 7, 128]\n net_h3 = BatchNormLayer(net_h3, act=tf.nn.relu, is_train=is_train,\n gamma_init=gamma_init, name='d/h3/batch_norm')\n # shape=[64, 7, 7, 128]\n net_h4 = FlattenLayer(net_h3, name='d/h4/flatten')\n # shape=[64, 6272]\n net_h4 = DenseLayer(net_h4, n_units=1024, act=tf.identity,\n W_init=w_init, name='d/h4/lin')\n # shape=[64, 1024]\n net_h5 = DenseLayer(net_h4, n_units=1, act=tf.identity,\n W_init=w_init, name='d/h5/lin')\n # shape=[64, 1]\n logits = net_h5.outputs\n net_h5.outputs = tf.nn.sigmoid(net_h5.outputs)\n return net_h5, logits\n\n'''\nif __name__ == '__main__':\n z = tf.placeholder(tf.float32, [FLAGS.batch_size, 100], name='z_noise')\n a, a1 = generator(z, is_train=True, reuse=False)\n discriminator(a.outputs, is_train=True, reuse=False)\n'''","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"390073335","text":"import pandas as pd\nimport numpy as np\nfrom imblearn.over_sampling import SMOTE\n\nfrom utils.data_management import DataManagement\nfrom utils.feature_scaling import FeatureScaling\nfrom sklearn.preprocessing import LabelEncoder\n\n\nclass FeatureEngineering:\n def __init__(self, dataset, config, logger):\n self.config = config\n self.dataset = dataset\n self.logger = logger\n self.feature_scaling = FeatureScaling(self.logger)\n self.data_mgmt = DataManagement(self.logger)\n self.smote = SMOTE()\n\n def pre_process_data(self):\n self.logger.info('***** Training Feature Engineering Pipeline pre_process_data Started *****')\n try:\n # remove unwanted cols\n self.remove_cols(['customerID'])\n\n # convert column TotalCharges into numeric\n self.dataset['TotalCharges'] = pd.to_numeric(self.dataset['TotalCharges'], errors='coerce')\n\n # We will follow approach derive the value of TotalCharges for null using Monthly charge & Tenure\n self.dataset['TotalCharges'] = self.dataset.apply(\n lambda x: x['TotalCharges'] if not pd.isna(x['TotalCharges']) else self.fill_total_charge(\n x['MonthlyCharges'], x['tenure']), axis=1)\n\n # process categorical features\n self.dataset = self.process_categorical_features()\n\n # scale down the numeric feature using MinMaxScalar\n numeric_features = list(self.dataset.columns[self.dataset.dtypes == 'float64'])\n numeric_features.append('tenure')\n self.dataset = self.feature_scaling.min_max_scaling(self.dataset, numeric_features)\n\n # divide independent and dependent columns\n x = self.dataset.drop('Churn', axis=1)\n y = self.dataset['Churn']\n\n # from dataset observed that churn column is imbalanced and due to this there\n # is higher chances our model will not predict better we can do up sampling using SMOTE from imblearn\n x, y = self.smote.fit_resample(x, y)\n\n final_df = pd.concat([x, y], axis=1)\n final_df.to_csv('./data/cleaned_data/training/cleaned_data.csv', sep=',', index=None, header=True)\n except Exception as e:\n self.logger.error(f'error in FeatureEngineering pre_process_data e: {e}')\n raise e\n self.logger.info('***** Training Feature Engineering Pipeline pre_process_data Finished *****')\n\n return x, y\n\n def remove_cols(self, cols):\n \"\"\" removes columns from dataframe.\n\n Parameters\n ----------\n cols : array\n List of columns to be removed.\n\n Returns\n -------\n df:\n dataframe without cols.\n \"\"\"\n self.logger.info(f'***** In FeatureEngineering remove_cols removing column {cols} Started *****')\n try:\n self.dataset.drop(labels=cols, inplace=True, axis=1)\n except Exception as e:\n self.logger.error(f'error in FeatureEngineering remove_cols e: {e}')\n raise e\n self.logger.info(f'***** In remove_cols removing column {cols} Finished *****')\n\n def fill_total_charge(self, monthly_charges, tenure):\n self.logger.info('***** In fill_total_charge Started *****')\n try:\n if tenure == 0:\n total_charges = monthly_charges\n else:\n total_charges = tenure * monthly_charges\n except Exception as e:\n self.logger.error(f'error in FeatureEngineering fill_total_charge e: {e}')\n raise e\n self.logger.info('***** In fill_total_charge Finished *****')\n return np.round(total_charges, 2)\n\n def process_categorical_features(self):\n self.logger.info('***** In FeatureEngineering process_categorical_features started *****')\n try:\n # for gender column replace with value 1 & 0\n self.dataset['gender'].replace({'Male': 1, 'Female': 0}, inplace=True)\n\n # for column MultipleLines replace value No phone service with No\n self.dataset['MultipleLines'].replace('No phone service', 'No', inplace=True)\n\n # for column OnlineSecurity replace No internet service with No\n self.dataset['OnlineSecurity'].replace('No internet service', 'No', inplace=True)\n\n # for column DeviceProtection replace No internet service with No\n self.dataset['DeviceProtection'].replace('No internet service', 'No', inplace=True)\n\n # for column TechSupport replace No internet service with No\n self.dataset['TechSupport'].replace('No internet service', 'No', inplace=True)\n\n # for column StreamingMovies replace No internet service with No\n self.dataset['StreamingMovies'].replace('No internet service', 'No', inplace=True)\n\n # for column OnlineBackup replace No internet service with No\n self.dataset['OnlineBackup'].replace('No internet service', 'No', inplace=True)\n\n # for column StreamingTV replace No internet service with No\n self.dataset['StreamingTV'].replace('No internet service', 'No', inplace=True)\n\n # for columns replace Yes with 1 and No 0\n yes_no_cols = ['Partner', 'PhoneService', 'Dependents', 'MultipleLines', 'OnlineSecurity',\n 'DeviceProtection', 'TechSupport', 'StreamingMovies', 'PaperlessBilling', 'OnlineBackup',\n 'StreamingTV', 'Churn']\n\n for col in yes_no_cols:\n self.dataset[col].replace({'Yes': 1, 'No': 0}, inplace=True)\n self.dataset[col] = self.dataset[col].astype(dtype='int8')\n\n # convert InternetService,Contract,PaymentMethod columns into numeric using Label Encoding\n label_encode_cols = ['InternetService', 'Contract', 'PaymentMethod']\n label_encoder = LabelEncoder()\n for label_encode_col in label_encode_cols:\n self.dataset[label_encode_col] = label_encoder.fit_transform(self.dataset[label_encode_col])\n self.dataset[label_encode_col] = self.dataset[label_encode_col].astype(dtype='int8')\n except Exception as e:\n self.logger.error(f'error in FeatureEngineering process_categorical_features e: {e}')\n raise e\n self.logger.info('***** In FeatureEngineering process_categorical_features finished *****')\n\n return self.dataset\n\n\nif __name__ == '__main__':\n df = pd.read_csv('../../data/raw_data/customer_churn.csv')\n dataset = df.copy()\n feature_eng = FeatureEngineering(dataset)\n x_train, y_train, x_test, y_test = feature_eng.pre_process_data()\n print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)\n","sub_path":"training/pre_process_data/feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":6808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499915950","text":"#! /usr/bin/env python\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport os\r\nimport time\r\nimport datetime\r\nimport data_helpers\r\nfrom CNN import TextCNN\r\nfrom tensorflow.contrib import learn\r\nimport csv\r\n\r\n# all parameters\r\n\r\ntf.flags.DEFINE_string(\"data_sets\", \"./data/datasets/consumer_complaints3.txt\", \"Data source for the consumer_comp data.\")\r\n# for eval \r\n\r\ntf.flags.DEFINE_integer(\"batch_size\", 64, \"Batch_Size\")\r\ntf.flags.DEFINE_string(\"checkpoint_dir\", \"\", \"Checkpoint_directory\")\r\ntf.flags.DEFINE_boolean(\"eval_train\", False, \"training data evaluate\")\r\n\r\n# for misc\r\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"allowing the soft device for a placement\")\r\ntf.flags.DEFINE_boolean(\"log_device_placement\", True, \"option for devices logs for a placemen\")\r\n\r\n\r\nFLAGS = tf.flags.FLAGS\r\nFLAGS._parse_flags()\r\nprint(\"\\nParameters:\")\r\nfor attr, value in sorted(FLAGS.__flags.items()):\r\n print(\"{}={}\".format(attr.upper(), value))\r\nprint(\"\")\r\n\r\n\r\nif FLAGS.eval_train:\r\n \r\n x_raw, y_test = data_helpers.load_data_and_labels(FLAGS.data_sets)\r\n y_test = np.argmax(y_test, axis=1)\r\nelse:\r\n x_raw = [\"a masterpiece four years in the making\", \"everything is off.\"]\r\n y_test = [1, 0]\r\n\r\n# vocabulary to data mapping\r\nvocab_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"vocab\")\r\nvocab_processor = learn.preprocessing.VocabularyProcessor.restore(vocab_path)\r\nx_test = np.array(list(vocab_processor.transform(x_raw)))\r\n\r\nprint(\"\\nEvaluating...\\n\")\r\n\r\n# here is the section for evaluation\r\n\r\ncheckpoint_file = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\r\ngraph = tf.Graph()\r\nwith graph.as_default():\r\n session_conf = tf.ConfigProto(\r\n allow_soft_placement=FLAGS.allow_soft_placement,\r\n log_device_placement=FLAGS.log_device_placement)\r\n sess = tf.Session(config=session_conf)\r\n with sess.as_default():\r\n \r\n saver = tf.train.import_meta_graph(\"{}.meta\".format(checkpoint_file))\r\n saver.restore(sess, checkpoint_file)\r\n\r\n \r\n input_x = graph.get_operation_by_name(\"input_x\").outputs[0]\r\n \r\n dropout_keep_prob = graph.get_operation_by_name(\"dropout_keep_prob\").outputs[0]\r\n\r\n \r\n predictions = graph.get_operation_by_name(\"output/predictions\").outputs[0]\r\n\r\n \r\n batches = data_helpers.batch_iter(list(x_test), FLAGS.batch_size, 1, shuffle=False)\r\n\r\n \r\n all_predictions = []\r\n\r\n for x_test_batch in batches:\r\n batch_predictions = sess.run(predictions, {input_x: x_test_batch, dropout_keep_prob: 1.0})\r\n all_predictions = np.concatenate([all_predictions, batch_predictions])\r\n\r\n\r\nif y_test is not None:\r\n correct_predictions = float(sum(all_predictions == y_test))\r\n print(\"Total number of test examples: {}\".format(len(y_test)))\r\n print(\"Accuracy: {:g}\".format(correct_predictions/float(len(y_test))))\r\n\r\n# saving__evaluations\r\npredictions_human_readable = np.column_stack((np.array(x_raw), all_predictions))\r\nout_path = os.path.join(FLAGS.checkpoint_dir, \"..\", \"prediction.csv\")\r\nprint(\"Saving evaluation to {0}\".format(out_path))\r\nwith open(out_path, 'w') as f:\r\n csv.writer(f).writerows(predictions_human_readable)","sub_path":"Codes/CNN/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"308947225","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.db.models import Sum\n\nfrom datetime import datetime, date, timedelta\n\nfrom reports.models import Consolidation\n\nfrom .models import *\nfrom .forms import *\n\n@login_required(login_url='/sign-in/')\ndef game(request):\n return redirect(operations)\n\n@login_required(login_url='/sign-in/')\ndef operations(request):\n my_operations = Operation.objects.filter(login=request.user)\n tour = Tour.objects.last()\n if request.user.is_staff:\n battle = Battle.objects.last()\n my_operations = Operation.objects.filter(id__lte=1000)\n form = OperationFilterForm(request.GET)\n\n if form.is_valid():\n\n if form.cleaned_data[\"date_ordering\"]:\n my_operations = my_operations.order_by(form.cleaned_data[\"date_ordering\"])\n\n if form.cleaned_data[\"tp_ordering\"]:\n my_operations = my_operations.order_by(form.cleaned_data[\"tp_ordering\"])\n\n if form.cleaned_data[\"point_ordering\"]:\n my_operations = my_operations.order_by(form.cleaned_data[\"point_ordering\"])\n\n return render(request, 'game/operations.html', {\n 'operations': my_operations,\n 'form': form,\n })\n\n@login_required(login_url='/sign-in/')\ndef battle(request):\n battle = Battle.objects.last()\n form = BattleTableForm()\n form_to_refresh = BattleTableForm()\n battle_tables = BattleTable.objects.filter(battle=battle).order_by('number')\n\n if request.method == 'GET':\n form = BattleTableForm(request.GET)\n if form.is_valid():\n battle = form.cleaned_data['battle']\n battle_tables = BattleTable.objects.filter(battle=battle).order_by('number')\n\n b = battle\n bt = battle_tables\n\n status_form = StatusForm()\n\n if request.method == 'POST':\n\n status_form = StatusForm(request.POST)\n form_to_refresh = BattleTableForm(request.POST)\n\n if form_to_refresh.is_valid():\n b = form_to_refresh.cleaned_data['battle']\n bt = BattleTable.objects.filter(battle=b).order_by('number')\n\n if status_form.is_valid() and status_form.cleaned_data['status']:\n print(\"-----------STATUS---------\") # to do при выборе статуса, меняется статус игры\n\n else:\n\n for battle_table in bt:\n\n start = b.start\n finish = b.finish\n\n member1 = battle_table.member1\n operations1 = Operation.objects.filter(activation_date__range=(start, finish),\n login=member1.user.username)\n points1 = operations1.aggregate(Sum('quality_points'))['quality_points__sum']\n if points1 == 'NULL' or points1 == None:\n points1 = 0\n battle_table.points1 = points1\n\n member2 = battle_table.member2\n operations2 = Operation.objects.filter(activation_date__range=(start, finish),\n login=member2.user.username)\n points2 = operations2.aggregate(Sum('quality_points'))['quality_points__sum']\n if points2 == 'NULL' or points2 == None:\n points2 = 0\n battle_table.points2 = points2\n\n battle_table.save()\n\n\n\n\n\n\n return render(request, 'game/battle.html', {\n 'form': form,\n 'form_to_refresh': form_to_refresh,\n 'battle_tables': battle_tables,\n 'battle': battle,\n 'battle_table2': bt,\n 'battle2': b,\n 'status_form': status_form,\n })\n\n@login_required(login_url='/sign-in/')\ndef tour(request):\n tour = Tour.objects.last()\n form = TourTableForm()\n tour_tables = TourTable.objects.filter(tour=tour).order_by('table_number')\n\n if request.method == 'GET':\n form = TourTableForm(request.GET)\n if form.is_valid():\n tour = form.cleaned_data['tour']\n tour_tables = TourTable.objects.filter(tour=tour).order_by('table_number')\n\n if request.method == 'POST':\n form = TourTableForm(request.POST)\n if form.is_valid():\n tour = form.cleaned_data['tour']\n tour_tables = TourTable.objects.filter(tour=tour).order_by('table_number')\n\n battle1 = Battle.objects.get(number=1, tour=tour)\n battle2 = Battle.objects.get(number=2, tour=tour)\n battle3 = Battle.objects.get(number=3, tour=tour)\n\n battle_table1 = BattleTable.objects.filter(battle=battle1)\n battle_table2 = BattleTable.objects.filter(battle=battle2)\n battle_table3 = BattleTable.objects.filter(battle=battle3)\n\n for tour_table in tour_tables:\n\n member = tour_table.member\n\n if member != Dvo.objects.get(user__username='bot'):\n\n if battle_table1.filter(member1=member).exists():\n battle_table_object1 = battle_table1.get(member1=member)\n tour_table.points1 = battle_table_object1.points1\n elif battle_table1.filter(member2=member).exists():\n battle_table_object1 = battle_table1.get(member2=member)\n tour_table.points1 = battle_table_object1.points2\n\n if battle_table2.filter(member1=member).exists():\n battle_table_object2 = battle_table2.get(member1=member)\n tour_table.points2 = battle_table_object2.points1\n elif battle_table2.filter(member2=member).exists():\n battle_table_object2 = battle_table2.get(member2=member)\n tour_table.points2 = battle_table_object2.points2\n\n if battle_table3.filter(member1=member).exists():\n battle_table_object3 = battle_table3.get(member1=member)\n tour_table.points3 = battle_table_object3.points1\n elif battle_table3.filter(member2=member).exists():\n battle_table_object3 = battle_table3.get(member2=member)\n tour_table.points3 = battle_table_object3.points2\n\n tour_table.battles_points = tour_table.points1 + tour_table.points2 + tour_table.points3\n\n tour_table.save()\n\n return render(request, 'game/tour.html', {\n 'form': form,\n 'tour': tour,\n 'tour_tables': tour_tables,\n })\n\n\n\n@login_required(login_url='/sign-in/')\ndef start_battle(request):\n form = StartTourForm()\n\n if request.method == 'POST':\n form = StartTourForm(request.POST)\n if form.is_valid():\n\n members = Dvo.objects.filter(user__is_active='True')\n # Создаём тур\n # TO DO если такой тур уже есть\n tour = Tour()\n tour.season = form.cleaned_data[\"season\"]\n tour.number = form.cleaned_data[\"number\"]\n tour.start = form.cleaned_data[\"start\"]\n tour.finish = tour.start + timedelta(days=29)\n tour.name = \"Сезон %d Тур %d\" % (tour.season, tour.number)\n tour.save()\n tour.members = members\n\n # Создаём 3 боя\n # Бой 1\n battle1 = Battle()\n battle1.tour = tour\n battle1.number = 1\n battle1.start = tour.start\n battle1.finish = battle1.start + timedelta(days=9)\n battle1.name = \"Сезон %d тур %d бой %d\" % (battle1.tour.season, battle1.tour.number, battle1.number)\n battle1.save()\n battle1.members = members\n battle1.save()\n\n # Бой 2\n battle2 = Battle()\n battle2.tour = tour\n battle2.number = 2\n battle2.start = battle1.finish + timedelta(days=1)\n battle2.finish = battle2.start + timedelta(days=9)\n battle2.name = \"Сезон %d тур %d бой %d\" % (battle2.tour.season, battle2.tour.number, battle2.number)\n battle2.save()\n battle2.members = members\n battle2.save()\n\n # Бой 3\n battle3 = Battle()\n battle3.tour = tour\n battle3.number = 3\n battle3.start = battle2.finish + timedelta(days=1)\n battle3.finish = tour.finish\n battle3.name = \"Сезон %d тур %d бой %d\" % (battle3.tour.season, battle3.tour.number, battle3.number)\n battle3.save()\n battle3.members = members\n battle3.save()\n\n # Таблица тура\n for member in members:\n tour_table = TourTable()\n tour_table.tour = tour\n tour_table.member = member\n\n # Определим сколько сотрудник заработал очков за прошлый месяц\n\n # Находим дату конца и начала прошлого месяца\n fn = date(tour.start.year, tour.start.month, 1) - timedelta(days=1)\n st = date(fn.year, fn.month, 1)\n\n # Получим операции этого сотрудника за период прошлого месяца\n operations = Operation.objects.filter(\n activation_date__range=(st, fn),\n login=member.user.username\n )\n\n # TO DO считать надо качественно\n # посчитаем сумму очков, если нет, то 0\n points = operations.aggregate(Sum('points'))['points__sum']\n if points == 'NULL' or points == None:\n points = 0\n tour_table.last_month_points = points\n tour_table.save()\n\n # Получившиеся строки упорядочим по убыванию\n tour_tables = TourTable.objects.filter(tour=tour).order_by('-last_month_points')\n\n # Присваиваем номер в таблице, номер в квартете и Лигу\n num = 0\n q_num = 0\n for t in tour_tables:\n num += 1\n q_num += 1\n t.table_number = num\n t.quartet_number = q_num\n t.league = League.objects.get(name=league_from_num(num))\n t.save()\n if q_num == 4:\n q_num = 0\n\n # Допилим хвост\n tail = len(tour_tables) % 4\n for i in range(tail):\n bot_tt = TourTable()\n bot_tt.tour = tour\n bot_tt.member = Dvo.objects.get(user__username='bot')\n num += 1\n q_num += 1\n bot_tt.table_number = num\n bot_tt.quartet_number = q_num\n bot_tt.league = League.objects.get(name=league_from_num(num))\n bot_tt.save()\n if q_num == 4:\n q_num = 0\n\n # разделив на квартеты, создаём 3 боя, только что созданного тура\n\n for i in range(0, len(tour_tables), 4):\n\n tour_table1 = TourTable.objects.get(tour=tour, table_number=i+1)\n tour_table2 = TourTable.objects.get(tour=tour, table_number=i+2)\n tour_table3 = TourTable.objects.get(tour=tour, table_number=i+3)\n tour_table4 = TourTable.objects.get(tour=tour, table_number=i+4)\n\n # Начинаем создавать таблицы боёв\n\n bt1_row1 = BattleTable()\n bt1_row1.battle = battle1\n bt1_row1.number = (i + 2)/2\n bt1_row1.league = tour_table1.league\n bt1_row1.member1 = tour_table1.member\n bt1_row1.member2 = tour_table2.member\n bt1_row1.save()\n\n bt1_row2 = BattleTable()\n bt1_row2.battle = battle1\n bt1_row2.number = (i + 4)/2\n bt1_row2.league = tour_table3.league\n bt1_row2.member1 = tour_table3.member\n bt1_row2.member2 = tour_table4.member\n bt1_row2.save()\n\n\n bt2_row1 = BattleTable()\n bt2_row1.battle = battle2\n bt2_row1.number = (i + 2)/2\n bt2_row1.league = tour_table1.league\n bt2_row1.member1 = tour_table1.member\n bt2_row1.member2 = tour_table3.member\n bt2_row1.save()\n\n bt2_row2 = BattleTable()\n bt2_row2.battle = battle2\n bt2_row2.number = (i + 4)/2\n bt2_row2.league = tour_table2.league\n bt2_row2.member1 = tour_table2.member\n bt2_row2.member2 = tour_table4.member\n bt2_row2.save()\n\n\n bt3_row1 = BattleTable()\n bt3_row1.battle = battle3\n bt3_row1.number = (i + 2)/2\n bt3_row1.league = tour_table1.league\n bt3_row1.member1 = tour_table1.member\n bt3_row1.member2 = tour_table4.member\n bt3_row1.save()\n\n bt3_row2 = BattleTable()\n bt3_row2.battle = battle3\n bt3_row2.number = (i + 4)/2\n bt3_row2.league = tour_table2.league\n bt3_row2.member1 = tour_table2.member\n bt3_row2.member2 = tour_table3.member\n bt3_row2.save()\n\n\n return render(request, 'game/start_battle.html', {\n 'form': form,\n })\n\ndef league_from_num(number):\n if 1 <= number <=20:\n return 'A'\n elif 20 < number <= 40:\n return 'B'\n elif 40 < number <= 60:\n return 'C'\n else:\n return 'D'\n","sub_path":"game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"158888944","text":"\nfrom pydub import AudioSegment\nimport os\n\ndef audio_folder_split(segment_len, audio_folder, msg=True):\n files = os.listdir(audio_folder)\n splitdir = \"split_audios\"\n\n # Adds numbers to titles if split_audio folder already exists\n if splitdir in files:\n i = 1\n splitdir += str(i)\n while splitdir in files:\n splitdir = splitdir[:-1] + str(i)\n i+=1\n os.mkdir(audio_folder + \"/\" + splitdir)\n\n # Loops through each .wav audio file\n for file in files:\n if file[-4:].lower() != '.wav':\n continue\n file_path = audio_folder + \"/\" + file\n sound = AudioSegment.from_file(file_path)\n size = len(sound)\n nsegs = int(size / segment_len) + (size % segment_len > 0)\n\n # Just to prevent accidentally creating 100+ files\n if nsegs > 100 and msg:\n print('File \"{}\" will make {} files, skip this one? (y/n)'.format(file, nsegs))\n if input().lower() in ('y', 'yes'):\n continue\n\n newdir = audio_folder + \"/\" + splitdir + \"/\" + file[:-4] + \"/\"\n os.mkdir(newdir)\n\n # Splits the files into equal length segments\n for x in range(nsegs):\n seg_sound = sound[x * segment_len:(x + 1) * segment_len]\n path = newdir + file[:-4] + \"_split\" + str(x) + \".wav\"\n seg_sound.export(path, format=\"wav\")\n print(\"Files successfully split into {} folder!\".format(splitdir))\n\n# loc = '/Users/jeremy.meyer/Desktop/wyze_camera/audio'\n\nprint(\"How long do you want each audio segment? (milliseconds)\")\nwhile True:\n try:\n seg_len = int(input())\n if seg_len > 0:\n break\n else:\n print(\"Please provide a positive integer!\")\n except TypeError:\n print(\"Please provide an integer!\")\n\nprint(\"Location of the folder with all audio files? (Will split all .wav files in folder)\")\nloc = input()\naudio_folder_split(seg_len, loc)\n","sub_path":"Vivint/Useful Python Scripts/audio_splitter.py","file_name":"audio_splitter.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"418509555","text":"# This program demonstrates the different text anchors.\nimport tkinter\nimport tkinter.font\n\nclass MyGUI:\n def __init__(self):\n # Create the main window.\n self.main_window = tkinter.Tk()\n\n # Create font object.\n myfont = tkinter.font.Font(family='Helvetica', size=12)\n\n # Create the Canvas widget.\n self.canvas = tkinter.Canvas(self.main_window, width=400, height=380)\n\n # Display text using the various anchor values.\n self.draw_dot(200, 20)\n self.canvas.create_text(200, 20, text='This text uses tkinter.CENTER', anchor=tkinter.CENTER, font=myfont)\n\n self.draw_dot(200, 60)\n self.canvas.create_text(200, 60, text='This text uses tkinter.NW', anchor=tkinter.NW, font=myfont)\n\n self.draw_dot(200, 100)\n self.canvas.create_text(200, 100, text='This text uses tkinter.N', anchor=tkinter.N, font=myfont)\n\n self.draw_dot(200, 140)\n self.canvas.create_text(200, 140, text='This text uses tkinter.NE', anchor=tkinter.NE, font=myfont)\n\n self.draw_dot(200, 180)\n self.canvas.create_text(200, 180, text='This text uses tkinter.W', anchor=tkinter.W, font=myfont)\n\n self.draw_dot(200, 220)\n self.canvas.create_text(200, 220, text='This text uses tkinter.E', anchor=tkinter.E, font=myfont)\n\n self.draw_dot(200, 260)\n self.canvas.create_text(200, 260, text='This text uses tkinter.SW', anchor=tkinter.SW, font=myfont)\n\n self.draw_dot(200, 300)\n self.canvas.create_text(200, 300, text='This text uses tkinter.S', anchor=tkinter.S, font=myfont)\n\n self.draw_dot(200, 340)\n self.canvas.create_text(200, 340, text='This text uses tkinter.SE', anchor=tkinter.SE, font=myfont)\n \n # Pack the canvas.\n self.canvas.pack()\n \n # Start the mainloop.\n tkinter.mainloop()\n\n def draw_dot(self, x, y):\n self.canvas.create_oval(x-3, y-3, x+3, y+3, fill='red')\n\n# Create an instance of the MyGUI class.\nmy_gui = MyGUI()\n","sub_path":"code/Chapter-13/text_anchors.py","file_name":"text_anchors.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"230870555","text":"import random\n\nWIDTH = 600\nHEIGHT = 600\n\nprzycisk = Rect((WIDTH/2-100, 100), (200,75))\n\nodpowiedzi = [\"Moj wywiad donosi: NIE\", \"Wyglada dobrze\", \"Kto wie?\", \"Zapomnij o tym\", \"Tak - w swoim czasie\",\n \"Prawie jak tak\", \"Nie teraz\", \"YES, YES, YES\", \"To musi poczekac\", \"Mam pewne watpliwosci\",\n \"Mozesz na to liczyc\", \"Zbyt wczesnie aby powiedziec\", \"Daj spokoj\", \"Absolutnie\", \"Chyba zartujesz?\",\n \"Na pewno nie\", \"Zrob to\", \"Prawdopodobnie\", \"Dla mnie rewelacja\", \"Na pewno tak\"]\n\nodpowiedz = \"\"\n\ndef draw():\n screen.blit('8ball', (0,0))\n screen.draw.filled_rect(przycisk, 'blue')\n screen.draw.text(\n \"Zadaj na glos pytanie i popros kule o odpowiedz!\",\n color='blue',\n midtop=(WIDTH/2,50),\n fontsize=25)\n screen.draw.text(\n \"Odpowiedz\",\n color='white',\n center=przycisk.center,\n fontsize=25)\n screen.draw.text(\n str(odpowiedz),\n color='red',\n center=(WIDTH/2, HEIGHT/2),\n fontsize=35,\n shadow=(1,1))\n\ndef on_mouse_down(pos):\n global odpowiedz\n if przycisk.collidepoint(pos):\n odpowiedz = random.choice(odpowiedzi)","sub_path":"magicball/magic8ball.py","file_name":"magic8ball.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"649370544","text":"import numpy\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.stats import norm as normal\r\n\r\nmu1 = 3\r\nstd1 = 3\r\nmu2 = 7\r\nstd2 = 4\r\n\r\nx = numpy.linspace(-15, 30, 100)\r\nnormal1 = normal(mu1, std1)\r\nnormal2 = normal(mu2, std2)\r\n\r\n# generating n sums of random variables\r\nn = 10000\r\nsamples1 = normal1.rvs(size=n)\r\nsamples2 = normal2.rvs(size=n)\r\nsamples = samples1 + samples2\r\n\r\n# finding the mean and std of samples\r\nmu = numpy.mean(samples)\r\nstd = numpy.std(samples)\r\nemp = normal(mu, std)\r\n\r\n# plotting the data:\r\nplt.plot(x, normal1.pdf(x), label='First distribution')\r\nplt.plot(x, normal2.pdf(x), label='Second distribution')\r\nplt.scatter(samples, [0] * len(samples), alpha=0.1, color='k', label='Samples')\r\nplt.plot(x, emp.pdf(x),linestyle=':',linewidth=3, label='Empirical distribution')\r\nplt.legend()\r\nplt.title('Sample Mean:{0}, Sample Variance:{1}'.format(round(mu, 2), round(std**2, 2)))\r\nplt.show()\r\n","sub_path":"HW2/Python Codes/Problem 4.py","file_name":"Problem 4.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"307119009","text":"from pyback import db\n\n\ndef get_collections(db_name: str):\n collections = []\n try:\n conn, err = db.get_connection(db_name)\n if err:\n raise Exception(err)\n\n cursor = conn.cursor()\n cursor.execute('show tables')\n tables = cursor.fetchall()\n for table in tables:\n collections.append(table[0])\n except Exception as err:\n return None, err\n else:\n return collections, None\n\n\nif __name__ == \"__main__\":\n collections, err = get_collections('test')\n if err:\n raise Exception(err)\n print(collections)\n","sub_path":"oprations.py","file_name":"oprations.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"27812680","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nn = int(input())\nc = 0\n\ndef isPrime(x:int):\n if x < 2 or x == 9:\n return False\n if x == 2 or x == 3:\n return True\n if x%2 == 0:\n return False\n i = 2\n while True:\n i += 1\n if x%i == 0:\n return False\n if x <= i**2 :\n return True\n\nfor _ in range(n):\n if isPrime(int(input())):\n c += 1\n\nprint (c)\n","sub_path":"ALDS1/1_1_c.py","file_name":"1_1_c.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"30106914","text":"# LSTM\nimport sys\nimport numpy as np\nimport keras\nfrom keras import Sequential\nfrom keras.layers import LSTM as KERAS_LSTM, Dense, Dropout\nfrom Common_Model import Common_Model\nfrom Utils import plotCurve\n\n# class LSTM inherited\nclass DNN_Model(Common_Model):\n\n def __init__(self, input_shape, num_classes, **params):\n super(DNN_Model, self).__init__(**params)\n self.input_shape = input_shape\n self.model = Sequential()\n self.make_model()\n self.model.add(Dense(num_classes, activation = 'softmax'))\n self.model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n print(self.model.summary(), file = sys.stderr)\n\n def save_model(self, model_name):\n h5_save_path = 'Models/' + model_name + '.h5'\n self.model.save_weights(h5_save_path)\n\n save_json_path = 'Models/' + model_name + '.json'\n with open(save_json_path, \"w\") as json_file:\n json_file.write(self.model.to_json())\n\n def train(self, x_train, y_train, x_val = None, y_val = None, n_epochs = 50):\n acc = []\n loss = []\n val_acc = []\n val_loss = []\n\n if x_val is None or y_val is None:\n x_val, y_val = x_train, y_train\n for i in range(n_epochs):\n\n print(\"NUMBER OF EPOCH :\", i)\n # epoch (randomize training data)\n p = np.random.permutation(len(x_train))\n x_train = x_train[p]\n y_train = y_train[p]\n \n history = self.model.fit(x_train, y_train, batch_size = 32, epochs = 1)\n\n # accuracy, loss\n acc.append(history.history['acc'])\n loss.append(history.history['loss'])\n\n # validation: accuracy, loss\n val_loss_single, val_acc_single = self.model.evaluate(x_val, y_val)\n val_acc.append(val_acc_single)\n val_loss.append(val_loss_single)\n\n plotCurve(acc, val_acc, 'LSTM Accuracy', 'acc')\n plotCurve(loss, val_loss, 'LSTM Loss', 'loss')\n self.trained = True\n\n def predict(self, sample):\n if not self.trained:\n sys.stderr.write(\"No Model.\")\n sys.exit(-1)\n return np.argmax(self.model.predict(sample), axis=1)\n\n def make_model(self):\n raise NotImplementedError()\n\n\nclass LSTM_Model(DNN_Model):\n\n def __init__(self, **params):\n params['name'] = 'LSTM'\n super(LSTM_Model, self).__init__(**params)\n\n def make_model(self):\n self.model.add(KERAS_LSTM(128, input_shape=(1, self.input_shape)))\n self.model.add(Dropout(0.5))\n self.model.add(Dense(32, activation='relu'))\n \n","sub_path":"DNN_Model.py","file_name":"DNN_Model.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"48824556","text":"data = [1, 2, 3, 4, 5, 6, 7, 8]\n\n# Ordinary loop\nevens_loop = []\nfor num in data:\n if not num % 2 == 0:\n evens_loop.append(num)\n\n# Generator\nevens = [num for num in data if not num % 2]\n\n# Ordinary loop\ndata = [1, 'One', 2, 'Two', 3, 'Three', 4, 'Four']\nwords_loop = []\nfor num in data:\n if isinstance(num, str):\n words_loop.append(num)\n\n# Generator\nwords = [num for num in data if isinstance(num, str)]\n\n# Ordinary loop\ndata = list('So long and thanks for all the fish'.split())\ntitle_loop = []\nfor word in data:\n title_loop.append(word.title())\n\n# Generator\ntitle = [word.title() for word in data]\n\n\n'''Loop and generator to revert a list'''\n\n# Loop to revert a list\na_list = [1, 'Two', 3, 4, 'Five', 6.0]\nprint(a_list)\n\nreverted_list = []\nfor index in range(len(a_list)-1, -1, -1):\n reverted_list.append(a_list[index])\n\nprint(reverted_list)\n","sub_path":"Generators/generators_try_2.py","file_name":"generators_try_2.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"71212412","text":"\"\"\"\n@Atakan Çokgünlü\nS009090\nDepartment of Computer Science\n\n\"\"\"\n\ndef split_first_line(line_f,conts):\n splitted = line_f.split(\":\")\n for x in splitted:\n tmp = x.split(\"-\")\n cont_to_course = int(tmp[1]) # take contrubition of grade\n conts.append(cont_to_course) # write contrubition of grade to an array\n\ndef take_average_grades(grades,conts):\n av = 0\n len_grades = len(conts)\n for x in range(0 , len_grades): # takes grade value for contrubition to the course ex: mt1 % 10\n av += ((conts[x] * grades[x] ) / 100 )\n return av # return students average grade\n\ngrades=dict();\ntry:\n f = open(\"gradebook.txt\", \"r\")\n firstLine=f.readline().rstrip() #get the first line from the file\n for line in f: #read the rest of the file line by line\n line=line.rstrip() #remove \\n at the end of each line\n c=line.split(\":\") #split each line into two parts\n #add each line to a dictionary - key is \"name\", value is \"all grades (i.e. a list)\n grades[c[0]]=[ int(x) for x in (c[1].strip()).split(\",\")]\nexcept:\n print(\"file couldnt read\")\n exit()\nprint(grades)\n\n\n\nall_grades = []\naverages = []\nmt1 = []\nmt2 = []\nfinal = []\nhw = []\nquiz = []\nconts = []\nsplit_first_line(firstLine,conts)\n\n\nfor x in grades.values(): #splits all all_grades to separate lists\n all_grades.append(x)\n mt1.append(x[0])\n mt2.append(x[1])\n final.append(x[2])\n hw.append(x[3])\n quiz.append(x[4])\n averages.append(take_average_grades(x,conts)) #calculates average values\nprint(averages)\n\n#writes output to file\ntry:\n out_f = open('out.txt','w')\n out_f.write(\"----------\\n\")\n out_f.write(\"averages : \\n\")\n out_f.write(str(averages)+\"\\n\")\n out_f.write(\"min mt1 : \"+str(min(mt1))+\"\\n\")\n out_f.write(\"max mt1 : \"+str(max(mt1))+\"\\n\")\n out_f.write(\"min mt2 : \"+str(min(mt2))+\"\\n\")\n out_f.write(\"max mt2 : \"+str(max(mt2))+\"\\n\")\n out_f.write(\"min final : \"+str(min(final))+\"\\n\")\n out_f.write(\"max final : \"+str(max(final))+\"\\n\")\n out_f.write(\"min hw : \"+str(min(hw))+\"\\n\")\n out_f.write(\"max hw : \"+str(max(hw))+\"\\n\")\n out_f.write(\"min quiz : \"+str(min(quiz))+\"\\n\")\n out_f.write(\"max quiz : \"+str(max(quiz))+\"\\n\")\n out_f.write(\"min average : \"+str(min(averages))+\"\\n\")\n out_f.write(\"max average : \"+str(max(averages))+\"\\n\")\n out_f.close()\nexcept:\n print (\"file write failed.\")\n exit()\n","sub_path":"ee393Codes/ee393_quiz3_S009090.py","file_name":"ee393_quiz3_S009090.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"430564783","text":"##Cette fonction \"decomp\" a pour but de décomposer une fonction\n##pour afficher chacun des termes dans une liste.\n##Elle a pour objectif de modifier un input \"trivial\" en une donnée\n##exploitable pour toutes les programmes créés par la suite,\n##notamment en supprimant les espaces en trop.\n\ndef decomp(f) :\n\n liste_termes = [] ##Liste des termes utilisés (entiers et inconnue)\n liste_op = [] ##Liste des opéateurs utilisés (+, - ou *)\n nombre = 0 \n\n ##Lecture des caractères un à un\n for i in range(len(f)) :\n \n ##Nombres\n try :\n int(f[i]) < 10 ##Vérifie que le terme de la chaîne est un nombre\n nombre = nombre * 10 ##Si c'est le cas, on multiplie le terme précédent par 10, ainsi pour 24, 2 devient 20 auquel on ajoute 4\n nombre = nombre + int(f[i]) ##On ajoute le nouveau nombre\n \n ##Ajout automatique des \"*\"\n try :\n if f[i+1] == \"x\" : ##Si le caractère suivant est un x\n liste_op.append(\"*\") ##On ajoute automatiquement un \"*\"\n #int(f[i+1]) < 10 ##On vérifie que le caractère suivant est un nombre\n\n except IndexError : ##S'il y a une erreur de taille de chaîne, c'est qu'on arrive au bout du str\n break ##Donc on break\n\n except ValueError : ##Si le caractère n'est pas un nombre\n\n if not nombre == 0 :\n liste_termes.append(nombre) ##On n'a plus besoin d'agrandir le nombre, on l'ajoute à la liste\n nombre = 0 ##On remet le nombre à 0 pour prévoir le nombre suivant\n \n ##Caractères\n \n ##Variable x\n if f[i] == \"x\" :\n liste_termes.append(\"x\")\n\n ##Opérateurs\n #elif f[i] == \"+\" or f[i] == \"-\" or f[i] == \"*\" :\n\n ##Suppression des espaces\n elif f[i] == \" \" :\n pass\n \n else :\n liste_op.append(f[i])\n\n if not nombre == 0:\n liste_termes.append(nombre)\n\n #print(\"==DÉCOUPAGE DES TERMES DE LA FONCTION==\")\n #print(\"Liste des termes de la fonction :\", liste_termes)\n #print(\"Liste des opérateurs :\", liste_op,\"\\n\")\n\n return(liste_termes, liste_op)\n\ndef calcul(liste_termes, liste_op, x) :\n\n resultat = liste_termes[0]\n\n #print(\"==CALCUL DES MULTIPLICATIONS==\")\n ##Priorité aux multiplications\n for i in range(len(liste_op)) :\n\n resultat = liste_termes[i]\n \n if liste_op[i] == \"*\" :\n resultat = resultat * eval(str(liste_termes[i+1]))\n liste_termes[i] = resultat\n #print(\"Liste des termes de la fonction :\", liste_termes)\n #print(\"Liste des opérateurs :\", liste_op,\"\\n\")\n\n i = 0\n \n #print(\"==SUPPRESSION DES TERMES MULTIPLICATEURS==\")\n ##Suppression des \"*\"\n while i < len(liste_op) :\n\n if liste_op[i] == \"*\" :\n liste_op.pop(i)\n liste_termes.pop(i+1)\n #print(\"Liste des termes de la fonction :\", liste_termes)\n #print(\"Liste des opérateurs :\", liste_op,\"\\n\")\n i = -1\n\n i = i+1\n \n #if IndexError :\n #print(i, \"Error\")\n #break\n\n #print(\"==CALCUL DES ADDITIONS ET SOUSTRACTIONS==\")\n ##Ensuite, additions et soustractions\n\n resultat = liste_termes[0]\n \n for i in range(len(liste_op)) :\n if liste_op[i] == \"+\" :\n resultat = resultat + eval(str(liste_termes[i+1]))\n elif liste_op[i] == \"-\" :\n resultat = resultat - eval(str(liste_termes[i+1]))\n #print(\"Liste des termes de la fonction :\", liste_termes)\n #print(\"Liste des opérateurs :\", liste_op,\"\\n\") \n\n return(resultat)\n\ndef racines(f) :\n print(\"Hello\")\n\ndef main(f, x) :\n\n (liste_termes, liste_op) = decomp(f)\n resultat = calcul(liste_termes, liste_op, x)\n print(\"Résultat de l'opération\", f,\"pour x =\", x, \":\", resultat)\n \n","sub_path":"decomp.py","file_name":"decomp.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"623357143","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nWindows max filename length sucks!\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\n\n\nFNAME_MAX = 120\nEND = '\\033[0m'\nULINE = '\\033[93m\\033[4m'\n\n\ndef trunc(fname, maxlen):\n \"\"\"\n Truncate to the nearest word below max.\n \"\"\"\n front, back = fname.rsplit('.', 1)\n front_pieces = front.split(' ')\n new_max = maxlen - len(back) - 1\n\n while len(front) >= new_max:\n front_pieces = front_pieces[:-1]\n if front_pieces[-1] == '-':\n front_pieces = front_pieces[:-1]\n front = ' '.join(front_pieces)\n\n new_fname = front + '.' + back\n return new_fname.replace(',.' + back, '.' + back) # remove trailing commas\n\n\ndef collect(dname='.'):\n \"\"\"\n Collect files into a dict indexed by fname length.\n \"\"\"\n files = {}\n\n for paths in os.walk(dname):\n for fname in paths[2]:\n flen = len(fname)\n fpath = os.path.join(paths[0], fname)\n try:\n files[flen].append(fpath)\n except KeyError:\n files[flen] = [fpath]\n\n return files\n\n\ndef word_diff(old, new):\n \"\"\"\n Return diff of word, highlighting deletions.\n \"\"\"\n dpos = len(old) - len(new)\n front, back = old.rsplit('.', 1)\n return front[:-dpos] + ULINE + front[-dpos:] + END + '.' + back\n\n\ndef main():\n mesg = 'Truncate a bunch of files in a folder to a maximum length.'\n parser = argparse.ArgumentParser(prog='wintrunc', description=mesg)\n parser.add_argument('-m', '--max', type=int, default=FNAME_MAX, help='the max len')\n parser.add_argument('-d', '--dname', default=os.getcwd(), help='truncate files under DNAME')\n parser.add_argument('-b', '--base', help='consider only base of fname', action='store_false')\n args = parser.parse_args()\n args.dname = os.path.abspath(args.dname)\n\n print('Searching for files under: ' + args.dname)\n files = collect(args.dname)\n\n rlist = []\n for key in files.keys():\n if key < args.max:\n continue\n\n if args.base:\n for fname in files[key]:\n dname, truncated = os.path.dirname(fname), trunc(os.path.basename(fname), args.max)\n rlist.append([fname, os.path.join(dname, truncated)])\n else:\n for fname in files[key]:\n rlist.append([fname, trunc(fname, args.max)])\n\n print('Preview of changes, underline will be removed.')\n for ent in rlist:\n print(word_diff(ent[0], ent[1]))\n\n choice = raw_input('Continue with renames? Y/n ')\n if choice.lower()[0] == 'y' and len(rlist) != 0:\n for ent in rlist:\n os.rename(ent[0], ent[1])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/wintrunc.py","file_name":"wintrunc.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"401196773","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\norigins = [\n \"http://localhost:3000\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"GET\"],\n allow_headers=[\"Content-type\",\"application/xml\"],\n)\n\n@app.get(\"/\")\nasync def root():\n return(\n \n )\n\n\n\n","sub_path":"FrontEnd/online_voting_backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"75445204","text":"from gathering_text import get_trump_tweets, get_clinton_tweets\nimport re\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nimport doctest\nanalyzer = SentimentIntensityAnalyzer()\n\n\ndef print_word_freqs(texts):\n '''Prints the frequency of words used in the list texts'''\n texts = [s + ' ' for s in texts]\n str_copy = str(texts)\n # Get rid of punctuation\n text_letters = \" \".join(re.findall(\"[a-zA-Z]+\", str_copy))\n text_letters = text_letters.split()\n # Don't include words that tell you nothing\n stop_words = ['a', 't', 'co', 'https', 'to', 'in', 'n', 'is', 'nhttps']\n stop_words += ['the', 'and', 'amp', 'pm', 'out', 'on', 'for', 'at']\n stop_words += ['s', 'of', 'be', 'going', 'p', 'The', 'it', 'our']\n stop_words += ['Kz', 'jfd', 'this', 'that', 'TKJ', 'H', 'CXLD', 'will']\n stop_words += ['have', 'RT', 're', 'kz', 'If', 'This', 'with', 've']\n # Get rid of stop words\n text_letters = [word for word in text_letters if word not in stop_words]\n my_dict = wordListToFreqDict(text_letters)\n sorted_words = sortFreqDict(my_dict)\n # Print the words sorted by frequency\n for val in sorted_words:\n print(val)\n\n\ndef wordListToFreqDict(wordlist):\n '''Given a list of words, return a dictionary of\n word-frequency pairs.\n >>> wordListToFreqDict(['hi', 'hi', 'hi'])\n {'hi': 3}\n '''\n wordfreq = [wordlist.count(p) for p in wordlist]\n return dict(zip(wordlist, wordfreq))\n\n\ndef sortFreqDict(freqdict):\n '''Sort a dictionary of word-frequency pairs in\n order of descending frequency.\n >>> sortFreqDict({'hi': 25, 'hello': 20, 'hola': 32})\n [(20, 'hello'), (25, 'hi'), (32, 'hola')]\n '''\n # Make list of dictionary entries as tuples\n # Include only words that show up more than 9 times\n freq_list = [(freqdict[key], key) for key in freqdict if freqdict[key] > 9]\n freq_list.sort()\n return freq_list\n\n\ndef main():\n '''Print Hillary and Trump's words and polarity scores'''\n print(\"Hillary's Words: \")\n print_word_freqs(get_clinton_tweets())\n print(analyzer.polarity_scores(str(get_clinton_tweets())))\n print(\"Trump's Words: \")\n print_word_freqs(get_trump_tweets())\n print(analyzer.polarity_scores(str(get_trump_tweets())))\n\n\nif __name__ == '__main__':\n main()\n doctest.testmod(verbose=True)\n","sub_path":"analyzing_text.py","file_name":"analyzing_text.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"144580887","text":"#!python\n# -*- coding: utf-8 -*-#\n#\n# Author : Bhishan Poudel; Physics Graduate Student, Ohio University\n# Date : Jan 7,2017\n# Ref: http://stackoverflow.com/questions/13413590/how-to-drop-rows-of-pandas\n# -dataframe-whose-value-in-certain-columns-is-nan\n\n# Imports\nimport pandas as pd\nimport numpy as np\n\ndef main():\n \n\n df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])\n print(df1)\n\n mask = df1.applymap(lambda x: x < -0.7)\n df1 = df1[-mask.any(axis=1)]\n mask = df1.applymap(lambda x: x >= -0.7)\n df1 = df1[mask.any(axis=1)]\n print(df1)\n\n sLength = len(df1['a'])\n print('sLength = ', sLength)\n\n # add new column to df1\n e = pd.Series(np.random.randn(sLength))\n df1 = df1.assign(e=e.values)\n print(df1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python/data_manipulation/pandas/pandas_learning/add_column.py","file_name":"add_column.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"532163845","text":"'''\n\nDescription:\n\nHTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.\n\nThe special characters and their entities for HTML are:\n\nQuotation Mark: the entity is " and symbol character is \".\nSingle Quote Mark: the entity is ' and symbol character is '.\nAmpersand: the entity is & and symbol character is &.\nGreater Than Sign: the entity is > and symbol character is >.\nLess Than Sign: the entity is < and symbol character is <.\nSlash: the entity is ⁄ and symbol character is /.\nGiven the input text string to the HTML parser, you have to implement the entity parser.\n\nReturn the text after replacing the entities by the special characters.\n\n \n\nExample 1:\n\nInput: text = \"& is an HTML entity but &ambassador; is not.\"\nOutput: \"& is an HTML entity but &ambassador; is not.\"\nExplanation: The parser will replace the & entity by &\n\n\n\nExample 2:\n\nInput: text = \"and I quote: "..."\"\nOutput: \"and I quote: \\\"...\\\"\"\n\n\n\nExample 3:\n\nInput: text = \"Stay home! Practice on Leetcode :)\"\nOutput: \"Stay home! Practice on Leetcode :)\"\n\n\n\nExample 4:\n\nInput: text = \"x > y && x < y is always false\"\nOutput: \"x > y && x < y is always false\"\n\n\n\nExample 5:\n\nInput: text = \"leetcode.com⁄problemset⁄all\"\nOutput: \"leetcode.com/problemset/all\"\n \n\nConstraints:\n\n1 <= text.length <= 10^5\nThe string may contain any possible characters out of all the 256 ASCII characters.\n\n'''\n\n\nimport re\nclass Solution:\n def entityParser(self, text: str) -> str:\n \n html_symbol = [ '"', ''', '>', '<', '⁄', '&']\n formal_symbol = [ '\"', \"'\", '>', '<', '/', '&']\n \n for html_sym, formal_sym in zip(html_symbol, formal_symbol):\n text = re.sub( html_sym , formal_sym, text )\n \n return text\n\n\n\n# n : the character length of input, text.\n\n## Time Complexity: O( n )\n#\n# The overhead in time is the cost of string replacement, which is of O( n ).\n\n## Space Complexity: O( n )\n#\n# The overhead in space is the storage for output string, which is of O( n ).\n\nfrom collections import namedtuple\nTestEntry = namedtuple('TestEntry', 'text')\ndef test_bench():\n\n test_data = [\n TestEntry( text = \"& is an HTML entity but &ambassador; is not.\" ),\n TestEntry( text = \"and I quote: "..."\" ),\n TestEntry( text = \"Stay home! Practice on Leetcode :)\" ),\n TestEntry( text = \"x > y && x < y is always false\" ),\n TestEntry( text = \"leetcode.com⁄problemset⁄all\" ),\n ]\n\n\n # expected output:\n '''\n & is an HTML entity but &ambassador; is not.\n and I quote: \"...\"\n Stay home! Practice on Leetcode :)\n x > y && x < y is always false\n leetcode.com/problemset/all\n '''\n\n for t in test_data:\n\n print( Solution().entityParser( text = t.text) )\n \n return\n\n\n\nif __name__ == '__main__':\n\n test_bench()","sub_path":"No_1410_HTML Entity Parser/by_re_replacement.py","file_name":"by_re_replacement.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"95257100","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\ni = 2004\ngames = [79, 80, 79, 78, 75, 81, 76, 79, 62, 76, 77, 69, 76, 74, 82, 55, 67, 36]\naux = 0\npoints = 0\npath = 'https://www.basketball-reference.com/players/j/jamesle01/gamelog/'\n\ngamesLJ =[]\ngamesLJ.append('Games Played')\npointsLJ = []\npointsLJ.append(\"Points scored\")\n\n#Miro cada una de sus temporadas para recoger sus partidos\nfor n in range(18):\n url = path + str(i+n) + '/'\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'lxml')\n\n table = soup.div.find(id='pgl_basic').tbody\n \n if n >0:\n aux += games[n-1]\n \n #Mirar cada uno de sus partidos para coger el número de puntos\n for m in range(1, 82):\n m = aux + m\n colID = 'pgl_basic.' + str(m)\n if table.find(id=colID)!=None:\n gamesLJ.append(m)\n points += int(table.find(id=colID).findAll('td')[26].text)\n pointsLJ.append(points)\n else:\n break\n \n \n #Aquí he sacado ya los datos y solo me queda meterlo en el csv y probar los regresores\n #print(\"Game\", m, \"Points\", points)\n\n\ndataset = r'C:\\Users\\Sergio\\Documents\\LebronPrediction\\dataset'\n\nnewFile = open(dataset + \"\\\\LJPredictionNew.csv\", 'w')\n\ndata = []\nrows = []\n\nfor n in range(0, len(gamesLJ)+1):\n rows.append(gamesLJ[n])\n rows.append(pointsLJ[n])\n\n data.append(rows)\n rows = []\n print(rows)\n\nwith newFile:\n writer = csv.writer(newFile)\n writer.writerows(data)\n\n\n \n\n\n","sub_path":"nba_predictions/scrappingDataset.py","file_name":"scrappingDataset.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"73037902","text":"import pygame\n\nclass Ship():\n\n def __init__(self,ai_settings,screen):\n '''初始化飞船并设置位置'''\n self.screen = screen\n self.ai_settings = ai_settings\n\n self.image = pygame.image.load('image/ship.png')\n self.rect =self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n self.rect.centerx =self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n self.center = float(self.rect.centerx)\n\n self.moving_rigth = False\n self.moving_left = False\n\n def blitme(self):\n '''绘制飞船'''\n self.screen.blit(self.image,self.rect)\n\n def update(self):\n '''更新飞船的位置'''\n if self.moving_rigth:\n self.center += self.ai_settings.ship_speed_factor\n #self.rect.centerx += 1\n if self.moving_left:\n self.center -= self.ai_settings.ship_speed_factor\n #self.rect.centerx -= 1\n if (self.screen_rect.left < self.center < self.screen_rect.right):\n self.rect.centerx = self.center","sub_path":"pygame/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"192692691","text":"import numpy as np\nimport scipy.stats\nimport json\n\ndef mean_confidence_interval(data, confidence=0.95, round=3):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return np.round(m,3), np.round(h,3)\n\ndef si_sdr_components(s_hat, s, n):\n \"\"\"\n Compute the components of s_hat as\n\n s_hat = alpha_s s + alpha_n n + e_art\n\n Args:\n s_hat ([type]): [description]\n s ([type]): [description]\n n ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n # s_target\n alpha_s = np.dot(s_hat, s) / np.linalg.norm(s)**2\n s_target = alpha_s * s\n\n # e_noise\n alpha_n = np.dot(s_hat, n) / np.linalg.norm(n)**2\n e_noise = alpha_n * n\n\n # e_art\n e_art = s_hat - s_target - e_noise\n \n return s_target, e_noise, e_art\n\ndef energy_ratios(s_hat, s, n):\n \"\"\"\n Compute si_sdr, si_sir, si_sar\n\n si_sir = si_snr\n (I call it like this because there is only noise as interfering source)\n\n Args:\n s_hat ([type]): [description]\n s ([type]): [description]\n n ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n s_target, e_noise, e_art = si_sdr_components(s_hat, s, n)\n\n si_sdr = 10*np.log10(np.linalg.norm(s_target)**2 / np.linalg.norm(e_noise + e_art)**2)\n si_sir = 10*np.log10(np.linalg.norm(s_target)**2 / np.linalg.norm(e_noise)**2)\n si_sar = 10*np.log10(np.linalg.norm(s_target)**2 / np.linalg.norm(e_art)**2)\n\n return si_sdr, si_sir, si_sar\n\ndef si_sdr_leroux(s_hat, s):\n \"\"\"\n Compute the components of s_hat as\n\n s_hat = alpha_s s + alpha_n n + e_art\n\n Args:\n s_hat ([type]): [description]\n s ([type]): [description]\n n ([type]): [description]\n\n Returns:\n [type]: [description]\n \"\"\"\n # s_target\n alpha_s = np.dot(s_hat, s) / np.linalg.norm(s)**2\n s_target = alpha_s * s\n\n si_sdr = 10*np.log10(np.linalg.norm(s_target)**2 / np.linalg.norm(s_target - s_hat)**2)\n \n return si_sdr\n\ndef compute_stats(metrics_keys,\n all_metrics,\n model_data_dir,\n confidence,\n all_snr_db=None,\n all_noise_types=None,\n all_speakers=None,\n all_noise_stationarities=None):\n\n # Dictionary with all metrics\n metrics = {}\n for id, key in enumerate(metrics_keys):\n metrics[key] = [j[id] for j in all_metrics]\n\n # Confidence interval\n stats = {}\n\n # Print the names of the columns. \n print (\"{:<10} {:<10} {:<10}\".format('METRIC', 'AVERAGE', 'CONF. INT.')) \n for key, metric in metrics.items():\n m, h = mean_confidence_interval(metric, confidence=confidence)\n stats[key] = {'avg': m, '+/-': h}\n print (\"{:<10} {:<10} {:<10}\".format(key, m, h))\n print('\\n')\n\n # # Save stats (si_sdr, si_sar, etc. )\n # with open(model_data_dir + 'stats.json', 'w') as f:\n # json.dump(stats, f)\n \n # #TODO: Metrics by gender?\n if all_snr_db is not None:\n for snr_db in np.unique(all_snr_db):\n stats = {}\n\n print('Input SNR = {:.2f}'.format(snr_db))\n # Print the names of the columns. \n print (\"{:<10} {:<10} {:<10}\".format('METRIC', 'AVERAGE', 'CONF. INT.')) \n for key, metric in metrics.items():\n subset_metric = np.array(metric)[np.where(all_snr_db == snr_db)]\n m, h = mean_confidence_interval(subset_metric, confidence=confidence)\n stats[key] = {'avg': m, '+/-': h}\n print (\"{:<10} {:<10} {:<10}\".format(key, m, h))\n print('\\n')\n\n if all_noise_types is not None:\n for noise_type in set(all_noise_types):\n stats = {}\n\n print('Noise type = {}'.format(noise_type))\n # Print the names of the columns. \n print (\"{:<10} {:<10} {:<10}\".format('METRIC', 'AVERAGE', 'CONF. INT.')) \n for key, metric in metrics.items():\n subset_metric = [i for i, x in zip(metric, all_noise_types) if x == noise_type]\n m, h = mean_confidence_interval(subset_metric, confidence=confidence)\n stats[key] = {'avg': m, '+/-': h}\n print (\"{:<10} {:<10} {:<10}\".format(key, m, h))\n print('\\n')\n \n if all_noise_stationarities is not None:\n for noise_stationarity in set(all_noise_stationarities):\n stats = {}\n\n print('Noise type = {}'.format(noise_stationarity))\n # Print the names of the columns. \n print (\"{:<10} {:<10} {:<10}\".format('METRIC', 'AVERAGE', 'CONF. INT.')) \n for key, metric in metrics.items():\n subset_metric = [i for i, x in zip(metric, all_noise_stationarities) if x == noise_stationarity]\n m, h = mean_confidence_interval(subset_metric, confidence=confidence)\n stats[key] = {'avg': m, '+/-': h}\n print (\"{:<10} {:<10} {:<10}\".format(key, m, h))\n print('\\n')\n\n if all_speakers is not None:\n for speaker in set(all_speakers):\n stats = {}\n\n print('Speaker = {}'.format(speaker))\n # Print the names of the columns. \n print (\"{:<10} {:<10} {:<10}\".format('METRIC', 'AVERAGE', 'CONF. INT.')) \n for key, metric in metrics.items():\n subset_metric = [i for i, x in zip(metric, all_speakers) if x == speaker]\n m, h = mean_confidence_interval(subset_metric, confidence=confidence)\n stats[key] = {'avg': m, '+/-': h}\n print (\"{:<10} {:<10} {:<10}\".format(key, m, h))\n print('\\n')","sub_path":"packages/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"266370818","text":"import sys\n\nhor = [\n \"X═══X\", #0\n \"X▌ ▐X\", #1\n \"X X\", #2\n \" \" #Err\n]\n\nver = [\n # 0 1 2 Err\n [\"║\", \"▀\", \" \", \" \"],\n [\"║\", \" \", \" \", \" \"],\n [\"║\", \"▄\", \" \", \" \"]\n]\n\nclass Drawer:\n def __init__(self, rooms):\n self.rooms = rooms\n\n def draw_line(self, line):\n global hor\n global ver\n\n line_len = len(line)\n\n for i in range(line_len):\n print(hor[line[i].get_result()[0]], end='')\n sys.stdout.write(\"\\n\")\n \n for j in range(3):\n for i in range(line_len):\n sys.stdout.write(ver[j][line[i].get_result()[3]] + \" \" + ver[j][line[i].get_result()[1]])\n print()\n \n for i in range(line_len):\n print(hor[line[i].get_result()[2]], end='') \n sys.stdout.write(\"\\n\")\n\n def draw(self):\n print(\"--------------------------------------\")\n for i in range(len(self.rooms)):\n self.draw_line(self.rooms[i])","sub_path":"Drawer.py","file_name":"Drawer.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"574312826","text":"# -*- coding: utf-8 -*-\n\"\"\"\nprograma que calcula a quantidade em segundos pelo input do usuário\n\n@author: Francisco Janela\n\"\"\"\n#função para calcular o total em segundos\ndef calcula_segundos(d,h,m,s):\n dias=24*3600*d\n horas=3600*h\n minutos=60*m\n seg=dias+horas+minutos+s\n return seg\n\n#define os inputs do usuário\ndias=input('quantos dias? ')\nhoras=input('quantas horas? ')\nminutos=input('quantos minutos? ')\nsegundos=input('quantos segundos? ')\n\nprint('total em segundos é: {0}'.format(calcula_segundos(float(dias),float(horas),float(minutos),float(segundos))))\n","sub_path":"backup/user_333/ch21_2020_03_02_22_53_43_248713.py","file_name":"ch21_2020_03_02_22_53_43_248713.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"603162541","text":"from pathlib import Path\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport numpy as np\nimport random\nimport io\nimport os\nimport sys\nfrom datetime import datetime\n\n\"\"\"\nThis is the early second one between the runs \n\"\"\"\n\nprint('Coirolanus maxlen RNN units 16 nodes in hidden layer 0.2 dropout ')\n\n# Data downloading and processing\npath = keras.utils.get_file('shakespeare.txt',\n 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')\n\nwith io.open(path, encoding=\"utf-8\") as f:\n text = f.read()\nprint(f'Amount of Characters: {len(text)}')\n\nchars = sorted(list(set(text))) # saving all the unique chars of the text\nprint(f'Amount of Unique Characters: {len(chars)}')\n\nchar_indices = dict((c, i) for i, c in enumerate(chars)) # dictionary of char->idx\nindices_char = dict((i, c) for i, c in enumerate(chars)) # dictionary of idx->char\n\nmaxlen = 40 # a length of a sentence\nstep = 3 # the distance (amount of chars) between 1 sentence and the next sentence we are taking\nsentences = [] # the list of the input sentences\nnext_chars = [] # the list of the chars coming after those sentences\n\n# filling the lists with the data\nfor i in range(0, len(text) - maxlen, step):\n sentences.append(text[i: i + maxlen])\n next_chars.append(text[i + maxlen])\nprint(\"Number of sequences:\", len(sentences))\n\nx = np.zeros((len(sentences), maxlen, len(chars)), dtype=np.bool) # defining the shape of X\ny = np.zeros((len(sentences), len(chars)), dtype=np.bool) # defining the shape of Y\nfor i, sentence in enumerate(sentences): # one-hot encoding\n for t, char in enumerate(sentence):\n x[i, t, char_indices[char]] = 1\n y[i, char_indices[next_chars[i]]] = 1\n\n# Building the model\n\nmodel = keras.Sequential(\n [\n keras.Input(shape=(maxlen, len(chars))),\n layers.LSTM(maxlen),\n layers.Dense(16, activation=\"relu\"),\n layers.Dropout(0.2),\n layers.Dense(len(chars), activation=\"softmax\"),\n ]\n)\n\noptimizer = keras.optimizers.RMSprop(learning_rate=0.01)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer)\n\n\n# TODO: read more about recommended optimizers & loss functions for RNN text gen,\n# these ones I saw was used in the internet.\n\n\ndef sample(preds, temperature=1.0):\n # a function to sample the index of the letter to use from the prediction\n \"\"\"\n :param preds: an array-like object that represents the probability each letter to be the next\n :param temperature: the degree of freedom for the decision\n (temperature > 1.0 -> more freedom, temperature < 1.0 less freedom)\n :return: the next letter of the sentence according to the statistical distribution\n \"\"\"\n\n preds = np.asarray(preds).astype(\"float64\")\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n # e^(ln(x)) = x (temperature = 1)\n # the role of the temperature is to tweak the values to lower and raise the probabilities\n\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)\n\n\ninput('\\nPress Enter to start training\\n')\n\nepochs = 40 # the amount of epochs to train\nbatch_size = 128 # the batch size\n\ntime = datetime.now().strftime(\"%d.%m.%Y.%H.%M.%S\")\ncurr_path = rf'{time}/'\nmodels_path = curr_path + 'models/'\ntexts_path = curr_path + 'texts/'\n\nif os.path.exists(curr_path) or os.path.exists(models_path) or os.path.exists(texts_path):\n sys.exit('---------------------------------\\n' +\n 'on of the paths is not good\\n' +\n '---------------------------------')\n\nos.mkdir(Path(curr_path))\nos.mkdir(Path(models_path))\nos.mkdir(Path(texts_path))\n\n# The training loop: training the model for {epochs} epochs\nfor epoch in range(epochs):\n\n # fitting it once\n model.fit(x, y, batch_size=batch_size, epochs=1)\n print()\n print(\"Generating text after epoch: %d\" % epoch)\n\n model_file_path = models_path + f'model_generation{epoch}'\n text_file_path = texts_path + f'text_generation{epoch}.txt'\n\n model.save(model_file_path) # saving the model\n\n for num in range(3):\n start_index = random.randint(0, len(text) - maxlen - 1)\n sentence = text[start_index: start_index + maxlen]\n seed = sentence # to keep track of the first sentence\n\n with open(text_file_path, 'a') as file:\n file.write(f'SEED:{seed}\\n\\n\\n')\n\n # using different kinds of divercities\n for diversity in [0.2, 0.5, 0.7, 1.0, 1.2]:\n # print(\"...Diversity:\", diversity)\n\n print(f'E{epoch} S{num} Div{diversity}')\n\n generated = \"\"\n sentence = seed # for each diversity we want the starting sentence to be the seed\n # print('...Seed:\\n' + sentence)\n\n # -- Generating 400 characters\n for i in range(400):\n x_pred = np.zeros((1, maxlen, len(chars)))\n for t, char in enumerate(sentence):\n x_pred[0, t, char_indices[char]] = 1.0\n preds = model.predict(x_pred, verbose=0)[0]\n next_index = sample(preds, diversity)\n next_char = indices_char[next_index]\n sentence = sentence[1:] + next_char\n generated += next_char\n\n # print(\"\\n...Generated:\\n\", generated)\n\n with open(text_file_path, 'a') as file:\n # I am using the append method because for each diversity i am appending the generated text\n content = f'Div {diversity}\\n'\n content += f'Generated:\\n' + seed + generated + '\\n\\n\\n'\n file.write(content)\n\n # print()\n\n with open(text_file_path, 'a') as file:\n file.write(\n f'\\n------------------------------------------------------------------------------------------------\\n')\n","sub_path":"Dropout/maxlen_RNN_16hidden_0.2.py","file_name":"maxlen_RNN_16hidden_0.2.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"36375628","text":"def read_file(filename):\r\n with open(filename) as input_file:\r\n text = input_file.read()\r\n return text\r\n\r\ndef parse_user_datafile_bs(filename):\r\n results = []\r\n text = read_file(filename)\r\n\r\n soup = BeautifulSoup(text)\r\n film_list = film_list = soup.find('div', {'class': 'profileFilmsList'})\r\n items = film_list.find_all('div', {'class': ['item', 'item even']})\r\n for item in items:\r\n # getting movie_id\r\n movie_link = item.find('div', {'class': 'nameRus'}).find('a').get('href')\r\n movie_desc = item.find('div', {'class': 'nameRus'}).find('a').text\r\n movie_id = re.findall('\\d+', movie_link)[0]\r\n\r\n # getting english name\r\n name_eng = item.find('div', {'class': 'nameEng'}).text\r\n\r\n #getting watch time\r\n watch_datetime = item.find('div', {'class': 'date'}).text\r\n date_watched, time_watched = re.match('(\\d{2}\\.\\d{2}\\.\\d{4}), (\\d{2}:\\d{2})', watch_datetime).groups()\r\n\r\n # getting user rating\r\n user_rating = item.find('div', {'class': 'vote'}).text\r\n if user_rating:\r\n user_rating = int(user_rating)\r\n\r\n results.append({\r\n 'movie_id': movie_id,\r\n 'name_eng': name_eng,\r\n 'date_watched': date_watched,\r\n 'time_watched': time_watched,\r\n 'user_rating': user_rating,\r\n 'movie_desc': movie_desc\r\n })\r\n return results\r\n\r\ndef parse_user_datafile_lxml(filename):\r\n results = []\r\n text = read_file(filename)\r\n\r\n tree = html.fromstring(text)\r\n\r\n film_list_lxml = tree.xpath('//div[@class = \"profileFilmsList\"]')[0]\r\n items_lxml = film_list_lxml.xpath('//div[@class = \"item even\" or @class = \"item\"]') \r\n for item_lxml in items_lxml:\r\n # getting movie id\r\n movie_link = item_lxml.xpath('.//div[@class = \"nameRus\"]/a/@href')[0]\r\n movie_desc = item_lxml.xpath('.//div[@class = \"nameRus\"]/a/text()')[0]\r\n movie_id = re.findall('\\d+', movie_link)[0]\r\n\r\n # getting english name\r\n name_eng = item_lxml.xpath('.//div[@class = \"nameEng\"]/text()')[0]\r\n\r\n # getting watch time\r\n watch_datetime = item_lxml.xpath('.//div[@class = \"date\"]/text()')[0]\r\n date_watched, time_watched = re.match('(\\d{2}\\.\\d{2}\\.\\d{4}), (\\d{2}:\\d{2})', watch_datetime).groups()\r\n\r\n # getting user rating\r\n user_rating = item_lxml.xpath('.//div[@class = \"vote\"]/text()')\r\n if user_rating:\r\n user_rating = int(user_rating[0])\r\n\r\n results.append({\r\n 'movie_id': movie_id,\r\n 'name_eng': name_eng,\r\n 'date_watched': date_watched,\r\n 'time_watched': time_watched,\r\n 'user_rating': user_rating,\r\n 'movie_desc': movie_desc\r\n })\r\n return results\r\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"67490462","text":"#!/usr/bin/env python\n\nfrom scapy.all import *\nfrom utils import *\nimport argparse\nimport threading\n\niface = get_if()\n\n# parse args\nparser = argparse.ArgumentParser()\nparser.add_argument('--duration', type=int, required=True, help=\"Length of sending\")\nparser.add_argument('--throughput', type=int, required=True, help=\"Number of packets per second\")\nargs = parser.parse_args()\n\n# send packets\nparent = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')/IP(src='10.0.0.1', dst='10.0.0.2')\n\np = parent / \"bunchofdata\"\np.summary()\nsendpfast(p, pps=args.throughput, loop=args.throughput*args.duration)\n\nprint(\"Sent all data packets\")\n\nfinish = parent / FINISHED\nsendp(finish, iface=iface)\n\nprint(\"Sent termination packet\")\n\nprint(\"========= Sender ========\")\nprint(\"Done\")\n","sub_path":"traffic_simulator/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"271508739","text":"import configbag\nfrom dateutil import parser\nfrom subprocess import check_output, check_call, CalledProcessError\n\n\nclass Microk8sSnap:\n def __init__(self, track, channel, juju_unit=None, juju_controller=None):\n arch = configbag.get_arch()\n cmd = \"snapcraft list-revisions microk8s --arch {}\".format(arch).split()\n revisions_list = check_output(cmd).decode(\"utf-8\").split(\"\\n\")\n if track == \"latest\":\n channel_patern = \" {}*\".format(channel)\n else:\n channel_patern = \" {}/{}*\".format(track, channel)\n\n self.juju_unit = juju_unit\n self.juju_controller = juju_controller\n self.track = track\n self.channel = channel\n revision_info_str = None\n for revision in revisions_list:\n if channel_patern in revision:\n revision_info_str = revision\n if revision_info_str:\n # revision_info_str looks like this:\n # \"180 2018-09-12T15:51:33Z amd64 v1.11.3 1.11/edge*\"\n revision_info = revision_info_str.split()\n\n self.under_testing_channel = channel\n if \"edge\" in self.under_testing_channel:\n self.under_testing_channel = \"{}/under-testing\".format(\n self.under_testing_channel\n )\n self.revision = revision_info[0]\n self.version = revision_info[3]\n version_parts = self.version.split(\".\")\n self.is_prerelease = False\n if not version_parts[2].isdigit():\n self.is_prerelease = True\n self.major_minor_version = \"{}.{}\".format(\n version_parts[0], version_parts[1]\n )\n self.release_date = parser.parse(revision_info[1])\n self.released = True\n else:\n self.released = False\n\n def release_to(self, channel, dry_run=\"no\"):\n \"\"\"\n Release the Snap to the input channel\n Args:\n channel: The channel to release to\n\n \"\"\"\n if self.is_prerelease:\n print(\n \"This is a pre-release {}. Cannot release to other channels.\".format(\n self.revision\n )\n )\n raise Exception(\"Cannot release pre-releases.\")\n target = (\n channel if self.track == \"latest\" else \"{}/{}\".format(self.track, channel)\n )\n cmd = \"snapcraft release microk8s {} {}\".format(self.revision, target)\n if dry_run == \"no\":\n check_call(cmd.split())\n else:\n print(\"DRY RUN - calling: {}\".format(cmd))\n\n def test_cross_distro(\n self,\n channel_to_upgrade=\"stable\",\n tests_branch=None,\n distributions=[\"ubuntu:16.04\", \"ubuntu:18.04\"],\n proxy=None,\n ):\n \"\"\"\n Test the channel this snap came from and make sure we can upgrade the\n channel_to_upgrade. Tests are run on the distributions distros.\n\n Args:\n channel_to_upgrade: what channel to try to upgrade\n tests_branch: the branch where tests live. Normally next to the released code.\n distributions: where to run tests on\n proxy: Proxy URL to pass to the tests\n\n \"\"\"\n # Get the microk8s source where the tests are. Switch to the branch\n # that matches the track we are going to release to.\n cmd = \"rm -rf microk8s\"\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n cmd = \"git clone https://github.com/ubuntu/microk8s\"\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n if not tests_branch:\n if self.track == \"latest\":\n tests_branch = \"master\"\n else:\n # See if we have tests for the track we are using. If not, we should default to master branch.\n # This may happen for the tracks that are building from master GH branch.\n cmd = (\n \"git ls-remote --exit-code \"\n \"--heads https://github.com/ubuntu/microk8s.git {}\".format(\n self.track\n ).split()\n )\n try:\n check_call(cmd)\n tests_branch = self.track\n except CalledProcessError:\n print(\"GH branch {} does not exist.\".format(self.track))\n tests_branch = \"master\"\n print(\"Tests are taken from branch {}\".format(tests_branch))\n cmd = \"(cd microk8s; git checkout {})\".format(tests_branch)\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n if \"under-testing\" in self.under_testing_channel:\n self.release_to(self.under_testing_channel)\n for distro in distributions:\n if self.track == \"latest\":\n track_channel_to_upgrade = channel_to_upgrade\n testing_track_channel = self.under_testing_channel\n else:\n track_channel_to_upgrade = \"{}/{}\".format(\n self.track, channel_to_upgrade\n )\n testing_track_channel = \"{}/{}\".format(\n self.track, self.under_testing_channel\n )\n\n cmd = \"sudo tests/test-distro.sh {} {} {}\".format(\n distro, track_channel_to_upgrade, testing_track_channel\n )\n if proxy:\n cmd = \"{} {}\".format(cmd, proxy)\n cmd = \"(cd microk8s; {} )\".format(cmd)\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n def build_and_release(self, release=None, dry_run=\"no\"):\n \"\"\"\n Build and release the snap from release.\n\n Args:\n release: what k8s version to package\n dry_run: if \"no\" do the actual release\n \"\"\"\n arch = configbag.get_arch()\n cmd = \"rm -rf microk8s\"\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n cmd = \"git clone https://github.com/ubuntu/microk8s\"\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n if release:\n if not release.startswith(\"v\"):\n release = \"v{}\".format(release)\n cmd = \"sed -i '/^set.*/a export KUBE_VERSION={}' microk8s/build-scripts/set-env-variables.sh\".format(\n release\n )\n if self.juju_controller:\n cmd_array = self.cmd_array_to_run(cmd)\n else:\n cmd_array = [\n \"sed\",\n \"-i\",\n \"/^set.*/a export KUBE_VERSION={}\".format(release),\n \"microk8s/build-scripts/set-env-variables.sh\",\n ]\n check_call(cmd_array)\n\n cmd = \"(cd microk8s; sudo /snap/bin/snapcraft cleanbuild)\"\n cmd_array = self.cmd_array_to_run(cmd)\n check_call(cmd_array)\n\n cmd = \"rm -rf microk8s_latest_{}.snap\".format(arch)\n check_call(cmd.split())\n if self.juju_controller:\n cmd = \"juju scp -m {} {}:/var/lib/juju/agents/unit-ubuntu-0/charm/microk8s/microk8s_latest_{}.snap .\".format(\n self.juju_controller, self.juju_unit, arch\n )\n check_call(cmd.split())\n else:\n cmd = \"mv microk8s/microk8s_latest_{}.snap .\".format(arch)\n check_call(cmd.split())\n\n target = \"{}/{}\".format(self.track, self.channel)\n cmd = \"snapcraft push microk8s_latest_{}.snap --release {}\".format(arch, target)\n if dry_run == \"no\":\n check_call(cmd.split())\n else:\n print(\"DRY RUN - calling: {}\".format(cmd))\n\n cmd = \"rm -rf microk8s_latest_{}.snap\".format(arch)\n check_call(cmd.split())\n\n def cmd_array_to_run(self, cmd):\n \"\"\"\n Return the cmd array needed to execute the command provided.\n The returned array should be applicable for running the command with juju run.\n\n Args:\n cmd: the command we wish to execute\n\n \"\"\"\n if self.juju_unit:\n cmd_array = \"juju run -m {} --timeout=120m0s --unit {}\".format(\n self.juju_controller, self.juju_unit\n ).split()\n cmd_array.append(cmd)\n else:\n cmd_array = cmd.split()\n print(\"Executing: {}\".format(cmd_array))\n return cmd_array\n","sub_path":"jobs/microk8s/snapstore.py","file_name":"snapstore.py","file_ext":"py","file_size_in_byte":8432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"39970805","text":"# ##### BEGIN GPL LICENSE BLOCK #####\r\n#\r\n# This program is free software; you can redistribute it and/or\r\n# modify it under the terms of the GNU General Public License\r\n# as published by the Free Software Foundation; either version 2\r\n# of the License, or (at your option) any later version.\r\n#\r\n# This program is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with this program; if not, write to the Free Software Foundation,\r\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n#\r\n# ##### END GPL LICENCE BLOCK #####\r\n\r\nbl_info = {\r\n \"name\": \"Sculpt Alphas Manager\",\r\n \"description\": \"Displays thumbnails of alpha textures (by categories) for quicker assignment to sculpt brushes\",\r\n \"author\": \"Ryxx\",\r\n \"blender\": (2, 81, 0),\r\n \"version\": (1, 0),\r\n \"location\": \"Sculpt Mode > Properties Editor > Active Tool tab > Texture Panel\",\r\n \"category\": \"Sculpting\"\r\n}\r\n\r\nimport os\r\nimport sys\r\nimport bpy\r\nimport bpy.utils.previews\r\nfrom bpy.types import Operator, Menu, Panel, PropertyGroup, AddonPreferences, Scene, WindowManager, BlendData\r\nfrom bpy.props import StringProperty, EnumProperty\r\n\r\n#--------------------------------------------------------------------------------------\r\n# A D D O N P R E F E R E N C E S\r\n#--------------------------------------------------------------------------------------\r\n\r\nclass SculptAlphasManagerPreferences(AddonPreferences):\r\n\r\n bl_idname = __name__\r\n\r\n sculpt_alphas_library: StringProperty(\r\n name=\"\",\r\n subtype='FILE_PATH',\r\n description = 'Main Folder containing the alphas textures used for sculpt brushes'\r\n )\r\n \r\n def draw(self, context):\r\n layout = self.layout\r\n col = layout.column(align=True)\r\n col.label(text=\"FOLDERS SETUP INSTRUCTIONS:\")\r\n col.label(text=\"Step 1 - Create a main folder that will contain your alpha textures collections and copy paste its location in the 'Library Path' field below.\")\r\n col.label(text=\"Step 2 - In that main folder, create as many sub-folders as needed and name them as you wish. These will be displayed as Categories.\")\r\n col.label(text=\"Step 3 - Fill each sub-folder with your own black and white alpha textures (formats accepted: jpeg, png, tiff). These will be displayed as thumbnails.\")\r\n col = layout.column(align=True)\r\n col.label(text=\"LIBRARY PATH:\")\r\n col.prop(self, \"sculpt_alphas_library\")\r\n\r\n#--------------------------------------------------------------------------------------\r\n# F U N C T I O N A L I T I E S\r\n#--------------------------------------------------------------------------------------\r\n\r\n# CATEGORIES PREVIEWS FUNCTION\r\ndef preview_sub_folders_categories(self, context):\r\n lib_path = context.preferences.addons[__name__].preferences.sculpt_alphas_library\r\n \r\n list_of_category_folders = []\r\n for folder in os.listdir(lib_path):\r\n if os.path.isdir(os.path.join(lib_path, folder)):\r\n list_of_category_folders.append(folder)\r\n\r\n return [(name, name, \"\") for name in list_of_category_folders]\r\n\r\n# CATEGORY ITEMS PREVIEWS FUNCTION\r\ndef preview_items_in_folders(self, context):\r\n enum_items = []\r\n\r\n if context is None:\r\n return enum_items\r\n\r\n wm = context.window_manager\r\n lib_path = context.preferences.addons[__name__].preferences.sculpt_alphas_library\r\n selected_category_name = bpy.data.scenes[\"Scene\"].category_pointer_prop.Categories\r\n directory = os.path.join(lib_path, selected_category_name)\r\n\r\n pcoll = preview_collections[\"main\"]\r\n\r\n if directory == pcoll.my_previews_dir:\r\n return pcoll.my_previews\r\n\r\n if directory and os.path.exists(directory):\r\n image_paths = []\r\n for fn in os.listdir(directory):\r\n if fn.lower().endswith(\".jpeg\") or fn.lower().endswith(\".jpg\") or fn.lower().endswith(\".png\") or fn.lower().endswith(\".tif\"):\r\n image_paths.append(fn)\r\n\r\n for i, name in enumerate(image_paths):\r\n filepath = os.path.join(directory, name)\r\n icon = pcoll.get(name)\r\n if not icon:\r\n thumb = pcoll.load(name, filepath, 'IMAGE')\r\n else:\r\n thumb = pcoll[name]\r\n enum_items.append((name, name, \"\", thumb.icon_id, i))\r\n\r\n pcoll.my_previews = enum_items\r\n pcoll.my_previews_dir = directory\r\n return pcoll.my_previews\r\n\r\n# OPEN CATEGORY FOLDER\r\nclass OpenCategoryFolder(bpy.types.Operator):\r\n bl_idname = \"open.category_folder\"\r\n bl_label = \"Open Category Folder\"\r\n bl_description = \"Open selected category's folder in OS explorer\"\r\n bl_options = {'REGISTER', 'UNDO'}\r\n\r\n def execute(self, context):\r\n lib_path = context.preferences.addons[__name__].preferences.sculpt_alphas_library\r\n selected_category_name = bpy.data.scenes[\"Scene\"].category_pointer_prop.Categories\r\n \r\n if sys.platform == \"win32\":\r\n os.startfile(os.path.join(lib_path, selected_category_name))\r\n else:\r\n opener = \"open\" if sys.platform == \"darwin\" else \"xdg-open\"\r\n subprocess.call([opener, os.path.join(lib_path, selected_category_name)])\r\n \r\n return {'FINISHED'}\r\n\r\n# ASSIGN TEXTURE\r\ndef assignTexture(self, context):\r\n\r\n lib_path = context.preferences.addons[__name__].preferences.sculpt_alphas_library\r\n selected_category_name = bpy.data.scenes[\"Scene\"].category_pointer_prop.Categories\r\n selected_alpha = bpy.context.window_manager.items_in_folders\r\n texname_no_extension = os.path.splitext(selected_alpha)[0]\r\n\r\n if bpy.context.mode == 'SCULPT':\r\n if bpy.context.tool_settings.sculpt.brush.texture is not None:\r\n sculpt_tex = bpy.context.tool_settings.sculpt.brush.texture\r\n bpy.data.textures.remove(sculpt_tex, do_unlink=True, do_id_user=True, do_ui_user=True)\r\n\r\n bpy.data.images.load(os.path.join(lib_path, selected_category_name, selected_alpha), check_existing=True)\r\n image_to_texture = bpy.data.textures.new(texname_no_extension, 'IMAGE')\r\n image_to_texture.image = bpy.data.images[selected_alpha]\r\n \r\n bpy.context.tool_settings.sculpt.brush.texture = bpy.data.textures[texname_no_extension]\r\n\r\n if bpy.context.mode == 'PAINT_TEXTURE':\r\n if bpy.context.tool_settings.image_paint.brush.texture is not None:\r\n paint_tex = bpy.context.tool_settings.image_paint.brush.texture\r\n bpy.data.textures.remove(paint_tex, do_unlink=True, do_id_user=True, do_ui_user=True)\r\n\r\n bpy.data.images.load(os.path.join(lib_path, selected_category_name, selected_alpha), check_existing=True)\r\n image_to_texture = bpy.data.textures.new(texname_no_extension, 'IMAGE')\r\n image_to_texture.image = bpy.data.images[selected_alpha]\r\n \r\n bpy.context.tool_settings.image_paint.brush.texture = bpy.data.textures[texname_no_extension]\r\n\r\n if bpy.context.mode == 'PAINT_VERTEX':\r\n if bpy.context.tool_settings.vertex_paint.brush.texture is not None:\r\n vertpaint_tex = bpy.context.tool_settings.vertex_paint.brush.texture\r\n bpy.data.textures.remove(vertpaint_tex, do_unlink=True, do_id_user=True, do_ui_user=True)\r\n\r\n bpy.data.images.load(os.path.join(lib_path, selected_category_name, selected_alpha), check_existing=True)\r\n image_to_texture = bpy.data.textures.new(texname_no_extension, 'IMAGE')\r\n image_to_texture.image = bpy.data.images[selected_alpha]\r\n \r\n bpy.context.tool_settings.vertex_paint.brush.texture = bpy.data.textures[texname_no_extension]\r\n\r\n return {'FINISHED'}\r\n\r\n# CATEGORY PROPERTY SCENE\r\nclass CategoryPropertyScene(bpy.types.PropertyGroup):\r\n \r\n Categories: EnumProperty(items = preview_sub_folders_categories)\r\n WindowManager.items_in_folders = EnumProperty(items=preview_items_in_folders, update=assignTexture)\r\n\r\n#--------------------------------------------------------------------------------------\r\n# T E X T U R E P A N E L E X T E N S I O N\r\n#--------------------------------------------------------------------------------------\r\n\r\ndef sculpt_alphas_categories_prepend(self, context):\r\n layout = self.layout\r\n \r\n row = layout.row(align=True)\r\n row.prop(context.scene.category_pointer_prop, \"Categories\", text = '')\r\n row.operator(\"open.category_folder\", text = \"\", icon =\"FILE_FOLDER\")\r\n col = layout.column(align=True)\r\n col.template_icon_view(context.window_manager, \"items_in_folders\", show_labels = True)\r\n\r\n#--------------------------------------------------------------------------------------\r\n# R E G I S T R Y\r\n#--------------------------------------------------------------------------------------\r\n\r\nclasses = (\r\n SculptAlphasManagerPreferences,\r\n OpenCategoryFolder,\r\n CategoryPropertyScene\r\n)\r\n\r\npreview_collections = {}\r\n\r\ndef register():\r\n from bpy.utils import register_class\r\n for cls in classes:\r\n register_class(cls)\r\n \r\n bpy.types.VIEW3D_PT_tools_brush_texture.prepend(sculpt_alphas_categories_prepend)\r\n\r\n Scene.category_pointer_prop = bpy.props.PointerProperty(type = CategoryPropertyScene)\r\n\r\n pcoll = bpy.utils.previews.new()\r\n pcoll.my_previews_dir = \"\"\r\n pcoll.my_previews = ()\r\n preview_collections[\"main\"] = pcoll\r\n\r\ndef unregister():\r\n from bpy.utils import unregister_class\r\n for cls in classes:\r\n unregister_class(cls)\r\n\r\n bpy.types.VIEW3D_PT_tools_brush_texture.remove(sculpt_alphas_categories_prepend)\r\n\r\n for pcoll in preview_collections.values():\r\n bpy.utils.previews.remove(pcoll)\r\n preview_collections.clear()\r\n\r\nif __name__ == \"__main__\":\r\n register()","sub_path":"Sculpt_Alphas_Manager.py","file_name":"Sculpt_Alphas_Manager.py","file_ext":"py","file_size_in_byte":9927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"132091482","text":"#!/usr/bin/env python2\n# -*- coding:UTF-8 -*-\nfrom __future__ import print_function\nimport sys\nimport argparse\nimport codecs\nimport os\nimport itertools\nimport urllib\nimport urllib2\nimport requests\nimport re\nimport execjs\nimport json\nimport time\nimport random\nimport hashlib\n# from translate import Translator\n\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n\ndef get_tk(string):\n ctx = execjs.compile(\"\"\"function VL(a) {\n var b = a.trim();\n alert(TL(b));\n //return TL(b);\n \n //测试1 //\"http://translate.google.cn/translate_a/single?client=t&sl=en&tl=zh-CN&hl=zh-CN&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&source=sel&tk=670448.790148&q=hello\"\n \n //测试2\n //\"http://translate.google.cn/translate_a/single?client=t&sl=en&tl=zh-CN&hl=zh-CN&dt=bd&dt=ex&dt=ld&dt=md&dt=qc&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&source=sel&tk=968488.586588&q=happy new year!\"\n //返回的结果\n //[[[\"新年快乐!\",\"happy new year!\",,,1],[,,\"Xīnnián kuàilè!\"]],[[\"感叹词\",[\"恭贺新禧!\",\"新年好!\"],[[\"恭贺新禧!\",[\"Happy New Year!\"]],[\"新年好!\",[\"Happy New Year!\"]]],\"Happy New Year!\",9]],\"en\",,,[[\"happy new year!\",32000,[[\"新年快乐!\",0,true,false]],[[0,15]],\"happy new year!\",0,0]],0.61467338,,[[\"en\"],,[0.61467338]],,,,,,[[\"Happy New Year!\",\"happy\",\"new\",\"year\",\"new year\"]]]\n}\nfunction TL(a) {\n var k = \"\";\n var b = 406644;\n var b1 = 3293161072;\n \n var jd = \".\";\n var $b = \"+-a^+6\";\n var Zb = \"+-3^+b+-f\";\n for (var e = [], f = 0, g = 0; g < a.length; g++) {\n var m = a.charCodeAt(g);\n 128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023),\n e[f++] = m >> 18 | 240,\n e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224,\n e[f++] = m >> 6 & 63 | 128),\n e[f++] = m & 63 | 128)\n }\n a = b;\n for (f = 0; f < e.length; f++) a += e[f],\n a = RL(a, $b);\n a = RL(a, Zb);\n a ^= b1 || 0;\n 0 > a && (a = (a & 2147483647) + 2147483648);\n a %= 1E6;\n return a.toString() + jd + (a ^ b)\n};\nfunction RL(a, b) {\n\tvar t = \"a\";\n var Yb = \"+\";\n for (var c = 0; c < b.length - 2; c += 3) {\n var d = b.charAt(c + 2),\n d = d >= t ? d.charCodeAt(0) - 87 : Number(d),\n d = b.charAt(c + 1) == Yb ? a >>> d: a << d;\n a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d\n }\n return a\n}\"\"\")\n return ctx.call(\"TL\", string)\n\n\ndef str_translate(string, lang_src=\"auto\", lang_dst=\"en\", mode=\"google1\"):\n if mode == \"google1\":\n tk = get_tk(string)\n params = {\"sl\": lang_src, \"tl\": lang_dst, \"tk\": tk, \"q\": string}\n data = requests.get((\"https://translate.google.cn/translate_a/single?client=t\"\n \"&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t\"\n \"&ie=UTF-8&oe=UTF-8&source=bh&ssel=0&tsel=0&kc=0\"), params=params)\n result = \"\".join([sentence[0] for sentence in data.json()[0] if sentence[0] is not None])\n # url = (\"https://translate.google.cn/translate_a/single?client=t&sl={}&tl={}\"\n # \"&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t\"\n # \"&ie=UTF-8&oe=UTF-8&source=bh&ssel=0&tsel=0&kc=0\"\n # \"&tk={}&q={}\").format(lang_src,lang_dst, tk, urllib.quote(string))\n # req = urllib2.Request(url)\n # req.add_header(\"User-Agent\",\n # (r\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n # r\" Chrome/62.0.3202.94 Safari/537.36\"))\n # response = urllib2.urlopen(req)\n # data = response.read().decode(\"utf-8\")\n # result = \"\".join([sentence[0] for sentence in json.loads(data)[0] if sentence[0] is not None])\n elif mode == \"google2\":\n params = {\"hl\": \"zh-CN\", \"ie\": \"utf-8\", \"text\": string, \"langpair\": \"{}|{}\".format(lang_src, lang_dst)}\n req = urllib2.Request(\"http://translate.google.cn?%s\" % urllib.urlencode(params))\n req.add_header(\"User-Agent\",\n (\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n \" Chrome/62.0.3202.94 Safari/537.36\"))\n response = urllib2.urlopen(req)\n data = response.read().decode(\"utf-8\")\n prog = re.compile(r\"(?<=TRANSLATED_TEXT=).*?;\")\n result = prog.search(data).group(0).strip(\";\").strip(\"'\")\n elif mode == \"youdao\":\n salt = str(int(time.time() * 1000) + random.randint(0, 9))\n sign = hashlib.md5(\"fanyideskweb{}{}aNPG!!u6sesA>hBAW1@(-\".format(string, salt).encode(\"utf-8\")).hexdigest()\n req = urllib2.Request(\"http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule\"\n \"&smartresult=ugc&sessionFrom=http://www.youdao.com/\")\n req.add_header(\"User-Agent\",\n (\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n \" Chrome/62.0.3202.94 Safari/537.36\"))\n params = {\"i\": string,\n \"from\": lang_src,\n \"to\": lang_dst,\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": salt,\n \"sign\": sign,\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\": \"lan-select\", # \"FY_BY_CLICKBUTTON\", \"FY_BY_REALTIME\"\n \"typoResult\": \"false\" # \"true\"\n }\n response = urllib2.urlopen(req, urllib.urlencode(params).encode(\"utf-8\"))\n data = response.read().decode(\"utf-8\")\n result = \"\".join([sentence[\"tgt\"] for sentence in json.loads(data)[\"translateResult\"][0]])\n elif mode == \"baidu\":\n # salt = str(random.randint(32768, 65536))\n # sign = hashlib.md5(\"your_appidyour_secretKey\".format(string,salt).encode(\"utf-8\")).hexdigest()\n # params = {\"appid\": \"your_appid\", \"q\": string, \"from\": lang_src, \"to\": lang_dst, \"salt\": salt, \"sign\": sign}\n # req = urllib2.Request(\"http://fanyi.baidu.com/v2transapi\" % urllib.urlencode(params))\n req = urllib2.Request(\"http://fanyi.baidu.com/v2transapi\")\n req.add_header(\"User-Agent\",\n (\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n \" Chrome/62.0.3202.94 Safari/537.36\"))\n # response = urllib2.urlopen(req)\n params = {\"from\": lang_src,\n \"to\": lang_dst,\n \"query\": string,\n \"transtype\": \"realtime\",\n \"simple_means_flag\": 3\n }\n response = urllib2.urlopen(req, urllib.urlencode(params).encode(\"utf-8\"))\n data = response.read().decode(\"utf-8\")\n # result = json.loads(data)[\"trans_result\"][0][\"dst\"]\n result = json.loads(data)[\"trans_result\"][\"data\"][0][\"dst\"]\n # elif mode == \"translate\":\n # result = translator.translate(string)\n else:\n print(\"unknown mode:\", mode)\n result = \"\"\n return result\n\n\ndef _main(argv=None):\n if argv is None:\n argv = sys.argv[1:]\n parser = argparse.ArgumentParser()\n parser.add_argument(\"input_txt_path\")\n parser.add_argument(\"output_txt_path\")\n parser.add_argument(\"-s\", \"--src\", nargs=\"?\",\n const=\"zh\", default=\"auto\")\n parser.add_argument(\"-d\", \"--dst\", nargs=\"?\",\n const=\"auto\", default=\"en\")\n parser.add_argument(\"-m\", \"--mode\", nargs=\"?\",\n const=\"google1\", default=\"google1\",\n choices=[\"google1\", \"google2\", \"youdao\", \"baidu\"])\n try:\n args = parser.parse_args(argv)\n except argparse.ArgumentError as msg:\n print(repr(msg), file=sys.stderr)\n return 1\n else:\n with codecs.open(args.input_txt_path, \"r\", \"utf-8\") as f:\n data = f.readlines()\n if os.path.exists(args.output_txt_path):\n with codecs.open(args.output_txt_path, \"rb\") as f:\n buf_gen = itertools.takewhile(lambda x: x, (f.read(1024 * 1024) for _ in itertools.repeat(None)))\n count = sum(buf.count(b\"\\n\") for buf in buf_gen)\n else:\n count = 0\n try:\n for line in data[count:]:\n with codecs.open(args.output_txt_path, \"a\", \"utf-8\") as f:\n f.write(\"%s\\n\" % str_translate(line.strip(), lang_src=args.src, lang_dst=args.dst, mode=args.mode))\n return 0\n except Exception as e:\n print(repr(e))\n return -1\n\n\nif __name__ == \"__main__\":\n sys.exit(_main())\n","sub_path":"string_translate.py","file_name":"string_translate.py","file_ext":"py","file_size_in_byte":8873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"639360212","text":"# %%\nimport lightgbm as lgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import GridSearchCV\nimport numpy as np\nimport os\nimport pandas as pd\n\n# %%\nbase_dir = os.getcwd()\n# base_dir = '/Users/jason/bestpaycup2020'\nx_df = pd.read_csv(base_dir + '/dataset/dataset2/trainset/train_main.csv')\ny_df = pd.read_csv(base_dir + '/dataset/raw_dataset/trainset/train_label.csv')\ndata_x = np.array(x_df)\n# train_x = np.delete(train_x, 0, axis=1)\ndata_y = np.array(y_df)\n\n# %%\n# 将x与y对应,并做预处理\ndata_x = data_x[data_x[:, 0].argsort()]\ndata_y = data_y[data_y[:, 0].argsort()]\ndata_x = data_x[:, 1:].astype(float)\ndata_y = data_y[:, 1:].astype(float).reshape(1, -1)[0]\n\n# %%\n# 归一化\n# n, l = data_x.shape\n# for j in range(l):\n# meanVal = np.mean(data_x[:, j])\n# stdVal = np.std(data_x[:, j])\n# if stdVal != 0 and not np.all(meanVal == 0.0):\n# data_x[:, j] = (data_x[:, j] - meanVal) / stdVal\n\n# %%\n# 打乱数据\nstate = np.random.get_state()\nnp.random.shuffle(data_x)\nnp.random.set_state(state)\nnp.random.shuffle(data_y)\n\n# %%\nX_train, X_val, y_train, y_val = train_test_split(data_x, data_y, test_size=0.1)\n\n# %%\ntrain_data = lgb.Dataset(X_train, label=y_train)\nval_data = lgb.Dataset(X_val, label=y_val)\nparams = {\n 'learning_rate': 0.1,\n 'max_depth': 10,\n 'num_leaves': 1000,\n 'objective': 'binary',\n 'subsample': 0.8,\n 'colsample_bytree': 0.8,\n 'metric': 'auc',\n 'n_estimators': 63\n # 'is_training_metric': True,\n}\n\n# %%\n# train\n# clf = lgb.train(params, train_data, valid_sets=[val_data])\n\n# %%\n# 调参,找出最佳 n_estimators\nclf = lgb.cv(params, train_data, num_boost_round=1000, nfold=5, stratified=False, shuffle=True, metrics='auc',\n early_stopping_rounds=50, seed=0)\n\nprint('best n_estimators:', len(clf['auc-mean']))\nprint('best cv score:', pd.Series(clf['auc-mean']).max())\n\n# %%\n# 调参,确定max_depth和num_leaves\nparams_test1 = {\n 'max_depth': range(3, 8, 1),\n 'num_leaves': range(5, 100, 5)\n}\n\ngsearch1 = GridSearchCV(estimator=lgb.LGBMClassifier(\n boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.1,\n n_estimators=63,\n max_depth=10,\n bagging_fraction=0.8,\n feature_fraction=0.8\n),\n param_grid=params_test1,\n scoring='roc_auc',\n cv=5,\n n_jobs=-1)\n\ngsearch1.fit(X_train, y_train)\n\nprint(gsearch1.best_params_)\nprint(gsearch1.best_score_)\n# output:\n# {'max_depth': 6, 'num_leaves': 30}\n# 0.7111428352044761\n\n# %%\n# 确定 min_data_in_leaf 和 max_bin\nparams_test2 = {\n 'max_bin': range(5, 256, 10),\n 'min_data_in_leaf': range(1, 102, 10)\n}\n\ngsearch2 = GridSearchCV(\n estimator=lgb.LGBMClassifier(boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.1,\n n_estimators=63,\n max_depth=6,\n num_leaves=30,\n bagging_fraction=0.8,\n feature_fraction=0.8),\n param_grid=params_test2, scoring='roc_auc', cv=5, n_jobs=-1\n)\n\ngsearch2.fit(X_train, y_train)\n\nprint(gsearch2.best_params_)\nprint(gsearch2.best_score_)\n\n# output:\n# {'max_bin': 15, 'min_data_in_leaf': 71}\n# 0.7130982903950965\n\n# %%\n# 确定 feature_fraction, bagging_fraction, bagging_freq\nparams_test3 = {\n 'feature_fraction': [0.6, 0.7, 0.8, 0.9, 1.0],\n 'bagging_fraction': [0.6, 0.7, 0.8, 0.9, 1.0],\n 'bagging_freq': range(0, 81, 10)\n}\n\ngsearch3 = GridSearchCV(\n estimator=lgb.LGBMClassifier(boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.1,\n n_estimators=63,\n max_depth=6,\n num_leaves=30,\n max_bin=15,\n min_data_in_leaf=71),\n param_grid=params_test3, scoring='roc_auc', cv=5, n_jobs=-1\n)\n\ngsearch3.fit(X_train, y_train)\n\nprint(gsearch3.best_params_)\nprint(gsearch3.best_score_)\n\n# output\n# {'bagging_fraction': 0.6, 'bagging_freq': 0, 'feature_fraction': 0.8}\n# 0.7130982903950965\n\n# %%\n# 确定 lambda_l1 和 lambda_l2\nparams_test4 = {'lambda_l1': [1e-5, 1e-3, 1e-1, 0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0],\n 'lambda_l2': [1e-5, 1e-3, 1e-1, 0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]}\n\ngsearch4 = GridSearchCV(\n estimator=lgb.LGBMClassifier(boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.1,\n n_estimators=63,\n max_depth=6,\n num_leaves=30,\n max_bin=15,\n min_data_in_leaf=71,\n bagging_fraction=0.6,\n bagging_freq=0,\n feature_fraction=0.8),\n param_grid=params_test4, scoring='roc_auc', cv=5, n_jobs=-1\n)\n\ngsearch4.fit(X_train, y_train)\n\nprint(gsearch4.best_params_)\nprint(gsearch4.best_score_)\n\n# output\n# {'lambda_l1': 1.0, 'lambda_l2': 0.7}\n# 0.7132416453983882\n\n# %%\n# 确定 min_split_gain\nparams_test5 = {'min_split_gain': [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]}\n\ngsearch5 = GridSearchCV(\n estimator=lgb.LGBMClassifier(boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.1,\n n_estimators=63,\n max_depth=6,\n num_leaves=30,\n max_bin=15,\n min_data_in_leaf=71,\n bagging_fraction=0.6,\n bagging_freq=0,\n feature_fraction=0.8,\n lambda_l1=1.0,\n lambda_l2=0.7),\n param_grid=params_test5, scoring='roc_auc', cv=5, n_jobs=-1\n)\n\ngsearch5.fit(X_train, y_train)\n\nprint(gsearch5.best_params_)\nprint(gsearch5.best_score_)\n\n# output\n# {'min_split_gain': 0.1}\n# 0.7117714487623986\n\n# %%\n# 训练 1\n\"\"\"\n这个训练的效果不好,只有0.53的分数\n\"\"\"\nmodel1 = lgb.LGBMClassifier(boosting_type='gbdt',\n objective='binary',\n metrics='auc',\n learning_rate=0.01,\n n_estimators=10000,\n max_depth=6,\n num_leaves=30,\n max_bin=15,\n min_data_in_leaf=71,\n bagging_fraction=0.6,\n bagging_freq=0,\n feature_fraction=0.8,\n lambda_l1=1.0,\n lambda_l2=0.7,\n min_split_gain=0.1)\n\nmodel1.fit(X_train, y_train, eval_set=[(X_val, y_val)], early_stopping_rounds=500)\n\ny_hat = model1.predict(X_val)\n\nprint('auc: ', roc_auc_score(y_val, y_hat))\n\n# %%\n# 查看权重\nheaders = x_df.columns.tolist()\nheaders.pop(0)\npd.set_option('display.max_rows', None)\nprint(pd.DataFrame({\n 'column': headers,\n 'importance': model.feature_importances_,\n}).sort_values(by='importance'))\n\nimportance = pd.DataFrame({\n 'column': headers,\n 'importance': model.feature_importances_,\n}).sort_values(by='importance')\n\nimportance.to_csv(base_dir + '/models/treemodel/lgb_2_1_weight1.csv', index=False)\n\n# %%\n# 训练 2\n\"\"\"\n这个训练效果很好,本地0.72,上传后0.67(添加output1_1_1后)\n\"\"\"\ntrain_data = lgb.Dataset(X_train, label=y_train)\nval_data = lgb.Dataset(X_val, label=y_val, reference=train_data)\n\nparams = {\n 'boosting_type': 'gbdt',\n 'objective': 'binary',\n 'metrics': 'auc',\n 'learning_rate': 0.01,\n 'n_estimators': 10000,\n 'max_depth': 6,\n 'num_leaves': 30,\n 'max_bin': 15,\n 'min_data_in_leaf': 71,\n 'bagging_fraction': 0.6,\n 'bagging_freq': 0,\n 'feature_fraction': 0.8,\n 'lambda_l1': 1.0,\n 'lambda_l2': 0.7,\n 'min_split_gain': 0.1\n}\n\nmodel2 = lgb.train(params, train_data, num_boost_round=1000, valid_sets=val_data, early_stopping_rounds=500)\n\ny_hat = model2.predict(X_val)\n\nprint('auc: ', roc_auc_score(y_val, y_hat))\n\n# %%\n# 查看权重\nheaders = x_df.columns.tolist()\nheaders.pop(0)\npd.set_option('display.max_rows', None)\nprint(pd.DataFrame({\n 'column': headers,\n 'importance': model2.feature_importance().tolist()\n}).sort_values(by='importance'))\n\nimportance = pd.DataFrame({\n 'column': headers,\n 'importance': model2.feature_importance().tolist()\n}).sort_values(by='importance')\n\nimportance.to_csv(base_dir + '/models/treemodel/lgb_2_1_weight2.csv', index=False)\n\n# %%\n# model2 prediction\n# 测试集\ntest_x = np.array(pd.read_csv(base_dir + '/dataset/dataset2/testset/test_a_main.csv'))\ny_df = pd.read_csv(base_dir + '/dataset/raw_dataset/testset/submit_example.csv')\n\n# lr_1_1 的输出\nout_1_1 = pd.read_csv(base_dir + '/models/logistic_regression/output_1_1_1.csv')\nout_1_2_1 = pd.read_csv(base_dir + '/models/treemodel/output_1_2_1.csv')\n\ntest_x = test_x[test_x[:, 0].argsort()]\ntest_x = test_x[:, 1:].astype(float)\n\n# %%\npred = model2.predict(test_x, num_iteration=model2.best_iteration)\ny_df.loc[:, 'prob'] = pred\n\n# %%\n# 将无op或无trans记录的预测值换成out_1_1的\ntest_df = pd.read_csv(base_dir + '/dataset/dataset2/testset/test_a_main.csv')\nfor i in range(len(test_df)):\n if test_df['n_op'].loc[i] == 0 or test_df['n_trans'].loc[i] == 0:\n y_df['prob'].loc[i] = out_1_1['prob'].loc[i]\n\n# %%\n# 将无op或无trans记录的预测值换成lgb的out_1_2_1的\ntest_df = pd.read_csv(base_dir + '/dataset/dataset4/testset/test_a_main.csv')\nfor i in range(len(test_df)):\n if test_df['n_op'].loc[i] == 0 or test_df['n_trans'].loc[i] == 0:\n y_df['prob'].loc[i] = out_1_2_1['prob'].loc[i]\n\n# %%\n\ny_df.to_csv(base_dir + '/models/treemodel/output_2_1_3.csv', index=False)\n\n# %%\n# prediction validation\n# y_pred = clf.predict(X_val)\n# y_pred = np.array([list(x).index(max(x)) for x in y_pred])\n# y_val = np.array(y_val)\n# score = roc_auc_score(y_val, y_pred)\n# print(score)\n","sub_path":"models/treemodel/lgb_2_1.py","file_name":"lgb_2_1.py","file_ext":"py","file_size_in_byte":10557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"7524553","text":"import logging\nimport os\n\nfrom django.conf import settings\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 apps.core.models import AHAGroup, EnrollWareGroup\nfrom scraper.aha.base import AHABase\n\nlogger = logging.getLogger('aha_export')\n\n\"\"\"\nEXAMPLE_DATA_TO_EXPORT = {\n 'course': \"Airway Management Course\",\n 'language': \"English\",\n 'location': \"Above Bar CPR Office \",\n 'tc': \"HeartShare Training Services Inc.\",\n 'ts': \"HeartShare Training North Bay\",\n 'instructor': \"Jason Boudreault\",\n 'date': \"14/02/2018\",\n 'from': \"10:15 AM\",\n 'to': \"11:15 AM\",\n 'class_description': \"test\",\n 'roster_limit': '15',\n 'roster_date': \"14/02/2018\",\n 'class_notes': \"string\"\n}\n\"\"\"\n\n\nclass AHAExporter(AHABase):\n \"\"\"\n Class for export information info from AHA site\n \"\"\"\n\n ERROR_MESSAGE = \"Pasting {} failed\"\n\n def __init__(self, username, password, group_data, *args, **kwargs):\n \"\"\"\n Init\n :param username: AHA account username \n :param password: AHA account password\n :param group_data: group data to export \n \"\"\"\n super(AHAExporter, self).__init__(username, password, *args, **kwargs)\n self.group_data = group_data\n\n def _paste_fields(self):\n \"\"\"\n Paste all fields to create new class\n :return: \n \"\"\"\n self._paste_course()\n self._paste_language()\n self._paste_tc()\n self._paste_ts()\n self._paste_instructor()\n self._paste_location()\n self._paste_date()\n self._paste_roster_settings()\n self._paste_notes()\n\n def _paste_course(self):\n \"\"\"\n Paste 'course' value\n :return: \n \"\"\"\n logger.info(\"Pasting course: {}\".format(self.group_data['course']))\n value = self.group_data['course']\n element = \"//select[@id='courseId']/option[@value='{}']\".format(value)\n self.browser.find_element_by_xpath(element).click()\n\n def _paste_language(self):\n \"\"\"\n Paste 'language' value\n :return: \n \"\"\"\n logger.info(\"Pasting language: {}\".format(self.group_data['language']))\n value = self.group_data['language']\n element = \"//select[@id='languageId']/option[text()='{}']\".format(\n value)\n self.browser.find_element_by_xpath(element).click()\n\n def _paste_tc(self):\n \"\"\"\n Paste 'training center' value\n :return: \n \"\"\"\n logger.info(\n \"Pasting Training Center: {}\".format(self.group_data['tc']))\n value = self.group_data['tc']\n # element = \"//select[@id='tcId']/option[text()='{}']\".format(value)\n element = \"//select[@id='tcId']/option[@value='{}']\".format(value)\n self.browser.find_element_by_xpath(element).click()\n\n def _paste_ts(self):\n \"\"\"\n Paste 'training site' value\n :return: \n \"\"\"\n logger.info(\"Pasting Training Site: {}\".format(self.group_data['ts']))\n value = self.group_data['ts']\n WebDriverWait(self.browser, 5).until(\n EC.presence_of_element_located((By.ID, 'tsNames')))\n all_ts = self.browser.find_element_by_id('tcSiteId')\n options = [x for x in all_ts.find_elements_by_tag_name('option')]\n for element in options:\n if element.get_attribute('value') == value:\n element.click()\n break\n\n def _paste_instructor(self):\n \"\"\"\n Paste 'instructor' value\n :return: \n \"\"\"\n logger.info(\n \"Pasting instructor: {}\".format(self.group_data['instructor']))\n value = self.group_data['instructor']\n WebDriverWait(self.browser, 5).until(\n EC.presence_of_element_located((By.ID, 'instructorId')))\n all_instructor = self.browser.find_element_by_id('instrNames')\n\n options = [x for x in\n all_instructor.find_elements_by_tag_name('option')]\n for element in options:\n if element.get_attribute('value') == value:\n element.click()\n break\n\n # all_instructor.screenshot(\n # os.path.join(settings.AHA_EXPORT_SCREENS_DIR,\n # 'instructor.png'))\n\n def _paste_location(self):\n \"\"\"\n Paste 'location' value\n :return: \n \"\"\"\n logger.info(\"Pasting location: {}\".format(self.group_data['location']))\n value = self.group_data['location']\n element = \"//select[@id='locationId']/option[@value={}]\".format(value)\n self.browser.find_element_by_xpath(element).click()\n\n def _paste_date(self):\n \"\"\"\n Paste 'date' value (class start date)\n :return: \n \"\"\"\n logger.info(\"Pasting date: {}\".format(self.group_data['date']))\n value_date = self.group_data['date']\n element_date = \"//input[@id='classStartDate']\"\n element = self.browser.find_element_by_xpath(element_date)\n self.browser.execute_script(\n \"arguments[0].value = '\" + value_date + \"'\", element)\n self.browser.find_element_by_xpath(element_date).send_keys('date')\n\n logger.info(\"Pasting description: {}\".format(\n self.group_data['class_description']))\n class_description = self.group_data['class_description']\n element_description = \"//input[@id='classMeetingDescr']\"\n self.browser.find_element_by_xpath(element_description).send_keys(\n class_description)\n\n logger.info(\"Pasting roster dated: {}\".format(self.group_data['from'],\n self.group_data['to']))\n value_start = self.group_data['from']\n element_start = \"//select[@id='classMeetingStartTime']/option[text()='{}']\".format(\n value_start)\n self.browser.find_element_by_xpath(element_start).click()\n\n value_end = self.group_data['to']\n element_end = \"//select[@id='classMeetingEndTime']/option[text()='{}']\".format(\n value_end)\n self.browser.find_element_by_xpath(element_end).click()\n\n time_button = \"//a[@id='buttonSubmitClassTime']\"\n self.browser.find_element_by_xpath(time_button).click()\n\n def _paste_roster_settings(self):\n \"\"\"\n Paste roster stiings\n :return: \n \"\"\"\n logger.info(\"Pasting roster setting:\")\n logger.info(\"Roster limit: {}\".format(self.group_data['roster_limit']))\n value_roster_limit = self.group_data['roster_limit']\n element_limit = \"//input[@id='numberOfStudents']\"\n self.browser.find_element_by_xpath(element_limit).send_keys(\n value_roster_limit)\n\n logger.info((\"Cutoff Date: {}\".format(self.group_data['cutoff_date'])))\n value_roster_date = self.group_data['cutoff_date']\n element_date = \"//input[@id='enrollCutOffDate']\"\n element = self.browser.find_element_by_xpath(element_date)\n self.browser.execute_script(\n \"arguments[0].value = '\" + value_roster_date + \"'\", element)\n\n def _paste_notes(self):\n \"\"\"\n Paste 'notes' value\n :return: \n \"\"\"\n logger.info(\"Pasting notes: {}\".format(self.group_data['class_notes']))\n class_notes = self.group_data['class_notes']\n element_notes = \"//textarea[@id='notes']\"\n self.browser.find_element_by_xpath(element_notes).send_keys(\n class_notes)\n\n def _save_button(self):\n \"\"\"\n Click on 'save' to save class\n :return: \n \"\"\"\n logger.info(\n \"Finish, click 'save': {}\".format(self.group_data['course']))\n self.browser.execute_script(\"saveInfo('save','false')\")\n\n def _check_success_export(self):\n \"\"\"\n Check if class successfully created\n :return: \n \"\"\"\n try:\n alert_div = WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.CLASS_NAME,\n \"alert-success\")))\n except:\n alert_div = self.browser.find_element(By.CLASS_NAME,\n \"alert-danger\")\n ul = alert_div.find_element(By.TAG_NAME, 'ul')\n li_elements = ul.find_elements(By.TAG_NAME, 'li')\n\n errors = [li.text for li in li_elements]\n\n raise Exception('\\n'.join(errors))\n\n def _save_aha_group_to_db(self):\n \"\"\"\n Create exported AHA group in database\n :return: \n \"\"\"\n try:\n ew_group = EnrollWareGroup.objects.get(\n id=self.group_data['enroll_id'])\n except:\n logger.info(\"enrollware group with id = {} not found \".format(\n self.group_data['enroll_id']))\n else:\n AHAGroup.objects.create(\n enrollware_group=ew_group,\n course=self.group_data['course'],\n location=self.group_data['location'],\n instructor=self.group_data['instructor'],\n training_center=self.group_data['tc'],\n training_site=self.group_data['ts'],\n cutoff_date=self.group_data['cutoff_date'],\n roster_limit=self.group_data['roster_limit'],\n description=self.group_data['class_description'],\n notes=self.group_data['class_notes']\n )\n self.logger.info(\"AHA group successfully created\")\n\n def run(self):\n \"\"\"\n Run process of export groups to AHA\n :return: \n \"\"\"\n\n # try to login and redirect to add class page\n try:\n self._login()\n self._go_to_add_class_page()\n except:\n raise Exception(\n 'login failed (username/password incorrect or AHA service unavailable)')\n\n # try to paste all fields\n try:\n self._paste_fields()\n except:\n raise Exception('can not paste fields, try again')\n\n # try to save class on AHA and save info in database\n try:\n self._save_button()\n self._check_success_export()\n self._save_aha_group_to_db()\n except Exception as msg:\n raise Exception('error while exporting group {}'.format(msg))\n","sub_path":"src/scraper/aha/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":10380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"70522264","text":"# coding=utf-8\n\n\"\"\"Add One Row to Tree.\"\"\"\n\nfrom TreeNode import TreeNode\n\n\n# dfs\ndef _solve(root, v, d):\n def _dfs(root, depth):\n if root:\n if depth == 0:\n new_left = TreeNode(v)\n new_right = TreeNode(v)\n new_left.left = root.left\n new_right.right = root.right\n root.left = new_left\n root.right = new_right\n return\n _dfs(root.left, depth - 1)\n _dfs(root.right, depth - 1)\n\n if d == 1:\n new_root = TreeNode(v)\n new_root.left = root\n return new_root\n _dfs(root, d - 1)\n return root\n\n\n# bfs,参考 https://discuss.leetcode.com/topic/92938/short-python-bfs\ndef _solve1(root, v, d):\n dummy, dummy.left = TreeNode(None), root\n row = [dummy]\n for _ in xrange(d - 1):\n row = [kid for node in row for kid in (node.left, node.right) if kid]\n for node in row:\n node.left, node.left.left = TreeNode(v), node.left\n node.right, node.right.right = TreeNode(v), node.right\n return dummy.left\n","sub_path":"medium/623.py","file_name":"623.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"244756669","text":"# -*- coding: utf-8 -*-\n\n#! /usr/bin/env python3\nimport multiprocessing\nimport multiprocessing as mp\nfrom threading import Thread\nfrom queue import Queue\n\n\nclass HendlerMidleware:\n index = 1\n def __init__(self, id_task,f):\n self.index+=self.index\n self.task_id = f\n\n\n def print_info(self):\n # print('none',self.index)\n return self.index, self.task_id\n\nf = []\n\nc = HendlerMidleware(3,f)\n\nf.append(c)\n\nc1 = HendlerMidleware(3,f)\n\n#print(c.index,c1.task_id)\n\n\nimport multiprocessing as mp\n\ndef worker(q):\n q.put()\n # while True:\n ## \n # print(item)\n\n # q.task_done()\n\nq = Queue()\n\n\nfor loop_main in range(10):pass\n # q.put(loop_main)\n\n #t = mp.Process(target=worker,args=(q,))\n #t.daemon= True\n #t.start()\n \n\nq.join()\n\nfrom functools import partial\n\npartial1 = partial\n\ndef partial(func, *args, **kwargs):\n def run_before(*fargs, **fkwargs):\n\n run_kwargs = kwargs.copy()\n run_kwargs.update(fkwargs)\n\n return func(*(args+fargs), **run_kwargs)\n \n run_before.func = func\n run_before.args = args\n run_before.kwargs = kwargs\n\n return run_before\n\nt = partial1(int, base=2)\n\n#print(t)\n\nt.__doc__= 'Convert base 2 string to an int.'\n\n#print(t('100100'))\n\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef fib(n):\n if n <2:\n return n\n return fib(n-1) + fib(n-2)\n\n\n \n\nclass Loop_Awaiter:\n queue_in_class = Queue()\n\n def __init__(self,name,balance):\n self.name = name\n self.balance = balance\n self.list_jobs = []\n\n def _put_job_in(self, job):\n Loop_Awaiter.queue_in_class.put(job)\n\n def _get_job(self):\n\n while not Loop_Awaiter.queue_in_class.empty():\n args = Loop_Awaiter.queue_in_class.get()\n\n self.list_jobs.append(args)\n yield self.list_jobs\n\n\n\n\n\n\nclass Job:\n\n def __init__(self, job_name):\n self._job_name = job_name\n #print('in init job %s ' %self._job_name)\n self._queue = Loop_Awaiter._put_job_in('1',self._job_name)\n\n\nfrom collections import deque\n\nclass QueueA:\n \n\n def __init__(self):\n self.items_in = deque()\n self.items_out = deque()\n self.items_out_count = 5\n\n # def isEmpty_out(self):\n # return self.items == \n def get_items_out(self):\n\n #if self.items_out.__len__ == self.items_out_count:\n\n\n for x in range(1):\n try:\n _ = self.items_in.pop()\n self.items_out.append(_)\n except Exception as e:\n pass\n\n # print(self.items_in is self.items_out)\n # print(self.items_in)\n return self.items_out\n\n def set_item(self, args):\n self.items_in.append(args)\n\n\nloop = Loop_Awaiter('test','balance')\n\n#Job('sdfsdfsdfsdf')\n#Job('sdfsdfsdfsdf')\n\n\n\n#for x in loop._get_job():\n# print(x)\n\n#print([fib(n) for n in range(100)])\n\nz = QueueA()\n\nfor x in range(15):\n z.set_item(x)\n\ns = z.get_items_out()\n#print(s)\n\n\n\n#print(s.pop())\n\nmax_size_q = 10\n\nsize_q_now = 3\n\ni = max_size_q - size_q_now\n\nwhile i:\n #print(i)\n i-=1\n\n#s = Z.get_items_out()\n#print(s)\n\n\nruning_task = 5\nMAX_SIZE_QUEUE = 10\n\ni =0 \nif runing_task >= MAX_SIZE_QUEUE:\n i = MAX_SIZE_QUEUE\nelse:\n i = runing_task\n#print(i)\n\n # runing_task = queue_of_run_tasks.__len__()\n\nlen_items = 1230\nparts_items = 4\n\nfrom datetime import datetime\nimport time\n\ndef time_it(func):\n def wrapper(*args,**kwargs):\n start_time = time.time()\n print('Function name {} start time ::{}'.format(func.__name__,datetime.now().strftime('%c')))\n result = func(*args,**kwargs)\n stop_time = time.time() - start_time\n print('Function name %s stop time ::%s ::working time %0.10f' % (func.__name__,datetime.now().strftime('%c'), stop_time))\n return result\n return wrapper\n\n\n#@time_it\ndef partsy_maker(*args):\n from math import floor\n from collections import deque\n\n len_items, parts_items = args\n\n# print(' len item :: %s parts :: %s ###'%(len_items, parts_items))\n\n chunk_parts = deque()\n\n chunk_size = floor(len_items/parts_items)\n #print(chunk_size)\n x = 0\n\n for i in range(parts_items):\n chunk_parts.append([x, chunk_size + x-1])\n x += chunk_size\n\n start, stop = chunk_parts[-1]\n\n if stop != len_items:\n s,e = chunk_parts.pop()\n chunk_parts.append([s, len_items])\n\n\n\n\n return chunk_parts\n\n\n\n#print(partsy_maker(len_items,parts_items))\n\n\n\ndef test_partsy_maker(func,*args):\n\n yield map(func, list(args))\n a,x,i= args\n #print('test_partsy_maker args %s : %s, item_run %s func id %s' % (a,x,str(i), id(args) ))\n\n#Function name mas_test stop time ::Wed May 3 19:16:49 2017 ::working time 59.7964541912\n@time_it\ndef mas_test():\n i = 0\n for x in range(1000):\n t=None\n \n t = list(test_partsy_maker(partsy_maker, len_items, parts_items,i)) \n #print('dfsdfdfsf',t)\n i +=1\n\n@time_it\ndef compri_test(r):\n i = 0\n o = 15000\n e=385\n yield list((partsy_maker(o,e)) for i in range(r))\n\n \n\n #print('t',list(t))\n\n#mas_test()\n#for x in compri_test(1):\n# print(x)\n\n#import pprint\n\n#print('sdsd', d)\n\n#for x in sorted(d):\n\n # print(min(x))\n\n#for x in compri_test(10):\n# print(x)\n\n\n \n# print(x)\n\n\n@time_it\ndef polindrome_n(s):\n\n len_s = len(s)\n pole_count=0\n\n for idx in range(len_s):\n l = 0\n\n #print(l)\n while (l < len_s):\n\n a,b = s[idx:l+1], s[idx:l+1][::-1]\n #print(a==b,a,b)\n if (a == b and len(b)>2):\n yield True\n pole_count+=1\n \n l+=1\n\n yield pole_count \n\n\n@time_it\ndef polindrome_n2(s):\n from array import array\n s1=array('b')\n s1.fromstring(s)\n\n #print(len(s1))\n len_s = len(s1)\n pole_count=0\n\n for idx in range(len_s):\n l = 0\n\n\n while (l < len_s):\n\n a,b =s1[idx:l+1], s1[idx:l+1][::-1]\n #print(a==b,a,b)\n if (a == b and len(b)>2):\n yield True\n pole_count+=1\n \n\n l+=1\n yield pole_count\n\n@time_it\ndef polindrome_n3(s):\n s1=[x for x in s]\n \n len_s = len(s1)\n \n pole_count=0\n\n for idx in range(len_s):\n l = 0\n\n while (l < len_s):\n\n a,b =s1[idx:l+1], s1[idx:l+1][::-1]\n\n if (a == b and len(b)>2):\n yield True\n pole_count+=1\n\n l+=1\n yield pole_count\n\n@time_it\ndef polindrome_n4(*args):\n # s1=[x for x in s]\n s = args[0]\n len_s = len(s)\n print(args)\n pole_count=0\n \n for idx in range(len_s):\n l = 0\n while (l < len_s):\n a,b =s[idx:l+1], s[idx:l+1][::-1]\n if (a == b and len(b)>2):\n yield True\n pole_count+=1\n\n l+=1\n yield pole_count\n\n\ns = 'civic'\n\n\ndef is_palindrome(seq):\n return seq == seq[::-1]\n\nwords = 'civiccivic'.split()\n#print(\"YES\" if is_palindrome(words) else \"NO\")\n\n\n\n#print(list(polindrome_n(s)))\n\n#print(list(polindrome_n2(s)))\n#print(list(polindrome_n3(s)))\n\n\n#print(list(list(list(map(polindrome_n4,(s,))))))\n\n\n#list(map(polindrome_n,(lambda *x,y: x+1,len('civic'))))\ns='ivivar'\ns[::-1]\n\n#d = lambda x,y: x+y, s[::-1],s\n#d(s,s)\n#print(d)\n#import functools\n\n#d = lambda x,y:(x+y, s[x:y+1])\n\n\n#cx = map(polindrome_n,'civic')\n#print(list(cx))\n\n\n#xc = map(lambda x: x, s)\n\n#d('ivivar','ivivar')\n#d = (functools.reduce(lambda x,y: x+y, s[::-1]) == functools.reduce(lambda x,y: x+y, s))\n#print(list(xc))\n@time_it\ndef longestPalindrome(s):\n #The main idea is manacher's algorithm\n string=\"#\"+\"#\".join(s)+\"#\" # a trick that simplifies the problems\n # e.g.:\"aaa\" ->\"#a#a#a#\" or \"aa\"->\"#a#a#\"\n i=0\n mxBorder=0 #stores the max Border that has been reached\n mxCenter=0 # ------mxCenter------mxBorder\n p=[0]*len(string)\n res=[0,0]\n \n while i< len(string):\n if mxBorder>i: #------mxCenter---i--mxBorder\n p[i]=min(p[2*mxCenter-i],mxBorder-i) # pickes the min in(center to i or i to border) \n \n else:\n p[i]=1\n \n while i-p[i]>=0 and i+p[i]res[1]-res[0]:\n res=[mxCenter,mxBorder]#records the temp maxCenter and mxBorder\n \n i+=1\n \n return \"\".join([x for x in string[2*res[0]-res[1]+1:res[1]] if x!='#'])\n\n\n#`print(longestPalindrome('civiccivic'))\n\n\nfruits = ['banana','fig','apple','cherry']\n\ni = sorted(fruits,key=lambda word:word[::-1])\ni1 = sorted(fruits,key=lambda word:word)\nprint(i,'\\n',i1)\n\n\nsd = 'civic'\n\nsss = [f for f in (lambda x:x+x, lambda x:x) if f('civic') == f('civic')[::-1]]\n\nprint(sss.__getitem__(0))\n\nprint(list(sss))\n\n\n@time_it\ndef polindrome_n42(*args):\n\n\n\n # s1=[x for x in s]\n\n\n\n s = args[0]\n s1 = [(len(s[idx:len(s)-idx]),idx,idx1) for idx in range(len(s)) for idx1 in s[idx::] if (s[idx:len(s)-idx] == s[idx:len(s)-idx][::-1]) and (len(s[idx:len(s)-idx])>2)]\n # if s[idx:idx+1] == s[idx:idx1+1][::-1]\n #s1 = [(x,idx,idx1) for x, idx in enumerate(range(len(s)), start=1) (idx1 for idx1 in s)]\n #s1 = [x for x in (x1 for x1 in range(len(s)) (c for c in s[x:])) ]\n\n\n print('s1',s1)\n\n\n len_s = len(s)\n #print(args)\n pole_count=0\n \n for idx in range(len_s):\n l = 0\n while (l < len_s):\n a,b =s[idx:l+1], s[idx:l+1][::-1]\n if (a == b and len(b)>2):\n # yield True\n pole_count+=1\n\n l+=1\n #yield pole_count\n\nsd = 'civic'\npolindrome_n42(sd)\n\n@time_it\ndef fib(n):\n a = 0\n b = 1\n for __ in range(n):\n a, b = b, a + b\n return a\n\n\nfib(5000000)","sub_path":"pyth3-gtk/testqueue.py","file_name":"testqueue.py","file_ext":"py","file_size_in_byte":9949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"414434573","text":"from copy import copy\nfrom models.batch import Batch\nfrom models.trainer import Trainer\nfrom pytest import raises\nfrom daos.daos_impl.trainer_dao_impl import TrainerDAOImpl as t\nfrom daos.daos_impl.batch_dao_impl import BatchDAOImpl as b\nfrom exceptions.resource_not_found import ResourceNotFound\nfrom utils.connection import Connection\n\nconn = Connection().conn\n\nBATCH = Batch(\"TestBatch\", \"Python Automation\", 1625788800, 1631145600)\nTRAINER = Trainer(\"Trainer\", \"McTrainerFace\", \"i@like.trains\")\n\n\ndef test_get_trainer_by_id():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n result = t.create_trainer(cursor, trainer)\n retrieve = t.get_trainer_by_id(cursor, result.id)\n assert result.first_name == retrieve.first_name\n conn.rollback()\n\n\ndef test_get_trainers_in_batch():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n batch = copy(BATCH)\n trainer.id = t.create_trainer(cursor, trainer).id\n batch.id = b.create_batch(cursor, batch).id\n t.create_trainer_batch(cursor, trainer, batch)\n trainers = t.get_trainers_in_batch(cursor, batch.id)\n assert len(trainers) != 0\n conn.rollback()\n\n\ndef test_login():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n trainer.id = t.create_trainer(cursor, trainer).id\n result = t.login(cursor, \"i@like.trains\")\n assert result.id == trainer.id\n conn.rollback()\n\n\ndef test_get_trainer_by_id_fail():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n t.create_trainer(cursor, trainer)\n with raises(ResourceNotFound):\n t.get_trainer_by_id(cursor, 0)\n conn.rollback()\n\n\ndef test_get_trainers_in_batch_fail():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n batch = copy(BATCH)\n trainer.id = t.create_trainer(cursor, trainer).id\n batch.id = b.create_batch(cursor, batch).id\n t.create_trainer_batch(cursor, trainer, batch)\n trainers = t.get_trainers_in_batch(cursor, 0)\n assert len(trainers) == 0\n conn.rollback()\n\n\ndef test_login_fail():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n trainer.id = t.create_trainer(cursor, trainer).id\n with raises(ResourceNotFound):\n t.login(cursor, \"im@a.potato\")\n conn.rollback()\n\n\ndef test_get_years_for_trainer():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n batch = copy(BATCH)\n trainer.id = t.create_trainer(cursor, trainer).id\n batch.id = b.create_batch(cursor, batch).id\n t.create_trainer_batch(cursor, trainer, batch)\n results = t.get_years_for_trainer(cursor, trainer.id)\n assert len(results) != 0\n conn.rollback()\n\n\ndef test_get_all_trainers():\n with conn:\n with conn.cursor() as cursor:\n trainer = copy(TRAINER)\n trainer.id = t.create_trainer(cursor, trainer).id\n trainer = copy(TRAINER)\n trainer_id = t.create_trainer(cursor, trainer).id\n trainers = t.get_all_trainers(cursor)\n assert len(trainers) > 1\n conn.rollback()\n\n","sub_path":"tests/dao_tests/trainer_dao_test.py","file_name":"trainer_dao_test.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"416404550","text":"def coffee(quantity, price):\r\n change = price - (quantity * 100)\r\n if change >= 0:\r\n prn(quantity, change)\r\n else:\r\n prn()\r\n\r\ndef prn(quantity=0, change=0):\r\n if quantity == 0 & change == 0:\r\n print('돈이 부족합니다.')\r\n else :\r\n print('커피 {}잔이 나왔습니다.\\n잔돈은 {}원 입니다.'.format(quantity, change))\r\n\r\ndef start():\r\n q = int(input('커피 몇 잔?'))\r\n p = int(input('돈! (1잔당 100원)'))\r\n coffee(q, p)\r\n\r\nif __name__ == '__main__':\r\n start()","sub_path":"Python01/test03/coffee_machine.py","file_name":"coffee_machine.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"239834848","text":"import numpy as np\n\n\nclass GlobalAlignment:\n def __init__(self, string1, string2, gap_penalty, matrix):\n \"\"\"\n :param string1: first string to be aligned, string\n :param string2: second string to be aligned, string\n :param gap_penalty: gap penalty, integer\n :param matrix: substitution matrix containing scores for amino acid\n matches and mismatches, dict\n\n Attention! string1 is used to index columns, string2 is used to index rows\n \"\"\"\n self.string1 = string1\n self.string2 = string2\n self.gap_penalty = gap_penalty\n self.substitution_matrix = matrix\n self.score_matrix = np.zeros((len(string2) + 1, len(string1) + 1), dtype=np.int)\n # for each cell store from which other cells it was reached (can be multiple)\n self.path_matrix = [[[] for _ in range(len(string1) + 1)] for _ in range(len(string2) + 1)]\n self.align()\n\n def align(self):\n \"\"\"\n Align given strings using the Needleman-Wunsch algorithm,\n store the alignments and the score matrix used to compute those alignments.\n NB: score matrix and the substitution matrix are different matrices!\n \"\"\"\n subst = self.substitution_matrix\n scores = self.score_matrix\n path = self.path_matrix\n gap = self.gap_penalty\n\n # fill first row and column with 0, -1, -2, ...\n for i in range(len(self.string1) + 1):\n scores[0][i] = i * gap\n for i in range(len(self.string2) + 1):\n scores[i][0] = i * gap\n\n # fill other cells, indices are on strings (add 1 for scores)\n for s1 in range(len(self.string1)):\n for s2 in range(len(self.string2)):\n s1_char = self.string1[s1]\n s2_char = self.string2[s2]\n\n # compute scores\n diag = scores[s2][s1] + subst[s1_char][s2_char]\n vert = scores[s2+1][s1] + gap\n horz = scores[s2][s1+1] + gap\n\n # update best score\n score = max(diag, vert, horz)\n scores[s2+1][s1+1] = score\n\n # update path: save from which cells this one can be reached\n coming_from = []\n if diag == score:\n coming_from.append((s2, s1))\n if vert == score:\n coming_from.append((s2+1, s1))\n if horz == score:\n coming_from.append((s2, s1+1))\n path[s2+1][s1+1] = coming_from\n\n def get_best_score(self):\n \"\"\"\n :return: the highest score for the aligned strings, int\n\n \"\"\"\n return self.score_matrix[len(self.string2)][len(self.string1)]\n\n def get_number_of_alignments(self):\n \"\"\"\n :return: number of found alignments with the best score\n \"\"\"\n return self.get_number_of_alignments_rec(len(self.string2), len(self.string1))\n\n def get_number_of_alignments_rec(self, f2, f1):\n \"\"\"\n Starting from field (s2, s1), recursively get the number of alignments\n \"\"\"\n # recursion stop\n if f2 == 0 or f1 == 0:\n return 1\n\n # sum num paths of all fields that lead to this one\n num_paths = 0\n coming_from = self.path_matrix[f2][f1]\n for f2_prev, f1_prev in coming_from:\n num_paths += self.get_number_of_alignments_rec(f2_prev, f1_prev)\n return num_paths\n\n def get_alignments(self):\n \"\"\"\n :return: list of alignments, where each alignment is represented\n as a tuple of aligned strings\n \"\"\"\n return self.get_alignments_rec(len(self.string2), len(self.string1))\n\n def get_alignments_rec(self, f2, f1):\n \"\"\"\n Starting from field (s2, s1), recursively get list if alignments\n \"\"\"\n\n # edge cases: top row / left column\n if f1 == 0 and f2 == 0:\n return [('', '')]\n if f2 == 0: # move back horizontally (top row)\n s1_char = self.string1[f1-1]\n a1, a2 = self.get_alignments_rec(f2, f1-1)[0]\n return [(a1 + s1_char, a2 + '-')]\n if f1 == 0: # move back vertically (left column)\n s2_char = self.string2[f2-1]\n a1, a2 = self.get_alignments_rec(f2-1, f1)[0]\n return [(a1 + '-', a2 + s2_char)]\n\n # somewhere in the middle\n coming_from = self.path_matrix[f2][f1]\n s1_char = self.string1[f1-1]\n s2_char = self.string2[f2-1]\n\n alignments = []\n\n # get alignments from every path leading here\n # append characters based on direction\n for f2_prev, f1_prev in coming_from:\n prev_alignments = self.get_alignments_rec(f2_prev, f1_prev)\n if f2_prev + 1 == f2 and f1_prev + 1 == f1:\n # coming from diagonal -> append chars to both strings: (X, Y) -> (Xa, Yb)\n prev_alignments = list(map(lambda al: (al[0] + s1_char, al[1] + s2_char), prev_alignments))\n\n elif f2_prev == f2 and f1_prev + 1 == f1:\n # coming from horizontal -> append char only to string 1: (X, Y) -> (Xa, Y-)\n prev_alignments = list(map(lambda al: (al[0] + s1_char, al[1] + '-'), prev_alignments))\n\n else:\n # coming from vertical -> append char only to string 2: (X, Y) -> (X-, Yb)\n prev_alignments = list(map(lambda al: (al[0] + '-', al[1] + s2_char), prev_alignments))\n\n alignments.extend(prev_alignments) # add previous extended alignments\n\n return alignments\n\n def get_score_matrix(self):\n \"\"\"\n :return: matrix built during the alignment process as a list of lists\n \"\"\"\n return self.score_matrix\n","sub_path":"codechecker/repos/3/collected_files/global_alignment/ga96xiq.py","file_name":"ga96xiq.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"485121721","text":"import sys\nimport os\n\narr = [1024, 2048, 1048576]\n\ndef countTwos(arr):\n bin_list = [] \n for i in arr:\n if i != 0 and ((i & (i - 1)) == 0):\n bin_list.append(1)\n else:\n bin_list.append(0)\n\n return bin_list\n\n\n\nf = open('temp.txt', 'w')\n \n_arr_cnt = int(raw_input(\"Enter count: \"))\n_arr_i=0\n_arr = []\nwhile _arr_i < _arr_cnt:\n _arr_item = int(raw_input(\"Enter number: \"));\n _arr.append(_arr_item)\n _arr_i+=1\n \n\nres = countTwos(_arr);\nfor res_cur in res:\n f.write( str(res_cur) + \"\\n\" )\n\nf.close()","sub_path":"misc/hr/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"634920787","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 19 11:52:14 2019\r\n\r\n@author: arje\r\n\"\"\"\r\nimport sys\r\nimport cloudpickle as pickle\r\n\r\n\"\"\"\r\nReading in the new Detect data\r\n\"\"\"\r\nfolder = ['./data/Expo_1000_Ap_3.8','./data/Expo_1000_Ap_8','./data/Expo_1000_Ap_16','./data/Expo_1500_Ap_3.8','./data/Expo_1500_Ap_8','./data/Expo_1500_Ap_16','./data/Expo_2000_Ap_3.8','./data/Expo_2000_Ap_8','./data/Expo_2000_Ap_16']\r\nseed=[12,3491,6054,9852,333,7878,5555,497,103053,45645]\r\n\r\nindex = int(sys.argv[1])\r\nfo = folder[index]\r\n\r\nconf=dict()\r\n\r\nfor se in seed:\r\n fid = open(fo+'/'+str(se)+'_sum_res_iv.pickle','rb')\r\n conf[str(se)] = pickle.load(fid)['test_m_confusion']\r\n fid.close()\r\n \r\n \r\nfid = open(fo+'/'+str(se)+'_conf_iv3.pickle','wb')\r\npickle.dump(conf,fid)\r\nfid.close()\r\n\r\nave_conf = conf['12']+conf['3491']+conf['6054']+conf['9852']+conf['333']+conf['7878']+conf['5555']+conf['497']+conf['103053']+conf['45645']\r\nave_conf = ave_conf/10\r\n\r\nave_conf\r\nprint(ave_conf)\r\n","sub_path":"Johanna/conf_seeds.py","file_name":"conf_seeds.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"40563095","text":"n = input(\"Enter number: \")\nn = int(n)\n\ni = 1\ns = 0\n\nwhile i <= n:\n if i%2 == 1:\n s = i + s\n i+=1\n else:\n i+=1\nprint(\"Sum is: \" + str(s))\n\n","sub_path":"week1/Saturday-Tasks/sum_of_odds.py","file_name":"sum_of_odds.py","file_ext":"py","file_size_in_byte":166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"130196750","text":"import argparse\nimport csv\nimport cv2\nfrom pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom sklearn import utils\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.models import Sequential\nfrom keras.layers import Lambda, Cropping2D, Conv2D, Dropout, Flatten, Dense, LeakyReLU\nfrom keras.callbacks import EarlyStopping, TensorBoard\n\nBATCH_SIZE = 32\nEPOCHS = 10\n\ndef get_model():\n model = Sequential()\n\n model.add(Lambda(lambda x: x / 127.5 - 1., input_shape=(100, 200, 3)))\n model.add(Cropping2D(cropping=((34, 0), (0, 0))))\n model.add(Conv2D(24, 5, strides=2))\n model.add(LeakyReLU())\n model.add(Conv2D(36, 5, strides=2))\n model.add(LeakyReLU())\n model.add(Conv2D(48, 5, strides=2))\n model.add(LeakyReLU())\n model.add(Conv2D(64, 3))\n model.add(LeakyReLU())\n model.add(Conv2D(64, 3))\n model.add(LeakyReLU())\n model.add(Dropout(0.5))\n\n model.add(Flatten())\n model.add(Dense(100))\n model.add(Dense(50))\n model.add(Dense(10))\n model.add(Dense(1))\n\n return model\n\ndef preprocess(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)\n img[:,:,0] = cv2.equalizeHist(img[:,:,0])\n img = cv2.resize(img, (200, 100))\n return img\n\ndef generator(samples):\n num_samples = len(samples)\n while 1:\n utils.shuffle(samples)\n for offset in range(0, num_samples, BATCH_SIZE):\n batch_samples = samples[offset:offset + BATCH_SIZE]\n\n images = []\n angles = []\n for batch_sample in batch_samples:\n for pos in range(3):\n img_path = Path(batch_sample[pos])\n img = preprocess(cv2.imread(img_path.as_posix()))\n images.append(img)\n\n center_angle = float(batch_sample[3])\n correction = 0.2\n angles.extend([\n center_angle,\n center_angle + correction,\n center_angle - correction\n ])\n\n for i in range(len(images)):\n images.append(cv2.flip(images[i], 1))\n angles.append(-angles[i])\n\n X_train = np.array(images)\n y_train = np.array(angles)\n yield utils.shuffle(X_train, y_train)\n\ndef plot_history(history):\n epochs = len(history.history['loss'])\n plt.plot(range(1, epochs+1), history.history['loss'], marker=\"o\")\n plt.plot(range(1, epochs+1), history.history['val_loss'], marker=\"o\")\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.ylim(bottom=0)\n plt.legend(['Training', 'Validation'])\n plt.savefig('figure.png')\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dir', default='./data')\n parser.add_argument('--out', default='model.h5')\n args = parser.parse_args()\n\n\n samples = []\n with Path(args.dir).joinpath('driving_log.csv').open() as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n samples.append(line)\n\n train_samples, valid_samples = train_test_split(samples, test_size=0.2)\n train_generator = generator(train_samples)\n valid_generator = generator(valid_samples)\n \n es_cb = EarlyStopping(monitor='val_loss', verbose=1)\n tb_cb = TensorBoard(log_dir='log', histogram_freq=0)\n\n model = get_model()\n model.compile(loss='mse', optimizer='adam')\n history = model.fit_generator(train_generator,\n steps_per_epoch=int(np.ceil(len(train_samples) / BATCH_SIZE)),\n validation_data=valid_generator,\n validation_steps=int(np.ceil(len(valid_samples) / BATCH_SIZE)),\n callbacks=[es_cb, tb_cb], epochs=10, verbose=1)\n\n plot_history(history)\n model.save(args.out)\n\nif __name__ == '__main__': main()\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"603847658","text":"#!/usr/bin/env python3\n\ndef is_valid(r):\n for i in range(0, len(r)):\n for j in range(i + 1, len(r)):\n if r[i] == r[j]:\n return 0\n return 1\n\nrs = []\nwith open(\"input.txt\") as f:\n for l in f.readlines():\n r = l.split()\n if r:\n rs.append(r)\nt = 0\nfor r in rs:\n t += is_valid(r)\nprint(t)\n","sub_path":"day04/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"362740100","text":"\"\"\"This module implements the UnitaryBuilder class.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Sequence\n\nimport numpy as np\n\nfrom bqskit.ir.location import CircuitLocation\nfrom bqskit.ir.location import CircuitLocationLike\nfrom bqskit.qis.unitary.unitary import Unitary\nfrom bqskit.qis.unitary.unitarymatrix import UnitaryMatrix\nfrom bqskit.utils.typing import is_integer\nfrom bqskit.utils.typing import is_valid_radixes\n\nlogger = logging.getLogger(__name__)\n\n\nclass UnitaryBuilder(Unitary):\n \"\"\"\n The UnitaryBuilder Class.\n\n A UnitaryBuilder is similar to a StringBuilder in the sense that it is an\n efficient way to string together or accumulate Unitary's. This class uses\n concepts from tensor networks to efficiently multiply unitary matrices.\n \"\"\"\n\n def __init__(self, size: int, radixes: Sequence[int] = []) -> None:\n \"\"\"\n UnitaryBuilder constructor.\n\n Args:\n size (int): The number of qudits to build a Unitary for.\n\n radixes (Sequence[int]): A sequence with its length equal\n to `size`. Each element specifies the base of a\n qudit. Defaults to qubits.\n\n Raises:\n ValueError: if size is nonpositive.\n\n Examples:\n >>> builder = UnitaryBuilder(4) # Creates a 4-qubit builder.\n \"\"\"\n\n if not is_integer(size):\n raise TypeError('Expected int for size, got %s.' % type(size))\n\n if size <= 0:\n raise ValueError('Expected positive number for size.')\n\n self.size = size\n self.radixes = tuple(radixes if len(radixes) > 0 else [2] * self.size)\n\n if not is_valid_radixes(self.radixes):\n raise TypeError('Invalid qudit radixes.')\n\n if len(self.radixes) != self.size:\n raise ValueError(\n 'Expected length of radixes to be equal to size:'\n ' %d != %d' % (len(self.radixes), self.size),\n )\n\n self.num_params = 0\n self.dim = int(np.prod(self.radixes))\n self.tensor = np.identity(self.get_dim())\n self.tensor = self.tensor.reshape(self.radixes * 2)\n\n def get_unitary(self, params: Sequence[float] = []) -> UnitaryMatrix:\n \"\"\"Build the unitary.\"\"\"\n utry = self.tensor.reshape((self.get_dim(), self.get_dim()))\n return UnitaryMatrix(utry, self.get_radixes(), False)\n\n def apply_right(\n self,\n utry: UnitaryMatrix,\n location: CircuitLocationLike,\n inverse: bool = False,\n ) -> None:\n \"\"\"\n Apply the specified unitary on the right of this UnitaryBuilder.\n\n .-----. .------.\n 0 -| |---| |-\n 1 -| |---| utry |-\n . . '------'\n . .\n . .\n n-1 -| |------------\n '-----'\n\n Args:\n utry (UnitaryMatrix): The unitary to apply.\n\n location (CircuitLocationLike): The qudits to apply the unitary on.\n\n inverse (bool): If true, apply the inverse of the unitary.\n\n Notes:\n Applying the unitary on the right is equivalent to multiplying\n the unitary on the left of the tensor. This operation is\n performed using tensor contraction.\n \"\"\"\n\n if not isinstance(utry, UnitaryMatrix):\n raise TypeError('Expected UnitaryMatrix, got %s', type(utry))\n\n if not CircuitLocation.is_location(location, self.get_size()):\n raise TypeError('Invalid location.')\n\n location = CircuitLocation(location)\n\n if len(location) != utry.get_size():\n raise ValueError('Unitary and location size mismatch.')\n\n for utry_radix, bldr_radix_idx in zip(utry.get_radixes(), location):\n if utry_radix != self.get_radixes()[bldr_radix_idx]:\n raise ValueError('Unitary and location radix mismatch.')\n\n left_perm = list(location)\n mid_perm = [x for x in range(self.get_size()) if x not in location]\n right_perm = [x + self.get_size() for x in range(self.get_size())]\n\n left_dim = int(np.prod([self.get_radixes()[x] for x in left_perm]))\n\n utry = utry.get_dagger() if inverse else utry\n utry_np = utry.get_numpy()\n\n perm = left_perm + mid_perm + right_perm\n self.tensor = self.tensor.transpose(perm)\n self.tensor = self.tensor.reshape((left_dim, -1))\n self.tensor = utry_np @ self.tensor\n\n shape = list(self.get_radixes()) * 2\n shape = [shape[p] for p in perm]\n self.tensor = self.tensor.reshape(shape)\n inv_perm = list(np.argsort(perm))\n self.tensor = self.tensor.transpose(inv_perm)\n\n def apply_left(\n self,\n utry: UnitaryMatrix,\n location: CircuitLocationLike,\n inverse: bool = False,\n ) -> None:\n \"\"\"\n Apply the specified unitary on the left of this UnitaryBuilder.\n\n .------. .-----.\n 0 -| |---| |-\n 1 -| gate |---| |-\n '------' . .\n . .\n . .\n n-1 ------------| |-\n '-----'\n\n Args:\n utry (UnitaryMatrix): The unitary to apply.\n\n location (CircuitLocationLike): The qudits to apply the unitary on.\n\n inverse (bool): If true, apply the inverse of the unitary.\n\n Notes:\n Applying the unitary on the left is equivalent to multiplying\n the unitary on the right of the tensor. This operation is\n performed using tensor contraction.\n \"\"\"\n\n if not isinstance(utry, UnitaryMatrix):\n raise TypeError('Expected UnitaryMatrix, got %s', type(utry))\n\n if not CircuitLocation.is_location(location, self.get_size()):\n raise TypeError('Invalid location.')\n\n location = CircuitLocation(location)\n\n if len(location) != utry.get_size():\n raise ValueError('Unitary and location size mismatch.')\n\n for utry_radix, bldr_radix_idx in zip(utry.get_radixes(), location):\n if utry_radix != self.get_radixes()[bldr_radix_idx]:\n raise ValueError('Unitary and location radix mismatch.')\n\n left_perm = list(range(self.get_size()))\n mid_perm = [\n x + self.get_size()\n for x in left_perm if x not in location\n ]\n right_perm = [x + self.get_size() for x in location]\n\n right_dim = int(\n np.prod([\n self.get_radixes()[x - self.get_size()]\n for x in right_perm\n ]),\n )\n\n utry = utry.get_dagger() if inverse else utry\n utry_np = utry.get_numpy()\n\n perm = left_perm + mid_perm + right_perm\n self.tensor = self.tensor.transpose(perm)\n self.tensor = self.tensor.reshape((-1, right_dim))\n self.tensor = self.tensor @ utry_np\n\n shape = list(self.get_radixes()) * 2\n shape = [shape[p] for p in perm]\n self.tensor = self.tensor.reshape(shape)\n inv_perm = list(np.argsort(perm))\n self.tensor = self.tensor.transpose(inv_perm)\n\n def calc_env_matrix(self, location: Sequence[int]) -> np.ndarray:\n \"\"\"\n Calculates the environmental matrix w.r.t. the specified location.\n\n Args:\n location (Sequence[int]): Calculate the env_matrix with respect\n to the qudit indices in location.\n\n Returns:\n (np.ndarray): The environmental matrix.\n \"\"\"\n\n left_perm = list(range(self.get_size()))\n left_perm = [x for x in left_perm if x not in location]\n left_perm = left_perm + [x + self.get_size() for x in left_perm]\n right_perm = list(location) + [x + self.get_size() for x in location]\n\n perm = left_perm + right_perm\n a = np.transpose(self.tensor, perm)\n a = np.reshape(\n a, (\n 2 ** (self.get_size() - len(location)),\n 2 ** (self.get_size() - len(location)),\n 2 ** len(location),\n 2 ** len(location),\n ),\n )\n return np.trace(a)\n","sub_path":"bqskit/qis/unitary/unitarybuilder.py","file_name":"unitarybuilder.py","file_ext":"py","file_size_in_byte":8194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"246049638","text":"from copy import deepcopy\nfrom ftw.testbrowser import browsing\nfrom opengever.propertysheets.exportimport import dottedname\nfrom opengever.propertysheets.testing import dummy_default_factory_42\nfrom opengever.propertysheets.testing import dummy_default_factory_true\nfrom opengever.testing import IntegrationTestCase\nimport json\nimport transaction\nimport unittest\n\n\nclass TestSchemaDefinitionPatch(IntegrationTestCase):\n\n maxDiff = None\n\n @browsing\n def test_patch_requires_sheet_id(self, browser):\n self.login(self.propertysheets_manager, browser)\n\n patch_data = {\n \"assignments\": [u\"IDocumentMetadata.document_type.report\"],\n }\n\n with browser.expect_http_error(400):\n browser.open(\n view=\"@propertysheets/\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n\n self.assertEqual({\n u'type': u'BadRequest',\n u'message': u'Must supply exactly one {sheet_id} path parameter.',\n }, browser.json)\n\n @browsing\n def test_patch_assignments(self, browser):\n self.login(self.propertysheets_manager, browser)\n\n # Create a sheet definition\n data = {\n \"fields\": [\n {\n \"name\": \"foo\",\n \"field_type\": \"bool\",\n \"title\": u\"Y/N\",\n \"available_as_docproperty\": False,\n \"description\": u\"yes or no\",\n \"required\": True,\n }\n ],\n \"assignments\": [u\"IDocumentMetadata.document_type.question\"],\n }\n browser.open(\n view=\"@propertysheets/question\",\n method=\"POST\",\n data=json.dumps(data),\n headers=self.api_headers,\n )\n\n patch_data = {\n \"assignments\": [u\"IDocumentMetadata.document_type.report\"],\n }\n\n # Patch it\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n\n expected = deepcopy(data)\n expected['id'] = 'question'\n expected.update(patch_data)\n\n self.assertEqual(expected, browser.json)\n\n @browsing\n def test_patch_fields(self, browser):\n self.login(self.propertysheets_manager, browser)\n\n # Create a sheet definition\n data = {\n \"fields\": [\n {\n \"name\": \"yn\",\n \"available_as_docproperty\": False,\n \"field_type\": u\"bool\",\n \"title\": u\"ja oder nein\"\n },\n ],\n \"assignments\": [\"IDocumentMetadata.document_type.question\"],\n }\n browser.open(\n view=\"@propertysheets/question\",\n method=\"POST\",\n data=json.dumps(data),\n headers=self.api_headers,\n )\n\n patch_data = {\n \"fields\": [\n {\n \"name\": \"colors\",\n \"field_type\": u\"multiple_choice\",\n \"title\": u\"Some colors\",\n \"values\": [u\"Rot\", u\"Gr\\xfcn\", u\"Blau\"],\n \"description\": \"Select one or more\",\n \"required\": False,\n \"available_as_docproperty\": True,\n },\n ],\n }\n\n # Patch it\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n\n expected = deepcopy(data)\n expected['id'] = 'question'\n expected.update(patch_data)\n\n self.assertEqual(expected, browser.json)\n\n @browsing\n def test_patching_id_is_not_allowed(self, browser):\n self.login(self.propertysheets_manager, browser)\n\n # Create a sheet definition\n data = {\n \"fields\": [\n {\n \"name\": \"yn\",\n \"field_type\": u\"bool\",\n \"title\": u\"ja oder nein\"\n },\n ],\n \"assignments\": [\"IDocumentMetadata.document_type.question\"],\n }\n\n browser.open(\n view=\"@propertysheets/question\",\n method=\"POST\",\n data=json.dumps(data),\n headers=self.api_headers,\n )\n\n patch_data = {\n \"id\": \"some_new_id\",\n }\n\n # Patch it\n with browser.expect_http_error(400):\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n self.assertDictContainsSubset(\n {\n u\"message\": u\"The 'id' of an existing sheet must not be changed.\",\n u\"type\": u\"BadRequest\",\n },\n browser.json,\n )\n\n @browsing\n def test_can_patch_definition_with_dynamic_defaults(self, browser):\n \"\"\"Test that even non-Managers can PATCH property sheet definitions\n that contain dynamic defaults, as long as the dynamic defaults\n already existed and don't get modified.\n \"\"\"\n self.login(self.manager, browser)\n # Create a sheet definition with a dynamic default (as manager)\n data = {\n \"fields\": [\n {\n \"name\": \"yn\",\n \"field_type\": u\"bool\",\n \"title\": u\"ja oder nein\",\n \"available_as_docproperty\": False,\n \"default_factory\": dottedname(dummy_default_factory_true),\n },\n ],\n \"assignments\": [\"IDocument.default\"],\n }\n\n browser.open(\n view=\"@propertysheets/question\",\n method=\"POST\",\n data=json.dumps(data),\n headers=self.api_headers,\n )\n\n # Now login as a regular PropertySheetsManager, and patch field title\n self.login(self.propertysheets_manager, browser)\n\n patch_data = {\n \"fields\": [\n {\n \"name\": \"yn\",\n \"field_type\": u\"bool\",\n \"title\": u\"My new title\",\n \"available_as_docproperty\": False,\n \"default_factory\": dottedname(dummy_default_factory_true),\n },\n ],\n \"assignments\": [\"IDocument.default\"],\n }\n\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n self.assertEquals({\n u'id': u'question',\n u'assignments': [u'IDocument.default'],\n u'fields': [{\n u'available_as_docproperty': False,\n u'default_factory': dottedname(dummy_default_factory_true),\n u'description': u'',\n u'field_type': u'bool',\n u'name': u'yn',\n u'required': False,\n u'title': u'My new title',\n }],\n }, browser.json)\n\n # Changing the dynamic default is not allowed though\n patch_data['fields'][0]['default_factory'] = dottedname(\n dummy_default_factory_42)\n\n with browser.expect_http_error(401):\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n self.assertEqual({\n u'message': u'Setting any dynamic defaults requires Manager role',\n u'type': u'Unauthorized',\n }, browser.json)\n\n @unittest.expectedFailure\n @browsing\n def test_existing_data_preserved_after_patch(self, browser):\n \"\"\"Test that existing propertysheet field data is preserved after\n \"renaming\" (deleting and re-adding) a propertysheet field from the\n definition, and manipulating content in between.\n \"\"\"\n self.login(self.propertysheets_manager, browser)\n\n # Create an initial sheet definition\n data = {\n \"fields\": [\n {\n \"name\": \"color\",\n \"field_type\": u\"choice\",\n \"title\": u\"A color\",\n \"values\": [u\"Rot\", u\"Gr\\xfcn\", u\"Blau\"],\n \"description\": \"Select one\",\n \"default\": u\"Rot\",\n \"required\": False,\n },\n ],\n \"assignments\": [\"IDocument.default\"],\n }\n\n browser.open(\n view=\"@propertysheets/question\",\n method=\"POST\",\n data=json.dumps(data),\n headers=self.api_headers,\n )\n transaction.commit()\n\n # Create a document\n with self.observe_children(self.dossier) as children:\n browser.open(\n self.dossier,\n method=\"POST\",\n data=json.dumps({\n '@type': 'opengever.document.document',\n 'title': 'My document',\n 'custom_properties': {\n 'IDocument.default': {\n 'color': u'Gr\\xfcn',\n }\n }\n }),\n headers=self.api_headers,\n )\n document = list(children['added'])[0]\n transaction.commit()\n\n # Verify custom property field data has been written\n browser.open(\n document.absolute_url(),\n headers=self.api_headers,\n )\n self.assertEqual({\n u'IDocument.default': {\n u'color': {\n u'title': u'Gr\\xfcn',\n u'token': u'Gr\\\\xfcn',\n },\n }}, browser.json['custom_properties'])\n\n # \"Rename\" the field in the definition\n patch_data = {\n \"fields\": [\n {\n \"name\": \"temporary_color_field_name\", # <---\n \"field_type\": u\"choice\",\n \"title\": u\"A color\",\n \"values\": [u\"Rot\", u\"Gr\\xfcn\", u\"Blau\"],\n \"description\": \"Select one\",\n \"default\": u\"Rot\",\n \"required\": False,\n },\n ],\n }\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n\n transaction.commit()\n\n # Old data is still there and getting serialized\n # (no token/title any more though, because schema definition is gone)\n browser.open(\n document.absolute_url(),\n headers=self.api_headers,\n )\n self.assertEqual({\n u'IDocument.default': {\n u'color': u'Gr\\xfcn'}\n }, browser.json['custom_properties'])\n\n # Patch the document and write something to the temporary field\n browser.open(\n document.absolute_url(),\n method=\"PATCH\",\n data=json.dumps({\n 'custom_properties': {\n 'IDocument.default': {\n 'temporary_color_field_name': u'Blau',\n }\n }\n },\n ),\n headers=self.api_headers,\n )\n transaction.commit()\n\n # Both the old and new field data should still be there\n browser.open(\n document.absolute_url(),\n headers=self.api_headers,\n )\n self.assertEqual({\n u'IDocument.default': {\n u'color': u'Gr\\xfcn',\n u'temporary_color_field_name': {\n u'title': u'Blau',\n u'token': u'Blau',\n },\n }}, browser.json['custom_properties'])\n\n transaction.commit()\n\n # \"Rename\" the field back to its old name\n patch_data = {\n \"fields\": [\n {\n \"name\": \"color\", # <---\n \"field_type\": u\"choice\",\n \"title\": u\"A color\",\n \"values\": [u\"Rot\", u\"Gr\\xfcn\", u\"Blau\"],\n \"description\": \"Select one\",\n \"default\": u\"Rot\",\n \"required\": False,\n },\n ],\n }\n browser.open(\n view=\"@propertysheets/question\",\n method=\"PATCH\",\n data=json.dumps(patch_data),\n headers=self.api_headers,\n )\n transaction.commit()\n\n # The original field data should now be serialized again, with the\n # temporary field that also being preserved\n browser.open(\n document.absolute_url(),\n headers=self.api_headers,\n )\n self.assertEqual({\n u'IDocument.default': {\n u'color': {\n u'title': u'Gr\\xfcn',\n u'token': u'Gr\\\\xfcn',\n },\n u'temporary_color_field_name': u'Blau',\n }}, browser.json['custom_properties'])\n","sub_path":"opengever/propertysheets/tests/test_schema_definition_patch.py","file_name":"test_schema_definition_patch.py","file_ext":"py","file_size_in_byte":13352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"48378880","text":"import math\n\ndef sumOfDigit(n):\n res = 0\n while n > 0:\n res += n % 10\n n //= 10\n return res\n\ndef hashFunc(n):\n return n^sumOfDigit(n)\n\nnCollision = 0\nmaxHashValue = -1\nminHashValueCollision = 10 ** 9\nmaxFrequency = -1\nmp = dict()\n\nn = int(input())\na = list(map(int, input().split()))\nfor num in a:\n hash_value = hashFunc(num)\n maxHashValue = max(maxHashValue, hash_value)\n if hash_value in mp:\n mp[hash_value] += 1\n else:\n mp[hash_value] = 1\n\nfor item in mp:\n nCollision += mp[item] - 1\n maxFrequency = max(maxFrequency, mp[item])\n\nif len(mp) == n:\n print(maxHashValue, end = \" \")\nelse:\n for item in mp:\n if mp[item] == maxFrequency:\n minHashValueCollision = min(item, minHashValueCollision)\n print(minHashValueCollision, end = \" \")\nprint(nCollision)","sub_path":"Hash Table/The Monk and Prateek.py","file_name":"The Monk and Prateek.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"482206498","text":"import pytest\nfrom flask import json\nfrom api import app\nimport os\nimport cloudpickle as cp\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom scipy.sparse import csr_matrix\nfrom sklearn.metrics import roc_auc_score\n\ncategorize_route = \"v1/categorize\"\nvalid_categories_set = {\"Lembrancinhas\", \"Bebê\", \"Decoração\", \"Outros\",\n \"Papel e Cia\", \"Bijuterias e Jóias\"}\n\nTEST_PRODUCTS_PATH = os.getenv(\"TEST_PRODUCTS_PATH\")\nTEST_PRODUCTS_CSV_PATH = os.path.join(\"../\", \"data\", \"test_products.csv\")\nwith open(TEST_PRODUCTS_PATH, \"r\") as json_file:\n test_json = json.load(json_file)\n\n\ndef categorize_request(input_data):\n return app.test_client().post(categorize_route,\n data=json.dumps(input_data),\n content_type=\"application/json\")\n\n\n@pytest.mark.parametrize(\"input_data\", [\n None,\n \"\",\n {},\n {\"products\": []},\n {\"products\": [{\"title\": \"\"}]},\n {\"products\": [{\"concatenated_tags\": \"\"}]},\n {\"products\": [{\"other1\": \"\", \"other2\": \"\"}]}\n ])\ndef test_request_with_invalid_data(input_data):\n response = categorize_request(input_data)\n\n assert response.status_code == 400\n assert response.data == b\"(Bad Request)\"\n\n\n@pytest.mark.parametrize(\"input_data\", [\n {\"products\": [{\"title\": None, \"concatenated_tags\": None}]},\n {\"products\": [{\"title\": \"\", \"concatenated_tags\": \"\"}]},\n {\"products\": [{\"title\": \"\", \"concatenated_tags\": \"\", \"other\": \"\"}]},\n {\"products\": [{\"title\": \"a\", \"concatenated_tags\": \"a\"},\n {\"title\": \"b\", \"concatenated_tags\": \"b\"}]},\n test_json])\ndef test_request_with_valid_data(input_data):\n response = categorize_request(input_data)\n\n assert response.status_code == 200\n assert len(response.json[\"categories\"]) == len(input_data['products'])\n assert set(response.json['categories']).issubset(valid_categories_set)\n\ndef load_model():\n with open(os.getenv(\"MODEL_PATH\"), \"rb\") as file:\n return cp.load(file)\n\ndef load_data():\n data = pd.read_csv(TEST_PRODUCTS_CSV_PATH)\n string_columns = data.select_dtypes(\"object\").columns.tolist()\n data.loc[:, string_columns] = data.loc[:, string_columns].fillna(\"\")\n return data\n\n\ndef test_check_columns(): \n data = load_data()\n expected = ['title', 'query', 'concatenated_tags']\n\n assert np.all(pd.Series(expected).isin(data.columns))\n\ndef test_load_pipeline_model():\n model = load_model()\n expected = Pipeline\n assert expected == model.__class__\n\ndef test_column_concatenation():\n data = load_data()\n model = load_model()\n\n expected = data[\"title\"] + \" \" + data[\"concatenated_tags\"]\n assert expected.equals(model[\"preprocessor\"][\"text_column_concatenation\"].transform(data))\n\ndef test_preprocessor_pipeline_output_class():\n data = load_data()\n model = load_model()\n\n expected = csr_matrix\n assert expected == model[\"preprocessor\"].transform(data).__class__\n\ndef test_pipeline_predict():\n data = load_data()\n model = load_model()\n labels = model.classes_\n\n y_true = data[\"category\"]\n y_proba = model.predict_proba(data)\n\n assert roc_auc_score(y_true, y_proba, multi_class=\"ovr\") > 0.97\n","sub_path":"server/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"539468152","text":"from django import forms\r\nfrom .models import Event, Attraction, Restaurant\r\n\r\nclass CityForm(forms.Form):\r\n city = forms.CharField(label=\"\", max_length=50, required=True,\r\n widget=forms.TextInput(attrs={'placeholder': 'City to explore...'}))\r\n\r\nclass ItineraryForm(forms.Form):\r\n EVENT_CHOICES = (\r\n (\"Neutral\", (\"Neutral\")),\r\n (\"Like\", (\"Like\")),\r\n (\"Dislike\", (\"Dislike\")),\r\n )\r\n\r\n def __init__(self, *args, **kwargs):\r\n events = kwargs.pop('events')\r\n times = kwargs.pop(\"times\")\r\n super(ItineraryForm, self).__init__(*args, **kwargs)\r\n '''\r\n for i in range(0, len(events)):\r\n event = events[i]\r\n if isinstance(event, Attraction):\r\n self.fields[event.name] = forms.ChoiceField(choices=self.EVENT_CHOICES, label=event.name, initial='',\r\n attrs={\"name\": event.name, \"description\": event.description,\r\n \"time\": times[i]})\r\n elif event is Restaurant:\r\n self.fields[event.name] = forms.ChoiceField(choices=self.EVENT_CHOICES, label=event.name, initial='',\r\n attrs={\"name\": event.name, \"price\": event.price,\r\n \"time\": times[i], \"rating\": event.rating})\r\n else:\r\n print(\"Här\")\r\n self.fields[event.name] = forms.ChoiceField(choices=self.EVENT_CHOICES, label=event.name, initial='',\r\n attrs={\"name\": event.name, \"description\": event.description,\r\n \"time\": times[i]})\r\n '''","sub_path":"hackust/ubertravel/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"297440656","text":"'''\n Problem Statement : Odd divisors \n Link : https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/odd-divisors-1-4939f17d/description/\n Score : 7 - memory limit exceeding for large inputs \n'''\ntest = int(input())\nfor t in range(test):\n N,M = list(map(int,input().split()))\n total = [1 for i in range(N)]\n for divisor in range(3,N+1,2):\n for index in range(divisor,N+1,divisor):\n if index%divisor==0:\n total[index-1] = divisor\n print(sum(total)%M)\n \n\n","sub_path":"Hackerearth/Odd_divisors.py","file_name":"Odd_divisors.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"343106224","text":"import os, sys, subprocess\n\ndef open_file(filename):\n if sys.platform == \"win32\":\n os.startfile(filename)\n else: #Sistema operativo MAC OSX\n subprocess.call(['open', filename])\n \nprint('1) Imagen\\n2) Sonido\\n3) Video')\nopc = int(input('¿Qué archivo quieres abrir?: '))\nif opc == 1:\n nom_arch = 'hugepizza.png'\nelif opc == 2:\n nom_arch = 'music.mp3'\nelif opc == 3:\n nom_arch = 'video.mp4'\nelse:\n nom_arch = ''\n \nopen_file(nom_arch)","sub_path":"semana-4/class-13/ejercicios-pruebas/archivos_multimedia.py","file_name":"archivos_multimedia.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"107220596","text":"from prettytable import PrettyTable # importar o módulo Pretty Table\r\nfrom time import sleep\r\n\r\noperadores_de_cada_sentenca = {} # Definir variável global para ser retomado pela tabela\r\n\r\n\r\ndef caca_sentencas(proposicao_bruta):\r\n snt = []\r\n for elemento in proposicao_bruta:\r\n if elemento not in ['^', 'v', '->', '<->', '~', 'xv', '(', ')', '[', ']', '{', '}']:\r\n if elemento not in snt:\r\n snt.append(elemento)\r\n\r\n return snt\r\n\r\n\r\ndef calculo_frequencia_op_log(quantidade_sentencas, coluna):\r\n '''\r\n Calcula quantas vezes o 1 e 0 se repetirão para cada sentença. Exemplo: para 8 linhas, o 'p'\r\n assumirá 4 vezes '1' e 4 vezes '0'.\r\n '''\r\n\r\n coluna = coluna + 1\r\n frequencia = 2 ** (quantidade_sentencas - coluna)\r\n return frequencia\r\n\r\n\r\ndef operadores_da_sentenca(coluna, quantidade_de_linhas, frequencia):\r\n '''\r\n Definirá os bools para a sentença específica. (ex: p receberá 1 1 0 0 ...)\r\n\r\n '''\r\n\r\n aux = 0\r\n operadores = []\r\n lista_operadores_da_sentenca = []\r\n while aux < 2 ** coluna:\r\n for i in range(frequencia):\r\n operadores.append(1)\r\n for i in range(frequencia):\r\n operadores.append(0)\r\n aux += 1\r\n\r\n return operadores\r\n\r\n\r\ndef definir_operadores_logicos(sentencas):\r\n '''\r\n Definirá os valores bools (0, 1) que cada sentença (p, q, r...) irá assumir para cada linha.\r\n Monta os resultados obtidos da função anterior em um dicionário e o retorna.\r\n\r\n '''\r\n\r\n global operadores_de_cada_sentenca\r\n operadores_de_cada_sentenca = {}\r\n quantidade_sentecas = len(sentencas)\r\n quantidade_de_linhas = 2 ** (quantidade_sentecas)\r\n coluna = 0\r\n for sentenca in sentencas: # (p, q, r ...)\r\n frequencia_da_sentenca = calculo_frequencia_op_log(quantidade_sentecas, coluna) # A sequencia de 1 ou 0 dependendo da sentenca\r\n operadores_de_cada_sentenca[sentenca] = operadores_da_sentenca(coluna, quantidade_de_linhas, frequencia_da_sentenca)\r\n coluna += 1\r\n\r\n return operadores_de_cada_sentenca\r\n\r\n\r\ndef montador_de_expressao(sentencas, numero_da_linha, proposicao_bruta):\r\n '''\r\n Substitui as sentenças (p, q, r...) por 0 ou 1.\r\n Itera pela lista proposicao_bruta e procura pelos elementos da lista sentencas. A medida que os acha, substitui-os\r\n pelos valores bool.\r\n\r\n '''\r\n proposicao_reformada = proposicao_bruta[:]\r\n dicionario_bools = definir_operadores_logicos(sentencas)\r\n for sentenca in dicionario_bools:\r\n index_sentenca = []\r\n valor_em_bool = dicionario_bools[sentenca][numero_da_linha]\r\n index_auxiliar = 0\r\n for element in proposicao_bruta:\r\n if element == sentenca:\r\n index_sentenca.append(index_auxiliar)\r\n index_auxiliar += 1\r\n for i in index_sentenca:\r\n proposicao_reformada.remove(sentenca)\r\n proposicao_reformada.insert(i, valor_em_bool)\r\n\r\n return proposicao_reformada\r\n\r\n\r\ndef prioridade(expressao):\r\n '''\r\n Determina o index das operações com prioridade, acha a expressão que será realizada e retorna o index por meio de uma\r\n lista binária.\r\n\r\n '''\r\n lista_prioridade = []\r\n aux = 0\r\n for elemento in expressao:\r\n if elemento == '(':\r\n first_index = aux\r\n elif elemento == ')':\r\n second_index = aux\r\n lista_prioridade.append([first_index, second_index])\r\n return lista_prioridade\r\n break\r\n elif elemento == '[':\r\n third_index = aux\r\n elif elemento == ']':\r\n fourth_index = aux\r\n lista_prioridade.append([third_index, fourth_index])\r\n return lista_prioridade\r\n break\r\n elif elemento == '{':\r\n fifth_index = aux\r\n elif elemento == '}':\r\n sixth_index = aux\r\n lista_prioridade.append([fifth_index, sixth_index])\r\n return lista_prioridade\r\n break\r\n aux += 1\r\n\r\n return lista_prioridade\r\n\r\n\r\ndef resolve_expressao_aux(expre):\r\n '''\r\n Função auxiliar para a resolução das expressões. Ela que realiza as operações lógicas e retorna o valor final da\r\n expressão.\r\n\r\n '''\r\n end = False\r\n while not end:\r\n if not '~' in expre and len(expre) != 1:\r\n for elemento in expre:\r\n if elemento == '^':\r\n index = expre.index('^')\r\n op1 = index - 1\r\n op2 = index + 1\r\n end = True\r\n return expre[op1] and expre[op2]\r\n elif elemento == 'v':\r\n index = expre.index('v')\r\n op1 = index - 1\r\n op2 = index + 1\r\n end = True\r\n return expre[op1] or expre[op2]\r\n elif elemento == '->':\r\n index = expre.index('->')\r\n op1 = expre[index - 1]\r\n op2 = expre[index + 1]\r\n end = True\r\n if op1 and op2:\r\n return True\r\n elif op1 and not op2:\r\n return False\r\n elif not op1 and op2:\r\n return True\r\n elif not op1 and not op2:\r\n return True\r\n elif elemento == '<->':\r\n index = expre.index('<->')\r\n op1 = expre[index - 1]\r\n op2 = expre[index + 1]\r\n end = True\r\n if op1 and op2:\r\n return 1\r\n elif op1 and not op2:\r\n return 0\r\n elif not op1 and op2:\r\n return 0\r\n elif not op1 and not op2:\r\n return 1\r\n elif elemento == 'xv':\r\n index = expre.index('xv')\r\n op1 = expre[index - 1]\r\n op2 = expre[index + 1]\r\n end = True\r\n if op1 and op2:\r\n return 0\r\n elif op1 and not op2:\r\n return 1\r\n elif not op1 and op2:\r\n return 1\r\n elif not op1 and not op2:\r\n return 0\r\n else:\r\n aux = 0 # index auxiliar, pois não conflitará caso exista dois objetos iguais na lista.\r\n for elemento in expre:\r\n if elemento == '~':\r\n index = aux # Armazena o valor do ultimo 'not' a aparecer na lista, caso hajam dois 'not' seguidos, assim pode fazê-los sem problemas\r\n aux += 1\r\n if len(expre) == 1:\r\n return expre[0]\r\n elif expre[index + 1] in [0, 1]:\r\n contrario = not expre[index + 1] # Define o bool contrário\r\n expre.pop(index + 1) # Remove o bool antigo\r\n expre.insert(index + 1, contrario) # Insere o bool contrário\r\n expre.pop(index) # Remove o 'not' operado\r\n\r\n\r\ndef resolve_expressao(sentencas, proposicao_bruta):\r\n '''\r\n Função que resolve as operações lógicas por meio de organizar as expressões com prioridade, pois, a partir dos index\r\n já determinados anteriormente (expressões com prioridade), a função faz um recorte a cada duas sentenças e as envia\r\n para a função anterior resolvê-la. Recebe o valor da operação feita, substitui o valor no lugar da expressão já re-\r\n solvida.\r\n\r\n '''\r\n resultado_de_cada_linha = {}\r\n expressoes = [] # O numero da linha corresponde ao index de cada elemento dessa lista, iniciando por 0.\r\n for i in range(2**len(sentencas)):\r\n expressoes.append(montador_de_expressao(sentencas, i, proposicao_bruta))\r\n\r\n aux = 0\r\n for expressao in expressoes:\r\n passo_a_passo = []\r\n end = False\r\n while not end:\r\n lista_prio = prioridade(expressao)\r\n if len(lista_prio) != 0:\r\n while len(lista_prio) != 0: # prio é uma lista com dois números referentes à prioridade (index).\r\n prio = lista_prio[0]\r\n inicio = prio[0]\r\n fim = prio [1] + 1\r\n expressao_prioritária = expressao[inicio:fim]\r\n resultado = resolve_expressao_aux(expressao_prioritária)\r\n for i in range(inicio, fim):\r\n expressao.pop(inicio) # Remove a expressao já resolvida\r\n expressao.insert(inicio, resultado)\r\n lista_prio.remove(lista_prio[0])\r\n\r\n else:\r\n resultado = resolve_expressao_aux(expressao)\r\n end = True\r\n resultado_de_cada_linha[aux] = resultado\r\n aux += 1\r\n\r\n return resultado_de_cada_linha\r\n\r\n\r\n# Agora é montar a tabela\r\npt = PrettyTable()\r\n\r\n\r\ndef lista_to_string(lista): # Transforma uma lista em string para ser escrita na tabela.\r\n string = ''\r\n for elemento in lista:\r\n string += str(elemento)\r\n\r\n return string\r\n\r\n\r\ndef montador_de_tabela(sentencas, proposicao_bruta, resultados):\r\n '''\r\n Monta a tabela associando os resultados finais das expressões com sua respectiva linha da tabela. Substitui os 0 e 1\r\n recebidos por True e False.\r\n\r\n '''\r\n sentencas1 = sentencas[:]\r\n sentencas.append(lista_to_string(proposicao_bruta))\r\n colunas = sentencas\r\n pt.field_names = colunas\r\n qtd_de_linhas = len(operadores_de_cada_sentenca['p'])\r\n for linha in range(qtd_de_linhas):\r\n line = []\r\n result = resultados[linha]\r\n for sentenca in sentencas1:\r\n line.append(operadores_de_cada_sentenca[sentenca][linha])\r\n if result == 0:\r\n result = 'False'\r\n elif result == 1:\r\n result = 'True'\r\n line.append(result)\r\n pt.add_row(line)\r\n print(pt)\r\n\r\n\r\ndef main(): # Chamada principal\r\n '''\r\n Translation:\r\n Truth Table!\r\n By Alex Victor Silva (Aveusalex)\r\n Use the following signals for each operator: and = ^ , or = v , not = ~ , conditional = -> , biconditional = <-> , exclusive or = xv .\r\n Type the logic expression, with each character split by spaces. Example: ( p ^ q ) -> ~ r .\r\n \r\n '''\r\n print(\"Tabela Verdade!\")\r\n print(\"Por Alex Victor Silva (Aveusalex)\")\r\n print()\r\n sleep(2)\r\n print('Use os seguintes sinais para cada operador: E = ^ , OU = v , NOT = ~ , CONDICIONAL = -> , BICONDICIONAL = <-> , OU EXCLUSIVO = xv .')\r\n sleep(2)\r\n proposicao_bruta = input('Digite a expressão lógica, com cada caracter separado por espaço. (Exemplo: ( p ^ q ) -> ~ r ): ').split() # Faz a expressão ser uma lista\r\n sentencas = caca_sentencas(proposicao_bruta)\r\n resultados = resolve_expressao(sentencas, proposicao_bruta) # Chama as funções secundárias\r\n montador_de_tabela(sentencas, proposicao_bruta, resultados)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"Taabela_V3.py","file_name":"Taabela_V3.py","file_ext":"py","file_size_in_byte":11164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"479189410","text":"# -*- coding: utf-8 -*-\n__author__ = \"Edson de Lima Cosme Junior\"\n__copyright__ = \"Copyright 2018, Edson Junior\"\n__credits__ = [\"equipe de desenvolvimento Cinte\"]\n__license__ = \"GPL\"\n__version__ = \"1.0\"\n__maintainer__ = \"Edson de Lima Cosme Junior\"\n__email__ = \"edson.junior@outboxsistemas.com\"\n__status__ = \"Production\"\n\nfrom openerp import models, fields, api\n\n\nclass CancelamentoAdesao(models.Model):\n \"\"\"\n Classe Cancelamento Adesao implementa as funcionalidades de cancelamentos de adesoes de contratos banda larga.\n\n Implementa regras e notificações necessárias no processo de cancelamento de adesoes dos clientes banda larga.\n \"\"\"\n _name = 'cancelamento_adesao'\n _inherit = ['mail.thread', 'ir.needaction_mixin']\n\n name = fields.Many2one(\n string='Motivo',\n comodel_name='motivo_cancelamento_contrato',\n required=True,\n track_visibility='onchange')\n\n adesao = fields.Many2one(\n string=\"Adesão\",\n comodel_name='adesao',\n required=True,\n help=\"Adesão a qual o cancelamento está vinculada\")\n\n descricao = fields.Text(\n string='Descrição',\n required=True,\n track_visibility='onchange'\n )\n\n retorno_validacao = fields.Text(\n string=''\n )\n\n @api.onchange('name')\n def on_change_name(self, cr, user, ids, name, adesao, context=None):\n \"\"\"\n Função onchange para o motivo do cancelamento no formulário.\n\n Retorna todas as verificações da adesão necessárias antes do cancelamento.\n\n :param cr: Cursor da base de dados.\n :param user: Usuário logado.\n :param ids: IDs das instâncias da classe.\n :param name: Motivo do cancelamento.\n :param contrato: Adesao a ser cancelada.\n :param context: Contexto da aplicação. Default None\n :return: Retorna um alerta no retorno da validacao\n \"\"\"\n\n if name:\n adesao = self.pool.get('adesao').browse(cr, user, adesao)\n retorno = \"\"\n if not adesao.ativo and adesao.situacao != '4':\n retorno += \"Adesão \" + str(adesao.name) + \" está inativa, favor verificar antes de cancelar o \" \\\n \"cadastro.\\n\"\n\n if retorno:\n return {\n 'value': {\n 'retorno_validacao': retorno,\n }\n }\n else:\n return {\n 'type': 'ir.actions.client',\n 'tag': 'action_warn',\n 'name': 'Warning',\n 'params': {\n 'title': 'Validação do cancelamento!',\n 'text': 'Leu o retorno'\n }\n }\n else:\n return {\n 'type': 'ir.actions.client',\n 'tag': 'action_warn',\n 'name': 'Warning',\n 'params': {\n 'title': 'Validação do cancelamento!',\n 'text': 'Não leu o motivo'\n }\n }\n\n @api.model\n def create(self, values):\n record = super(CancelamentoAdesao, self).create(values)\n\n if record.adesao.situacao != '4':\n if record.adesao.ativo:\n record.adesao.gerar_fatura_proporcional(\"Cancelamento de adesão\", record.adesao.plano_cidade.valor)\n\n record.adesao.write({'ativo': False, 'situacao': '4'})\n\n return record\n","sub_path":"suporte/models/cancelamento_adesao.py","file_name":"cancelamento_adesao.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"98501708","text":"import curses\nimport os\nimport random\nimport time\n\nimport data\n\n\nclass Screen:\n \"\"\"Представляет игровой экран, отображающий всю графику.\n\n Поля:\n stdscr -- стандартный экран игры\n scr_dices -- кости, находящийся на экране. Индекс означает позицию по\n DICES_POSITIONS. Значение \"0\" означает пустоту, т.е. при\n отображении \"нулевой\" кости, ее позиция очистится.\n colorist -- экземпляр соответсвующего класса\n SH, SW -- досл. screen hight и screen width\n ZONE_*NAME* -- координаты различных зон экрана:\n [0] и [1] - y и x левого верхнего угла;\n [2] и [3] - y и x правого нижнего угла;\n [4] и [5] - длина зоны по y и x\n DICES_POSITIONS -- Позиции костей (верхний левый угол) в зоне для костей\n\n \"\"\"\n\n SH, SW = 30, 70\n ZONE_MSG = (3, 7, 5, 61, 3, 55)\n ZONE_DICES = (11, 7, 19, 35, 9, 29)\n ZONE_SCORE = (11, 42, 19, 61, 9, 20)\n ZONE_INPUT = (25, 7, 25, 35, 1, 29)\n\n DICES_POSITIONS = {\n 0: (ZONE_DICES[0], ZONE_DICES[1] + 2),\n 1: (ZONE_DICES[0], ZONE_DICES[1] + 11),\n 2: (ZONE_DICES[0], ZONE_DICES[1] + 20),\n 3: (ZONE_DICES[0] + 4, ZONE_DICES[1] + 2),\n 4: (ZONE_DICES[0] + 4, ZONE_DICES[1] + 11),\n 5: (ZONE_DICES[0] + 4, ZONE_DICES[1] + 20)\n }\n\n colorist = None\n\n def __init__(self):\n self.stdscr = curses.initscr()\n self.scr_dices = [0] * 6\n self.msg_display_settings = data.MSG_DISPLAY_DEFAULT_SETTINGS.copy()\n\n stdscr = self.stdscr\n SH, SW = Screen.SH, Screen.SW\n\n os.system(\"mode con: cols={0} lines={1}\".format(SW, SH))\n stdscr.resize(SH, SW)\n curses.noecho()\n stdscr.keypad(True)\n curses.curs_set(0)\n\n def __del__(self):\n curses.beep()\n curses.echo()\n curses.nocbreak()\n curses.curs_set(1)\n curses.endwin()\n\n # d8b 888\n # Y8P 888\n # 888\n # 888 88888b. 88888b. 888 888 888888\n # 888 888 \"88b 888 \"88b 888 888 888\n # 888 888 888 888 888 888 888 888\n # 888 888 888 888 d88P Y88b 888 Y88b.\n # 888 888 888 88888P\" \"Y88888 \"Y888 88888888\n # 888\n # 888\n # 888\n def input_str(self):\n \"\"\"Возвращает введенную пользователем строку.\"\"\"\n stdscr = self.stdscr\n ZONE_INPUT = Screen.ZONE_INPUT\n inp = \"\"\n\n stdscr.move(ZONE_INPUT[0], ZONE_INPUT[1])\n curses.curs_set(1)\n curses.flushinp()\n\n # Пока не запонится поле для ввода\n while len(inp) < ZONE_INPUT[4] * ZONE_INPUT[5] - 1:\n key_id = stdscr.getch()\n key = chr(key_id)\n\n # Если нажата клавиша цифры или буквы\n if key.isalpha() or key_id in range(32, 65):\n stdscr.addstr(key)\n inp += key\n # Если курсор достиг края, он перемещается на след. строку\n cy, cx = stdscr.getyx()\n if cx == ZONE_INPUT[1] + ZONE_INPUT[5]:\n stdscr.move(cy + 1, ZONE_INPUT[1])\n\n # Если нажат Enter\n elif key_id in (10, 13):\n break\n\n # Если нажат Backspase (и есть что стереть)\n elif key_id == 8 and inp != \"\":\n cy, cx = stdscr.getyx()\n # Если курсор не находится в начале новой строки, то сотрется\n # символ, находящийся за курсором\n if cx != ZONE_INPUT[1]:\n dely = cy\n delx = cx - 1\n # Иначе сотрется символ, находящийся в конце предыдущей строки\n else:\n dely = cy - 1\n delx = ZONE_INPUT[1] + ZONE_INPUT[5] - 1\n stdscr.addch(dely, delx, \" \") # удаление = замена на пробел\n stdscr.move(dely, delx)\n inp = inp[:-1]\n\n # Если нажат Esc\n elif key_id == 27:\n self.clear_zone(ZONE_INPUT)\n stdscr.move(ZONE_INPUT[0], ZONE_INPUT[1])\n inp = \"\"\n\n curses.curs_set(0)\n self.clear_zone(ZONE_INPUT)\n return inp\n\n def input_delayinterrupt(self, delay):\n \"\"\"Создает задержку, прерываемую нажатием любой кнопки.\"\"\"\n stdscr = self.stdscr\n curses.flushinp()\n stdscr.timeout(round(delay * 1000)) # перевод в миллесекунды\n key = stdscr.getch()\n stdscr.timeout(-1)\n\n if key == -1:\n return False\n else:\n return True\n\n # 888 d8b 888\n # 888 Y8P 888\n # 888 888\n # .d88888 888 .d8888b 88888b. 888 8888b. 888 888\n # d88\" 888 888 88K 888 \"88b 888 \"88b 888 888\n # 888 888 888 \"Y8888b. 888 888 888 .d888888 888 888\n # Y88b 888 888 X88 888 d88P 888 888 888 Y88b 888\n # \"Y88888 888 88888P' 88888P\" 888 \"Y888888 \"Y88888 88888888\n # 888 888\n # 888 Y8b d88P\n # 888 \"Y88P\"\n #\n def display_msg(self, id, *insert, delay=None,\n wait=None, speedup=None, inner_idx=None):\n \"\"\"Выводит на экран сообщения из реестра.\"\"\"\n stdscr = self.stdscr\n ZONE_MSG = Screen.ZONE_MSG\n settings = self.msg_display_settings\n\n if delay is None:\n delay = settings[\"delay\"]\n if wait is None:\n wait = settings[\"wait\"]\n if speedup is None:\n speedup = settings[\"speedup\"]\n if inner_idx is not None:\n msg = data.MSG_REGISTRY[id][inner_idx]\n else:\n msg = data.MSG_REGISTRY[id]\n if delay < 0:\n can_skip = False\n else:\n can_skip = True\n\n ch_print_delay = data.TIMINGS[\"PRINT-CHR\"] / speedup\n\n def printing_with_animation(with_animation):\n y, x_start = ZONE_MSG[0], ZONE_MSG[1] + 1\n insert_idx = 0\n fill = 1 # заполненность текущей строки по x\n\n self.clear_zone(ZONE_MSG)\n stdscr.move(y, x_start)\n\n for word in msg.split():\n # Вставка слова из insert с учетов возможных знаков препинания\n if word.startswith(\"%s\"):\n word = str(insert[insert_idx]) + word[2:]\n insert_idx += 1\n # Пауза в печати. Не ставится, если печать без анимации\n elif word == \"%p\":\n if with_animation:\n time.sleep(data.TIMINGS[\"PRINT-PAU\"])\n continue\n\n # Переход на новую строку по заполненности предыдущей или\n # по спец. символу.\n if fill + len(word) + 1 >= ZONE_MSG[5] or word == \"%n\":\n y += 1\n fill = 1\n stdscr.move(y, x_start)\n if word == \"%n\":\n continue\n\n # Печать слова с анимацией или без нее\n if with_animation:\n result = self.anim_percharword(word, ch_print_delay,\n can_skip)\n if result == \"interrupted\":\n return result\n else:\n stdscr.addstr(word + \" \")\n fill += len(word) + 1 # увеличение заполненности строки\n return \"complete\"\n\n result = printing_with_animation(True)\n if result == \"interrupted\":\n printing_with_animation(False)\n\n # Если необходимо ждать, пока игрок прочитает сообщение, то после\n # небольшой задержки появляетя мигающий курсор, ожидающий нажатия.\n if wait and delay == 0:\n if self.input_delayinterrupt(1) is False:\n curs_y, curs_x = stdscr.getyx()\n self.anim_arrowflick(curs_y, curs_x)\n # Если задержка - положительное число, то ее можно прервать нажатием\n # клавиши. Если отрицательное - прервать ее нельзя.\n elif delay > 0:\n self.input_delayinterrupt(delay)\n else:\n time.sleep(abs(delay))\n\n def display_msg_seq(self, seq_id, delay=None, wait=None, speedup=None):\n \"\"\"Выводит на экран последовательность сообщений из реестра.\"\"\"\n seq_len = len(data.MSG_REGISTRY[seq_id])\n for i in range(seq_len):\n self.display_msg(seq_id, delay=delay, wait=wait,\n speedup=speedup, inner_idx=i)\n\n def display_dice(self, position, value, *, cp=0):\n \"\"\"Выводит на экран кость в указанную позицию.\"\"\"\n stdscr = self.stdscr\n y, x = Screen.DICES_POSITIONS[position]\n\n stdscr.attron(curses.color_pair(cp))\n for idx, line in enumerate(data.ASCII_DICES[value]):\n # Печать первой строки с подчеркиваниями посередине, \"крыша\" кости\n if idx == 0 and value != 0:\n stdscr.addstr(y, x + 1, line[:-2],\n curses.color_pair(cp) + curses.A_UNDERLINE)\n # Печать последней строки с подчеркиваниями посередине, \"дно\" кости\n elif idx == 3 and value != 0:\n stdscr.addstr(y + idx, x, line,\n curses.color_pair(cp) + curses.A_UNDERLINE)\n stdscr.addch(y + 3, x, \"│\")\n stdscr.addch(y + 3, x + 6, \"│\")\n else:\n stdscr.addstr(y + idx, x, line)\n stdscr.attroff(curses.color_pair(cp))\n\n def display_dices(self, dices):\n \"\"\"Выводит кости на экран.\"\"\"\n self.scr_dices = [0] * 6\n scr_dices = self.scr_dices\n\n # Запись переданных костей в scr_dices со случайными позициями\n positions = [i for i in range(6)]\n random.shuffle(positions)\n for i, value in enumerate(dices):\n scr_dices[positions[i]] = value\n\n for position, value in enumerate(scr_dices):\n self.display_dice(position, value)\n self.stdscr.refresh()\n\n def display_score(self, player, score_type):\n \"\"\"Выводит/убирает с экрана очки игрока.\"\"\"\n stdscr = self.stdscr\n ZONE_SCORE = Screen.ZONE_SCORE\n\n if score_type == \"total\":\n score = player.score_total\n y = ZONE_SCORE[0] + 3\n elif score_type == \"turn\":\n score = player.score_turn\n y = ZONE_SCORE[0] + 5\n elif score_type == \"pick\":\n score = player.score_pick\n y = ZONE_SCORE[0] + 6\n\n if player.type == \"Human\":\n x = ZONE_SCORE[1] + 5\n else:\n x = ZONE_SCORE[1] + 14\n\n if score != 0:\n if score_type == \"pick\":\n cp = Screen.colorist.blue\n stdscr.addstr(y, x, \"+{}\".format(score), curses.color_pair(cp))\n else:\n stdscr.addstr(y, x, str(score), curses.A_UNDERLINE)\n else: # Отчищение строки, если очков нет\n if score_type == \"pick\":\n stdscr.addstr(y, x, \"+\" + \" \" * 5)\n else:\n stdscr.addstr(y, x, \" \", curses.A_UNDERLINE)\n stdscr.refresh()\n\n # d8b\n # Y8P\n #\n # 8888b. 88888b. 888 88888b.d88b.\n # \"88b 888 \"88b 888 888 \"888 \"88b\n # .d888888 888 888 888 888 888 888\n # 888 888 888 888 888 888 888 888\n # \"Y888888 888 888 888 888 888 888 88888888\n #\n def anim_playerhl(self, game_mode):\n \"\"\"Проигрывает анимацию бегунка, выделяющего имена игроков.\"\"\"\n stdscr = self.stdscr\n ZONE_SCORE = Screen.ZONE_SCORE\n white_cp = Screen.colorist.white\n y = ZONE_SCORE[0] + 1\n\n # Если текущий игрок - человек, то выделение перемещается справa\n # налево (с робота на человека). В обратном случае, наоборот.\n if game_mode.player.type == \"Human\":\n name_h = game_mode.player.name\n name_r = game_mode.second_player.name\n for i in range(9 + len(name_r)):\n # Установка x_forward для выделения, x_backward для его снятия\n x_f = ZONE_SCORE[1] + 14 - i\n x_b = ZONE_SCORE[1] + 14 + len(name_r) - i\n\n # Ограничение, чтобы выделение не заходило за имя человека\n if x_f >= ZONE_SCORE[1] + 5:\n stdscr.chgat(y, x_f, 1, curses.color_pair(5))\n # Ограничение, чтобы выделение не снималось с имени человека\n if x_b >= ZONE_SCORE[1] + 5 + len(name_h):\n stdscr.chgat(y, x_b, 1, curses.color_pair(white_cp))\n\n stdscr.refresh()\n time.sleep(0.03)\n else:\n name_h = game_mode.second_player.name\n name_r = game_mode.player.name\n for i in range(9 + len(name_r)):\n x_f = ZONE_SCORE[1] + 5 + len(name_h) + i\n x_b = ZONE_SCORE[1] + 5 + i\n\n if x_f < ZONE_SCORE[1] + 14 + len(name_r):\n stdscr.chgat(y, x_f, 1, curses.color_pair(5))\n if x_b < ZONE_SCORE[1] + 14:\n stdscr.chgat(y, x_b, 1, curses.color_pair(white_cp))\n\n stdscr.refresh()\n time.sleep(0.03)\n\n def anim_diceroll(self, num_of_dices):\n \"\"\"Проигрывает анимацию броска костей.\"\"\"\n rand_dices = []\n for k in range(10):\n rand_dices = [random.randint(1, 6) for i in range(num_of_dices)]\n self.display_dices(rand_dices)\n time.sleep(0.1)\n\n def anim_arrowflick(self, y, x):\n \"\"\"Проигрывает анимащию мигающей стрелки.\"\"\"\n stdscr = self.stdscr\n curr_symb, next_symb = \"▼\", \" \"\n interrupt = False\n\n while not interrupt:\n stdscr.addstr(y, x, curr_symb)\n curr_symb, next_symb = next_symb, curr_symb\n interrupt = self.input_delayinterrupt(0.8)\n\n stdscr.addstr(y, x, \" \")\n\n def anim_percharword(self, word, ch_print_delay, can_skip):\n \"\"\"Посимвольно выводит слово на экран.\"\"\"\n stdscr = self.stdscr\n curses.flushinp()\n stdscr.timeout(0)\n for char in word + \" \":\n stdscr.addch(char)\n stdscr.refresh()\n # Если игрок нажал кнопку и можно пропустить анимацию\n if stdscr.getch() != -1 and can_skip:\n stdscr.timeout(-1)\n return \"interrupted\"\n time.sleep(ch_print_delay)\n stdscr.timeout(-1)\n return \"complete\"\n\n def anim_ending(self):\n \"\"\"Сдвигает экран вверх.\"\"\"\n stdscr = self.stdscr\n stdscr.move(0, 0)\n for i in range(Screen.SH - 1):\n stdscr.deleteln()\n stdscr.refresh()\n time.sleep(0.04)\n\n # .d888 .d888 888\n # d88P\" d88P\" 888\n # 888 888 888\n # .d88b. 888888 888888 .d88b. .d8888b 888888\n # d8P Y8b 888 888 d8P Y8b d88P\" 888\n # 88888888 888 888 88888888 888 888\n # Y8b. 888 888 Y8b. Y88b. Y88b.\n # \"Y8888 888 888 \"Y8888 \"Y8888P \"Y888 88888888\n #\n def effect_hldices(self, dices=[], *, cp=None):\n \"\"\"Выделяет кости.\"\"\"\n scr_dices = self.scr_dices[:]\n if not cp:\n cp = Screen.colorist.blue\n\n if dices != []:\n for value in dices:\n position = scr_dices.index(value)\n self.display_dice(position, value, cp=cp)\n scr_dices[position] = 0\n else: # Пустой список dices означает, что нужно снять выделение.\n for position, value in enumerate(scr_dices):\n self.display_dice(position, value)\n self.stdscr.refresh()\n\n def effect_hlplayers(self, game_mode):\n \"\"\"Выделяет имя текущего игрока, снимая выделение с предыдущего.\"\"\"\n stdscr = self.stdscr\n ZONE_SCORE = Screen.ZONE_SCORE\n p1, p2 = game_mode.player, game_mode.second_player\n\n if p1.type == \"Human\":\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 5,\n p1.name, curses.color_pair(5))\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 14,\n p2.name, curses.color_pair(0))\n elif p1.type == \"Robot\":\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 14,\n p1.name, curses.color_pair(5))\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 5,\n p2.name, curses.color_pair(0))\n stdscr.refresh()\n\n # 888 888\n # 888 888\n # 888 888\n # 8888b. .d88888 .d88888\n # \"88b d88\" 888 d88\" 888\n # .d888888 888 888 888 888\n # 888 888 Y88b 888 Y88b 888\n # \"Y888888 \"Y88888 \"Y88888 88888888\n #\n def add_zone(self, zone, headline):\n \"\"\"Добавляет на экран игровую зону, созданную с заданными цветами.\"\"\"\n stdscr = self.stdscr\n colorist = Screen.colorist\n uy, lx = zone[0] - 1, zone[1] - 1\n ly, rx = zone[2] + 1, zone[3] + 1\n ltshadow = curses.color_pair(colorist.bkgd_ltshadow)\n dkshadow = curses.color_pair(colorist.bkgd_dkshadow)\n ltborder = curses.color_pair(colorist.bkgd_ltborder)\n dkborder = curses.color_pair(0)\n\n stdscr.addstr(uy, lx + 1, \"─\" * zone[5], ltborder)\n stdscr.addstr(ly, lx + 1, \"─\" * zone[5], dkborder)\n for line in range(1, zone[4] + 1):\n stdscr.addstr(uy + line, lx, \"│\", ltborder)\n stdscr.addstr(uy + line, rx, \"│\", dkborder)\n for line in range(1, zone[4] + 2):\n stdscr.addstr(uy + line, rx + 1, \"∙\", dkshadow)\n stdscr.addstr(uy + line + 1, rx + 2, \"∙\", ltshadow)\n stdscr.addstr(ly + 1, lx + 1, \"∙\" * (zone[5] + 2), dkshadow)\n stdscr.addstr(ly + 2, lx + 2, \"∙\" * (zone[5] + 2), ltshadow)\n\n stdscr.addstr(uy, lx, \"∙\", ltborder)\n stdscr.addstr(uy, rx, \"∙\", ltborder)\n stdscr.addstr(ly, lx, \"∙\", ltborder)\n stdscr.addstr(ly, rx, \"∙\", dkborder)\n self.clear_zone(zone)\n stdscr.addstr(uy, rx - len(headline) - 2, headline, ltborder)\n stdscr.refresh()\n\n def add_interface(self):\n \"\"\"Мгновенно добавляет интерфейс на экран.\"\"\"\n stdscr = self.stdscr\n colorist = Screen.colorist\n SH, SW = Screen.SH, Screen.SW\n ZONE_DICES = Screen.ZONE_DICES\n ZONE_INPUT = Screen.ZONE_INPUT\n ZONE_SCORE = Screen.ZONE_SCORE\n ZONE_MSG = Screen.ZONE_MSG\n\n # Заполнение точками игрового окна\n self.clear_zone((0, 0, SH - 2, SW - 2, SH, SW), \"∙\", cp=colorist.bkgd)\n\n for zone, head in ([ZONE_DICES, \"┤dices├\"], [ZONE_SCORE, \"┤score├\"],\n [ZONE_INPUT, \"┤input├\"], [ZONE_MSG, \"┤msg├\"]):\n self.add_zone(zone, head)\n\n self.add_zonescore()\n stdscr.addstr(ZONE_INPUT[0], ZONE_INPUT[1] - 1, \">\",\n curses.color_pair(colorist.bkgd_ltborder))\n stdscr.refresh()\n\n def add_players(self, game_mode):\n \"\"\"Добавляет на экран имена игроков.\"\"\"\n stdscr = self.stdscr\n ZONE_SCORE = Screen.ZONE_SCORE\n name1, name2 = game_mode.player.name, game_mode.second_player.name\n\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 5, name1)\n stdscr.addstr(ZONE_SCORE[0] + 1, ZONE_SCORE[1] + 14, name2)\n self.effect_hlplayers(game_mode)\n\n def add_high_bar(self, hbar):\n \"\"\"Добавляет на экран high_bar.\"\"\"\n ZONE_SCORE = Screen.ZONE_SCORE\n self.stdscr.addstr(ZONE_SCORE[0] + 7, ZONE_SCORE[1] + 9, str(hbar),\n curses.A_UNDERLINE)\n\n def add_zonescore(self):\n \"\"\"Отчищает и ��трисовывает зону для очков.\"\"\"\n stdscr = self.stdscr\n ZONE_SCORE = self.ZONE_SCORE\n zone_txt = [\" Tot \",\n \" Tur \",\n \" + + \",\n \" Win \"]\n self.clear_zone(ZONE_SCORE)\n for i, y in enumerate((3, 5, 6, 7)):\n stdscr.addstr(ZONE_SCORE[0] + y, ZONE_SCORE[1], zone_txt[i])\n if y == 3 or y == 5:\n stdscr.addstr(ZONE_SCORE[0] + y, ZONE_SCORE[1] + 5, \" \",\n curses.A_UNDERLINE)\n stdscr.addstr(ZONE_SCORE[0] + y, ZONE_SCORE[1] + 14, \" \",\n curses.A_UNDERLINE)\n elif y == 7:\n stdscr.addstr(ZONE_SCORE[0] + y, ZONE_SCORE[1] + 9, \" \",\n curses.A_UNDERLINE)\n stdscr.refresh()\n\n # 888\n # 888\n # 888\n # .d88b. 888 .d8888b .d88b.\n # d8P Y8b 888 88K d8P Y8b\n # 88888888 888 \"Y8888b. 88888888\n # Y8b. 888 X88 Y8b.\n # \"Y8888 888 88888P' \"Y8888\n #\n def clear_zone(self, zone, back=\" \", *, cp=0):\n \"\"\"Отчищает игровую зону.\"\"\"\n stdscr = self.stdscr\n for y in range(zone[0], zone[2] + 1):\n stdscr.addstr(y, zone[1], back * zone[5], curses.color_pair(cp))\n stdscr.refresh()\n\n def msg_display_attron(self, *, delay=None, wait=None, speedup=None):\n \"\"\"Включает атрибуты вывода сообщений.\"\"\"\n settings = self.msg_display_settings\n if delay is not None:\n settings[\"delay\"] = delay\n if wait is not None:\n settings[\"wait\"] = wait\n if speedup is not None:\n settings[\"speedup\"] = speedup\n\n def msg_display_attroff(self, *, delay=False, wait=False, speedup=False):\n \"\"\"Отключает атрибуты вывода сообщений.\"\"\"\n settings = self.msg_display_settings\n std_settings = data.MSG_DISPLAY_DEFAULT_SETTINGS\n if delay:\n settings[\"delay\"] = std_settings[\"delay\"]\n if wait:\n settings[\"wait\"] = std_settings[\"wait\"]\n if speedup:\n settings[\"speedup\"] = std_settings[\"speedup\"]\n\n def set_colorist(self, colorist):\n \"\"\"Делает, что сказано.\"\"\"\n Screen.colorist = colorist\n\n def beep(self):\n \"\"\"Делает *прлууммм*.\"\"\"\n curses.beep()\n","sub_path":"Classes/Graphics/c_screen.py","file_name":"c_screen.py","file_ext":"py","file_size_in_byte":24973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"399856248","text":"import os,cv2 \r\nimport numpy as np\r\nfrom sklearn import svm\r\nfrom sklearn import metrics\r\nfrom skimage.feature import hog\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import confusion_matrix\r\nimport time\r\n\r\n#TRAINING DATASET \r\npath = \"devnagriData/train\"\r\nimgsTrain=[]\r\nlabelsTrain=[]\r\n\r\n#Extracting the train images and labels and storing in list\r\nfor (dirname, dirs, files) in os.walk(path):\r\n for filename in files:\r\n if filename.endswith('.jpg'): \r\n img = cv2.imread(os.path.abspath(dirname+'/'+filename)) \r\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Colour image to grayscale image \r\n fd1, hog_image = hog(img_gray, orientations=9, pixels_per_cell=(8, 8), \r\n cells_per_block=(2, 2), visualize=True, multichannel=False)\r\n imgsTrain.append(fd1)\r\n labelsTrain.append(int(os.path.abspath(dirname)[-1]))\r\n else:\r\n pass\r\n \r\n \r\n#Extracting the test images and labels and storing in lsit\r\npath = \"devnagriData/test\"\r\nimgsTest=[]\r\nlabelsTest=[]\r\n\r\nfor (dirname, dirs, files) in os.walk(path):\r\n for filename in files:\r\n if filename.endswith('.jpg'):\r\n img = cv2.imread(os.path.abspath(dirname+'/'+filename))\r\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Colour image to grayscale image\r\n fd2, hog_image = hog(img_gray, orientations=9, pixels_per_cell=(8, 8), \r\n cells_per_block=(2, 2), visualize=True, multichannel=False)\r\n imgsTest.append(fd2)\r\n\r\n labelsTest.append(int(os.path.abspath(dirname)[-1]))\r\n else:\r\n pass \r\n \r\n#Converting the list to array \r\nimgsTestN=np.array(imgsTest)\r\nimgsTrainN=np.array(imgsTrain)\r\n\r\n\r\n##Using SVM to train the model\r\n#start = time.time()\r\n#model = svm.SVC(kernel=\"linear\")\r\n#model.fit(imgsTrainN,labelsTrain)\r\n#end = time.time()\r\n\r\n#Using Decision Tree Classifier to train the model\r\nstart = time.time()\r\nclf = DecisionTreeClassifier()\r\nclf = clf.fit(imgsTrainN,labelsTrain)\r\nend = time.time()\r\n\r\n#Testing the model with Test images\r\npredict = clf.predict(imgsTestN)\r\n\r\n#Calculating the time required to train the model\r\nprint(end - start,\" seconds for training the model.\")\r\n\r\n#Finding out the accuracy of the model \r\nprint(\"Model score is \",100*metrics.accuracy_score(labelsTest,predict),\"%\")\r\nprint(\" \")\r\n\r\nresults=confusion_matrix(labelsTest,predict)\r\nprint(results)\r\n\r\ny_actual=labelsTest\r\ny_hat=predict\r\n\r\ndef perf_measure(y_actual, y_hat):\r\n TP = 0\r\n FP = 0\r\n TN = 0\r\n FN = 0\r\n\r\n for i in range(len(y_hat)): \r\n if y_actual[i]==y_hat[i]==1:\r\n TP += 1\r\n if y_hat[i]==1 and y_actual[i]!=y_hat[i]:\r\n FP += 1\r\n if y_actual[i]==y_hat[i]==0:\r\n TN += 1\r\n if y_hat[i]==0 and y_actual[i]!=y_hat[i]:\r\n FN += 1\r\n\r\n return(TP, FP, TN, FN)\r\n \r\nprint(\" \") \r\nTP, FP, TN, FN = perf_measure(y_actual, y_hat)\r\nprint(\"True Positive=\", TP)\r\nprint(\"False Positive=\", FP)\r\nprint(\"True Negative=\", TN)\r\nprint(\"False Negative=\", FN)\r\n\r\nSensitivity = round((TP)/ (TP+FN),4)\r\nSpecificity = round((TN) / (FP + TN),4)\r\nPPV = round(TP/(TP+FP),4)\r\nACC = round((TP+TN)/(TP+FP+FN+TN),4)\r\n\r\nprint(\" \")\r\nprint(\"Sensitivity=\", Sensitivity)\r\nprint(\"Specificity=\", Specificity)\r\nprint(\"Precision=\", PPV)\r\nprint(\"Accuracy=\", ACC)\r\n \r\n\r\n\r\n \r\n","sub_path":"HOGDTC1_0.py","file_name":"HOGDTC1_0.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"41434749","text":"\n\ndef req_headers(url, host, is_gzip=False):\n gzip_param = \"Accept-Encoding: gzip, deflate, sdch\\r\\n\"\n if is_gzip == False:\n gzip_param = \"\"\n headers = \\\n\"GET %s HTTP/1.1\\r\\n\\\nAccept: application/text; version=1.0\\r\\n\\\nAccept-Language: zh-CN,zh\\r\\n\\\nHost: %s\\r\\n\\\n%s\\\nConnection: Keep-Alive\\r\\n\\r\\n\" % (url, host, gzip_param)\n return headers\n\ndef responseData(content):\n headers = \\\n\"\"\"HTTP/1.1 200 OK\\r\\n\\\nContext-Type: text/plain; charset=utf-8\\r\\n\\\nContent-Length: %d\\r\\n\\\nConnection: Keep-Alive\\r\\n\\r\\n\\\n%s\\r\\n\\r\\n\\\n\"\"\" % (len(content), content)\n return headers\n\n","sub_path":"http/http_protocol.py","file_name":"http_protocol.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"386246763","text":"# -*- coding: utf-8 -*-\n\n# (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"aihwkit example 25: analog CNN with hardware aware training.\n\nMnist dataset on a LeNet5 inspired network.\n\"\"\"\n# pylint: disable=invalid-name\n\nimport os\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Imports from PyTorch.\nfrom torch import nn, manual_seed, no_grad, save\nfrom torch import max as torch_max\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\n\n# Imports from aihwkit.\nfrom aihwkit.nn import AnalogConv2d, AnalogLinear, AnalogSequential\nfrom aihwkit.optim import AnalogSGD\nfrom aihwkit.simulator.configs import (\n InferenceRPUConfig,\n TorchInferenceRPUConfig,\n WeightRemapType,\n WeightModifierType,\n WeightClipType,\n NoiseManagementType,\n BoundManagementType,\n)\nfrom aihwkit.simulator.presets import StandardHWATrainingPreset\nfrom aihwkit.inference import PCMLikeNoiseModel\nfrom aihwkit.simulator.rpu_base import cuda\n\n# Check device\nDEVICE = \"cuda\" if cuda.is_compiled() else \"cpu\"\n\n# Path to store datasets\nPATH_DATASET = os.path.join(\"data\", \"DATASET\")\n\n# Path to store results\nRESULTS = os.path.join(os.getcwd(), \"results\", \"LENET5\")\nN_CLASSES = 10\n\n\ndef load_images(batch_size):\n \"\"\"Load images for train from torchvision datasets.\n\n Args:\n batch_size (int): dtto\n\n Returns:\n DataLoader, DataLoader: train data and validation data\n \"\"\"\n transform = transforms.Compose([transforms.ToTensor()])\n train_set = datasets.MNIST(PATH_DATASET, download=True, train=True, transform=transform)\n val_set = datasets.MNIST(PATH_DATASET, download=True, train=False, transform=transform)\n train_data = DataLoader(train_set, batch_size=batch_size, shuffle=True)\n validation_data = DataLoader(val_set, batch_size=batch_size, shuffle=False)\n\n return train_data, validation_data\n\n\ndef create_analog_network(rpu_config):\n \"\"\"Return a LeNet5 inspired analog model.\n\n Args:\n rpu_config (InferenceRPUConfig): hardware and HWA training settings to use\n\n Returns:\n nn.Module: lenet analog model\n \"\"\"\n channel = [16, 32, 512, 128]\n model = AnalogSequential(\n AnalogConv2d(\n in_channels=1, out_channels=channel[0], kernel_size=5, stride=1, rpu_config=rpu_config\n ),\n nn.Tanh(),\n nn.MaxPool2d(kernel_size=2),\n AnalogConv2d(\n in_channels=channel[0],\n out_channels=channel[1],\n kernel_size=5,\n stride=1,\n rpu_config=rpu_config,\n ),\n nn.Tanh(),\n nn.MaxPool2d(kernel_size=2),\n nn.Tanh(),\n nn.Flatten(),\n AnalogLinear(in_features=channel[2], out_features=channel[3], rpu_config=rpu_config),\n nn.Tanh(),\n AnalogLinear(in_features=channel[3], out_features=N_CLASSES, rpu_config=rpu_config),\n nn.LogSoftmax(dim=1),\n )\n\n return model\n\n\ndef create_sgd_optimizer(model, learning_rate):\n \"\"\"Create the analog-aware optimizer.\n\n Args:\n model (nn.Module): model to be trained\n learning_rate (float): global parameter to define learning rate\n\n Returns:\n Optimizer: created analog optimizer\n\n \"\"\"\n optimizer = AnalogSGD(model.parameters(), lr=learning_rate)\n optimizer.regroup_param_groups(model)\n\n return optimizer\n\n\ndef train_step(data, model, criterion, optimizer):\n \"\"\"Train network.\n\n Args:\n data (DataLoader): Validation set to perform the evaluation\n model (nn.Module): Trained model to be evaluated\n criterion (nn.CrossEntropyLoss): criterion to compute loss\n optimizer (Optimizer): analog model optimizer\n\n Returns:\n nn.Module, Optimizer, float: model, optimizer, and epoch loss\n \"\"\"\n total_loss = 0\n\n model.train()\n\n for images, labels in data:\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n optimizer.zero_grad()\n\n # Add training Tensor to the model (input).\n output = model(images)\n loss = criterion(output, labels)\n\n # Run training (backward propagation).\n loss.backward()\n\n # Optimize weights.\n optimizer.step()\n total_loss += loss.item() * images.size(0)\n epoch_loss = total_loss / len(data.dataset)\n\n return model, optimizer, epoch_loss\n\n\n@no_grad()\ndef test_evaluation(data, model, criterion):\n \"\"\"Test trained network\n\n Args:\n data (DataLoader): Validation set to perform the evaluation\n model (nn.Module): Trained model to be evaluated\n criterion (nn.CrossEntropyLoss): criterion to compute loss\n\n\n Returns:\n float, float, float: test epoch loss, test error, and test accuracy\n \"\"\"\n total_loss = 0\n predicted_ok = 0\n total_images = 0\n\n model.eval()\n\n for images, labels in data:\n images = images.to(DEVICE)\n labels = labels.to(DEVICE)\n\n pred = model(images)\n loss = criterion(pred, labels)\n total_loss += loss.item() * images.size(0)\n\n _, predicted = torch_max(pred.data, 1)\n total_images += labels.size(0)\n predicted_ok += (predicted == labels).sum().item()\n\n accuracy = predicted_ok / total_images * 100\n error = (1 - predicted_ok / total_images) * 100\n epoch_loss = total_loss / len(data.dataset)\n\n return epoch_loss, error, accuracy\n\n\ndef training_loop(model, criterion, optimizer, train_data, validation_data, epochs, print_every=1):\n \"\"\"Training loop.\n\n Args:\n model (nn.Module): Trained model to be evaluated\n criterion (nn.CrossEntropyLoss): criterion to compute loss\n optimizer (Optimizer): analog model optimizer\n train_data (DataLoader): Validation set to perform the evaluation\n validation_data (DataLoader): Validation set to perform the evaluation\n epochs (int): global parameter to define epochs number\n print_every (int): defines how many times to print training progress\n\n Returns:\n nn.Module, Optimizer, Tuple: model, optimizer,\n and a tuple of lists of train losses, validation losses, and test\n error\n \"\"\"\n train_losses = []\n valid_losses = []\n test_error = []\n\n # Train model\n for epoch in range(0, epochs):\n # Train_step\n model, optimizer, train_loss = train_step(train_data, model, criterion, optimizer)\n train_losses.append(train_loss)\n\n # Validate_step\n valid_loss, error, accuracy = test_evaluation(validation_data, model, criterion)\n valid_losses.append(valid_loss)\n test_error.append(error)\n\n if epoch % print_every == (print_every - 1):\n print(\n f\"{datetime.now().time().replace(microsecond=0)} --- \"\n f\"Epoch: {epoch}\\t\"\n f\"Train loss: {train_loss:.4f}\\t\"\n f\"Valid loss: {valid_loss:.4f}\\t\"\n f\"Test error: {error:.2f}%\\t\"\n f\"Accuracy: {accuracy:.2f}%\\t\"\n )\n\n # Save results and plot figures\n np.savetxt(os.path.join(RESULTS, \"Test_error.csv\"), test_error, delimiter=\",\")\n np.savetxt(os.path.join(RESULTS, \"Train_Losses.csv\"), train_losses, delimiter=\",\")\n np.savetxt(os.path.join(RESULTS, \"Valid_Losses.csv\"), valid_losses, delimiter=\",\")\n\n return model, optimizer, (train_losses, valid_losses, test_error)\n\n\ndef plot_results(train_losses, valid_losses, test_error, t_inference_times, inference_test_error):\n \"\"\"Plot results.\n\n Args:\n train_losses (List): training losses as calculated in the training_loop\n valid_losses (List): validation losses as calculated in the training_loop\n test_error (List): test error as calculated in the training_loop\n t_inference_times (List): inference times\n inference_test_error (List): Inference test error\n \"\"\"\n plt.ion()\n plt.figure(figsize=[14, 5])\n plt.subplot(1, 3, 1)\n h = plt.plot(train_losses, \"r-s\", valid_losses, \"b-o\")\n plt.title(\"LeNet5 - HWA training\")\n plt.legend(h[:2], [\"Training Losses\", \"Validation Losses\"])\n plt.xlabel(\"Epoch number\")\n plt.ylabel(\"Loss [A.U.]\")\n plt.grid(which=\"both\", linestyle=\"--\")\n\n plt.subplot(1, 3, 2)\n handle = plt.plot(test_error, \"r-s\")\n plt.title(\"Test w/o prog. noise and drift\")\n plt.legend(handle[:1], [\"Validation test error\"])\n plt.xlabel(\"Epoch number\")\n plt.ylabel(\"Test Error [%]\")\n plt.yscale(\"log\")\n plt.ylim((5e-1, 1e2))\n plt.grid(which=\"both\", linestyle=\"--\")\n\n plt.subplot(1, 3, 3)\n handle = plt.plot(t_inference_times, inference_test_error, \"r-s\")\n plt.title(\"Eval. w/ prog. noise and drift)\")\n plt.legend(handle[:1], [\"Validation test error\"])\n plt.xlabel(\"Time of inference [s]\")\n plt.ylabel(\"Test Error [%]\")\n plt.yscale(\"log\")\n plt.xscale(\"log\")\n plt.ylim((5e-1, 1e2))\n plt.grid(which=\"both\", linestyle=\"--\")\n\n plt.show()\n plt.tight_layout()\n\n\ndef training_phase(model, criterion, optimizer, train_data, validation_data):\n \"\"\"Training phase.\n\n Args:\n model (nn.Module): Trained model to be evaluated\n criterion (nn.CrossEntropyLoss): criterion to compute loss\n optimizer (Optimizer): analog model optimizer\n train_data (DataLoader): Validation set to perform the evaluation\n validation_data (DataLoader): Validation set to perform the evaluation\n\n Returns:\n Tuple: results from the training phase\n \"\"\"\n print(\"\\n ********************************************************* \\n\")\n print(f\"\\n{datetime.now().time().replace(microsecond=0)} --- \" f\"Started LeNet5 Training\")\n\n model, optimizer, res = training_loop(\n model, criterion, optimizer, train_data, validation_data, N_EPOCHS\n )\n\n print(f\"{datetime.now().time().replace(microsecond=0)} --- \" f\"Completed LeNet5 Training\")\n\n return res\n\n\n@no_grad()\ndef inference_phase(t_inference_times, model, criterion, validation_data):\n \"\"\"Inference phase.\n\n Args:\n t_inference_times (list): list of times to do inference\n model (nn.Module): Trained model to be evaluated\n criterion (nn.CrossEntropyLoss): criterion to compute loss\n validation_data (DataLoader): Validation set to perform the evaluation\n\n Returns:\n Tuple: results from the training phase\n \"\"\"\n # pylint: disable=too-many-locals\n\n _, error_pre, accuracy_pre = test_evaluation(validation_data, model, criterion)\n print(\n f\"{datetime.now().time().replace(microsecond=0)} --- \"\n f\"Error after training: {error_pre:.2f}%\\t\"\n f\"Accuracy after training: {accuracy_pre:.2f}%\\t\"\n )\n\n error_lst = []\n accuracy_lst = []\n\n # Simulation of inference pass at different times after training.\n for t_inference in t_inference_times:\n model.drift_analog_weights(t_inference)\n\n _, error_post, accuracy_post = test_evaluation(validation_data, model, criterion)\n\n print(\n f\"{datetime.now().time().replace(microsecond=0)} --- \"\n f\"Error after inference: {error_post:.2f}%\\t\"\n f\"Accuracy after inference: {accuracy_post:.2f}%\\t\"\n f\"Drift t={t_inference: .2e}\\t\"\n )\n\n error_lst.append(error_post)\n accuracy_lst.append(accuracy_post)\n\n return error_lst, accuracy_lst\n\n\n# Make sure the directory where to save the results exist.\n# Results include: Loss vs Epoch graph, Accuracy vs Epoch graph and vector data.\nos.makedirs(RESULTS, exist_ok=True)\nmanual_seed(1)\n\n# Training parameters\nN_EPOCHS = 1\nBATCH_SIZE = 50\nLEARNING_RATE = 0.1\n\n# Load datasets.\ntraining_data, valid_data = load_images(BATCH_SIZE)\n\n\n# Define the properties of the neural network in terms of noise simulated during\n# the inference/training pass\ndef populate_rpu_config(rpu_config: InferenceRPUConfig):\n \"\"\"\n Populate the rpu config fields.\n\n Args:\n rpu_config (Union[TorchInferenceRPUConfig, InferenceRPUConfig]): The config to populate.\n\n Returns:\n Union[TorchInferenceRPUConfig, InferenceRPUConfig]: The same rpu config that was passed.\n \"\"\"\n rpu_config.mapping.digital_bias = True\n rpu_config.mapping.out_scaling_columnwise = False\n rpu_config.mapping.learn_out_scaling = True\n rpu_config.mapping.weight_scaling_omega = 1.0\n rpu_config.mapping.weight_scaling_columnwise = True\n rpu_config.mapping.max_input_size = 512\n rpu_config.mapping.max_output_size = 512\n\n rpu_config.noise_model = PCMLikeNoiseModel(g_max=25.0)\n rpu_config.remap.type = WeightRemapType.LAYERWISE_SYMMETRIC\n rpu_config.clip.type = WeightClipType.LAYER_GAUSSIAN\n rpu_config.clip.sigma = 2.0\n rpu_config.clip.fixed_value = 1.0\n\n # train input clipping\n rpu_config.forward.is_perfect = False\n rpu_config.forward.noise_management = NoiseManagementType.NONE\n rpu_config.forward.bound_management = BoundManagementType.NONE\n rpu_config.forward.out_bound = 10.0\n rpu_config.forward.inp_bound = 1.0\n rpu_config.forward.out_noise = 0.04\n rpu_config.forward.inp_res = 2**8\n rpu_config.forward.out_res = 2**8\n\n rpu_config.mapping.max_input_size = 256\n rpu_config.mapping.max_output_size = 256\n\n rpu_config.modifier.type = WeightModifierType.ADD_NORMAL\n rpu_config.modifier.std_dev = 0.1\n rpu_config.modifier.per_batch_sample = True\n rpu_config.pre_post.input_range.enable = True\n rpu_config.pre_post.input_range.manage_output_clipping = False\n\n return rpu_config\n\n\ntorch_rpu_config = populate_rpu_config(TorchInferenceRPUConfig())\n\n\n# Train the model with the purely torch-based tile.\ntorch_analog_model = create_analog_network(torch_rpu_config)\ntorch_analog_model = torch_analog_model.to(DEVICE)\n\nopt = create_sgd_optimizer(torch_analog_model, LEARNING_RATE)\ncrit = nn.CrossEntropyLoss()\n\nresults = training_phase(torch_analog_model, crit, opt, training_data, valid_data)\nsave(torch_analog_model.state_dict(), os.path.join(RESULTS, \"lenet_torch_tile_model.th\"))\n\n# Use the reference HWA-training preset for loading the trained model\n# and use the standardized AIMC evaluation for inference and drift.\nstandard_rpu_config = populate_rpu_config(StandardHWATrainingPreset())\nnetwork = create_analog_network(standard_rpu_config)\nnetwork.load_state_dict(torch_analog_model.state_dict())\nnetwork.to(DEVICE)\n\n# Test model inference over time.\nt_inference_lst = [0.0, 1.0, 20.0, 1000.0, 1e5, 1e7]\ninference_error, _ = inference_phase(t_inference_lst, network, crit, valid_data)\nplot_results(*results, t_inference_lst, inference_error)\n","sub_path":"examples/25_torch_tile_lenet5_hardware_aware.py","file_name":"25_torch_tile_lenet5_hardware_aware.py","file_ext":"py","file_size_in_byte":14922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"617093194","text":"'''\nShin Tran\nPython 210\nLesson 3 Assignment\n'''\n\nmasterList = []\nnameList = []\n\n\n# Creates the masterList where it has 12 donations pre-populated\ndef initialize():\n\tglobal masterList\n\td1 = [\"James Smith\", 91561.25]\n\td2 = [\"Mary Johnson\", 5811.05]\n\td3 = [\"John Williams\", 41113.42]\n\td4 = [\"Patricia Brown\", 19184.81]\n\td5 = [\"Robert Jones\", 51227.53]\n\td6 = [\"Jennifer Miller\", 53514.94]\n\td7 = [\"Michael David\", 31051.46]\n\td8 = [\"Mary Johnson\", 71646.16]\n\td9 = [\"William Rodriguez\", 69244.21]\n\td10 = [\"Mary Johnson\", 12689.07]\n\td11 = [\"Michael David\", 57145.50]\n\td12 = [\"Patricia Brown\", 81679.15]\n\tmasterList = [d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,d11,d12]\n\n# Prompts the user to enter an option\ndef mainPrompt():\n\tresponse = input(\"Choose from one of 3 actions:\\n\\\n\t\t1) Send a Thank You\\n\\\n\t\t2) Create a Report\\n\\\n\t\t3) Quit\\n\\\n\t\tPlease type 1, 2, or 3: \")\n\treturn response\n\n# Takes in a user input as a parameter, enters a donation, prints a report,\n# prints list, exit, prompts again if the input is bad\n# If the user types exit it'll go back to the main prompt\ndef action(userInput):\n\ttempList = []\n\tcreateNameList()\n\tif userInput == 'list':\n\t\tfor i in range(0,len(nameList)):\n\t\t\tprint(nameList[i])\n\t\taction(mainPrompt())\n\telif userInput == '1':\n\t\tdonorName = input(\"Enter a full name: \")\n\t\tif (donorName != 'exit'):\n\t\t\ttempList.append(donorName)\n\t\t\tdonationAmt = input(\"Enter a donation amount: \")\n\t\t\tif (donationAmt != 'exit'):\n\t\t\t\ttempList.append(float(donationAmt))\n\t\t\t\tmasterList.append(tempList)\n\t\t\t\tprintEmail(tempList)\n\t\taction(mainPrompt())\n\telif userInput == '2':\n\t\tprintReport()\n\t\taction(mainPrompt())\n\telif userInput == '3':\n\t\tquit()\n\telse:\n\t\taction(mainPrompt())\n\n# Creates a list of names of distinct donors\ndef createNameList():\n\tglobal masterList\n\tglobal nameList\n\tfor i in range(0,len(masterList)):\n\t\tnameList.append(masterList[i][0])\n\tnameList = list(set(nameList))\n\n# Prints a thank you email to a donator\n# Donor name and amount is passed in as a parameter\ndef printEmail(currentDonation):\n\tprint(\"Dear {:s},\\n\\\n\t\tThank you for the generous donation of {:.2f}.\\n\\\n\t\tSincerely,\\n\\\n\t\tYour Local Charity\".format(*currentDonation))\n\n# Prints a report of all the previous donators\n# Report includes name, total donated, count of donations, average gift\n# Report is also formatted with a certain spacing\ndef printReport():\n\tglobal masterList\n\tglobal nameList\n\tdonationTotal = []\n\tfor x in range(0,len(nameList)):\n\t\tdonationSum = 0\n\t\tcounter = 0\n\t\tfor y in range(0, len(masterList)):\n\t\t\tif masterList[y][0] == nameList[x]:\n\t\t\t\tdonationSum += masterList[y][1]\n\t\t\t\tcounter += 1\n\t\tdonationTotal.append([nameList[x], round(donationSum,2), counter, round(donationSum/counter,2)])\n\tdonationTotal.sort(key=lambda l: l[1], reverse = True)\n\tprint(\"Donor Name | Total Given | Num Gifts | Average Gift\")\n\tprint(\"-----------------------------------------------------------------\")\n\tfor z in range(0, len(donationTotal)):\n\t\tprint('{:20} ${:13.2f}{:14} ${:13.2f}'.format(*donationTotal[z]))\n\n# Python program to use main for function call\nif __name__ == \"__main__\":\n\tinitialize()\n\ttheInput = mainPrompt()\n\taction(theInput)","sub_path":"students/ShinTran/lesson03/mailroom.py","file_name":"mailroom.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"471914157","text":"#!/usr/bin/env python3\n#\n# Since: January, 2019\n# Author: gvenzl\n# Name: unit_tests.py\n# Description: Unit tests file for csv2db\n#\n# Copyright 2019 Gerald Venzl\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 functions as f\nimport config as cfg\nimport unittest\nimport csv2db\n\n\nclass CSV2DBTestCase(unittest.TestCase):\n\n def setUp(self):\n # Set the default column separator for all tests\n cfg.column_separator = \",\"\n cfg.quote_char = '\"'\n cfg.data_loading_error = False\n\n def test_open_csv_file(self):\n print(\"test_open_csv_file\")\n with f.open_file(\"../resources/201811-citibike-tripdata.csv\") as file:\n self.assertIsNotNone(file.read())\n\n def test_open_zip_file(self):\n print(\"test_open_zip_file\")\n with f.open_file(\"../resources/201811-citibike-tripdata.csv.zip\") as file:\n self.assertIsNotNone(file.read())\n\n def test_open_gzip_file(self):\n print(\"test_open_gzip_file\")\n with f.open_file(\"../resources/201811-citibike-tripdata.csv.gz\") as file:\n self.assertIsNotNone(file.read())\n\n def test_read_header(self):\n print(\"test_read_header\")\n with f.open_file(\"../resources/201811-citibike-tripdata.csv.gz\") as file:\n reader = f.get_csv_reader(file)\n expected = [\"BIKEID\", \"BIRTH_YEAR\", \"END_STATION_ID\", \"END_STATION_LATITUDE\",\n \"END_STATION_LONGITUDE\", \"END_STATION_NAME\", \"GENDER\", \"STARTTIME\",\n \"START_STATION_ID\", \"START_STATION_LATITUDE\", \"START_STATION_LONGITUDE\",\n \"START_STATION_NAME\", \"STOPTIME\", \"TRIPDURATION\", \"USERTYPE\"]\n expected.sort()\n actual = f.read_header(reader)\n actual.sort()\n self.assertListEqual(expected, actual)\n\n def test_tab_separated_file(self):\n print(\"test_tab_separated_file\")\n cfg.column_separator = \"\\t\"\n with f.open_file(\"../resources/201812-citibike-tripdata.tsv\") as file:\n reader = f.get_csv_reader(file)\n content = [f.read_header(reader)]\n for line in reader:\n content.append(line)\n self.assertEqual(11, len(content))\n\n def test_pipe_separated_file(self):\n print(\"test_pipe_separated_file\")\n cfg.column_separator = \"|\"\n with f.open_file(\"../resources/201812-citibike-tripdata.psv\") as file:\n reader = f.get_csv_reader(file)\n content = [f.read_header(reader)]\n for line in reader:\n content.append(line)\n self.assertEqual(11, len(content))\n\n def test_loading(self):\n print(\"test_loading\")\n self.assertEqual(f.ExitCodes.SUCCESS.value,\n csv2db.run(\n [\"load\",\n \"-f\", \"../resources/201811-citibike-tripdata.csv\",\n \"-u\", \"test\",\n \"-p\", \"test\",\n \"-t\", \"STAGING\"]\n )\n )\n\n def test_exit_code_SUCCESS(self):\n print(\"test_exit_code_SUCCESS\")\n self.assertEqual(f.ExitCodes.SUCCESS.value,\n csv2db.run([\"gen\", \"-f\", \"../resources/201811-citibike-tripdata.csv.gz\", \"-t\", \"STAGING\"]))\n\n def test_exit_code_GENERIC_ERROR(self):\n print(\"test_exit_code_GENERIC_ERROR\")\n self.assertEqual(f.ExitCodes.GENERIC_ERROR.value,\n csv2db.run([\"gen\", \"-f\", \"../resources/bad/201811-citibike-tripdata-invalid.csv.zip\"]))\n\n def test_exit_code_ARGUMENT_ERROR(self):\n print(\"test_exit_code_ARGUMENT_ERROR\")\n # Test that command raises SystemExit exception\n with self.assertRaises(SystemExit) as cm:\n csv2db.run([\"load\", \"-f\", \"../resources/201811-citibike-tripdata.csv.gz\", \"-t\", \"STAGING\"])\n # Test that command threw SystemExit with status code 2\n self.assertEqual(cm.exception.code, 2)\n\n def test_exit_code_DATABASE_ERROR(self):\n print(\"test_exit_code_DATABASE_ERROR\")\n self.assertEqual(f.ExitCodes.DATABASE_ERROR.value,\n csv2db.run(\n [\"load\",\n \"-f\", \"../resources/201811-citibike-tripdata.csv\",\n \"-u\", \"INVALIDUSER\",\n \"-p\", \"test\",\n \"-t\", \"STAGING\"]\n )\n )\n\n def test_exit_code_DATA_LOADING_ERROR(self):\n print(\"test_exit_code_DATA_LOADING_ERROR\")\n self.assertEqual(f.ExitCodes.DATA_LOADING_ERROR.value,\n csv2db.run(\n [\"load\",\n \"-f\", \"../resources/bad/201811-citibike-tripdata-bad-data.csv\",\n \"-u\", \"test\",\n \"-p\", \"test\",\n \"-t\", \"DOES_NOT_EXIST\"]\n )\n )\n\n def test_empty_file(self):\n print(\"test_empty_file\")\n self.assertEqual(f.ExitCodes.SUCCESS.value,\n csv2db.run(\n [\"load\",\n \"-f\", \"../resources/bad/201811-citibike-tripdata-empty.csv\",\n \"-u\", \"test\",\n \"-p\", \"test\",\n \"-t\", \"STAGING\"]\n )\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/python/unit_tests.py","file_name":"unit_tests.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"19908824","text":"from django.db import models\n\nfrom django.contrib.auth.models import User\n\nfrom bmcore.models.account import Account\n\nfrom bmcore.models.inventory import Inventory\n\nfrom bmcore.models.customer import Customer\n\nfrom bmcore.models.branch import Branch\n\nfrom bmcore.models.doctor import Doctor\n\n\n# Voucher manager\nclass VoucherManager(models.Manager):\n\n def create(self, **kwargs):\n\n instance = self.model()\n\n instance.trans_date = kwargs.get('trans_date')\n\n instance.value_date = kwargs.get('value_date')\n\n instance.voucher_model = kwargs.get('voucher_model')\n\n instance.voucher_type = kwargs.get('voucher_type')\n\n instance.ref_no = kwargs.get('ref_no')\n\n instance.op_account = kwargs.get('op_account')\n\n instance.op_inventory = kwargs.get('op_inventory')\n\n instance.account1 = kwargs.get('account1')\n\n instance.account2 = kwargs.get('account2')\n\n instance.rounded = kwargs.get('rounded')\n\n instance.discount = kwargs.get('discount')\n\n instance.narration = kwargs.get('narration')\n\n instance.cashier = kwargs.get('cashier')\n\n instance.customer = kwargs.get('customer')\n\n instance.doctor = kwargs.get('doctor')\n\n instance.tax_exempt = kwargs.get('tax_exempt')\n\n instance.branch = kwargs.get('branch')\n\n instance.status = kwargs.get('status')\n\n instance.created_by = kwargs.get('created_by')\n\n instance.voucher_no = kwargs.get('voucher_no')\n\n instance.save()\n\n instance.id = instance.pk\n\n return instance\n\n @staticmethod\n def update(inst, branch, created_by, **kwargs):\n\n instance = inst\n\n instance.ref_no = kwargs.get('ref_no', None)\n\n instance.op_account = kwargs.get('op_account', None)\n\n instance.op_inventory = kwargs.get('op_inventory', None)\n\n instance.account1 = kwargs.get('account1', None)\n\n instance.account2 = kwargs.get('account2', None)\n\n instance.rounded = kwargs.get('rounded', None)\n\n instance.discount = kwargs.get('discount', None)\n\n instance.narration = kwargs.get('narration', None)\n\n instance.cashier = kwargs.get('cashier', None)\n\n instance.tax_exempt = kwargs.get('tax_exempt', False)\n\n instance.branch = branch\n\n instance.status = kwargs.get('status', True)\n\n instance.created_by = created_by\n\n instance.voucher_no = kwargs.get('voucher_no', None)\n\n instance.save()\n\n return instance\n\n\n# Voucher\nclass Voucher(models.Model):\n\n trans_date = models.DateField(blank=True, null=True)\n\n value_date = models.DateField(blank=True, null=True)\n\n account1 = models.ForeignKey(Account, related_name=\"voucher_account1\", blank=True, null=True)\n\n account2 = models.ForeignKey(Account, related_name=\"voucher_account2\", blank=True, null=True)\n\n rounded = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True)\n\n discount = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True)\n\n voucher_no = models.CharField(max_length=10, blank=True, null=True)\n\n voucher_type = models.CharField(max_length=30, blank=True, null=True)\n\n ref_no = models.CharField(max_length=10, blank=True, null=True)\n\n narration = models.CharField(max_length=100, blank=True, null=True)\n\n op_account = models.ForeignKey(Account, blank=True, null=True)\n\n op_inventory = models.ForeignKey(Inventory, blank=True, null=True)\n\n voucher_model = models.IntegerField(blank=True, null=True)\n\n tax_exempt = models.BooleanField(default=False)\n\n tran = models.CharField(max_length=50, blank=True, null=True)\n\n batch = models.CharField(max_length=50, blank=True, null=True)\n\n branch = models.ForeignKey(Branch, blank=True, null=True)\n\n cashier = models.ForeignKey(Account, related_name=\"voucher_cashier\", blank=True, null=True)\n\n customer = models.ForeignKey(Customer, related_name=\"voucher_customer\", blank=True, null=True)\n\n doctor = models.ForeignKey(Doctor, related_name=\"voucher_doctor\", blank=True, null=True)\n\n status = models.BooleanField(default=True)\n\n timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)\n\n updated = models.DateTimeField(auto_now=True, auto_now_add=False)\n\n created_by = models.ForeignKey(User, default=1)\n\n objects = VoucherManager()\n\n class Meta:\n db_table = 'tbl_voucher'\n ordering = [\"-timestamp\", \"-updated\"]\n\n def __unicode__(self):\n return str(self.voucher_no)\n\n def __str__(self):\n return str(self.voucher_no)\n","sub_path":"bmcore/models/voucher.py","file_name":"voucher.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"177455335","text":"from corehq.apps.case_search.models import CaseSearchConfig, disable_case_search, enable_case_search\nfrom django.test import TestCase\nfrom mock import call, patch\n\n\nclass TestCaseSearch(TestCase):\n domain = \"meereen\"\n\n @patch('corehq.apps.case_search.tasks.get_case_search_reindexer')\n def test_enable_case_search_reindex(self, fake_reindexer):\n \"\"\"\n When case search is enabled, reindex that domains cases\n \"\"\"\n enable_case_search(self.domain)\n self.assertEqual(fake_reindexer.call_args, call(self.domain))\n self.assertTrue(fake_reindexer().reindex.called)\n\n @patch('corehq.apps.case_search.tasks.delete_case_search_cases')\n def test_disable_case_search_reindex(self, fake_deleter):\n \"\"\"\n When case search is disabled, delete that domains cases\n \"\"\"\n with patch('corehq.apps.case_search.tasks.get_case_search_reindexer'):\n enable_case_search(self.domain)\n\n disable_case_search(self.domain)\n self.assertEqual(fake_deleter.call_args, call(self.domain))\n\n def test_fuzzy_search_parameters(self):\n config = CaseSearchConfig(domain=self.domain).config\n\n self.assertItemsEqual(config.get_fuzzy_properties_for_case_type('mermaids'), [])\n\n config.add_fuzzy_properties(case_type=\"pirates\", properties=[\"name\", \"age\"])\n config.add_fuzzy_properties(case_type=\"pirates\", properties=[\"smells_bad\"])\n config.add_fuzzy_properties(case_type=\"swashbucklers\", properties=[\"has_parrot\"])\n\n self.assertItemsEqual(config.get_fuzzy_properties_for_case_type('pirates'), ['name', 'age', 'smells_bad'])\n self.assertItemsEqual(config.get_fuzzy_properties_for_case_type('swashbucklers'), ['has_parrot'])\n\n config.add_fuzzy_property(case_type=\"swashbucklers\", property=\"has_sword\")\n self.assertItemsEqual(\n config.get_fuzzy_properties_for_case_type('swashbucklers'),\n ['has_parrot', 'has_sword']\n )\n\n config.remove_fuzzy_property(case_type=\"pirates\", property=\"smells_bad\")\n self.assertItemsEqual(config.get_fuzzy_properties_for_case_type('pirates'), ['name', 'age'])\n\n with self.assertRaises(AttributeError):\n config.remove_fuzzy_property(case_type=\"pirates\", property=\"smells_bad\")\n","sub_path":"corehq/apps/case_search/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"615931996","text":"import copy\nimport sys\nfrom typing import Set, Dict, List, Tuple, Optional\n\nsplit = sys.argv[3] if len(sys.argv) >= 4 else 'dlcs'\n\n\n# noinspection DuplicatedCode\ndef dp(clauses: List[Set[int]],\n resolved: Dict[int, bool],\n unprocessed: Set[int],\n call_split: bool = True,\n **split_vars) -> Tuple[bool, Dict[int, bool], List[Set[int]], Optional[int]]:\n # noinspection DuplicatedCode\n def resolve(_literal: int) -> bool:\n _variable: int = abs(_literal)\n _polarity: bool = _variable == _literal\n # Only write to resolved and unprocessed when necessary.\n if _variable not in resolved:\n resolved[_variable]: bool = _polarity\n unprocessed.add(_literal)\n # We encountered a contradiction.\n elif resolved[_variable] != _polarity:\n return False\n return True\n\n # Test for pure literals.\n unprocessed: Set[int] = set()\n\n # Copy the clauses, because otherwise the loop will break if we remove items from the iteration.\n for clause in [*clauses]:\n removed: bool = False\n # Remove all clauses that contain a resolved variable.\n for literal in unprocessed and not removed:\n # Remove the whole clause if it contains the resolved literal (therefore the clause resolves to True).\n if literal in clause:\n clauses.remove(clause)\n removed = True\n continue\n\n # Remove the opposite literal from the clause, because the instance will resolve to False.\n polar_literal: int = literal * -1\n if polar_literal in clause:\n clause.remove(polar_literal)\n clauses[clauses.index(clause)] = clause\n # Test for empty clauses.\n if len(clause) == 0:\n return False, resolved, clauses, abs(literal)\n\n if removed:\n continue\n\n clause_length: int = len(clause)\n\n # Test for unit clauses.\n if clause_length == 1:\n clauses.remove(clause)\n literal = [*clause][0]\n # Since there is only one literal left in this clause, we can resolve it to True (called unit propagation).\n if not resolve(literal):\n # We encountered a contradiction.\n return False, resolved, clauses, abs(literal)\n continue\n\n # There is still something to process, rerun with the current context.\n if len(unprocessed) != 0:\n return dp(clauses, resolved, unprocessed, call_split, **split_vars)\n\n # Test if there are still unresolved clauses, which means that we're not done yet with parsing.\n elif call_split and len(clauses) != 0:\n # Perform a Split operation.\n return split_cdcl(clauses, resolved)\n\n # Found a solution!\n return True, resolved, clauses, None\n\n\n# Conflict-Driven Clause Learning split.\ndef split_cdcl(clauses: List[Set[int]],\n resolved: Dict[int, bool]) -> Tuple[bool, Dict[int, bool], List[Set[int]]]:\n unresolved: Dict[int, Tuple[List[Set[int]], List[Set[int]]]] = {}\n\n for clause in clauses:\n for literal in clause:\n variable = abs(literal)\n if variable not in unresolved:\n unresolved[variable] = ([], [])\n unresolved[variable][variable == literal].append(clause - {literal})\n\n history: List[Tuple[int, Set[int]]] = []\n backtrack = {}\n for literal in [-1, 3, -2, 7]:\n variable = abs(literal)\n polarity = variable == literal\n\n success, _resolved, _clauses, conflict = dp(clauses, {**resolved, variable: polarity}, {literal}, False)\n new_literals: Set[int] = {*map(\n lambda _variable: _variable if _resolved[_variable] else _variable * -1,\n {*_resolved} - {*resolved}\n )}\n\n history.append((literal, new_literals))\n\n # for new_literal in new_literals:\n # new_variable = abs(new_literal)\n # new_polarity: bool = new_variable == new_literal\n # if new_literal not in backtrack:\n # backtrack[new_literal] = {}\n # for clause in unresolved[new_variable][new_polarity]:\n # variables = extract_clause_vars(clause)\n # if len(variables - set(_resolved)) == 0:\n # for historic_literals in history:\n # backtrack_variables = extract_clause_vars(historic_literals).intersection(variables)\n # if len(backtrack_variables) != 0:\n # backtrack[new_literal][history.index(historic_literals)] = backtrack_variables\n # continue\n\n return False, resolved, clauses, None\n\n\ndef extract_clause_vars(clause: Set[int]) -> Set[int]:\n # Get the variable name from all literals in the clause by removing any hyphens.\n return {*map(lambda literal: abs(literal), clause)}\n\n\ndef remove_literal(clause: Set[int], literal: int) -> Set[int]:\n if literal in clause:\n clause.remove(literal)\n return clause\n\n\nprint(dp([\n {1, 4},\n {1, -3, -8},\n {1, 8, 12},\n {2, 11},\n {-7, -3, 9},\n {-7, 8, -9},\n {7, 8, -10},\n {7, 10, -12},\n], {}, set()))\n","sub_path":"cdcl.py","file_name":"cdcl.py","file_ext":"py","file_size_in_byte":5209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"310057410","text":"'''\n\n Dynamic Programming\n\nConsider a game where a player can score 3 or 5 or 10 points in a move. Given a total score n, find number of distinct combinations to reach the given score.\n\nExample:\nInput\n3\n8\n20\n13\nOutput\n1\n4\n2\nExplanation\nFor 1st example when n = 8\n{ 3, 5 } and {5, 3} are the \ntwo possible permutations but \nthese represent the same \ncobmination. Hence output is 1.\n\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function count( ) which takes N as input parameter and returns the answer to the problem.\n\nConstraints:\n1 ≤ T ≤ 100\n1 ≤ n ≤ 1000\n\n'''\n\ndef count(n):\n #your code here\n dp=[0 for i in range(n+1)]\n dp[0]=1\n for i in [3,5,10]:\n \n for j in range(len(dp)):\n if j>=i:\n dp[j]=dp[j-i]+dp[j]\n \n return dp[-1]\n","sub_path":"Reach a given score.py","file_name":"Reach a given score.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"326981979","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport paramiko\nimport re\n\nfrom django.conf import settings\nfrom lck.django.common import nested_commit_on_success\n\nfrom ralph.util import network, Eth\nfrom ralph.util import plugin\nfrom ralph.discovery import guessmodel\nfrom ralph.discovery.hardware import normalize_wwn\nfrom ralph.discovery.models import (\n Device, DeviceType, DiskShareMount, DiskShare,\n ComponentType, ComponentModel, Storage,\n Processor, Memory, IPAddress, OperatingSystem\n)\n\n\nAIX_USER = settings.AIX_USER\nAIX_PASSWORD = settings.AIX_PASSWORD\nAIX_KEY = settings.AIX_KEY\n\nMODELS = {\n 'IBM,9131-52A': 'IBM P5 520',\n 'IBM,8203-E4A': 'IBM P6 520',\n 'IBM,8233-E8B': 'IBM Power 750 Express',\n}\n\nSAVE_PRIORITY = 4\n\n\nclass Error(Exception):\n pass\n\n\ndef _connect_ssh(ip):\n return network.connect_ssh(ip, AIX_USER, AIX_PASSWORD, key=AIX_KEY)\n\n\ndef _ssh_lines(ssh, command):\n stdin, stdout, stderr = ssh.exec_command(command)\n for line in stdout.readlines():\n yield line\n\n\n@nested_commit_on_success\ndef run_ssh_aix(ip):\n ssh = _connect_ssh(ip)\n try:\n ethernets = []\n for model_line in _ssh_lines(ssh, 'lsattr -El sys0 | grep ^modelname'):\n machine_model = model_line.split(None, 2)[1]\n break\n for mac_line in _ssh_lines(ssh, 'netstat -ia | grep link'):\n interface, mtu, net, mac, rest = mac_line.split(None, 4)\n if '.' not in mac:\n continue\n octets = mac.split('.')\n mac = ''.join('%02x' % int(o, 16) for o in octets).upper()\n ethernets.append(Eth(label=interface, mac=mac, speed=0))\n disks = {}\n os_storage_size = 0\n for disk_line in _ssh_lines(ssh, 'lsdev -c disk'):\n disk, rest = disk_line.split(None, 1)\n wwn = None\n model = None\n for line in _ssh_lines(ssh, 'lscfg -vl %s' % disk):\n if 'hdisk' in line:\n match = re.search(r'\\(([0-9]+) MB\\)', line)\n if match:\n os_storage_size += int(match.group(1))\n elif 'Serial Number...' in line:\n label, sn = line.split('.', 1)\n sn = sn.strip('. \\n')\n elif 'Machine Type and Model.' in line:\n label, model = line.split('.', 1)\n model = model.strip('. \\n')\n disks[disk] = (model, sn)\n os_version = ''\n for line in _ssh_lines(ssh, 'oslevel'):\n os_version = line.strip()\n break\n os_memory = 0\n for line in _ssh_lines(ssh, 'lsattr -El sys0 | grep ^realmem'):\n match = re.search(r'[0-9]+', line)\n if match:\n os_memory = int(int(match.group(0)) / 1024)\n break\n os_corescount = 0\n for line in _ssh_lines(ssh, 'lparstat -i|grep ^Active\\ Phys'):\n match = re.search(r'[0-9]+', line)\n if match:\n os_corescount += int(match.group(0))\n finally:\n ssh.close()\n dev = Device.create(\n ethernets=ethernets, model_type=DeviceType.rack_server,\n model_name='%s AIX' % MODELS.get(machine_model, machine_model))\n ipaddr = IPAddress.objects.get(address=ip)\n ipaddr.device = dev\n ipaddr.save()\n wwns = []\n sns = []\n stors = []\n for disk, (model_name, sn) in disks.iteritems():\n if not sn:\n continue\n if model_name == 'VV':\n wwns.append(sn)\n else:\n stors.append((disk, model_name, sn))\n sns.append(sn)\n for mount in dev.disksharemount_set.exclude(share__wwn__in=wwns):\n mount.delete()\n for stor in dev.storage_set.exclude(sn__in=sns):\n stor.delete()\n for wwn in wwns:\n try:\n share = DiskShare.objects.get(wwn=wwn)\n except DiskShare.DoesNotExist:\n continue\n wwn = normalize_wwn(sn[-4:] + sn[:-4])\n mount, created = DiskShareMount.concurrent_get_or_create(\n share=share, device=dev, defaults={'is_virtual':False})\n mount.volume = disk\n mount.save(priority=SAVE_PRIORITY)\n for disk, model_name, sn in stors:\n # FIXME: storage with no size\n model, c = ComponentModel.create(\n ComponentType.disk,\n family=model_name,\n priority=SAVE_PRIORITY,\n )\n stor, created = Storage.concurrent_get_or_create(\n device=dev,\n sn=sn,\n mount_point=None,\n )\n stor.model = model\n stor.label = disk\n stor.save(priority=SAVE_PRIORITY)\n # FIXME: memory with no size\n mem, created = Memory.concurrent_get_or_create(device=dev, index=0)\n mem.label = 'Memory'\n mem.model, c = ComponentModel.create(\n ComponentType.memory,\n family='pSeries',\n priority=SAVE_PRIORITY,\n )\n mem.save(priority=SAVE_PRIORITY)\n # FIXME: CPUs without info\n cpu, created = Processor.concurrent_get_or_create(device=dev, index=0)\n cpu.label = 'CPU'\n cpu.model, c = ComponentModel.create(\n ComponentType.processor,\n family='pSeries',\n name='pSeries CPU',\n priority=SAVE_PRIORITY,\n )\n cpu.save(priority=SAVE_PRIORITY)\n OperatingSystem.create(dev=dev,\n os_name='AIX',\n version=os_version,\n family='AIX',\n memory=os_memory or None,\n cores_count=os_corescount or None,\n storage=os_storage_size or None,\n priority=SAVE_PRIORITY\n )\n return machine_model\n\n\n@plugin.register(chain='discovery', requires=['ping'])\ndef ssh_aix(**kwargs):\n if 'nx-os' in kwargs.get('snmp_name', '').lower():\n return False, 'incompatible Nexus found.', kwargs\n ip = str(kwargs['ip'])\n if AIX_USER is None:\n return False, 'no auth.', kwargs\n kwargs['guessmodel'] = gvendor, gmodel = guessmodel.guessmodel(**kwargs)\n if gvendor != 'IBM':\n return False, 'no match: %s %s' % (gvendor, gmodel), kwargs\n snmp_name = kwargs.get('snmp_name', '')\n if snmp_name and not snmp_name.startswith('IBM PowerPC'):\n return False, 'no match.', kwargs\n if not network.check_tcp_port(ip, 22):\n return False, 'closed.', kwargs\n try:\n name = run_ssh_aix(ip)\n except (network.Error, Error) as e:\n return False, str(e), kwargs\n except paramiko.SSHException as e:\n return False, str(e), kwargs\n except Error as e:\n return False, str(e), kwargs\n return True, name, kwargs\n\n","sub_path":"src/ralph/discovery/plugins/ssh_aix.py","file_name":"ssh_aix.py","file_ext":"py","file_size_in_byte":6676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"96318066","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom cassiopeia import riotapi\nimport lilt.liltscore\n\n\ndef index(request):\n context = {}\n return render(request, \"lilt/index.html\", context)\n\n\ndef detail(request, summoner_name):\n summoner = riotapi.get_summoner_by_name(summoner_name)\n game = riotapi.get_current_game(summoner)\n if game is not None:\n blue_team = []\n red_team = []\n for participant in game.participants:\n if participant.side.name == \"blue\":\n blue_team.append((participant, lilt.liltscore.get_score(participant.summoner_name)))\n elif participant.side.name == \"red\":\n red_team.append((participant, lilt.liltscore.get_score(participant.summoner_name)))\n # Write html with 10 slots for the context(participant object, score)\n else:\n score = lilt.liltscore.get_score(summoner.name)\n return HttpResponse(\"

    The score for \" + summoner_name + \" was: \" + str(score) + \"

    \")\n","sub_path":"lilt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"361724499","text":"import sys\n# from PySide6.QtWidgets import QApplication, QMainWindow, QSpinBox\nfrom PySide6.QtWidgets import QApplication, QMainWindow, QDoubleSpinBox\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Hola Mundo\")\n\n numero = QDoubleSpinBox()\n numero.setRange(0, 20)\n numero.setSingleStep(0.5)\n numero.setPrefix(\"$ \")\n numero.setSuffix(\" %\")\n numero.setValue(8)\n\n print(numero.value())\n\n numero.valueChanged.connect(self.valor_cambiado)\n self.setCentralWidget(numero)\n\n def valor_cambiado(self, numero):\n print(\"Valor cambiado\", numero)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())","sub_path":"3-Formularios/numeros.py","file_name":"numeros.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"468528134","text":"#!/usr/local/bin/python3\n#coding: utf-8\n\n#python setup.py bdist_msi --add-to-path True \n#python3 setup.py bdist_msi --add-to-path True\n# Should also have a 'surgeo.py' file in the setup.py directory that contains:\n# from surgeo.executable import main\n# main\n\nfrom cx_Freeze import setup, Executable\n\nbuild_exe_options = {'include_msvcr': True}\n\nexe = Executable(\n script = 'surgeo.py',\n initScript = None,\n base = None,\n targetName = 'surgeo.exe',\n copyDependentFiles = True,\n appendScriptToExe = True,\n appendScriptToLibrary = True,\n shortcutName='surgeo',\n icon = None,\n compress = True)\n\nsetup(name='surgeo',\n version='0.6.8',\n description='Disparate impact testing and surname geocoding analysis',\n url='https://github.com/theonaun/surgeo',\n author='Theo Naunheim',\n author_email='theonaunheim@gmail.com',\n license='MIT',\n packages=['surgeo', 'surgeo.db', 'surgeo.model', 'surgeo.utilities'],\n options = {'build_exe': build_exe_options},\n executables=[exe],\n classifiers=['Development Status :: 4 - Beta',\n 'Intended Audience :: Financial and Insurance Industry',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 3',\n 'Topic :: Office/Business :: Financial']\n )\n","sub_path":"surgeo/scripts/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"562449562","text":"from unittest import TestCase\n\nfrom altimeter.core.graph.field.scalar_field import ScalarField\nfrom altimeter.core.graph.schema import Schema\n\n\nclass TestSchemna(TestCase):\n def test_parse(self):\n schema = Schema(ScalarField(\"Key1\"), ScalarField(\"Key2\"))\n data = {\"Key1\": \"Value1\", \"Key2\": \"Value2\"}\n links = schema.parse(data, {})\n expected_link_data = [\n {\"pred\": \"key1\", \"obj\": \"Value1\", \"type\": \"simple\"},\n {\"pred\": \"key2\", \"obj\": \"Value2\", \"type\": \"simple\"},\n ]\n link_data = [link.to_dict() for link in links]\n self.assertEqual(expected_link_data, link_data)\n","sub_path":"tests/unit/altimeter/core/graph/test_schema.py","file_name":"test_schema.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"586247656","text":"# -*- coding: utf-8 -*\nimport pandas as pd\nfrom xgboost.sklearn import XGBClassifier\nimport xgboost as xgb\nimport cPickle as pickle\n\n#read data\ndf = pd.read_csv(\"train_test_data/test.csv\")\nrowkey = list(df['rowkey'])\n\nfeas = df.drop(['rowkey'], axis=1).copy()\n\n#load model and predict\nf1 = file(\"model/xgb_model.pkl\")\nmodel = pickle.load(f1)\npreds = model.predict(feas)\n\ndic = {'rowkey':rowkey, 'is_risk':preds}\ncols = ['rowkey', 'is_risk']\nresult = pd.DataFrame(dic)\nresult = result.ix[:, cols]\n\n#save to disk\nresult.to_csv(\"result/xgb_res.csv\", index=False, header=False, encoding='utf8')","sub_path":"script/xgb_predict.py","file_name":"xgb_predict.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"48976869","text":"from zentral.conf import settings, probes as all_probes\nfrom zentral.core.exceptions import ImproperlyConfigured\n\n__all__ = ['machine_id_secret', 'santa_conf', 'probes', 'probes_lookup_dict']\n\n# MachineID: MachineIDSecret$Key$Val\n# MachineIDSecret to test if it is a valid request.\n# Key / Val to try to link with the machine.\n# If no machine found, not a problem.\n# MachineID example: TOTO$SERIAL$0123456789\n\n\ndef get_machine_id_secret(settings):\n try:\n return settings['apps']['zentral.contrib.santa']['machine_id_secret']\n except KeyError:\n raise ImproperlyConfigured(\"Missing attribute 'machine_id_secret' in santa app settings\")\n\nmachine_id_secret = get_machine_id_secret(settings)\n\n\ndef build_santa_conf(all_probes):\n \"\"\"\n Build the santa conf, the probe lookup dict and the list of santa probes.\n\n The santa conf is the source of the json document that is sent to the santa\n client when it connects to zentral. It is a list of all the rules found in\n all the configured probes.\n\n The lookup dict is used when we process a santa event to find the probes\n that, because of the set of santa rules they contain, are responsible for\n its processing. Once we have the probes, we can trigger all the configured\n actions.\n\n The list of santa probes is a list of (probe_name, probe_d) tupes.\n \"\"\"\n rules = []\n lookup_d = {}\n probes = []\n for probe_name, probe_d in all_probes.items():\n santa_l = probe_d.get('santa', None)\n if not santa_l:\n continue\n probes.append((probe_name, probe_d))\n rules.extend(santa_l)\n for santa_r in santa_l:\n lookup_d.setdefault(santa_r[\"sha256\"], []).append(probe_d.copy())\n probes.sort()\n return {'rules': rules}, lookup_d, probes\n\nsanta_conf, probes_lookup_dict, probes = build_santa_conf(all_probes)\n","sub_path":"zentral/contrib/santa/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"474076170","text":"# -*- coding:utf-8 -*-\n\nimport numpy as np\nfrom PIL import Image\n\ndef get_samps_and_lables_batch(samps_pool, batch_sz=(10,25)):\n \"\"\"\n :return: image samps batch and labels batch\n \"\"\"\n SAMPLE_SIZE = 127\n\n samps_batch = []\n labels_batch = []\n\n img_list = samps_pool.img_list_np\n\n POS_PER_FRAME = samps_pool.pos_per_frame\n NEG_PER_FRAME = samps_pool.neg_per_frame\n\n pos_samps_pool_info = samps_pool.pos_samps_info\n neg_samps_pool_info = samps_pool.neg_samps_info\n\n pos_batch_size = batch_sz[0]\n neg_batch_size = batch_sz[1]\n\n pos_pool_size = len(samps_pool.pos_samps_info)\n neg_pool_size = len(samps_pool.neg_samps_info)\n\n pos_index = np.random.choice(np.arange(pos_pool_size), pos_batch_size)\n neg_index = np.random.choice(np.arange(neg_pool_size), neg_batch_size)\n\n for i in range(pos_batch_size):\n #print(len(img_list))\n #print(pos_index[i])\n image_samples = just_crop_image(img_list[int((pos_index[i] + 1) / POS_PER_FRAME) - 1], pos_samps_pool_info[pos_index[i]])\n image_samples_resized = image_samps_resize(image_samples, SAMPLE_SIZE)\n samps_batch.append(image_samples_resized)\n labels_batch.append([0., 1.])\n\n for i in range(neg_batch_size):\n image_samples = just_crop_image(img_list[int((neg_index[i] + 1) / NEG_PER_FRAME) - 1], neg_samps_pool_info[neg_index[i]])\n image_samples_resized = image_samps_resize(image_samples, SAMPLE_SIZE)\n samps_batch.append(image_samples_resized)\n labels_batch.append([1., 0.])\n\n return samps_batch, labels_batch\n\n\ndef just_crop_image(img_np, bbox_tl):\n\n crop = img_np[int(bbox_tl[1]):int(bbox_tl[1]+bbox_tl[3]),int(bbox_tl[0]):int(bbox_tl[0]+bbox_tl[2]),:]\n return crop\n\ndef image_samps_resize(img_np, size=127):\n img_pil = Image.fromarray(np.uint8(img_np))\n img_pil_resized = img_pil.resize((size, size))\n img_np_resized = np.asarray(img_pil_resized)\n return img_np_resized\n\n","sub_path":"src/get_samps_and_labels_batch.py","file_name":"get_samps_and_labels_batch.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"388716053","text":"from opentrons import labware, instruments, modules, robot\nimport numpy as np\n\n\nfinal_assembly_dict={\"A1\": [\"A7\", \"B7\", \"C7\", \"D7\", \"E7\"], \"B1\": [\"A7\", \"F7\", \"G7\", \"H7\", \"A8\"], \"C1\": [\"A7\", \"B8\", \"C8\", \"D8\", \"E8\"]}\ntiprack_num=1\n\n\ndef final_assembly(final_assembly_dict, tiprack_num, tiprack_type=\"tiprack-10ul\"):\n \"\"\"Implements final assembly reactions using an opentrons OT-2.\n\n Args:\n final_assembly_dict (dict): Dictionary with keys and values corresponding to destination and associated linker-ligated part wells, respectively.\n tiprack_num (int): Number of tipracks required during run.\n\n \"\"\"\n\n # Constants\n CANDIDATE_TIPRACK_SLOTS = ['3', '6', '9', '2', '5', '8', '11']\n PIPETTE_MOUNT = 'right'\n MAG_PLATE_TYPE = '4ti-0960_FrameStar'\n MAG_PLATE_POSITION = '1'\n TUBE_RACK_TYPE = 'tube-rack_E1415-1500'\n TUBE_RACK_POSITION = '7'\n DESTINATION_PLATE_TYPE = 'aluminium-block_4ti-0960_FrameStar'\n TEMPDECK_SLOT = '4'\n TEMP = 20\n TOTAL_VOL = 15\n PART_VOL = 1.5\n MIX_SETTINGS = (1, 3)\n\n # Errors\n sample_number = len(final_assembly_dict.keys())\n if sample_number > 96:\n raise ValueError('Final assembly nummber cannot exceed 96.')\n\n # Tips and pipette\n slots = CANDIDATE_TIPRACK_SLOTS[:tiprack_num]\n tipracks = [labware.load(tiprack_type, slot)\n for slot in slots]\n pipette = instruments.P10_Single(mount=PIPETTE_MOUNT, tip_racks=tipracks)\n\n # Define Labware and set temperature\n magbead_plate = labware.load(MAG_PLATE_TYPE, MAG_PLATE_POSITION)\n tube_rack = labware.load(TUBE_RACK_TYPE, TUBE_RACK_POSITION)\n tempdeck = modules.load('tempdeck', TEMPDECK_SLOT)\n destination_plate = labware.load(\n DESTINATION_PLATE_TYPE, TEMPDECK_SLOT, share=True)\n tempdeck.set_temperature(TEMP)\n tempdeck.wait_for_temp()\n\n # Master mix transfers\n final_assembly_lens = []\n for values in final_assembly_dict.values():\n final_assembly_lens.append(len(values))\n unique_assemblies_lens = list(set(final_assembly_lens))\n master_mix_well_letters = ['A', 'B', 'C', 'D']\n for x in unique_assemblies_lens:\n master_mix_well = master_mix_well_letters[(x - 1) // 6] + str(x - 1)\n destination_inds = [i for i, lens in enumerate(\n final_assembly_lens) if lens == x]\n destination_wells = np.array(\n [key for key, value in list(final_assembly_dict.items())])\n destination_wells = list(destination_wells[destination_inds])\n pipette.pick_up_tip()\n pipette.transfer(TOTAL_VOL - x * PART_VOL, tube_rack.wells(master_mix_well),\n destination_plate.wells(destination_wells),\n new_tip='never')\n pipette.drop_tip()\n\n # Part transfers\n for key, values in list(final_assembly_dict.items()):\n pipette.transfer(PART_VOL, magbead_plate.wells(values),\n destination_plate.wells(key), mix_after=MIX_SETTINGS,\n new_tip='always')\n\n tempdeck.deactivate()\n\n\nfinal_assembly(final_assembly_dict=final_assembly_dict,\n tiprack_num=tiprack_num)\n\nfor c in robot.commands():\n print(c)\n","sub_path":"tests/outputs/3_assembly_ot2_APIv1.py","file_name":"3_assembly_ot2_APIv1.py","file_ext":"py","file_size_in_byte":3173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"280889626","text":"from pytest import fixture\nimport vcr\nfrom uwaterloodriver import UW_Driver\n\n\"\"\"Below are a list of key fixtures to test responses with, they are NOT exhaustive.\"\"\"\n@fixture\ndef courses_keys():\n # Responsible for only returning the test data\n return ['course_id', 'subject', 'catalog_number', 'title']\n\n@fixture\ndef subject_keys():\n return ['units', 'description', 'academic_level']\n\n@fixture\ndef course_id_keys():\n return ['instructions', 'prerequisites', 'antirequisites', 'crosslistings',\n 'terms_offered', 'notes']\n\n@fixture\ndef schedule_keys():\n return ['title', 'class_number', 'section', 'campus', 'associated_class']\n\n@fixture\ndef prereq_keys():\n return ['subject', 'catalog_number', 'title', 'prerequisites', 'prerequisites_parsed']\n\n@fixture\ndef examschedule_keys():\n return ['course', 'sections']\n\n@vcr.use_cassette('vcr_cassettes/courses/courses.yml', filter_query_parameters=['key'])\ndef test_courses(courses_keys):\n \"\"\"Tests an API call to /courses/ endpoint.\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses()\n\n assert isinstance(response, list)\n assert isinstance(response[0], dict)\n assert set(courses_keys).issubset(response[0].keys()), \"All courses keys should be present.\"\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_subjects.yml', filter_query_parameters=['key'])\ndef test_courses_subjects(courses_keys, subject_keys):\n \"\"\"Tests an API call to /courses/{subject} endpoint.\n subject=MATH\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses(subject=\"MATH\")\n\n assert isinstance(response, list)\n assert isinstance(response[0], dict)\n assert set(courses_keys).issubset(response[0].keys()), \"All courses keys should be present.\"\n assert set(subject_keys).issubset(response[0].keys()), \"All subjects keys should be present.\"\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_course_id.yml', filter_query_parameters=['key'])\ndef test_courses(courses_keys, subject_keys, course_id_keys):\n \"\"\"Tests an API call to /courses/{course_id} endpoint.\n course_id=007407\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses(course_id=7407)\n\n assert isinstance(response, dict)\n assert set(courses_keys).issubset(response.keys())\n assert set(subject_keys).issubset(response.keys())\n assert set(course_id_keys).issubset(response.keys())\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_schedule_course_num.yml', filter_query_parameters=['key'])\ndef test_courses_schedule_by_class_number(schedule_keys):\n \"\"\"Tests an API call to /courses/{class_number}/schedule endpoint.\n class_number=5377\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses_schedule(class_num=5377)\n\n assert isinstance(response, list)\n assert isinstance(response[0], dict)\n assert set(schedule_keys).issubset(response[0].keys())\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_by_subject_catalog.yml', filter_query_parameters=['key'])\ndef test_courses_by_subject_catalog(courses_keys, course_id_keys):\n \"\"\"Tests an API call to /courses/{subject}/{catalog_number} endpoint.\n subject=PHYS, catalog=234\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses(subject=\"PHYS\", catalog_num=234)\n\n assert isinstance(response, dict)\n assert set(courses_keys).issubset(response.keys())\n assert set(course_id_keys).issubset(response.keys())\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_schedule_by_subject_catalog.yml', filter_query_parameters=['key'])\ndef test_courses_schedule_by_subject_catalog(schedule_keys):\n \"\"\"Tests an API call to /courses/{subject}/{catalog_number}/schedule endpoint.\n subject=CS, catalog=486\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses_schedule(subject=\"CS\", catalog_num=486)\n\n assert isinstance(response, list)\n assert isinstance(response[0], dict)\n assert set(schedule_keys).issubset(response[0].keys())\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_prerequisites.yml', filter_query_parameters=['key'])\ndef test_courses_prerequisites(prereq_keys):\n \"\"\"Tests an API call to /courses/{subject}/{catalog_number}/prerequisites endpoint.\n subject=PHYS, catalog=375\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses_prerequisites(\"PHYS\", 375)\n\n assert isinstance(response, dict)\n assert set(prereq_keys).issubset(response.keys())\n\n\n@vcr.use_cassette('vcr_cassettes/courses/courses_examschedule.yml', filter_query_parameters=['key'])\ndef test_courses_examschedule(examschedule_keys):\n \"\"\"Tests an API call to /courses/{subject}/{catalog_number}/examschedule endpoint.\n subject=CS, catalog=486\"\"\"\n\n uw_driver = UW_Driver()\n response = uw_driver.courses_examschedule(\"CS\", 486)\n\n assert isinstance(response, dict)\n assert set(examschedule_keys).issubset(response.keys())\n","sub_path":"tests/test_courses.py","file_name":"test_courses.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"596950037","text":"# Hint: You may not need all of these. Remove the unused functions.\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # Your code here\n\n # init array... \n route = [None] * length\n\n # init dict...\n route_lookup = dict()\n\n # go through tickets...\n for ticket in tickets:\n\n # save destination...\n route_lookup[ticket.source] = ticket.destination\n\n # First ticket source none...\n next_destination = route_lookup[\"NONE\"]\n\n # for each leg in route...\n for current_leg in range(0, length):\n\n # set leg to next destination...\n route[current_leg] = next_destination \n \n # set next destination...\n next_destination = route_lookup[next_destination]\n\n return route\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"393048090","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n\nclient_email = \"msu-schedule@appspot.gserviceaccount.com\"\n\nRULE = {\n 'scope': {\n 'type': 'user',\n 'value': 'maxim.v.kochurov@gmail.com',\n },\n 'role': 'owner'\n}\n\nCLD_META = {\n \"kind\": \"calendar#calendar\",\n \"summary\": \"msu-schedule\",\n}\n\n\ndef CLD_SET(cld_id):\n res = {\n \"kind\": \"calendar#calendarListEntry\",\n \"id\": cld_id,\n \"description\": \"Расписание\",\n \"location\": \"Российская Федерация, 119991, г.Москва, ГСП-1, Ленинские горы, Московский государственный университет имени М.В.Ломоносова, 3-й новый учебный корпус, д.1 стр. 46, Экономический факультет\".decode(\"utf8\"),\n \"timeZone\": \"Europe/Moscow\",\n \"backgroundColor\": \"#00FFFB\",\n \"hidden\": False,\n \"selected\": True,\n \"accessRole\": \"reader\"\n }\n return res\n\n\nHOST = \"localhost\"\nPORT = 9090\nDATA = \"data/BD\"\n","sub_path":"schedule/CONSTANTS.py","file_name":"CONSTANTS.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"181958004","text":"import re\nimport sys\nimport random\nimport argparse\n\nPARSE_DIRECTIVE = re.compile(\"(?P[A-Z]+)\\((?P.*)\\)\\s?;\\s?\")\n\nOUT=sys.stdout\nERR=sys.stderr\nMAX_ITER=10000\n\n# Predefined 'known types'\n#\ndef Unsigned8():\n return random.randint(0,255)\n#\ndef Boolean():\n return random.choice([True, False])\n\n# Parse command line arguments\n#\np = argparse.ArgumentParser()\np.add_argument('-i', '--input', type=argparse.FileType('r'), default=sys.stdin)\nargs = p.parse_args()\n\n# Read source\n#\nlines = [l.rstrip(\"\\n\") for l in args.input.readlines()]\n\nparams = dict()\nconstraints = dict()\n\ndef info(s, quit=False):\n ERR.write(\"[INFO] \")\n ERR.write(s + '\\n')\n if quit:\n sys.exit(0)\n\ndef error(s, code=1):\n ERR.write(s + '\\n')\n sys.exit(code)\n\n\nclass State:\n def __init__(self):\n self.reset()\n def reset(self):\n self.environment = dict()\n self.constraints = dict()\n self.parameters = dict()\n self.preconditions = list()\n def eval(self, smt):\n return eval(smt, self.environment, self.environment)\n def exec(self, smt):\n exec(smt, self.environment, self.environment)\n def gen_configuration(self):\n for k, v in self.parameters.items():\n self.environment[k] = v()\n for p in self.preconditions:\n self.exec(p)\n def is_valid_configuration(self):\n for k, v in self.constraints.items():\n f = self.eval(v)\n if not f():\n return False\n return True\n \n# Process CFG file\n#\n(state, warnings) = (State(), 0)\nfor (line_no, line) in enumerate(lines):\n\n parse_error = lambda fatal, reason:\\\n error (fatal, 'Error (line %d): %s' % (line_no + 1, reason))\n \n # Skip comments and empty lines.\n #\n if len(line) == 0 or (line[0] == '#'):\n continue\n\n m = PARSE_DIRECTIVE.match(line)\n if not m:\n parse_error(False, 'Invalid directive: %s' % line)\n\n directive = m.group('directive')\n if directive == 'PARAMETER':\n args = m.group('operand').split(',', 1)\n\n def set_param(value):\n k = args[0]\n if k in params:\n parse_error(\"Parameter '%s' already defined\" % (k))\n state.parameters[k] = value\n\n d = args[1]\n if type(eval(d)) == type (list()):\n set_param(eval('lambda : random.choice(%s)' % (d)))\n else:\n set_param(eval(d, globals(), state.environment))\n\n elif directive == 'ECHO':\n info(eval(m.group('operand')))\n\n \n elif directive == 'CONSTRAINT':\n args = m.group('operand').split(',', 1)\n state.constraints[args[0]] = \"lambda : %s\" % args[1]\n if 'if' in state.constraints[args[0]]:\n state.constraints[args[0]] += \" else True\"\n\n\n elif directive == 'PRECONDITIONS':\n args = m.group('operand').split(',', 1)\n state.preconditions.append(args[0])\n\n \n elif directive == 'EMIT':\n args = m.group('operand').split(',', 1)\n\n results = list()\n count = int(args[0])\n while count > 0:\n n = MAX_ITER\n\n state.gen_configuration()\n while (not state.is_valid_configuration() and n != 0):\n state.gen_configuration()\n n -= 1\n\n if (n == 0):\n error(\"Failure, iteration count exceeded!\", 2)\n\n d = dict()\n for k, _ in state.parameters.items():\n d[k] = state.environment[k]\n print(str(d))\n \n count -= 1\n \n elif directive == 'RESET':\n state.reset()\n\n \n elif directive == 'QUIT':\n info('Complete: (Warnings %d)' % (warnings))\n sys.exit(0)\n\n \n else:\n parse_error('Invalid directive')\n \ninfo('Complete: (Warnings %d)' % (warnings))\n","sub_path":"cgen.py","file_name":"cgen.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"443682303","text":"import json\nimport cv2\nimport os\nimport uuid\nimport numpy\nimport io\nimport folium\nfrom folium import plugins\nimport inspect\nfrom pyppeteer import launch\nimport asyncio\n# ----------------------------------------------------------------------------------------------------------------------\nimport tools_image\nimport tools_time_profiler\n# ----------------------------------------------------------------------------------------------------------------------\nclass tools_GIS(object):\n def __init__(self,folder_out=None):\n self.folder_out = folder_out\n self.TP = tools_time_profiler.Time_Profiler()\n return\n# ----------------------------------------------------------------------------------------------------------------------\n def evaluate_GPS_boundries(self,gis_points,W,H):\n filename_temp_html = uuid.uuid4().hex + '.html'\n filename_temp_png = filename_temp_html.split('.')[0] + '.png'\n self.build_folium_html(gis_points,filename_temp_html,mode='bbox')\n self.html_to_png(os.getcwd().replace('\\\\','/')+self.folder_out[1:]+filename_temp_html,filename_temp_png,W,H)\n\n image_bbox = cv2.imread(self.folder_out+filename_temp_png)\n os.remove(self.folder_out + filename_temp_html)\n os.remove(self.folder_out + filename_temp_png)\n\n\n V = tools_image.bgr2hsv(image_bbox)[:,:,2]\n xx = numpy.where(V>0)\n top = numpy.min(numpy.array(xx).T[:,0])\n left = numpy.where(V[top] > 0)[0][0]\n right = numpy.where(V[top] > 0)[0][-1]\n bottom =V.shape[0]-top-10 + numpy.sum(V[-top - 10:, left:right], axis=1).argmax()\n\n north = numpy.array(gis_points)[:, 0].max()\n south = numpy.array(gis_points)[:, 0].min()\n west = numpy.array(gis_points)[:, 1].min()\n east = numpy.array(gis_points)[:, 1].max()\n\n scaler = 1e5\n k_east_west = numpy.longdouble(scaler*(east - west) / (right - left))\n b_east_west = (east + west - k_east_west*(right+left)/scaler)/2\n bound_east,bound_west = b_east_west,b_east_west+k_east_west*image_bbox.shape[1]/scaler\n\n k_south_nord = numpy.longdouble(scaler * (south - north) / (bottom - top))\n b_south_nord = (south + north - k_south_nord * (bottom + top) / scaler) / 2\n bound_north, bound_south = b_south_nord, b_south_nord + k_south_nord * image_bbox.shape[0] / scaler\n\n #print(k_east_west,b_east_west,k_south_nord,b_south_nord)\n\n return bound_east,bound_west,bound_north, bound_south\n# ----------------------------------------------------------------------------------------------------------------------\n def gps_to_ij(self, gis_points, W, H, dct_bbox):\n scaler = 1e5\n k_east_west = -numpy.longdouble(scaler * (dct_bbox['east'] - dct_bbox['west']) / (W))\n b_east_west = (dct_bbox['east'] + dct_bbox['west'] - k_east_west * (W) / scaler) / 2\n I = (gis_points[:, 1] - b_east_west) * scaler / k_east_west\n\n k_south_nord = -numpy.longdouble(scaler * (dct_bbox['north'] - dct_bbox['south']) / (H))\n b_south_nord = (dct_bbox['north'] + dct_bbox['south'] - k_south_nord * (H) / scaler) / 2\n J = (gis_points[:, 0] - b_south_nord) * scaler / k_south_nord\n #print(k_east_west, b_east_west, k_south_nord, b_south_nord)\n IJ = numpy.concatenate([[I],[J]]).astype(int).T\n return IJ\n# ----------------------------------------------------------------------------------------------------------------------\n def build_folium_html(self, gis_points,filename_html,colors=None,mode=None):\n\n tiles = ['openstreetmap','stamentoner','mapquestopen','stamenterrain','cartodbpositron','cartodbdark_matter']\n map_folium = folium.Map(location=gis_points[0],tiles=tiles[1],zoom_control=True,scrollWheelZoom=True,dragging=True)\n\n if mode =='bbox':\n north = numpy.array(gis_points)[:, 0].max()\n south = numpy.array(gis_points)[:, 0].min()\n west = numpy.array(gis_points)[:, 1].min()\n east = numpy.array(gis_points)[:, 1].max()\n poly_bound = [(north, west), (north, east), (south, east), (south, west), (north, west)]\n folium.PolyLine(locations=poly_bound,color='#ff0000',weight=1).add_to(map_folium)\n\n weight,fillOpacity = 1,0.6\n\n if mode in ['clean','bbox']:\n weight, fillOpacity = 0, 0\n\n if colors is None:\n colors = ['#C00000']*gis_points.shape[0]\n\n for point,color in zip(gis_points,colors):\n folium.CircleMarker(location=point,radius=3,color=color,weight=weight,fillColor=color,fillOpacity=fillOpacity).add_to(map_folium)\n\n folium.CircleMarker(location=gis_points[ 0], radius=12, color=colors[ 0], weight=weight, fillColor=colors[ 0],fillOpacity=1).add_to(map_folium)\n folium.CircleMarker(location=gis_points[-1], radius=12, color=colors[-1], weight=weight, fillColor=colors[-1],fillOpacity=1).add_to(map_folium)\n\n map_folium.fit_bounds(map_folium.get_bounds())\n map_folium.save(self.folder_out + filename_html)\n\n return\n# ----------------------------------------------------------------------------------------------------------------------\n def build_folium_png_with_gps(self,gis_points, filename_out,W,H,draw_points=False):\n bound_east,bound_west,bound_north, bound_south = self.evaluate_GPS_boundries(gis_points,W,H)\n filename_temp_html = uuid.uuid4().hex + '.html'\n self.build_folium_html(gis_points, filename_temp_html,mode=(None if draw_points else 'clean'))\n self.html_to_png(os.getcwd().replace('\\\\', '/') + self.folder_out[1:] + filename_temp_html, filename_out,W,H)\n os.remove(self.folder_out + filename_temp_html)\n dct_bbox = dict({'east':bound_east,'west':bound_west,'north':bound_north, 'south':bound_south})\n json.dump(dct_bbox, open(self.folder_out+filename_out.split('.')[0]+'.json', 'w'))\n image = cv2.imread(self.folder_out +filename_out)\n return dct_bbox,image\n# ----------------------------------------------------------------------------------------------------------------------\n async def __html_to_png_core(self,html_full_path, output_image_path,W,H):\n browser = await launch({'defaultViewport': {'width': W, 'height': H}})\n page = await browser.newPage()\n await page.goto('file://'+html_full_path)\n await page.screenshot({'path': output_image_path,'clip':{\"x\": 0,\"y\": 0,\"width\": W,\"height\": H}})\n await browser.close()\n return\n# ----------------------------------------------------------------------------------------------------------------------\n def html_to_png(self,html_full_path,output_image_path,W,H):\n self.TP.tic(inspect.currentframe().f_code.co_name, reset=True)\n asyncio.get_event_loop().run_until_complete(self.__html_to_png_core(html_full_path, self.folder_out+output_image_path,W,H))\n self.TP.print_duration(inspect.currentframe().f_code.co_name)\n return\n# ----------------------------------------------------------------------------------------------------------------------\n","sub_path":"tools_GIS.py","file_name":"tools_GIS.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"381733124","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nposts = [\n {\n 'author':'CoreyMS',\n 'title':'Blog Post 1',\n 'content':'First post comment',\n 'date_posted':'August 27, 2018'\n },\n {\n 'author':'Jane Doe',\n 'title':'Blog Post 2',\n 'content':'Second post comment',\n 'date_posted':'August 28, 2018'\n }\n]\n# Create your views here.\ndef home(requests):\n context = {\n 'posts' : posts\n }\n return render(requests, 'blog/home.html', context)\n\ndef about(requests):\n return render(requests, 'blog/about.html', {'title': 'About'})","sub_path":"django_project/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"635235487","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 6 21:44:57 2020\n\n@author: natal\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom setup import cycles, nu, histories, slab, mid, Nbins, Sigma_t\nfrom col_type import col_type\n\nk_save=np.zeros(cycles)\nflux_save=np.zeros((Nbins,cycles))\n\nfis_loc=slab*np.random.rand(histories) #fission locations. Start with a random distribution of locations for new particles\n\nfor m in range(cycles):\n\n col_save=[] #to store collision locations \n fis_save=[] #to store fission locations\n fissions=0 #number of fissions in the current cylce\n \n for n in range(histories): \n #sample position and direction\n pos=fis_loc[np.random.randint(0,len(fis_loc))]\n direc=np.random.randint(0,2) #0=going left, 1=going right\n #Because this problem is 1D, the only sense of an angle that we need is whether the neutron is moving right or left\n \n active=True #use this to tell the code when to end a history\n \n while active==True:\n if pos \"+ch_file)\n os.rename(file,ch_file)\n os.chdir(current_dir)\n print('All files renamed!')\n\nrename_files()","sub_path":"renameFiles/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"479874730","text":"import os\r\nfrom requests import get\r\nimport re\r\nfrom lxml import etree\r\nfrom time import sleep\r\n\r\ndis=''\r\n\r\ndef gett(url): \r\n ob1=get(url).content.decode('UTF8')\r\n ota=etree.HTML(ob1)\r\n otaitem=ota.xpath('//div/div/div/div/div/div/a/text()')\r\n otahref=ota.xpath('//div/div/div/div/div/div/div/a/@href')\r\n otatime=ota.xpath('//div/div/div/div/div/div/div/span/text()')\r\n \r\n assert(len(otaitem)==len(otahref))\r\n return list(zip(otaitem,otahref,otatime)) \r\n\r\ndef writefile(target,result): \r\n for i in range(len(result)):\r\n target.write('%s\\t%s\\t\\t%s\\n\\n'%(result[i][2],result[i][0],'http://www.chancheng.gov.cn'+result[i][1]))\r\n\r\ndef download_detail(result,filename):\r\n os.makedirs(dis+'/政策文件/'+filename+'/全部文章')\r\n for g in range(len(result)):\r\n oba=get('http://www.chancheng.gov.cn'+result[g][1]).content.decode('utf8')\r\n obaa=etree.HTML(oba)\r\n obatitle=obaa.xpath('//div[@class=\"title_cen mar-t2 text\"]/text()')\r\n obadetail=obaa.xpath('//div/ucapcontent/p/text()')\r\n with open(dis+'/政策文件/'+filename+'/全部文章/'+obatitle[0]+'.docx','a+',encoding='utf8') as fi:\r\n for i in obadetail:\r\n fi.write(i+'\\n')\r\n print('下载完成')\r\n\r\ndef download_list(url,filename): \r\n result=gett(url)\r\n os.chdir('D:')\r\n path=dis+'/政策文件/'+filename+'\\/'+filename+'.docx'\r\n if os.path.exists(path): \r\n fi=open(path,'a+',encoding='utf8')\r\n writefile(fi,result)\r\n elif os.path.exists(dis+'/政策文件/'+filename): \r\n fi=open(path,'w+',encoding='utf8')\r\n writefile(fi,result)\r\n elif os.path.exists(dis+'/政策文件'):\r\n os.makedirs(dis+'/政策文件/'+filename) \r\n fi=open(path,'w+',encoding='utf8')\r\n writefile(fi,result)\r\n else:\r\n os.makedirs(dis+'/政策文件')\r\n os.makedirs(dis+'/政策文件/'+filename)\r\n fi=open(path,'w+',encoding='utf8')\r\n writefile(fi,result)\r\n return result\r\n\r\ndef getpage(url):\r\n ob=get(url).content.decode('UTF8')\r\n if re.search(r'createPageHTML(.*?);',ob,re.S):\r\n return re.findall(r'createPageHTML(.*?);',ob,re.S)[0][12]\r\n else:\r\n return False\r\n \r\ndef start(place):\r\n print('开始查找关于 \\''+place+'\\' 的政策文件....')\r\n for i in range(len(ob4)):\r\n if re.search(place,ob4[i][0],re.S):\r\n urlfront=ob4[i][1]\r\n filename=ob4[i][0]+'政策文件'\r\n sleep(0.8)\r\n print('查找'+filename+'....')\r\n url=urlfront+'/0200/bmlist.shtml'\r\n if not getpage(url)==False: \r\n sleep(0.8)\r\n print('正在下载资料目录...')\r\n assemble=download_list(url,filename)\r\n page=int(getpage(url))\r\n for j in range(page+1):\r\n url2=urlfront+'/0200/bmlist_'+str(j)+'.shtml'\r\n assemble2=download_list(url2,filename)\r\n assemble+=assemble2\r\n sleep(0.8)\r\n print('下载成功!')\r\n sleep(0.5)\r\n print('您是否需要下载所有的阅读资料?')\r\n need=input('>')\r\n if need=='是' or need=='需要':\r\n download_detail(assemble,filename)\r\n else:\r\n print('感谢老板使用!')\r\n else:\r\n sleep(0.8)\r\n print('没有政策文件')\r\n\r\nob3=get('http://www.chancheng.gov.cn/').content.decode('utf8')\r\nob3text=etree.HTML(ob3).xpath('//div[@id=\"div_4\"]/ul/li/a/text()')\r\nob3href=etree.HTML(ob3).xpath('//div[@id=\"div_4\"]/ul/li/a/@href')\r\nob4=list(zip(ob3text,ob3href))\r\n\r\nprint('您想搜索哪个单位的文章?')\r\nname=input('>') \r\nprint('保存到哪个盘?')\r\ndis=input('>')+':'\r\n\r\nstart(name)\r\n\r\n\r\n","sub_path":"chanchengwenjian.py","file_name":"chanchengwenjian.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"180260804","text":"\"\"\"Reference implementations of discord algorithms for anomaly detection.\"\"\"\n\nimport random as rn\n\nimport numpy as np\n\nfrom . import distances\nfrom .discord_window import DiscordWindow\nfrom .priority_queue import MaxQueue\n\n\ndef _discord_brute_force(series, k, distance_fn, top):\n \"\"\"Brute force algorithm for finding the top discords.\"\"\"\n N = series.shape[0]\n\n max_queue = MaxQueue(size=top)\n\n for p in range(N - k + 1):\n nearest_neighbor_dist = float('inf')\n\n for q in range(N - k + 1):\n if np.abs(p - q) >= k:\n d = distance_fn(series[p:p + k], series[q:q + k])\n if d < nearest_neighbor_dist:\n nearest_neighbor_dist = d\n\n max_queue.put(p, nearest_neighbor_dist)\n\n return [\n DiscordWindow(start=x[0], length=k, discordance=x[1])\n for x in max_queue.as_list()]\n\n\ndef _random_sort_key(x):\n \"\"\"Sort key for random ordering heuristic.\"\"\"\n return rn.random()\n\n\ndef _identity_sort_key(x):\n \"\"\"Sort key for standard ordering heuristic.\"\"\"\n return x\n\n\ndef _discord_heuristic(series, k, distance_fn, top, outer_sort_key_fn=None,\n inner_sort_key_fn=None):\n \"\"\"Heuristic ordering algorithm for finding the top discords.\"\"\"\n if outer_sort_key_fn is None:\n outer_sort_key_fn = _identity_sort_key\n if inner_sort_key_fn is None:\n inner_sort_key_fn = _identity_sort_key\n\n N = series.shape[0]\n\n max_queue = MaxQueue(size=top)\n\n for p in sorted(range(N - k + 1), key=outer_sort_key_fn):\n nearest_neighbor_dist = float('inf')\n add_to_queue = True\n\n for q in sorted(range(N - k + 1), key=inner_sort_key_fn):\n if np.abs(p - q) >= k:\n d = distance_fn(series[p:p + k], series[q:q + k])\n if max_queue.full() and d < max_queue.peek_min():\n add_to_queue = False\n continue\n if d < nearest_neighbor_dist:\n nearest_neighbor_dist = d\n\n if add_to_queue:\n max_queue.put(p, nearest_neighbor_dist)\n\n return [\n DiscordWindow(start=x[0], length=k, discordance=x[1])\n for x in max_queue.as_list()]\n\n\n_IMPLEMENTATION_FN_DICT = {\n 'brute_force': _discord_brute_force,\n 'heuristic': _discord_heuristic}\n\n\ndef discord(series, window_length, distance_fn=None, top=None,\n implementation='heuristic'):\n \"\"\"Common interface for reference discord implementations.\"\"\"\n if distance_fn is None:\n distance_fn = distances.euclidean_distance\n\n impl_fn = _IMPLEMENTATION_FN_DICT[implementation]\n\n return impl_fn(series, window_length, distance_fn, top)\n","sub_path":"mc_discord/discord_static.py","file_name":"discord_static.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"233895819","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport sys\nfrom io import BytesIO\n\nfrom .models import ShareProperties, DirectoryProperties, FileProperties\nfrom ._generated.models import StorageErrorException\nfrom ._shared.utils import process_storage_error, parse_length_from_content_range\nfrom ._shared.upload_chunking import upload_file_chunks\nfrom ._shared.download_chunking import (\n validate_and_format_range_headers,\n process_range_and_offset,\n process_content,\n ParallelFileChunkDownloader,\n SequentialFileChunkDownloader)\n\n\ndef deserialize_metadata(response, obj, headers): # pylint: disable=unused-argument\n raw_metadata = {k: v for k, v in response.headers.items() if k.startswith(\"x-ms-meta-\")}\n return {k[10:]: v for k, v in raw_metadata.items()}\n\n\ndef deserialize_share_properties(response, obj, headers):\n metadata = deserialize_metadata(response, obj, headers)\n share_properties = ShareProperties(\n metadata=metadata,\n **headers\n )\n return share_properties\n\n\ndef deserialize_directory_properties(response, obj, headers):\n metadata = deserialize_metadata(response, obj, headers)\n directory_properties = DirectoryProperties(\n metadata=metadata,\n **headers\n )\n return directory_properties\n\n\ndef deserialize_file_properties(response, obj, headers):\n metadata = deserialize_metadata(response, obj, headers)\n file_properties = FileProperties(\n metadata=metadata,\n **headers\n )\n if 'Content-Range' in headers:\n if 'x-ms-content-md5' in headers:\n file_properties.content_settings.content_md5 = headers['x-ms-content-md5']\n else:\n file_properties.content_settings.content_md5 = None\n return file_properties\n\n\ndef deserialize_file_stream(response, obj, headers):\n file_properties = deserialize_file_properties(response, obj, headers)\n obj.properties = file_properties\n return response.location_mode, obj\n\n\ndef upload_file_helper(\n client,\n stream,\n size,\n metadata,\n content_settings,\n validate_content,\n timeout,\n max_connections,\n file_settings,\n **kwargs):\n try:\n if size is None or size < 0:\n raise ValueError(\"A content size must be specified for a File.\")\n response = client.create_file(\n size,\n content_settings=content_settings,\n metadata=metadata,\n timeout=timeout,\n **kwargs\n )\n if size == 0:\n return response\n\n return upload_file_chunks(\n file_service=client,\n file_size=size,\n block_size=file_settings.max_range_size,\n stream=stream,\n max_connections=max_connections,\n validate_content=validate_content,\n timeout=timeout,\n **kwargs)\n except StorageErrorException as error:\n process_storage_error(error)\n\n\nclass StorageStreamDownloader(object): # pylint: disable=too-many-instance-attributes\n \"\"\"A streaming object to download a file.\n\n The stream downloader can iterated, or download to open file or stream\n over multiple threads.\n \"\"\"\n\n def __init__(\n self, share, file_name, file_path, service, config, offset,\n length, validate_content, timeout, **kwargs):\n self.service = service\n\n self.config = config\n self.offset = offset\n self.length = length\n self.timeout = timeout\n self.validate_content = validate_content\n self.request_options = kwargs\n self.location_mode = None\n self._download_complete = False\n\n # The service only provides transactional MD5s for chunks under 4MB.\n # If validate_content is on, get only self.MAX_CHUNK_GET_SIZE for the first\n # chunk so a transactional MD5 can be retrieved.\n self.first_get_size = self.config.max_single_get_size if not self.validate_content \\\n else self.config.max_chunk_get_size\n initial_request_start = self.offset if self.offset is not None else 0\n if self.length is not None and self.length - self.offset < self.first_get_size:\n initial_request_end = self.length\n else:\n initial_request_end = initial_request_start + self.first_get_size - 1\n\n self.initial_range, self.initial_offset = process_range_and_offset(\n initial_request_start,\n initial_request_end,\n self.length,\n None, None)\n\n self.download_size = None\n self.file_size = None\n self.file = self._initial_request()\n self.properties = self.file.properties\n self.properties.name = file_name\n self.properties.share = share\n self.properties.path = file_path\n\n # Set the content length to the download size instead of the size of\n # the last range\n self.properties.size = self.download_size\n\n # Overwrite the content range to the user requested range\n self.properties.content_range = 'bytes {0}-{1}/{2}'.format(self.offset, self.length, self.file_size)\n\n # Overwrite the content MD5 as it is the MD5 for the last range instead\n # of the stored MD5\n # TODO: Set to the stored MD5 when the service returns this\n self.properties.content_md5 = None\n\n def __len__(self):\n return self.download_size\n\n def __iter__(self):\n if self.download_size == 0:\n content = b\"\"\n else:\n content = process_content(\n self.file,\n self.initial_offset[0],\n self.initial_offset[1],\n False, None, None)\n\n if content is not None:\n yield content\n if self._download_complete:\n return\n\n end_file = self.file_size\n if self.length is not None:\n # Use the length unless it is over the end of the file\n end_file = min(self.file_size, self.length + 1)\n\n downloader = SequentialFileChunkDownloader(\n file_service=self.service,\n download_size=self.download_size,\n chunk_size=self.config.max_chunk_get_size,\n progress=self.first_get_size,\n start_range=self.initial_range[1] + 1, # start where the first download ended\n end_range=end_file,\n stream=None,\n validate_content=self.validate_content,\n timeout=self.timeout,\n use_location=self.location_mode,\n cls=deserialize_file_stream,\n **self.request_options)\n\n for chunk in downloader.get_chunk_offsets():\n yield downloader.yield_chunk(chunk)\n\n def _initial_request(self):\n range_header, range_validation = validate_and_format_range_headers(\n self.initial_range[0],\n self.initial_range[1],\n start_range_required=False,\n end_range_required=False,\n check_content_md5=self.validate_content)\n\n try:\n location_mode, file_stream = self.service.download(\n timeout=self.timeout,\n range=range_header,\n range_get_content_md5=range_validation,\n validate_content=self.validate_content,\n cls=deserialize_file_stream,\n data_stream_total=None,\n download_stream_current=0,\n **self.request_options)\n\n # Check the location we read from to ensure we use the same one\n # for subsequent requests.\n self.location_mode = location_mode\n\n # Parse the total file size and adjust the download size if ranges\n # were specified\n self.file_size = parse_length_from_content_range(file_stream.properties.content_range)\n if self.length is not None:\n # Use the length unless it is over the end of the file\n self.download_size = min(self.file_size, self.length - self.offset + 1)\n elif self.offset is not None:\n self.download_size = self.file_size - self.offset\n else:\n self.download_size = self.file_size\n\n except StorageErrorException as error:\n if self.offset is None and error.response.status_code == 416:\n # Get range will fail on an empty file. If the user did not\n # request a range, do a regular get request in order to get\n # any properties.\n try:\n _, file_stream = self.service.download(\n timeout=self.timeout,\n validate_content=self.validate_content,\n cls=deserialize_file_stream,\n data_stream_total=0,\n download_stream_current=0,\n **self.request_options)\n except StorageErrorException as error:\n process_storage_error(error)\n\n # Set the download size to empty\n self.download_size = 0\n self.file_size = 0\n else:\n process_storage_error(error)\n\n # If the file is small, the download is complete at this point.\n # If file size is large, download the rest of the file in chunks.\n if file_stream.properties.size == self.download_size:\n self._download_complete = True\n\n return file_stream\n\n def content_as_bytes(self, max_connections=1):\n \"\"\"Download the contents of this file.\n\n This operation is blocking until all data is downloaded.\n\n :param int max_connections:\n The number of parallel connections with which to download.\n :rtype: bytes\n \"\"\"\n stream = BytesIO()\n self.download_to_stream(stream, max_connections=max_connections)\n return stream.getvalue()\n\n def content_as_text(self, max_connections=1, encoding='UTF-8'):\n \"\"\"Download the contents of this file, and decode as text.\n\n This operation is blocking until all data is downloaded.\n\n :param int max_connections:\n The number of parallel connections with which to download.\n :rtype: str\n \"\"\"\n content = self.content_as_bytes(max_connections=max_connections)\n return content.decode(encoding)\n\n def download_to_stream(self, stream, max_connections=1):\n \"\"\"Download the contents of this file to a stream.\n\n :param stream:\n The stream to download to. This can be an open file-handle,\n or any writable stream. The stream must be seekable if the download\n uses more than one parallel connection.\n :returns: The properties of the downloaded file.\n :rtype: ~azure.storage.file.models.FileProperties\n \"\"\"\n # the stream must be seekable if parallel download is required\n if max_connections > 1:\n error_message = \"Target stream handle must be seekable.\"\n if sys.version_info >= (3,) and not stream.seekable():\n raise ValueError(error_message)\n\n try:\n stream.seek(stream.tell())\n except (NotImplementedError, AttributeError):\n raise ValueError(error_message)\n\n if self.download_size == 0:\n content = b\"\"\n else:\n content = process_content(\n self.file,\n self.initial_offset[0],\n self.initial_offset[1],\n False, None, None)\n # Write the content to the user stream\n # Clear file content since output has been written to user stream\n if content is not None:\n stream.write(content)\n if self._download_complete:\n return self.properties\n\n end_file = self.file_size\n if self.length is not None:\n # Use the length unless it is over the end of the file\n end_file = min(self.file_size, self.length + 1)\n\n downloader_class = ParallelFileChunkDownloader if max_connections > 1 else SequentialFileChunkDownloader\n downloader = downloader_class(\n file_service=self.service,\n download_size=self.download_size,\n chunk_size=self.config.max_chunk_get_size,\n progress=self.first_get_size,\n start_range=self.initial_range[1] + 1, # start where the first download ended\n end_range=end_file,\n stream=stream,\n validate_content=self.validate_content,\n timeout=self.timeout,\n use_location=self.location_mode,\n cls=deserialize_file_stream,\n **self.request_options)\n\n if max_connections > 1:\n import concurrent.futures\n executor = concurrent.futures.ThreadPoolExecutor(max_connections)\n list(executor.map(downloader.process_chunk, downloader.get_chunk_offsets()))\n else:\n for chunk in downloader.get_chunk_offsets():\n downloader.process_chunk(chunk)\n\n return self.properties\n","sub_path":"sdk/storage/azure-storage-file/azure/storage/file/_share_utils.py","file_name":"_share_utils.py","file_ext":"py","file_size_in_byte":13331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"474413139","text":"import pysys\nfrom pysys.constants import *\nfrom pysys.basetest import BaseTest\nfrom pysys.utils.perfreporter import CSVPerformanceFile\nimport os, sys, math, shutil\n\nclass PySysTest(BaseTest):\n\n\tdef execute(self):\n\t\tl = {}\n\t\texec(open(self.input+'/../../../utilities/resources/runpysys.py').read(), {}, l) # define runPySys\n\t\trunPySys = l['runPySys']\n\t\t\n\t\tfor subtest in ['customformat', 'customclass']:\n\t\t\tshutil.copytree(self.input, self.output+'/'+subtest)\n\t\t\tos.rename(self.output+'/'+subtest+'/pysysproject-%s.xml'%subtest, self.output+'/'+subtest+'/pysysproject.xml')\n\t\n\t\t\trunPySys(self, subtest+'_pysys', ['run', '-o', self.output+'/'+subtest+'_output'], workingDir=subtest)\n\t\t\tself.logFileContents(subtest+'_pysys.out', maxLines=0)\n\t\t\tself.logFileContents(subtest+'_output/PySys_NestedTestcase/run.log')\n\t\t\tself.logFileContents(subtest+'_pysys.err')\n\t\t\tself.assertGrep(subtest+'_pysys.out', expr='Test final outcome: .*(PASSED|NOT VERIFIED)', abortOnError=True)\n\t\t\t\n\tdef validate(self):\n\t\t\n\t\tself.assertGrep('customformat'+'_pysys.out', expr=r'STDOUT_DATE_FORMAT \\d\\d\\d\\d-\\d\\d.*STDOUT_PREFIX Sample log message')\n\t\tself.assertGrep('customformat_output/PySys_NestedTestcase/run.log', expr=r'\\d\\d\\d\\d-\\d\\d.*RUNLOG_PREFIX Sample log message')\n\t\t\n\t\tself.assertGrep('customclass'+'_pysys.out', expr=r'CUSTOM_STDOUT_PREFIX \\d\\d\\d\\d-\\d\\d.*Sample log message')\n\t\tself.assertGrep('customclass_output/PySys_NestedTestcase/run.log', expr=r'CUSTOM_RUNLOG_PREFIX \\d\\d\\d\\d-\\d\\d.*Sample log message')\n\n","sub_path":"pysys-examples/internal/testcases/PySys_internal_066/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"522838517","text":"\"\"\"MIT License\n\nCopyright (c) 2020 Jojo#7711\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\"\"\"\n\nfrom redbot.core import commands, Config\nimport discord\n\nimport logging\nfrom . import parsers\nfrom typing import Optional, Literal # *\n\nlog = logging.getLogger(\"red.jojo.embedmaker\")\n\n\nclass Embedder(commands.Cog):\n \"\"\"\n An embed maker for Red.\n This mostly exists because I couldn't find a better first/third party cog\n\n Create an embed from text or from a json file (upload a json file with the command)\n \"\"\"\n\n __version__ = \"1.0.0\"\n\n def __init__(self, bot):\n self.bot = bot\n self.config = Config.get_conf(self, 12535235231231231, True)\n self.config.register_global(embeds={})\n self.config.register_guild(embeds={}, defaults=False)\n # `Embeds` is dict(name: str, embed: discord.Embed)\n\n async def red_delete_data_for_user(\n self,\n requester: Literal[\"discord\", \"owner\", \"user\", \"user_strict\"],\n user_id: int\n ) -> None:\n \"\"\"Nothing to delete.\"\"\"\n return\n\n @commands.group()\n @commands.admin()\n async def setembed(self, ctx):\n \"\"\"Base setter command for embeds\"\"\"\n\n @setembed.command()\n async def usedefault(self, ctx, state: bool):\n await self.config.guild(ctx.guild).set_raw(\"defaults\", value=state)\n await ctx.tick()\n\n @commands.group()\n async def embed(self, ctx):\n \"\"\"Basic embed command\"\"\"\n\n @embed.group(name=\"global\")\n @commands.is_owner()\n async def global_embed(self, ctx):\n \"\"\"Base global command\"\"\"\n\n @global_embed.command(name=\"upload\")\n async def global_upload(self, ctx, name):\n \"\"\"Upload a global embed\"\"\"\n await self.upload_embed_parser(ctx, name, True)\n\n @global_embed.command(name=\"create\") # Pesky already-defined errors\n async def global_create(self, ctx, name: str, title: str, *, description):\n \"\"\"Create a global embed\"\"\"\n await self.create_embed(ctx, name, title, description, True)\n\n @global_embed.command(name=\"remove\", aliases=(\"del\", \"delete\"))\n async def globla_remove(self, ctx, embed: str):\n \"\"\"Remove a global embed\"\"\"\n embeds = await self.config.get_raw('embeds')\n if embed not in embeds.keys():\n await ctx.send(\"Hm, that embed doesn't seem to exist!\")\n return\n del embeds[embed]\n await self.config.set_raw(\"embeds\", value=embeds)\n await ctx.tick()\n\n @embed.group(invoke_without_command=True)\n async def drop(self, ctx, channel: Optional[discord.TextChannel], name: str):\n \"\"\"Send an embed from the given title\"\"\"\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n try:\n embed = embeds[name]\n except KeyError:\n await ctx.send(\"Hm, that embed does not seem to exist\")\n return\n channel = channel or ctx.channel\n await channel.send(embed=discord.Embed.from_dict(embed))\n\n @drop.command(name=\"global\")\n async def drop_global(self, ctx, channel: Optional[discord.TextChannel], name: str):\n \"\"\"Drop a global embed\"\"\"\n embeds = await self.config.get_raw(\"embeds\")\n try:\n embed = embeds[name]\n except KeyError:\n await ctx.send(\"Hm, that embed doesn't seem to exist\")\n return\n channel = channel or ctx.channel\n await channel.send(embed=discord.Embed.from_dict(embed))\n\n @embed.command()\n @commands.mod_or_permissions(embed_links=True)\n async def create(self, ctx, name: str, title: str, *, description: str = None):\n \"\"\"Create a simple embed\"\"\"\n await self.create_embed(ctx, name, title, description, False)\n\n @embed.group(invoke_without_command=True)\n @commands.mod_or_permissions(embed_links=True)\n async def store(self, ctx, name: str, title: str, *, description: str):\n \"\"\"Store a simple embed by a name\n Example:\n `[p]embed store rules \\\"Demaratus support server rules\\\" Be nice\n Don't steal other's code`\"\"\"\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n if name in embeds.keys(): # Do this **before** creating the embed\n await ctx.send(f\"An embed with the name {name} has already been created!\")\n return\n embed = discord.Embed(title=title, description=description)\n embeds[name] = embed.to_dict()\n await self.config.guild(ctx.guild).set_raw(\"embeds\", value=embeds)\n await ctx.send(embed=embed)\n\n @store.command()\n async def msg(self, ctx, name: str, message: int):\n \"\"\"Store an embed from a message\"\"\"\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n if name in embeds.keys():\n await ctx.send(f\"An embed with the name `{name}` already exists!\")\n return\n try:\n msg: discord.Message = await ctx.fetch_message(message)\n except discord.NotFound:\n await ctx.send(\"Hm, I couldn't seem to find that message\")\n return\n if len(msg.embeds) < 1:\n await ctx.send(\"That message doesn't seem to have any embeds!\")\n return\n await ctx.send(embed=msg.embeds[0])\n embeds[name] = msg.embeds[0].to_dict()\n await self.config.guild(ctx.guild).set_raw('embeds', value=embeds)\n\n @embed.command()\n @commands.mod_or_permissions(embed_links=True)\n async def upload(self, ctx, name: str):\n \"\"\"Store an embed from a JSON file\"\"\"\n await self.upload_embed_parser(ctx, name, False)\n\n @embed.command()\n async def uploadnostore(self, ctx, channel: discord.TextChannel = None):\n \"\"\"Upload an embed from a file without storing it\"\"\"\n channel = channel or ctx.channel\n em = await parsers.parse_embed(ctx.message.attachments)\n if type(em) == str:\n await ctx.send(\n f\"Couldn't create an embed from that file!\"\n f\" ```py\\n{em}```\"\n )\n return\n elif type(em) == None:\n await ctx.send(\"That's not a `json` file\")\n return\n await ctx.send(embed=em)\n\n @embed.command(name=\"list\")\n async def embed_list(self, ctx, guild_specific: bool = True):\n \"\"\"List all of the available embeds\"\"\"\n embs = await self.embed_lister(ctx, guild_specific)\n log.info(embs)\n if not embs:\n msg = \"There are no embeds yet!\" if guild_specific is False else f\"{ctx.guild.name} doesn't have any embeds!\"\n await ctx.send(msg)\n return\n embed = discord.Embed()\n embed.title = f\"{ctx.guild.name} Embeds\" if guild_specific else f\"{ctx.me.name} Embeds\"\n embed.add_field(name=\"Embeds\", value=\", \".join(embs))\n await ctx.send(embed=embed)\n\n @embed.command(aliases=(\"del\", \"delete\"))\n @commands.mod_or_permissions(embed_links=True)\n async def remove(self, ctx, embed: str):\n \"\"\"Delete a stored embed\"\"\"\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n if not embed in embeds.keys():\n await ctx.send(\"Hm, that embed doesn't seem to exist\")\n return\n del embeds[embed]\n await self.config.guild(ctx.guild).set_raw('embeds', value=embeds)\n await ctx.tick()\n\n async def embed_lister(self, ctx: commands.Context, global_guild: bool) -> list:\n if global_guild:\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n if len(list(embeds.keys())) > 0:\n return list(embeds.keys())\n return None\n else:\n embeds = await self.config.get_raw('embeds')\n if len(list(embeds.keys())) > 0:\n return list(embeds.keys())\n return None\n\n async def default_embed(self, ctx: commands.Context = None):\n embed = discord.Embed()\n if ctx:\n embed.colour = await ctx.embed_colour\n else:\n embed.colour = 0x00ffff\n return embed # This was shorter than I thought...\n\n async def upload_embed_parser(\n self, ctx: commands.Context, name: str, glob: bool = False\n ):\n if glob:\n embeds = await self.config.get_raw(\"embeds\")\n else:\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n\n if name in embeds.keys():\n await ctx.send(f\"An embed with the name {name} already exists!\")\n return\n\n if len(ctx.message.attachments) < 1:\n await ctx.send(\"You need to have a `json` file uploaded when using this command!\")\n return\n parsed = await parsers.parse_embed(ctx.message.attachments)\n if parsed == None:\n await ctx.send(\"The type of a file for embeds needs to end with `.json`!\")\n return\n elif type(parsed) == str:\n await ctx.send(parsed)\n return\n await ctx.send(embed=parsed)\n embeds[name] = parsed.to_dict()\n if glob:\n await self.config.set_raw('embeds', value=embeds)\n return\n await self.config.guild(ctx.guild).set_raw(\"embeds\", value=embeds)\n\n async def create_embed(self, ctx: commands.Context, name: str, title: str, description: str, glob: bool):\n \"\"\"Create an embed that's either global or guild\"\"\"\n if glob:\n embeds = await self.config.get_raw(\"embeds\")\n else:\n embeds = await self.config.guild(ctx.guild).get_raw(\"embeds\")\n\n if name in embeds.keys():\n await ctx.send(f\"An embed with the name `{name}` already exists!\")\n return\n\n embed = await self.default_embed()\n embed.title = title\n embed.description = description\n log.info(embed)\n\n await ctx.send(embed=embed)\n embeds[name] = embed.to_dict()\n if glob:\n await self.config.embeds.set(embeds)\n else:\n await self.config.guild(ctx.guild).embeds.set(embeds)\n","sub_path":"embedder/embedder.py","file_name":"embedder.py","file_ext":"py","file_size_in_byte":10947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"215915017","text":"# Import required library's or files\r\nimport discord as dc\r\nfrom discord.ext import commands as cmd\r\nfrom config import token\r\n\r\n# Create list with extensions in it.\r\nEXTENSIONS = ['Main', 'EmojiLogger']\r\n\r\n# Create Class for the bot to start in.\r\nclass Reaction(cmd.Bot):\r\n # Bot init setup\r\n def __init__(self):\r\n prefixes = ['!']\r\n super().__init__(command_prefix=cmd.when_mentioned_or(*prefixes),\r\n description='Reaction',\r\n help_attrs=dict(hidden=True))\r\n self.token = token\r\n self.remove_command('help')\r\n\r\n # Select an item in the list we created and try to load it.\r\n for extension in EXTENSIONS:\r\n try:\r\n full = 'extensions.' + extension\r\n self.load_extension(full)\r\n except Exception as e: print('An error occurred while trying to load the \"{}\" extension.\\n{}: {}'.format(extension,\r\n type(e).__name__, e))\r\n \r\n # Setup message when the bot starts!\r\n async def on_ready(self):\r\n print(f'------------\\nLogged in as:\\nUsername: {self.user.name}\\nID: {self.user.id}\\n------------')\r\n\r\n #check if the message author is a bot & process the message. (check if a command is in it ect)\r\n async def on_message(self, message):\r\n if message.author.bot: return\r\n await self.process_commands(message)\r\n\r\n # run the bot\r\n def run(self):\r\n super().run(self.token, reconnect=True)\r\n\r\n\r\nif __name__ == '__main__':\r\n bot_Reaction = Reaction()\r\n bot_Reaction.run()\r\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"204684518","text":"#==============================================================================\n# \n# License for using the Keras pretrained model in Line 71\n# \n# MIT License\n# \n# Copyright (c) 2016 François Chollet\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\nfrom styx_msgs.msg import TrafficLight\nfrom keras.models import Model,load_model\nimport tensorflow as tf\nimport numpy as np\nfrom keras import backend as K\nfrom keras.applications.inception_v3 import preprocess_input\nimport rospy\nimport scipy\nimport cv2\nimport time\nfrom scipy.misc import imsave\nimport os\n\ndef categorical_crossentropy_with_weights(y_true, y_pred):\n class_weights = tf.constant(np.array([1.,1.,0.001], dtype=np.float32))\n weighted_y_true = tf.multiply(y_true, class_weights)\n \n return K.categorical_crossentropy(weighted_y_true, y_pred)\n \ndef preprocess_im_correct(image_1,flipper,tc,bc,lc,rc):\n \n re_img = image_1[tc:image_1.shape[0]-bc,lc:image_1.shape[1]-rc,:]\n if(flipper==1):\n re_img = np.fliplr(re_img)\n re_img = scipy.misc.imresize(re_img, [512,512,3])\n re_img = re_img/255.\n\n return re_img\n\ndef prepare_im_test(img):\n \n img = preprocess_im_correct(img,0,0,0,0,0)\n \n img = np.reshape(img,(1,img.shape[0],img.shape[1],img.shape[2]))\n \n return img\n \nclass TLClassifier(object):\n def __init__(self):\n #TODO load classifier\n self.unet = load_model('./../../../weights/concise_weights.19.h5', custom_objects={'categorical_crossentropy_with_weights': categorical_crossentropy_with_weights})\n self.unet._make_predict_function()\n self.graph_unet = tf.get_default_graph()\n self.Resnet = load_model('./../../../weights/InceptionV3_keras.h5')\n self.Resnet._make_predict_function()\n self.graph_Resnet = tf.get_default_graph()\n self.light_color_dict = {'Red':TrafficLight.RED,'Green':TrafficLight.GREEN,'No light':TrafficLight.UNKNOWN}\n\n pass\n \n def return_preds(self,img):\n \n x = np.expand_dims(img, axis=0)\n x = preprocess_input(x)\n \n with self.graph_Resnet.as_default():\n preds = self.Resnet.predict(x)\n \n #preds = self.Resnet.predict(x)\n \n return preds\n def return_best_rect(self,img,img_to_imprint):\n img = img*255\n img = img.astype(np.uint8)\n ret,thresh = cv2.threshold(img,127,255,0)\n _,contours,hierarchy = cv2.findContours(thresh, 1, 2)\n best_prob = 0.1\n best_rect = [0,0,0,0]\n light_found = False\n for cnt in contours:\n x,y,w,h = cv2.boundingRect(cnt)\n if(w>=10 and h>=20):\n patch_image = img_to_imprint[y:y+h,x:x+w,:]\n patch_image = scipy.misc.imresize(patch_image, [224,224,3])\n patch_image = patch_image.astype(np.float16)\n \n tl_prob = self.return_preds(patch_image)[0,920]\n \n if(tl_prob>=best_prob):\n best_rect = [x,y,w,h] \n best_prob = tl_prob\n light_found = True\n \n return best_rect,light_found \n def detect_traffic_light_color(self,img):\n \n threshold = 0.95\n \n with self.graph_unet.as_default():\n pred_mask = self.unet.predict(img)\n \n\n \n pred_mask = np.reshape(pred_mask,(512,512,3))\n \n #Green mask\n green_mask = pred_mask[:,:,0]\n\n green_mask[green_mask=threshold] = 1.0\n \n #Red mask\n red_mask = pred_mask[:,:,1]\n \n red_mask[red_mask=threshold] = 1.0\n \n boundary_mask = red_mask+green_mask\n \n [x,y,w,h],lf = self.return_best_rect(boundary_mask,np.copy(img[0]))\n class_mask = np.argmax(pred_mask,axis=2)[y:y+h,x:x+w]\n \n green_tl = np.sum(class_mask==0)\n red_tl = np.sum(class_mask==1)\n \n \n \n if(lf):\n if(green_tl>red_tl):\n light_color = 'Green'\n else:\n light_color = 'Red'\n else:\n light_color = 'No light'\n \n return light_color\n def get_classification(self, image):\n \"\"\"Determines the color of the traffic light in the image\n\n Args:\n image (cv::Mat): image containing the traffic light\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n \n im_arr = np.asarray(image)\n im_arr = prepare_im_test(im_arr)\n lc = self.detect_traffic_light_color(im_arr)\n\n \n return self.light_color_dict[lc]\n","sub_path":"ros/src/tl_detector/light_classification/tl_classifier.py","file_name":"tl_classifier.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"296190822","text":"\"\"\"Gather figures (to be included in thesis).\"\"\"\n\nimport os\nimport pathlib\nimport shutil\n\n\nrootdir = pathlib.Path(__file__).absolute().parents[1]\nn_parts = len(rootdir.parts)\n\n# Create the output directory.\nfigdir = rootdir / 'figures_thesis'\nfigdir.mkdir(parents=True, exist_ok=True)\n\n# Load paths of figures to gather.\ninpath = rootdir / 'misc' / 'figures_thesis.txt'\nfilepaths = []\nwith open(inpath, 'r') as infile:\n filepaths = [rootdir / line.strip() for line in infile.readlines()\n if not line.startswith('#')]\n\n# Define new names of the output figures.\nfilenames = []\nfor filepath in filepaths:\n filename, filedir = filepath.name, filepath.parent\n prefix = '_'.join([e for e in filedir.parts[n_parts + 2:]\n if e not in ['figures', 'run']])\n filenames.append('_'.join([prefix, filename]).lstrip('_'))\n\n# Copy figures to output directory.\nfor filepath, filename in zip(filepaths, filenames):\n shutil.copy(filepath, figdir / filename)\n","sub_path":"misc/figures_thesis.py","file_name":"figures_thesis.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"134521890","text":"import serial\nimport socket, sys, time\nimport MySQLdb as db\nimport urllib2\n\n\n\nclass DataController:\n \n # Initializing the attributes\n def __init__(self): \n self.MoistThreshold = 0.00\n self.RainThreshold = 0.00\n\n\n\n # sets the moisture limit threshold if the value is valid and assigns it to the attribute MoistThreshold\n def setMoistThreshold(self, value):\n value = float(value)\n if ((value >= 0) and (value <= 100)):\n self.MoistThreshold = value\n return True\n else: \n return False\n \n \n # sets the rain limit threshold if the value is valid and assigns it to the attribute RainThreshold\n def setRainThreshold(self, value):\n value = float(value)\n if ((value >= 0) and (value <= 100)):\n self.RainThreshold = value\n return True\n else: \n return False\n \n \n #checks if it is raining or not \n def isRaining(self, rainValue):\n if ((rainValue >= self.RainThreshold) and (rainValue <= 100)):\n return True\n else: \n return False\n \n \n #checks if it is raining or not \n def isMoist(self, moistValue):\n if ((moistValue >= self.MoistThreshold) and (moistValue <= 100)):\n return True\n else: \n return False \n\n\n\n\n\n# ================== MAIN ================== #\n \ndc = DataController()\ndc.setMoistThreshold(5.00)\ndc.setRainThreshold(35.00)\n \n\n# UDP setup\nhost = \"10.0.0.21\"\ntextport = 2004\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nport = int(textport)\nserver_address = (host, port)\n\n\n# Arduino USB serial setup\nser = serial.Serial('/dev/ttyACM0', 9600)\n\n\n# Database connection setup\nconn = db.connect('localhost', 'datacontrol', '123', 'smart_watering')\n\n\n# Main loop\nwhile 1:\n \n # Read the data printed from the Arduino to the serial\n str = ser.readline().decode(\"utf-8\") # Receive the sensor values in the format \"xx:yy\", where xx is the soil value, yy is the rain\n soil, rain = str.split(\":\") # Split the string into the 2 variabes at the \":\"\n soil = float(soil) # Cast as float for inserting into db\n rain = float(rain)\n print(\"\\nSoil: %.2f\" % soil)\n print(\"Rain: %.2f\" % rain)\n \n \n\n # Send instruction to Server.py based on data \n if (not dc.isRaining(rain)) and (not dc.isMoist(soil)):\n print(\"Not raining, Soil not moist\")\n data = \"ManualOpen\"\n s.sendto(data.encode('utf-8'), server_address)\n \n elif (dc.isRaining(rain)) and (dc.isMoist(soil)):\n print(\"Raining, Soil is moist\")\n data = \"RainLimPassed\"\n s.sendto(data.encode('utf-8'), server_address) \n \n elif dc.isRaining(rain):\n print(\"Raining, Soil not moist\")\n data = \"RainLimPassed\"\n s.sendto(data.encode('utf-8'), server_address)\n \n elif dc.isMoist(soil):\n print(\"Not raining, Soil is moist\")\n data = \"MoistureLimPassed\"\n s.sendto(data.encode('utf-8'), server_address)\n \n else:\n print(\"Error\")\n \n \n \n # Enter rain/moisture data into database\n with conn:\n \n cur = conn.cursor()\n cur.execute(\"INSERT INTO rain_log VALUES(CURDATE(), CURTIME(), %f, %f)\" % (rain, dc.RainThreshold)) # insert rain data into rain_log\n cur.execute(\"INSERT INTO moist_log VALUES(CURDATE(), CURTIME(), %f, %f)\" % (soil, dc.MoistThreshold)) # insert soil data into moist_log\n\n\n \n \n \n ","sub_path":"latest version/Data4.py","file_name":"Data4.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"88563937","text":"from google.appengine.api.urlfetch_errors import DownloadError\nfrom gaesessions import get_current_session\n__author__ = 'ankur'\n\n\nimport hmac\nimport json\nimport trainConstants\nfrom google.appengine.api import urlfetch\n\n\ndef generateHash():\n\n digest_maker = hmac.new('f707f95d07aa0f270d07bf71c74dc915')\n digest_maker.update('NDLSCnB10-03-20161Atimejson14c98f7aca50827374ab773844a9ca1b')\n return digest_maker.hexdigest();\n\ntrainNumberstoDurationMap ={}\n\ndef parseTrainBetweenStationsAndReturnTrainNumber(jsonData):\n returnedData = json.loads(jsonData.content)\n trainNumbers = []\n global trainNumberstoDurationMap\n for train in returnedData[\"train\"] :\n trainNumbers.append(train[\"number\"])\n trainNumberstoDurationMap[train[\"number\"]]={}\n trainNumberstoDurationMap[train[\"number\"]][\"departure\"]=train[\"src_departure_time\"]\n trainNumberstoDurationMap[train[\"number\"]][\"arrival\"]=train[\"dest_arrival_time\"]\n trainNumberstoDurationMap[train[\"number\"]][\"duration\"]=train[\"travel_time\"]\n trainNumberstoDurationMap[train[\"number\"]][\"srcStation\"]=train[\"from\"][\"code\"]\n trainNumberstoDurationMap[train[\"number\"]][\"destStation\"]=train[\"to\"][\"code\"]\n\n return trainNumbers\n\n\ndef parseAndReturnFare(jsonData,trainCounter):\n route={}\n try:\n\n returnedFareData = json.loads(jsonData.content)\n\n session = get_current_session()\n if len(returnedFareData[\"fare\"])!=0:\n full={}\n full[\"carrierName\"]=returnedFareData[\"train\"][\"name\"]\n full[\"price\"]=returnedFareData[\"fare\"][0][\"fare\"]\n full[\"duration\"]=trainNumberstoDurationMap[returnedFareData[\"train\"][\"number\"]][\"duration\"]\n full[\"id\"]= \"train\"+str(trainCounter)\n full[\"mode\"]=\"train\"\n full[\"site\"]=\"IRCTC\"\n full[\"source\"]=session['source']\n full[\"destination\"]=session['destination']\n full[\"arrival\"]=trainNumberstoDurationMap[returnedFareData[\"train\"][\"number\"]][\"arrival\"]\n full[\"departure\"]=trainNumberstoDurationMap[returnedFareData[\"train\"][\"number\"]][\"departure\"]\n route[\"full\"]=[]\n route[\"parts\"]=[]\n route[\"full\"].append(full)\n parts=full\n parts[\"id\"]=\"train\"+str(trainCounter)+str(1)\n route[\"parts\"].append(parts)\n except ValueError:\n return route\n return route\n\n\nclass PlaceToStationCodesCache:\n \"\"\"Class returs all stations corresponding to a city\"\"\"\n\n cityToStationsMap={}\n\n\n def parseStationNameToStationCodes(self,jsonData):\n returnedData = json.loads(jsonData.content)\n stationList=[]\n if returnedData[\"response_code\"]==200:\n for station in returnedData[\"stations\"]:\n stationList.append(station[\"code\"])\n\n return stationList\n\n def getStationsByCode(self,stationName):\n if stationName in PlaceToStationCodesCache.cityToStationsMap:\n return self.cityToStationsMap[stationName]\n else:\n jsonResponseNameToCode = urlfetch.fetch(\"http://api.railwayapi.com/name_to_code/station/\"+ stationName + \"/apikey/\" + trainConstants.ERAILWAYAPI_APIKEY + \"/\",method=urlfetch.GET, deadline=45)\n stationList = self.parseStationNameToStationCodes(jsonResponseNameToCode)\n if stationList:\n PlaceToStationCodesCache.cityToStationsMap[stationName]=stationList\n return stationList\n\n\nclass TrainController:\n \"\"\"Entry point to get all routes with train as the major mode of transport\"\"\"\n placetoStationCodesCache = PlaceToStationCodesCache()\n\n def getTrainBetweenStations(self,sourceStation,destinationStation,journeyDate):\n try:\n jsonResponseTrainBetweenStations = urlfetch.fetch(\"http://api.railwayapi.com/between/source/\"+ sourceStation + \"/dest/\" + destinationStation+ \"/date/\" + journeyDate +\"/apikey/\"+ trainConstants.ERAILWAYAPI_APIKEY +\"/\",method=urlfetch.GET, deadline=45)\n availableTrainNumbers = parseTrainBetweenStationsAndReturnTrainNumber(jsonResponseTrainBetweenStations)\n return availableTrainNumbers\n except DownloadError:\n return []\n\n def getTrainFare(self,sourceStation,destinationStation,journeyDate,trainNumber,trainCounter,resultJsonData):\n try:\n jsonResponseTrainFare = urlfetch.fetch(\"http://api.railwayapi.com/fare/train/\" + trainNumber + \"/source/\"+ sourceStation+ \"/dest/\"+ destinationStation+ \"/age/18/quota/GN/doj/\"+ journeyDate+ \"/apikey/\"+trainConstants.ERAILWAYAPI_APIKEY +\"/\",method=urlfetch.GET, deadline=45)\n fareData=parseAndReturnFare(jsonResponseTrainFare,trainCounter)\n if not fareData:\n pass\n else:\n resultJsonData[\"train\"].append(fareData)\n except DownloadError:\n pass\n\n def findTrainsBetweenStations(self,sourceStationList,destinationStationList,journeyDate):\n resultJsonData = {}\n resultJsonData[\"train\"]=[]\n availableTrainNumbers=set([])\n hack =0\n for sourceStation in sourceStationList:\n if hack==0:\n for destinationStation in destinationStationList:\n availableTrainNumbersList = self.getTrainBetweenStations(sourceStation,destinationStation,journeyDate)\n availableTrainNumbers = availableTrainNumbers.union(availableTrainNumbersList)\n hack=1\n trainCounter=0\n\n for trainNumber in availableTrainNumbers:\n trainCounter=trainCounter+1\n if trainCounter<10:\n self.getTrainFare(trainNumberstoDurationMap[trainNumber][\"srcStation\"],trainNumberstoDurationMap[trainNumber][\"destStation\"],journeyDate,trainNumber,trainCounter,resultJsonData)\n\n return resultJsonData\n\n\n def getRoutes(self,source,destination,dateOfJourney):\n urlfetch.set_default_fetch_deadline(45)\n sourceStations = self.placetoStationCodesCache.getStationsByCode(source)\n destinationStations = self.placetoStationCodesCache.getStationsByCode(destination)\n if not sourceStations or not destinationStations:\n return\n else:\n return self.findTrainsBetweenStations(sourceStations,destinationStations,dateOfJourney)\n\n\n\n","sub_path":"GoIndi/trainapi.py","file_name":"trainapi.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"230946913","text":"def album(\n nome_artista: str, titulo_album: str, n_faixas: int = 0) -> dict:\n \"\"\"\n -> Constrói um dicionário descrevendo um álbum musical\n contendo o nome do artista, o título do álbum e se fornecido,\n o número de faixas do álbum.\n :param nome_artista: O nome do artista.\n :param titulo_album: O título do álbum.\n :param n_faixas: (Opcional) O número de faixas do álbum.\n :return: Retorna um dicionário que contém o nome do artista,\n o título do álbum e se fornecido, o número de faixas como valores.\n \"\"\"\n album_musical = {'artista': nome_artista, 'album': titulo_album}\n if n_faixas:\n album_musical['n_faixas'] = n_faixas\n\n return album_musical\n\n\nalbum_1 = album('slipknot', 'iowa')\nprint(album_1)\nalbum_2 = album('flobots', 'fight with tools')\nprint(album_2)\nalbum_3 = album('alt-j', 'this is all yours')\nprint(album_3)\nalbum_4 = album('gorillaz', 'demon days', 15)\nprint(album_4)\n","sub_path":"capitulo_08/exercicios/album.py","file_name":"album.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"540120128","text":"import os, re, shutil\n# 移动文件的MoveFile类\nclass MoveFile(object):\n def __init__(self, srcDir, dstDir, recursive=True, flag='.DOC'):\n self.srcDir = srcDir # 源目录\n self.dstDir = dstDir # 目标目录\n self.recursive = recursive # 递归查找文件夹,默认为False,只查找源目录下的文件,不会递归查找其子文件夹\n self.flag = flag # 要匹配的文件类型 '.DOC'-doc文件\n self.duplicateFileName = [] # 捕获重复移动文件,即目标文件中已存在此文件\n self.badFileName = [] # 文件类型符合要求,但命名不符合要求\n self.docFile = [] # 捕获的jpg文件\n self.srcDirDict = {} # 当递归查找时,记录文件的root目录,在移动时使用\n # 找到给定类型(flag)的文件\n def findAllDOC(self):\n # recursively find file \n if self.recursive == False: \n for item in os.listdir(self.srcDir):\n if os.path.isfile(os.path.join(self.srcDir,item)) and \\\n os.path.splitext(item)[-1] == self.flag.lower():\n self.docFile.append(item)\n else:\n for root, dirs, files in os.walk(self.srcDir):\n for item in files:\n if os.path.splitext(item)[-1] == self.flag.lower():\n self.docFile.append(item)\n print(root)\n self.srcDirDict[item] = root\n\n if not self.docFile:\n print('NOT FIND ANY DOC FILE!')\n return self.docFile\n # 使用正则表达式匹配\n # def parse(self, text):\n # try:\n # pat =re.compile('[\\s\\S]*')\n # match = pat.match(text)\n # data = match.group(1)\n # fileName = data[:4]+'-'+data[4:6]\n # except:\n # self.badFileName.append(text)\n # fileName = None\n # return fileName\n # 移动\n def move(self, text):\n try:\n fileName = text\n # if fileName == None: return\n # if not os.path.isdir(os.path.join(self.dstDir, fileName)):# 判断主目录是否存在子文件夹\n # os.mkdir(os.path.join(self.dstDir,fileName))\n\n srcPath= os.path.join(self.srcDirDict[text], text)\n dstDir = os.path.join(self.dstDir, fileName)\n shutil.copy(srcPath, dstDir)\n except:\n self.duplicateFileName.append(text)\n raise\n\n @staticmethod\n def decC(dir):\n return os.path.join(self.srcDir, dir)\n # 运行\n def run(self):\n try:\n if not os.path.isdir(self.dstDir):\n os.mkdir(self.dstDir)\n for text in self.findAllDOC():\n print(text)\n self.move(text)\n print('MOVE SUCCESSFUL!') \n except TypeError:\n raise\n# 例子: 将srcDir中的符合parse要求的doc文件移动到dstDir\nsrcDir = r'D:\\wuhan'\ndstDir = r'D:\\wuhandoc'\nfmv = MoveFile(srcDir, dstDir, recursive = True)\nfmv.run()\n","sub_path":"tool/copyfile2dic.py","file_name":"copyfile2dic.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"614181148","text":"import numpy as np\nimport math\n\nclass S_Codebook():\n\n def __init__(self, Lv, N_sp, M_r ):\n \"\"\"\n Inicialize the codebook\n :param Lv: Dimention of the space\n :param N_sp: Number of point for each pi arch\n :param M_r: Number of codewords in the gain (radius) codebook\n \"\"\"\n self.Lv = Lv\n self.N_sp = N_sp\n self.M_r = M_r\n\n # Compute the angular distance between two centroids in a pi arch (all expcept the last one)\n self.theta = math.pi/N_sp\n\n # Initialize the sin and cos dictionaries *(to improve the computation efficiency)\n self.sin_d = self.init_sin_dic()\n self.cos_d = self.init_cos_dic()\n\n # Initialize the spherical codebook\n \n self.centroids_count = 0\n self.c_indx_to_coords = {}\n # peelist: List contaning \n self.centroids, self.peelist = self.init_centroids(self.c_indx_to_coords)\n self.c_indx_to_cart = self.init_cartesians_dic()\n self.c_indx_to_angles = self.init_angle_dic()\n\n\n def preselection(self, d0):\n \"\"\"\n Gets the candidates to be quantized given the vector d0. To do so w\n :param d0: <[floats]> vector to be quantized\n :return: <[int]> a list containing the indexes (int) referring to the candidates centroids\n \"\"\"\n candidates = []\n # 1 - Normalize the vector\n d0_norm = np.linalg.norm(d0)\n c0 = d0/d0_norm\n # 2 - Convert the vector to spherical coordinates\n _, sph_c0 = self.cartesian2spherical(c0)\n # 3 - Select the candidiates making use of the peelist\n peeling_centroids = self.centroids\n\n def search(values,lists):\n cand = []\n # Check if we are on the last layer of the lists:\n # At this stage the list would be as:\n # list = [[phi1,cent1],[phi2,cent2],...]\n # values = [phiL]\n if type(lists[0][1]) is not list:\n for i in range(len(lists)):\n if values[0] <= lists[i][0]:\n cand.append(lists[i][1])\n cand.append(lists[i-1][1])\n else:\n # If we aren't still on the last layer:\n if values[0] < lists[0][0]:\n cand = search(values[1:], lists[0][1])\n elif values[0] > lists[-1][0]:\n cand = search(values[1:], lists[-1][1])\n else:\n for i in range(len(lists)-1):\n if lists[i][0] <= values[0] <= lists[i+1][0]:\n cand_rec_1 = search(values[1:], lists[i][1])\n cand_rec_2 = search(values[1:], lists[i][1])\n cand = cand + cand_rec_1 + cand_rec_2\n break\n return cand\n\n candidates = search(sph_c0, self.peelist)\n\n return candidates\n\n ## INITIALIZE FUNCTIONS:\n\n def init_centroids(self, d, lv_i=0, previous=()):\n \"\"\"\n Initialize the centroids of the shape codebook. This is done following the apple-peeling method\n It stores the result in the c parameter\n :param d: dictionary with centroid index as a key and the dimension's coordinates as value\n :param lv_i: current dimension of the apple-peeling process\n :param previous: index of the previous dimension\n :return:\n centroids parameter: centroids list where the centroids are stored\n peelist: <[[float,list],[float, list],...]> list formed by pairs of angles (floats) and lists\n each sublist if formed by another list of the same type\n it turns to have the following shape: [float,...[[float, int],[float, int]...]..]>\n \"\"\"\n # Number of angles -> Lv - 1\n if lv_i < self.Lv - 2 :\n peelist = []\n c = []\n for i in range(self.N_sp):\n phi_0 = (i + 0.5) * self.theta\n # Call the same function to compute recursively\n c_i, pl_i = self.init_centroids(d, lv_i + 1, previous=previous + (i,))\n # Add elements in the list\n c.append(c_i)\n peelist.append([phi_0, pl_i])\n return c, peelist\n else:\n # The last layer of the apple peeling method\n phi_p = (previous[-1] + 0.5)*self.theta\n Nspl = self.get_Nspl(phi_p)\n coords_last_layer = []\n last_layer_peelist = []\n for i in range(Nspl):\n coords_last_layer.append(self.centroids_count)\n d[self.centroids_count] = previous + (i,)\n phi_last = (i + 0.5) * 2 * math.pi / Nspl\n last_layer_peelist.append([phi_last, self.centroids_count])\n self.centroids_count += 1\n return coords_last_layer, last_layer_peelist\n\n def init_cartesians_dic(self):\n \"\"\"\n Function to create a dictionary with centroids indexes as keys and a list of cartesian coordenates as values\n :return: <{int:(float)}> Dictionary\n keys: Centroids indexes\n values: List containing the cartesian coordenates\n \"\"\"\n # Make use of the already created dictionary containing the centroid indexes and angle indexes (coords)\n d = self.c_indx_to_coords\n cartesians_dic = {}\n for k, coords in d.items():\n cartesians = ()\n # For all the components except the last 2 we make use of the already computed values of sin and cos\n for i, c in enumerate(coords[:-1]):\n res = 1\n for j in range(i):\n res *= self.sin_d[coords[i]]\n res = res * self.cos_d[c]\n cartesians = cartesians + (res,)\n res = 1\n # For the last 2 coordinate we need to compute the last angle (phi_p) as it is different form the rest\n for j in range(len(coords)-1):\n res *= self.sin_d[coords[j]]\n phi_p = (coords[-1] + 0.5) * 2 * math.pi / self.get_Nspl((coords[-2] + 0.5)*self.theta)\n rn_1 = res * math.cos(phi_p)\n rn = res * math.sin(phi_p)\n cartesians = cartesians + (rn_1, rn)\n cartesians_dic[k] = cartesians\n\n return cartesians_dic\n\n\n\n def init_angle_dic(self,):\n d = self.c_indx_to_coords\n angle_dic = {}\n for k, coords in d.items():\n angles = ()\n for i, c in enumerate(coords[:-1]):\n a = (c + 0.5)*self.theta\n angles += (a,)\n phi_p = (coords[-1] + 0.5) * 2 * math.pi / self.get_Nspl((coords[-2] + 0.5) * self.theta)\n angles += (phi_p,)\n angle_dic[k] = angles\n return angle_dic\n\n def init_sin_dic(self):\n \"\"\"\n Initialize a dictionary containing the sin of all the predefined angles\n :return: <{int : float}> Dictionary with\n key: angle index\n value: sin of that angle\n \"\"\"\n d = {}\n for i in range(self.N_sp):\n d[i]=math.sin((i + 0.5)*self.theta)\n return d\n\n def init_cos_dic(self):\n \"\"\"\n Initialize a dictionary containing the cos of all the predefined angles\n :return: <{int : float}> Dictionary with\n key: angle index\n value: cos of that angle\n \"\"\"\n d = {}\n for i in range(self.N_sp):\n d[i] = math.cos((i + 0.5)*self.theta)\n return d\n\n\n ## GETTERS & AUXILIAR FUNCTIONS:\n\n def get_Nspl(self, phi_i):\n \"\"\"\n Auxiliar function to compute the number of centroids in the last layer\n (centroids equally distributed along a circle)\n :param phi_i: Value of the angle form the previous apple-peeling layer coordinate\n :return: Number of centroids for that layer\n \"\"\"\n N_sp_l = int(2 * math.pi / self.theta * math.sin(phi_i))\n return N_sp_l\n\n def get_centroids(self):\n return self.centroids\n\n def get_coords(self, index):\n return self.c_indx_to_coords[index]\n\n def get_cartesians_dic(self):\n return self.c_indx_to_cart\n\n def cartesian2spherical(self, c0):\n \"\"\"\n Converts the vector to is spherical equivalent\n :param c0: cartesian n-dimensional vector\n :return: modulus, n-1-dimensional list containing the spherical coordinates\n \"\"\"\n # TODO: Debugg division by Zero and ANGLES!!!!!!!\n sph_coords = () # Vector containing the angles\n modulus = np.linalg.norm(c0)\n for i, c in enumerate(c0[:-2]):\n mod_i = np.linalg.norm(c0[i:])\n phi_i = math.acos(c/mod_i)\n sph_coords += (phi_i,)\n # Last angle:\n last_mod = np.linalg.norm(c0[-2:])\n # Check divison by zero case:\n if c0[-2] == 0 and last_mod == 0:\n if c0[-1] >= 0:\n phi_l = math.acos(0)\n else:\n phi_l = 2*math.pi-math.acos(0)\n else:\n if c0[-1] >= 0:\n phi_l = math.acos(c0[-2] / last_mod)\n else:\n phi_l = 2*math.pi-math.acos(c0[-2] / last_mod)\n sph_coords += (phi_l,)\n\n return modulus, sph_coords\n\n","sub_path":"Spherical_Codebook.py","file_name":"Spherical_Codebook.py","file_ext":"py","file_size_in_byte":9376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"520192841","text":"# -*- coding: utf-8 -*-\nimport pytest\nfrom unittest import mock\n\nfrom django.core.exceptions import ValidationError\n\nfrom awx.api.versioning import reverse\n\nfrom awx.main.models import InventorySource, Inventory, ActivityStream\n\nimport json\n\n\n@pytest.fixture\ndef scm_inventory(inventory, project):\n with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):\n inventory.inventory_sources.create(\n name='foobar', update_on_project_update=True, source='scm',\n source_project=project, scm_last_revision=project.scm_revision)\n return inventory\n\n\n@pytest.fixture\ndef factory_scm_inventory(inventory, project):\n def fn(**kwargs):\n with mock.patch('awx.main.models.unified_jobs.UnifiedJobTemplate.update'):\n return inventory.inventory_sources.create(source_project=project,\n overwrite_vars=True,\n source='scm',\n scm_last_revision=project.scm_revision,\n **kwargs)\n return fn\n\n\n@pytest.mark.django_db\ndef test_inventory_source_notification_on_cloud_only(get, post, inventory_source_factory, user, notification_template):\n u = user('admin', True)\n\n cloud_is = inventory_source_factory(\"ec2\")\n cloud_is.source = \"ec2\"\n cloud_is.save()\n\n not_is = inventory_source_factory(\"not_ec2\")\n\n url = reverse('api:inventory_source_notification_templates_any_list', kwargs={'pk': cloud_is.id})\n response = post(url, dict(id=notification_template.id), u)\n assert response.status_code == 204\n\n url = reverse('api:inventory_source_notification_templates_success_list', kwargs={'pk': not_is.id})\n response = post(url, dict(id=notification_template.id), u)\n assert response.status_code == 400\n\n\n@pytest.mark.django_db\ndef test_inventory_source_unique_together_with_inv(inventory_factory):\n inv1 = inventory_factory('foo')\n inv2 = inventory_factory('bar')\n is1 = InventorySource(name='foo', source='file', inventory=inv1)\n is1.save()\n is2 = InventorySource(name='foo', source='file', inventory=inv1)\n with pytest.raises(ValidationError):\n is2.validate_unique()\n is2 = InventorySource(name='foo', source='file', inventory=inv2)\n is2.validate_unique()\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 200),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_edit_inventory(put, inventory, alice, role_field, expected_status_code):\n data = { 'organization': inventory.organization.id, 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(inventory, role_field).members.add(alice)\n put(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.django_db\ndef test_async_inventory_deletion(delete, get, inventory, alice):\n inventory.admin_role.members.add(alice)\n resp = delete(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), alice)\n assert resp.status_code == 202\n assert ActivityStream.objects.filter(operation='delete').exists()\n\n resp = get(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), alice)\n assert resp.status_code == 200\n assert resp.data.get('pending_deletion') is True\n\n\n@pytest.mark.django_db\ndef test_async_inventory_duplicate_deletion_prevention(delete, get, inventory, alice):\n inventory.admin_role.members.add(alice)\n resp = delete(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), alice)\n assert resp.status_code == 202\n\n resp = delete(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), alice)\n assert resp.status_code == 400\n assert resp.data['error'] == 'Inventory is already pending deletion.'\n\n\n@pytest.mark.django_db\ndef test_async_inventory_deletion_deletes_related_jt(delete, get, job_template, inventory, alice, admin):\n job_template.inventory = inventory\n job_template.save()\n assert job_template.inventory == inventory\n inventory.admin_role.members.add(alice)\n resp = delete(reverse('api:inventory_detail', kwargs={'pk': inventory.id}), alice)\n assert resp.status_code == 202\n\n resp = get(reverse('api:job_template_detail', kwargs={'pk': job_template.id}), admin)\n jdata = json.loads(resp.content)\n assert jdata['inventory'] is None\n\n\n@pytest.mark.parametrize('order_by', ('script', '-script', 'script,pk', '-script,pk'))\n@pytest.mark.django_db\ndef test_list_cannot_order_by_unsearchable_field(get, organization, alice, order_by):\n for i, script in enumerate(('#!/bin/a', '#!/bin/b', '#!/bin/c')):\n custom_script = organization.custom_inventory_scripts.create(\n name=\"I%d\" % i,\n script=script\n )\n custom_script.admin_role.members.add(alice)\n\n get(reverse('api:inventory_script_list'), alice,\n QUERY_STRING='order_by=%s' % order_by, expect=403)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 201),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_create_inventory_group(post, inventory, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(inventory, role_field).members.add(alice)\n post(reverse('api:inventory_groups_list', kwargs={'pk': inventory.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 201),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_create_inventory_group_child(post, group, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(group.inventory, role_field).members.add(alice)\n post(reverse('api:group_children_list', kwargs={'pk': group.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 200),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_edit_inventory_group(put, group, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(group.inventory, role_field).members.add(alice)\n put(reverse('api:group_detail', kwargs={'pk': group.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 201),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_create_inventory_inventory_source(post, inventory, alice, role_field, expected_status_code):\n data = { 'source': 'ec2', 'name': 'ec2-inv-source'}\n if role_field:\n getattr(inventory, role_field).members.add(alice)\n post(reverse('api:inventory_inventory_sources_list', kwargs={'pk': inventory.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 204),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_delete_inventory_group(delete, group, alice, role_field, expected_status_code):\n if role_field:\n getattr(group.inventory, role_field).members.add(alice)\n delete(reverse('api:group_detail', kwargs={'pk': group.id}), alice, expect=expected_status_code)\n\n\n@pytest.mark.django_db\ndef test_create_inventory_smartgroup(post, get, inventory, admin_user, organization):\n data = { 'name': 'Group 1', 'description': 'Test Group'}\n smart_inventory = Inventory(name='smart',\n kind='smart',\n organization=organization,\n host_filter='inventory_sources__source=ec2')\n smart_inventory.save()\n post(reverse('api:inventory_groups_list', kwargs={'pk': smart_inventory.id}), data, admin_user)\n resp = get(reverse('api:inventory_groups_list', kwargs={'pk': smart_inventory.id}), admin_user)\n jdata = json.loads(resp.content)\n\n assert getattr(smart_inventory, 'kind') == 'smart'\n assert jdata['count'] == 0\n\n\n@pytest.mark.django_db\ndef test_create_inventory_smart_inventory_sources(post, get, inventory, admin_user, organization):\n data = { 'name': 'Inventory Source 1', 'description': 'Test Inventory Source'}\n smart_inventory = Inventory(name='smart',\n kind='smart',\n organization=organization,\n host_filter='inventory_sources__source=ec2')\n smart_inventory.save()\n post(reverse('api:inventory_inventory_sources_list', kwargs={'pk': smart_inventory.id}), data, admin_user)\n resp = get(reverse('api:inventory_inventory_sources_list', kwargs={'pk': smart_inventory.id}), admin_user)\n jdata = json.loads(resp.content)\n\n assert getattr(smart_inventory, 'kind') == 'smart'\n assert jdata['count'] == 0\n\n\n@pytest.mark.django_db\ndef test_urlencode_host_filter(post, admin_user, organization):\n \"\"\"\n Host filters saved on the model must correspond to the same result\n as when that host_filter is used in the URL as a querystring.\n That means that it must be url-encoded patterns like %22 for quotes\n must be escaped as the string is saved to the model.\n\n Expected host filter in this test would match a host such as:\n inventory.hosts.create(\n ansible_facts={\"ansible_distribution_version\": \"7.4\"}\n )\n \"\"\"\n # Create smart inventory with host filter that corresponds to querystring\n post(\n reverse('api:inventory_list'),\n data={\n 'name': 'smart inventory', 'kind': 'smart',\n 'organization': organization.pk,\n 'host_filter': 'ansible_facts__ansible_distribution_version=%227.4%22'\n },\n user=admin_user,\n expect=201\n )\n # Assert that the saved version of host filter has escaped \"\"\n si = Inventory.objects.get(name='smart inventory')\n assert si.host_filter == 'ansible_facts__ansible_distribution_version=\"7.4\"'\n\n\n@pytest.mark.django_db\ndef test_host_filter_unicode(post, admin_user, organization):\n post(\n reverse('api:inventory_list'),\n data={\n 'name': 'smart inventory', 'kind': 'smart',\n 'organization': organization.pk,\n 'host_filter': u'ansible_facts__ansible_distribution=レッドハット'\n },\n user=admin_user,\n expect=201\n )\n si = Inventory.objects.get(name='smart inventory')\n assert si.host_filter == u'ansible_facts__ansible_distribution=レッドハット'\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 201),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_create_inventory_host(post, inventory, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(inventory, role_field).members.add(alice)\n post(reverse('api:inventory_hosts_list', kwargs={'pk': inventory.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 201),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_create_inventory_group_host(post, group, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(group.inventory, role_field).members.add(alice)\n post(reverse('api:group_hosts_list', kwargs={'pk': group.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 200),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_edit_inventory_host(put, host, alice, role_field, expected_status_code):\n data = { 'name': 'New name', 'description': 'Hello world', }\n if role_field:\n getattr(host.inventory, role_field).members.add(alice)\n put(reverse('api:host_detail', kwargs={'pk': host.id}), data, alice, expect=expected_status_code)\n\n\n@pytest.mark.parametrize(\"role_field,expected_status_code\", [\n (None, 403),\n ('admin_role', 204),\n ('update_role', 403),\n ('adhoc_role', 403),\n ('use_role', 403)\n])\n@pytest.mark.django_db\ndef test_delete_inventory_host(delete, host, alice, role_field, expected_status_code):\n if role_field:\n getattr(host.inventory, role_field).members.add(alice)\n delete(reverse('api:host_detail', kwargs={'pk': host.id}), alice, expect=expected_status_code)\n\n\n# See companion test in tests/functional/test_rbac_inventory.py::test_inventory_source_update\n@pytest.mark.parametrize(\"start_access,expected_status_code\", [\n (True, 202),\n (False, 403)\n])\n@pytest.mark.django_db\ndef test_inventory_update_access_called(post, inventory_source, alice, mock_access, start_access, expected_status_code):\n with mock_access(InventorySource) as mock_instance:\n mock_instance.can_start = mock.MagicMock(return_value=start_access)\n post(reverse('api:inventory_source_update_view', kwargs={'pk': inventory_source.id}),\n {}, alice, expect=expected_status_code)\n mock_instance.can_start.assert_called_once_with(inventory_source)\n\n\n@pytest.mark.django_db\ndef test_inventory_source_vars_prohibition(post, inventory, admin_user):\n with mock.patch('awx.api.serializers.settings') as mock_settings:\n mock_settings.INV_ENV_VARIABLE_BLACKLIST = ('FOOBAR',)\n r = post(reverse('api:inventory_source_list'),\n {'name': 'new inv src', 'source_vars': '{\\\"FOOBAR\\\": \\\"val\\\"}', 'inventory': inventory.pk},\n admin_user, expect=400)\n assert 'prohibited environment variable' in r.data['source_vars'][0]\n assert 'FOOBAR' in r.data['source_vars'][0]\n\n\n@pytest.mark.django_db\nclass TestInventorySourceCredential:\n def test_need_cloud_credential(self, inventory, admin_user, post):\n \"\"\"Test that a cloud-based source requires credential\"\"\"\n r = post(\n url=reverse('api:inventory_source_list'),\n data={'inventory': inventory.pk, 'name': 'foo', 'source': 'openstack'},\n expect=400,\n user=admin_user\n )\n assert 'Credential is required for a cloud source' in r.data['credential'][0]\n\n def test_ec2_no_credential(self, inventory, admin_user, post):\n \"\"\"Test that an ec2 inventory source can be added with no credential\"\"\"\n post(\n url=reverse('api:inventory_source_list'),\n data={'inventory': inventory.pk, 'name': 'fobar', 'source': 'ec2'},\n expect=201,\n user=admin_user\n )\n\n def test_validating_credential_type(self, organization, inventory, admin_user, post):\n \"\"\"Test that cloud sources must use their respective credential type\"\"\"\n from awx.main.models.credential import Credential, CredentialType\n openstack = CredentialType.defaults['openstack']()\n openstack.save()\n os_cred = Credential.objects.create(\n credential_type=openstack, name='bar', organization=organization)\n r = post(\n url=reverse('api:inventory_source_list'),\n data={\n 'inventory': inventory.pk, 'name': 'fobar', 'source': 'ec2',\n 'credential': os_cred.pk\n },\n expect=400,\n user=admin_user\n )\n assert 'Cloud-based inventory sources (such as ec2)' in r.data['credential'][0]\n assert 'require credentials for the matching cloud service' in r.data['credential'][0]\n\n def test_vault_credential_not_allowed(self, project, inventory, vault_credential, admin_user, post):\n \"\"\"Vault credentials cannot be associated via the deprecated field\"\"\"\n # TODO: when feature is added, add tests to use the related credentials\n # endpoint for multi-vault attachment\n r = post(\n url=reverse('api:inventory_source_list'),\n data={\n 'inventory': inventory.pk, 'name': 'fobar', 'source': 'scm',\n 'source_project': project.pk, 'source_path': '',\n 'credential': vault_credential.pk\n },\n expect=400,\n user=admin_user\n )\n assert 'Credentials of type insights and vault' in r.data['credential'][0]\n assert 'disallowed for scm inventory sources' in r.data['credential'][0]\n\n def test_vault_credential_not_allowed_via_related(\n self, project, inventory, vault_credential, admin_user, post):\n \"\"\"Vault credentials cannot be associated via related endpoint\"\"\"\n inv_src = InventorySource.objects.create(\n inventory=inventory, name='foobar', source='scm',\n source_project=project, source_path=''\n )\n r = post(\n url=reverse('api:inventory_source_credentials_list', kwargs={'pk': inv_src.pk}),\n data={\n 'id': vault_credential.pk\n },\n expect=400,\n user=admin_user\n )\n assert 'Credentials of type insights and vault' in r.data['msg']\n assert 'disallowed for scm inventory sources' in r.data['msg']\n\n def test_credentials_relationship_mapping(self, project, inventory, organization, admin_user, post, patch):\n \"\"\"The credentials relationship is used to manage the cloud credential\n this test checks that replacement works\"\"\"\n from awx.main.models.credential import Credential, CredentialType\n openstack = CredentialType.defaults['openstack']()\n openstack.save()\n os_cred = Credential.objects.create(\n credential_type=openstack, name='bar', organization=organization)\n r = post(\n url=reverse('api:inventory_source_list'),\n data={\n 'inventory': inventory.pk, 'name': 'fobar', 'source': 'scm',\n 'source_project': project.pk, 'source_path': '',\n 'credential': os_cred.pk\n },\n expect=201,\n user=admin_user\n )\n aws = CredentialType.defaults['aws']()\n aws.save()\n aws_cred = Credential.objects.create(\n credential_type=aws, name='bar2', organization=organization)\n inv_src = InventorySource.objects.get(pk=r.data['id'])\n assert list(inv_src.credentials.values_list('id', flat=True)) == [os_cred.pk]\n patch(\n url=inv_src.get_absolute_url(),\n data={\n 'credential': aws_cred.pk\n },\n expect=200,\n user=admin_user\n )\n assert list(inv_src.credentials.values_list('id', flat=True)) == [aws_cred.pk]\n\n\n@pytest.mark.django_db\nclass TestControlledBySCM:\n '''\n Check that various actions are correctly blocked if object is controlled\n by an SCM follow-project inventory source\n '''\n def test_safe_method_works(self, get, options, scm_inventory, admin_user):\n get(scm_inventory.get_absolute_url(), admin_user, expect=200)\n options(scm_inventory.get_absolute_url(), admin_user, expect=200)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision != ''\n\n def test_vars_edit_reset(self, patch, scm_inventory, admin_user):\n patch(scm_inventory.get_absolute_url(), {'variables': 'hello: world'},\n admin_user, expect=200)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''\n\n def test_name_edit_allowed(self, patch, scm_inventory, admin_user):\n patch(scm_inventory.get_absolute_url(), {'variables': '---', 'name': 'newname'},\n admin_user, expect=200)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision != ''\n\n def test_host_associations_reset(self, post, scm_inventory, admin_user):\n inv_src = scm_inventory.inventory_sources.first()\n h = inv_src.hosts.create(name='barfoo', inventory=scm_inventory)\n g = inv_src.groups.create(name='fooland', inventory=scm_inventory)\n post(reverse('api:host_groups_list', kwargs={'pk': h.id}), {'id': g.id},\n admin_user, expect=204)\n post(reverse('api:group_hosts_list', kwargs={'pk': g.id}), {'id': h.id},\n admin_user, expect=204)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''\n\n def test_group_group_associations_reset(self, post, scm_inventory, admin_user):\n inv_src = scm_inventory.inventory_sources.first()\n g1 = inv_src.groups.create(name='barland', inventory=scm_inventory)\n g2 = inv_src.groups.create(name='fooland', inventory=scm_inventory)\n post(reverse('api:group_children_list', kwargs={'pk': g1.id}), {'id': g2.id},\n admin_user, expect=204)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''\n\n def test_host_group_delete_reset(self, delete, scm_inventory, admin_user):\n inv_src = scm_inventory.inventory_sources.first()\n h = inv_src.hosts.create(name='barfoo', inventory=scm_inventory)\n g = inv_src.groups.create(name='fooland', inventory=scm_inventory)\n delete(h.get_absolute_url(), admin_user, expect=204)\n delete(g.get_absolute_url(), admin_user, expect=204)\n assert InventorySource.objects.get(inventory=scm_inventory.pk).scm_last_revision == ''\n\n def test_remove_scm_inv_src(self, delete, scm_inventory, admin_user):\n inv_src = scm_inventory.inventory_sources.first()\n delete(inv_src.get_absolute_url(), admin_user, expect=204)\n assert scm_inventory.inventory_sources.count() == 0\n\n def test_adding_inv_src_ok(self, post, scm_inventory, admin_user):\n post(reverse('api:inventory_inventory_sources_list', kwargs={'version': 'v2', 'pk': scm_inventory.id}),\n {'name': 'new inv src', 'update_on_project_update': False, 'source': 'scm', 'overwrite_vars': True},\n admin_user, expect=201)\n\n def test_adding_inv_src_prohibited(self, post, scm_inventory, project, admin_user):\n post(reverse('api:inventory_inventory_sources_list', kwargs={'pk': scm_inventory.id}),\n {'name': 'new inv src', 'source_project': project.pk, 'update_on_project_update': True, 'source': 'scm', 'overwrite_vars': True},\n admin_user, expect=400)\n\n def test_two_update_on_project_update_inv_src_prohibited(self, patch, scm_inventory, factory_scm_inventory, project, admin_user):\n scm_inventory2 = factory_scm_inventory(name=\"scm_inventory2\")\n res = patch(reverse('api:inventory_source_detail', kwargs={'version': 'v2', 'pk': scm_inventory2.id}),\n {'update_on_project_update': True,},\n admin_user, expect=400)\n content = json.loads(res.content)\n assert content['update_on_project_update'] == [\"More than one SCM-based inventory source with update on project update \"\n \"per-inventory not allowed.\"]\n\n def test_adding_inv_src_without_proj_access_prohibited(self, post, project, inventory, rando):\n inventory.admin_role.members.add(rando)\n post(reverse('api:inventory_inventory_sources_list', kwargs={'pk': inventory.id}),\n {'name': 'new inv src', 'source_project': project.pk, 'source': 'scm', 'overwrite_vars': True},\n rando, expect=403)\n\n\n@pytest.mark.django_db\nclass TestInsightsCredential:\n def test_insights_credential(self, patch, insights_inventory, admin_user, insights_credential):\n patch(insights_inventory.get_absolute_url(),\n {'insights_credential': insights_credential.id}, admin_user,\n expect=200)\n\n def test_insights_credential_protection(self, post, patch, insights_inventory, alice, insights_credential):\n insights_inventory.organization.admin_role.members.add(alice)\n insights_inventory.admin_role.members.add(alice)\n post(reverse('api:inventory_list'), {\n \"name\": \"test\",\n \"organization\": insights_inventory.organization.id,\n \"insights_credential\": insights_credential.id\n }, alice, expect=403)\n patch(insights_inventory.get_absolute_url(),\n {'insights_credential': insights_credential.id}, alice, expect=403)\n\n def test_non_insights_credential(self, patch, insights_inventory, admin_user, scm_credential):\n patch(insights_inventory.get_absolute_url(),\n {'insights_credential': scm_credential.id}, admin_user,\n expect=400)\n","sub_path":"awx/main/tests/functional/api/test_inventory.py","file_name":"test_inventory.py","file_ext":"py","file_size_in_byte":25130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"584277041","text":"############################################################################\n# This file contains the code for the 2nd half of the data processing: taking\n# especially high/low blocks in a user's speech, and putting them in\n# time context: beginning, middle, end / first half, second half\n############################################################################\n\nimport numpy as np\n\n# Determines whether more meaningful to split speech by thirds or halves\ndef putInTimeContext(groups, category, duration):\n if category == \"normal\":\n results = {\"split\":\"everywhere\"}\n return results\n\n speech_by_thirds = locateInTime(groups, category, \"thirds\", duration)\n thirds_std = speech_by_thirds[\"std\"]\n\n speech_by_halves = locateInTime(groups, category, \"halves\", duration)\n halves_std = speech_by_halves[\"std\"]\n\n if halves_std > thirds_std:\n split = \"halves\"\n summary = speech_by_halves[\"times_summary\"]\n else:\n split = \"thirds\"\n summary = speech_by_thirds[\"times_summary\"]\n\n results = {}\n if len(summary) == 0:\n results[\"split\"] = \"everywhere\"\n elif (split == \"halves\" and len(summary) == 2) or (split == \"thirds\" and len(summary) == 3):\n trend = summary[\"0\"][\"trend\"]\n for i in summary:\n if summary[str(i)][\"trend\"] != trend:\n results[\"split\"] = split\n results[\"summary\"] = summary\n else:\n results[\"split\"] = \"everywhere\"\n else:\n results[\"split\"] = split\n results[\"summary\"] = summary\n\n return results\n\n\n# Given a category to look for (high, low, or normal), scan the speech for that\n# category.\ndef locateInTime(groups, category, split, duration):\n if category == \"normal\":\n return []\n else:\n summary = flagCategory(groups, category, split, duration)\n\n return summary\n\n\n# Given a speech divided in time blocks, sees if any part is particularly high/low. Returns\n# standard deviation (measurement of how well the split divides up the data) and\n# where high/low blocks are.\ndef flagCategory(groups, category, split, duration):\n time_ranges = getTimeRanges(duration, split)\n\n percentages = []\n leftover_time = 0\n leftover_index = None\n group_index = 0\n\n # traverse blocks of time\n for i in range(len(time_ranges)-1):\n rangeStart = time_ranges[i]\n rangeEnd = time_ranges[i+1]\n rangeDuration = rangeEnd - rangeStart\n indices = [] # list of indices seen in this time range.\n\n if leftover_time < rangeDuration:\n groupDuration = leftover_time\n leftover_time = 0\n if leftover_index is not None:\n indices.append({\"index\":leftover_index,\"duration\":groupDuration})\n else:\n percentages.append({\"trend\":category,\"percentage\":1., \"index\":leftover_index})\n leftover_time = leftover_time - rangeDuration\n continue\n\n # traverse special groups\n while group_index < len(groups):\n groupStart = groups[group_index][\"start\"]\n groupEnd = groups[group_index][\"end\"]\n duration = groupEnd - groupStart\n trend = groups[group_index][\"trend\"]\n\n # if out of time range entirely.\n if groupStart > rangeEnd:\n break\n\n # if goes beyond time boundary\n elif groupEnd > rangeEnd:\n if (trend == category):\n leftover_time = groupEnd - rangeEnd\n leftover_index = group_index\n groupDuration = groupDuration + (rangeEnd - groupStart)\n indices.append({\"index\":group_index,\"duration\":(rangeEnd - groupStart)})\n else:\n leftover_time = 0\n leftover_index = 0\n group_index = group_index + 1\n break\n else:\n if (trend == category):\n groupDuration = groupDuration + duration\n indices.append({\"index\":group_index,\"duration\":duration})\n leftover_time = 0\n leftover_index = 0\n\n group_index = group_index + 1\n\n try:\n percentage = groupDuration / float(rangeDuration)\n except ZeroDivisionError as e:\n percentage = 0\n\n sig_index = findMostSigIndex(indices)\n percentages.append({\"trend\":category,\"percentage\":percentage, \"index\":sig_index})\n\n times_summary = {}\n for i in range(len(percentages)):\n if percentages[i][\"percentage\"] > .4:\n times_summary[str(i)] = {\"trend\":percentages[i][\"trend\"], \"percentage\":percentages[i][\"percentage\"],\n \"index\":percentages[i][\"index\"]}\n\n summary = {\"std\": np.std(np.array([x[\"percentage\"] for x in percentages])), \"times_summary\": times_summary}\n return summary\n\n\ndef findMostSigIndex(indices):\n if len(indices) == 0:\n return None\n\n maxDuration = indices[0][\"duration\"]\n maxIndex = indices[0][\"index\"]\n for item in indices:\n if item[\"duration\"] > maxDuration:\n maxDuration = item[\"duration\"]\n maxIndex = item[\"index\"]\n return maxIndex\n\n\n# Returns time intervals based on if the speech is split into thirds or halves\ndef getTimeRanges(duration, split):\n if split == \"thirds\":\n interval = duration / 3.\n time_ranges = [0, interval, (2*interval), (3*interval)]\n else:\n interval = duration / 2.\n time_ranges = [0, interval, (2*interval)]\n\n return time_ranges\n\n\n# make data fit certain patterns to make for easier lexicalization:\ndef clean(location_summary):\n cleaned = {}\n\n match_index = findTwoThirdsMatch(location_summary)\n if (match_index is not None):\n # first, switch to \"halves\" if it makes more sense.\n middle = location_summary[\"1\"]\n match = location_summary[match_index]\n if match[\"percentage\"] > .7: #change to .5?\n cleaned[\"split\"] = \"halves\"\n if match_index == \"2\":\n match_index = \"1\"\n other_index = 1-int(match_index)\n try:\n other = location_summary[other_index]\n cleaned[\"summary\"] = {match_index:match, other_index:other}\n except KeyError as e:\n cleaned[\"summary\"] = {match_index:match}\n\n return cleaned\n\n # otherwise, keep the more significant one and discard the other.\n else:\n cleaned[\"split\"] = \"thirds\"\n middle_score = middle[\"percentage\"]\n match_score = match[\"percentage\"]\n other_index = 2-int(match_index)\n\n cleaned[\"summary\"] = {}\n try:\n other = location_summary[other_index]\n cleaned[\"summary\"][other_index] = other\n except KeyError as e:\n pass\n\n if middle_score > match_score:\n cleaned[\"summary\"][\"1\"] = middle\n else:\n cleaned[\"summary\"][match_index] = match\n\n return cleaned\n\n # if no changes\n cleaned = {\"split\":\"thirds\", \"summary\":location_summary}\n return cleaned\n\n\n# look for if 2 adjacent timeblocks share the same index\ndef findTwoThirdsMatch(summary):\n try:\n middle = summary[\"1\"]\n except KeyError as e:\n return None\n\n try:\n start = summary[\"0\"]\n except KeyError as e:\n start = {\"trend\":None}\n\n try:\n end = summary[\"2\"]\n except KeyError as e:\n end = {\"trend\":None}\n\n if start[\"trend\"] == middle[\"trend\"]:\n return \"0\"\n elif end[\"trend\"] == middle[\"trend\"]:\n return \"2\"\n else:\n return None\n","sub_path":"lessons/timeContext.py","file_name":"timeContext.py","file_ext":"py","file_size_in_byte":7700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"111206234","text":"import os\nimport pandas as pd\nimport numpy as np\nimport logging\nimport sklearn\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef reorder(X: pd.DataFrame, columns: list) -> pd.DataFrame:\n X = X.copy()\n X = X[columns]\n\n return X\n\n\ndef sorter(X: pd.DataFrame) -> pd.DataFrame:\n X = X.copy()\n X['date'] = pd.to_datetime(X['date'], format='%d.%m.%Y')\n X = X.sort_values(by='date').reset_index(drop=True)\n X['date'] = X['date'].dt.year.astype('str') + '-' + X['date'].dt.month.astype('str') + '-01'\n X['date'] = pd.to_datetime(X['date'])\n\n return X\n\n\ndef grouper(X: pd.DataFrame, variables: list) -> pd.DataFrame:\n X = X.copy()\n X = pd.DataFrame(X.groupby(variables).agg(\n {'item_price': 'mean', 'item_cnt_day': 'sum'}))\n X = X.reset_index(drop=False).rename(columns={'item_cnt_day': 'monthly_sales'})\n X = X.groupby('date').monthly_sales.sum().reset_index()\n\n return X\n\n\ndef stationarizer(X: pd.DataFrame) -> pd.DataFrame:\n X = X.copy()\n X['prev_sales'] = X['monthly_sales'].shift(1)\n # drop the null values and calculate the difference\n X = X.dropna()\n X['diff'] = (X['monthly_sales'] - X['prev_sales'])\n\n return X\n\n\n# def shopGrouper(X: pd.DataFrame) -> pd.DataFrame:\n# X = X.copy()\n# X = X.groupby(['date', 'date_block_num', 'shop_id']).item_cnt_month.sum().reset_index()\n# agg_sales = X.groupby('date_block_num').item_cnt_month.sum().reset_index()\n# date_agg = dict(zip(agg_sales.date_block_num, agg_sales.item_cnt_month))\n# X['agg'] = X.date_block_num.map(date_agg)\n# X['shop_contrib'] = X['item_cnt_month'] / X['agg']\n#\n# return X\n\n\ndef featureBuilder(X: pd.DataFrame, look_back: int) -> pd.DataFrame:\n X = X.copy()\n X = X.drop(['prev_sales'], axis=1)\n for i in range(1, look_back + 1):\n fieldname = 'lag_' + str(i)\n X[fieldname] = X['diff'].shift(i)\n # drop Nan\n X = X.dropna(axis=0, inplace=False).reset_index(drop=True)\n X = X.drop(['monthly_sales', 'date'], axis=1)\n\n return X\n\n\ndef scale_features(X: pd.DataFrame) -> (sklearn.preprocessing.MinMaxScaler, np.array):\n scaler = MinMaxScaler(feature_range=(-1, 1))\n scaler.fit(X.values)\n train_set_scaled = scaler.transform(X.values)\n\n return scaler, train_set_scaled\n\n\ndef targetDefiner(X: np.array)-> (np.array, np.array):\n X = X.copy()\n X_train, y_train = X[:, 1:], X[:, 0:1]\n X_train = X_train.reshape(X_train.shape[0], 1, X_train.shape[1])\n\n return X_train, y_train\n","sub_path":"ETL.py","file_name":"ETL.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"458834782","text":"# *****************************************************************************\n# * Copyright 2019 Amazon.com, Inc. and its affiliates. All Rights Reserved. *\n# *\n# Licensed under the Amazon Software License (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://aws.amazon.com/asl/ *\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, either *\n# express or implied. See the License for the specific language governing *\n# permissions and limitations under the License. *\n# *****************************************************************************\n\nimport logging\nimport os\n\nfrom torch.optim import SGD\n\nfrom evaluator_factory_service_locator import EvalutorFactoryServiceLocator\nfrom model_resnet import ModelResnet\nfrom train import Train\nfrom train_pipeline import TrainPipeline\nfrom tripletloss import TripletLoss\n\n\nclass TrainFactory:\n \"\"\"\n Constructs the objects required to kick off training\n \"\"\"\n\n def __init__(self, epochs=50, early_stopping=True, patience_epochs=10, batch_size=32, num_workers=None,\n additional_args=None):\n\n if num_workers is None and os.cpu_count() > 1:\n self.num_workers = min(4, os.cpu_count() - 1)\n else:\n self.num_workers = 0\n\n self.batch_size = batch_size\n self.patience_epochs = patience_epochs\n self.early_stopping = early_stopping\n self.epochs = epochs\n self.additional_args = additional_args or {}\n\n @property\n def logger(self):\n return logging.getLogger(__name__)\n\n def _get_value(self, kwargs, key, default):\n value = kwargs.get(key, default)\n self.logger.info(\"Retrieving key {} with default {}, found {}\".format(key, default, value))\n return value\n\n def get(self, train_dataset):\n\n evaluator_factory = EvalutorFactoryServiceLocator().get_factory(\"EvaluationFactory\")\n evaluator = evaluator_factory.get_evaluator()\n\n trainer = Train(evaluator, patience_epochs=self.patience_epochs, early_stopping=self.early_stopping,\n epochs=self.epochs)\n model = ModelResnet()\n\n # Define optimiser\n learning_rate = float(self._get_value(self.additional_args, \"learning_rate\", \".0001\"))\n weight_decay = float(self._get_value(self.additional_args, \"weight_decay\", \"5e-5\"))\n momentum = float(self._get_value(self.additional_args, \"momentum\", \".9\"))\n optimiser = SGD(lr=learning_rate, params=model.parameters(), momentum=momentum, weight_decay=weight_decay)\n # optimiser = Adam(lr=self.learning_rate, params=model.parameters())\n\n self.logger.info(\"Using optimiser {}\".format(type(optimiser)))\n\n # Define loss function\n tripletloss_margin = float(self._get_value(self.additional_args, \"tripletloss_margin\", \"2.5\"))\n tripletloss_topk = int(self._get_value(self.additional_args, \"tripletloss_topk\", \"25\"))\n loss = TripletLoss(margin=tripletloss_margin, topk=tripletloss_topk)\n # loss = nn.CrossEntropyLoss()\n\n train_pipeline = TrainPipeline(batch_size=self.batch_size,\n optimiser=optimiser,\n trainer=trainer,\n num_workers=self.num_workers,\n loss_func=loss,\n model=model)\n\n return train_pipeline\n","sub_path":"src/train_factory.py","file_name":"train_factory.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"451507989","text":"import csv\nimport logging\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom urllib.parse import urlencode, quote\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.utils.encoding import smart_str\nimport jwt\nimport pydash\n\nimport talentmap_api.fsbid.services.cdo as cdo_services\nimport talentmap_api.fsbid.services.available_positions as services_ap\nfrom talentmap_api.common.common_helpers import ensure_date\nfrom talentmap_api.fsbid.requests import requests\n\nHRDATA_URL = settings.HRDATA_URL\nHRDATA_URL_EXTERNAL = settings.HRDATA_URL_EXTERNAL\nSECREF_ROOT = settings.SECREF_URL\nCLIENTS_ROOT = settings.CLIENTS_API_URL\nCLIENTS_ROOT_V2 = settings.CLIENTS_API_V2_URL\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_user_information(jwt_token, perdet_seq_num):\n '''\n Gets the office_phone and office_address for the employee\n '''\n url = f\"{SECREF_ROOT}/user?request_params.perdet_seq_num={perdet_seq_num}\"\n user = requests.get(url, headers={'JWTAuthorization': jwt_token, 'Content-Type': 'application/json'}).json()\n user = next(iter(user.get('Data', [])), {})\n try:\n return {\n \"office_address\": pydash.get(user, 'gal_address_text'),\n \"office_phone\": pydash.get(user, 'gal_phone_nbr_text'),\n \"email\": pydash.get(user, 'gal_smtp_email_address_text'),\n \"hru_id\": pydash.get(user, 'hru_id'),\n }\n except:\n return {}\n\n\ndef client(jwt_token, query, host=None):\n '''\n Get Clients by CDO\n '''\n from talentmap_api.fsbid.services.common import send_get_request\n response = send_get_request(\n \"\",\n query,\n convert_client_query,\n jwt_token,\n fsbid_clients_to_talentmap_clients,\n get_clients_count,\n \"/api/v2/clients/\",\n host,\n CLIENTS_ROOT_V2,\n )\n\n return response\n\n\ndef get_clients_count(query, jwt_token, host=None):\n '''\n Gets the total number of available positions for a filterset\n '''\n from talentmap_api.fsbid.services.common import send_count_request\n return send_count_request(\"\", query, convert_client_count_query, jwt_token, host, CLIENTS_ROOT_V2)\n\n\ndef client_suggestions(jwt_token, perdet_seq_num):\n '''\n Get a suggestion for a client\n '''\n\n # if less than LOW, try broader query\n LOW = 5\n # but also don't go too high\n HIGH = 100\n # but going over HIGH is preferred over FLOOR\n FLOOR = 0\n\n CLIENT = single_client(jwt_token, perdet_seq_num)\n grade = CLIENT.get(\"grade\")\n skills = CLIENT.get(\"skills\")\n skills = deepcopy(skills)\n mappedSkills = ','.join([str(x.get(\"code\")) for x in skills])\n\n values = {\n \"position__grade__code__in\": grade,\n \"position__skill__code__in\": mappedSkills,\n }\n\n # Dictionary for the next grade \"up\"\n nextGrades = {\n \"08\": \"07\",\n \"07\": \"06\",\n \"06\": \"05\",\n \"05\": \"04\",\n \"04\": \"03\",\n \"02\": \"01\",\n }\n\n count = services_ap.get_available_positions_count(values, jwt_token)\n count = int(count.get(\"count\"))\n\n # If we get too few results, try a broader query\n if count < LOW and nextGrades.get(grade) is not None:\n nextGrade = nextGrades.get(grade)\n values2 = deepcopy(values)\n values2[\"position__grade__code__in\"] = f\"{grade},{nextGrade}\"\n count2 = services_ap.get_available_positions_count(values2, jwt_token)\n count2 = int(count2.get(\"count\"))\n # Only use our broader query if the first one <= FLOOR OR the second < HIGH, and the counts don't match\n if (count <= FLOOR or count2 < HIGH) and count != count2:\n values = values2\n\n # Finally, return the query\n return values\n\n\ndef single_client(jwt_token, perdet_seq_num, is_bureau_not_superuser=False, host=None):\n '''\n Get a single client for a CDO\n '''\n from talentmap_api.fsbid.services.common import send_get_request\n from talentmap_api.fsbid.services.common import get_employee_profile_urls\n ad_id = jwt.decode(jwt_token, verify=False).get('unique_name')\n query = {\n \"ad_id\": ad_id,\n \"perdet_seq_num\": perdet_seq_num,\n \"currentAssignmentOnly\": \"false\",\n }\n responseAllAssignments = send_get_request(\n \"\",\n query,\n convert_client_query,\n jwt_token,\n fsbid_clients_to_talentmap_clients,\n get_clients_count,\n \"/api/v2/clients/\",\n host,\n CLIENTS_ROOT_V2,\n )\n query[\"currentAssignmentOnly\"] = \"true\"\n responseCurrentAssignment = send_get_request(\n \"\",\n query,\n convert_client_query,\n jwt_token,\n fsbid_clients_to_talentmap_clients,\n get_clients_count,\n \"/api/v2/clients/\",\n host,\n CLIENTS_ROOT_V2,\n )\n cdo = cdo_services.single_cdo(jwt_token, perdet_seq_num)\n # TO-DO: Use v2/clients here to fill out this payload\n # WS Request: Add current and historical assignments to one endpoint\n user_info = get_user_information(jwt_token, perdet_seq_num)\n try:\n CLIENT = list(responseAllAssignments['results'])[0]\n CLIENT['cdo'] = cdo\n CLIENT['user_info'] = user_info\n CLIENT['current_assignment'] = list(responseCurrentAssignment['results'])[0].get('current_assignment', {})\n CLIENT['employee_profile_url'] = get_employee_profile_urls(pydash.get(user_info, 'hru_id'))\n return CLIENT\n except IndexError:\n pass\n\n\ndef get_client_csv(query, jwt_token, rl_cd, host=None):\n from talentmap_api.fsbid.services.common import send_get_csv_request\n ad_id = jwt.decode(jwt_token, verify=False).get('unique_name')\n data = send_get_csv_request(\n \"\",\n query,\n convert_client_query,\n jwt_token,\n fsbid_clients_to_talentmap_clients_for_csv,\n CLIENTS_ROOT_V2,\n host,\n ad_id\n )\n\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = f\"attachment; filename=clients_{datetime.now().strftime('%Y_%m_%d_%H%M%S')}.csv\"\n\n writer = csv.writer(response, csv.excel)\n response.write(u'\\ufeff'.encode('utf8'))\n\n # write the headers\n writer.writerow([\n smart_str(u\"Name\"),\n smart_str(u\"Email\"),\n smart_str(u\"Skill\"),\n smart_str(u\"Grade\"),\n smart_str(u\"Employee ID\"),\n # smart_str(u\"Role Code\"), Might not be useful to users\n smart_str(u\"Position Location Code\"),\n ])\n\n for record in data:\n email_response = get_user_information(jwt_token, record['id'])\n email = pydash.get(email_response, 'email') or 'None listed'\n writer.writerow([\n smart_str(record[\"name\"]),\n email,\n smart_str(record[\"skills\"]),\n smart_str(\"=\\\"%s\\\"\" % record[\"grade\"]),\n smart_str(\"=\\\"%s\\\"\" % record[\"employee_id\"]),\n # smart_str(record[\"role_code\"]), Might not be useful to users\n smart_str(\"=\\\"%s\\\"\" % record[\"pos_location\"]),\n ])\n return response\n\n\ndef fsbid_clients_to_talentmap_clients(data):\n employee = data.get('employee', None)\n current_assignment = None\n assignments = None\n position = None\n location = {}\n\n if employee is not None:\n current_assignment = employee.get('currentAssignment', None)\n\n if employee.get('assignment', None) is not None:\n assignments = employee.get('assignment', None)\n # handle if array\n if type(assignments) is type([]) and list(assignments):\n current_assignment = list(assignments)[0]\n # handle if object\n if type(assignments) is type(dict()):\n current_assignment = assignments\n # remove current prefix\n if assignments.get('currentPosition', None) is not None:\n assignments['position'] = assignments['currentPosition']\n assignments['position']['location'] = assignments['currentPosition']['currentLocation']\n assignments = [].append(assignments)\n\n if current_assignment is not None:\n # handle if object\n if current_assignment.get('currentPosition', None) is not None:\n position = current_assignment.get('currentPosition', None)\n # handle if array\n if current_assignment.get('position', None) is not None:\n position = current_assignment.get('position', None)\n\n if position is not None:\n # handle if object\n if position.get('currentLocation', None) is not None:\n location = position.get('currentLocation', {})\n # handle if array\n if position.get('location', None) is not None:\n location = position.get('location', {})\n\n if current_assignment and current_assignment.get('currentPosition', None) is not None:\n # remove current prefix\n current_assignment['position'] = current_assignment['currentPosition']\n current_assignment['position']['location'] = current_assignment['position']['currentLocation']\n\n # first object in array, mapped\n try:\n current_assignment = fsbid_assignments_to_tmap(current_assignment)[0]\n except:\n current_assignment = {}\n\n initials = None\n try:\n initials = employee['per_first_name'][:1] + employee['per_last_name'][:1]\n except:\n initials = None\n\n middle_name = get_middle_name(employee)\n suffix_name = f\" {employee['per_suffix_name']}\" if pydash.get(employee, 'per_suffix_name') else ''\n\n return {\n \"id\": str(employee.get(\"pert_external_id\", None)),\n \"name\": f\"{employee.get('per_first_name', None)} {middle_name['full']}{employee.get('per_last_name', None)}{suffix_name}\",\n \"shortened_name\": f\"{employee.get('per_last_name', None)}{suffix_name}, {employee.get('per_first_name', None)} {middle_name['initial']}\",\n \"initials\": initials,\n \"perdet_seq_number\": str(int(employee.get(\"perdet_seq_num\", None))),\n \"grade\": employee.get(\"per_grade_code\", None),\n \"skills\": map_skill_codes(employee),\n \"employee_id\": str(employee.get(\"pert_external_id\", None)),\n \"role_code\": data.get(\"rl_cd\", None),\n \"pos_location\": map_location(location),\n # not exposed in FSBid yet\n # \"hasHandshake\": fsbid_handshake_to_tmap(data.get(\"hs_cd\")),\n # \"noPanel\": fsbid_no_successful_panel_to_tmap(data.get(\"no_successful_panel\")),\n # \"noBids\": fsbid_no_bids_to_tmap(data.get(\"no_bids\")),\n \"classifications\": fsbid_classifications_to_tmap(employee.get(\"classifications\") or []),\n \"languages\": fsbid_languages_to_tmap(data.get(\"languages\") or []),\n \"cdos\": data.get(\"cdos\") or [],\n \"current_assignment\": current_assignment,\n \"assignments\": fsbid_assignments_to_tmap(assignments),\n }\n\n\ndef fsbid_clients_to_talentmap_clients_for_csv(data):\n employee = data.get('employee', None)\n current_assignment = employee.get('currentAssignment', None)\n pos_location = None\n middle_name = get_middle_name(employee)\n if current_assignment is not None:\n position = current_assignment.get('currentPosition', None)\n if position is not None:\n pos_location = map_location(position.get(\"currentLocation\", None))\n\n suffix_name = f\" {employee['per_suffix_name']}\" if pydash.get(employee, 'per_suffix_name') else ''\n\n return {\n \"id\": employee.get(\"perdet_seq_num\", None),\n \"name\": f\"{employee.get('per_last_name', None)}{suffix_name}, {employee.get('per_first_name', None)} {middle_name['full']}\",\n \"grade\": employee.get(\"per_grade_code\", None),\n \"skills\": ' , '.join(map_skill_codes_for_csv(employee)),\n \"employee_id\": employee.get(\"pert_external_id\", None),\n \"role_code\": data.get(\"rl_cd\", None),\n \"pos_location\": pos_location,\n # not exposed in FSBid yet\n # \"hasHandshake\": fsbid_handshake_to_tmap(data.get(\"hs_cd\")),\n # \"noPanel\": fsbid_no_successful_panel_to_tmap(data.get(\"no_successful_panel\")),\n # \"noBids\": fsbid_no_bids_to_tmap(data.get(\"no_bids\")),\n \"classifications\": fsbid_classifications_to_tmap(employee.get(\"classifications\", []))\n }\n\n\ndef get_middle_name(employee, prop='per_middle_name'):\n middle_name = employee.get(prop, None) or ''\n middle_initial = ''\n if middle_name == 'NMN':\n middle_name = ''\n if middle_name:\n middle_name = middle_name + ' '\n middle_initial = middle_name[:1] + ' '\n return {\"full\": middle_name, \"initial\": middle_initial}\n\n\ndef hru_id_filter(query):\n from talentmap_api.fsbid.services.common import convert_multi_value\n results = []\n hru_id = query.get(\"hru_id\", None)\n results += [hru_id] if hru_id is not None else []\n hru_ids = convert_multi_value(query.get(\"hru_id__in\", None))\n results += hru_ids if hru_ids is not None else []\n return results if len(results) > 0 else None\n\n\ndef convert_client_query(query, isCount=None):\n '''\n Converts TalentMap filters into FSBid filters\n\n The TalentMap filters align with the client search filter naming\n '''\n from talentmap_api.fsbid.services.common import sorting_values, convert_multi_value\n values = {\n \"request_params.hru_id\": hru_id_filter(query),\n \"request_params.rl_cd\": query.get(\"rl_cd\", None),\n \"request_params.ad_id\": query.get(\"ad_id\", None),\n \"request_params.order_by\": sorting_values(query.get(\"ordering\", None)),\n \"request_params.freeText\": query.get(\"q\", None),\n \"request_params.bsn_id\": convert_multi_value(query.get(\"bid_seasons\")),\n \"request_params.hs_cd\": tmap_handshake_to_fsbid(query.get('hasHandshake', None)),\n \"request_params.no_successful_panel\": tmap_no_successful_panel_to_fsbid(query.get('noPanel', None)),\n \"request_params.no_bids\": tmap_no_bids_to_fsbid(query.get('noBids', None)),\n \"request_params.page_index\": int(query.get(\"page\", 1)),\n \"request_params.page_size\": query.get(\"limit\", 25),\n \"request_params.currentAssignmentOnly\": query.get(\"currentAssignmentOnly\", 'true'),\n \"request_params.get_count\": query.get(\"getCount\", 'false'),\n \"request_params.perdet_seq_num\": query.get(\"perdet_seq_num\", None),\n }\n if isCount:\n values['request_params.page_size'] = None\n return urlencode({i: j for i, j in values.items() if j is not None}, doseq=True, quote_via=quote)\n\n\ndef convert_client_count_query(query):\n return convert_client_query(query, True)\n\n\ndef map_skill_codes_for_csv(data, prefix='per'):\n skills = []\n for i in range(1, 4):\n index = f'_{i}'\n if i == 1:\n index = ''\n desc = data.get(f'{prefix}_skill{index}_code_desc', None)\n skills.append(desc)\n return filter(lambda x: x is not None, skills)\n\n\ndef map_skill_codes(data):\n skills = []\n for i in range(1, 4):\n index = f'_{i}'\n if i == 1:\n index = ''\n code = pydash.get(data, f'per_skill{index}_code', None)\n desc = pydash.get(data, f'per_skill{index}_code_desc', None) # Not coming through with /Persons\n skills.append({'code': code, 'description': desc})\n return filter(lambda x: x.get('code', None) is not None, skills)\n\n\ndef map_skill_codes_additional(skills, employeeSkills):\n employeeCodesAdd = []\n try:\n for w in employeeSkills:\n foundSkill = [a for a in skills if a['skl_code'] == w['code']]\n # some times, the user's skill is not in the full /skillCodes list\n if foundSkill:\n foundSkill = foundSkill[0]\n cone = foundSkill['jc_nm_txt']\n foundSkillsByCone = [b for b in skills if b['jc_nm_txt'] == cone]\n for x in foundSkillsByCone:\n employeeCodesAdd.append(x['skl_code'])\n except Exception as e:\n logger.error(f\"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}\")\n return set(employeeCodesAdd)\n\n\ndef map_location(location):\n city = location.get('city')\n country = location.get('country')\n state = location.get('state')\n result = city\n if country and country.strip():\n result = f\"{city}, {country}\"\n if state and state.strip():\n result = f\"{city}, {state}\"\n return result\n\n\ndef fsbid_handshake_to_tmap(hs):\n # Maps FSBid Y/N value for handshakes to expected TMap Front end response for handshake\n fsbid_dictionary = {\n \"Y\": True,\n \"N\": False\n }\n return fsbid_dictionary.get(hs, None)\n\n\ndef tmap_handshake_to_fsbid(hs):\n # Maps TMap true/false value to acceptable fsbid api params for handshake\n tmap_dictionary = {\n \"true\": \"Y\",\n \"false\": \"N\"\n }\n return tmap_dictionary.get(hs, None)\n\ndef fsbid_no_successful_panel_to_tmap(panel):\n fsbid_dictionary = {\n \"Y\": True,\n \"N\": False\n }\n return fsbid_dictionary.get(panel, None)\n\n\ndef tmap_no_successful_panel_to_fsbid(panel):\n tmap_dictionary = {\n \"true\": \"Y\",\n \"false\": \"N\"\n }\n return tmap_dictionary.get(panel, None)\n\ndef fsbid_no_bids_to_tmap(bids):\n fsbid_dictionary = {\n \"Y\": True,\n \"N\": False\n }\n return fsbid_dictionary.get(bids, None)\n\n\ndef tmap_no_bids_to_fsbid(bids):\n tmap_dictionary = {\n \"true\": \"Y\",\n \"false\": \"N\"\n }\n return tmap_dictionary.get(bids, None)\n\n\ndef fsbid_classifications_to_tmap(cs):\n tmap_classifications = []\n if type(cs) is list:\n for x in cs:\n tmap_classifications.append(\n # resolves disrepancy between string and number comparison\n pydash.to_number(x.get('te_id', None))\n )\n else:\n tmap_classifications.append(\n # resolves disrepancy between string and number comparison\n pydash.to_number(cs.get('te_id', None))\n )\n return tmap_classifications\n\n\ndef fsbid_assignments_to_tmap(assignments):\n from talentmap_api.fsbid.services.common import get_post_overview_url, get_post_bidding_considerations_url, get_obc_id\n assignmentsCopy = []\n tmap_assignments = []\n if type(assignments) is type(dict()):\n assignmentsCopy.append(assignments)\n else:\n assignmentsCopy = assignments\n if type(assignmentsCopy) is type([]):\n for x in assignmentsCopy:\n pos = x.get('position', {})\n loc = pos.get('location', {})\n tmap_assignments.append(\n {\n \"id\": x.get('asg_seq_num', None),\n \"position_id\": x.get('pos_seq_num', None),\n \"start_date\": ensure_date(x.get('asgd_eta_date', None)),\n \"end_date\": ensure_date(x.get('asgd_etd_ted_date', None)),\n \"position\": {\n \"grade\": pos.get(\"pos_grade_code\", None),\n \"skill\": f\"{pos.get('pos_skill_desc', None)} ({pos.get('pos_skill_code')})\",\n \"skill_code\": pos.get(\"pos_skill_code\", None),\n \"bureau\": f\"({pos.get('pos_bureau_short_desc', None)}) {pos.get('pos_bureau_long_desc', None)}\",\n \"bureau_code\": pydash.get(pos, 'pos_bureau_short_desc'), # only comes through for available bidders\n \"organization\": pos.get('pos_org_short_desc', None),\n \"position_number\": pos.get('pos_num_text', None),\n \"position_id\": x.get('pos_seq_num', None),\n \"title\": pos.get(\"pos_title_desc\", None),\n \"post\": {\n \"code\": loc.get(\"gvt_geoloc_cd\", None),\n \"post_overview_url\": get_post_overview_url(loc.get(\"gvt_geoloc_cd\", None)),\n \"post_bidding_considerations_url\": get_post_bidding_considerations_url(loc.get(\"gvt_geoloc_cd\", None)),\n \"obc_id\": get_obc_id(loc.get(\"gvt_geoloc_cd\", None)),\n \"location\": {\n \"country\": loc.get(\"country\", None),\n \"code\": loc.get(\"gvt_geoloc_cd\", None),\n \"city\": loc.get(\"city\", None),\n \"state\": loc.get(\"state\", None),\n }\n },\n \"language\": pos.get(\"pos_position_lang_prof_desc\", None)\n },\n }\n )\n return tmap_assignments\n\n\ndef fsbid_languages_to_tmap(languages):\n tmap_languages = []\n empty_score = '--'\n for x in languages:\n if not x.get('empl_language', None) or not str(x.get('empl_language')).strip():\n continue\n r = str(x.get('empl_high_reading', '')).strip()\n s = str(x.get('empl_high_speaking', '')).strip()\n tmap_languages.append({\n \"code\": str(x.get('empl_language_code')).strip() if x.get('empl_language_code') else x.get('empl_language_code') or None,\n \"language\": str(x.get('empl_language')).strip() if x.get('empl_language') else x.get('empl_language') or None,\n \"test_date\": ensure_date(x.get('empl_high_test_date', None)),\n \"speaking_score\": s or empty_score,\n \"reading_score\": r or empty_score,\n \"custom_description\": f\"{str(x.get('empl_language')).strip()} {s or empty_score}/{r or empty_score}\"\n })\n return tmap_languages\n\ndef get_available_bidders(jwt_token, isCDO, query, host=None):\n from talentmap_api.fsbid.services.common import send_get_request\n from talentmap_api.cdo.services.available_bidders import get_available_bidders_stats\n cdo = 'cdo' if isCDO else 'bureau'\n uri = f\"availablebidders/{cdo}\"\n response = send_get_request(\n uri,\n query,\n convert_available_bidder_query,\n jwt_token,\n fsbid_available_bidder_to_talentmap,\n False, # No count function\n f\"/api/v1/clients/availablebidders/{cdo}\",\n host,\n CLIENTS_ROOT,\n )\n stats = get_available_bidders_stats(response)\n return {\n **stats,\n \"results\": list({v['perdet_seq_number']:v for v in response.get('results')}.values()),\n }\n\n# Can update to reuse client mapping once client v2 is updated and released with all the new fields\ndef fsbid_available_bidder_to_talentmap(data):\n employee = data.get('employee', None)\n current_assignment = None\n assignments = None\n position = None\n location = {}\n\n if employee is not None:\n current_assignment = employee.get('currentAssignment', None)\n\n if employee.get('assignment', None) is not None:\n assignments = employee.get('assignment', None)\n # handle if array\n if type(assignments) is type([]) and list(assignments):\n current_assignment = list(assignments)[0]\n # handle if object\n if type(assignments) is type(dict()):\n current_assignment = assignments\n # remove current prefix\n if assignments.get('currentPosition', None) is not None:\n assignments['position'] = assignments['currentPosition']\n assignments['position']['location'] = assignments['currentPosition']['currentLocation']\n assignments = [].append(assignments)\n\n if current_assignment is not None:\n # handle if object\n if current_assignment.get('currentPosition', None) is not None:\n position = current_assignment.get('currentPosition', None)\n # handle if array\n if current_assignment.get('position', None) is not None:\n position = current_assignment.get('position', None)\n\n if position is not None:\n # handle if object\n if position.get('currentLocation', None) is not None:\n location = position.get('currentLocation', {})\n # handle if array\n if position.get('location', None) is not None:\n location = position.get('location', {})\n\n if current_assignment and current_assignment.get('currentPosition', None) is not None:\n # remove current prefix\n current_assignment['position'] = current_assignment['currentPosition']\n current_assignment['position']['location'] = current_assignment['position']['currentLocation']\n\n # first object in array, mapped\n try:\n current_assignment = fsbid_assignments_to_tmap(current_assignment)[0]\n except:\n current_assignment = {}\n\n initials = None\n try:\n initials = employee['per_first_name'][:1] + employee['per_last_name'][:1]\n except:\n initials = None\n\n middle_name = get_middle_name(employee)\n suffix_name = f\" {employee['per_suffix_name']}\" if pydash.get(employee, 'per_suffix_name') else ''\n\n res = {\n \"id\": str(employee.get(\"pert_external_id\", None)),\n \"cdo\": {\n \"full_name\": data.get('cdo_fullname', None),\n \"last_name\": data.get('cdo_last_name', None),\n \"first_name\": data.get('cdo_first_name', None),\n \"email\": data.get('cdo_email', None),\n \"hru_id\": data.get(\"hru_id\", None),\n },\n \"name\": f\"{employee.get('per_last_name', None)}{suffix_name}, {employee.get('per_first_name', None)} {middle_name['initial']}\",\n \"shortened_name\": f\"{employee.get('per_first_name', None)} {middle_name['initial']}{employee.get('per_last_name', None)}{suffix_name}\",\n \"initials\": initials,\n \"perdet_seq_number\": str(employee.get(\"perdet_seq_num\", None)),\n \"grade\": employee.get(\"per_grade_code\", None),\n \"skills\": map_skill_codes(employee),\n \"employee_id\": str(employee.get(\"pert_external_id\", None)),\n \"role_code\": data.get(\"rl_cd\", None),\n \"pos_location\": map_location(location),\n # not exposed in FSBid yet\n # \"hasHandshake\": fsbid_handshake_to_tmap(data.get(\"hs_cd\")),\n # \"noPanel\": fsbid_no_successful_panel_to_tmap(data.get(\"no_successful_panel\")),\n # \"noBids\": fsbid_no_bids_to_tmap(data.get(\"no_bids\")),\n \"classifications\": fsbid_classifications_to_tmap(employee.get(\"classifications\", [])),\n \"current_assignment\": current_assignment,\n \"assignments\": fsbid_assignments_to_tmap(assignments),\n \"languages\": fsbid_languages_to_tmap(data.get('languages', []) or []),\n \"available_bidder_details\": {\n **data.get(\"details\", {}),\n \"is_shared\": pydash.get(data, 'details.is_shared') == '1',\n \"archived\": pydash.get(data, 'details.archived') == '1',\n }\n }\n return res\n\ndef convert_available_bidder_query(query):\n sort_asc = query.get(\"ordering\", \"name\")[0] != \"-\"\n ordering = query.get(\"ordering\", \"name\").lstrip(\"-\")\n values = {\n \"order_by\": ordering,\n \"is_asc\": 'true' if sort_asc else 'false',\n \"ad_id\": query.get(\"ad_id\", None),\n }\n\n return urlencode({i: j for i, j in values.items() if j is not None}, doseq=True, quote_via=quote)\n","sub_path":"talentmap_api/fsbid/services/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":26870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"385207139","text":"from sklearn.utils import shuffle\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\n# NaNを返すのを防ぐ\ndef tf_log(x):\n return tf.log(tf.clip_by_value(x, 1e-10, x))\n\nclass Dense:\n def __init__(self, in_dim, out_dim, function=lambda x: x):\n # use He\n stddev = tf.sqrt(2.0 / in_dim)\n self.W = tf.Variable(tf.truncated_normal(shape=(in_dim, out_dim), stddev=stddev))\n self.b = tf.Variable(tf.zeros(out_dim))\n self.params = [self.W, self.b]\n self.function = function\n\n def __call__(self, h_prev):\n # h_prev: 前の層のforwardの値\n self.h_prev = h_prev\n return self.function(tf.matmul(self.h_prev, self.W) + self.b)\n\nclass Dropout:\n def __init__(self, dropout_keep_prob=1.0):\n self.dropout_keep_prob = dropout_keep_prob\n self.params = []\n \n def __call__(self, x):\n # 訓練時のみdropoutを適用\n return tf.cond(\n pred=is_training,\n true_fn=lambda: tf.nn.dropout(x, keep_prob=self.dropout_keep_prob),\n false_fn=lambda: x\n )\n\nclass MultilayerPerceptron:\n def __init__(self, layers, lr=0.001, optimizer=None):\n self.layers = layers\n self.optimizer = optimizer\n self.lr = lr\n\n def inference(self, input_placeholder):\n \"\"\"\n Builds the model as far as required for running the network\n forward to make predictions\n \"\"\"\n x = input_placeholder\n for layer in layers:\n x = layer(x)\n return x\n \n def calc_loss(self, predicted_value, label_placeholder):\n \"\"\"\n Adds to the inference model the layers required to generate loss\n \"\"\"\n cross_entropy = - tf.reduce_mean(tf.reduce_sum(label_placeholder * tf_log(predicted_value), axis=1)) \n return cross_entropy\n \n def train(self, input_placeholder, label_placeholder):\n # forward \n y = self.inference(input_placeholder)\n loss = self.calc_loss(y, label_placeholder)\n params_list = []\n for layer in self.layers:\n params_list.extend(layer.params)\n \n # backward\n grads = tf.gradients(loss, params_list)\n if self.optimizer is None:\n updates = []\n for param, grad in zip(params_list, grads):\n updates.append(param.assign_sub(self.lr * grad))\n else:\n updates = self.optimizer.update(params_list, grads)\n\n return updates\n\n def valid(self, input_placeholder, label_placeholder):\n y = self.inference(input_placeholder)\n loss = self.calc_loss(y, label_placeholder)\n return y, loss\n\nclass Adam:\n def __init__(self, lr=0.001, beta1=0.9, beta2=0.99):\n self.lr = lr\n self.beta1 = beta1\n self.beta2 = beta2\n self.t = 0\n \n def update(self, params, grads):\n updates = []\n self.t += 1\n for param, grad in zip(params, grads):\n m = tf.Variable(tf.zeros_like(param, dtype=tf.float32), name='m')\n v = tf.Variable(tf.zeros_like(param, dtype=tf.float32), name='v')\n updates.append(m.assign(self.beta1 * m + (1 - self.beta1) * grad))\n updates.append(v.assign(self.beta2 * v + (1 - self.beta2) * grad**2))\n with tf.control_dependencies(updates):\n mhat = m / (1 - self.beta1 ** self.t)\n vhat = v / (1 - self.beta2 ** self.t)\n updates.append(param.assign_sub(self.lr * mhat / (tf.sqrt(vhat) + 1e-8)))\n\n return updates\n\n# preparing\nx_train, y_train, x_test = load_fashionmnist()\nx_train, x_valid, y_train, y_valid = train_test_split(x_train, y_train, test_size=10000)\n\n# fitting\nepoch = 25\nbatch_size = 100\ntrain_size = x_train.shape[0]\niteration = int(train_size / batch_size)\ntf.reset_default_graph()\nwith tf.Session() as sess:\n # valiables\n input_placeholder = tf.placeholder(tf.float32, (None, 784))\n label_placeholder = tf.placeholder(tf.float32, (None, 10))\n is_training = tf.placeholder(tf.bool)\n dropout_keep_prob = 0.5\n layers = [\n Dense(784, 2000, tf.nn.relu),\n Dropout(dropout_keep_prob),\n Dense(2000, 1000, tf.nn.relu),\n Dropout(dropout_keep_prob),\n Dense(1000, 500, tf.nn.relu),\n Dropout(dropout_keep_prob),\n Dense(500, 10, tf.nn.softmax)\n ]\n # prepare operation\n optimizer = Adam(lr=0.00009)\n model = MultilayerPerceptron(layers=layers, optimizer=optimizer)\n updates = model.train(input_placeholder, label_placeholder)\n valid = model.valid(input_placeholder, label_placeholder)\n predict = model.inference(input_placeholder)\n train = tf.group(*updates)\n\n # execute operation \n sess.run(tf.global_variables_initializer())\n for i in range(epoch):\n rand_index = np.random.permutation(np.arange(train_size)).reshape(-1, batch_size)\n for j in range(iteration):\n feed_dict = {\n input_placeholder: x_train[rand_index[j]],\n label_placeholder: y_train[rand_index[j]],\n is_training: True,\n }\n # train\n sess.run(train, feed_dict)\n\n # valid\n feed_dict = { \n input_placeholder: x_valid,\n label_placeholder: y_valid,\n is_training: False\n }\n y_pred, cost_valid_ = sess.run(valid, feed_dict)\n print('EPOCH: {}, Valid Cost: {:.3f}, Valid Accuracy: {:.3f}'.format(\n i + 1,\n cost_valid_,\n accuracy_score(y_valid.argmax(axis=1), y_pred.argmax(axis=1))\n ))\n \n # label保存\n feed_dict = { input_placeholder: x_test, is_training: False }\n y_test_pred = sess.run(predict, feed_dict)\n y_pred = y_test_pred.argmax(axis=1)\n submission = pd.Series(y_pred, name='label')\n","sub_path":"deep-learning-lecture/lec-5-task/submission_code.py","file_name":"submission_code.py","file_ext":"py","file_size_in_byte":5857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"535842234","text":"from flask import Flask, flash, render_template, send_from_directory, request, make_response\nimport sys\nfrom wtforms import Form, validators, StringField\nimport os\napp = Flask(__name__)\napp.config['SESSION_TYPE'] = 'memcached'\napp.config['SECRET_KEY'] = 'need to hide this'\n\napp.config.update(\n SESSION_COOKIE_SECURE=True,\n SESSION_COOKIE_HTTPONLY=True,\n SESSION_COOKIE_SAMESITE='Lax',\n)\nclass UrlForm(Form):\n\n url = StringField('inp_url', validators=[validators.URL()])\n\n\n@app.route('/')\ndef index(error=None):\n r = make_response(render_template('gapfiller_home.html', error=error))\n r.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')\n r.headers.set('Content-Security-Policy', \"default-src 'self'\")\n r.headers.set('X-Content-Type-Options', 'nosniff')\n r.headers.set('X-Frame-Options', 'SAMEORIGIN')\n r.set_cookie('username', 'flask', secure=True, httponly=True, samesite='Lax')\n return r\n\n\n@app.route(\"/url_input\", methods=['POST'])\ndef move_forward():\n #Moving forward code\n temp = request.form\n form = UrlForm(request.form)\n if request.method == \"POST\" and form.validate():\n this_url = form.this_url\n print(this_url)\n forward_message = \"Moving Forward...\"\n print(forward_message, file=sys.stderr)\n return send_from_directory(directory='static', filename='test.pdf', as_attachment=True)\n\n else:\n flash(\"!!!This is not valid url I'm afraid, please try a different one!!!\")\n error = \"not valid url I'm afraid\"\n\n return index(error=error)\n #return render_template('thanks_page.html')\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"flask_scripts/test_flask_app.py","file_name":"test_flask_app.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"148177225","text":"import httplib2\nimport os\nimport oauth2client\nfrom oauth2client import client, tools, file\nimport base64\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom apiclient import errors, discovery\nfrom sys import platform\n\ndef prost5():\n print('Hello World!')\n\ndef log(path):\n with open(path, 'r') as LF:\n list1 = LF.readlines()\n str1 = ''\n for i in list1:\n str1 = str1 + i + '
    '\n print(str1)\n return str1\n\ndef send(topic, message):\n SCOPES = 'https://www.googleapis.com/auth/gmail.send'\n if platform == 'win32':\n CLIENT_SECRET_FILE = 'C:\\PythonProject\\mygmail\\client_secret.json'\n elif platform == 'linux':\n CLIENT_SECRET_FILE = '/home/pi/Downloads/client_secret.json'\n else:\n print(f'Платформа {platform} не поддерживается')\n APPLICATION_NAME = 'Gmail API Python Send Email'\n\n def SendMessageInternal(service, user_id, message):\n try:\n print('mark #3')\n message = (service.users().messages().send(userId=user_id, body=message).execute())\n print('mark #4')\n print('Message Id: %s' % message['id'])\n print('mark #5')\n return message\n except errors.HttpError as error:\n print('An error occurred: %s' % error)\n\n def CreateMessage(sender, to, subject, msgHtml, msgPlain):\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject\n msg['From'] = sender\n msg['To'] = to\n msg.attach(MIMEText(msgPlain, 'plain'))\n msg.attach(MIMEText(msgHtml, 'html'))\n raw = base64.urlsafe_b64encode(msg.as_bytes())\n raw = raw.decode()\n body = {'raw': raw}\n return body\n\n def get_credentials(): #Удостоверение личности\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir, 'gmail-python-email-send.json')\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n credentials = tools.run_flow(flow, store)\n print('Storing credentials to ' + credential_path)\n input('...[press Enter]...')\n return credentials\n\n def SendMessage(sender, to, subject, msgHtml, msgPlain):\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('gmail', 'v1', http=http)\n print('mark #1')\n message1 = CreateMessage(sender, to, subject, msgHtml, msgPlain)\n print('mark #2')\n SendMessageInternal(service, \"me\", message1)\n\n def main(topic, message):\n to = \"zabavniy7@gmail.com\"\n sender = \"raspberry.assistant.py@gmail.com\"\n subject = topic\n msgHtml = message\n msgPlain = message\n SendMessage(sender, to, subject, msgHtml, msgPlain)\n\n main(topic, message)\n\nif __name__ != '__main__':\n print(f'ЗАПУСК МОДУЛЯ {__name__}')\nelse:\n print('ВЫ ТЕСТИРУЕТЕ МОДУЛЬ')\n prost5()","sub_path":"RasAsiVer1/Gmail_Packeg/Send.py","file_name":"Send.py","file_ext":"py","file_size_in_byte":3486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"222810407","text":"# (c) Copyright Rocket Software, Inc. 2018, 2019 All Rights Reserved.\n\nfrom numpy import pi\nfrom bokeh.colors import HSL\nfrom bokeh.plotting import *\nfrom bokeh.models import HoverTool\nfrom .his_profile import tree_item_count\nfrom math import fmod\nimport pickle\n\ndef invert_data(list_of_dicts):\n result = dict()\n for d in list_of_dicts:\n for name, value in d.items():\n if name not in result:\n result[name] = list()\n result[name].append(value)\n return result\n\ndef color_for_wedge(level, total, subtotal_for_color):\n return HSL(int(256*0.99999*(subtotal_for_color/total)),\n 1.0, # 1.0 - subtree.count/float(tree.count), # sat [0,1]\n 0.5, # 0.4+(level*0.2)/6, # light [0=black,1/2=sat,1=white]\n 1.0) # alpha\n\ndef tree_to_wedge_data(data, tree, level=0, total=None, subtotal=0, ancestor_subtotal=None,\n threshold = 0.0025):\n if total is None:\n total = float(tree.count)\n initial_subtotal = subtotal\n final_subtotal = subtotal + tree.count\n item_list = tree.key_to_subtree.items()\n subtotal_for_color = initial_subtotal if level == 0 else ancestor_subtotal\n for key, subtree in sorted(item_list, key=tree_item_count, reverse=True):\n if subtree.count/total <= threshold:\n break\n subtotal_begin = subtotal\n subtotal_end = subtotal + subtree.count\n if level == 0:\n subtotal_for_color = subtotal_begin\n elif (subtotal_end-subtotal_begin)/(final_subtotal-initial_subtotal) >= 0.66:\n subtotal_for_color = ancestor_subtotal\n else:\n subtotal_for_color = fmod(subtotal_for_color+0.1*total, total)\n data.append({'inner_radius':level, 'outer_radius':level+1,\n 'start_angle':(subtotal/total)*2*pi, 'end_angle':(subtotal_end/total)*2*pi,\n 'fill_color':color_for_wedge(level, total, subtotal_for_color),\n 'name':key})\n tree_to_wedge_data(data, subtree, level=level+1,\n total=total, subtotal=subtotal, ancestor_subtotal=subtotal_for_color, threshold=threshold)\n subtotal += subtree.count\n ancestor_subtotal = None\n if False: \n data.append({'inner_radius':level, 'outer_radius':level+1,\n 'start_angle':(subtotal/total)*2*pi, 'end_angle':(final_subtotal/total)*2*pi,\n 'fill_color':HSL(0,1,1),\n 'name':'(other)'})\n\ndef show_tree(pickled_tree):\n with open(pickled_tree, \"rb\") as tree_pickle_file:\n tree = pickle.load(tree_pickle_file)\n data = []\n tree_to_wedge_data(data, tree)\n source = ColumnDataSource(invert_data(data))\n p = figure(x_range=(-8, 8), y_range=(-8, 8))\n circle_x, circle_y = (0, 0)\n p.annular_wedge(circle_x, circle_y,\n inner_radius='inner_radius', outer_radius='outer_radius',\n start_angle='start_angle', end_angle='end_angle',\n fill_color='fill_color', name='name',\n source=source)\n p.add_tools(HoverTool(tooltips=\"@name\", show_arrow=False, point_policy='follow_mouse'))\n show(p)\n\ndef show_example_tree():\n show_tree('/u/pdharr/profile_tree_2018-02-27-13:53:03.pkl')\n \n","sub_path":"zos_python/profile/his_plotting.py","file_name":"his_plotting.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"350568997","text":"print(\"==== replace str ====\")\n\n\ndef find_str(paragraph, word, start=0, end=None, model='one'):\n result = []\n index = 0\n\n paragraph = str(paragraph)\n word = str(word)\n word_len = len(word)\n head_ch = word[:1]\n if model:\n if model not in ('one', 'all'):\n raise SyntaxError(\"model= ['one','all']\")\n\n if start:\n start = int(start)\n index = start\n if end:\n end = int(end)\n paragraph = paragraph[start:end]\n else:\n paragraph = paragraph[start:]\n\n for ch in paragraph:\n if ch == head_ch:\n begin_index = index\n end_index = index + word_len\n\n tmp_word = paragraph[begin_index:end_index]\n if tmp_word == word:\n result.append(index)\n index += 1\n if model == 'one' and len(result) == 1:\n break\n if result:\n if len(result) == 1:\n return result[0]\n else:\n return result\n else:\n return -1\n\n\ndef replace_str(paragraph, word1, word2, start=0, end=None, model='all'):\n index_list = find_str(paragraph, word1, model='all')\n word1_len = len(word1)\n\n slice_list = []\n for index in index_list:\n slice_list.append(index)\n slice_list.append(index+word1_len)\n\n head = slice[0]\n tail = slice[-1]\n slice_new = slice[1:-1]\n \nif __name__ == '__main__':\n print(replace_str('THis is my word word word word', 'word', model=\"all\"))\n","sub_path":"replace_str.py","file_name":"replace_str.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"502902115","text":"\"\"\"\nAdd two random numbers together\n\nRequires no setup. \n\"\"\"\nimport random\n\n# Instructions:\n# Download this file\n# Run it with \n# python -i docs.py\n# This will run the file and leave you at the command prompt, with the file imported.\n# Now try \n# help(add)\n\ndef add (num1, num2):\n \"\"\"\n Add two numbers.\n\n Postional arguments:\n num1 -- an integer or double number (no default)\n num2 -- an integer or double number (no default)\n\n Returns:\n Sum of the two numbers.\n \"\"\"\n \n return num1 + num2 \n\n\n \nnumA = random.random() * 10\nnumB = random.random() * 10 \nprint(add(numA, numB))\n\n\n\n","sub_path":"docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"123150852","text":"\"\"\"\nUtilities for using Wireless Extensions (WE) ioctls\n WT -- http://www.hpl.hp.com/personal/Jean_Tourrilhes/Linux/Tools.html\n WE -- /usr/include/linux/wireless.h\n\nAs set of scapy Packet classes model the structs from wireless.h\n\"\"\"\nimport re\nimport socket\nimport sys\n\n\nfrom ctypes import cast\nfrom ctypes import c_int\nfrom ctypes import c_uint\nfrom ctypes import c_byte\nfrom ctypes import c_ubyte\nfrom ctypes import c_short\nfrom ctypes import c_ushort\nfrom ctypes import c_void_p\nfrom ctypes import c_char\nfrom ctypes import Structure\nfrom ctypes import sizeof\nfrom ctypes import pointer\nfrom ctypes import Union\nfrom exceptions import IOError\nfrom fcntl import ioctl\nfrom subprocess import check_call\nfrom tempfile import SpooledTemporaryFile\n\n\nclass IW_PARAM(Structure):\n\t_fields_ = [('value', c_int),\n\t\t\t\t('fixed', c_byte),\n\t\t\t\t('disabled', c_byte),\n\t\t\t\t('flags', c_ushort)]\n\n\nclass IW_POINT(Structure):\n\t_fields_ = [('pointer', c_void_p),\n\t\t\t\t('length', c_ushort),\n\t\t\t\t('flags', c_ushort)]\n\n\nclass IW_QUALITY(Structure):\n\t_fields_ = [('qual', c_byte),\n\t\t\t\t('level', c_byte),\n\t\t\t\t('noise', c_byte),\n\t\t\t\t('updated', c_byte)]\n\n\nclass IW_FREQ(Structure):\n\t_fields_ = [('m', c_int),\n\t\t\t\t('e', c_short),\n\t\t\t\t('i', c_ubyte),\n\t\t\t\t('flags', c_byte)]\n\n\nclass IW_RANGE(Structure):\n\t_fields_ = [('throughput', c_uint),\n\t\t\t\t('min_nwid', c_uint),\n\t\t\t\t('max_nwid', c_uint),\n\t\t\t\t('old_num_channels', c_ushort),\n\t\t\t\t('old_num_frequency', c_byte),\n\t\t\t\t('scan_capa', c_byte),\n\t\t\t\t('event_capa', c_uint * 6),\n\t\t\t\t('sensitivity', c_int),\n\t\t\t\t('max_qual', IW_QUALITY),\n\t\t\t\t('avg_qual', IW_QUALITY),\n\t\t\t\t('num_bitrates', c_byte),\n\t\t\t\t('bitrate', c_int * 32),\n\t\t\t\t('min_rts', c_int),\n\t\t\t\t('max_rts', c_int),\n\t\t\t\t('min_frag', c_int),\n\t\t\t\t('max_frag', c_int),\n\t\t\t\t('min_pmp', c_int),\n\t\t\t\t('max_pmp', c_int),\n\t\t\t\t('min_pmt', c_int),\n\t\t\t\t('max_pmt', c_int),\n\t\t\t\t('pmp_flags', c_ushort),\n\t\t\t\t('pmt_flags', c_ushort),\n\t\t\t\t('pm_capa', c_ushort),\n\t\t\t\t('encoding_size', c_ushort * 8),\n\t\t\t\t('num_encoding_sizes', c_byte),\n\t\t\t\t('max_encoding_tokens', c_byte),\n\t\t\t\t('encoding_login_index', c_byte),\n\t\t\t\t('txpower_capa', c_ushort),\n\t\t\t\t('num_txpower', c_byte),\n\t\t\t\t('txpower', c_int * 8),\n\t\t\t\t('we_version_compiled', c_byte),\n\t\t\t\t('we_version_source', c_byte),\n\t\t\t\t('retry_capa', c_ushort),\n\t\t\t\t('retry_flags', c_ushort),\n\t\t\t\t('r_time_flags', c_ushort),\n\t\t\t\t('min_retry', c_int ),\n\t\t\t\t('max_retry', c_int ),\n\t\t\t\t('min_r_time', c_int ),\n\t\t\t\t('max_r_time', c_int),\n\t\t\t\t('num_channels', c_ushort),\n\t\t\t\t('num_frequency', c_byte),\n\t\t\t\t('freq', IW_FREQ * 32),\n\t\t\t\t('enc_capa', c_uint)]\n\n\nclass SOCKADDR(Structure):\n\t_fields_ = [('sa_family', c_ushort),\n\t\t\t\t('ss_data', c_char * 14)]\n\n\nclass IWREQ_DATA(Union):\n\t_fields_ = [('name', c_char * 16),\n\t\t\t\t('essid', IW_POINT),\n\t\t\t\t('nwid', IW_PARAM),\n\t\t\t\t('freq', IW_FREQ),\n\t\t\t\t('sens', IW_PARAM),\n\t\t\t\t('bitrate', IW_PARAM),\n\t\t\t\t('txpower', IW_PARAM),\n\t\t\t\t('rts', IW_PARAM),\n\t\t\t\t('frag', IW_PARAM),\n\t\t\t\t('mode', c_uint),\n\t\t\t\t('retry', IW_PARAM),\n\t\t\t\t('encoding', IW_PARAM),\n\t\t\t\t('power', IW_PARAM),\n\t\t\t\t('qual', IW_QUALITY),\n\t\t\t\t('ap_addr', SOCKADDR),\n\t\t\t\t('addr', SOCKADDR),\n\t\t\t\t('param', IW_PARAM),\n\t\t\t\t('data', IW_POINT)]\n\nclass IFR_IFRN(Union):\n\t_fields_ = [('ifr_name', c_char * 16)]\n\n\nclass IW_REQ(Structure):\n\t_fields_ = [('ifr_ifrn', IFR_IFRN),\n\t\t\t\t('iwreq_data', IWREQ_DATA)]\n\n\nclass WirelessIOCTL:\n\t# IOCTL to set channel/frequency (Hz)\n\tSIOCSIWFREQ = 0x8B04\n\t# IOCTL to get channel/frequency (Hz)\n\tSIOCGIWFREQ = 0x8B05\n\t# IOCTL to get range of parameters\n\tSIOCGIWRANGE = 0x8B0B\n\nclass WirelessExtension:\n\t\"\"\"A singleton for getting/caching/setting data with WE IOCTLS\"\"\"\n\n\tdef __init__(self, iface):\n\t\t# Dict to map [channel -> iw_freq]\n\t\tself._freq_map = None\n\n\t\t# Maximum available channel\n\t\tself._max_channel = 0\n\n\t\tself._iface = iface\n\n\t\tself._can_ioctl_set_channel = True\n\t\tself._can_ioctl_get_channel = True\n\t\tself._can_ioctl_freq_map = True\n\n\n\tdef _shell_command(self, cmd):\n\t\t\"\"\"Shell out a subprocess and return what it writes to stdout as a string\"\"\"\n\t\tin_mem_file = SpooledTemporaryFile(max_size=2048, mode=\"r+\")\n\t\tcheck_call(cmd, shell=True, stdout=in_mem_file)\n\t\tin_mem_file.seek(0)\n\t\tstdout = in_mem_file.read()\n\t\tin_mem_file.close()\n\t\treturn stdout\n\n\n\tdef _ioctl(self, code, data, write_on_out=1):\n\t\tsockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tioctl(sockfd.fileno(), code, data, write_on_out)\n\t\tsockfd.close()\n\t\tdel sockfd\n\n\n\tdef _ioctl_get_freq_map(self):\n\t\t\"\"\"Populate an iw_range with data and introspect the frequency data\"\"\"\n\t\tif self._freq_map:\n\t\t\treturn self._freq_map\n\n\t\tif self._can_ioctl_freq_map:\n\t\t\ttry:\n\t\t\t\treq = IW_REQ()\n\t\t\t\treq.ifr_ifrn.ifr_name = self._iface\n\n\t\t\t\t# Allocate an array for the response\n\t\t\t\tresp = IW_RANGE()\n\t\t\t\tresp.num_frequency = 0\n\t\t\t\treq.iwreq_data.data.pointer = cast(pointer(resp), c_void_p)\n\t\t\t\treq.iwreq_data.data.length = sizeof(resp)\n\n\t\t\t\tself._ioctl(WirelessIOCTL.SIOCGIWRANGE, req)\n\n\t\t\t\tself._freq_map = {}\n\t\t\t\tfor index, freq in enumerate(resp.freq):\n\t\t\t\t\tif index >= resp.num_frequency:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif freq.m:\n\t\t\t\t\t\tself._freq_map[str(freq.i)] = freq\n\t\t\t\t\t\tif freq.i > self._max_channel:\n\t\t\t\t\t\t\tself._max_channel = freq.i\n\t\t\texcept IOError:\n\t\t\t\tself._can_ioctl_freq_map = False\n\n\t\tif not self._can_ioctl_freq_map:\n\t\t\tstdout = self._shell_command('iwlist {0} frequency'.format(self._iface))\n\t\t\tmatch = re.search('(\\d+) channels in total', stdout)\n\t\t\tself._max_channel = repr(match)\n\n\t\t\tself._freq_map = {}\n\t\t\tmatch = re.findall('Channel (\\d+) : (\\d+).?(\\d+)?', stdout)\n\t\t\tfor channel_id, freq_lead, freq_trail in match:\n\t\t\t\tfreq = IW_FREQ(i=int(channel_id), m=int(freq_lead + freq_trail), e=7)\n\t\t\t\tself._freq_map[str(freq.i)] = freq\n\n\t\treturn self._freq_map\n\n\n\tdef get_max_channel(self):\n\t\t\"\"\"Get the maximum channel supported by the interface\"\"\"\n\t\tself._ioctl_get_freq_map()\n\t\treturn self._max_channel\n\n\n\tdef get_channel(self):\n\t\t\"\"\"Get the current channel for the interface\"\"\"\n\t\tchannel = 0\n\n\t\tif self._can_ioctl_set_channel:\n\t\t\treq = IW_REQ()\n\t\t\treq.ifr_ifrn.ifr_name = self._iface\n\t\t\ttry:\n\t\t\t\tself._ioctl(WirelessIOCTL.SIOCGIWFREQ, req)\n\t\t\t\tfreq = req.iwreq_data.freq.m\n\t\t\t\t# TODO(ivanlei): Replace with more correct algorithm\n\t\t\t\tchannel = min(14, max(1, (freq - 2407) / 5))\n\n\t\t\texcept IOError:\n\t\t\t\tself._can_ioctl_get_channel = True\n\n\t\tif not self._can_ioctl_get_channel:\n\t\t\tstdout = self._shell_command('iwgetid -c {0}'.format(self._iface))\n\t\t\tmatch = re.search('Channel:(\\d+)', stdout)\n\t\t\tchannel = int(match.group(1))\n\n\t\treturn channel\n\n\n\tdef set_channel(self, channel):\n\t\t\"\"\"Set the current channel for the interface\"\"\"\n\t\tif self._can_ioctl_set_channel:\n\t\t\tself._ioctl_get_freq_map()\n\t\t\tfreq = self._freq_map[str(channel)]\n\n\t\t\treq = IW_REQ()\n\t\t\treq.ifr_ifrn.ifr_name = self._iface\n\t\t\treq.iwreq_data.freq.m = freq.m\n\t\t\treq.iwreq_data.freq.e = freq.e\n\t\t\treq.iwreq_data.freq.i = freq.i\n\t\t\treq.iwreq_data.freq.flags = freq.flags\n\n\t\t\ttry:\n\t\t\t\tself._ioctl(WirelessIOCTL.SIOCSIWFREQ,\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\twrite_on_out=1)\n\t\t\texcept IOError:\n\t\t\t\tself._can_ioctl_set_channel = False\n\n\t\tif not self._can_ioctl_set_channel:\n\t\t\tself._shell_command('iwconfig {0} channel {1}'.format(self._iface, channel))\n\n","sub_path":"airoiv/we.py","file_name":"we.py","file_ext":"py","file_size_in_byte":7102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"58116697","text":"from combinatorics import *\r\nfrom scipy.special import comb\r\n\r\nclass SportsLottery(object):\r\n\r\n\tdef __init__(self, sizes, points, selections):\r\n\t\tself.sizes = sizes\r\n\t\tself.points = points\r\n\t\tself.selections = selections\r\n\t\tself.prob_table = self.probabilities()\r\n\t\tself.prize_table = {}\r\n\r\n\tdef reset(self, sizes, points, selections):\r\n\t\tself.sizes = sizes\r\n\t\tself.points = points\r\n\t\tself.selections = selections\r\n\t\tself.prob_table = self.probabilities()\r\n\t\tself.prize_table = {}\t\t\r\n\t\r\n\tdef score(self, item):\r\n\t\tindex = 0\r\n\t\tlimit = self.sizes[0]\r\n\t\twhile True:\r\n\t\t\tif index >= len(self.sizes):\r\n\t\t\t\tbreak\r\n\t\t\telif item <= limit:\r\n\t\t\t\treturn self.points[index]\r\n\t\t\t\tbreak\r\n\t\t\telse:\r\n\t\t\t\tindex += 1\r\n\t\t\t\tlimit += self.sizes[index]\r\n\t\t\t\t\r\n\tdef probabilities(self):\r\n\t\tnumber_parts = len(self.sizes)\r\n\t\tparts = OrderedPartition(self.selections, number_parts)\r\n\t\tanswer = {}\r\n\t\twhile True:\r\n\t\t\ttemp_part = parts.partition()\r\n\t\t\tpoint_total = 0\r\n\t\t\tcomb_count = 1\r\n\t\t\tfor i in range(0, len(temp_part)):\r\n\t\t\t\tpoint_total += temp_part[i]*self.points[i]\r\n\t\t\t\tcomb_count *= comb(self.sizes[i],temp_part[i])\r\n\t\t\tif comb_count > 0:\r\n\t\t\t\ttest_point = answer.get(point_total)\r\n\t\t\t\tif not test_point:\r\n\t\t\t\t\tanswer[point_total] = comb_count\r\n\t\t\t\telse:\r\n\t\t\t\t\tanswer[point_total] += comb_count\r\n\t\t\tif not parts.increment():\r\n\t\t\t\tbreak\r\n\t\tcomb_total = comb(sum(self.sizes),self.selections)\r\n\t\tfor points, comb_count in answer.items():\r\n\t\t\tanswer[points] /= comb_total\r\n\t\treturn answer\r\n\t\t\t\t","sub_path":"sports_lottery.py","file_name":"sports_lottery.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"605837821","text":"\"\"\"empty message\n\nRevision ID: 284063115099\nRevises: 672f7c0c62a1\nCreate Date: 2017-06-12 05:36:01.341796\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '284063115099'\ndown_revision = '672f7c0c62a1'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_locations', sa.Column('latlng', sa.String(length=64), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user_locations', 'latlng')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/284063115099_.py","file_name":"284063115099_.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499103493","text":"import os\nimport skia\nfrom .errors import DrawbotError\nfrom .text import getShapeFuncForSkiaTypeface\nfrom .segmenting import textSegments, reorderedSegments\n\n\nclass GraphicsState:\n\n def __init__(self, cachedTypefaces=None, _doInitialize=True):\n if cachedTypefaces is None:\n cachedTypefaces = {}\n self.doFill = True\n self.doStroke = False\n self._cachedTypefaces = cachedTypefaces\n\n if not _doInitialize:\n # self.copy() will initialize further\n return\n\n self.fillPaint = skia.Paint(\n Color=0xFF000000,\n AntiAlias=True,\n Style=skia.Paint.kFill_Style,\n )\n self.strokePaint = skia.Paint(\n Color=0xFF000000,\n AntiAlias=True,\n Style=skia.Paint.kStroke_Style,\n )\n self.strokePaint.setStrokeMiter(5) # default better matching DrawBot\n self.textStyle = TextStyle(cachedTypefaces)\n\n def copy(self):\n result = GraphicsState(self._cachedTypefaces, _doInitialize=False)\n for name in [\"doFill\", \"doStroke\"]:\n setattr(result, name, getattr(self, name))\n result.fillPaint = _copyPaint(self.fillPaint)\n result.strokePaint = _copyPaint(self.strokePaint)\n result.textStyle = self.textStyle.copy()\n return result\n\n def setFillColor(self, color):\n if color is None:\n self.doFill = False\n else:\n self.doFill = True\n self.fillPaint.setARGB(*color)\n\n def setStrokeColor(self, color):\n if color is None:\n self.doStroke = False\n else:\n self.doStroke = True\n self.strokePaint.setARGB(*color)\n\n\nclass TextStyle:\n\n def __init__(self, cachedTypefaces, _doInitialize=True):\n self._cachedTypefaces = cachedTypefaces\n self._ttFont = None\n self._shape = None\n\n if not _doInitialize:\n # self.copy() will initialize further\n return\n\n self.font = skia.Font(skia.Typeface(None), 10)\n self.font.setForceAutoHinting(False)\n self.font.setHinting(skia.FontHinting.kNone)\n self.font.setSubpixel(True)\n self.font.setEdging(skia.Font.Edging.kAntiAlias)\n self.features = {}\n self.variations = {}\n\n def copy(self):\n result = TextStyle(self._cachedTypefaces, _doInitialize=False)\n result.font = _copyFont(self.font)\n result.features = dict(self.features)\n result.variations = dict(self.variations)\n\n def setFont(self, fontNameOrPath):\n if os.path.exists(fontNameOrPath):\n path = os.path.normpath(os.path.abspath(os.fspath(fontNameOrPath)))\n tf = self._getFontFromFile(path)\n else:\n tf = skia.Typeface(fontNameOrPath)\n self.font.setTypeface(tf)\n # purge cached items:\n self._ttFont = None\n self._shape = None\n\n def _getFontFromFile(self, fontPath):\n if fontPath not in self._cachedTypefaces:\n tf = skia.Typeface.MakeFromFile(fontPath)\n if tf is None:\n raise DrawbotError(f\"can't load font: {fontPath}\")\n self._cachedTypefaces[fontPath] = tf\n return self._cachedTypefaces[fontPath]\n\n def setOpenTypeFeatures(self, features, resetFeatures):\n if resetFeatures:\n self.features = {}\n self.features.update(features)\n return dict(self.features)\n\n def setFontVariations(self, location, resetVariations):\n from .font import intToTag\n fvar = self.ttFont.get(\"fvar\")\n if fvar is None:\n # TODO: warn?\n return\n\n if resetVariations:\n currentLocation = {a.axisTag: location.get(a.axisTag, a.defaultValue) for a in fvar.axes}\n else:\n pos = self.font.getTypeface().getVariationDesignPosition()\n # XXX: With MutatorSans.ttf, this is \"overcomplete\" on macOS\n # (hence the p.axis != 0 condition), and incomplete on Linux:\n # the wght axis is not reported there.\n # https://github.com/kyamagu/skia-python/issues/113\n currentLocation = {intToTag(p.axis): p.value for p in pos if p.axis != 0}\n\n tags = [a.axisTag for a in fvar.axes]\n location = [(tag, location.get(tag, currentLocation[tag])) for tag in tags]\n self._setFontVariationDesignPosition(location)\n self.variations = dict(location)\n return dict(self.variations)\n\n def _setFontVariationDesignPosition(self, location):\n from .font import tagToInt\n makeCoord = skia.FontArguments.VariationPosition.Coordinate\n rawCoords = [makeCoord(tagToInt(tag), value) for tag, value in location]\n coords = skia.FontArguments.VariationPosition.Coordinates(rawCoords)\n pos = skia.FontArguments.VariationPosition(coords)\n fontArgs = skia.FontArguments()\n fontArgs.setVariationDesignPosition(pos)\n tf = self.font.getTypeface().makeClone(fontArgs)\n self.font.setTypeface(tf)\n\n @property\n def ttFont(self):\n if self._ttFont is None:\n from .font import makeTTFontFromSkiaTypeface\n self._ttFont = makeTTFontFromSkiaTypeface(self.font.getTypeface())\n return self._ttFont\n\n def shape(self, txt):\n if self._shape is None:\n self._shape = getShapeFuncForSkiaTypeface(self.font.getTypeface())\n\n segments, baseLevel = textSegments(txt)\n segments = reorderedSegments(segments, baseLevel)\n startPos = (0, 0)\n glyphsInfo = None\n for runChars, script, bidiLevel, index in segments:\n runInfo = self._shape(\n runChars,\n fontSize=self.font.getSize(),\n startPos=startPos,\n startCluster=index,\n flippedCanvas=True,\n features=self.features,\n variations=self.variations,\n )\n if glyphsInfo is None:\n glyphsInfo = runInfo\n else:\n glyphsInfo.gids += runInfo.gids\n glyphsInfo.clusters += runInfo.clusters\n glyphsInfo.positions += runInfo.positions\n glyphsInfo.endPos = runInfo.endPos\n startPos = runInfo.endPos\n glyphsInfo.baseLevel = baseLevel\n return glyphsInfo\n\n\n_paintProperties = [\n # kwarg getter name\n ('Alpha', 'getAlpha'),\n ('AntiAlias', 'isAntiAlias'),\n ('BlendMode', 'getBlendMode'),\n ('Color', 'getColor'),\n ('ColorFilter', 'getColorFilter'),\n ('Dither', 'isDither'),\n ('FilterQuality', 'getFilterQuality'),\n ('ImageFilter', 'getImageFilter'),\n ('MaskFilter', 'getMaskFilter'),\n ('PathEffect', 'getPathEffect'),\n ('Shader', 'getShader'),\n ('StrokeCap', 'getStrokeCap'),\n ('StrokeJoin', 'getStrokeJoin'),\n ('StrokeMiter', 'getStrokeMiter'),\n ('StrokeWidth', 'getStrokeWidth'),\n ('Style', 'getStyle'),\n]\n\n\ndef _copyPaint(paint):\n # Make a shallow copy of a Paint object.\n # I was hoping for a paint.copy() method, though.\n kwargs = {k: getattr(paint, g)() for k, g in _paintProperties}\n return skia.Paint(**kwargs)\n\n\n_fontProperties = [\n ('setBaselineSnap', 'isBaselineSnap'),\n ('setEdging', 'getEdging'),\n ('setEmbeddedBitmaps', 'isEmbeddedBitmaps'),\n ('setEmbolden', 'isEmbolden'),\n ('setForceAutoHinting', 'isForceAutoHinting'),\n ('setHinting', 'getHinting'),\n ('setLinearMetrics', 'isLinearMetrics'),\n ('setScaleX', 'getScaleX'),\n # ('setSize', 'getSize'),\n ('setSkewX', 'getSkewX'),\n ('setSubpixel', 'isSubpixel'),\n # ('setTypeface', 'getTypeface'),\n]\n\n\ndef _copyFont(font):\n # Make a copy of a Font object.\n # Was hoping for a font.copy() method.\n tf = skia.Typeface.MakeDeserialize(font.getTypeface().serialize())\n newFont = skia.Font(tf, font.getSize())\n for setter, getter in _fontProperties:\n getattr(newFont, setter)(getattr(font, getter)())\n return newFont\n","sub_path":"src/drawbot_skia/gstate.py","file_name":"gstate.py","file_ext":"py","file_size_in_byte":8184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"591886093","text":"from flask import Flask, render_template, request, redirect, url_for, flash\nfrom flask_sqlalchemy import SQLAlchemy\n\n\n\napp = Flask(__name__, template_folder='template')\napp.secret_key = \"Secret Key\"\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/crud'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nclass Tempat(db.Model):\n id = db.Column(db.Integer, primary_key = True)\n name = db.Column(db.String(100))\n\n def __init__ (self, name):\n self.name = name\n\n@app.route('/')\ndef Index():\n all_data = Tempat.query.all()\n data = Item.query.all()\n dat = Subscriber.query.all()\n da = Borrow.query.all()\n return render_template(\"index.html\", library = all_data, item = data, subscriber = dat, borrow = da)\n\n@app.route('/insert', methods = ['POST'])\ndef insert():\n if request.method == 'POST':\n name = request.form['name']\n\n my_data = Tempat(name)\n db.session.add(my_data)\n db.session.commit()\n\n flash(\"Library Added\")\n\n return redirect(url_for('Index'))\n\n@app.route('/update', methods = ['GET', 'POST'])\ndef update():\n if request.method == 'POST':\n my_data = Tempat.query.get(request.form.get('id'))\n\n my_data.name = request.form['name']\n\n db.session.commit()\n\n flash(\"Library Updated\")\n\n return redirect(url_for('Index'))\n\n\n@app.route('/delete//', methods=['GET', 'POST'])\ndef delete(id):\n my_data = Tempat.query.get(id)\n db.session.delete(my_data)\n db.session.commit()\n flash(\"Library Deleted\")\n\n return redirect(url_for('Index'))\n\n\nclass Item(db.Model):\n item_id = db.Column(db.Integer, primary_key = True)\n category = db.Column(db.String(100))\n title = db.Column(db.String(100))\n author = db.Column(db.String(100))\n publisher = db.Column(db.String(100))\n production = db.Column(db.String(100))\n copies = db.Column(db.String(100))\n\n def __init__ (self, category, title, author, publisher, production, copies):\n self.category = category\n self.title = title\n self.author = author\n self.publisher = publisher\n self.production = production\n self.copies = copies\n\n@app.route('/insertitem', methods = ['POST', 'GET'])\ndef insertitem():\n if request.method == 'POST':\n\n category = request.form['category']\n title = request.form['title']\n author = request.form['author']\n publisher = request.form['publisher']\n production = request.form['production']\n copies = request.form['copies']\n\n my_data = Item(category, title, author, publisher, production, copies)\n db.session.add(my_data)\n db.session.commit()\n\n flash(\"Item Added\")\n\n return redirect(url_for('Index'))\n\n@app.route('/updateitem', methods = ['GET', 'POST'])\ndef updateitem():\n if request.method == 'POST':\n my_data = Item.query.get(request.form.get('item_id'))\n\n my_data.category = request.form['category']\n my_data.title = request.form['title']\n my_data.author = request.form['author']\n my_data.publisher = request.form['publisher']\n my_data.production = request.form['production']\n my_data.copies = request.form['copies']\n\n\n db.session.commit()\n\n flash(\"Item Updated\")\n\n return redirect(url_for('Index'))\n\n\n@app.route('/deleteitem//', methods=['GET', 'POST'])\ndef deleteitem(item_id):\n my_data = Item.query.get(item_id)\n db.session.delete(my_data)\n db.session.commit()\n\n flash(\"Item Deleted\")\n\n return redirect(url_for('Index'))\n\nclass Subscriber(db.Model):\n subscriber_id = db.Column(db.Integer, primary_key = True)\n typ = db.Column(db.String(100))\n name_subscriber = db.Column(db.String(100))\n address = db.Column(db.String(100))\n phone = db.Column(db.String(100))\n email = db.Column(db.String(100))\n\n def __init__ (self, typ, name_subscriber, address, phone, email):\n self.typ = typ\n self.name_subscriber = name_subscriber\n self.address = address\n self.phone = phone\n self.email = email\n\n@app.route('/insertsubscriber', methods = ['POST', 'GET'])\ndef insertsubscriber():\n if request.method == 'POST':\n\n typ = request.form['typ']\n name_subscriber = request.form['name_subscriber']\n address = request.form['address']\n phone = request.form['phone']\n email = request.form['email']\n\n my_data = Subscriber(typ, name_subscriber, address, phone, email)\n db.session.add(my_data)\n db.session.commit()\n\n flash(\"Subscriber Added\")\n\n return redirect(url_for('Index'))\n\n@app.route('/updatesubscriber', methods = ['GET', 'POST'])\ndef updatesubscriber():\n if request.method == 'POST':\n my_data = Subscriber.query.get(request.form.get('subscriber_id'))\n\n my_data.typ = request.form['typ']\n my_data.name_subscriber = request.form['name_subscriber']\n my_data.address = request.form['address']\n my_data.phone = request.form['phone']\n my_data.email = request.form['email']\n\n db.session.commit()\n\n flash(\"Subscriber Updated\")\n\n return redirect(url_for('Index'))\n\n@app.route('/deletesubscriber//', methods=['GET', 'POST'])\ndef deletesubscriber(subscriber_id):\n my_data = Subscriber.query.get(subscriber_id)\n db.session.delete(my_data)\n db.session.commit()\n\n flash(\"Subscriber Deleted\")\n\n return redirect(url_for('Index'))\n\nclass Borrow(db.Model):\n sub_id = db.Column(db.Integer, primary_key = True)\n borrowdate = db.Column(db.String(100))\n itemid = db.Column(db.String(100))\n returndate = db.Column(db.String(100))\n fee = db.Column(db.String(100))\n\n def __init__ (self, borrowdate, itemid, returndate, fee):\n self.borrowdate =borrowdate\n self.itemid = itemid\n self.returndate = returndate\n self.fee = fee\n\n@app.route('/insertborrow', methods = ['POST', 'GET'])\ndef insertborrow():\n if request.method == 'POST':\n\n borrowdate = request.form['borrowdate']\n itemid = request.form['itemid']\n returndate = request.form['returndate']\n fee = request.form['fee']\n\n my_data = Borrow(borrowdate, itemid, returndate, fee)\n db.session.add(my_data)\n db.session.commit()\n\n flash(\"Borrow Added\")\n\n return redirect(url_for('Index'))\n\n@app.route('/updateborrow', methods = ['GET', 'POST'])\ndef updateborrow():\n if request.method == 'POST':\n my_data = Borrow.query.get(request.form.get('sub_id'))\n\n my_data.borrowdate = request.form['borrowdate']\n my_data.itemid = request.form['itemid']\n my_data.returndate = request.form['returndate']\n my_data.fee = request.form['fee']\n\n db.session.commit()\n\n flash(\"Borrow Updated\")\n\n return redirect(url_for('Index'))\n\n@app.route('/deleteborrow//', methods=['GET', 'POST'])\ndef deleteborrow(sub_id):\n my_data = Borrow.query.get(sub_id)\n db.session.delete(my_data)\n db.session.commit()\n\n flash(\"Borrow Deleted\")\n\n return redirect(url_for('Index'))\n\n\n\nif __name__ == \"__main__\" :\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"606295705","text":"import gym\nfrom gym.envs.registration import register\nimport sys, tty, termios\nimport numpy as np\nimport random as pr\nimport matplotlib.pyplot as plt\n\ndef rargmax(vector):\n m = np.amax(vector)\n indices = np.nonzero(vector == m)[0]\n return pr.choice(indices)\n\nclass _Getch:\n def __call__(self):\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(3)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\ninkey = _Getch()\n\nLEFT = 0\nDOWN = 1\nRIGHT = 2\nUP =3\n\narrow_keys = {\n '\\x1b[A' : UP,\n '\\x1b[B' : DOWN,\n '\\x1b[C' : RIGHT,\n '\\x1b[D' : LEFT,\n}\n\nregister(\n id='FrozenLake-v3',\n entry_point='gym.envs.toy_text:FrozenLakeEnv',\n kwargs={'map_name' : '4x4', 'is_slippery' : False}\n)\n\nenv = gym.make('FrozenLake-v3')\n\nQ = np.zeros([env.observation_space.n, env.action_space.n])\nnum_episodes = 2000\nrList = []\n\n#discount factor\ndis = .99\n\nfor i in range(num_episodes):\n #decaying E-greedy\n e = 1. / ((i // 100) +1)\n \n state = env.reset()\n rAll = 0\n done = False\n\n while not done:\n #action = np.argmax(Q[state,:]+np.random.randn(1,env.action_space.n) / (i+1))\n #Q[state,action] = reward+dis*max(Q[new_state,:])\n if np.random.rand(1) < e:\n action = env.action_space.sample()\n else:\n action = np.argmax(Q[state, :])\n new_state, reward, done, _ = env.step(action)\n Q[state,action] = reward + dis*np.max(Q[new_state,:])\n rAll += reward\n state = new_state\n rList.append(rAll)\n\nprint(\"Success rate: \" + str(sum(rList)/num_episodes))\nprint(\"Final Q-Table Values\")\nprint(\"LEFT DOWN RIGHT UP\")\nprint(Q)\nplt.bar(range(len(rList)),rList, color=\"blue\")\nplt.show()\n\n#env.render()\n\"\"\"\nwhile True:\n key = inkey()\n if key not in arrow_keys.keys():\n print(\"Game aborted!\")\n break\n action = arrow_keys[key]\n state,reward,done,info = env.step(action)\n env.render()\n print(\"State: \",state, \"Action: \", action, \"Rewar:\", reward, \"Info: \", info)\n\n if done:\n print(\"Finished with reward\", reward)\n break\n\n\"\"\"\n","sub_path":"reinforcement_learning/frozenlake-v3_by_dqn.py","file_name":"frozenlake-v3_by_dqn.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"544892978","text":"from copy import deepcopy\nfrom collections import namedtuple\nfrom contextlib import contextmanager\n\ntry:\n import sqlite3\nexcept ImportError:\n sqlite3 = None\n\ntry:\n import psycopg2\nexcept ImportError:\n psycopg2 = None\n\ntry:\n import MySQLdb as mysql\nexcept ImportError:\n mysql = None\n\n\n__version__ = \"0.4.4\"\n__all__ = [\n \"Clause\",\n \"ClauseError\",\n \"Database\",\n \"DatabaseError\",\n \"EstoultError\",\n \"Field\",\n \"FieldError\",\n \"fn\",\n \"op\",\n \"Query\",\n \"QueryError\",\n]\n\n\nclass EstoultError(Exception):\n pass\n\n\nclass ClauseError(EstoultError):\n pass\n\n\nclass FieldError(EstoultError):\n pass\n\n\nclass QueryError(EstoultError):\n pass\n\n\nclass DatabaseError(EstoultError):\n pass\n\n\n_sql_ops = {\n \"eq\": \"=\",\n \"lt\": \"<\",\n \"le\": \"<=\",\n \"gt\": \">\",\n \"ge\": \">=\",\n \"ne\": \"<>\",\n}\n\n\ndef _parse_arg(arg):\n if isinstance(arg, Clause):\n return arg\n elif isinstance(arg, Field):\n return str(arg), ()\n elif isinstance(arg, Query):\n return arg._query, arg._params\n elif isinstance(arg, list) or isinstance(arg, tuple):\n placeholders = \", \".join([\"%s\"] * len(arg))\n return placeholders, tuple(arg)\n\n return \"%s\", (arg,)\n\n\ndef _parse_args(func):\n def wrapper(*args):\n return func(*[_parse_arg(a) for a in args])\n\n return wrapper\n\n\ndef _strip(string):\n string = string.rstrip(\" ,\")\n\n if string.endswith(\"and\"):\n string = string[:-3]\n\n return string\n\n\ndef _make_op(operator):\n @_parse_args\n def wrapper(lhs, rhs):\n return Clause(f\"({lhs[0]}) {operator} ({rhs[0]})\", tuple(lhs[1] + rhs[1]))\n\n return wrapper\n\n\ndef _make_fn(name):\n def wrapper(*args):\n return Clause(f\"{name}({str(', '.join([str(a) for a in args]))})\", ())\n\n return wrapper\n\n\nclass ClauseMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n # Add op overloading\n for name, operator in _sql_ops.items():\n attrs[f\"__{name}__\"] = _make_op(operator)\n\n return super(ClauseMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n\nclass Clause(namedtuple(\"Clause\", [\"clause\", \"params\"]), metaclass=ClauseMetaclass):\n def __str__(self):\n return self.clause\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, comp):\n return str(self) == comp\n\n\nclass OperatorMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n for name, operator in _sql_ops.items():\n attrs[name] = _make_op(operator)\n\n return super(OperatorMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n\nclass op(metaclass=OperatorMetaclass):\n @classmethod\n def add_op(cls, name, op):\n def func(lhs, rhs):\n fn = _make_op(op)\n return fn(lhs, rhs)\n\n setattr(cls, name, staticmethod(func))\n\n @staticmethod\n @_parse_args\n def or_(lhs, rhs):\n return Clause(f\"(({_strip(lhs[0])}) or ({_strip(rhs[0])}))\", (lhs[1] + rhs[1]))\n\n @staticmethod\n @_parse_args\n def and_(lhs, rhs):\n return Clause(f\"(({_strip(lhs[0])}) and ({_strip(rhs[0])}))\", (lhs[1] + rhs[1]))\n\n @staticmethod\n @_parse_args\n def in_(lhs, rhs):\n return Clause(f\"(({_strip(lhs[0])}) in ({_strip(rhs[0])}))\", (lhs[1] + rhs[1]))\n\n @staticmethod\n @_parse_args\n def like(lhs, rhs):\n return Clause(f\"({lhs[0]}) like ({rhs[0]})\", (lhs[1] + rhs[1]))\n\n @staticmethod\n @_parse_args\n def ilike(lhs, rhs):\n # Does a case insensitive `like`. Only postgres has this operator,\n # but we can hack it together for the others\n if psycopg2:\n return Clause(f\"({lhs[0]}) ilike ({rhs[0]})\", (lhs[1] + rhs[1]))\n\n return Clause(f\"lower({lhs[0]}) like lower({rhs[0]})\", (lhs[1] + rhs[1]))\n\n @staticmethod\n @_parse_args\n def not_(arg):\n return Clause(f\"not ({arg[0]})\", (arg[1]))\n\n @staticmethod\n @_parse_args\n def is_null(arg):\n return Clause(f\"({arg[0]}) is null\", (arg[1]))\n\n @staticmethod\n @_parse_args\n def not_null(arg):\n return Clause(f\"({arg[0]}) is not null\", (arg[1]))\n\n\nclass FunctionMetaclass(type):\n\n sql_fns = [\n \"count\",\n \"sum\",\n \"avg\",\n \"ceil\",\n \"distinct\",\n \"concat\",\n ]\n\n def __new__(cls, clsname, bases, attrs):\n for f in cls.sql_fns:\n attrs[f] = _make_fn(f)\n\n return super(FunctionMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n\nclass fn(metaclass=FunctionMetaclass):\n @classmethod\n def add_fn(cls, name, sql_fn):\n def func(*args):\n fn = _make_fn(sql_fn)\n return fn(*args)\n\n setattr(cls, name, staticmethod(func))\n\n @staticmethod\n def alias(lhs, rhs):\n s, p = _parse_arg(lhs)\n return Clause(f\"{s} as {rhs}\", tuple(p))\n\n @staticmethod\n def cast(lhs, rhs):\n s, p = _parse_arg(lhs)\n return Clause(f\"cast({s} as {rhs})\", tuple(p))\n\n @staticmethod\n def wild(schema):\n return Clause(f\"{schema.__tablename__}.*\", ())\n\n\nclass FieldMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n # Add op overloading\n for name, operator in _sql_ops.items():\n attrs[f\"__{name}__\"] = _make_op(operator)\n\n return super(FieldMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n\nclass Field(metaclass=FieldMetaclass):\n def __init__(self, type, name, **kwargs):\n self.type = type\n self.name = name\n\n self.caster = kwargs.get(\"caster\")\n\n self.null = kwargs.get(\"null\", True)\n self.default = kwargs.get(\"default\")\n self.primary_key = kwargs.get(\"primary_key\") is True\n\n @property\n def full_name(self):\n return f\"{self.schema.__tablename__}.{self.name}\"\n\n def __str__(self):\n return self.full_name\n\n def __hash__(self):\n return hash(str(self))\n\n def __eq__(self, comp):\n return str(self) == comp\n\n\nclass SchemaMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n # Deepcopy inherited fields\n for base in bases:\n at = dir(base)\n\n for a in at:\n f = getattr(base, a)\n\n if isinstance(f, Field):\n attrs[a] = deepcopy(f)\n\n c = super(SchemaMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n # Add schema to fields\n for key in dir(c):\n f = getattr(c, key)\n\n if isinstance(f, Field):\n f.schema = c\n\n return c\n\n @property\n def fields(cls):\n return [\n getattr(cls, key)\n for key in dir(cls)\n if isinstance(getattr(cls, key), Field)\n ]\n\n @property\n def pk(cls):\n pk = None\n\n for field in cls.fields:\n if field.primary_key is True:\n return field\n\n if field.name == \"id\":\n pk = field\n\n return pk\n\n def __getitem__(cls, item):\n return getattr(cls, item)\n\n\nclass Schema(metaclass=SchemaMetaclass):\n\n _database_ = None\n __tablename__ = None\n\n @classmethod\n def _cast(cls, updating, row):\n # Allow you to use a Field as key\n for key, value in list(row.items()):\n if isinstance(key, Field):\n row[key.name] = value\n else:\n row[key] = value\n\n changeset = {}\n\n for field in cls.fields:\n value = None\n\n if field.default is not None:\n value = field.default\n\n try:\n value = row[field.name]\n except KeyError:\n if updating is True or field.name == cls.pk.name:\n continue\n\n if value is not None:\n value = (\n field.type(value) if field.caster is None else field.caster(value)\n )\n\n changeset[field.name] = value\n\n return changeset\n\n @classmethod\n def _validate(cls, updating, row):\n changeset = {}\n\n for field in cls.fields:\n try:\n value = row[field.name]\n except KeyError:\n continue\n\n if field.null is False and value is None and updating is True:\n raise FieldError(f\"{str(field)} cannot be None\")\n\n changeset[field.name] = value\n\n return changeset\n\n @classmethod\n def casval(cls, row, updating):\n changeset = cls._cast(updating, row)\n changeset = cls._validate(updating, changeset)\n\n # A user specified validation function\n validate_func = getattr(cls, \"validate\", lambda x: x)\n changeset = validate_func(changeset)\n\n return changeset\n\n @classmethod\n def insert(cls, obj):\n changeset = cls.casval(obj, updating=False)\n\n params = list(changeset.values())\n fields = \", \".join(changeset.keys())\n placeholders = \", \".join([\"%s\"] * len(changeset))\n\n sql = f\"insert into {cls.__tablename__} (%s) values (%s)\\n\" % (\n fields,\n placeholders,\n )\n\n if psycopg2 is not None:\n sql += f\"returning {cls.pk.name}\\n\"\n\n return cls._database_.insert(_strip(sql), params)\n\n @classmethod\n def update(cls, old, new):\n # This updates a single row only, if you want to update several\n # use `update` in `Query`\n changeset = cls.casval({**old, **new}, updating=True)\n sql = f\"update {cls.__tablename__} set \"\n params = []\n\n for key, value in changeset.items():\n sql += f\"{key} = %s, \"\n params.append(value)\n\n sql = f\"{_strip(sql)} where \"\n\n for key, value in old.items():\n sql += f\"{key} = %s and \"\n params.append(value)\n\n return cls._database_.sql(_strip(sql), params)\n\n @classmethod\n def update_by_pk(cls, id, new):\n return cls.update({cls.pk.name: id}, new)\n\n @classmethod\n def delete(cls, row):\n # Deletes single row - look at `Query` for batch\n sql = f\"delete from {cls.__tablename__} where \"\n params = []\n\n for key, value in row.items():\n sql += f\"{key} = %s and \"\n params.append(value)\n\n return cls._database_.sql(_strip(sql), params)\n\n @classmethod\n def delete_by_pk(cls, id, new):\n return cls.delete({cls.pk.name: id}, new)\n\n\nclass QueryMetaclass(type):\n\n sql_joins = [\n \"inner join\",\n \"left join\",\n \"left outer join\",\n \"right join\",\n \"right outer join\",\n \"full join\",\n \"full outer join\",\n ]\n\n @staticmethod\n def make_join_fn(join_type):\n def join_fn(self, schema, on):\n q = f\"{str(on[0])} = {str(on[1])}\"\n self._add_node(f\"{join_type} {schema.__tablename__} on {q}\", ())\n return self\n\n return join_fn\n\n def __new__(cls, clsname, bases, attrs):\n for join_type in cls.sql_joins:\n attrs[join_type.replace(\" \", \"_\")] = QueryMetaclass.make_join_fn(join_type)\n\n return super(QueryMetaclass, cls).__new__(cls, clsname, bases, attrs)\n\n\nNode = namedtuple(\"Node\", [\"node\", \"params\"])\n\n\nclass Query(metaclass=QueryMetaclass):\n def __init__(self, schema):\n self.schema = schema\n\n self._method = None\n self._nodes = []\n\n def _add_node(self, node, params):\n self._nodes.append(Node(_strip(node), params))\n\n @property\n def _query(self):\n return \" \".join([x.node for x in self._nodes])\n\n @property\n def _params(self):\n return tuple([p for x in self._nodes for p in x.params])\n\n def select(self, *args):\n self._method = \"select\"\n\n query = \"\"\n params = []\n\n if len(args) < 1:\n query += \"*\"\n else:\n for arg in args:\n if isinstance(arg, Clause):\n string, p = arg\n query += f\"{string}, \"\n params.extend(p)\n else:\n query += f\"{arg}, \"\n\n self._add_node(\n f\"select {_strip(query)} from {self.schema.__tablename__}\", params\n )\n\n return self\n\n def update(self, changeset):\n self._method = \"sql\"\n\n changeset = self.schema.casval(changeset, updating=True)\n\n query = \"\"\n params = []\n\n for key, value in changeset.items():\n query += f\"{key} = %s, \"\n params.append(value)\n\n self._add_node(f\"update {self.schema.__tablename__} set {query}\", params)\n\n return self\n\n def delete(self):\n self._method = \"sql\"\n self._add_node(f\"delete from {self.schema.__tablename__}\", ())\n return self\n\n def get(self, *args):\n self.select(*args)\n self._method = \"get\"\n return self\n\n def get_or_none(self, *args):\n self.select(*args)\n self._method = \"get_or_none\"\n return self\n\n def union(self):\n self._add_node(\"union\", ())\n return self\n\n def where(self, *clauses):\n query = \"\"\n params = []\n\n for clause in clauses:\n string, p = clause\n\n # We can always add an `and` to the end cus it get stripped off ;)\n query += f\"{string} and \"\n params.extend(p)\n\n self._add_node(f\"where {query}\", params)\n\n return self\n\n def limit(self, *args):\n # Example: .limit(1) or limit(1, 2)\n if len(args) == 1:\n self._add_node(\"limit %s\", (args,))\n elif len(args) == 2:\n # `offset` works in mysql and postgres\n self._add_node(\"limit %s offset %s\", args)\n else:\n raise QueryError(\"`limit` has too many arguments\")\n\n return self\n\n def order_by(self, *args):\n # Example: .order_by(Frog.id, {Frog.name: \"desc\"})\n query = \"order by \"\n params = []\n\n for a in args:\n v = None\n\n if isinstance(a, dict):\n k, v = next(iter(a.items()))\n\n if v != \"asc\" and v != \"desc\":\n raise QueryError(\"Value must be 'asc' or 'desc'\")\n else:\n k = a\n\n if isinstance(k, Clause):\n c, p = _parse_arg(k)\n query += \"%s \" % c\n params.extend(p)\n else:\n query += \"%s \"\n params.append(str(k))\n\n if v:\n query += f\"{v}, \"\n\n self._add_node(f\"{query}\", params)\n\n return self\n\n def execute(self):\n func = getattr(self.schema._database_, self._method)\n return func(self._query, self._params)\n\n def copy(self):\n return deepcopy(self)\n\n def __str__(self):\n return self.schema._database_.mogrify(self._query, self._params).decode(\"utf-8\")\n\n def __repr__(self):\n return f''\n\n\ndef _replace_placeholders(func):\n def wrapper(self, query, *args, **kwargs):\n query = query.replace(\"%s\", self.placeholder)\n return func(self, query, *args, **kwargs)\n\n return wrapper\n\n\ndef _get_connection(func):\n def wrapper(self, *args, **kwargs):\n if self.autoconnect is True:\n self.connect()\n\n if self.is_trans is False:\n self._new_cursor()\n\n f = func(self, *args, **kwargs)\n\n if self.autoconnect is True:\n self.close()\n\n return f\n\n return wrapper\n\n\nclass Database:\n def __init__(self, autoconnect=True, *args, **kwargs):\n self.autoconnect = autoconnect\n\n self.Schema = Schema\n self.Schema._database_ = self\n\n self._conn = None\n self._cursor = None\n self.is_trans = False\n\n self.cargs = args\n self.ckwargs = kwargs\n\n def connect(self):\n self._conn = self._connect()\n\n def conn(self):\n return self._conn\n\n def _close(self):\n self._conn.close()\n\n def close(self):\n return self._close()\n\n def _new_cursor(self):\n self._cursor = self.conn.cursor()\n\n @property\n def cursor(self):\n if self._cursor is None:\n self._cursor = self.conn.cursor()\n\n return self._cursor\n\n @contextmanager\n def atomic(self, commit=True):\n # estoult says trans rights\n self.is_trans = True\n\n try:\n yield\n except Exception as err:\n self.conn.rollback()\n raise err\n else:\n if commit:\n self.conn.commit()\n else:\n self.conn.rollback()\n finally:\n self.is_trans = False\n\n @_replace_placeholders\n def _execute(self, query, params):\n self.cursor.execute(query, params)\n\n if self.is_trans is False:\n self.conn.commit()\n\n @_get_connection\n def sql(self, query, params):\n return self._execute(query, params)\n\n @_get_connection\n def mogrify(self, query, params):\n with self.atomic(commit=False):\n self._execute(query, params)\n return self.cursor._executed\n\n @_get_connection\n def select(self, query, params):\n self._execute(query, params)\n cols = [col[0] for col in self.cursor.description]\n return [dict(zip(cols, row)) for row in self.cursor.fetchall()]\n\n @_get_connection\n def insert(self, query, params):\n self._execute(query, params)\n\n if psycopg2 is not None:\n return self.cursor.fetchone()[0]\n\n return self.cursor.lastrowid\n\n def get(self, query, params):\n row = self.select(query, params)\n return row[0]\n\n def get_or_none(self, query, params):\n try:\n return self.get(query, params)\n except IndexError:\n return None\n\n\nclass MySQLDatabase(Database):\n def __init__(self, *args, **kwargs):\n self.placeholder = \"%s\"\n\n super().__init__(*args, **kwargs)\n\n def _connect(self):\n return mysql.connect(*self.cargs, **self.ckwargs)\n\n\nclass PostgreSQLDatabase(Database):\n def __init__(self, *args, **kwargs):\n self.placeholder = \"%s\"\n\n super().__init__(*args, **kwargs)\n\n def _connect(self):\n return psycopg2.connect(*self.cargs, **self.ckwargs)\n\n @_get_connection\n def mogrify(self, query, params):\n return self.cursor.mogrify(query, params)\n\n\nclass SQLiteDatabase(Database):\n def __init__(self, *args, **kwargs):\n self.placeholder = \"?\"\n\n super().__init__(*args, **kwargs)\n\n def _connect(self):\n return sqlite3.connect(*self.cargs, **self.ckwargs)\n","sub_path":"estoult.py","file_name":"estoult.py","file_ext":"py","file_size_in_byte":18538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"77591647","text":"import django_filters as filters\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext_lazy as _\nfrom .models import *\n\n\nclass InsuranceDebtFilter(filters.FilterSet):\n debt_no_filter = filters.CharFilter(label=_('Debt No'), method='custom_debt_no_filter')\n\n class Meta:\n model = InsuranceDebt\n fields = {\n 'sub_contract': ['exact'],\n 'type': ['exact'],\n 'status': ['exact'],\n 'driver_government_id': ['icontains'],\n 'driver_mobile': ['icontains'],\n 'ref_no': ['exact'],\n }\n\n def custom_debt_no_filter(self, queryset, name, value):\n return queryset.filter(Q(pk__exact=value) | Q(legacy_system_no__exact=value))\n\n # def __init__(self, *args, **kwargs):\n # super(InsuranceDebtFilter, self).__init__(*args, **kwargs)\n # self.filters['id'].label = _('Insurance Debt No')\n","sub_path":"debtcollect/insurancedebt/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"438988452","text":"# coding:utf8\nfrom django.conf.urls import patterns, include, url\nfrom django.http import HttpResponse\n\nfrom myblog.views import RSSFeed\n\nurlpatterns = patterns('myblog',\n # url(r'^home/settings', 'jfpal.views.settings_', name='startup.app.settings'),\n url(r'^$', 'views.index'),\n url(r'^article/list$', 'views.article_info_list'),\n url(r'^article/details$', 'views.article_details'),\n url(r'^article/next$', 'views.next_article_details'),\n url(r'^article/previous$', 'views.previous_article_details'),\n url(r'^right/container$', 'views.right_container'),\n url(r'^add/comment$', 'views.add_comment'),\n url(r'^load/comment$', 'views.comment'),\n url(r'^load/article$', 'views.article_info_list'),\n url(r'^change$', 'views.change'),\n url(r'^about$', 'views.about'),\n url(r'^archives$', 'views.archives'),\n url(r'^categories$', 'views.categories'),\n url(r'^feed/$', RSSFeed()),\n )\n","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"544214129","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\n\nimport sys\nimport numpy as np\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom geometry_msgs.msg import Twist\nimport time\n\nclass image_converter:\n\n def __init__(self):\n self.cmd_vel_pub = rospy.Publisher(\"/cmd_vel\",Twist, queue_size=2)\n\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/camera/color/image_raw\",Image, self.callback)\n self.twist = Twist()\n\n \n def callback(self,data):\n try:\n image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n \n #converting bgr to hsv in order to identify the green color\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n # crop =cv2.resize(cv_image,(500,250))\n except CvBridgeError as e:\n print(e)\n\n lower_red = np.array([0, 55, 55])\n upper_red = np.array([10, 255, 255]) \n mask = cv2.inRange(hsv, lower_red, upper_red)\n \n h, w, d = image.shape\n \n M = cv2.moments(mask)\n\n\n if M['m00'] > 0:\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n #cv2.circle(image, (cx, cy), 20, (0,0,255), -1)\n \n #err = cx - w/2\n \n\n if cy > 320:\n self.twist.linear.x = 0.0\n self.twist.angular.z = 0.0\n self.cmd_vel_pub.publish(self.twist)\n \n \n\n cv2.imshow(\"Red_detection\", mask)\n \n cv2.waitKey(3)\n\n \n \n \ndef main(args):\n ic = image_converter()\n rospy.init_node('red', anonymous = True)\n\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n \n","sub_path":"pile/src/red.py","file_name":"red.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"548665784","text":"#!/usr/bin/env python\n\n'''**********************************\nE-yantra\nTheme: Vitran Drone\nTask: task3\nPurpose: marker detection\nTeam ID : 0583\nTeam name : !ABHIMANYU \n**********************************'''\n\nfrom vitarana_drone.msg import MarkerData\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nimport cv2\nimport numpy as np\nimport rospy\nfrom sensor_msgs.msg import NavSatFix, Imu\nfrom std_msgs.msg import String,Float64,Float32, Int8\nimport matplotlib.pyplot as plt\nimport rospkg\nimport math\nimport time\n\nclass image_detection():\n\n # Initialise everything\n def __init__(self):\n rospy.init_node('marker_detect') # Initialise rosnode\n self.img = np.empty([])\n\n self.theta = 0\n self.vertical_distance = 0\n\n img_width = 400\n hfov_rad = 1.3962634 \n self.focal_length = (img_width/2)/math.tan(hfov_rad/2)\n self.curr_marker_id = 0\n self.marker_data = MarkerData()\n # This will contain your image frame from camera\n self.bridge = CvBridge()\n # self.pub = rospy.Publisher('qrValue',String,queue_size=1)\n # self.pub = rospy.Publisher('/edrone/marker_data',Float64,queue_size=1)\n #self.pub = rospy.Publisher('pixValue',Int32MultiArray,queue_size=1)\n self.rate = rospy.Rate(1)\n # Subscribing to the camera topic\n self.image_sub = rospy.Subscriber(\n \"/edrone/camera/image_raw\", Image, self.image_callback)\n\n rospy.Subscriber(\"/edrone/curr_marker_id\", Int8, self.marker_id_callback)\n rospy.Subscriber(\"/edrone/vertical_distance\", Float64, self.vertical_distance_callback)\n rospy.Subscriber(\"/edrone/yaw\", Float64, self.theta_callback)\n\n\n rospack = rospkg.RosPack()\n filepath = rospack.get_path('vitarana_drone')+'/data/cascade.xml'\n self.logo_cascade = cv2.CascadeClassifier(filepath)\n self.marker_data_pub = rospy.Publisher(\"/edrone/marker_data\", MarkerData, queue_size = 1)\n\n # self.err_x_m = rospy.Publisher('/edrone/err_x_m', Float64, queue_size = 1)\n # self.err_y_m = rospy.Publisher('/edrone/err_y_m', Float64, queue_size = 1)\n \n rospy.spin()\n\n\n def marker_id_callback(self, msg):\n self.curr_marker_id = msg.data\n\n def vertical_distance_callback(self, data):\n self.vertical_distance = data.data\n \n\n def theta_callback(self, msg):\n self.theta = msg.data\n\n def pixel_to_m(self,centre_x_pixel, centre_y_pixel):\n err_x = (centre_x_pixel*self.vertical_distance)/self.focal_length\n err_y = (centre_y_pixel*self.vertical_distance)/self.focal_length\n err_x = err_x*np.cos(self.theta) - err_y*np.sin(self.theta)\n err_y= err_x*np.sin(self.theta) + err_y*np.cos(self.theta)\n\n self.marker_data.marker_id = self.curr_marker_id\n self.marker_data.err_x_m = err_x\n self.marker_data.err_y_m = err_y\n self.marker_data_pub.publish(self.marker_data)\n # self.rate.sleep()\n\n # t = time.time()\n # while time.time() - t <= 1:\n # pass\n\n # self.err_x_m.publish(err_x)\n # self.err_y_m.publish(err_y)\n\n # Callback function of camera topic\n def image_callback(self, data):\n try:\n # Converting the image to OpenCV standard image\n self.img = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n gray = cv2.cvtColor(self.img,cv2.COLOR_BGR2GRAY)\n logo = self.logo_cascade.detectMultiScale(gray, scaleFactor=1.05,minNeighbors=5)\n\n for (x, y, w, h) in logo:\n cv2.rectangle(self.img, (x, y), (x + w, y + h), (255, 255, 0), 2)\n #print(x + w/2)\n #print(y + h/2)\n\n #Pixel coordinates wrt drone\n centre_x = x + w/2 - 200\n centre_y = 200 - (y + h/2)\n self.pixel_to_m(centre_x, centre_y)\n #data_for_publishing = Int32MultiArray(data = [centre_x, centre_y])\n \n # plt.imshow(cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB))\n cv2.imshow('image',self.img)\n cv2.waitKey(1)\n # plt.show()\n # plt.clf()\n\n except CvBridgeError as e:\n print(e)\n return\n\n\nif __name__ == '__main__':\n try:\n image_dec_obj = image_detection()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"task3_submission/Task_3_VD_0583_detect_marker_cascade.py","file_name":"Task_3_VD_0583_detect_marker_cascade.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"411778593","text":"from django.contrib import admin\n\nfrom .models import Panda\n\n\nclass PandaAdmin(admin.ModelAdmin):\n list_display = [\n 'id',\n 'email',\n 'title',\n 'first_name',\n 'last_name',\n ]\n list_display_links = ['email']\n\nadmin.site.register(Panda, PandaAdmin)\n","sub_path":"rest_panda/panda/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"286989970","text":"from django.db import models\nfrom django.contrib.auth.models import User, Permission, Group\nfrom django.utils.translation import ugettext as _\nfrom django.core.validators import RegexValidator\nimport uuid\nimport os.path\n\n\ndef imagefield_upload_to(instance, filename):\n return os.path.join(\n type(instance).__name__.lower(),\n str(uuid.uuid4()) + os.path.splitext(filename)[1]\n )\n\n\nclass Profile(models.Model):\n GENDER_MALE = 'M'\n GENDER_FEMALE = 'F'\n GENDER_OTHER = 'O'\n GENDER_CHOICES = (\n (GENDER_MALE, 'Male'),\n (GENDER_FEMALE, 'Female'),\n (GENDER_OTHER, 'Other'),\n )\n birth_date = models.DateField(_('Birth date'))\n gender = models.CharField(\n max_length=1,\n choices=GENDER_CHOICES,\n default=GENDER_OTHER,\n )\n address = models.CharField(max_length=256)\n city = models.CharField(max_length=64)\n zip_code = models.CharField(\n max_length=10,\n validators=[RegexValidator(regex='^\\d{2,5}-\\d{3,4}$')]\n )\n pesel = models.DecimalField(max_digits=11, decimal_places=0)\n avatar = models.URLField(blank=True)\n user = models.OneToOneField(User)\n\n\nclass Unit(models.Model):\n code = models.CharField(max_length=32, primary_key=True)\n name = models.CharField(max_length=32)\n\n def __str__(self):\n return self.name\n\n\nclass Test(models.Model):\n name = models.CharField(max_length=128)\n time = models.DateTimeField()\n patient = models.ForeignKey(User, related_name='test_patient')\n doctor = models.ForeignKey(User, related_name='test_doctor')\n\n def __str__(self):\n return '{} ({}, {})'.format(self.name, str(self.patient), self.time)\n\n\nclass TestEntry(models.Model):\n name = models.CharField(max_length=32)\n value = models.DecimalField(max_digits=8, decimal_places=2)\n unit = models.ForeignKey(Unit, related_name='test_units', on_delete=models.CASCADE)\n test = models.ForeignKey(Test, related_name='test_entries', on_delete=models.CASCADE)\n\n def __str__(self):\n return '{}: {} {}'.format(self.name.title(), self.value, self.unit)\n\n\nclass TestImage(models.Model):\n summary = models.CharField(max_length=1024)\n description = models.TextField()\n image = models.ImageField(upload_to=imagefield_upload_to)\n test = models.ForeignKey(Test, related_name='test_images', on_delete=models.CASCADE)\n\n\nclass Prescription(models.Model):\n issue_date = models.DateTimeField(auto_now_add=True)\n expiration_date = models.DateTimeField()\n patient = models.ForeignKey(User, related_name='prescription_patient')\n doctor = models.ForeignKey(User, related_name='prescription_doctor')\n\n def __str__(self):\n return '{} {}'.format(\n self.issue_date,\n str(self.patient),\n )\n\n\nclass PrescriptionEntry(models.Model):\n class Meta:\n verbose_name_plural = 'prescription entries'\n\n name = models.CharField(max_length=128)\n quantity = models.PositiveIntegerField()\n unit = models.ForeignKey(Unit, related_name='prescription_units', on_delete=models.CASCADE)\n prescription = models.ForeignKey(Prescription, related_name='prescription_entries', on_delete=models.CASCADE)\n\n\nclass Visit(models.Model):\n time = models.DateTimeField()\n patient = models.ForeignKey(User, related_name='visit_patient')\n doctor = models.ForeignKey(User, related_name='visit_doctor')\n description = models.TextField()\n\n def __str__(self):\n return '{} {}'.format(\n self.time,\n str(self.patient),\n )\n\nUser._meta.verbose_name = 'patient'\nUser._meta.verbose_name_plural = 'patients'\n\ndef user_str(self):\n u_str = '{} {}'.format(\n self.first_name,\n self.last_name,\n )\n\n try:\n u_str += ' ({})'.format(self.profile.pesel)\n except:\n pass\n\n return u_str\n\nUser.add_to_class('__str__', user_str)\n","sub_path":"server/patients/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"388445282","text":"import cv2 as cv\nimport random\nimport numpy as np\n\npath = 'D://Tello/img'\n\nwidth, height = 300, 300 #设置拍摄窗口大小\nx0,y0 = 300, 100\n\ndef rotate(image, scale=0.9):\n angle = random.randrange(-90, 90)#随机角度\n w = image.shape[1]\n h = image.shape[0]\n #rotate matrix\n M = cv.getRotationMatrix2D((w/2,h/2), angle, scale)\n #rotate\n image = cv.warpAffine(image,M,(w,h))\n return image\n\n\n\nframe = cv.VideoCapture(0)\nframe.open(1)\ncnt = 7\nnum = 0\nwhile(1):\n ret,pict = frame.read()\n pict = cv.flip(pict,1)\n #ycrcb = cv.cvtColor(pict, cv.COLOR_BGR2YCrCb)\n #(_, cr, _) = cv.split(ycrcb)\n #cr1 = cv.GaussianBlur(cr, (5, 5), 0)\n #_, skin = cv.threshold(cr1, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)\n #pict = cv.bitwise_and(pict,pict,mask = skin)\n #kernel = np.ones((3,3), np.uint8)\n #pict = cv.erode(pict, kernel)\n #pict = cv.dilate(pict, kernel)\n pict = pict[x0:x0+width,y0:y0+height]#取手势所在框图并进行处理\n key = cv.waitKey(10) & 0xFF\n if key == ord('i'):\n y0 += 5\n elif key == ord('k'):\n\t y0 -= 5\n elif key == ord('l'):\n\t x0 += 5\n elif key == ord('j'):\n\t x0 -= 5\n elif key == ord('c'):\n cnt += 1\n cv.imwrite(path + '/' + str(num) + '/' + str(cnt)+ '.png',pict)\n elif key == ord('v'):\n num += 1\n cnt = 7\n elif key == ord('q'):\n break\n ycrcb = cv.cvtColor(pict, cv.COLOR_BGR2YCrCb)\n (_, cr, _) = cv.split(ycrcb)\n cr1 = cv.GaussianBlur(cr, (5, 5), 0)\n _, skin = cv.threshold(cr1, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)\n pict = cv.bitwise_and(pict,pict,mask = skin)\n kernel = np.ones((3,3), np.uint8)\n pict = cv.erode(pict, kernel)\n pict = cv.dilate(pict, kernel)\n cv.imshow(\"test\",pict)\nframe.release()\ncv.destroyAllWindows()","sub_path":"2018202159/第二次报告/code/get_gesture.py","file_name":"get_gesture.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"96954323","text":"from ev3.ev3dev import Msensor\nimport unittest\nfrom util import get_input\n\n\nclass TestMsensor(unittest.TestCase):\n\n def test_msensor(self):\n get_input('Attach a Msensor on port 1 then continue')\n d = Msensor(port=1)\n print(d.mode)\n type_id = d.type_id\n print(type_id)\n print(d.port)\n d = Msensor(type_id=type_id)\n print(d.mode)\n print(d.type_id)\n print(d.port)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_ev3_msensor.py","file_name":"test_ev3_msensor.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"248976008","text":"import boto3\nimport json\nimport os\n\nfrom multiprocessing import Queue, Process\n\ns3 = boto3.resource(\"s3\")\n\nbucket = s3.Bucket(\"com.amazon.evi.fever.wiki\")\n\nid = 0\n\n\nq = Queue(maxsize=4000)\nkeys = []\n\n\nshutdown = False\n\n\ndef process_article():\n while not (shutdown and q.empty()):\n try:\n a,b = q.get(15)\n contents = bucket.Object(a).get()[\"Body\"].read().decode(\"utf-8\")\n lines = contents.split(\"\\n\")\n lines = map(lambda line: line.split(\"\\t\")[1] if len(line.split(\"\\t\"))>1 else \"\",lines)\n with open(b,\"w+\") as f:\n f.write(\"\\n\".join(lines))\n except:\n print(\"QException\")\n print(\"Queue finished\")\n\n\nfor _ in range(500):\n t = Process(target=process_article)\n t.start()\n\n\nfor obj in bucket.objects.filter(Prefix=\"intro_sentences/\").page_size(100):\n keys.append(obj.key)\n\n store_path = \"data/intros/\"+str(id).zfill(10)+\".txt\"\n q.put((obj.key,store_path))\n\n if id % 1e4 == 0:\n print(\"Done\",id)\n\n id += 1\n\n\nprint(\"Finished indexing. Writing keys\")\njson.dump(keys, open(\"data/intro.keys.json\", \"w+\"))\nprint(\"Shutting down\")\n\n\nshutdown = True\nprint(\"Waiting for queues to stop\")","sub_path":"src/dataset/indexing/download_bucket.py","file_name":"download_bucket.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"465839879","text":"#!/usr/bin/python\n\nHEADER = '\\033[95m'\nOKBLUE = '\\033[94m'\nOKGREEN = '\\033[92m'\nWARNING = '\\033[93m'\nFAIL = '\\033[91m'\nENDC = '\\033[0m'\nBOLD = '\\033[1m'\nUNDERLINE = '\\033[4m'\n\ndef substring_after(s, delim):\n return s.partition(delim)[2]\n\nimport os\nimport glob\nimport pandas as pd\nimport time\nimport datetime\nimport subprocess\nfrom subprocess import STDOUT\nfrom filecmp import cmp\nbinaries_dict = {}\nGPU_binaries_dict = {}\n\nos.chdir(\"new_binaries\")\npathToDir = os.getcwd()\nbinaries_cpu_new = sorted(glob.glob('GOMC_CPU_*'), key=os.path.getmtime)\nbinaries_gpu_new = sorted(glob.glob('GOMC_GPU_*'), key=os.path.getmtime)\nfor binary in binaries_cpu_new:\n binaries_dict[substring_after(binary, \"GOMC_\")+\"_new\"] = os.path.join(pathToDir, binary)\nfor binary in binaries_gpu_new:\n binaries_dict[substring_after(binary, \"GOMC_\")+\"_new\"] = os.path.join(pathToDir, binary)\n\nos.chdir(\"../ref_binaries\")\npathToDir = os.getcwd()\nbinaries_cpu_ref = sorted(glob.glob('GOMC_CPU_*'), key=os.path.getmtime)\nbinaries_gpu_ref = sorted(glob.glob('GOMC_GPU_*'), key=os.path.getmtime)\nfor binary in binaries_cpu_ref:\n binaries_dict[substring_after(binary, \"GOMC_\")+\"_ref\"] = os.path.join(pathToDir, binary)\nfor binary in binaries_gpu_ref:\n binaries_dict[substring_after(binary, \"GOMC_\")+\"_ref\"] = os.path.join(pathToDir, binary)\n\n\nos.chdir(\"../integration\")\n\nconfFileName = \"in.conf\"\n\nLog_Template_file = open(\"IntegrationTest2.log\", 'w')\nLog_Template_file.write(\"opened Log\")\n\nlistOfTests = []\n\n# traverse root directory, and list directories as dirs and files as files\n# traverse root directory, and list directories as dirs and files as files\nfor root, dirs, files in os.walk(\".\"):\n path = root.split(os.sep)\n for file in files:\n if file==confFileName:\n newOrRef = \"\"\n cpuOrGpu = \"\"\n if \"new_cpu\" in path:\n newOrRef = \"_new\"\n cpuOrGpu = \"CPU_\"\n elif \"ref_cpu\" in path:\n newOrRef = \"_ref\"\n cpuOrGpu = \"CPU_\"\n elif \"new_gpu\" in path:\n newOrRef = \"_new\"\n cpuOrGpu = \"GPU_\"\n elif \"ref_gpu\" in path:\n newOrRef = \"_ref\"\n cpuOrGpu = \"GPU_\"\n\n if cpuOrGpu+\"NVT\"+newOrRef in binaries_dict and 'NVT' in path and 'NVT_GEMC' not in path:\n command = binaries_dict[cpuOrGpu+\"NVT\"+newOrRef],os.path.abspath(root),cpuOrGpu+\"NVT\"+newOrRef,cpuOrGpu,newOrRef,\"NVT_\"+os.path.basename(root)\n listOfTests.append(command)\n elif cpuOrGpu+\"NPT\"+newOrRef in binaries_dict and 'NPT' in path and 'NPT_GEMC' not in path:\n command = binaries_dict[cpuOrGpu+\"NPT\"+newOrRef],os.path.abspath(root),cpuOrGpu+\"NPT\"+newOrRef,cpuOrGpu,newOrRef,\"NPT_\"+os.path.basename(root)\n listOfTests.append(command)\n elif cpuOrGpu+\"GCMC\"+newOrRef in binaries_dict and 'GCMC' in path:\n command = binaries_dict[cpuOrGpu+\"GCMC\"+newOrRef],os.path.abspath(root),cpuOrGpu+\"GCMC\"+newOrRef,cpuOrGpu,newOrRef,\"GCMC_\"+os.path.basename(root)\n listOfTests.append(command)\n elif cpuOrGpu+\"GEMC\"+newOrRef in binaries_dict and 'NVT_GEMC' in path:\n command = binaries_dict[cpuOrGpu+\"GEMC\"+newOrRef],os.path.abspath(root),cpuOrGpu+\"NVT_GEMC\"+newOrRef,cpuOrGpu,newOrRef,\"NVT_GEMC_\"+os.path.basename(root)\n listOfTests.append(command)\n elif cpuOrGpu+\"GEMC\"+newOrRef in binaries_dict and 'NPT_GEMC' in path:\n command = binaries_dict[cpuOrGpu+\"GEMC\"+newOrRef],os.path.abspath(root),cpuOrGpu+\"NPT_GEMC\"+newOrRef,cpuOrGpu,newOrRef,\"NPT_GEMC_\"+os.path.basename(root)\n listOfTests.append(command)\n# Create the pandas DataFrame\ncolNames = ['PathToBinary', 'PathToExample', 'Binary', 'CPU_or_GPU','New_or_Ref','Example']\ndf = pd.DataFrame(listOfTests, columns = colNames)\ndf = df.sort_values(by=['Example'])\ngrouped = df.groupby(['Example'])\nall_examples = df['Example'].unique()\nCPU_v_GPU_global = True\nNew_v_Ref_global = True\ncross_bool_global = True\nCPU_v_GPU_exists_global = False\nNew_v_Ref_exists_global = False\ncross_exists_global = False\nfor example in all_examples:\n ex_df = grouped.get_group(example)\n full_path_pdb_files = sorted(glob.glob(os.path.join(ex_df['PathToExample'].iloc[0],'*.pdb')), key=os.path.getmtime)\n just_file_names = []\n for path in full_path_pdb_files:\n just_file_names.append(os.path.basename(path))\n cross = ex_df.merge(ex_df, on=['Example'],how='outer')\n Log_Template_file.write(\"---{}\\n\".format(ex_df['Example'].iloc[0]))\n CPU_v_GPU = True\n New_v_Ref = True\n cross_bool = True\n CPU_v_GPU_exists = False\n New_v_Ref_exists = False\n cross_exists = False\n for pdb_file in just_file_names:\n Log_Template_file.write(\"------{}\\n\".format(pdb_file))\n my_tuples = []\n for index, row in cross.iterrows():\n f1 = os.path.join(row['PathToExample_x'],pdb_file)\n f2 = os.path.join(row['PathToExample_y'],pdb_file)\n if ((row['CPU_or_GPU_x'] != row['CPU_or_GPU_y']) and (row['New_or_Ref_x'] == row['New_or_Ref_y'])):\n CPU_v_GPU_exists = True\n CPU_v_GPU_exists_global = True\n result = cmp(f1, f2, shallow=False)\n CPU_v_GPU = CPU_v_GPU and result\n CPU_v_GPU_global = CPU_v_GPU_global and result\n elif ((row['CPU_or_GPU_x'] == row['CPU_or_GPU_y']) and (row['New_or_Ref_x'] != row['New_or_Ref_y'])):\n New_v_Ref_exists = True\n New_v_Ref_exists_global = True\n result = cmp(f1, f2, shallow=False)\n New_v_Ref = New_v_Ref and result\n New_v_Ref_global = New_v_Ref_global and result\n elif ((row['CPU_or_GPU_x'] != row['CPU_or_GPU_y']) and (row['New_or_Ref_x'] != row['New_or_Ref_y'])):\n cross_exists = True\n cross_exists_global = True\n result = cmp(f1, f2, shallow=False)\n cross_bool = cross_bool and result\n cross_bool_global = cross_bool_global and result\n if(CPU_v_GPU_exists):\n if(CPU_v_GPU):\n Log_Template_file.write(\"---------{}\\n\".format(\"CPU_v_GPU: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(\"---------{}\\n\".format(\"CPU_v_GPU: \"+ FAIL + \"FAIL\" + ENDC))\n if(New_v_Ref_exists):\n if(New_v_Ref):\n Log_Template_file.write(\"---------{}\\n\".format(\"New_v_Ref: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(\"---------{}\\n\".format(\"New_v_Ref: \"+ FAIL + \"FAIL\" + ENDC))\n if(cross_exists):\n if(cross_bool):\n Log_Template_file.write(\"---------{}\\n\".format(\"CPU v GPU X New v Ref: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(\"---------{}\\n\".format(\"CPU v GPU X New v Ref: \"+ FAIL + \"FAIL\" + ENDC))\n\n\nif(CPU_v_GPU_exists_global):\n if(CPU_v_GPU_global):\n Log_Template_file.write(str(\"CPU_v_GPU Global: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(str(\"CPU_v_GPU Global: \"+ FAIL + \"FAIL\" + ENDC))\nif(New_v_Ref_exists_global):\n if(New_v_Ref_global):\n Log_Template_file.write(str(\"New vs Ref Global: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(str(\"New vs Ref Global: \"+ FAIL + \"FAIL\" + ENDC))\nif(cross_exists_global):\n if(cross_bool_global):\n Log_Template_file.write(str(\"CPU vs GPU X New vs Ref Global: \"+ OKGREEN + \"PASS\" + ENDC))\n else:\n Log_Template_file.write(str(\"CPU vs GPU X New vs Ref Global: \"+ FAIL + \"FAIL\" + ENDC))\n","sub_path":"test/WriteLog.py","file_name":"WriteLog.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"220374893","text":"\"\"\"\n@title Project 3\n@author Sotheanith Sok\n\nThis is the project 3 for EE 381 Spring 2018\n\nNote: This project is heavily helped by Professor John De Sulima-Przyborowski at California\nState University of Long Beach for EE381\n\n\"\"\"\n\"\"\"\nProblem 2:\nConsider the same simple binomial distribution experiment as above with five trials and in each trial the probability of\nsuccess is 0.7. What is the expected (average) value?\n\nAugment the program from simulation 1 to calculate the expected value of the binomial r.v\n\"\"\"\n\n#Import\nimport random\n\n#Variables\np=0.7 #Probability of success\nx=3 #Target success\nn=5 #Number of trials per run.\nN=1000000 #Number of run\n\n#Counters\nrunCount=0\ntrialCount=0\n\n#Store all number of trial\nallResult=[0]*(n+1)\n\n#Loop for run\nfor i in range(N): \n \n #Loop for trial\n for j in range(n):\n result=random.uniform(0,1)\n \n #if success, add one to trial counter\n if(result\", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])\n@application.route(\"/apis/\", methods=['GET', 'PUT', 'POST', 'PATCH', 'DELETE'])\ndef apis_proxy(path):\n user = proxy_user()\n session = get_user_session(user)\n\n api_client = proxy_api_client(session)\n header_params = {}\n if flask.request.headers.get('Accept'):\n header_params['Accept'] = flask.request.headers['Accept']\n if flask.request.content_type:\n header_params['Content-Type'] = flask.request.content_type\n try:\n (data, status, headers) = api_client.call_api(\n flask.request.path,\n flask.request.method,\n auth_settings = ['BearerToken'],\n body = flask.request.json,\n header_params = header_params,\n query_params = [ (k, v) for k, v in flask.request.args.items() ],\n response_type = 'object',\n )\n return flask.make_response(\n json.dumps(data, separators=(',',':')),\n status,\n [(k, v) for k, v in headers.items() if k not in ('Content-Length', 'Transfer-Encoding')]\n )\n except kubernetes.client.rest.ApiException as e:\n if e.body:\n resp = flask.make_response(e.body, e.status)\n resp.headers['Content-Type'] = 'application/json'\n flask.abort(resp)\n else:\n flask.abort(flask.make_response(flask.jsonify({\"reason\": e.reason}), e.status))\n\n@application.route('/')\ndef root_path():\n return flask.redirect('/ui/')\n\n@application.route('/ui/')\n@application.route('/ui/r/')\ndef ui_path(path=None):\n return flask.send_file(application.static_folder + '/index.html')\n\nif __name__ == \"__main__\":\n application.run()\n","sub_path":"admin/api/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"201717900","text":"import keyword\nimport re\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nfrom functools import lru_cache\nfrom pathlib import Path\nfrom typing import Any, DefaultDict, Dict, Iterator, List, Optional, Set\n\nfrom jinja2 import Environment, FileSystemLoader, Template\nfrom pydantic import BaseModel, root_validator\n\nfrom datamodel_code_generator import cached_property\nfrom datamodel_code_generator.imports import IMPORT_OPTIONAL, Import\nfrom datamodel_code_generator.reference import Reference\nfrom datamodel_code_generator.types import DataType\n\nTEMPLATE_DIR: Path = Path(__file__).parents[0] / 'template'\n\nOPTIONAL: str = 'Optional'\n\nALL_MODEL: str = '#all#'\n\n\nclass ConstraintsBase(BaseModel):\n ...\n\n\nclass DataModelFieldBase(BaseModel):\n name: Optional[str]\n default: Optional[Any]\n required: bool = False\n alias: Optional[str]\n example: Any = None\n examples: Any = None\n description: Optional[str]\n title: Optional[str]\n data_type: DataType\n constraints: Any = None\n strip_default_none: bool = False\n nullable: Optional[bool] = None\n\n @property\n def type_hint(self) -> str:\n type_hint = self.data_type.type_hint\n\n if not type_hint:\n return OPTIONAL\n elif self.nullable is not None:\n if self.nullable:\n return f'{OPTIONAL}[{type_hint}]'\n return type_hint\n elif self.required:\n return type_hint\n return f'{OPTIONAL}[{type_hint}]'\n\n @property\n def imports(self) -> List[Import]:\n if self.nullable is None:\n if not self.required:\n return self.data_type.imports_ + [IMPORT_OPTIONAL]\n elif self.nullable:\n return self.data_type.imports_ + [IMPORT_OPTIONAL]\n return self.data_type.imports_\n\n @property\n def unresolved_types(self) -> Set[str]:\n return self.data_type.unresolved_types\n\n @property\n def field(self) -> Optional[str]:\n \"\"\"for backwards compatibility\"\"\"\n return None\n\n @property\n def method(self) -> Optional[str]:\n return None\n\n @root_validator\n def validate_root(cls, values: Any) -> Dict[str, Any]:\n name: Optional[str] = values.get('name')\n if name:\n if keyword.iskeyword(name):\n alias = name\n name += '_'\n elif name.isidentifier():\n return values\n else: # pragma: no cover\n alias = name\n name = re.sub(r'\\W', '_', name)\n if not values.get('alias'):\n values['alias'] = alias\n values['name'] = name\n return values\n\n @property\n def represented_default(self) -> str:\n return repr(self.default)\n\n\n@lru_cache()\ndef get_template(template_file_path: Path) -> Template:\n loader = FileSystemLoader(str(TEMPLATE_DIR / template_file_path.parent))\n environment: Environment = Environment(loader=loader)\n return environment.get_template(template_file_path.name)\n\n\nclass TemplateBase(ABC):\n def __init__(self, template_file_path: Path) -> None:\n self.template_file_path: Path = template_file_path\n self._template: Template = get_template(template_file_path)\n\n @property\n def template(self) -> Template:\n return self._template\n\n @abstractmethod\n def render(self) -> str:\n raise NotImplementedError\n\n def _render(self, *args: Any, **kwargs: Any) -> str:\n return self.template.render(*args, **kwargs)\n\n def __str__(self) -> str:\n return self.render()\n\n\nclass DataModel(TemplateBase, ABC):\n TEMPLATE_FILE_PATH: str = ''\n BASE_CLASS: str = ''\n\n def __init__(\n self,\n name: str,\n fields: List[DataModelFieldBase],\n decorators: Optional[List[str]] = None,\n base_classes: Optional[List[str]] = None,\n custom_base_class: Optional[str] = None,\n custom_template_dir: Optional[Path] = None,\n extra_template_data: Optional[DefaultDict[str, Dict[str, Any]]] = None,\n imports: Optional[List[Import]] = None,\n auto_import: bool = True,\n reference_classes: Optional[List[str]] = None,\n methods: Optional[List[str]] = None,\n path: Optional[Path] = None,\n description: Optional[str] = None,\n reference: Optional[Reference] = None,\n ) -> None:\n if not self.TEMPLATE_FILE_PATH:\n raise Exception('TEMPLATE_FILE_PATH is undefined')\n\n template_file_path = Path(self.TEMPLATE_FILE_PATH)\n if custom_template_dir is not None:\n custom_template_file_path = custom_template_dir / template_file_path.name\n if custom_template_file_path.exists():\n template_file_path = custom_template_file_path\n\n self.name: str = name\n self.fields: List[DataModelFieldBase] = fields or []\n self.decorators: List[str] = decorators or []\n self.imports: List[Import] = imports or []\n self.base_class: Optional[str] = None\n base_classes = [base_class for base_class in base_classes or [] if base_class]\n self.base_classes: List[str] = base_classes\n self.path: Optional[Path] = path\n self.reference: Optional[Reference] = reference\n\n if self.reference:\n self.reference.source = self\n\n self.reference_classes: Set[str] = {\n r for r in base_classes if r != self.BASE_CLASS\n } if base_classes else set()\n if reference_classes:\n self.reference_classes.update(reference_classes)\n\n if self.base_classes:\n self.base_class = ', '.join(self.base_classes)\n else:\n base_class_full_path = custom_base_class or self.BASE_CLASS\n if auto_import:\n if base_class_full_path:\n self.imports.append(Import.from_full_path(base_class_full_path))\n self.base_class = base_class_full_path.rsplit('.', 1)[-1]\n\n if '.' in name:\n module, class_name = name.rsplit('.', 1)\n prefix = f'{module}.'\n if self.base_class.startswith(prefix):\n self.base_class = self.base_class.replace(prefix, '', 1)\n else:\n class_name = name\n\n self.class_name: str = class_name\n\n self.extra_template_data = (\n extra_template_data[self.name]\n if extra_template_data is not None\n else defaultdict(dict)\n )\n if extra_template_data:\n all_model_extra_template_data = extra_template_data.get(ALL_MODEL)\n if all_model_extra_template_data:\n self.extra_template_data.update(all_model_extra_template_data)\n\n unresolved_types: Set[str] = {*()}\n for field in self.fields:\n unresolved_types.update(field.unresolved_types)\n\n self.reference_classes |= unresolved_types\n\n if auto_import:\n for field in self.fields:\n self.imports.extend(field.imports)\n\n self.methods: List[str] = methods or []\n\n self.description = description\n super().__init__(template_file_path=template_file_path)\n\n @cached_property\n def module_path(self) -> List[str]:\n if self.path:\n return [\n *self.path.parts[:-1],\n self.path.stem,\n *self.name.split('.')[:-1],\n ]\n return self.name.split('.')[:-1]\n\n @property\n def all_data_types(self) -> Iterator['DataType']:\n for field in self.fields:\n yield from field.data_type.all_data_types\n\n def render(self) -> str:\n response = self._render(\n class_name=self.class_name,\n fields=self.fields,\n decorators=self.decorators,\n base_class=self.base_class,\n methods=self.methods,\n description=self.description,\n **self.extra_template_data,\n )\n return response\n","sub_path":"datamodel_code_generator/model/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"238410149","text":"from .common import *\n\nDEBUG = True\n\n# Parse database configuration from $DATABASE_URL\nimport dj_database_url\nDATABASES = {}\nDATABASES['default'] = dj_database_url.config()\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nINSTALLED_APPS += (\n 'storages',\n)\n\nMEDIA_URL = 'https://allisterheroku.s3.amazonaws.com/media/'\n\nSTATIC_URL = 'https://allisterheroku.s3.amazonaws.com/'\n\nADMIN_MEDIA_PREFIX = 'https://allisterheroku.s3.amazonaws.com/static/admin/'\n\n# Settings for Boto to send files to Amazon S3\nDEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\nSTATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'\n\n# Settings for Amazon S3 storage of Static files\n# grab the S3 security credentials from the environment variables\nAWS_ACCESS_KEY_ID = os.environ[\"AWS_ACCESS_KEY_ID\"]\nAWS_SECRET_ACCESS_KEY = os.environ[\"AWS_SECRET_ACCESS_KEY\"]\nAWS_STORAGE_BUCKET_NAME = 'allisterheroku'","sub_path":"settings/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"35094064","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotData(X, y):\n \"\"\"\n Plots the data points with + for positive examples and o for negative examples\n \"\"\"\n plt.plot(X[y==0, 0], X[y==0, 1], 'yo', label='y=0')\n plt.plot(X[y==1, 0], X[y==1, 1], 'k+', label='y=1')\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.xlim(-1, 1.5)\n plt.ylim(-0.8, 1.2)\n plt.legend(loc='upper right')\n plt.show()\n\ndef mapFeature(X1, X2):\n \"\"\"\n Feature mapping function to polynomial features\n Returns a new array with more features, comprising of X1, X2, X1^2, X2^2,\n X1*X2, X1*X2^2,...\n \"\"\"\n degree = 6\n out = np.ones((X1.shape[0], 1))\n\n for i in range(1, degree+1):\n for j in range(i+1):\n new = np.multiply(X1**(i-j), X2**j).reshape(-1, 1)\n out = np.append(out, new, axis=1)\n return out\n\ndef sigmoid(z):\n \"\"\"\"\n Returns the sigmoid of z\n \"\"\"\n return 1 / (1+np.exp(-z))\n\ndef costFunctionReg(theta, X, y, lam):\n \"\"\"\n Computes the cost of using theta as a parameter for regularized logistic regression\n \"\"\"\n #number of training examples\n y = y.reshape(-1, 1)\n m = y.shape[0]\n #compute the cost\n theta = theta.reshape(-1, 1)\n h = sigmoid(np.matmul(X, theta))\n J = (-1/m) * np.sum(np.multiply(y, np.log(h)) + np.multiply(1-y, np.log(1-h))) + (lam/(2*m)) * np.sum(theta[1:, 0] **2)\n return J\n\ndef gradient(theta, X, y, lam):\n \"\"\"\n Computes the gradient of regularized logistic regression\n \"\"\"\n #number of training examples\n y = y.reshape(-1, 1)\n m = y.shape[0]\n #compute the gradient\n theta = theta.reshape(-1, 1)\n h = sigmoid(np.matmul(X, theta))\n diff = h - y\n temp = np.matmul(X.transpose(), diff)\n grad = 1/m * temp\n grad[1:, 0] = grad[1:, 0] + (lam/m) * theta[1:, 0]\n return grad\n\ndef predict(theta, X):\n \"\"\"\n Predict whether the label is 0 or 1 using learned logistic regression parameters theta\n Threshhold at 0.5\n \"\"\"\n #number of training examples\n m = X.shape[0]\n theta = theta.reshape(-1, 1)\n\n temp = sigmoid(np.matmul(X, theta))\n p = (temp >= 0.5).astype(np.int)\n return p\n\ndef mapFeaturePlotting(X1, X2):\n \"\"\"\n Map feature function for plotting decision boundary\n \"\"\"\n degree = 6\n out = np.ones(1)\n for i in range(1, degree+1):\n for j in range(i+1):\n out = np.hstack((out, np.multiply(np.power(X1, i-j), np.power(X2, j))))\n return out\n\ndef plotDecisionBoundary(theta, X, y):\n \"\"\"\n Plots the data points X and y into a new figure with the decision boundary\n defined by theta\n \"\"\"\n u = np.linspace(-1, 1.5, 50)\n v = np.linspace(-1, 1.5, 50)\n z = np.zeros((len(u), len(v)))\n\n for i in range(len(u)):\n for j in range(len(v)):\n z[i, j] = np.dot(mapFeaturePlotting(u[i], v[j]), theta)\n\n plt.contour(u, v, z, 0)\n plt.plot(X[y==0, 0], X[y==0, 1], 'yo', label='y=0')\n plt.plot(X[y==1, 0], X[y==1, 1], 'k+', label='y=1')\n plt.xlabel('Microchip Test 1')\n plt.ylabel('Microchip Test 2')\n plt.xlim(-1, 1.5)\n plt.ylim(-0.8, 1.2)\n plt.legend(loc='upper right')\n plt.show()\n","sub_path":"ex2/ex2regfunctions.py","file_name":"ex2regfunctions.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"74"} +{"seq_id":"423185123","text":"# coding=utf-8\nimport requests\nimport json\nimport re\nfrom lxml import etree,html\n\nclass BiLiBiLi:\n def __init__(self,url):\n self.url = url\n #弹幕的消息\n self.danmu_url = 'https://comment.bilibili.com/{}.xml'\n self.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36\"\n\n }\n\n \"\"\"发送请求 返回响应\"\"\"\n def get_html(self,url):\n return requests.get(url,headers=self.headers).content.decode()\n \"\"\"保存弹幕信息\"\"\"\n def save_danmu(self,l,num):\n with open('./danmu{}.txt'.format(num),'a',encoding='utf-8') as f:\n for danm_str in l:\n print(danm_str)\n f.write(danm_str)\n f.write(\"\\n\")\n\n def run(self):\n #发送请求 获取结果\n bl_html = self.get_html(self.url)\n print(bl_html)\n print(\"获取cid\")\n li = re.findall(r\"