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# \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\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.', ''),('