diff --git "a/536.jsonl" "b/536.jsonl" new file mode 100644--- /dev/null +++ "b/536.jsonl" @@ -0,0 +1,533 @@ +{"seq_id":"9879963","text":"from PyQt5.QtCore import pyqtSlot\n\nfrom resources.ui.python.GroupWidget_ui import Ui_frmGroup\n\nfrom libopenimu.models.Group import Group\nfrom libopenimu.qt.DataEditor import DataEditor\n\nclass GroupWindow(DataEditor):\n\n group = Group()\n dbMan = None\n\n def __init__(self, dbManager, group=None, parent=None):\n super().__init__(parent=parent)\n self.UI = Ui_frmGroup()\n self.UI.setupUi(self)\n\n self.group = group\n self.dbMan = dbManager\n self.data_type = \"group\"\n\n # Signals / Slots connections\n self.UI.btnCancel.clicked.connect(self.cancel_clicked)\n self.UI.btnSave.clicked.connect(self.save_clicked)\n self.UI.txtName.textEdited.connect(self.name_edited)\n self.UI.txtDesc.textChanged.connect(self.desc_edited)\n\n # Update data\n self.update_data()\n\n self.enable_buttons(False)\n\n def validate(self):\n rval = True\n if self.UI.txtName.text() == '':\n self.UI.txtName.setStyleSheet('background-color: #ffcccc;')\n rval = False\n else:\n self.UI.txtName.setStyleSheet('background-color: rgba(226, 226, 226, 90%);')\n\n return rval\n\n def update_data(self):\n if self.group is not None:\n self.UI.txtName.setText(self.group.name)\n self.UI.txtDesc.setPlainText(self.group.description)\n else:\n self.UI.txtName.setText(\"\")\n self.UI.txtDesc.setPlainText(\"\")\n\n def enable_buttons(self, enable):\n self.UI.btnCancel.setEnabled(enable or self.group is None)\n self.UI.btnSave.setEnabled(enable)\n\n def update_modified_status(self):\n self.enable_buttons(\n (self.group is not None and self.UI.txtName.text() != self.group.name) or\n (self.group is None and self.UI.txtName.text() != \"\") or\n (self.group is not None and self.UI.txtDesc.toPlainText() != self.group.description) or\n (self.group is None and self.UI.txtDesc.toPlainText() != \"\")\n )\n\n @pyqtSlot()\n def save_clicked(self):\n if self.validate():\n if self.group is None:\n self.group = Group()\n self.group.name = self.UI.txtName.text()\n self.group.description = self.UI.txtDesc.toPlainText()\n self.group = self.dbMan.update_group(self.group)\n self.enable_buttons(False)\n self.dataSaved.emit()\n\n\n @pyqtSlot()\n def cancel_clicked(self):\n self.update_data()\n self.dataCancelled.emit()\n\n\n @pyqtSlot(str)\n def name_edited(self, new_value):\n self.update_modified_status()\n\n @pyqtSlot()\n def desc_edited(self):\n self.update_modified_status()\n\n","sub_path":"python/libopenimu/qt/GroupWindow.py","file_name":"GroupWindow.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"121500156","text":"class Semantic_Routine():\n \"\"\"This class is used to convert the source code into IR code. It will then\n turned into tiny code by another class\n \"\"\"\n\n def __init__(self):\n self._output = []\n self._r_num = 0\n self._label = 0\n self._type_list = [\"ADDI \", \"SUBI \", \"MULI \", \"DIVI \", \"STOREI \" ]\n self._jump_list = [\"JGEI \", \"JNEI \", \"JEQI \", \"JGTI \", \"JLTI \", \"JLEI \"]\n\n def add_primary (self, var_in):\n \"\"\"Creates instruction for loading a value into a variable\"\"\"\n if var_in[0].isdigit():\n self._r_num += 1\n if \".\" in var_in:\n instr = [[\"STOREI \", var_in , self._r_num]]\n return instr\n else:\n instr = [[\"STOREI \", var_in , self._r_num]]\n return instr\n else:\n return([[var_in]])\n\n def add_assign_expr(self, expr, var_name):\n \"\"\"Set the left side of an assign to the value of the right side\"\"\"\n instr = [[\"STOREI \" , expr[-1][-1], var_name]]\n if len(expr[-1]) < 2:\n del expr[-1]\n instr = expr + instr\n\n return instr\n\n def add_mul_op(self, l_side, r_side):\n \"\"\"This method is used in p_assign_expr, p_expr_prefix, p_factor, and\n p_factor_prefix. This correctly builds add and mul commands\n \"\"\"\n self._r_num += 1\n if l_side[-1] == '+':\n ret = self.make_op(l_side, r_side)\n instr = [[\"ADDI \", ret[1], ret[2], self._r_num]]\n return ret[0] + instr\n\n elif l_side[-1] == '-':\n ret = self.make_op(l_side, r_side)\n instr = [[\"SUBI \", ret[1], ret[2], self._r_num]]\n return ret[0] + instr\n\n elif l_side[-1] == '*':\n ret = self.make_op(l_side, r_side)\n instr = [[\"MULI \", ret[1], ret[2], self._r_num]]\n return ret[0] + instr\n\n elif l_side[-1] == '/':\n ret = self.make_op(l_side, r_side)\n instr = [[\"DIVI \", ret[1], ret[2], self._r_num]]\n return ret[0] + instr\n\n def make_op(self, l_side, r_side):\n \"\"\"What registers or variables to add\"\"\"\n l_reg = 0\n r_reg = 0\n\n if len(l_side[-2]) > 1:\n l_reg = l_side[-2][-1]\n del l_side[-1]\n else:\n l_reg = l_side[-2][0]\n del l_side[-1]\n del l_side[-1]\n\n if len(r_side[-1]) > 1:\n r_reg = r_side[-1][-1]\n l_side = l_side + r_side\n else:\n r_reg = r_side[-1][0]\n\n return (l_side, l_reg, r_reg)\n\n def add_cond(self, l_side, compop, r_side, d_type):\n \"\"\"Add a conditional like in if statements\"\"\"\n get_reg = self.make_op(l_side + [compop], r_side)\n l_reg = get_reg[1]\n r_reg = get_reg[2]\n self._label += 1\n instr = ''\n\n if compop == '<':\n instr = [[\"JGEI \", l_reg, r_reg, self._label]]\n\n elif compop == '>':\n instr = [[\"JLEI \", l_reg, r_reg, self._label]]\n\n elif compop == '=':\n instr = [[\"JNEI \", l_reg, r_reg, self._label]]\n\n elif compop == '!=':\n instr = [[\"JEQI \", l_reg, r_reg, self._label]]\n\n elif compop == '<=':\n instr = [[\"JGTI \", l_reg, r_reg, self._label]]\n\n elif compop == '>=':\n instr = [[\"JLTI \", l_reg, r_reg, self._label]]\n\n instr = get_reg[0] + instr\n instr = self.change_type(instr, d_type)\n\n return instr\n\n def add_else(self):\n \"\"\"Add else section to if statement\"\"\"\n self._label += 1\n return [[\"JUMP \", self._label]]\n\n def get_label(self):\n \"\"\"Dynamically make new labels as needed\"\"\"\n self._label += 1\n return [['LABEL ', self._label]]\n\n def write_list(self, id_list):\n \"\"\"Make write instr\"\"\"\n instr_list =[]\n for i in id_list:\n instr_list += [[\"WRITE \", i]]\n return instr_list\n\n def read_list(self, id_list):\n \"\"\"Make read instr\"\"\"\n instr_list =[]\n for i in id_list:\n instr_list += [[\"READ \", i]]\n return instr_list\n\n def change_type(self, code, d_type):\n \"\"\"Make type of instructions correct\"\"\"\n if d_type[0] == 'FLOAT':\n for lists in code:\n if lists[0] in self._type_list or lists [0] in self._jump_list:\n st = lists[0][:-2]\n lists[0] = st + \"F \"\n return code\n\n\nclass IR_To_Tiny():\n \"\"\"Converts IR code to tiny code\"\"\"\n def __init__(self, IR, sym_table):\n self.IR = IR\n self.cur_reg = 1\n self.reg_offset = -1\n self.sym_table = sym_table\n self.i_list = []\n self._type_list = [\"ADDI \", \"SUBI \", \"MULI \", \"DIVI \", \"ADDF \",\\\n \"SUBF \", \"MULF \", \"DIVF \" ]\n self._jump_list = [\"JGEI \", \"JNEI \", \"JEQI \", \"JGTI \", \"JLTI \", \"JLEI \",\\\n \"JGEF \", \"JNEF \", \"JEQF \", \"JGTF \", \"JLTF \", \"JLEF \"]\n\n for key,val in sym_table[0].items():#make variable declarations\n if val[0] == \"STRING\":\n self.i_list.append(\"str \" + key + \" \" + val[1])\n else:\n self.i_list.append(\"var \" + key)\n\n self.i_list.append(\"label main\")\n\n for lists in IR:#each instruction is turned into tiny with this loop\n print (\";\" + str(lists))\n if lists[0] == \"STOREF \" or lists[0] == \"STOREI \":\n lists = self.to_move(lists)\n elif lists[0] in self._type_list:\n self.to_add(lists)\n elif lists[0] in self._jump_list:\n self.to_jump(lists)\n elif lists[0] == \"LABEL \":\n self.to_label(lists)\n elif lists[0] == \"JUMP \":\n self.to_jmp(lists)\n elif lists[0] == \"WRITE \":\n self.to_write(lists)\n elif lists[0] == \"READ \":\n self.to_read(lists)\n elif lists[0] == \"RETURN\":\n self.to_return(lists)\n\n\n for lists in self.i_list:\n print (lists)\n\n\n def to_move(self, instr):\n \"\"\"Convert stores to moves\"\"\"\n if self.is_id(instr[1]) and self.is_id(instr[2]):\n instr1 =\"move \" + instr[1] + \" r\" + str(self.cur_reg + self.reg_offset + 1)\n instr2 = \"move r\" + str(self.cur_reg + self.reg_offset + 1) + \" \" \\\n + instr[2]\n\n self.reg_offset += 1\n self.i_list.append(instr1)\n self.i_list.append(instr2)\n\n else:\n instr = \"move \" + self.is_reg(instr[1]) + \" \" + self.is_reg(instr[2])\n self.i_list.append(instr)\n\n def to_add(self, instr):\n \"\"\"Convert addops\"\"\"\n instr1 = ''\n instr2 = ''\n\n if not self.is_id(instr[1]):\n instr1 = \"move \" + \"r\" + str(instr[1]+self.reg_offset) + \" r\" + str(instr[3] + self.reg_offset)\n else:\n instr1 = \"move \" + str(instr[1]) + \" r\" + str(instr[3] + self.reg_offset)\n\n if not self.is_id(instr[2]):\n instr2 = self.op_to_ir(instr[0]) + \"r\" + str(instr[2] + self.reg_offset) + \" r\" + str(instr[3] + self.reg_offset)\n else:\n instr2 = self.op_to_ir(instr[0]) + str(instr[2]) + \" r\" + str(instr[3] + self.reg_offset)\n\n self.is_reg(instr[3])\n self.i_list.append(instr1)\n self.i_list.append(instr2)\n\n def to_jump(self, instr):\n \"\"\"Convert conditionals\"\"\"\n instr = self.add_reg(instr)\n\n if instr[0][-2] == 'I':\n instr1 = \"cmpi \" + self.is_reg(instr[1]) + \" \" + self.is_reg(instr[2])\n else:\n instr1 = \"cmpr \" + self.is_reg(instr[1]) + \" \" + self.is_reg(instr[2])\n\n self.i_list.append(instr1)\n instr2 = self.strip_type(instr[0]) + \"label\" + str(instr[3])\n self.i_list.append(instr2)\n\n def to_label(self, instr):\n \"\"\"Convert labels\"\"\"\n instr1 = \"label \" + \"label\" + str(instr[1])\n self.i_list.append(instr1)\n\n def to_jmp(self, instr):\n \"\"\"Convert Jumps\"\"\"\n instr1 = \"jmp \" + \"label\" + str(instr[1])\n self.i_list.append(instr1)\n\n def to_write(self, instr):\n \"\"\"Convert write statements\"\"\"\n d_type = self.get_type(instr[1])[0]\n if d_type == \"STRING\":\n instr = \"sys writes \" + instr[1]\n elif d_type == \"INT\":\n instr = \"sys writei \" + instr[1]\n elif d_type ==\"FLOAT\":\n instr =\"sys writer \" + instr[1]\n self.i_list.append(instr)\n\n def to_read(self, instr):\n \"\"\"Convert read statements\"\"\"\n d_type = self.get_type(instr[1])[0]\n if d_type == \"INT\":\n instr = \"sys readi \" + instr[1]\n elif d_type ==\"FLOAT\":\n instr =\"sys readr \" + isntr[1]\n self.i_list.append(instr)\n\n def to_return(self, instr):\n \"\"\"Add halt\"\"\"\n self.i_list.append(\"sys halt\")\n\n def get_type(self, ident):\n \"\"\"Get data type of variable\"\"\"\n return self.sym_table[0][ident]\n\n\n def add_reg(self, instr):\n \"\"\"add necessary moves to convert cond to 2 variable tiny code\"\"\"\n if self.is_id(instr[2]):\n m_instr = \"move \" + instr[2] + \" r\" + str(self.cur_reg + self.reg_offset + 1)\n instr = [instr[0], instr[2], self.cur_reg + self.reg_offset + 1, instr[3]]\n self.reg_offset += 1\n self.i_list.append(m_instr)\n return instr\n else:\n return instr\n\n def op_to_ir(self, op):\n \"\"\"convert operatin to lower case and tiny syntax\"\"\"\n if op[-2] == 'I':\n return op.lower()\n else:\n op = op[:-2]\n op = op +\"R \"\n return op.lower()\n\n def strip_type(self, op):\n \"\"\"Get rid of type from operations\"\"\"\n op = op[:-2]\n op = op + \" \"\n return op.lower()\n\n def is_reg(self, p_reg):\n \"\"\"keep updated on current register. Return string.\"\"\"\n if isinstance(p_reg, int):\n if p_reg > self.cur_reg:\n self.cur_reg = p_reg\n return \"r\" + str(p_reg + self.reg_offset)\n\n else:\n return p_reg\n\n def is_id(self, p_id):\n \"\"\"Checks whether a variable is an ID\"\"\"\n if isinstance(p_id, str):\n if p_id[0].isalpha():\n return True\n return False\n","sub_path":"FINAL/semantic_routine.py","file_name":"semantic_routine.py","file_ext":"py","file_size_in_byte":10303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"457775806","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\n\n\n### 8:30 insingle file flask apps (WHICH IS NOT THIS)\n##you would normmally pass in the app when you instanuate the DB for the first time but\n##when you use this pattewrn of create app you cant do that\n###so you have to instaniate the single alchemy object without the app\n####and then inside it you create an aoo function thats where you instaniate the app\ndb = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n###for the config we will be using a sqllite database\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'\n\n ##calling the db here\n db.init_app(app)\n\n\n ##!! we have to import the .views here so it will work cause it needs to be imported AFTER flask has been not\n ##alll at once\n ##\"main\" being the name of the entire file called views\n from .views import main\n ##. register will register the blueprint\n app.register_blueprint(main)\n\n ####later will use the db object that we create later to instantiate the app with this database but\n ##for now will return app\n return app\n\n##there will be two endpoints in this app one to view the movies, and another to add the movies\n\n","sub_path":"Desktop/react-for-flask/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"339795743","text":"fruits = {\r\n\t\"バナナ\":300,\r\n\t\"オレンジ\":240,\r\n\t\"イチゴ\":350,\r\n\t\"マンゴー\":400\r\n}\r\n\r\n# 辞書型のデータ一覧を表示\r\nfor name in fruits.keys():\r\n\t# 値段を取得\r\n\tprice = fruits[name]\r\n\t# 画面に出力\r\n\ts = \"{0}は、{1}円です。\".format(name, price)\r\n\tprint(s)","sub_path":"Python/chapter3/3-2/print-dict.py","file_name":"print-dict.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"5688610","text":"import time\n\nimport pytz\n\nfrom django.conf import settings\nfrom django.utils import timezone, translation\nfrom django.conf.locale.en import formats as formats_en_us\nfrom django.conf.locale.en_GB import formats as formats_en_gb\n\n\ndef update_en_us_date_formats():\n \"\"\"\n Update the datetime formats for the en-US locale. This is handled here and\n not using `FORMAT_MODULE_PATH` because the processing of format modules\n does not allow us to distinguish appropriately between en-US and en-GB\n based on user settings.\n \"\"\"\n if settings.USE_24_HOUR_TIME_FORMAT:\n formats_en_us.DATETIME_FORMAT = \"N j, Y, H:i:s\"\n custom_input_formats = [\n \"%m/%d/%Y %H:%M:%S\", # '10/25/2006 14:30:59'\n \"%m/%d/%Y %H:%M\", # '10/25/2006 14:30'\n ]\n formats_en_us.SHORT_DATETIME_FORMAT = \"m/d/Y G:i:s\"\n formats_en_us.TIME_FORMAT = \"H:i:s\"\n else:\n # These formats are added to support the locale style of Baby Buddy's\n # frontend library, which uses momentjs.\n custom_input_formats = [\n \"%m/%d/%Y %I:%M:%S %p\", # '10/25/2006 2:30:59 PM'\n \"%m/%d/%Y %I:%M %p\", # '10/25/2006 2:30 PM'\n ]\n\n # Add custom \"short\" version of `MONTH_DAY_FORMAT`.\n formats_en_us.SHORT_MONTH_DAY_FORMAT = \"M j\"\n\n # Append all other input formats from the base locale.\n formats_en_us.DATETIME_INPUT_FORMATS = (\n custom_input_formats + formats_en_us.DATETIME_INPUT_FORMATS\n )\n\n\ndef update_en_gb_date_formats():\n if settings.USE_24_HOUR_TIME_FORMAT:\n # 25 October 2006 14:30:00\n formats_en_gb.DATETIME_FORMAT = \"j F Y H:i:s\"\n custom_input_formats = [\n \"%d/%m/%Y %H:%M:%S\", # '25/10/2006 14:30:59'\n \"%d/%m/%Y %H:%M\", # '25/10/2006 14:30'\n ]\n formats_en_gb.SHORT_DATETIME_FORMAT = \"d/m/Y H:i\"\n formats_en_gb.TIME_FORMAT = \"H:i\"\n else:\n formats_en_gb.DATETIME_FORMAT = \"j F Y f a\" # 25 October 2006 2:30 p.m\n # These formats are added to support the locale style of Baby Buddy's\n # frontend library, which uses momentjs.\n custom_input_formats = [\n \"%d/%m/%Y %I:%M:%S %p\", # '25/10/2006 2:30:59 PM'\n \"%d/%m/%Y %I:%M %p\", # '25/10/2006 2:30 PM'\n ]\n\n # Append all other input formats from the base locale.\n formats_en_gb.DATETIME_INPUT_FORMATS = (\n custom_input_formats + formats_en_gb.DATETIME_INPUT_FORMATS\n )\n\n\nclass UserLanguageMiddleware:\n \"\"\"\n Customizes settings based on user language setting.\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n user = request.user\n if hasattr(user, \"settings\") and user.settings.language:\n language = user.settings.language\n elif request.LANGUAGE_CODE:\n language = request.LANGUAGE_CODE\n else:\n language = settings.LANGUAGE_CODE\n\n if language:\n if language == \"en-US\":\n update_en_us_date_formats()\n elif language == \"en-GB\":\n update_en_gb_date_formats()\n\n # Set the language before generating the response.\n translation.activate(language)\n\n response = self.get_response(request)\n\n # Deactivate the translation before the response is sent so it not\n # reused in other threads.\n translation.deactivate()\n\n return response\n\n\nclass UserTimezoneMiddleware:\n \"\"\"\n Sets the timezone based on a user specific setting that falls back on\n `settings.TIME_ZONE`. This middleware must run after\n `django.contrib.auth.middleware.AuthenticationMiddleware` because it uses\n the request.user object.\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n user = request.user\n if hasattr(user, \"settings\") and user.settings.timezone:\n try:\n timezone.activate(pytz.timezone(user.settings.timezone))\n except pytz.UnknownTimeZoneError:\n pass\n return self.get_response(request)\n\n\nclass RollingSessionMiddleware:\n \"\"\"\n Periodically resets the session expiry for existing sessions.\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if request.session.keys():\n session_refresh = request.session.get(\"session_refresh\")\n if session_refresh:\n try:\n delta = int(time.time()) - session_refresh\n except (ValueError, TypeError):\n delta = settings.ROLLING_SESSION_REFRESH + 1\n if delta > settings.ROLLING_SESSION_REFRESH:\n request.session[\"session_refresh\"] = int(time.time())\n request.session.set_expiry(settings.SESSION_COOKIE_AGE)\n else:\n request.session[\"session_refresh\"] = int(time.time())\n return self.get_response(request)\n","sub_path":"babybuddy/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"42892319","text":"import sys\nfrom scraping import *\nfrom print import *\n\nif __name__ == '__main__':\n\n # arguments\n argvs = sys.argv\n\n # check\n if len(argvs) != 2:\n print(\"Usage: python main.py url\")\n exit()\n url = argvs[1]\n\n # scraping\n soup_data = scraping(url)\n\n # tag rate\n rate_data = tag_rate.tag_rate(soup_data)\n\n data = {}\n data[\"tag_rate\"] = rate_data\n data[\"url\"] = url\n\n print_data(data)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"316717783","text":"'''\n\tsolution.py\n\tClassroom allocation problem.\n\tAttempting to solve in O(n) time.\n\tMy attempt failed, though it is solvable in O(n) time.\n\tGeeks solution, instead of using tuple, separate into\n\ttwo separate lists. Makes sense.\n'''\n\nimport unittest\n\ndef solve(times):\n\tcount = 1\n\ttotal = 1\n\ttimes = zip(*times)\n\tarrival = list(times[0])\n\tdeparture = list(times[1])\n\tarrival.sort()\n\tdeparture.sort()\n\tstart = 1\n\tending = 0\n\twhile start < len(arrival) and ending < len(arrival):\n\t\tif arrival[start] <= departure[ending]:\n\t\t\tcount += 1\n\t\t\tstart += 1\n\t\t\tif count > total:\n\t\t\t\ttotal = count\n\t\telse:\n\t\t\tending -= 1\n\t\t\tcount -= 1\n\treturn total\n\nclass Test(unittest.TestCase):\n\t\n\tdata = [(((0, 30), (15, 45), (60, 150), (60, 80), (90, 150)), 4),\n\t\t\t(((30, 75), (0, 50), (60, 150)), 2),\n\t\t\t(((30, 60), (45, 60), (60, 150)), 3)]\n\t\n\t\n\tdef test_solution(self):\n\t\tfor [case, expected] in self.data:\n\t\t\tactual = solve(case)\n\t\t\tself.assertEqual(actual, expected)\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"Problem_21/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"448109350","text":"#!/usr/bin/env python\n\n# Standard imports\nimport ROOT\nimport numpy as np\nimport random\nimport cProfile\nimport time\nimport os, sys\nfrom math import log, exp, sqrt\nimport copy\n\n# RootTools\nfrom RootTools.core.standard import *\n\n# Analysis\nimport Analysis.Tools.syncer\n\n# BIT\nfrom BoostedInformationTree import BoostedInformationTree\n\n# User\nfrom user import plot_directory as user_plot_directory\n\n# Model choices\nallModels = set( [ os.path.splitext(item)[0] for item in os.listdir( \"toy_models\" ) if not item.startswith(\"_\") ] )\n\n# Models an theta values\n# exponential - 0.001\n# power_law - 0.2\n\n# Parser\nimport argparse\nargParser = argparse.ArgumentParser(description = \"Argument parser\")\nargParser.add_argument(\"--plot_directory\", action=\"store\", default=\"BIT_v1\", help=\"plot sub-directory\")\nargParser.add_argument(\"--model\", action=\"store\", default=\"exponential\", type=str, choices=allModels, help=\"import model\")\nargParser.add_argument(\"--theta\", action=\"store\", default=0.001, type=float, help=\"theta value for model\")\nargParser.add_argument(\"--nTraining\", action=\"store\", default=10000, type=int, help=\"number of training events\")\nargParser.add_argument(\"--luminosity\", action=\"store\", default=137, type=int, help=\"luminosity value, currently only for plot label\")\nargParser.add_argument(\"--lowPtThresh\", action=\"store\", default=50, type=int, help=\"low pt threshold\")\nargParser.add_argument(\"--highPtThresh\", action=\"store\", default=200, type=int, help=\"high pt threshold\")\nargParser.add_argument(\"--fraction_alpha\", action=\"store\", default=1, type=float, help=\"Move information to this fraction of the events (for overtraining study)\")\nargParser.add_argument(\"--max_uncertainty\", action=\"store\", default=0, type=float, help=\"Maximum allowed relative uncertainty in each node split\")\nargParser.add_argument(\"--bagging_fraction\", action=\"store\", default=1., type=float, help=\"Bagging fraction\")\nargParser.add_argument(\"--max_n_split\", action=\"store\", default=-1, type=int, help=\"Maximum number of splits in node split\")\nargs = argParser.parse_args()\n\n# import the toy model\nimport toy_models as models\nmodel = getattr( models, args.model )\n\n# Produce training data set\ntraining_features, training_weights, training_diff_weights = model.get_dataset( args.nTraining )\n\ndef weight_up(fraction_alpha, diff_weights):\n bool_arr = np.zeros(len(diff_weights), dtype=bool)\n bool_arr[:int(round(fraction_alpha*len(diff_weights)))] = True\n random.shuffle(bool_arr)\n diff_weights[bool_arr] = diff_weights[bool_arr]/args.fraction_alpha\n diff_weights[~bool_arr] = 0.\n\n# Move the whole information into a fraction 'fraction_alpha' of events\nmodel_postfix = ''\nif args.fraction_alpha>0 and args.fraction_alpha<1:\n weight_up( args.fraction_alpha, training_diff_weights)\n model_postfix += \"_alpha%4.4f\"%args.fraction_alpha\n\nif args.max_uncertainty>0:\n model_postfix += \"_maxJN%4.4f\"%args.max_uncertainty\n\nif args.bagging_fraction<1.0:\n model_postfix += \"_BF%2.2f\"%args.bagging_fraction\n\nif args.max_n_split>1:\n model_postfix += \"_MNS%i\"%args.max_n_split\n\n# directory for plots\nplot_directory = os.path.join( user_plot_directory, args.plot_directory, model.id_string + model_postfix )\n\nif not os.path.isdir(plot_directory):\n os.makedirs( plot_directory )\n\n# initiate plot\nPlot.setDefaults()\n\n\n# Text on the plots\ndef drawObjects( lumi, offset=0 ):\n tex1 = ROOT.TLatex()\n tex1.SetNDC()\n tex1.SetTextSize(0.05)\n tex1.SetTextAlign(11) # align right\n\n tex2 = ROOT.TLatex()\n tex2.SetNDC()\n tex2.SetTextSize(0.04)\n tex2.SetTextAlign(11) # align right\n\n line1 = ( 0.15+offset, 0.95, \"Boosted Info Trees\" )\n line2 = ( 0.68, 0.95, \"%i fb^{-1} (13 TeV)\"%lumi )\n\n return [ tex1.DrawLatex(*line1), tex2.DrawLatex(*line2) ]\n\n\n# Plot a 1D histogram\ndef plot1DHist( plot, plot_directory, yRange=(0.3,\"auto\"), ratio={'yRange':(0.1,1.9)}, legend=(0.2,0.7,0.9,0.9), lumi=137, plotLog=True, histModifications=[], titleOffset=0 ):\n\n for log in [True, False] if plotLog else [False]:\n\n if yRange[0] == 0 and log:\n yRange = list(yRange)\n yRange[0] = 0.0003\n yRange = tuple(yRange)\n\n # Add subdirectory for lin/log plots\n plot_directory_ = os.path.join( plot_directory, \"log\" if log else \"lin\" )\n\n plotting.draw( plot,\n plot_directory = plot_directory_,\n logX = False, logY = log, sorting = False,\n yRange = yRange,\n ratio = ratio,\n# drawObjects = drawObjects( lumi, offset=titleOffset ),\n legend = legend,\n histModifications = histModifications,\n copyIndexPHP = True,\n )\n\n##############\n# Plot Model #\n##############\n\n# Let's plot the model so that Niki sees the hypothesis.\nh_SM = ROOT.TH1F(\"h_SM\", \"h_SM\", 40, model.xmin, model.xmax)\nh_BSM = ROOT.TH1F(\"h_BSM\", \"h_BSM\", 40, model.xmin, model.xmax)\n\nfor i in range(args.nTraining):\n h_SM.Fill ( training_features[i], training_weights[i] )\n h_BSM.Fill( training_features[i], training_weights[i]+args.theta*training_diff_weights[i] )\n\n# Histo style\nh_SM.style = styles.lineStyle( ROOT.kRed, width=2 )\nh_SM.Scale(1./h_SM.Integral())\n\nh_BSM.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\nh_BSM.Scale(1./h_BSM.Integral())\n\nif args.model == \"exponential\" or \"mixture\":\n h_SM.legendText = \"#theta_{0}=%.2f\"%model.theta0\n h_BSM.legendText = \"#theta_{0}+#Delta#theta, #Delta#theta=%.3f\"%args.theta\nelse:\n h_SM.legendText = \"#theta_{0}=%i\"%model.theta0\n h_BSM.legendText = \"#theta_{0}+#Delta#theta, #Delta#theta=%.1f\"%args.theta\n\n\n# Plot of hypothesis\nhistos = [ [h_SM], [h_BSM] ]\nplot = Plot.fromHisto( \"model\", histos, texX=\"x\", texY=\"a.u.\" )\n\n# Plot Style\nhistModifications = [] #lambda h: h.GetYaxis().SetTitleOffset(2.2) ]\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = [] #lambda h: h.GetYaxis().SetTitleOffset(2.2) ]\nratio = None #{'yRange':(0.51,1.49), 'texY':\"BSM/SM\", \"histModifications\":ratioHistModifications}\nlegend = (0.2,0.74,0.6,0.88)\nif args.model == \"power_law\":\n yRange = (0.00003, \"auto\")\nelse:\n yRange = (0, \"auto\")\n\nplot1DHist( plot, plot_directory, yRange=yRange, ratio=ratio, legend=legend, lumi=args.luminosity, histModifications=histModifications )\n\n##############\n##############\n\n\n# Boosting\ntime1 = time.time()\n\n# BIT config\nn_trees = 50\nmax_depth = 3\nlearning_rate = 0.20\nmin_size = 50\nn_plot = 5\n\nbit= BoostedInformationTree(\n training_features = training_features,\n training_weights = training_weights,\n training_diff_weights = training_diff_weights,\n learning_rate = learning_rate,\n n_trees = n_trees,\n max_depth = max_depth,\n min_size = min_size,\n split_method = 'vectorized_split_and_weight_sums',\n weights_update_method = 'vectorized',\n calibrated = False,\n max_uncertainty = args.max_uncertainty,\n bagging_fraction = args.bagging_fraction,\n max_n_split = args.max_n_split,\n )\n\nbit.boost(debug = True)\n\nfrom debug import make_debug_plots\n\n# Testing\ntest_features, test_weights, test_diff_weights = model.get_dataset( args.nTraining )\nif args.fraction_alpha>0 and args.fraction_alpha<1:\n weight_up( args.fraction_alpha, test_diff_weights)\n\nmake_debug_plots( bit, training_features, training_weights, training_diff_weights, test_features, test_weights, test_diff_weights, plot_directory)\n\n#bit.save('tmp.pkl')\n#bit = BoostedInformationTree.load('tmp.pkl')\n\ntime2 = time.time()\nboosting_time = time2 - time1\nprint (\"Boosting time: %.2f seconds\" % boosting_time)\n\ntraining_profile = ROOT.TProfile(\"trainP\", \"trainP\", 8, model.xmin, model.xmax)\ntest_profile = ROOT.TProfile(\"testP\", \"testP\", 8, model.xmin, model.xmax)\ntraining_BSM_profile = ROOT.TProfile(\"BSM_trainP\", \"BSM_trainP\", 8, model.xmin, model.xmax)\ntest_BSM_profile = ROOT.TProfile(\"BSM_testP\", \"BSM_testP\", 8, model.xmin, model.xmax)\n\ntraining = ROOT.TH1D(\"train\", \"train\", 8, model.min_score_theory, model.max_score_theory )\ntest = ROOT.TH1D(\"test\", \"test\", 8, model.min_score_theory, model.max_score_theory )\ntraining_BSM = ROOT.TH1D(\"BSM_train\", \"BSM_train\", 8, model.min_score_theory, model.max_score_theory )\ntest_BSM = ROOT.TH1D(\"BSM_test\", \"BSM_test\", 8, model.min_score_theory, model.max_score_theory )\n\ntraining_FI_histo = ROOT.TH1D(\"trainFI\", \"trainFI\", n_trees, 1, n_trees+1 )\ntest_FI_histo = ROOT.TH1D(\"testFI\", \"testFI\", n_trees, 1, n_trees+1 )\n\ntest_FIs = np.zeros(n_trees)\ntraining_FIs = np.zeros(n_trees)\ntest_FIs_lowPt = np.zeros(n_trees)\ntraining_FIs_lowPt = np.zeros(n_trees)\ntest_FIs_highPt = np.zeros(n_trees)\ntraining_FIs_highPt = np.zeros(n_trees)\n\n\n# Weight variance measure\nVM = ROOT.TH1D(\"VM\", \"VM\", 20, model.xmin, model.xmax)\nVMwp_den = ROOT.TH1D(\"VMwp_den\", \"VMwp_den\", 20, model.xmin, model.xmax)\nVM_den = ROOT.TH1D(\"VM_den\", \"VM_den\", 20, model.xmin, model.xmax)\n\nVM_test = ROOT.TH1D(\"VM_test\", \"VM_test\", 20, model.xmin, model.xmax)\nVM_testwp_den = ROOT.TH1D(\"VM_testwp_den\", \"VM_testwp_den\", 20, model.xmin, model.xmax)\nVM_test_den = ROOT.TH1D(\"VM_test_den\", \"VM_test_den\", 20, model.xmin, model.xmax)\n\nfor i in range(args.nTraining):\n test_scores = bit.predict( test_features[i], summed = False)\n training_scores = bit.predict( training_features[i], summed = False)\n\n test_score = sum( test_scores )\n train_score = sum( training_scores )\n\n test_profile .Fill( test_features[i][0], test_score, test_weights[i] )\n training_profile.Fill( training_features[i][0], train_score, training_weights[i] )\n test_BSM_profile .Fill( test_features[i][0], test_score, test_weights[i]+args.theta*test_diff_weights[i] )\n training_BSM_profile.Fill( training_features[i][0], train_score, training_weights[i]+args.theta*training_diff_weights[i] )\n test .Fill( test_score, test_weights[i])\n training.Fill( train_score, training_weights[i])\n test_BSM .Fill( test_score, test_weights[i]+args.theta*test_diff_weights[i])\n training_BSM.Fill( train_score, training_weights[i]+args.theta*training_diff_weights[i])\n\n # compute test and training FI evolution during training\n test_FIs += test_diff_weights[i]*test_scores\n training_FIs += training_diff_weights[i]*training_scores\n if test_features[i][0]args.highPtThresh:\n test_FIs_highPt += test_diff_weights[i]*test_scores\n if training_features[i][0]>args.highPtThresh:\n training_FIs_highPt += training_diff_weights[i]*training_scores\n\n # compute VM = sum(w'^2/w) / (sum(w')^2/sum(w) ) - 1\n if training_weights[i]!=0:\n VM.Fill( training_features[i][0], training_diff_weights[i]**2/training_weights[i]) \n VMwp_den.Fill(training_features[i][0], training_diff_weights[i]) \n VM_den.Fill( training_features[i][0], training_weights[i]) \n if test_weights[i]!=0:\n VM_test.Fill( test_features[i][0], test_diff_weights[i]**2/test_weights[i]) \n VM_testwp_den.Fill( test_features[i][0], test_diff_weights[i]) \n VM_test_den.Fill( test_features[i][0], test_weights[i]) \n\nfor i_bin in range(1, 1+VM.GetNbinsX() ):\n if VM_den.GetBinContent(i_bin)!=0 and VMwp_den.GetBinContent(i_bin):\n #VM.SetBinContent( i_bin, -1+VM.GetBinContent(i_bin)/(VMwp_den.GetBinContent(i_bin)**2/VM_den.GetBinContent(i_bin)))\n VM.SetBinContent( i_bin, (VMwp_den.GetBinContent(i_bin)**2/VM_den.GetBinContent(i_bin))/VM.GetBinContent(i_bin))\n else:\n VM.SetBinContent( i_bin, 0.)\nfor i_bin in range(1, 1+VM_test.GetNbinsX() ):\n if VM_test_den.GetBinContent(i_bin)!=0 and VM_testwp_den.GetBinContent(i_bin):\n VM_test.SetBinContent( i_bin, (VM_testwp_den.GetBinContent(i_bin)**2/VM_test_den.GetBinContent(i_bin))/VM_test.GetBinContent(i_bin))\n #print i_bin, VM_test.GetBinContent(i_bin), VM_testwp_den.GetBinContent(i_bin)**2, VM_test_den.GetBinContent(i_bin), VM_test.GetBinContent(i_bin)/(VM_testwp_den.GetBinContent(i_bin)**2/VM_test_den.GetBinContent(i_bin)) \n #print i_bin, VM.GetBinContent(i_bin), VM_test.GetBinContent(i_bin)\n else:\n VM_test.SetBinContent( i_bin, 0.)\n\n########################\n# Plot Weight Variance #\n########################\n\n# Histo style\nVM.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\nVM_test.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\nVM.legendText = \"Training (#alpha_f=%4.4f)\"%args.fraction_alpha\nVM_test.legendText = \"Test\"\n\n#VMwp_den.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\n#VM_testwp_den.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\n#VMwp_den.legendText = \"Training (#alpha_f=%4.4f)\"%args.fraction_alpha\n#VM_testwp_den.legendText = \"Test\"\n#\n#VM_den.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\n#VM_test_den.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\n#VM_den.legendText = \"Training (#alpha_f=%4.4f)\"%args.fraction_alpha\n#VM_test_den.legendText = \"Test\"\n\n# Plot of hypothesis\n\n# Plot Style\nhistModifications = [ lambda h: h.GetYaxis().SetTitleOffset(1.4) ]\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = []\nratio = None\nlegend = (0.5,0.65,0.9,0.9)\n\nplot = Plot.fromHisto( \"VM\", [ [VM], [VM_test] ], texX=model.texX, texY=\"VM\" )\nplot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\n#plot = Plot.fromHisto( \"VM_den\", [ [VM_den], [VM_test_den] ])\n#plot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\n#plot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=True, histModifications=histModifications )\n#plot = Plot.fromHisto( \"VMwp_den\", [ [VMwp_den], [VM_testwp_den] ])\n#plot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\n#plot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=True, histModifications=histModifications )\n\n######################################\n# Stat uncertainty of score function #\n######################################\n\nn_bins = 20\n\nJN = ROOT.TH1D(\"JN\", \"JN\", n_bins, model.xmin, model.xmax)\nJN_test = ROOT.TH1D(\"JN_test\", \"JN_test\", n_bins, model.xmin, model.xmax)\n\nJN_rel = ROOT.TH1D(\"JN_rel\", \"JN_rel\", n_bins, model.xmin, model.xmax)\nJN_rel_test = ROOT.TH1D(\"JN_rel_test\", \"JN_rel_test\", n_bins, model.xmin, model.xmax)\n\ndigi = np.digitize(training_features[:,0], np.arange(model.xmin, model.xmax, (model.xmax-model.xmin)/float(n_bins)))\nfor n_bin in range(1,n_bins+1):\n events = digi==n_bin\n n = np.sum(events)\n all_but_one = ( -training_diff_weights[events]+np.sum(training_diff_weights[events]) ) / (-training_weights[events]+np.sum(training_weights[events]) )\n mean_all_but_one = np.mean(all_but_one)\n uncertainty = sqrt( (n-1.)/n*( np.sum( ( all_but_one-mean_all_but_one)**2 ) ) )\n JN.SetBinContent( n_bin, uncertainty )\n JN_rel.SetBinContent( n_bin, uncertainty/np.sum(training_weights[events]) )\ndigi = np.digitize(test_features[:,0], np.arange(model.xmin, model.xmax, (model.xmax-model.xmin)/float(n_bins)))\nfor n_bin in range(1,n_bins+1):\n events = digi==n_bin\n n = np.sum(events)\n all_but_one = ( -test_diff_weights[events]+np.sum(test_diff_weights[events]) ) / (-test_weights[events]+np.sum(test_weights[events]) )\n mean_all_but_one = np.mean(all_but_one)\n uncertainty = sqrt( (n-1.)/n*( np.sum( ( all_but_one-mean_all_but_one)**2 ) ) )\n JN_test.SetBinContent( n_bin, uncertainty )\n JN_rel_test.SetBinContent( n_bin, uncertainty/np.sum(test_weights[events]) )\n\nJN.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\nJN_test.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\nJN.legendText = \"Training (#alpha_f=%4.4f)\"%args.fraction_alpha\nJN_test.legendText = \"Test\"\nJN_rel.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\nJN_rel_test.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\nJN_rel.legendText = \"Training (#alpha_f=%4.4f)\"%args.fraction_alpha\nJN_rel_test.legendText = \"Test\"\n\n# Plot Style\nhistModifications = [ lambda h: h.GetYaxis().SetTitleOffset(1.4) ]\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = []\nratio = None\nlegend = (0.5,0.65,0.9,0.9)\n\nplot = Plot.fromHisto( \"JN\", [ [JN], [JN_test] ], texX=model.texX, texY=\"JN\" )\nplot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\nplot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=True, histModifications=histModifications )\nplot = Plot.fromHisto( \"JN_rel\", [ [JN_rel], [JN_rel_test] ], texX=model.texX, texY=\"JN_rel\" )\nplot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\nplot1DHist( plot, plot_directory, yRange=\"auto\", ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=True, histModifications=histModifications )\n\n######################\n# Plot Score Profile #\n######################\n\n# Histo style\ntraining_profile.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\ntest_profile .style = styles.lineStyle( ROOT.kBlue, width=2 )\ntraining_BSM_profile.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\ntest_BSM_profile .style = styles.lineStyle( ROOT.kRed, width=2 )\n\ntraining_profile.legendText = \"Training (#theta_{0})\"\ntest_profile .legendText = \"Test (#theta_{0})\"\ntraining_BSM_profile.legendText = \"Training (#theta_{0}+#Delta#theta)\"\ntest_BSM_profile .legendText = \"Test (#theta_{0}+#Delta#theta)\"\n\n# Plot of hypothesis\nhistos = [ [training_profile], [test_profile], [training_BSM_profile], [test_BSM_profile] ]\nplot = Plot.fromHisto( \"score_profile_validation_profile\", histos, texX=model.texX, texY=\"F(x)\" )\n\n# Plot Style\nhistModifications = [ lambda h: h.GetYaxis().SetTitleOffset(1.4) ]\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = []\nratio = None\nlegend = (0.55,0.6,0.9,0.9)\nminY = model.min_score_theory\nmaxY = model.max_score_theory\nyRange = (minY, maxY)\n\n#plot1DHist( plot, plot_directory, yRange=yRange, ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\n\n##############\n##############\n\n\n#########################\n# Plot Score Validation #\n#########################\n\n# Histo style\ntraining.style = styles.lineStyle( ROOT.kBlue, width=2, dashed=True )\ntest .style = styles.lineStyle( ROOT.kBlue, width=2 )\ntraining_BSM.style = styles.lineStyle( ROOT.kRed, width=2, dashed=True )\ntest_BSM .style = styles.lineStyle( ROOT.kRed, width=2 )\n\ntraining.legendText = \"Training (#theta_{0})\"\ntest .legendText = \"Test (#theta_{0})\"\ntraining_BSM.legendText = \"Training (#theta_{0}+#Delta#theta)\"\ntest_BSM .legendText = \"Test (#theta_{0}+#Delta#theta)\"\n\ntest.Scale(1./training.Integral())\ntest_BSM.Scale(1./training_BSM.Integral())\ntraining.Scale(1./training.Integral())\ntraining_BSM.Scale(1./training_BSM.Integral())\n\n# Plot of hypothesis\nhistos = [ [training], [test], [training_BSM], [test_BSM] ]\n\nplot = Plot.fromHisto( \"score_validation\", histos, texX=\"F(x)\", texY=\"a.u.\" )\n\n# Plot Style\nhistModifications = []\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = []\nratio = None\nlegend = (0.2,0.64,0.6,0.88)\nminY = 1\nmaxY = (10 if model.make_log else 2.2)*max( map( lambda h:h.GetMaximum(), [training, test, training_BSM, test_BSM] ) )\n#yRange = (0, \"auto\") #( minY, maxY )\nyRange = \"auto\" #( minY, maxY )\n\nplot1DHist( plot, plot_directory, yRange=yRange, ratio=ratio, legend=legend, lumi=args.luminosity, histModifications=histModifications )\n\n##############\n##############\n\n\n##################\n# Plot Evolution #\n##################\n\nfor name, texName, test_FIs_, training_FIs_ in [\n (\"all\", \"\", test_FIs, training_FIs),\n# (\"lowPt\", \", p_{T}< %i GeV\"%args.lowPtThresh, test_FIs_lowPt, training_FIs_lowPt),\n# (\"highPt\", \", p_{T} > %i GeV\"%args.highPtThresh, test_FIs_highPt, training_FIs_highPt),\n ]:\n for i_tree in range(n_trees):\n test_FI_histo .SetBinContent( i_tree+1, -sum(test_FIs_[:i_tree]) )\n training_FI_histo.SetBinContent( i_tree+1, -sum(training_FIs_[:i_tree]) )\n\n # Histo style\n test_FI_histo .style = styles.lineStyle( ROOT.kBlue, width=2 )\n training_FI_histo.style = styles.lineStyle( ROOT.kRed, width=2 )\n test_FI_histo .legendText = \"Test%s\"%texName\n training_FI_histo.legendText = \"Training%s\"%texName\n\n minY = 0.01 * min( test_FI_histo.GetBinContent(test_FI_histo.GetMaximumBin()), training_FI_histo.GetBinContent(training_FI_histo.GetMaximumBin()))\n maxY = 1.5 * max( test_FI_histo.GetBinContent(test_FI_histo.GetMaximumBin()), training_FI_histo.GetBinContent(training_FI_histo.GetMaximumBin()))\n\n histos = [ [test_FI_histo], [training_FI_histo] ]\n plot = Plot.fromHisto( \"FI_evolution_%s\"%name, histos, texX=\"b\", texY=\"L(D,b)\" )\n\n # Plot Style\n histModifications = []\n histModifications += [ lambda h: h.GetYaxis().SetTitleOffset(1.4) ]\n histModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\n histModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\n histModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\n histModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\n ratioHistModifications = []\n ratio = None\n if name == \"all\":\n legend = (0.6,0.75,0.9,0.88)\n# legend = (0.6, 0.2, 0.9, 0.32)\n elif args.model == \"power_law\" and name == \"highPt\":\n legend = (0.2,0.75,0.7,0.88)\n else:\n legend = (0.4, 0.2, 0.9, 0.4)\n yRange = \"auto\" #( minY, maxY )\n\n plot1DHist( plot, plot_directory, yRange=yRange, ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, titleOffset=0.08, histModifications=histModifications )\n\n##############\n##############\n\n\n##############\n# Plot Score #\n##############\n\n# Make a histogram from the score function (1D)\ndef score_histo( bit, title, max_n_tree = None):\n h = ROOT.TH1F(str(title), str(title), 400, model.xmin, model.xmax)\n for i in range(1, h.GetNbinsX()+1):\n h.SetBinContent( i, bit.predict([h.GetBinLowEdge(i)], max_n_tree = max_n_tree, last_tree_counts_full=False))\n return copy.deepcopy(h.Clone())\n\n# Histo style\nhistos = []\nhistos.append( [model.score_theory] )\nhistos[-1][0].style = styles.lineStyle( ROOT.kRed, width=2 )\nhistos[-1][0].legendText = \"t(x|#theta_{0})\"\n\n# empty slot in the legend\nempty = score_histo( bit, \"empty\", max_n_tree=0 )\nempty.Scale(0)\nhistos.append( [empty] )\nhistos[-1][0].style = styles.lineStyle( ROOT.kWhite, width=0 )\nhistos[-1][0].legendText = \" \"\n\ncounter=0\ncolors = [8,30,38,9,13]\nfor n_tree in range(bit.n_trees):\n if bit.n_trees <= n_plot or n_tree%(bit.n_trees/n_plot) == 0:\n\n histos.append( [score_histo( bit, str(counter), max_n_tree=n_tree )] )\n histos[-1][0].style = styles.lineStyle( colors[counter], width=3 )\n histos[-1][0].legendText = \"F^{(%i)}\"%(n_tree)\n counter+=1\n\nhistos.append( [score_histo( bit, \"full\" )] )\nhistos[-1][0].style = styles.lineStyle( ROOT.kBlack, width=3 )\nhistos[-1][0].legendText = \"F^{(%i)}\"%(n_tree+1)\n\n# Plot of hypothesis\nplot = Plot.fromHisto( \"score_boosted\", histos, texX=\"x\", texY=\"F(x)\" )\n\n# Plot Style\nhistModifications = []\nhistModifications += [ lambda h: h.GetXaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetYaxis().SetTitleSize(26) ]\nhistModifications += [ lambda h: h.GetXaxis().SetLabelSize(22) ]\nhistModifications += [ lambda h: h.GetYaxis().SetLabelSize(22) ]\n\nratioHistModifications = []\nratio = None\nminY = model.min_score_theory\nmaxY = model.max_score_theory\nif args.model == \"power_law\":\n legend = [(0.6,0.63,0.85,0.9),2]\nelif args.model == \"gaussian_width\":\n legend = [(0.42,0.6,0.67,0.87),2]\n minY = -1\n maxY = 17\nelif args.model == \"gaussian_mean\":\n legend = [(0.2,0.6,0.45,0.87),2]\nelif args.model == \"piece_wise\":\n legend = [(0.65,0.15,0.9,0.5),2]\n minY = -0.4\n maxY = 0.25\nelif args.model == \"mixture1D\":\n legend = [(0.2,0.45,0.45,0.73),2]\nelse:\n legend = [(0.2,0.15,0.45,0.43),2]\nyRange = (minY, maxY)\n\nplot1DHist( plot, plot_directory, yRange=yRange, ratio=ratio, legend=legend, lumi=args.luminosity, plotLog=False, histModifications=histModifications )\n\n##############\n##############\n","sub_path":"bit_tests.py","file_name":"bit_tests.py","file_ext":"py","file_size_in_byte":27755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"245301778","text":"# Runtime 94 ms\n# Beats 61%\n# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n def connect(self, root):\n # cur: current level\n # pre: next level, previous node in the linked list\n # first: next level, first node in the linked list\n\n cur = root\n while (cur): \n first = pre = TreeLinkNode(0)\n while (cur):\n if cur.left:\n pre.next = cur.left\n pre = pre.next\n\n if cur.right:\n pre.next = cur.right\n pre = pre.next\n \n cur = cur.next\n cur = first.next\n","sub_path":"117-Populating-Next-Right-Pointers-in-Each-Node-II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"559218400","text":"from lib import action\n\n\nclass JobInfo(action.JenkinsBaseAction):\n def run(self, jobname):\n jobInfo = self.jenkins.get_job_info(jobname)\n buildNumber = jobInfo[\"lastSuccessfulBuild\"][\"number\"]\n buildInfo = self.jenkins.get_build_info(jobname,buildNumber)\n userId = buildInfo[\"actions\"][0][\"causes\"][0][\"userId\"]\n timeStamp = buildInfo[\"timestamp\"]\n result = buildInfo[\"result\"]\n mongoDict = {\n 'jobname' : jobname,\n 'buildnumber' : buildNumber,\n 'user' : userId,\n 'timestamp' : timeStamp\n }\n# mongoResult = self.pymongo.db.jenkins.insert_one(mongoDict)\n message = \"JobName = \" + str(jobname) + \"\\nBuild Number = \" + str(buildNumber) + \"\\n user = \" + str(userId) + \"\\nTimeStamp = \" + str(timeStamp) + \"\\nResult = \" + str(result)\n return message\n","sub_path":"actions/get_build_info.py","file_name":"get_build_info.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"92624402","text":"import pandas as pd\r\nimport datetime as datetime\r\nimport pyarrow as pa\r\nimport pyarrow.parquet as pq\r\nimport shutil\r\n\r\nt = datetime.datetime.now().date()\r\n\r\ndef date_range(t):\r\n if t.month >= 7 and t.month <= 9:\r\n date_range_start = datetime.date(t.year - 1, 7, 1) #Dates for whole cumulative year.\r\n date_range_end = datetime.date(t.year, 6, 30)\r\n FY = t.year\r\n FQ = 'Q4'\r\n elif t.month >= 10 and t.month <= 12:\r\n date_range_start = datetime.date(t.year, 7, 1) #First Quarter\r\n date_range_end = datetime.date(t.year, 9, 30)\r\n FY = t.year + 1\r\n FQ = 'Q1'\r\n elif t.month >= 1 and t.month <= 3:\r\n date_range_start = datetime.date(t.year - 1, 7, 1) #Second Quarter\r\n date_range_end = datetime.date(t.year - 1, 12, 31)\r\n FY = t.year\r\n FQ = 'Q2'\r\n elif t.month >= 4 and t.month <= 6:\r\n date_range_start = datetime.date(t.year - 1, 7, 1) #Third Quarter\r\n date_range_end = datetime.date(t.year, 3, 31)\r\n FY = t.year\r\n FQ = 'Q3'\r\n return [date_range_start, date_range_end, FQ, FY]\r\n\r\n[date_range_start, date_range_end, FQ, FY] = date_range(t)\r\n\r\nstart_date = str(date_range_start.month) + '/' + str(date_range_start.day) + '/' + str(date_range_start.year)\r\nend_date = str(date_range_end.month) + '/' + str(date_range_end.day) + '/' + str(date_range_end.year)\r\n\r\ndf = pd.read_csv(r'S:\\Contracts\\Research and IT\\08 - MWBE\\DAS Only\\09 - Python and R Scripts\\LL1 PROG\\Open Contracts Localized\\open_contracts%s_%s.txt' % (str(FY)[2:4], str(t)), low_memory = False)\r\n\r\ntable = pa.Table.from_pandas(df, preserve_index = False)\r\n\r\npath = r'C:\\open_contracts'\r\n\r\npq.write_table(table, path + '\\\\' + r'open_contracts_%s.parquet' % (str(t)))\r\n\r\nshutil.move(\"C:\\open_contracts\\open_contracts_%s.parquet\" % (str(t)), r\"S:\\Contracts\\Research and IT\\08 - MWBE\\DAS Only\\09 - Python and R Scripts\\LL1ProgFY19Q3\\Datasets\\Open Contracts\")\r\n\r\n\r\n\r\n","sub_path":"open_contracts_localization.py","file_name":"open_contracts_localization.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"228258487","text":"__author__ = 'Sunny Han'\nimport numpy as np\nimport cv2\n\nim1 = cv2.imread(\"../img/4.png\",0)\ncv2.imshow(\"orig\",im1)\n\n\n# 调用OpenCV中的均值模糊API\nim_meanblur1 = cv2.blur(im1,(10,10))\ncv2.imshow('mean_blur_1',im_meanblur1)\n\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"图像滤波/均值滤波.py","file_name":"均值滤波.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"625850233","text":"from mcpi import minecraft\nimport RPi.GPIO as gpio\nimport time\n\n\nmc = minecraft.Minecraft.create()\n\ndef my_callback(self):\n global camera\n if camera == True:\n mc.camera.setNormal()\n camera = False\n else:\n mc.camera.setFollow(mc.getPlayerEntityIds())\n camera = True\n\ncamera = False\n\ngpio.setmode(gpio.BCM)\ngpio.setup(17, gpio.IN)\ngpio.add_event_detect(17, gpio.RISING, callback=my_callback, bouncetime =200)\ntry:\n while True:\n time.sleep(0.2)\nexcept KeyboardInterrupt:\n pass\n\ngpio.cleanup()\n","sub_path":"mc_camera.py","file_name":"mc_camera.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"488470115","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5, padding=2)\n self.pool = nn.MaxPool2d(2, stride=2)\n self.conv2 = nn.Conv2d(6, 16, 4, padding=0)\n self.fc1 = nn.Linear(16 * 6 * 6, 100)\n self.fc2 = nn.Linear(100, 23)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 6 * 6)\n x = F.relu(self.fc1(x))\n x = self.fc2(x)\n return x\n\ndef number_to_char(num):\n alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',\n 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Z']\n return alpha[num]\n","sub_path":"text-based-captcha-solver/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"540238298","text":"from zipfile import ZipFile\n\n\ndef good_human_read_format(size):\n values = ['Б', 'КБ', 'МБ', 'ГБ']\n num = 0\n while size >= 1024:\n size /= 1024\n num += 1\n return f\"{round(size)}{values[num]}\"\n\n\nwith ZipFile('input.zip') as myzip:\n for file in myzip.filelist:\n name = file.filename\n if name[-1] == '/': # каталог\n print(' ' * (name.count('/') - 1) + file.orig_filename.split('/')[-2])\n else:\n print(f\"{' ' * (name.count('/'))}{file.orig_filename.split('/')[-1]} \"\n f\"{good_human_read_format(file.file_size)}\")\n","sub_path":"2nd_year/WEB0. Работа с популярными форматами файлов (json, xml)/Home/05_archive_structure_2.py","file_name":"05_archive_structure_2.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"76225405","text":"# Sorbonne Université 3I024 2018-2019\n# TME 2 : Cryptanalyse du chiffre de Vigenere\n#\n# Etudiant.e 1 : TAOUSSI 3521415\n# Etudiant.e 2 : MMADI ALI AMIRDINE 3520922\n\nimport sys, getopt, string, math\n\n# Alphabet français\nalphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n# Fréquence moyenne des lettres en français\n# À modifier\nfreq_FR = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n\n# Chiffrement César\ndef chiffre_cesar(txt, clef):\n \"\"\"\n Documentation à écrire\n \"\"\"\n cle = int(clef)\n res = \"\"\n message_chiffre = txt\n for i in range(len(message_chiffre)):\n let = ord(message_chiffre[i])%ord('A')\n let = (let+cle)%26\n res += chr(let+ord('A'))\n message_chiffre = res\n \n return message_chiffre\n\n# Déchiffrement César\ndef dechiffre_cesar(txt, clef):\n \"\"\"\n Documentation à écrire\n \"\"\"\n cle = int(clef)\n message_chiffre = txt\n chiff = \"\"\n for i in range(len(message_chiffre)):\n res = ord(message_chiffre[i] )%ord('A')\n res = (res-cle)%26\n chiff += chr(res + ord('A'))\n message_chiffre = chiff\n return message_chiffre\n\n# Chiffrement Vigenere\ndef chiffre_vigenere(txt, key):\n \"\"\"\n Documentation à écrire\n \"\"\"\n message_chiffre = \"\"\n for i in range(len(txt)):\n lettre = ord(txt[i])%ord(\"A\")\n lettre_chiffre = (lettre + key[i%len(key)])%26\n message_chiffre += chr(lettre_chiffre+ord('A'))\n \n return message_chiffre\n\n# Déchiffrement Vigenere\ndef dechiffre_vigenere(txt, key):\n \"\"\"\n Documentation à écrire\n \"\"\"\n message_dechiffre = \"\"\n for i in range(len(txt)):\n lettre = ord(txt[i])%ord(\"A\")\n lettre_dechiffre = (lettre-key[i%len(key)])%26\n message_dechiffre += chr(lettre_dechiffre+ord('A'))\n \n return message_dechiffre\n\n# Analyse de fréquences\ndef freq(txt):\n \"\"\"\n Documentation à écrire\n \"\"\"\n\n freq = list()\n\n for i in range(26):\n freq.append(0)\n\n for lettre in txt:\n tmp = ord(lettre.upper())%ord('A')\n freq[tmp]+=1\n\n \n return freq\n\n# Renvoie l'indice dans l'alphabet\n# de la lettre la plus fréquente d'un texte\ndef lettre_freq_max(txt):\n \"\"\"\n Documentation à écrire\n \"\"\"\n frequence = freq(txt)\n maximum = max(frequence)\n lettre = frequence.index(maximum)\n return lettre\n\n# indice de coïncidence\ndef indice_coincidence(hist):\n \"\"\"\n Documentation à écrire\n \"\"\"\n #On calcule le nombre de lettre totals\n total_lettres = sum(hist)\n\n res = 0.0\n for i in range(len(hist)):\n res += (hist[i]*1.0*(hist[i]-1))/(total_lettres*1.0*(total_lettres-1))\n return res\n\n# Recherche la longueur de la clé\ndef longueur_clef(cipher):\n \"\"\"\n Documentation à écrire\n \"\"\"\n #On parcours les tailles de clés possibles (20)\n for i in range(20):\n Liste_Colonne = list()\n #On construit nos colonnes\n for j in range(i+1):\n Liste_Colonne.append(cipher[j:len(cipher):i+1])\n moy_colonne = 0\n #On calcule la moyenne de chaque colonne\n for colonne in Liste_Colonne:\n moy_colonne += indice_coincidence(freq(colonne))\n #on teste si la moyenne est bien superieure a 0.06\n if moy_colonne/((i+1)*1.0) > 0.06:\n return i+1\n return -1\n \n# Renvoie le tableau des décalages probables étant\n# donné la longueur de la clé\n# en utilisant la lettre la plus fréquente\n# de chaque colonne\ndef clef_par_decalages(cipher, key_length):\n \"\"\"\n Documentation à écrire\n \"\"\"\n decalages=[0]*key_length\n Liste_Colonne = list()\n for j in range(key_length):\n Liste_Colonne.append(cipher[j:len(cipher):key_length])\n for i in range(len(Liste_Colonne)):\n decalages[i] = (lettre_freq_max(Liste_Colonne[i])-(ord('E')%ord('A')))%26\n \n return decalages\n\n# Cryptanalyse V1 avec décalages par frequence max\ndef cryptanalyse_v1(cipher):\n \"\"\"\n Documentation à écrire\n 18 texts sur 100 ont été dechiffrés. Cela est du au fait que les textes ne sont pas assez long \n pour analyser les colonnes.\n \"\"\"\n clef = clef_par_decalages(cipher,longueur_clef(cipher))\n \n return dechiffre_vigenere(cipher,clef)\n\n\n################################################################\n\n\n### Les fonctions suivantes sont utiles uniquement\n### pour la cryptanalyse V2.\n\n# Indice de coincidence mutuelle avec décalage\ndef indice_coincidence_mutuelle(h1,h2,d):\n \"\"\"\n Documentation à écrire\n \"\"\"\n total_lettres = sum(h1)*sum(h2)\n res = 0.0\n for i in range(len(h1)):\n res += (h1[i]*h2[(i+d)%26]*1.0)/total_lettres\n return res\n\n# Renvoie le tableau des décalages probables étant\n# donné la longueur de la clé\n# en comparant l'indice de décalage mutuel par rapport\n# à la première colonne\ndef tableau_decalages_ICM(cipher, key_length):\n \"\"\"\n Documentation à écrire\n \"\"\" \n decalages=[0]*key_length\n Liste_Colonne = list()\n for j in range(key_length):\n Liste_Colonne.append(cipher[j:len(cipher):key_length])\n copy = Liste_Colonne\n for deuxieme in Liste_Colonne[1:]:\n maxim = 0\n for i in range(26):\n res = indice_coincidence_mutuelle(freq(Liste_Colonne[0]),freq(deuxieme),i)\n if res > maxim:\n decalages[Liste_Colonne.index(deuxieme)] = i\n maxim = res\n return decalages\n\n# Cryptanalyse V2 avec décalages par ICM\ndef cryptanalyse_v2(cipher):\n \"\"\"\n Documentation à écrire\n \"\"\"\n Liste_Colonne = list()\n key_length = longueur_clef(cipher)\n decalages = tableau_decalages_ICM(cipher,key_length)\n \n for j in range(key_length):\n Liste_Colonne.append(cipher[j:len(cipher):key_length])\n\n for i in range(len(Liste_Colonne)):\n Liste_Colonne[i] = dechiffre_cesar(Liste_Colonne[i],decalages[i])\n text = \"\"\n for i in range(len(Liste_Colonne[0])):\n for colonne in Liste_Colonne:\n if i < len(colonne):\n text+=colonne[i]\n decalage = (lettre_freq_max(text)-4)%26\n text = dechiffre_cesar(text,decalage)\n\n return text\n\n\n################################################################\n\n\ngerminal = open(\"./Germinal.txt\",\"r\").read()\nfreq_FR = freq(germinal)\nfor i in range(len(freq_FR)):\n freq_FR[i] = freq_FR[i]/(1.0*len(germinal))\nprint(freq_FR)\n\n### Les fonctions suivantes sont utiles uniquement\n### pour la cryptanalyse V3.\nfrom math import sqrt\n# Prend deux listes de même taille et\n# calcule la correlation lineaire de Pearson\ndef correlation(L1,L2):\n \"\"\"\n Documentation à écrire\n \"\"\"\n if len(L2) != len(L1):\n return -1\n cor = 0.0\n numerateur = 0.0\n denominateur1 = 0.0\n denominateur2 = 0.0\n l1_barre = 0.0\n l2_barre = 0.0\n \n for i in range(len(L2)):\n l1_barre += L1[i]\n l2_barre += L2[i]\n l1_barre = l1_barre/(len(L1)*1.0)\n l2_barre = l2_barre/(len(L2)*1.0)\n\n for i in range(len(L2)):\n numerateur += (L1[i] - l1_barre) * (L2[i] - l2_barre)\n denominateur1 += pow(L1[i]-l1_barre,2)\n denominateur2 += pow(L2[i]-l2_barre,2)\n \n cor = (numerateur*1.0)/(sqrt(denominateur1*denominateur2))\n \n return cor\n\n# Renvoie la meilleur clé possible par correlation\n# étant donné une longueur de clé fixée\ndef clef_correlations(cipher, key_length):\n \"\"\"\n Documentation à écrire\n \"\"\"\n key=[0]*key_length\n scores = [-1.0]*key_length\n score = 0.0\n Liste_Colonne_orig = list()\n for j in range(key_length):\n Liste_Colonne_orig.append(cipher[j:len(cipher):key_length])\n \n for i in range(key_length):\n for j in range(26):\n score_temp = correlation(freq(dechiffre_cesar(Liste_Colonne_orig[i],j)),freq_FR)\n \n if score_temp > scores[i]:\n scores[i] = score_temp\n key[i] = j\n if len(scores) > 0:\n score = sum(scores)/(len(scores)*1.0)\n return (score, key)\n\n# Cryptanalyse V3 avec correlations\ndef cryptanalyse_v3(cipher):\n \"\"\"\n Documentation à écrire\n \"\"\"\n\n score = -1.0\n key = 0\n\n for i in range(20):\n score_temp,key_temp = clef_correlations(cipher,i)\n if score_temp > score:\n score = score_temp\n key = key_temp\n\n text = dechiffre_vigenere(cipher,key)\n \n return text\n\n\n################################################################\n# NE PAS MODIFIER LES FONCTIONS SUIVANTES\n# ELLES SONT UTILES POUR LES TEST D'EVALUATION\n################################################################\n\n\n# Lit un fichier et renvoie la chaine de caracteres\ndef read(fichier):\n f=open(fichier,\"r\")\n txt=(f.readlines())[0].rstrip('\\n')\n f.close()\n return txt\n\n# Execute la fonction cryptanalyse_vN où N est la version\ndef cryptanalyse(fichier, version):\n cipher = read(fichier)\n if version == 1:\n return cryptanalyse_v1(cipher)\n elif version == 2:\n return cryptanalyse_v2(cipher)\n elif version == 3:\n return cryptanalyse_v3(cipher)\n\ndef usage():\n print (\"Usage: python3 cryptanalyse_vigenere.py -v <1,2,3> -f \", file=sys.stderr)\n sys.exit(1)\n\ndef main(argv):\n size = -1\n version = 0\n fichier = ''\n try:\n opts, args = getopt.getopt(argv,\"hv:f:\")\n except getopt.GetoptError:\n usage()\n for opt, arg in opts:\n if opt == '-h':\n usage()\n elif opt in (\"-v\"):\n version = int(arg)\n elif opt in (\"-f\"):\n fichier = arg\n if fichier=='':\n usage()\n if not(version==1 or version==2 or version==3):\n usage()\n\n print(\"Cryptanalyse version \"+str(version)+\" du fichier \"+fichier+\" :\")\n print(cryptanalyse(fichier, version))\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"cryptanalyse_vigenere.py","file_name":"cryptanalyse_vigenere.py","file_ext":"py","file_size_in_byte":9925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"44861125","text":"class Node:\r\n def __init__(self,val):\r\n self.val = val\r\n self.left = None\r\n self.right = None\r\n self.level = 0\r\n\r\n# need to use level and 2^level\r\ndef minimum_level_sun(root):\r\n q = [root]\r\n summ = []\r\n while q:\r\n x = 0\r\n marx = len(q)\r\n for i in range(marx):\r\n temp = q.pop(0)\r\n x += temp.val\r\n if temp.left and (not temp.right):\r\n q.append(temp.left)\r\n if temp.right and (not temp.left):\r\n q.append(temp.right)\r\n if temp.left and temp.right:\r\n q.append(temp.left)\r\n q.append(temp.right)\r\n summ.append(x)\r\n return min(summ)\r\n\r\nroot = Node(10)\r\nroot.left = Node(2)\r\nroot.right = Node(8)\r\nroot.left.left = Node(4)\r\nroot.left.right = Node(1)\r\nroot.right.right = Node(2)\r\n\r\nprint(minimum_level_sun(root))\r\n\r\n\r\n ","sub_path":"dailyProInterview/day30.py","file_name":"day30.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"550699214","text":"from typing import List\nimport heapq\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n nums_copy = [-1*num for num in nums]\n heapq.heapify(nums_copy)\n k-=1\n while k:\n heapq.heappop(nums_copy)\n k-=1\n return -1*heapq.heappop(nums_copy)\n\n\nobj = Solution()\nprint(obj.findKthLargest([3,2,1,5,6,4],2))","sub_path":"215-Kth-Largest-In-An-Array.py","file_name":"215-Kth-Largest-In-An-Array.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"224579351","text":"\"\"\"4.3 List of Depths\n\nProblem:\n\n Given a binary tree, design an algorithm which creates a linked list of all\n the nodes at each depth.\n\nApproach:\n\n The BFS traverses the tree in level-order fashion; that means the queue used\n at beginning of each iteration would contain entire nodes within the level.\n\n\"\"\"\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.left = self.right = None\n self.visisted = None\n\nclass Solution:\n def createDepthLists(self, root):\n result = []\n queue = [root]\n while len(queue) > 0:\n result.append(queue.copy())\n parents = queue\n queue = []\n for node in parents:\n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n return result\n\ndef main():\n root = Node(1)\n node1, node2 = Node(2), Node(3)\n node3, node4 = Node(4), Node(5)\n root.left, root.right = node1, node2\n node1.left, node2.right = node3, node4\n result = Solution().createDepthLists(root)\n values = []\n for level in result:\n temp = []\n for node in level:\n temp.append(node.data)\n values.append(temp)\n print(values)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Coding_Question/CCI/04_Trees_and_Graphs/4.3_listOfDepths.py","file_name":"4.3_listOfDepths.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"51260159","text":"#!usr/bin/python3\n\nimport socket,time\n#checking for socket functions\n\n\nprint([i for i in dir(socket) if 'socket' in i])\n\n#now creating udp socket\n#ipv4 socket would be-- ipv4+2byte por\n#ipv6 socket would be-- ipv6+2byte port \ns=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) #for ipv4 UDP\n#socket.socket(socket.AF_INET,socket.SOCK_STREAM) # for ipv4 TCP\n\n###below step for receivers end\ns.bind((\"\",8883))\n#bind will aceept tuple format ip & port\nwhile True :\n data=s.recvfrom(1000)\n print(data[0])\n print('sender address is :',data[1])\n msg=input('enter reply :')\n newmsg=msg.encode('ascii')\n s.sendto(newmsg,data[1])\ns.close()\n\n###below step for senders end\n#msg=input(\"enter data to send : \")\n\n#converting data into byte-like string format\n#newmsg=msg.encode('ascii')\n#s.sendto(msg,(\"127.0.0.1\",8899))\n#s.close()\n\n","sub_path":"manish_rx.py","file_name":"manish_rx.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"249080059","text":"# Python program to find current\n# weather details of any city\n# using openweathermap api\n\n# import required modules\nimport requests\nimport json\n\n\ndef weather(city_name):\n # Enter your API key here\n api_key = \"d7fb6928448a9df3527ff57926ebec3c\"\n\n # base_url variable to store url\n base_url = \"http://api.openweathermap.org/data/2.5/weather?\"\n\n # Give city name\n # city_name = input(\"Enter city name : \")\n\n # complete_url variable to store\n # complete url address\n complete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name\n\n # get method of requests module\n # return response object\n response = requests.get(complete_url)\n\n # json method of response object\n # convert json format data into\n # python format data\n x = response.json()\n\n # Now x contains list of nested dictionaries\n # Check the value of \"cod\" key is equal to\n # \"404\", means city is found otherwise,\n # city is not found\n if x[\"cod\"] != \"404\":\n # store the value of \"main\"\n # key in variable y\n y = x[\"main\"]\n # store the value corresponding\n # to the \"temp\" key of y\n current_temperature = y[\"temp\"]\n # store the value corresponding\n # to the \"pressure\" key of y\n current_pressure = y[\"pressure\"]\n # store the value corresponding\n # to the \"humidity\" key of y\n current_humidiy = y[\"humidity\"]\n # store the value of \"weather\"\n # key in variable z\n z = x[\"weather\"]\n # store the value corresponding\n # to the \"description\" key at\n # the 0th index of z\n weather_description = z[0][\"description\"]\n # print following values\n info = \" Temperature (in Celsius unit) = \"+str(current_temperature-273.15)+\" *C\"\\\n + \"\\n Feels like: \" + str(y['feels_like']-273.15)+\" *C\"+\"\\nTemperature max/min: \"+str(y['temp_max']-273.15)+\"/\"\\\n + str(y['temp_min']-273.15)+\" *C\"+\"\\natmospheric pressure (in hPa unit) = \"\\\n + str(current_pressure)+\"\\n humidity (in percentage) = \"+str(current_humidiy)+\"%\"+\"\\n description = \"\\\n + str(weather_description)\n return info\n else:\n return 'City not found'\n\n# a = {'coord': {'lon': 105.84, 'lat': 21.02},\n# 'weather': [{'id': 701, 'main': 'Mist', 'description': 'mist', 'icon': '50n'}],\n# 'base': 'stations',\n# 'main': {'temp': 294.15, 'feels_like': 296.79, 'temp_min': 294.15, 'temp_max': 294.15, 'pressure': 1016, 'humidity': 94},\n# 'visibility': 2100,\n# 'wind': {'speed': 1.5, 'deg': 40},\n# 'clouds': {'all': 90},\n# 'dt': 1584378298,\n# 'sys': {'type': 1, 'id': 9308, 'country': 'VN', 'sunrise': 1584399805, 'sunset': 1584443196},\n# 'timezone': 25200,\n# 'id': 1581130,\n# 'name': 'Hanoi',\n# 'cod': 200}\n","sub_path":"function/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"314818135","text":"from flask import Flask, render_template, request, redirect, session, flash\napp = Flask(__name__)\napp.secret_key=\"343uhr32u4923g49u32h4\"\nprint('\\n','===== server start =====')\n\n@app.route('/')\ndef index():\n if 'name' not in session:\n session['name']=''\n if 'description' not in session:\n session['description'] =''\n\n return render_template('index.html', name=session['name'], descr=session['description'])\n\n@app.route('/forminfo', methods=['POST'])\ndef forminfo():\n print('\\n')\n print(' = = = = got POST info = = = =')\n print(request.form)\n print(' = = = = end of POST info = = = = =')\n print('\\n')\n session['name'] = request.form['name']\n session['description'] = request.form['description']\n session['location'] = request.form['location']\n session['language'] = request.form['language']\n \n validationErrors = False\n\n # name valid\n if len(request.form['name']) == 0:\n validationErrors = True\n flash('name cannot be empty!')\n elif len(request.form['name']) < 4:\n validationErrors = True\n flash('name must be more than 3 characters long')\n\n # description valid\n if len(session['description']) > 120:\n validationErrors = True\n flash('comments cannot exceed 120 characters :(')\n\n if validationErrors:\n return redirect('/')\n else:\n return redirect('/success')\n\n@app.route('/success')\ndef success():\n return render_template('result.html')\n\n@app.route('/reset')\ndef reset():\n print('\\n')\n print(' = = = = session cleared = = = =')\n session.clear()\n print(' = = = = redirecting to \"/\" = = = = =')\n print('\\n')\n return redirect ('/')\n\n@app.route('/danger/')\ndef danger():\n print('# # # # # # # # # # # # # # # DANGER ZONE')\n return redirect('/')\n \nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"flask_fundamentals/Dojo_Survey-validation/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"565647605","text":"# Project Euler Probrem 92\n# \"Pro92.py\" editted by Seki\n\ntotal = 0\ntotal2 = 0\nlist =[]\n\ndef chain(n):\n\t while n != 1 and n != 89:\n\t \tstring = str(n)\n\t \tlist = []\n\t \tfor i in range(0, len(string)):\n\t \t\t num = str(int(string[i])**2)\n\t \t\t list.append(num)\n\t \t\t n = 0\n\t \t\t for k in range(0, len(list)):\n\t \t\t \t n = n + int(list[k])\n\t if n == 1:\n\t \t return True\n\t elif n == 89:\n\t \t return False\n\t \t \nfor i in range(1, 10000000):\n\t val = chain(i)\n\t if val == True:\n\t \t total = total + 1\n\t \t print(1) \n\t if val == False:\n\t \t total2 = total2 + 1 \n\t \t print(89)\n\nprint (total2)\n\t\t \t \n\t \t","sub_path":"Pro92.py","file_name":"Pro92.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"501640708","text":"# coding=UTF-8\n\"\"\" Class of the process with important data for calculation and scheduling for both methods: FIFO and RR \"\"\"\nclass Process:\n def __init__(self, name, arrivalTime, cpuTime):\n self.arrivalTime = arrivalTime\n self.cpuTime = cpuTime\n self.name = name\n self.waitTime = 0\n self.cpuTimeDone = 0\n self.lastTimeProcessed = 0\n\n def responseTime(self):\n return self.waitTime + self.cpuTime\n\n def waiting(self, time, wait=0):\n if wait != 0:\n self.waitTime = wait + self.lastTimeProcessed #time + wait - (time - self.lastTimeProcessed)\n else:\n self.waitTime = time - self.arrivalTime + wait\n\n return self.waitTime\n\n def toString(self):\n return self.name + ' | ' + str(self.arrivalTime) + ' | ' + str(self.cpuTime)\n\n\"\"\"\nOpen file and where is all process for scheduling. The file has three information:\nProcess name, arrival time and cpu time and the file had to follow that format:\n[process name]#[arrival time]#[cpu time]\nReturn the list of process already sorted by arrival time\n\"\"\"\ndef getFile():\n list = []\n with open('schedule', 'r') as file:\n pLine = ''\n for line in file:\n pLine = line.split('#')\n list.append(Process(pLine[0], int(pLine[1]), int(pLine[2])))\n # ordenando e mostrando lista\n list.sort(key=lambda p: p.arrivalTime)\n return list\n\n\"\"\"\nFirst in First out\nReturn Average response Time\n\"\"\"\ndef FIFO():\n list = getFile()\n i, time, cpuTimeDone, tm, w = 0, 0, 0, 0, 0\n while i < len(list):\n # print(\"\\n\", list[i].toString())\n # print(\"wait time: \", list[i].waiting(time))\n list[i].waiting(time)\n while cpuTimeDone < list[i].cpuTime:\n time += 1\n cpuTimeDone += 1\n cpuTimeDone = 0\n # print(\"response time: \", list[i].responseTime())\n list[i].responseTime()\n w += list[i].waitTime\n tm += list[i].responseTime()\n i += 1\n print(\"\\nFirst in First out\")\n print(\"Total time: \", time)\n print(\"Average wait time\", w/len(list))\n print(\"Average response time\", tm/len(list))\n return w/len(list), tm/len(list)\n\n\"\"\"\nRound Robin with time preemption\n\nReturn wait time and Average response Time\n\"\"\"\ndef RR(t=4):\n list = getFile()\n step, time, i, tm, tam, w = 1, 0, 0, 0, len(list), 0\n while len(list) != 0:\n # print(\"\\n\", list[i].toString())\n # print(\"previous waiting: \", list[i].waitTime, \", time waiting: \", time)\n list[i].waiting(time, list[i].waitTime)\n # print(\"wait time: \", list[i].waiting(time, list[i].waitTime))\n if list[i].arrivalTime <= time:\n while step <= t:\n # print(\"process \", list[i].name, \" time \", time, \" step \", step)\n step += 1\n time += 1\n list[i].cpuTimeDone += 1\n if list[i].cpuTimeDone == list[i].cpuTime:\n # print(\"removed process\", list[i].name)\n # print(\"response time: \", list[i].responseTime())\n list[i].responseTime()\n w += list[i].waitTime\n tm += list[i].responseTime()\n list.remove(list[i])\n i -= 1\n break\n step = 1\n else: i += 1\n # print(i, \" >= \", len(list)-1, \" len \", len(list))\n if i >= len(list) - 1: i = 0\n else: i += 1\n print(\"\\nRound Robin Preemption: \", t)\n print(\"Total time: \", time)\n print(\"Average wait time\", w/tam)\n print(\"Average response time\", tm/tam)\n return w/tam, tm/tam\n\nf = FIFO()\nr = RR(4)\n","sub_path":"scheduling.py","file_name":"scheduling.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"612936370","text":"from mininet.net import Mininet\nfrom mininet.log import output\nfrom mininet.cli import CLI\nfrom mininet.link import TCIntf\nimport json\nimport copy\nimport pdb\n\ndef is_switch(str):\n return str[0] == 's'\n\ndef is_host(str):\n return str[0] == 'h'\n\nif __name__ == \"__main__\":\n net = Mininet()\n\n hosts = dict()\n # switches = dict()\n\n fin = open(\"topology.json\", \"r\")\n topology = json.load(fin)\n\n for i, host_name in enumerate(sorted(topology[\"hosts\"].keys())):\n \n net.addHost(host_name, ip=None)\n hosts[host_name] = [net.hosts[i], 0]\n \n # for switch_name in sorted(topology[\"switches\"].keys()):\n # cur_ip[2] += 1\n # if cur_ip[2] == 256:\n # cur_ip[1] += 1\n # cur_ip[2] = 0\n \n # ip_str = \"{}.{}.{}.{}\".format(cur_ip[0], cur_ip[1], cur_ip[2], cur_ip[3])\n # switches[switch_name] = (self.addSwitch(switch_name, ip=ip_str), ip_str)\n \n fout = open(\"topology.txt\", \"w\")\n i = 0\n cur_ip = [10, 0, 0, 0]\n\n links = []\n \n for link in topology[\"links\"]:\n i += 1\n cur_ip[2] += 1\n if cur_ip[2] == 256:\n cur_ip[1] += 1\n cur_ip[2] = 0\n \n node_name1 = link[0]\n node_name2 = link[1]\n\n bw = link[2][\"bw\"]\n delay = link[2][\"delay\"]\n loss = link[2][\"loss\"]\n queue_len = link[2][\"queue_length\"]\n\n node_item1 = hosts[node_name1]\n node_item2 = hosts[node_name2]\n\n cur_ip_str1 = \"{}.{}.{}.2\".format(cur_ip[0], cur_ip[1], cur_ip[2])\n cur_ip_str2 = \"{}.{}.{}.1\".format(cur_ip[0], cur_ip[1], cur_ip[2])\n\n #fout.write(\"{} {} {} {}\\n\".format(node_name1, cur_ip_str1, node_name2, cur_ip_str2))\n \n\n intf1 = \"{}-eth{}\".format(node_item1[0].name, node_item1[1])\n intf2 = \"{}-eth{}\".format(node_item2[0].name, node_item2[1])\n links.append([node_name1, cur_ip_str1, node_name2, cur_ip_str2, intf1, intf2])\n\n net.addLink(node_item1[0], node_item2[0], intfName1=intf1, intfName2=intf2, intf=TCIntf, bw=bw, delay=delay, loss=loss, max_queue_size=queue_len)\n \n\n node_item1[0].intf(intf1).setIP(cur_ip_str1, 24)\n node_item2[0].intf(intf2).setIP(cur_ip_str2, 24)\n\n node_item1[1] += 1\n node_item2[1] += 1\n\n for i, link in enumerate(net.links):\n fout.write(\"{} {} {} {} {} {} {} {}\\n\".format(links[i][0], links[i][1], links[i][4], link.intf1.mac, links[i][2], links[i][3], links[i][5], link.intf2.mac))\n fout.close()\n \n fin.close()\n\n net.start()\n client = CLI(net)\n client.run()\n #net.stop()\n \n \n","sub_path":"src_CPU/topo/launch_mininet.py","file_name":"launch_mininet.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"57401470","text":"import os\nimport sys\nDIRNAME = os.path.dirname(__file__)\nsys.path.append(os.path.join(DIRNAME, '..'))\n\nfrom src.constrainedChasingEscapingEnv.envMujoco import Transition3Objects\nfrom src.neuralNetwork.policyValueNet import GenerateModel, restoreVariables, ApproximateActionPrior\nfrom src.constrainedChasingEscapingEnv.envMujoco import ResetUniform\nfrom src.episode import Sample3ObjectsTrajectory, chooseGreedyAction\nfrom exec.trajectoriesSaveLoad import saveToPickle\nfrom src.inferChasing.continuousPolicy import RandomPolicy\n\n\nimport pandas as pd\nimport mujoco_py as mujoco\npd.set_option('display.max_rows', None)\npd.set_option('display.max_columns', None)\n\ndef main():\n dirName = os.path.dirname(__file__)\n physicsDynamicsPath = os.path.join(dirName, '..', 'env', 'xmls', 'threeAgents.xml')\n agentsBodyMassIndex = [6, 7, 8]\n physicsSmallMassModel = mujoco.load_model_from_path(physicsDynamicsPath)\n physicsSmallMassModel.body_mass[agentsBodyMassIndex] = [4, 5, 4]\n physicsLargeMassModel = mujoco.load_model_from_path(physicsDynamicsPath)\n physicsLargeMassModel.body_mass[agentsBodyMassIndex] = [8, 10, 8]\n\n physicsSmallMassSimulation = mujoco.MjSim(physicsSmallMassModel)\n physicsLargeMassSimulation = mujoco.MjSim(physicsLargeMassModel)\n # set_constants fit for mujoco_py version >= 2.0, no fit for 1.50\n physicsSmallMassSimulation.set_constants()\n physicsLargeMassSimulation.set_constants()\n\n numSimulationFrames = 20\n transitSmallMassAgents = Transition3Objects(physicsSmallMassSimulation, numSimulationFrames)\n transitLargeMassAgents = Transition3Objects(physicsLargeMassSimulation, numSimulationFrames)\n\n transit = transitSmallMassAgents\n\n\n qPosInit = (0, 0, 0, 0, 0, 0) # (initial position of sheep, initial position of wolf)\n qVelInit = (0, 0, 0, 0, 0, 0) # (initial velocity of sheep, initial velocity of wolf)\n qPosInitNoise = 9.7 # adds some randomness to the initial positions\n qVelInitNoise = 5 # adds some randomness to the initial velocities\n numAgent = 3\n reset = ResetUniform(physicsSmallMassSimulation, qPosInit, qVelInit, numAgent, qPosInitNoise, qVelInitNoise)\n\n # sample trajectory\n maxRunningSteps = 20 # max possible length of the trajectory/episode\n sampleTrajectory = Sample3ObjectsTrajectory(maxRunningSteps, transit, reset, chooseGreedyAction)\n\n # Neural Network\n actionSpace = [(10, 0), (7, 7), (0, 10), (-7, 7), (-10, 0), (-7, -7), (0, -10), (7, -7)]\n numActionSpace = len(actionSpace)\n numStateSpace = 12\n regularizationFactor = 1e-4\n sharedWidths = [128]\n actionLayerWidths = [128]\n valueLayerWidths = [128]\n generateModel = GenerateModel(numStateSpace, numActionSpace, regularizationFactor)\n\n # wolf NN Policy\n wolfModelPath = os.path.join(dirName, '..','NNModels','wolfNNModels', 'killzoneRadius=0.5_maxRunningSteps=10_numSimulations=100_qPosInitNoise=9.7_qVelInitNoise=5_rolloutHeuristicWeight=0.1_trainSteps=99999')\n wolfNNModel = generateModel(sharedWidths, actionLayerWidths, valueLayerWidths)\n restoreVariables(wolfNNModel, wolfModelPath)\n wolfPolicy = ApproximateActionPrior(wolfNNModel, actionSpace) # input state, return action distribution\n\n # sheep NN Policy\n sheepModelPath = os.path.join(dirName, '..','NNModels','sheepNNModels', 'killzoneRadius=2_maxRunningSteps=25_numSimulations=100_qPosInitNoise=9.7_qVelInitNoise=8_rolloutHeuristicWeight=0.1_trainSteps=99999')\n sheepNNModel = generateModel(sharedWidths, actionLayerWidths, valueLayerWidths)\n restoreVariables(sheepNNModel, sheepModelPath)\n sheepPolicy = ApproximateActionPrior(sheepNNModel, actionSpace) # input sheepstate, return action distribution\n\n randomPolicy = RandomPolicy(actionSpace)\n\n policy = lambda state: [sheepPolicy(state[:2]), wolfPolicy(state[:2]), randomPolicy(state)]\n\n trajectory = sampleTrajectory(policy)\n dataIndex = 15\n dataPath = os.path.join(dirName, '..', 'trainedData', 'trajectory'+ str(dataIndex) + '.pickle')\n saveToPickle(trajectory, dataPath)\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"exec/sample3ObjectsTraj.py","file_name":"sample3ObjectsTraj.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"261172142","text":"import os\nfrom flask import url_for\nfrom database import db\nfrom src.config import Config\n\n\nclass Photo(db.Model):\n \"\"\" фото услуг мастера \"\"\"\n __tablename__ = 'photo' # название таблицы в БД\n id = db.Column(db.Integer, primary_key=True) # id фото в БД\n master_id = db.Column(db.Integer, db.ForeignKey('master.id')) # id мастера, загрузившего фото\n path = db.Column(db.String(50)) # путь к фото (название и формат файла в папке фотографий мастера)\n\n def get_photo_url(self):\n \"\"\" возвращает URL фото\n\n Returns:\n string: URL фото\n \"\"\"\n return url_for('profile.photo', id=self.id)\n\n def get_photos_folder_path(self):\n \"\"\" возвращает путь к папке с фото\n\n Returns:\n string: путь к папке с фото\n \"\"\"\n return os.path.join(Config.UPLOAD_FOLDER, str(self.master_id))\n\n def get_photo_path(self):\n \"\"\" возвращает путь к фото\n\n Returns:\n string: путь к фото\n \"\"\"\n folder = self.get_photos_folder_path()\n return os.path.join(folder, self.path)\n","sub_path":"Project/src/models/photo.py","file_name":"photo.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"458998696","text":"import os\nimport multiprocessing\n\nBASE_PATH = '/home/lils/'\n\n\ndef path_to(*to):\n return os.path.join(BASE_PATH, *to)\n\n\nbind = 'unix:' + path_to('tmp', 'gunicorn.sock')\n\npidfile = path_to('tmp', 'gunicorn.pid')\nworkers = multiprocessing.cpu_count() * 2 + 1\n\ntimeout = 6000\n\naccesslog = path_to('logs', 'gunicorn.access.log')\nerrorlog = path_to('logs', 'gunicorn.error.log')\nloglevel = 'info'\n","sub_path":"gunicorn.conf.py","file_name":"gunicorn.conf.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"578742461","text":"from song import Song\nfrom click import Click\nfrom beatType import BeatType\n\nimport os.path\n\n# calculates the score\nclass Score:\n # Constructor\n def __init__(self, click, song):\n self.click = click\n self.song = song\n self.score = 0\n self.beatList = self.song.ts.beatList\n self.startTime = 0\n print(self.startTime)\n self.toleranceTime = 7.5/(self.song.ts.bpm)*1000\n \n # start the score count \n def startScore(self, startTime):\n self.startTime = startTime\n \n # updates the score if a hit on a pad accurs\n def updateScore(self, currentTime, multiplier):\n self.getBeats()\n hitTime = currentTime - self.startTime\n # hit after the beat\n # plus points\n if(hitTime >= self.lastBeat.getBeatTime() - self.toleranceTime/2 and hitTime <= self.lastBeat.getBeatTime() + self.toleranceTime/2):\n value = ((1-(abs(hitTime - self.lastBeat.getBeatTime())/(self.toleranceTime/2)))*100)\n if(self.lastBeat.getBeatType == BeatType.QUARTER):\n value *= 4\n elif(self.lastBeat.getBeatType == BeatType.EIGTH):\n value *= 2\n self.score += value * multiplier\n print('<+<', ' ', self.score)\n # hit in between beats\n # minus points\n if(hitTime >= self.lastBeat.getBeatTime() + self.toleranceTime/2 and hitTime <= self.nextBeat.getBeatTime() - self.toleranceTime/2):\n self.score -= ((1-(abs(hitTime - (self.lastBeat.getBeatTime() + self.toleranceTime))/(self.toleranceTime/2)))*50)\n print('>-<', ' ', self.score)\n # hit before beat\n # plus points\n if(hitTime >= self.nextBeat.getBeatTime() - self.toleranceTime/2 and hitTime <= self.nextBeat.getBeatTime() + self.toleranceTime/2):\n value = ((1-(abs(hitTime - self.nextBeat.getBeatTime())/(self.toleranceTime/2)))*100)\n if(self.nextBeat.getBeatType == BeatType.QUARTER):\n value *= 4\n elif(self.nextBeat.getBeatType == BeatType.EIGTH):\n value *= 2\n self.score += value * multiplier\n print('>+>', ' ', self.score)\n \n # writes score to the score.txt file\n scoreFile = open(\"score.txt\", \"w\")\n scoreFile.write(str(round(self.score)))\n scoreFile.close()\n \n # grads the last and next beat from Click \n def getBeats(self):\n self.lastBeat = self.click.lastBeat\n self.nextBeat = self.click.nextBeat\n \n # returns current score\n def getScore(self):\n return round(self.score)\n \n # returns final score and writes score\n # to the score.txt file\n def getFinalScore(self):\n finalScore = round(self.score)\n print('Final Score:', finalScore)\n \n scoreFile = open(\"score.txt\", \"w\")\n scoreFile.write(str(round(self.score)))\n scoreFile.close()\n \n \n return finalScore\n \n \n","sub_path":"score.py","file_name":"score.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"316938817","text":"import os\nimport codecs\nfrom collections import Counter\n\n\ndictsWithEnglish = [\n 'md', 'wil', 'yat', 'gst', 'ben', 'mw72', 'ap90', 'cae',\n 'mw', 'shs', 'mwe', 'bor', 'ae', 'inm', 'vei', 'pui', 'bhs', 'acc', 'ieg',\n 'snp', 'pe', 'pgn', 'mci'\n]\n\n\ndef find_known_words(code, threshold=1):\n filein = os.path.join('output', code + '_error.txt')\n fileout = os.path.join('knownwords', code + '_knownwords.txt')\n words = []\n fin = codecs.open(filein, 'r', 'utf-8')\n fout = codecs.open(fileout, 'w', 'utf-8')\n for line in fin:\n line = line.rstrip()\n splits = line.split(':')\n errorwords = splits[2]\n words += errorwords.split(',')\n cnt = Counter(words)\n result = []\n for (a, b) in cnt.most_common():\n if b > threshold:\n print(a, '\\t', b)\n result.append(a)\n result = sorted(result)\n fout.write('\\n'.join(result))\n fin.close()\n fout.close()\n\n\nif __name__ == \"__main__\":\n for code in dictsWithEnglish:\n print(code)\n find_known_words(code, 1)\n","sub_path":"english_error/known_word_extractor.py","file_name":"known_word_extractor.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"584175124","text":"# https://www.careercup.com/question?id=6303093824159744\r\n\r\ndef solution(weights, boat_capacity=150):\r\n weights.sort()\r\n if not weights:\r\n return 0\r\n elif weights[-1] > boat_capacity:\r\n raise Exception()\r\n i = 0\r\n j = len(weights) - 1\r\n count = 0\r\n while i <= j:\r\n if weights[i] + weights[j] <= boat_capacity:\r\n i += 1\r\n j -= 1\r\n count += 1\r\n return count\r\n","sub_path":"max_boats.py","file_name":"max_boats.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"394171116","text":"# -*- coding: utf-8 -*-\nimport os\nimport glob\nimport numpy as np\nfrom xml.etree.ElementTree import parse\nimport json\nfrom utils.util import ensure_dir\nfrom pathlib import Path\n\ndef get_filelists(path, prefix, suffix):\n return glob.glob(os.path.join(path, '{}.{}'.format(prefix, suffix)))\n\ndef save_ecp_json(det_list, dest_folder, img_path, id_to_class):\n '''\n det_list: [boxes, labels, scores, var]\n '''\n objects = []\n img_name = Path(img_path).stem\n for index, bbox in enumerate(det_list[0]):\n covs = det_list[3][index]\n obj_class = id_to_class[int(det_list[1][index])]\n if obj_class == 'pedestrian':\n obj_class = 'person'\n obj = {'identity': obj_class,\n 'x0': float(bbox[0]),\n 'y0': float(bbox[1]),\n 'x1': float(bbox[2]),\n 'y1': float(bbox[3]),\n 'sigma_xmin': float(covs[0]),\n 'sigma_ymin': float(covs[1]),\n 'sigma_xmax': float(covs[2]),\n 'sigma_ymax': float(covs[3]),\n 'orient': 0.0,\n 'score': float(det_list[2][index])\n }\n objects.append(obj)\n\n frame = {'identity': 'frame'}\n frame['children'] = objects\n ensure_dir(dest_folder)\n json.dump(frame, open(os.path.join(dest_folder, img_name + '.json'), 'w'), indent=1)\n\n\nclass PascalVocXmlParser(object):\n \"\"\"Parse annotation for 1-annotation file \"\"\"\n\n def __init__(self, annfile, labels):\n self.annfile = annfile\n self.root = self._root_tag(self.annfile)\n self.tree = self._tree(self.annfile)\n self.labels = labels\n\n def parse(self, filterdiff=True):\n fname = self.get_fname()\n labels, diffcults = self.get_labels()\n boxes = self.get_boxes()\n if filterdiff:\n indices = np.where(np.array(diffcults) == 0)\n boxes = boxes[indices]\n labels=labels[indices]\n return fname, np.array(boxes), labels\n else:\n return fname,boxes,labels,diffcults\n\n def get_fname(self):\n return os.path.join(self.root.find(\"filename\").text)\n\n def get_width(self):\n for elem in self.tree.iter():\n if 'width' in elem.tag:\n return int(elem.text)\n\n def get_height(self):\n for elem in self.tree.iter():\n if 'height' in elem.tag:\n return int(elem.text)\n\n def get_labels(self):\n labels = []\n difficult = []\n obj_tags = self.root.findall(\"object\")\n for t in obj_tags:\n labels.append(self.labels.index(t.find(\"name\").text))\n difficult.append(int(t.find(\"difficult\").text))\n return np.array(labels), np.array(difficult)\n\n def get_boxes(self):\n bbs = []\n obj_tags = self.root.findall(\"object\")\n for t in obj_tags:\n box_tag = t.find(\"bndbox\")\n x1 = box_tag.find(\"xmin\").text\n y1 = box_tag.find(\"ymin\").text\n x2 = box_tag.find(\"xmax\").text\n y2 = box_tag.find(\"ymax\").text\n box = np.array([(float(x1)), (float(y1)), (float(x2)), (float(y2))])\n bbs.append(box)\n bbs = np.array(bbs)\n return bbs\n\n def _root_tag(self, fname):\n tree = parse(fname)\n root = tree.getroot()\n return root\n\n def _tree(self, fname):\n tree = parse(fname)\n return tree\n","sub_path":"utils/dataset_util.py","file_name":"dataset_util.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"335639961","text":"#coding=utf-8\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nimport time\nimport xlrd\nimport xlwt\nimport pymysql\n# from openpyxl.workbook import Workbook\n# from openpyxl.writer.excel import ExcelWriter\n\n# 打开网页\nbrowser = webdriver.Chrome('E:\\chromedriver_win32\\chromedriver.exe')\nbrowser.get('http://www.1234i.com/p.php')\n\n# 创建数据库连接\nconn = pymysql.connect(\n host='192.168.223.10',\n port=3306,\n user='root',\n passwd='TomLee4!',\n db='big_data',\n charset='utf8'\n )\nsql = \"INSERT INTO phone_detail VALUES (NULL , '%s', '%s', '%s')\"\n\n# 读取excel文件,获取手机号码\ndata = xlrd.open_workbook('E:\\phone\\phone1.xls')\n# 打开第一张表\ntable = data.sheets()[0]\n# 获取表的行数\nnrows = table.nrows\n# 循环逐行打印\nfor i in range(nrows):\n # 获取输入手机号码的位置\n text = browser.find_element_by_xpath(\"/html/body/center/center/form/textarea\")\n text.send_keys(table.col_values(0)[i+1]+ \"\\n\")\n if nrows == i + 2 or (i+1) % 100 == 0 :\n button = browser.find_element_by_xpath(\"/html/body/center/center/form/input\")\n button.click()\n workbook = xlwt.Workbook(encoding='ascii')\n worksheet = workbook.add_sheet('phone')\n for j in range(100) :\n # 获取手机号码元素,归属地元素并进行异常处理\n try:\n phone = browser.find_element_by_xpath(\"/html/body/center/p/u\"+ \"[\" + str(j + 1) + \"]\")\n except NoSuchElementException as msg:\n phone = browser.find_element_by_xpath(\"/html/body/center/p/u\" + \"[\" + str(1) + \"]\")\n\n try:\n address = browser.find_element_by_xpath(\"/html/body/center/p/font\"+ \"[\" + str(j + 1) + \"]\")\n except NoSuchElementException as msg:\n address = browser.find_element_by_xpath(\"/html/body/center/p/font\" + \"[\" + str(1) + \"]\")\n\n # 测试数据库连接\n cur = conn.cursor()\n data = (phone.text, address.text, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n cur.execute(sql % data)\n cur.close()\n conn.commit()\n\n # 筛选广州的号码,并存入excel文件\n # if(address.text.find(\"广州\") != -1):\n # print( phone.text, ' ' ,address.text);\n # # row0 = [u'手机号码', u'归属地']\n # worksheet.write(j, 0, phone.text)\n # worksheet.write(j, 1, address.text)\n # workbook.save(\"E:\\phone\\phone\" + str(i) + \".xls\")\n\n# 关闭数据库连接\nconn.close()","sub_path":"PhoneFilter.py","file_name":"PhoneFilter.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"508351781","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport threading\nfrom multiprocessing import Process\n\nimport cchardet\nimport time\nfrom functools import wraps\n\n\ndef timeit(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print('used:', end - start)\n return result\n\n return wrapper\n\n\n@timeit\ndef get_encoding(file):\n with open(file, 'rb')as f:\n data = f.read()\n encode = cchardet.detect(data)['encoding']\n return encode\n\n\n@timeit\ndef get_files(file_path):\n for root, dirs, files in os.walk(file_path):\n for file in files:\n full_path = os.path.join(root, file)\n encode = get_encoding(full_path)\n print(file, \"-->\", encode)\n\n\n@timeit\ndef foo():\n for i in range(10000):\n pass\n\n\ndef func(x):\n print(x)\n\n\n\n\nif __name__ == '__main__':\n get_files(\".\")\n foo()\n # t = threading.Thread(target=func, args=(12,))\n # # 线程启动\n # t.start()\n # # 主进程阻塞,等待子进程的退出\n # t.join()\n # 设置线程为主线程的守护线程\n p = Process(target=func, args=(12,))\n p.daemon = True\n\n p.start() # 启动子进程实例(创建子进程)\n p.is_alive() # 判断进程子进程是否还在活着\n\n p.join() # 是否等待子进程执行结束,或者等待多少秒\n p.terminate() # 不管任务是否完成,立即终止子进程\n # p.daemon = True # 设置守护进程","sub_path":"test/yest2.py","file_name":"yest2.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"332216236","text":"from django.forms import ModelForm\n\nfrom core.forms.admin import EmployeeCreateForm\nfrom django import forms\n\nfrom core.models import Branch, ATM, Maintainer\n\nEMPLOYEE_TYPES = (\n ('Cashier', 'صندوق دار'),\n ('Jursit', 'کارشناس حقوقی'),\n ('Auditor', 'حسابرس'),\n ('Maintainer', 'مسئول دستگاه خودپرداز'),\n)\n\n\nclass BranchEmployeeCreateForm(EmployeeCreateForm):\n type = forms.ChoiceField(choices=EMPLOYEE_TYPES, label='سمت')\n\n def __init__(self, data=None, *args, **kwargs):\n super(BranchEmployeeCreateForm, self).__init__(data, *args, **kwargs)\n self.user = kwargs.get('user')\n branch = self.user.manager.branch\n self.fields['branch'].initial = branch\n self.fields['branch'].queryset = Branch.objects.filter(id=branch.id)\n\n\nclass ATMCreateForm(ModelForm):\n button_text = \"ایجاد دستگاه\"\n\n def __init__(self, data=None, *args, **kwargs):\n super(ATMCreateForm, self).__init__(data)\n self.user = kwargs.get('user')\n branch = self.user.manager.branch\n self.fields['maintainer'].queryset = Maintainer.objects.filter(branch=branch)\n\n class Meta:\n model = ATM\n fields = ['serial', 'maintainer']\n labels = {\n 'serial': \"شماره سریال دستگاه\",\n 'maintainer': 'مسئول دستگاه'\n }\n\n def clean(self):\n cleaned_data = super(ATMCreateForm, self).clean()\n # validate form data here!\n return cleaned_data\n\n def save(self, commit=True):\n atm = ATM(branch=self.user.manager.branch, **self.cleaned_data)\n atm.save()\n return atm\n\n\nclass SetMaintainerForATMForm(forms.Form):\n button_text = \"انتخاب مسئول\"\n\n atm = forms.ModelChoiceField(None, label='دستگاه')\n maintainer = forms.ModelChoiceField(None, label='مسئول دستگاه خودپرداز')\n\n def __init__(self, data=None, *args, **kwargs):\n super(SetMaintainerForATMForm, self).__init__(data)\n user = kwargs.get('user')\n branch = user.manager.branch\n print(branch)\n self.fields['maintainer'].queryset = Maintainer.objects.filter(branch=branch)\n self.fields['atm'].queryset = ATM.objects.filter(branch=branch)\n\n def save(self):\n atm = self.cleaned_data.get('atm', None)\n maintainer = self.cleaned_data.get('maintainer', None)\n\n print(atm)\n print(maintainer)\n\n atm.maintainer = maintainer\n atm.save()\n\n return atm","sub_path":"core/forms/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"203720000","text":"from .layers import *\nfrom .fast_layers import *\n\n\ndef affine_relu_forward(x, w, b):\n \"\"\"Convenience layer that performs an affine transform followed by a ReLU.\n\n Inputs:\n - x: Input to the affine layer\n - w, b: Weights for the affine layer\n\n Returns a tuple of:\n - out: Output from the ReLU\n - cache: Object to give to the backward pass\n \"\"\"\n a, fc_cache = affine_forward(x, w, b)\n out, relu_cache = relu_forward(a)\n cache = (fc_cache, relu_cache)\n return out, cache\n\ndef affine_relu_backward(dout, cache):\n \"\"\"Backward pass for the affine-relu convenience layer.\n \"\"\"\n fc_cache, relu_cache = cache\n da = relu_backward(dout, relu_cache)\n dx, dw, db = affine_backward(da, fc_cache)\n return dx, dw, db\n\n# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n# def affine_norm_relu_forward(x, w, b, gamma, beta, normalization, bn_param):\n# #first affine forward which returns out and cache=(x,w,b)\n# affine_out, affine_cache = affine_forward(x, w, b)\n\n# # passing the affine_out to batch norm which returns out and cache with\n# # (x, mu, xmu, sq, var, sqrtvar, ivar, xhat, eps, gamma) these values\n# bn_out, bn_cache = batchnorm_forward(affine_out, gamma, beta, bn_param)\n\n# #finally we pass it through relu which returns out and cache = x (bn_out)\n# out, relu_cache = relu_forward(bn_out)\n# return out, (affine_cache, bn_cache, relu_cache)\n\n# def affine_norm_relu_backward(dout, cache, normalization):\n# affine_cache, bn_cache, relu_cache = cache\n# #backward pass to relu layer\n# relu_dout = relu_backward(dout, relu_cache)\n\n# #backward pass to batch norm (using alternate method)\n# bn_dout, dgamma, dbeta = batchnorm_backward_alt(relu_dout, bn_cache)\n \n# #backward pass to affine layer\n# dx, dw,db = affine_backward(bn_dout, affine_cache)\n# return dx, dw, db, dgamma, dbeta\npass \n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\ndef conv_relu_forward(x, w, b, conv_param):\n \"\"\"A convenience layer that performs a convolution followed by a ReLU.\n\n Inputs:\n - x: Input to the convolutional layer\n - w, b, conv_param: Weights and parameters for the convolutional layer\n\n Returns a tuple of:\n - out: Output from the ReLU\n - cache: Object to give to the backward pass\n \"\"\"\n a, conv_cache = conv_forward_fast(x, w, b, conv_param)\n out, relu_cache = relu_forward(a)\n cache = (conv_cache, relu_cache)\n return out, cache\n\n\ndef conv_relu_backward(dout, cache):\n \"\"\"Backward pass for the conv-relu convenience layer.\n \"\"\"\n conv_cache, relu_cache = cache\n da = relu_backward(dout, relu_cache)\n dx, dw, db = conv_backward_fast(da, conv_cache)\n return dx, dw, db\n\n\ndef conv_bn_relu_forward(x, w, b, gamma, beta, conv_param, bn_param):\n \"\"\"Convenience layer that performs a convolution, a batch normalization, and a ReLU.\n\n Inputs:\n - x: Input to the convolutional layer\n - w, b, conv_param: Weights and parameters for the convolutional layer\n - pool_param: Parameters for the pooling layer\n - gamma, beta: Arrays of shape (D2,) and (D2,) giving scale and shift\n parameters for batch normalization.\n - bn_param: Dictionary of parameters for batch normalization.\n\n Returns a tuple of:\n - out: Output from the pooling layer\n - cache: Object to give to the backward pass\n \"\"\"\n a, conv_cache = conv_forward_fast(x, w, b, conv_param)\n an, bn_cache = spatial_batchnorm_forward(a, gamma, beta, bn_param)\n out, relu_cache = relu_forward(an)\n cache = (conv_cache, bn_cache, relu_cache)\n return out, cache\n\n\ndef conv_bn_relu_backward(dout, cache):\n \"\"\"Backward pass for the conv-bn-relu convenience layer.\n \"\"\"\n conv_cache, bn_cache, relu_cache = cache\n dan = relu_backward(dout, relu_cache)\n da, dgamma, dbeta = spatial_batchnorm_backward(dan, bn_cache)\n dx, dw, db = conv_backward_fast(da, conv_cache)\n return dx, dw, db, dgamma, dbeta\n\n\ndef conv_relu_pool_forward(x, w, b, conv_param, pool_param):\n \"\"\"Convenience layer that performs a convolution, a ReLU, and a pool.\n\n Inputs:\n - x: Input to the convolutional layer\n - w, b, conv_param: Weights and parameters for the convolutional layer\n - pool_param: Parameters for the pooling layer\n\n Returns a tuple of:\n - out: Output from the pooling layer\n - cache: Object to give to the backward pass\n \"\"\"\n a, conv_cache = conv_forward_fast(x, w, b, conv_param)\n s, relu_cache = relu_forward(a)\n out, pool_cache = max_pool_forward_fast(s, pool_param)\n cache = (conv_cache, relu_cache, pool_cache)\n return out, cache\n\n\ndef conv_relu_pool_backward(dout, cache):\n \"\"\"Backward pass for the conv-relu-pool convenience layer.\n \"\"\"\n conv_cache, relu_cache, pool_cache = cache\n ds = max_pool_backward_fast(dout, pool_cache)\n da = relu_backward(ds, relu_cache)\n dx, dw, db = conv_backward_fast(da, conv_cache)\n return dx, dw, db\n","sub_path":"assignment2/cs231n/layer_utils.py","file_name":"layer_utils.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"87192135","text":"import yfinance as yf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsymbol = 'IBM'\nstockData = yf.Ticker(symbol)\n\n# Get stock info\ndata = stockData.history(period=\"5y\")\n\n# Get close price\nclose = data['Close'].to_numpy()\n\ndef moving_average(a, n=3):\n ret = np.cumsum(a, dtype=float)\n ret[n:] = ret[n:] - ret[:-n]\n return ret[n - 1:] / n\n\navg = moving_average(close, 10)\n\nplt.plot(avg)\nplt.show()","sub_path":"get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"259922545","text":"from collections import deque\n\n\ndirection_dict = {\n 0: [0, 1], # 오른쪽\n 1: [1, 0], # 아래\n 2: [0, -1], # 왼쪽\n 3: [-1, 0] # 위\n}\n\n\ndef index_checker(ix, thresh):\n if ix < 0:\n ix = thresh - 1\n elif ix == thresh:\n ix = 0\n\n return ix\n\n\ndef bfs(row, col, memory, direction):\n d = deque()\n d.append([row, col, memory, direction])\n visited = [[row, col, memory, direction]]\n i = 0\n while d:\n # print(d)\n popped = d.popleft()\n row, col, memory, direction = popped[0], popped[1], popped[2], popped[3]\n value = board[row][col]\n q_flag = False\n\n if value == '@':\n return True\n elif value == '>':\n direction = 0\n elif value == 'v':\n direction = 1\n elif value == '<':\n direction = 2\n elif value == '^':\n direction = 3\n elif value == '_':\n if memory == 0:\n direction = 0\n else:\n direction = 2\n elif value == '|':\n if memory == 0:\n direction = 1\n else:\n direction = 3\n elif value == '?':\n q_flag = True\n elif value == '+':\n if memory == 15:\n memory = 0\n else:\n memory += 1\n elif value == '-':\n if memory == 0:\n memory = 15\n else:\n memory -= 1\n elif value == '.':\n pass\n else:\n memory = int(value)\n\n if q_flag:\n for k in range(4):\n new_row = index_checker(row + direction_dict[k][0], r)\n new_col = index_checker(col + direction_dict[k][1], c)\n if [new_row, new_col, memory, k] not in visited:\n d.append([new_row, new_col, memory, k])\n visited.append([new_row, new_col, memory, k])\n else:\n row = index_checker(row + direction_dict[direction][0], r)\n col = index_checker(col + direction_dict[direction][1], c)\n if [row, col, memory, direction] not in visited:\n d.append([row, col, memory, direction])\n visited.append([row, col, memory, direction])\n i += 1\n if i == 1000:\n return False\n return False\n\n\ntries = int(input())\n\nfor t in range(1, tries + 1):\n r, c = map(int, input().split())\n\n board = []\n flag = False\n for _ in range(r):\n tmp_list = []\n for v in input():\n if v == '@':\n flag = True\n tmp_list.append(v)\n board.append(tmp_list)\n\n if not flag:\n print('#{} {}'.format(t, 'NO'))\n continue\n\n end_flag = bfs(0, 0, 0, 0)\n if end_flag:\n print('#{} {}'.format(t, 'YES'))\n else:\n print('#{} {}'.format(t, 'NO'))\n","sub_path":"study/1824_Hyukjin_program.py","file_name":"1824_Hyukjin_program.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"337960163","text":"import requests\nfrom reportlab.lib.pagesizes import A4, portrait\nfrom reportlab.pdfgen import canvas\n\nimport tempfile\n\nw, h = portrait(A4)\n\nurls = [\n 'http://192.168.2.188:8029/exported/img20170601_11392407.jpg',\n 'http://192.168.2.188:8029/exported/img20170601_11392592.jpg',\n]\n\nwith tempfile.NamedTemporaryFile(\n prefix='test-',\n suffix='.pdf',\n delete=False\n) as fp:\n print(fp.name)\n c = canvas.Canvas(fp.name, pagesize=portrait(A4))\n\n # for u in urls:\n for i, u in enumerate(urls):\n with tempfile.NamedTemporaryFile() as img:\n try:\n resp = requests.get(u)\n except Exception:\n pass\n else:\n img.write(resp.content)\n c.drawImage(img.name, 0, 0, w, h)\n # 新建页\n c.showPage()\n c.save()\n","sub_path":"backend/main/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"130016836","text":"#!/usr/bin/python\n# aw_character\n# ===================================================================\nimport readline\nimport json\nfrom aw_debug import logger\nfrom aw_tools import menu, dice\nfrom aw_names import namePick\n\nclass unit(object):\n def __init__(self, name='', classe=''):\n self.name=name\n self.classe=classe\n self.active=True\n return\n def found(self, s):\n return (self.active and (s.lower() in self.name.lower()))\n def display(self):\n if self.active: return self.name.ljust(10)+\" \"+self.classe.ljust(10)\n\nclass character(unit):\n def __init__(self, n, c, st=[0, 0, 0, 0, 0], sk=''):\n unit.__init__(self, n,c)\n self.level = 1\n self.hp = 11+st[0]\n self.countdown = {}\n self.stats = st # str(hard)0, int(sharp)1, chm(hot)2, dex(cool)3, psi(weird)4\n self.skill = sk\n return\n def display(self):\n r = unit.display(self)+'\\t'\n r+= '['+str(self.level)+']['+str(self.hp)+']'+'\\t'\n r+= 'stats:'+','.join(str(self.stats[i]) for i in range(len(self.stats))).ljust(10)+'\\t'\n r+= 'skill:'+self.skill\n return r\n\nclass player():\n def __init__(self):\n self.characters = []\n self.countdowns = {}\n return\n def starterPack(self, awcls):\n chList=[]\n for c in awcls:\n chList.append(c)\n for i, k in enumerate(chList):\n self.characters.append(character(namePick(), k, awcls[k]['stat'],awcls[k]['skill']))\n return\n def display(self):\n r=''\n for i in self.characters:\n r+=i.display()+'\\n'\n return r\n\ndef confuse(c):\n action='confusing'\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef doublestrike(c):\n action=('double striking')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef hack(c):\n action=('hacking')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef cure(c):\n action=('healing')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef charm(c):\n action=('charming')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef leader(c):\n action=('leading')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef diplomacy(c):\n action=('talking')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef rage(c):\n action=('berserking')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\ndef dominate(c):\n action=('dominating')\n print(c.name+' try '+action+'='+dice(0)[1])\n return\n\nfn_menu={\n'confuse':confuse,\n'doublestrike':doublestrike,\n'hack':hack,\n'cure':cure,\n'charm':charm,\n'leader':leader,\n'diplomacy':diplomacy,\n'rage':rage,\n'dominate':dominate\n}\n\ndef listingm(ul):\n for i in ul:\n fn_menu[i.skill](i)\n return\n\ndef main():\n try:\n with open('AW-db/aw_classes.json') as f:\n awcl=json.load(f)\n except IOError:\n print(IOError)\n m=[]\n p = player()\n p.starterPack(awcl)\n print(p.display())\n listingm(p.characters)\n for i in p.characters:\n m.append(i.name)\n r=menu(m)\n i=p.characters[r[0]]\n fn_menu[i.skill](i)\n return\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"aw_character.py","file_name":"aw_character.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"612658638","text":"from unittest import mock\n\nimport numpy as np\n\nimport curling.constants\nimport log_handler\nfrom curling import board as board_utils\nfrom curling import constants as c\nfrom curling import game\nfrom curling import utils\n\ninch = utils.dist(inches=1)\n\nlog_handler.flush_on_error()\n\n\nclass UnitTestException(Exception):\n \"\"\"For testing expected exceptions.\"\"\"\n\n\ndef test_board_is_2d():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n height, width = board.shape\n assert width == 16\n assert height == 6\n\n\ndef test_CanonicalBoard_unchanged():\n curl = game.CurlingGame()\n original = curl.getInitBoard()\n original[1][1] = 1\n\n canonical = curl.getCanonicalForm(original, 1)\n\n np.testing.assert_array_equal(canonical, original)\n\n\ndef test_CanonicalBoard_unchanged_symmetric():\n curl = game.CurlingGame()\n original = curl.getInitBoard()\n original[1][1] = 1\n\n canonical_once = curl.getCanonicalForm(original, -1)\n canonical_twice = curl.getCanonicalForm(canonical_once, -1)\n\n np.testing.assert_array_equal(canonical_twice, original)\n\n\ndef test_gameEnded_GameNotStarted():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n ended = curl.getGameEnded(board, 1)\n\n assert ended == 0\n\n\ndef test_gameEnded_NoStonesInPlay():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n ended = curl.getGameEnded(board, 1)\n\n assert ended == 0.00001 # Draw\n\n\ndef test_gameEnded_HammerWinsBy1():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.configure_hammer_1_scenario(board)\n\n ended = curl.getGameEnded(board, c.P2)\n\n assert ended == 1\n\n\ndef test_gameEnded_HammerWinsBy2():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.configure_hammer_2_scenario(board)\n\n ended = curl.getGameEnded(board, c.P2)\n\n assert ended == 2 # Win by 2 is good\n\n\ndef test_gameEnded_SlightlyOffCenter_y_1():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n # Team 2 is winning by 1\n board_utils.set_stone(board, c.P2, 7, x, y - 1 * inch)\n curl.sim.setupBoard(board)\n\n board = curl.sim.getBoard()\n ended = curl.getGameEnded(board, 1)\n\n assert ended == -1\n\n\ndef test_gameEnded_SlightlyOffCenter_y_2():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n # Team 2 is winning by 1\n board_utils.set_stone(board, c.P2, 7, x, y + 1 * inch)\n curl.sim.setupBoard(board)\n\n board = curl.sim.getBoard()\n ended = curl.getGameEnded(board, 1)\n\n assert ended == -1\n\n\ndef test_gameEnded_x_HammerCloser():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n\n board_utils.set_stone(board, c.P1, 7, x, y + 10 * inch)\n board_utils.set_stone(board, c.P2, 7, x, y - 1 * inch)\n curl.sim.setupBoard(board)\n\n board = curl.sim.getBoard()\n ended = curl.getGameEnded(board, c.P2)\n\n assert ended == 1\n\n\ndef test_gameEnded_y_HammerCloser():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n\n board_utils.set_stone(board, c.P1, 7, x, y - 10 * inch)\n board_utils.set_stone(board, c.P2, 7, x, y + 1 * inch)\n curl.sim.setupBoard(board)\n\n board = curl.sim.getBoard()\n ended = curl.getGameEnded(board, c.P2)\n\n assert ended == 1\n\n\ndef test_gameEnded_SlightlyOffCenter_x_1():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n # Team 2 is winning by 1\n board_utils.set_stone(board, c.P2, 7, x - 1 * inch, y)\n curl.sim.setupBoard(board)\n\n board = curl.sim.getBoard()\n ended = curl.getGameEnded(board, c.P2)\n\n assert ended == 1\n\n\ndef test_gameEnded_SlightlyOffCenter_x_2():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n\n x, y = curling.constants.BUTTON_POSITION\n # Team 2 is winning by 1\n board_utils.set_stone(board, c.P2, 7, x + 1 * inch, y)\n\n ended = curl.getGameEnded(board, 1)\n\n assert ended == -1\n\n\ndef test_gameEnded_NotEndOfGame():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n board_utils.set_stone(board, c.P2, 7, 0, 0, c.NOT_THROWN, c.IN_PLAY)\n\n ended = curl.getGameEnded(board, 1)\n\n assert ended == 0\n\n\ndef test_gameEnded_edgeCase():\n # Ensure the board is setup/reset before counting the stones\n # This edge case is when a game goes in \"reverse\" because of MCTS\n\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.scenario_all_out_of_play(board)\n board_utils.set_stone(board, c.P2, 7, 0, 0, c.NOT_THROWN, c.IN_PLAY)\n\n assert curl.getGameEnded(board, 1) == 0\n\n board_utils.set_stone(board, c.P2, 7, 0, 0, c.THROWN, c.OUT_OF_PLAY)\n\n assert curl.getGameEnded(board, 1) != 0\n\n\ndef test_display():\n curl = game.CurlingGame()\n curl.display(curl.getInitBoard())\n\n\n@mock.patch(\"curling.constants.ACTION_LIST\", c.SHORT_ACTION_LIST)\ndef test_get_valid_moves():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n valid = curl.getValidMoves(board, 1)\n\n assert sum(valid) < len(c.ACTION_LIST)\n assert sum(valid) == 2\n\n\ndef test_get_valid_moves_too_late():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n board_utils.scenario_all_out_of_play(board)\n\n try:\n curl.getValidMoves(board, 1)\n except game.GameException:\n pass\n else:\n raise Exception('getValidMoves should prohibit 16 stones.')\n\n\ndef test_string_repr_is_symmetric():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n curl.getNextState(board, c.P1, c.ACTION_LIST.index((1, '3', 5)))\n board_setup = curl.sim.getBoard()\n\n curl.boardFromString(curl.stringRepresentation(board))\n\n board_check = curl.sim.getBoard()\n\n np.testing.assert_array_equal(board_setup, board_check)\n\n\ndef test_getNextState_is_cached():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n curl.getNextState(board, c.P1, c.ACTION_LIST.index((1, '3', 5)))\n\n curl.sim.setupBoard = mock.Mock(side_effect=UnitTestException)\n curl.getNextState(board, c.P1, c.ACTION_LIST.index((1, '3', 5)))\n\n\ndef test_getNextState_cache_canonical():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n p1_board, p1_next_player = curl.getNextState(board, c.P1, c.ACTION_LIST.index((1, '3', 5)))\n\n curl.sim.setupBoard = mock.Mock(side_effect=UnitTestException)\n p2_board, p2_next_player = curl.getNextState(board, c.P2, c.ACTION_LIST.index((1, '3', 5)))\n\n assert p1_next_player == c.P2\n assert p2_next_player == c.P1\n\n with np.testing.assert_raises(AssertionError):\n np.testing.assert_array_equal(p1_board, p2_board)\n\n p1_board_canon = curl.getCanonicalForm(p1_board, c.P2)\n np.testing.assert_array_equal(p1_board_canon[2], p2_board[2])\n\n\ndef test_getSymmetries_flip():\n curl = game.CurlingGame()\n board = curl.getInitBoard()\n\n board_utils.configure_hammer_2_scenario(board)\n\n sym = curl.getSymmetries(board, 0)\n back = curl.getSymmetries(sym[-1][0], 0)\n\n np.testing.assert_array_equal(board, back[-1][0])\n\n\ndef test_getSymmetries_count():\n curl = game.CurlingGame()\n\n board = curl.getInitBoard()\n sym = curl.getSymmetries(board, 0)\n assert len(sym) == 2 # Regular and flip\n\n board_utils.configure_hammer_2_scenario(board)\n sym = curl.getSymmetries(board, 0)\n # 2 stones yield (14 - 1) permutations.\n assert len(sym) == 28 # (13 permutations + original) * 2 for flip\n\n# NOTE: Commented out because it's really slow.\n# @mock.patch(\"curling.constants.ACTION_LIST\", c.SHORT_ACTION_LIST)\n# def test_get_valid_moves_caches():\n# curl = game.CurlingGame()\n# board = curl.getInitBoard()\n#\n# with mock.patch.object(curl.sim, 'run', wraps=curl.sim.run) as spy:\n# curl.getValidMoves(board, 1)\n# assert spy.call_count == 4\n#\n# curl.getValidMoves(board, 1)\n# assert spy.call_count == 4 # Call count didn't increase!\n","sub_path":"curling/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":8415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"510248846","text":"from math import floor\n\n\ndef binary_search(alist, item):\n \"Using binary search algorithm to search a sorted list\"\n search_start = 0\n search_end = len(alist) - 1 \n if search_start > search_end:\n return False\n midpoint = floor((search_start + search_end) / 2)\n if alist[midpoint] < item:\n search_start = midpoint + 1\n elif alist[midpoint] > item:\n search_end = midpoint - 1\n if alist[midpoint] == item:\n return True","sub_path":"Python Refresh/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"480215724","text":"import logging\n\nfrom sovrin_client.test.training.getting_started_future import *\nfrom sovrin_client.test.training.log_messages import setup_message_logging, print_log_uid_database, \\\n add_pool_uids, add_agent_uids\n# noinspection PyUnresolvedReferences\nfrom sovrin_node.test.conftest import tconf\n\n\ndef getting_started(base_dir=None):\n\n ####################################\n # Setup\n ####################################\n\n if base_dir is None:\n base_dir = TemporaryDirectory().name\n logging.info(\"### Base directory is: {} ###\".format(base_dir))\n\n demo_setup_logging(base_dir)\n setup_message_logging(base_dir)\n\n logging.info(\"### Start creating pool and stewards ###\")\n pool, stewards = create_local_pool(base_dir)\n\n add_pool_uids(pool, stewards)\n\n logging.info(\"### Start creating and starting agents ###\")\n agents = demo_start_agents(pool, pool, base_dir)\n\n add_agent_uids(agents)\n\n\n # ###################################\n # Alice's Wallet\n # ###################################\n\n\n logging.info(\"### Start creating Alice client ###\")\n alice_client = pool.create_client(5403, \"Alice's client\")\n\n logging.info(\"### Start creating Alice wallet ###\")\n alice_wallet = Wallet(\"Alice's Wallet\")\n\n logging.info(\"### Start creating Alice agent ###\")\n alice_agent = WalletedAgent(name=\"Alice\",\n basedirpath=base_dir,\n client=alice_client,\n wallet=alice_wallet,\n port=8786)\n\n logging.info(\"### Start adding identifier for Alice agent ###\")\n alice_agent.new_identifier()\n\n pool.add(alice_agent)\n\n pool.runFor(1)\n\n add_agent_uids([alice_agent])\n\n ####################################\n # Faber Invitation\n ####################################\n\n print(FABER_INVITE)\n\n logging.info(\"### Alice loads Faber's invitation: ### {}\".format(FABER_INVITE))\n link_to_faber = alice_agent.load_invitation_str(FABER_INVITE)\n\n print(link_to_faber)\n\n logging.info(\"### Alice sync link with Faber ###\")\n alice_agent.sync(link_to_faber.name)\n\n demo_wait_for_sync(pool, link_to_faber)\n\n print(link_to_faber)\n\n logging.info(\"### Alice accepts Faber's invitation ###\")\n alice_agent.accept_invitation(link_to_faber)\n\n demo_wait_for_accept(pool, link_to_faber)\n\n print(link_to_faber)\n\n logging.info(\"### Alice pings Faber ###\")\n alice_agent.sendPing(\"Faber College\")\n\n demo_wait_for_ping(pool)\n\n ####################################\n # Transcription Claim\n ####################################\n\n demo_wait_for_claim_available(pool, link_to_faber, 'Transcript')\n claim_to_request = link_to_faber.find_available_claim(name='Transcript')\n\n print(claim_to_request)\n\n logging.info(\"### Alice send claim request to Faber ###\")\n pool.run(alice_agent.send_claim(link_to_faber, claim_to_request))\n\n demo_wait_for_claim_received(pool, alice_agent, 'Transcript')\n\n claims = pool.run(alice_agent.prover.wallet.getAllClaims())\n\n print(claims)\n\n ####################################\n # Acme Invitation\n ####################################\n\n print(ACME_INVITE)\n logging.info(\"### Alice loads Acme's invitation: ### {}\".format(ACME_INVITE))\n link_to_acme = alice_agent.load_invitation_str(ACME_INVITE)\n\n print(link_to_acme)\n\n logging.info(\"### Alice sync link with Acme ###\")\n alice_agent.sync(link_to_acme.name)\n\n demo_wait_for_sync(pool, link_to_acme)\n\n print(link_to_acme)\n\n logging.info(\"### Alice accepts Acme's invitation ###\")\n alice_agent.accept_invitation(link_to_acme)\n\n demo_wait_for_accept(pool, link_to_acme)\n\n print(link_to_acme)\n\n logging.info(\"### Alice sends Job Application ###\")\n job_application_request = link_to_acme.find_proof_request(name='Job-Application')\n\n print(job_application_request)\n\n alice_agent.sendProof(link_to_acme, job_application_request)\n\n ####################################\n # Job-Certificate Claim\n ####################################\n\n logging.info(\"### Alice wait for Job-Certificate to be available ###\")\n demo_wait_for_claim_available(pool, link_to_acme, 'Job-Certificate')\n\n print(link_to_acme)\n\n job_certificate = link_to_acme.find_available_claim(name='Job-Certificate')\n\n print(job_certificate)\n\n logging.info(\"### Alice send claim request to Acme ###\")\n pool.run(alice_agent.send_claim(link_to_acme, job_certificate))\n\n demo_wait_for_claim_received(pool, alice_agent, 'Job-Certificate')\n\n claims = pool.run(alice_agent.prover.wallet.getAllClaims())\n\n print(claims)\n\n ####################################\n # Thrift Invitation\n ####################################\n\n print(THRIFT_INVITE)\n logging.info(\"### Alice loads Thrift's invitation: ### {}\".format(THRIFT_INVITE))\n link_to_thrift = alice_agent.load_invitation_str(THRIFT_INVITE)\n\n print(link_to_thrift)\n\n logging.info(\"### Alice sync link with Thrift ###\")\n alice_agent.sync(link_to_thrift.name)\n\n demo_wait_for_sync(pool, link_to_thrift)\n\n print(link_to_thrift)\n\n logging.info(\"### Alice accepts Thrift's invitation ###\")\n alice_agent.accept_invitation(link_to_thrift)\n\n demo_wait_for_accept(pool, link_to_thrift)\n\n print(link_to_thrift)\n\n ####################################\n # Proof to Thrift\n ####################################\n\n logging.info(\"### Alice sends Loan Application Basic to Thrift ###\")\n load_basic_request = link_to_thrift.find_proof_request(name='Loan-Application-Basic')\n\n print(load_basic_request)\n\n alice_agent.sendProof(link_to_thrift, load_basic_request)\n\n demo_wait_for_proof(pool, load_basic_request)\n\n #######\n\n logging.info(\"### Alice sends Loan Application KYC to Thrift ###\")\n load_kyc_request = link_to_thrift.find_proof_request(name='Loan-Application-KYC')\n\n print(load_kyc_request)\n\n alice_agent.sendProof(link_to_thrift, load_kyc_request)\n\n demo_wait_for_proof(pool, load_kyc_request)\n\n pool.shutdownSync()\n\nif __name__ == \"__main__\":\n getting_started()\n print_log_uid_database()\n print(\"### END ###\")\n","sub_path":"sovrin_client/test/training/test_getting_started_guide.py","file_name":"test_getting_started_guide.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"152330574","text":"from pymongo import MongoClient\nfrom flask import current_app, g\nfrom flask.cli import with_appcontext\nfrom backend.resources import data_utils\nimport click\n\ndef get_db():\n mongoConfig = current_app.config['mongodb']\n client = MongoClient(mongoConfig['host'], mongoConfig['port'])\n db = client[mongoConfig['database']]\n if 'db' not in g:\n g.db = db\n g.client = client\n return g.db\n\ndef close_db():\n client = g.pop('client', None)\n if client is not None:\n client.close()\n\n@click.command('load_data')\n@with_appcontext\ndef load_data_command():\n \"\"\" Import data to the database from JSON dataset file after erasing previous content\n The whole operation is performed in memory cause the dataset is small (no more than 1000 items)\n The mongo insertion method does not use batch insert for similar reason.\n This is a one shot operation done during application installation step.\n \"\"\"\n print('Load data:')\n people = data_utils.load_people()\n companies = data_utils.load_companies()\n companies_map = data_utils.companies_map()\n people_map = data_utils.people_map()\n\n db = get_db()\n db.companies.drop()\n db.people.drop()\n\n # inserting companies\n inserted_count = 0\n for c in companies:\n doc = {\n 'index': c['index'],\n 'name': c['company']\n }\n print('Inserting company %s' % c['company'])\n db.companies.insert_one(doc)\n print('%d companies inserted' % inserted_count)\n\n # inserting people\n inserted_count = 0\n for p in people:\n doc = data_utils.prepare_person_document(p, companies_map, people_map)\n print('Inserting person %s' % p['name'])\n db.people.insert_one(doc)\n inserted_count += 1\n print('%d people documents inserted' % inserted_count)\n\ndef init_app(app):\n \"\"\" Register flask command to load new data from .json files. \n Will be called in the module in create_app() factory\n \"\"\"\n app.cli.add_command(load_data_command)","sub_path":"backend/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"278171733","text":"# 5/3/21\n# Mohammed\n# sensor code\nimport os\nimport serial\nimport time\nimport matplotlib.pyplot as plt\n\n\ndef read_sensor():\n # arduino.write(bytes(x, 'utf-8'))\n # time.sleep(0.05)\n raw_data = arduino.readline()\n data = str(arduino_data.decode(\"utf-8\"))\n print(\"data Recoded\")\n\n return data\n\n\ndef get_voltage(data):\n A = 128*((2**24)-1)\n print(\"Pressure calculated\")\n return str(5*(data/A))\n\n\ndef animate(i, t, data):\n x = t\n y = data\n\n ax = plt.gca()\n line = ax.lines\n\n line.set_data(x, y)\n\n xlim_low, xlim_high = ax.get_xlim()\n ylim_low, ylim_high = ax.get_ylim()\n\n ax.set_xlim(xlim_low, (x.max() + 5))\n\n ymax = y.max()\n\n ymin = y.min()\n\n ax.set_ylim((ymin - 5), (ymax + 5))\n\n\ndef fitting(data):\n t = np.linspace(0, data[-1], length(data))\n\n # linear equation\n fit_constants = np.polyfit(t, data, 1)\n\n return fit_constants\n\n\ndef save_data(filename, data):\n # filename = time.strftime(\"%Y-%m-%d_%H%M\")\n if not os.path.isfile(\"data.csv\"):\n print(\"hi\")\n with open(filename+\".csv\", 'w') as file:\n file.write(\"time,\")\n file.write(\"readings,\")\n file.write('\\n')\n\n with open(filename+\".csv\", 'a') as file:\n file.write(str(data[0])+\",\")\n file.write(str(data[1])+\",\")\n file.write('\\n')\n return print(\"data printed\")\n\n\ndef main():\n print('hi main')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Previous codes/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"371264601","text":"from converter.idx import Writer, Reader\nfrom converter.mel import mel\nimport numpy as np\n\nfile = 'bee.wav'\n\ns = mel(file)\ns_shape = s.shape\ns = s.reshape((128*16,))\n\n# writer = Writer('bee.idx3-ubyte', len(s_shape), dt='d', dt_magic=0x0e)\n# writer.set_dimension_sizes(s_shape)\n#\n# writer.write(s)\n# writer.write(s)\n# writer.write(s)\n# writer.write(s)\n#\n# writerl = Writer('bee.idx1-ubyte', 1, dt='B', dt_magic=8)\n# writerl.set_dimension_sizes((1,))\n# writerl.write([1])\n# writerl.write([1])\n# writerl.write([1])\n# writerl.write([1])\n\nreader = Reader('bee.idx1-ubyte', dt='B')\nreader.read_metadata()\nprint(reader.read())","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"150484144","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n # use count because:\n # it handles the case of a \"tie\" when two list nodes have the same value. When that happens, Python will look at the next value in the tuple (in this case, count), and sort based on that value. Without count, a \"tie\" would error out if the next value in the tuple were a ListNode (which can't be compared).\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n pq = []\n dummy = ListNode(0)\n curr = dummy\n count = 0\n for node in lists:\n if node:\n count += 1\n heapq.heappush(pq, (node.val, count, node))\n while len(pq) > 0:\n currMin = heapq.heappop(pq)\n curr.next = currMin[2]\n curr = curr.next\n if curr.next:\n count += 1\n heapq.heappush(pq, (curr.next.val, count, curr.next))\n return dummy.next\n ","sub_path":"23.MergekSortedLists.py","file_name":"23.MergekSortedLists.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"124444187","text":"# -*- coding: utf-8 -*-\nimport xlrd\nimport xlwt\nfrom pathlib import Path\n\n\nclass Unit(object):\n\t\"\"\"\n\t表示一个单元,采用excle进行数据存储\n\t\"\"\"\n\tRECORD_COL = [\"门牌号\", \"姓名\", \"金额\", \"利息\"]\n\n\tdef __init__(self, xls_path):\n\t\tself.xls_path = Path(xls_path)\n\t\tself.has_change = False\n\t\tself.sheet = {}\n\t\tself.__init()\n\n\tdef __init(self):\n\t\t\"\"\"\n\t\t读取excle\n\t\t:return:\n\t\t\"\"\"\n\n\t\tif not self.xls_path.exists():\n\t\t\treturn\n\n\t\tdata = xlrd.open_workbook(str(self.xls_path))\n\t\ttable = data.sheets()[0]\n\n\t\trow_count = table.nrows\n\n\t\tfor i in range(row_count):\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\trecord = table.row_values(i)\n\t\t\tself.sheet[record[0]] = record[1:]\n\n\tdef get_records(self):\n\t\treturn self.sheet\n\n\n\tdef add_record(self, house_id, user_name, money, interest):\n\t\tself.sheet[house_id] = [user_name, money, interest]\n\t\tself.has_change = True\n\n\tdef del_record(self, house_id):\n\t\tdel self.sheet[house_id]\n\t\tself.has_change = True\n\n\n\tdef get_summary(self):\n\t\tunit_summary = {\n\t\t\"hourse_count\": 0,\n\t\t'total_money': 0,\n\t\t'total_interest': 0\n\t\t}\n\t\tfor index, house_id in enumerate(self.sheet):\n\t\t\thouse_info = self.sheet[house_id]\n\t\t\tunit_summary['hourse_count'] += 1\n\t\t\tunit_summary['total_money'] += float(house_info[1])\n\t\t\tunit_summary['total_interest'] += float(house_info[2])\n\t\treturn unit_summary\n\n\tdef __save(self):\n\t\tif self.has_change:\n\t\t\twb = xlwt.Workbook()\n\t\t\tws = wb.add_sheet('Sheet')\n\t\t\t# write head\n\t\t\tfor index, value in enumerate(Unit.RECORD_COL):\n\t\t\t\tws.write(0, index, value.decode(\"utf-8\"))\n\n\t\t\t# write content\n\t\t\tfor index, house_id in enumerate(self.sheet):\n\t\t\t\thouse_info = self.sheet[house_id]\n\n\t\t\t\tws.write(index + 1, 0, house_id)\n\t\t\t\tws.write(index + 1, 1, house_info[0])\n\t\t\t\tws.write(index + 1, 2, house_info[1])\n\t\t\t\tws.write(index + 1, 3, house_info[2])\n\n\t\t\twb.save(str(self.xls_path))\n\n\tdef __enter__(self):\n\t\treturn self\n\n\tdef __exit__(self, exc_type, exc_val, exc_tb):\n\t\tif self.has_change:\n\t\t\tself.__save()\n\n\nif __name__ == \"__main__\":\n\txml_path = \"c:\\\\aa.xls\"\n\twith Unit(xml_path) as u:\n\t\tu.del_record(\"A-201\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"handler/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"415870246","text":"from google_images_download_master import bing_scraper\r\n\r\ndef crawler_bing(key):\r\n response=bing_scraper.googleimagesdownload() \r\n arguments = {\"url\":\"https://www.bing.com/images/search?q=\"+key+\"+icon\",\"download\":True,\"prefix\":key,\"limit\":1,\"print_urls\":True,\"chromedriver\":\".\\google_images_download_master\\chromedriver\"} \r\n paths = response.download(arguments)\r\n \r\n for key,value in paths[0].items():\r\n for path in value:\r\n return_path=path\r\n return return_path\r\n","sub_path":"getimage_bing.py","file_name":"getimage_bing.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"489222086","text":"from cerise.back_end.xenon_job_runner import XenonJobRunner\nfrom cerise.job_store.job_state import JobState\nfrom cerise.test.xenon import xenon_init\n\nfrom .mock_store import MockStore\n\nimport os\nimport pytest\nimport shutil\nimport time\nimport xenon\n\n@pytest.fixture\ndef x(request, xenon_init):\n ret = xenon.Xenon()\n yield ret\n ret.close()\n\nclass MockConfig:\n def __init__(self, x):\n self._x = x\n\n def get_scheduler(self, run_on_head_node=False):\n return self._x.jobs().newScheduler('local', None, None, None)\n\n def get_queue_name(self):\n return None\n\n def get_slots_per_node(self):\n return 1\n\n def get_remote_cwl_runner(self):\n return '$CERISE_API_FILES/cerise/cwltiny.py'\n\n@pytest.fixture\ndef fixture(request, tmpdir, x):\n result = {}\n\n result['remote-dir'] = str(tmpdir)\n result['store'] = MockStore({\n 'local-base-path': '',\n 'remote-base-path': result['remote-dir']\n })\n result['xenon'] = x\n result['xenon-job-runner-config'] = MockConfig(result['xenon'])\n\n # stage api\n base_api_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'api')\n remote_api_dir = os.path.join(result['remote-dir'], 'api')\n shutil.copytree(base_api_dir, remote_api_dir)\n\n test_steps_dir = os.path.join(os.path.dirname(__file__), 'api', 'steps', 'test')\n remote_test_steps_dir = os.path.join(result['remote-dir'], 'api', 'steps', 'test')\n shutil.copytree(test_steps_dir, remote_test_steps_dir)\n\n test_install_script_dir = os.path.join(os.path.dirname(__file__), 'api', 'install.sh')\n remote_install_script_dir = os.path.join(result['remote-dir'], 'api', 'install.sh')\n shutil.copy2(test_install_script_dir, remote_install_script_dir)\n\n result['xenon-job-runner'] = XenonJobRunner(\n result['store'], x, result['xenon-job-runner-config'],\n result['remote-dir'] + '/api/files',\n result['remote-dir'] + '/api/install.sh')\n return result\n\ndef _wait_for_state(fixture, job_id, state, timeout):\n \"\"\"Waits for the job to be in the given state.\"\"\"\n job = fixture['store'].get_job(job_id)\n total_time = 0.0\n while job.state != state and total_time < timeout:\n time.sleep(0.1)\n fixture['xenon-job-runner'].update_job(job_id)\n job = fixture['store'].get_job(job_id)\n total_time += 0.1\n\n assert total_time < timeout\n return job\n\ndef test_stage_api_script_execution(fixture):\n assert os.path.isfile(os.path.join(\n fixture['remote-dir'], 'api', 'files', 'test', 'test_file.txt'))\n\ndef test_start_job(fixture):\n fixture['store'].add_test_job('test_start_job', 'pass', 'staged')\n fixture['xenon-job-runner'].start_job('test_start_job')\n fixture['store'].get_job('test_start_job').state = JobState.WAITING\n\n updated_job = _wait_for_state(fixture, 'test_start_job', JobState.FINISHED, 1.0)\n assert updated_job.remote_job_id == 'local-1'\n\ndef test_start_staging_job(fixture):\n fixture['store'].add_test_job('test_start_staging_job', 'wc', 'staged')\n fixture['xenon-job-runner'].start_job('test_start_staging_job')\n fixture['store'].get_job('test_start_staging_job').state = JobState.WAITING\n\n updated_job = _wait_for_state(fixture, 'test_start_staging_job', JobState.FINISHED, 2.0)\n assert updated_job.remote_job_id == 'local-1'\n\ndef test_start_broken_job(fixture):\n fixture['store'].add_test_job('test_start_broken_job', 'broken', 'staged')\n fixture['xenon-job-runner'].start_job('test_start_broken_job')\n fixture['store'].get_job('test_start_broken_job').state = JobState.WAITING\n\n updated_job = _wait_for_state(fixture, 'test_start_broken_job', JobState.FINISHED, 1.0)\n assert updated_job.remote_job_id == 'local-1'\n assert updated_job.remote_output == ''\n\ndef test_update(fixture):\n fixture['store'].add_test_job('test_update', 'slow', 'staged')\n fixture['xenon-job-runner'].start_job('test_update')\n fixture['store'].get_job('test_update').state = JobState.WAITING\n\n updated_job = _wait_for_state(fixture, 'test_update', JobState.RUNNING, 2.0)\n updated_job = _wait_for_state(fixture, 'test_update', JobState.FINISHED, 6.0)\n\ndef test_cancel(fixture):\n fixture['store'].add_test_job('test_cancel', 'slow', 'staged')\n fixture['xenon-job-runner'].start_job('test_cancel')\n fixture['store'].get_job('test_cancel').state = JobState.WAITING\n\n updated_job = _wait_for_state(fixture, 'test_cancel', JobState.RUNNING, 2.0)\n is_running = fixture['xenon-job-runner'].cancel_job('test_cancel')\n assert is_running == False\n\n is_running = fixture['xenon-job-runner'].cancel_job('test_cancel')\n assert is_running == False\n","sub_path":"cerise/back_end/test/test_xenon_job_runner.py","file_name":"test_xenon_job_runner.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"482592957","text":"from SignalModel import Signal\nfrom LayerSelect import LayerSelect\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom BlockThMethod import BlockThMethod\nfrom ThresholdSelect import ThSelect\nfrom WtProcess import DWTP\nfrom DenoiseResult import DenoiseRsult\n\nif __name__ == '__main__':\n s = Signal(1000)\n od1 = s.createSin(50, 60, 4)\n od2 = s.createPulse(50, 60, 4)\n od3 = s.createSpikes(4)\n ods = [od1, od2, od3]\n spds = []\n hpds = []\n thsemispds = []\n thf1pds = []\n thf2pds = []\n thf3pds = []\n dnames = ['Sine', 'Pulse', 'Spike']\n thfname = ['soft', 'hard', 'thsemisf', 'thf1', 'thf2', 'thf3']\n pdsmatrix = [spds, hpds, thsemispds, thf1pds, thf2pds, thf3pds]\n thps = [None, None, None, 0.5, 2, 2]\n\n for od in ods:\n dwd = DWTP(od)\n coeffs = dwd.dwtdec(wtname='db4', delevel=2)\n for i in range(len(pdsmatrix)):\n ncoeffs = dwd.thprocess(coeffs, thf=thfname[i], thp=thps[i])\n pd = dwd.dwtrec(ncoeffs, wtname='db4')\n pdsmatrix[i].append(pd)\n \n ssnrs = []\n hsnrs = []\n thsemissnrs = []\n thf1snrs = []\n thf2snrs = []\n thf3snrs = []\n\n smses = []\n hmses = []\n thsemismses = []\n thf1mses = []\n thf2mses = []\n thf3mses = []\n\n ssms = []\n hsms = []\n thsemissms = []\n thf1sms = []\n thf2sms = []\n thf3sms = []\n\n slrepvs = []\n hlrepvs = []\n thsemislrepvs = []\n thf1lrepvs = []\n thf2lrepvs = []\n thf3lrepvs = []\n tds = [s.createSin(50, 60, 0), s.createPulse(50, 60, 0), s.createSpikes(0)]\n for i in range(len(ods)):\n sdr = DenoiseRsult(tds[i], spds[i])\n hdr = DenoiseRsult(tds[i], hpds[i])\n thsemisdr = DenoiseRsult(tds[i], thsemispds[i])\n thf1dr = DenoiseRsult(tds[i], thf1pds[i])\n thf2dr = DenoiseRsult(tds[i], thf2pds[i])\n thf3dr = DenoiseRsult(tds[i], thf3pds[i])\n ssnrs.append(sdr.snr())\n hsnrs.append(hdr.snr())\n thsemissnrs.append(thsemisdr.snr())\n thf1snrs.append(thf1dr.snr())\n thf2snrs.append(thf2dr.snr())\n thf3snrs.append(thf3dr.snr())\n\n smses.append(sdr.mse())\n hmses.append(hdr.mse())\n thsemismses.append(thsemisdr.mse())\n thf1mses.append(thf1dr.mse())\n thf2mses.append(thf2dr.mse())\n thf3mses.append(thf3dr.mse())\n\n ssms.append(sdr.smooth(ods[i]))\n hsms.append(hdr.smooth(ods[i]))\n thsemissms.append(thsemisdr.smooth(ods[i]))\n thf1sms.append(thf1dr.smooth(ods[i]))\n thf2sms.append(thf2dr.smooth(ods[i]))\n thf3sms.append(thf3dr.smooth(ods[i]))\n\n slrepvs.append(sdr.lrepv(ods[i], 100))\n hlrepvs.append(hdr.lrepv(ods[i], 100))\n thsemislrepvs.append(thsemisdr.lrepv(ods[i], 100))\n thf1lrepvs.append(thf1dr.lrepv(ods[i], 100))\n thf2lrepvs.append(thf2dr.lrepv(ods[i], 100))\n thf3lrepvs.append(thf3dr.lrepv(ods[i], 100))\n\n snrss = [ssnrs, hsnrs, thsemissnrs, thf1snrs, thf2snrs, thf3snrs]\n snrsn = ['ssnrs', 'hsnrs', 'thsemissnrs', 'thf1snrs', 'thf2snrs', 'thf3snrs']\n msess = [smses, hmses, thsemismses, thf1mses, thf2mses, thf3mses]\n msesn = ['smses', 'hmses', 'thsemismses', 'thf1mses', 'thf2mses', 'thf3mses']\n\n sms = [ssms, hsms, thsemissms, thf1sms, thf2sms, thf3sms]\n smsn = ['ssms', 'hsms', 'thsemissms', 'thf1sms', 'thf2sms', 'thf3sms']\n lrepvs = [slrepvs, hlrepvs, thsemislrepvs, thf1lrepvs, thf2lrepvs, thf3lrepvs]\n lrepvsn = ['slrepvs', 'hlrepvs', 'thsemislrepvs', 'thf1lrepvs', 'thf2lrepvs', 'thf3lrepvs']\n for i in range(len(snrss)):\n print('{0} = {1}'.format(snrsn[i], snrss[i]))\n print()\n for i in range(len(msess)):\n print('{0} = {1}'.format(msesn[i], msess[i]))\n print()\n for i in range(len(msess)):\n print('{0} = {1}'.format(smsn[i], sms[i]))\n print()\n for i in range(len(msess)):\n print('{0} = {1}'.format(lrepvsn[i], lrepvs[i]))\n\n x = [x for x in range(1000)]\n for j in range(3):\n plt.figure()\n for i in range(6):\n plt.subplot(3, 2, i+1)\n plt.title('{0} signal by {1} threshold'.format(dnames[j], thfname[i]))\n plt.plot(x, pdsmatrix[i][j])\n plt.tight_layout()\n plt.show()\n\n\n\n\n","sub_path":"Experiment 1 with self-definitive signal/t1.4 processing with different Th functions.py","file_name":"t1.4 processing with different Th functions.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"402462211","text":"from django.contrib import admin\r\nfrom django.http import HttpResponse\r\n\r\nimport csv\r\nimport datetime\r\nfrom .models import *\r\n\r\ndef ExportToCSV(modeladmin, request, queryset):\r\n opts = modeladmin.model._meta\r\n response = HttpResponse(content_type = 'text/csv')\r\n response['Content-Disposition'] = 'attachment; \\\r\n filename = Memos-{}.csv'.format(datetime.now().strftime(\"%d/%m/%Y\"))\r\n writer = csv.writer(response)\r\n\r\n fields = [field for field in opts.get_fields() if not field.one_to_many]\r\n\r\n writer.writerow([field.verbose_name for field in fields])\r\n\r\n for obj in queryset:\r\n data_row = []\r\n for field in fields:\r\n if field.many_to_many:\r\n data = getattr(obj, field.name)\r\n for i in data.all():\r\n value+= str(i)\r\n else:\r\n value = getattr(obj, field.name)\r\n if isinstance(value, datetime):\r\n value = value.strftime('%d/%m/%Y')\r\n data_row.append(value)\r\n writer.writerow(data_row)\r\n return response\r\n ExportToCSV.short_discription = 'Export CSV'\r\nclass MemoAdmin(admin.ModelAdmin):\r\n actions=[ExportToCSV]\r\nadmin.site.register(Memo, MemoAdmin)\r\nadmin.site.register(deltaId)","sub_path":"Main/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"368690458","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport math\nimport sys\n\nfrom sklearn.preprocessing import scale\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score, confusion_matrix, roc_curve, auc\nfrom sklearn.model_selection import cross_val_score\n\nfrom pywsl.pul import pu_mr\nfrom pywsl.utils.comcalc import bin_clf_err\nfrom pywsl.cpe.cpe_ene import cpe\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef mountTitanicSet(setArray, type='train'):\n pclassArray = setArray.loc[:, 'Pclass']\n\n sexArray = list(map(lambda sex: 0 if str.lower(sex) ==\n 'male' else 1, setArray.loc[:, 'Sex']))\n\n ageArray = list(map(lambda age: age/100 if not np.isnan(age)\n else np.nanmean(setArray.loc[:, 'Age'] / 100), setArray.loc[:, 'Age']))\n\n sibSpParchArray = setArray.loc[:, 'SibSp'] + setArray.loc[:, 'Parch']\n\n fareArray = list(map(lambda fare: fare if str.lower(\n str(fare)) != 'nan' else 0, setArray.loc[:, 'Fare']))\n\n hasCabinArray = list(map(lambda cabin: 1 if str.lower(\n str(cabin)) != 'nan' else 0, setArray.loc[:, 'Cabin']))\n\n portsArray = ['nan', 'c', 'q', 's']\n\n embarkGroupArray = list(map(lambda port: portsArray.index(\n str.lower(str(port))), setArray.loc[:, 'Embarked']))\n\n if type == 'train':\n survivedArray = setArray.loc[:, 'Survived']\n\n trainingMatrix = np.array([pclassArray, sexArray, ageArray,\n sibSpParchArray, fareArray, hasCabinArray, embarkGroupArray])\n\n return np.transpose(trainingMatrix), survivedArray\n\n elif type == 'test':\n trainingMatrix = np.array([pclassArray, sexArray, ageArray,\n sibSpParchArray, fareArray, hasCabinArray, embarkGroupArray])\n\n return np.transpose(trainingMatrix)\n\n\nnp.set_printoptions(threshold=np.inf)\ntrainSet = pd.read_csv('../input/train.csv', sep=',')\ntestSet = pd.read_csv('../input/test.csv', sep=',')\n\nx_train, y_train = mountTitanicSet(trainSet, 'train')\n\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train.astype('int'), train_size=float(sys.argv[1]))\n\npu_sl = pu_mr.PU_SL(basis=sys.argv[3])\n\npu_sl.fit(x_train, y_train)\n\ny_predict = pu_sl.predict(x_val)\n\nscore = bin_clf_err(y_val, y_predict)\nprint('\\nbin_clf_err:\\n\\n', score)\n\n# Confusion Matrix calculation\nconf_matrix = confusion_matrix(y_val, y_predict)\nprint('\\nConfusion Matrix:\\n\\n', conf_matrix)\n\n# ROC Curve calculation\nfpr = {}\ntpr = {}\nroc_auc = {}\n\nfpr[0], tpr[0], _ = roc_curve(y_val, y_predict)\nroc_auc[0] = auc(fpr[0], tpr[0])\n\n# Compute micro-average ROC curve and ROC area\nfpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_val, y_predict)\nroc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\nplt.figure()\nlw = 2\nplt.plot(fpr[0], tpr[0], color='darkorange',\n lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[0])\nplt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver operating characteristic for PU ' + sys.argv[3])\nplt.legend(loc=\"lower right\")\nplt.savefig('../output/pu_' + sys.argv[3] + '.png')\n","sub_path":"poc1/titanic/src/titanic_pu.py","file_name":"titanic_pu.py","file_ext":"py","file_size_in_byte":3237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"448393352","text":"\n\nfrom Tkinter import*\nimport tkMessageBox\n\ndef funcao():\n\ttkMessageBox.showinfo(\"Curso de Ferias\", \"Bem Vindo!\")\n\n\n\ntk = Tk()\nframe = Frame(tk)\nframe.pack()\n\n\nbtn = Button(frame, text=\"b1\")\nbtn.pack(side=\"right\")\nbtn2 = Button(frame, text=\"b2\")\nbtn.pack(side=\"left\")\nbtn2.pack()\n\n\ntk.mainloop()\n\n\n\n","sub_path":"aulas/vision/db_aulas/Aulas_ferias_python/codes/tkinter/teste3.py","file_name":"teste3.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"378508603","text":"class pokemon :\n def __init__(self, name, hp, power, skill):\n self.name = name\n self.hp = hp\n self.power = power\n self.skill = skill\n\n def info(self):\n print(f'포켓몬:{self.name}')\n print(f'체력:{self.hp}')\n print(f'공격력:{self.power}')\n print(f'기술:{self.skill}')\n def attack(self, skill_num):\n print(self.skill[skill_num])\n\n# 객체 생성\npokemon1 = pokemon('피카츄', 35, 55, ['100만볼트','전광석화','번개'])\npokemon2 = pokemon('파이리', 39, 52, ['불꽃세례', '화염방사', '회오리불꽃'])\npokemon3 = pokemon('꼬부기', 44, 48, ['거품', '물대포', '하이드로펌프'])\n\npokemon1.info()\npokemon2.info()\npokemon3.info()\n\npokemon1.attack(0)\npokemon2.attack(1)\npokemon3.attack(2)","sub_path":"class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"134331327","text":"import time\n\nfrom scujkbapp.jkb import jkbSession, jkbException\nfrom scujkbapp.models import UserProfile\n\n\ndef cronJob():\n userList = UserProfile.objects.filter(vaild=True)\n for user in userList:\n try:\n jkb = jkbSession(user.stu_id, user.stu_pass, user.SCKey)\n old = jkb.get_daily()\n jkb.submit(old)\n\n except jkbException as e:\n if e.code == '10001':\n user.vaild = False\n user.save()\n jkbSession.wechat_message(user.SCKey, '密码错误', '您在统一认证平台的密码已更改,请登录平台重新修改密码为当前密码')\n if e.code == '10002':\n jkb.message('昨日信息获取错误', '昨日信息获取错误')\n if e.code == '10003':\n jkb.message('打卡失败', str(e))\n\n time.sleep(0.5)\n","sub_path":"scujkbapp/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"292767874","text":"from power_set import *\nfrom timeit import default_timer as timer\nimport random\n\nfrom itertools import chain, combinations\n\ndef power_set(iterable):\n s = list(iterable)\n return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))\n\n# Flattens a set of sets (sos) into a single set containing all elements that exist in all subsets of th\ndef universe(sos):\n u = set()\n for s in sos:\n u = u.union(s)\n return u\n\n# Takes in a set of sets (sos) and finds the absolute minimum amount of sets need to achieve full set\n# coverage (the elements in those sets represent all elements in the union of all sets in the\n# set of sets)\ndef optimal_set_cover(sos):\n u = universe(sos)\n power_sos = power_set(sos)\n min_sos = sos # The minimal set cover solution found so far.\n for s in power_sos:\n if universe(s) == u and len(s) < len(min_sos):\n min_sos = s\n return list(min_sos)\n\ndef suboptimal_set_cover_1(sos):\n u = universe(sos)\n sos = sorted(sos, key=len)\n min_sos = [] # The minimal set cover solution found so far.\n ku = set() # The universe of elements covered so far, the \"known universe\".\n while ku != u:\n s = sos.pop()\n # Sanity check: Don't add a set if it doesn't increase our coverage.\n if len(ku.union(s)) > len(ku):\n min_sos.append(s)\n ku = ku.union(s)\n return min_sos\n\n\n# Find approximately the minimum set cover by taking a greedy approach.\n# This approach is not guaranteed to be optimal, but it's guaranteed to be much faster.\n# Heurisitc: Greedily add the set that adds the most amount of new elements to our min_sos untile\n# there are no more sets to be added.\ndef suboptimal_set_cover_2(sos):\n u = universe(sos)\n min_sos = [] # The minimal set cover solution found so far.\n ku = set() # The universe of elements covered so far, the \"known universe\".\n while ku != u:\n max_s = max(sos, key=lambda s: s.difference(ku))\n ku = ku.union(max_s)\n min_sos.append(max_s)\n return min_sos\n\n# Generate a random set of sets with a given amount of elements split across a given number of sets.\ndef generate_random_sos(num_elements, num_sets):\n return [set([random.choice([z for z in range(1, num_elements + 1)])\n for y in range(1, random.randint(1, num_elements))])\n for x in range(num_sets)]\n\n# start = timer()\n# optimal_set_cover(generate_random_sos(10, 10)) # 0.0028 seconds\n# end = timer()\n# print(end-start)\n\n# start = timer()\n# optimal_set_cover(generate_random_sos(15, 15)) # 0.113 seconds\n# end = timer()\n# print(end-start)\n\n# start = timer()\n# optimal_set_cover(generate_random_sos(20, 20)) # 5.08 seconds\n# end = timer()\n# print(end-start)\n\n# start = timer()\n# optimal_set_cover(generate_random_sos(25, 25)) # 251.313 seconds\n# end = timer()\n# print(end-start)\n\n# start = timer()\n# optimal_set_cover(generate_random_sos(30, 30)) # Didn't finish\n# end = timer()\n# print(end-start)\n","sub_path":"2020/set_cover_and_aliens/set_cover.py","file_name":"set_cover.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"592429214","text":"#---------------------------------\r\n#Author: Chappuis Anthony\r\n#\r\n#Class responsible for the themes' collection of widget used in the main window\r\n#\r\n#Application: DragonShout music sampler\r\n#Last Edited: August 07th 2018\r\n#---------------------------------\r\n\r\nfrom classes.interface import MainWindow\r\nfrom classes.interface.ThemeButtons import ThemeButtons\r\nfrom classes.interface.ThemeButtonDialogBox import ThemeButtonDialogBox\r\n\r\nfrom PyQt5 import Qt\r\nfrom PyQt5.QtWidgets import (QWidget, QPushButton, QVBoxLayout, QInputDialog,\r\n QHBoxLayout, QMessageBox, QScrollArea)\r\n\r\nclass Themes(QWidget):\r\n\r\n def __init__(self, mainWindow:MainWindow):\r\n super().__init__()\r\n\r\n self.mainWindow = mainWindow\r\n self.themeButtons = []\r\n\r\n #Main layout\r\n self.mainLayout = QVBoxLayout()\r\n self.mainLayout.setAlignment(Qt.Qt.AlignHCenter)\r\n self.setLayout(self.mainLayout)\r\n\r\n #New theme button\r\n self.addNewThemeButton(self.mainLayout)\r\n\r\n #theme buttons layout\r\n self.themeButtonsLayout = QVBoxLayout()\r\n self.themeButtonsLayout.setAlignment(Qt.Qt.AlignHCenter)\r\n\r\n #Theme buttons widget\r\n themeButtonsWidget = QWidget()\r\n themeButtonsWidget.setLayout(self.themeButtonsLayout)\r\n\r\n # Theme buttons scrolling area\r\n self.scrollArea = QScrollArea(self)\r\n self.scrollArea.setWidgetResizable(True)\r\n self.scrollArea.setHorizontalScrollBarPolicy(Qt.Qt.ScrollBarAlwaysOff)\r\n self.scrollArea.setWidget(themeButtonsWidget)\r\n\r\n self.mainLayout.addWidget(self.scrollArea)\r\n\r\n def addNewThemeButton(self, mainLayout:QVBoxLayout):\r\n \"\"\"Add a button to add a new theme to the given layout.\r\n Takes one parameter:\r\n - layout as QVBoxLayout object.\r\n Returns nothing\r\n \"\"\"\r\n newThemeButton = QPushButton(self.mainWindow.text.localisation('buttons','newTheme','caption'))\r\n newThemeButton.clicked.connect(lambda *args: self.addTheme())\r\n self.mainLayout.addWidget(newThemeButton)\r\n\r\n\r\n def reset(self):\r\n \"\"\"Used to reset the themes layout by removing each childrens.\r\n Takes no parameter.\r\n Returns nothing.\r\n \"\"\"\r\n for i in reversed(range(self.themeButtonsLayout.count())):\r\n self.themeButtonsLayout.itemAt(i).widget().setParent(None)\r\n self.themeButtons = []\r\n\r\n def setThemes(self):\r\n \"\"\"Used to create the GUI elements for all existing themes.\r\n Takes no parameter.\r\n Returns nothing.\r\n \"\"\"\r\n self.reset()\r\n for theme in self.mainWindow.library.categories:\r\n themeButton = ThemeButtons(theme.name, theme.iconPath, self.mainWindow)\r\n self.themeButtonsLayout.addWidget(themeButton)\r\n self.themeButtons.append(themeButton)\r\n\r\n def addTheme(self):\r\n \"\"\"Adds a new theme button to the theme main layout.\r\n Takes no parameter.\r\n Returns nothing.\r\n \"\"\"\r\n ok = False\r\n\r\n themeName, themeIconPath, ok = ThemeButtonDialogBox(self.mainWindow).getItems()\r\n\r\n if ok :\r\n if themeName == '' or not isinstance(themeName, str):\r\n themeName = self.mainWindow.text.localisation('buttons','newTheme','caption')\r\n self.mainWindow.library.add_category(themeName,themeIconPath)\r\n\r\n #Theme widget\r\n themeButtons = ThemeButtons(themeName, themeIconPath, self.mainWindow)\r\n self.themeButtons.append(themeButtons)\r\n self.themeButtonsLayout.addWidget(themeButtons)\r\n\r\n def deleteTheme(self, themeName:str, themeButtons:ThemeButtons):\r\n \"\"\"Delete the theme both in the UI and in the library.\r\n Takes two parameter:\r\n - themeName as string\r\n - themeButtons object\r\n Returns nothing.\r\n \"\"\"\r\n choice = QMessageBox(QMessageBox.Question,self.mainWindow.text.localisation('messageBoxes','deleteTheme','title')+themeName+' ?',\r\n self.mainWindow.text.localisation('messageBoxes','deleteTheme','caption'),\r\n QMessageBox.Yes | QMessageBox.No).exec()\r\n\r\n if choice == QMessageBox.Yes :\r\n\r\n if themeName == self.mainWindow.playlist.label.text():\r\n self.mainWindow.playlist.reset()\r\n\r\n if themeButtons in self.themeButtons :\r\n self.themeButtons.remove(themeButtons)\r\n\r\n if self.mainWindow.library.get_category(themeName) :\r\n self.mainWindow.library.remove_category(themeName)\r\n themeButtons.deleteLater()\r\n\r\n def toggleThemes(self, toggleType:bool):\r\n \"\"\"Used to disable or enable the themeButtons.\r\n Takes one parameter:\r\n - toggleType as boolean.\r\n Returns nothing.\r\n \"\"\"\r\n for theme in self.themeButtons :\r\n themeButton = theme.themeButton\r\n\r\n if toggleType == True :\r\n themeButton.setEnabled(True)\r\n elif toggleType == False :\r\n themeButton.setEnabled(False)\r\n","sub_path":"classes/interface/Themes.py","file_name":"Themes.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"205841972","text":"import glob\nimport subprocess\nimport sys\nimport os\nfrom pathlib import Path\n\nflags = \"-i . -I- -i include -nostdinc -Cpp_exceptions off -O2 -proc gekko -fp hard -enum int -sdata 0 -sdata2 0 -g\"\nas_flags = \"-i . -I- -nostdinc -proc gekko -d __MWERKS__\"\n\nif not os.path.isdir(\"tools\"):\n print(\"tool directory not found\")\n sys.exit(1)\n\nif not os.path.isdir(\"build\"):\n os.mkdir(\"build\")\n\npath = os.path.dirname(os.path.realpath(__file__)) + \"\\\\source\\\\\"\n\nc_files = [f for f in glob.glob(path + \"**/*.c\", recursive=True)]\ncpp_files = [f for f in glob.glob(path + \"**/*.cpp\", recursive=True)]\nassembly_files = [f for f in glob.glob(path + \"**/*.s\", recursive=True)]\n\nfor f in cpp_files:\n file_name = Path(f).stem\n\t\n print(f\"Compiling {file_name}.cpp...\")\n\n if subprocess.call(f\"mwcceppc.exe {flags} -c -o build/{file_name}.o {f}\", shell=True) == 1:\n sys.exit(1)\n\nfor f in c_files:\n file_name = Path(f).stem\n\t\n print(f\"Compiling {file_name}.c...\")\n\n if subprocess.call(f\"mwcceppc.exe {flags} -c -o build/{file_name}.o {f}\", shell=True) == 1:\n sys.exit(1)\n\nfor f in assembly_files:\n file_name = Path(f).stem\n\t\n print(f\"Assembling {file_name}.s...\")\n\n if subprocess.call(f\"mwasmeppc.exe {as_flags} -o build/{file_name}.o {f}\", shell=True) == 1:\n sys.exit(1)","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"618175695","text":"# Gomspace test case. Gets cycle count purely for diagnostic purposes and logs\n# any other Gomspace state fields.\nfrom .base import SingleSatCase\nfrom .utils import Enums, TestCaseFailure\n\n# DO NOT USE AS A REFRENCE TO WRITE OTHER PTEST CASES\n#\n# This testcase is basically a dinosaur among the other testcases and using many\n# features that are considered \"deprecated\".\n\nclass GomspaceCheckoutCase(SingleSatCase):\n\n def read_state(self, string_state):\n return self.flight_controller.read_state(string_state)\n\n def write_state(self, string_state, state_value):\n self.flight_controller.write_state(string_state, state_value)\n return self.read_state(string_state)\n\n def str_to_bool(self, string):\n if string == \"true\":\n return True\n elif string == \"false\":\n return False\n else:\n raise ValueError\n\n def run(self):\n self.flight_controller.write_state('gomspace.piksi_off', False)\n self.failed = False\n self.cycle_no = self.flight_controller.read_state(\"pan.cycle_no\")\n self.write_state(\"gomspace.piksi_off\", \"false\")\n\n # readable fields\n vboost = [int(self.read_state(\"gomspace.vboost.output\" + str(i)))\n for i in range(1, 4)]\n for n in range(0, len(vboost)):\n self.logger.put(\"vboost\" + str(n) + \" is: \" + str(vboost[n]) + \" mV\")\n\n vbatt = int(self.read_state(\"gomspace.vbatt\"))\n if vbatt < 6000 or vbatt > 8400:\n self.logger.put(\n \"Vbatt is out of expected range [6000, 8400] mV at: \" + str(vbatt))\n\n curin = [int(self.read_state(\"gomspace.curin.output\" + str(i)))\n for i in range(1, 4)]\n for n in range(0, len(curin)):\n self.logger.put(\"curin\" + str(n) + \" is: \" + str(curin[n]) + \" mA\")\n cursun = int(self.read_state(\"gomspace.cursun\"))\n self.logger.put(\"cursun is: \" + str(cursun) + \" mA\")\n cursys = int(self.read_state(\"gomspace.cursys\"))\n self.logger.put(\"cursys is: \" + str(cursys) + \" mA\")\n\n curout = [int(self.read_state(\"gomspace.curout.output\" + str(i)))\n for i in range(1, 7)]\n for n in range(0, len(curout)):\n self.logger.put(\"curout\" + str(n) + \" is: \" + str(curout[n]) + \" mA\")\n\n output = [self.str_to_bool(self.read_state(\"gomspace.output.output\" + str(i)))\n for i in range(1, 7)]\n\n for n in range(0, len(output)):\n out_n = output[n]\n # checked umbilical for which outputs should be 0 and 1:\n # 1-5 are all 5V, 6 is 3.3V\n if out_n is False:\n self.logger.put(\"Output-\" + str(n) + \" is not on\")\n\n wdt_i2c_time_left = int(self.read_state(\"gomspace.wdt_i2c_time_left\"))\n if wdt_i2c_time_left < 99:\n self.logger.put(\"wdt_i2c_time_left is less than 99 seconds at: \" +\n str(wdt_i2c_time_left))\n\n counter_wdt_i2c = self.read_state(\"gomspace.counter_wdt_i2c\")\n self.logger.put(\"counter_wdt_i2c is: \" + str(counter_wdt_i2c))\n counter_boot = self.read_state(\"gomspace.counter_boot\")\n self.logger.put(\"counter_wdt_i2c is: \" + str(counter_boot))\n\n temp = [int(self.read_state(\"gomspace.temp.output\" + str(i)))\n for i in range(1, 5)]\n for n in range(0, len(temp)):\n temp_n = temp[n]\n if temp_n < 20 or out_n > 25:\n self.logger.put(\"Temp-\" + str(n) +\n \" is out of room temperature range [20, 25] degC at: \" + str(temp_n))\n\n bootcause = self.read_state(\"gomspace.bootcause\")\n self.logger.put(\"bootcause is: \" + str(bootcause))\n battmode = self.read_state(\"gomspace.battmode\")\n self.logger.put(\"battmode is: \" + str(battmode))\n pptmode = self.read_state(\"gomspace.pptmode\")\n self.logger.put(\"pptmode is: \" + str(pptmode))\n\n # writable fields\n power_cycle_output_cmd = [self.str_to_bool(self.read_state(\"gomspace.power_cycle_output\" + str(i) + \"_cmd\"))\n for i in range(1, 7)]\n cycle_no_init = int(self.read_state(\"pan.cycle_no\"))\n cycle_no = cycle_no_init\n\n # power cycling\n # start power cycle\n power_cycle_output_cmd = [self.str_to_bool(self.write_state(\"gomspace.power_cycle_output\"\n + str(i) + \"_cmd\", \"true\"))\n for i in range(1, 7)]\n self.cycle()\n while int(self.read_state(\"pan.cycle_no\")) % int(self.read_state(\"gomspace.powercycle_period\")) != 0:\n output = [self.str_to_bool(self.read_state(\"gomspace.output.output\" + str(i)))\n for i in range(1, 7)]\n self.logger.put(\"current output: \" + str(output))\n self.cycle()\n # wait for outputs to be off\n while (not all(out == False for out in output)) and cycle_no - cycle_no_init < 600:\n output = [self.str_to_bool(self.read_state(\"gomspace.output.output\" + str(i)))\n for i in range(1, 7)]\n self.cycle()\n cycle_no = int(self.read_state(\"pan.cycle_no\"))\n if cycle_no - cycle_no_init == 600:\n self.logger.put(\n \"Power cycled outputs could not turn off after 600 cycles (1 minute)\")\n cycle_no = int(self.read_state(\"pan.cycle_no\"))\n self.logger.put(\"failed on cycle: \" + str(cycle_no))\n self.failed = True\n \n # wait for outputs to turn on again\n while (not all(out == True for out in output)) and cycle_no - cycle_no_init < 600:\n output = [self.str_to_bool(self.read_state(\"gomspace.output.output\" + str(i)))\n for i in range(1, 7)]\n self.cycle()\n cycle_no = int(self.read_state(\"pan.cycle_no\"))\n if cycle_no - cycle_no_init == 600:\n self.logger.put(\n \"Power cycled outputs could not turn on after 600 cycles (1 minute)\")\n self.failed = True\n\n # check if finished power cycling\n power_cycle_output_cmd = [self.str_to_bool(self.read_state(\"gomspace.power_cycle_output\"\n + str(i) + \"_cmd\"))\n for i in range(1, 7)]\n for n in range(0, len(power_cycle_output_cmd)):\n if power_cycle_output_cmd[n] == True:\n self.logger.put(\"Could not update power_cycle_output\" + str(n))\n self.failed = True\n\n ppt_mode_cmd = int(self.read_state(\"gomspace.pptmode_cmd\"))\n ppt_mode_updated = int(self.write_state(\n \"gomspace.pptmode_cmd\", (int(ppt_mode_cmd) + 1) % 2))\n if ppt_mode_cmd == ppt_mode_updated:\n self.logger.put(\"Could not update pptmode\")\n self.failed = True\n\n heater_cmd = self.str_to_bool(self.read_state(\"gomspace.heater_cmd\"))\n heater_cmd_updated = self.str_to_bool(self.write_state(\n \"gomspace.heater_cmd\", not heater_cmd))\n if heater_cmd == heater_cmd_updated:\n self.logger.put(\"Could not update heater\")\n self.failed = True\n\n counter_reset_cmd = self.str_to_bool(self.read_state(\n \"gomspace.counter_reset_cmd\"))\n counter_reset_cmd_updated = self.str_to_bool(self.write_state(\n \"gomspace.counter_reset_cmd\", not counter_reset_cmd))\n if counter_reset_cmd == counter_reset_cmd_updated:\n self.logger.put(\"Could not update counter_reset\")\n self.failed = True\n\n gs_reset_cmd = self.str_to_bool(\n self.read_state(\"gomspace.gs_reset_cmd\"))\n gs_reset_cmd_updated = self.str_to_bool(self.write_state(\n \"gomspace.gs_reset_cmd\", not gs_reset_cmd))\n if gs_reset_cmd == gs_reset_cmd_updated:\n self.logger.put(\"Could not update gs_reset\")\n self.failed = True\n\n gs_reboot_cmd = self.str_to_bool(\n self.read_state(\"gomspace.gs_reboot_cmd\"))\n gs_reboot_cmd_updated = self.str_to_bool(self.write_state(\n \"gomspace.gs_reboot_cmd\", not gs_reboot_cmd))\n if gs_reboot_cmd == gs_reboot_cmd_updated:\n self.logger.put(\"Could not update gs_reboot\")\n self.failed = True\n\n if self.failed: \n raise TestCaseFailure(\"Failed a step in Gomspace checkout: see log above.\")\n\n self.finish()\n\nclass CheckBatteryLevel(SingleSatCase):\n def run(self):\n voltage = float(self.read_state(\"gomspace.vbatt\"))\n self.logger.put(\" \")\n self.logger.put(\"=================================\")\n self.logger.put(\"=================================\")\n self.logger.put(f\"Satellite battery level: {voltage/1000} volts\")\n self.logger.put(\"=================================\")\n self.logger.put(\"=================================\")\n self.logger.put(\" \")\n self.finish()\n","sub_path":"ptest/cases/gomspace_checkout_case.py","file_name":"gomspace_checkout_case.py","file_ext":"py","file_size_in_byte":9102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"108932977","text":"# encoding=UTF-8\n\nfrom pyspark import SparkContext, SparkConf\n\nFILE_PATH = '/Users/toru/spark/program/data'\nINPUT_FILE = 'questionnaire.csv'\n\n\nconf = SparkConf().setAppName('test05-5')\nsc = SparkContext(conf=conf)\n\nnum_m_acc = sc.accumulator(0)\nnum_f_acc = sc.accumulator(0)\ntotal_m_acc = sc.accumulator(0)\ntotal_f_acc = sc.accumulator(0)\n\n\n# 代入する場合は 変数を`global`で定義し直す必要あり\n# def calc(element):\n# global num_m_acc\n# global num_f_acc\n# global total_m_acc\n# global total_f_acc\n\n# if element[1] == 'M':\n# num_m_acc += 1\n# total_m_acc += element[2]\n# else:\n# num_f_acc += 1\n# total_f_acc += element[2]\n\n# メソッド呼び出しの場合は`global`での再定義不要\ndef calculate_m_or_f_average(element):\n if element[1] == 'M':\n num_m_acc.add(1)\n total_m_acc.add(element[2])\n else:\n num_f_acc.add(1)\n total_f_acc.add(element[2])\n\n\ndef split_data(line):\n array = line.split(',')\n age_range = int(int(array[0]) / 10) * 10 # 年代に変換\n sex = array[1]\n point = int(array[2])\n return age_range, sex, point\n\n\ndef compute_all_average(rdd):\n return rdd\\\n .map(lambda element: (element[2], 1))\\\n .reduce(lambda result, element: (\n result[0] + element[0], result[1], element[1]))\n\n\ndef compute_age_range_averate(rdd):\n return rdd\\\n .map(lambda element: (element[0], (element[2], 1))) \\\n .reduceByKey(lambda result, element: (\n result[0] + element[0], result[1] + element[1]))\n\n\ntry:\n # データの読み込み\n data = sc.textFile(FILE_PATH + '/' + INPUT_FILE) \\\n .map(split_data)\n\n # データを永続化(MEMORY_ONLY)\n data.cache()\n\n # 全体平均の算出1\n # count = data.count()\n # total_point = data.map(lambda element: element[2]).sum()\n # print('AVG ALL: ' + str(total_point / count))\n\n # 全体平均の算出2\n total_average = compute_all_average(data)\n print('AVG ALL: ' + str(total_average[0] / total_average[1]))\n\n # 年代別平均\n age_range_average = compute_age_range_averate(data)\n for value in age_range_average.collect():\n print('AVG Age Range(' + str(value[0]) +\n '): ' + str(value[1][0] / value[1][1]))\n\n # 性別毎平均\n # アキュームレータを利用する\n data.foreach(calculate_m_or_f_average)\n print('AVG M: ' + str(total_m_acc.value / num_m_acc.value))\n print('AVG F: ' + str(total_f_acc.value / num_f_acc.value))\n\nfinally:\n sc.stop()\n","sub_path":"program/test05-5.py","file_name":"test05-5.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"212962400","text":"from Singleton import *\nimport Logger\nfrom Component import *\nfrom Utils import *\n\n@Singleton\nclass MiddlewareRegistrar:\n \"\"\" A class used to register Middleware and dispatch Middleware \"\"\"\n def __init__(self):\n self._middleware = {} # Start with nothing registered\n\n def Register(self, name, fn):\n \"\"\" Registers some middleware \"\"\"\n name = normalizeStr(name)\n Logger.Debug(\"Registering Middleware:\", name)\n self._middleware[name] = fn\n\n def Dispatch(self, name):\n \"\"\" Returns a function to wrap around middleware \"\"\"\n name = normalizeStr(name)\n\n if name not in self._middleware:\n return None\n\n def dispatchWrapper(components):\n \"\"\" Wrapper Function to apply middleware \"\"\"\n cpy = components.Copy() # Create a copy of the component list (to continue in pipeline if failure)\n Logger.Debug(\"Running\", name, \"Middleware\")\n try:\n result = self._middleware[name](components)\n\n if type(result) is not KiCadComponentList:\n Logger.Error(\"Middleware\", name, \"returned\", type(result), \"not KiCadComponentList--Restoring copy of components\")\n return cpy\n\n return result\n\n except Exception as e:\n Logger.Error(\"Exception\", e, \"in\", name, \"Middleware--Restoring copy of components\")\n return cpy\n\n return dispatchWrapper\n","sub_path":"Middleware/middleware_registrar.py","file_name":"middleware_registrar.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"186596391","text":"from puppies import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\n\ndef create_session(dbinstance='puppyshelter.db'):\n\t'''\n\tConnects to dbinstance and returns a session\n\t'''\n\tengine = create_engine('sqlite:///'+dbinstance)\n\tBase.metadata.bind = engine\n\tDBSession = sessionmaker(bind=engine)\n\treturn DBSession()\n\ndef register_shelter(name,address,city,state,zipCode,website,max_capacity,session):\n\t'''\n\tRegisters a new shelter in database\n\t'''\n\tsession.add(Shelter(name=name,address=address,city=city,state=state,zipCode=zipCode,website=website,max_capacity=max_capacity))\n\tsession.commit()\n\ndef list_shelters(session):\n\t'''\n\tReturns list off shelters with their current occupancy\n\t'''\n\tshelters = session.query(Shelter).all()\n\tfor shelter in shelters:\n\t\tshelter.set_occupancy()\n\t\tprint('['+str(shelter.id)+'] '+shelter.name+' / Current occupancy: '+str(shelter.current_occupancy))\n\ndef query_shelter_spaceleft(shelterid,session):\n\t'''\n\tReturns True of False if the shelter has space left\n\t'''\n\tshelter = session.query(Shelter).get(shelterid)\n\tshelter.set_occupancy()\n\treturn shelter.current_occupancy < shelter.max_capacity\n\ndef register_puppy(shelterid,name,gender,dob,pic,weight,session):\n\t'''\n\tRegisters a new puppy in database\n\t'''\n\t#Check if selected shelter has space\n\tif query_shelter_spaceleft(shelterid,session):\n\t\t#If yes, create new puppy instance and commit to database\n\t\tpuppy = Puppy(name=name,gender=gender,dateOfBirth=dob,picture=pic,shelter_id=shelterid,weight= weight)\n\t\tsession.add(puppy)\n\t\tsession.commit()\n\t\t# print(name+' added to database / Shelter: '+puppy.shelter.name)\n\telse:\n\t\t#If no, asking user to select a different shelter\n\t\tprint('No space left in selected shelter')\n\ndef add_puppyprofile(description,specialneeds,puppyid,session):\n\t'''\n\tAdd a profile to a registered puppy\n\t'''\n\tsession.add(PuppyProfile(description=description,specialneeds=specialneeds,puppy_id=puppyid))\n\tsession.commit()\n\ndef register_adopter(firstname,lastname,session):\n\t'''\n\tRegisters a new adopter to database\n\t'''\n\tadopter = Adopter(firstname=firstname, lastname=lastname)\n\tsession.add(adopter)\n\tsession.commit()\n\ndef adopt_puppy(puppyid,l_adopters,session):\n\t'''\n\tAssigns the adopters id in the list of adopter (l_adopters) to the puppy with the matching puppyid.\n\tRemoves the puppy from his shelter and updates the shelter occupancy\n\t'''\n\tpuppy = session.query(Puppy).get(puppyid)\n\tprint('\\nAdopting: '+puppy.name)\n\tprint('Current shelter: '+puppy.shelter.name)\n\tprint('New owner(s):')\n\tfor adopterid in l_adopters:\n\t\tadopter = session.query(Adopter).get(adopterid)\n\t\tpuppy.owners.append(adopter)\n\t\tprint('\t'+adopter.firstname+' '+adopter.lastname)\n\t\t\n\tpuppy.remove_shelter()\n\tsession.commit()\n\n\n\n\n","sub_path":"vagrant/puppyshelter/puppycontroller.py","file_name":"puppycontroller.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"95262512","text":"#!/usr/bin/python3.4 -tt\n# -*- coding: utf-8 -*-\n\n\nfrom kivy.clock import Clock\nfrom kivy.graphics.texture import Texture\nfrom kivy.lang import Builder\nfrom kivy.uix.widget import Widget\nfrom kivy.properties import BooleanProperty, NumericProperty, ObjectProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.screenmanager import Screen\nfrom kivy.uix.button import Button\nfrom kivy.uix.progressbar import ProgressBar\n\nfrom timeit import default_timer as timer\n\nfrom threading import Thread, current_thread\n\nimport time\n\nimport cv2\n\nimport marsem.opencv as opencv\nimport marsem.protocol.car as car\nimport marsem.gui.calibrationScreen as calibration\n\n\nBuilder.load_file(\"homeScreen.kv\")\n\n\nclass HomeScreen(Screen):\n def start_server(self):\n if car.start_server():\n return True\n else:\n return False\n\n def stop_server(self):\n if car.stop_server():\n return False\n else:\n return True\n\n def stop_stream(self):\n opencv.stop()\n return car.stream(False)\n\n def connect(self):\n def _callback(t):\n if t and not opencv.is_connected():\n # Sleep ?\n time.sleep(1)\n return opencv.connect()\n\n def _failure(t):\n if opencv.is_connected():\n opencv.stop()\n return False\n return car.stream(True, success=_callback, failure=_failure)\n\n\nclass OpenCVStream(BoxLayout):\n error_count = 0 # Counting number of times a frame from OpenCV could not be parsed into texture.\n\n loaded = False\n\n frame = ObjectProperty(None,allownone=True, force_dispatch=True)\n\n def on_frame(self, instance, pos):\n if self.frame != None:\n texture = Texture.create(size=(self.frame.shape[1],\n self.frame.shape[0]),\n colorfmt='bgr')\n texture.blit_buffer(self.frame.tostring(),\n colorfmt='bgr',\n bufferfmt='ubyte')\n texture.flip_horizontal()\n self.stream_image.texture = texture\n else:\n self.stream_image.texture = None\n\n\n def load(self):\n if not self.loaded:\n self.loaded = True\n\n self.stream_image = Image(source='stream_image.png')\n self.stream_image.keep_ratio = False\n self.stream_image.allow_stretch = True\n\n self.add_widget(self.stream_image)\n\n def update(self, dt):\n self.frame = opencv.get_video()\n\n def start(self):\n def _callback():\n Clock.unschedule(self.update)\n self.stream_image.texture = None\n c = calibration.CURRENT_COLOR\n #c.set_min_max(opencv.green_min, opencv.green_max)\n ocv = Thread(target=opencv.run,kwargs={\"color\": c, \n \"callback\": _callback}, daemon=True)\n ocv.start()\n Clock.schedule_interval(self.update, 0.01)\n\n\nclass Status(Widget):\n # Assume that nothing is enabled and assign r, g, b and o to values you want as default\n # color for the widget \"thing\", whatever it might be (does not necessarily have to\n # inherit from 'Widget'.\n enabled = BooleanProperty(False)\n r = NumericProperty(0.988)\n g = NumericProperty(0.043)\n b = NumericProperty(0)\n o = NumericProperty(0.5)\n\n # 'value' is the 'enabled' BooleanProperty. Since we named the property 'enabled', the\n # function that will listen to a changed value HAS TO BE NAMED 'on_enabled'!\n def on_enabled(self, instance, value):\n if value:\n self.r = 0.227\n self.g = 1\n self.b = 0.082\n self.o = 1\n else:\n self.r = 0.988\n self.g = 0.043\n self.b = 0\n self.o = 0.5\n\n\nclass PhotoProgress(ProgressBar):\n def __init__(self, **kwargs):\n super(PhotoProgress, self).__init__(**kwargs)\n self.value = 0\n self.max = opencv.DEFAULT_TIMEOUT * 10 # Milliseconds\n\n def start(self):\n self.value = 0\n self.schedule_update()\n\n def schedule_update(self):\n Clock.unschedule(self.update) # Remove if already existing.\n Clock.schedule_interval(self.update, 0.1)\n\n def stop(self):\n Clock.unschedule(self.update)\n\n def update(self, dt):\n self.value += 1\n\n if self.value >= self.max:\n return False\n","sub_path":"marsem/gui/homeScreen.py","file_name":"homeScreen.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"227838893","text":"from django.shortcuts import render,redirect\nfrom curdapp.models import Employee\nfrom curdapp.forms import EmployeeForm\n# Create your views here.\ndef show_view(request):\n employee=Employee.objects.all()\n return render(request,'curdapp/index.html',{'employee':employee})\n\ndef Insert_view(request):\n form=EmployeeForm()\n if request.method=='POST':\n form=EmployeeForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n return render(request,'curdapp/insert.html',{'form':form})\n\ndef Delete_view(request,id):\n employee=Employee.objects.get(id=id)\n employee.delete()\n return redirect('/')\n\ndef update_view(request,id):\n employee= Employee.objects.get(id=id)\n if request.method == 'POST':\n form = EmployeeForm(request.POST,instance=employee)\n if form.is_valid():\n form.save()\n return redirect('/')\n return render(request,'curdapp/update.html',{'employee':employee})\n","sub_path":"fbvproject1/curdapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"320689093","text":"import discord\nfrom discord.ext import commands\nimport os\nimport sys\nfrom motor import motor_asyncio\nimport requests\nimport json\nfrom ext import utils\n\ndbclient = motor_asyncio.AsyncIOMotorClient('mongodb://hellobitgame:' + os.environ.get(\"DBPASS\") + '@ds255329.mlab.com:55329/hellobitgame')\ndb = dbclient.hellobitgame\n\nasync def get_pre(bot, message):\n try:\n result = await db.settings.find_one({'_id': str(message.guild.id)})\n except AttributeError:\n return \"!\"\n if not result or not result.get('prefix'):\n return \"!\"\n return result['prefix']\n\n\nbot = commands.Bot(command_prefix=get_pre, description=\"This is an example bot\", owner_id=279974491071709194)\n\nasync def save_prefix(prefix, guildID):\n await db.settings.update_one({'_id': guildID}, {'$set': {'_id': guildID, 'prefix': prefix}}, upsert=True)\n\n@bot.event\nasync def on_ready():\n print(\"Bot is online!\")\n await bot.change_presence(activity=discord.Activity(name=f'BattleBit | !help', type=discord.ActivityType.playing))\n \n@bot.command(hidden=True)\nasync def ping(ctx):\n '''Pong! Get the bot's response time'''\n em = discord.Embed(color=discord.Color.gold())\n em.title = \"Pong!\"\n em.description = f'{bot.latency * 1000:.0f} ms'\n await ctx.send(embed=em)\n \n@bot.command()\n@commands.has_permissions(manage_messages=True)\nasync def prefix(ctx, prefix=None):\n \"\"\"Change Prefix of the server\"\"\"\n guildID = str(ctx.guild.id)\n if not prefix:\n return await ctx.send('Please provide a prefix for this command to work')\n try:\n await save_prefix(prefix, guildID)\n await ctx.send(f'Prefix `{prefix}` successfully saved (re-run this command to replace it)')\n except Exception as e:\n await ctx.send(f'Something went wrong\\nError Log: `str({e})`')\n \n@bot.command()\nasync def suggest(ctx, *, suggestion=None):\n \"\"\"suggest a feature to be added\"\"\"\n if not suggestion:\n em = discord.Embed(color=utils.random_color())\n em.title = f'Usage: {ctx.prefix}suggest '\n em.description ='suggest a feature to be added!'\n return await ctx.send(embed=em)\n ch = bot.get_channel(442059237519130625)\n em = discord.Embed(color=utils.random_color())\n em.description = str(suggestion)\n em.title = 'Suggestion'\n em.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)\n em.set_footer(text=\"Bot created By Nyan Pikachu#4148\")\n await ch.send(embed=em)\n await ctx.send('Thanks for your suggestion Soldier!')\n \n@bot.command()\nasync def bug(ctx, type=None, *, body=None):\n \"\"\"Report a bug to the Dev Team!\"\"\"\n possible_types = [\"gameplay\", \"map\", \"glitch\", \"hardware\", \"optimization\" , \"rendering\" ,\"networking\", \"connection\", \"ui\" , \"general\" ,\"sound\", \"other\"]\n \n if type not in possible_types:\n em = discord.Embed(color=utils.random_color())\n em.title = f'{ctx.prefix}bug '\n em.description ='Report a bug within BattleBit!'\n em.add_field(name='Types:', value=\", \".join(possible_types))\n return await ctx.send(embed=em)\n if not body:\n em = discord.Embed(color=utils.random_color())\n em.title = f'{ctx.prefix}bug '\n em.description ='Report a bug within BattleBit!'\n em.add_field(name='Types:', value=\", \".join(possible_types))\n return await ctx.send(embed=em)\n\n ch = bot.get_channel(442059253453160470)\n \n em = discord.Embed(color=utils.random_color())\n em.title = 'Bug Reported'\n em.description = 'A bug has been reported!'\n em.add_field(name='Bug Type:', value=type)\n em.add_field(name='Description:', value=body)\n em.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)\n em.set_footer(text=\"Bot created By Nyan Pikachu#4148\")\n await ch.send(embed=em)\n await ctx.send('Thanks for your report Soldier!')\n\n@bot.command(aliases=['ui'])\n@commands.guild_only()\nasync def userinfo(ctx, user: discord.Member=None):\n \"\"\"user info\"\"\"\n if not user:\n user = ctx.author\n embed = discord.Embed(title=\"{}'s info\".format(user.name), description=\"Here's what i found.\", color=utils.random_color())\n embed.add_field(name=\"Name\", value=user.name, inline=True)\n embed.add_field(name=\"ID\", value=user.id, inline=True)\n embed.add_field(name=\"Status\", value=user.status, inline=True)\n embed.add_field(name=\"Game\", value=str(user.activity.name))\n embed.add_field(name=\"Highest role\", value=user.top_role.name or \"Empty\")\n embed.add_field(name=\"Joined\", value=user.joined_at)\n embed.set_thumbnail(url=user.avatar_url)\n em.set_footer(text=\"Bot created By Nyan Pikachu#4148\")\n await ctx.send(embed=embed)\n \n@bot.command()\n@commands.guild_only()\nasync def serverinfo(ctx): \n \"\"\"server info\"\"\"\n embed = discord.Embed(name=f\"{user.name}'s info\", description=\"Here's what I found.\", color=utils.random_color())\n embed.set_author(name=\"Pika Bot\")\n embed.add_field(name=\"Name\", value=ctx.message.guild.name, inline=True)\n embed.add_field(name=\"ID\", value=ctx.message.guild.id, inline=True)\n embed.add_field(name=\"Roles\", value=len(ctx.message.guild.roles), inline=True)\n embed.add_field(name=\"Members\", value=len(ctx.message.guild.members))\n embed.add_field(name=\"Owner\", value=(ctx.message.guild.owner))\n embed.add_field(name=\"Created at\", value=(ctx.message.guild.created_at))\n embed.set_thumbnail(url=ctx.message.guild.icon_url)\n em.set_footer(text=\"Bot created By Nyan Pikachu#4148\")\n await ctx.send(embed=embed)\n\nbot.run(os.environ.get(\"TOKEN\"))\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"316930726","text":"train_mass = 22680\ntrain_acceleration = 10\ntrain_distance = 100\n\nbomb_mass = 1\n\ndef f_to_c (f_temp):\n c_temp = (f_temp-32) * 5/9\n return c_temp\n\ndef c_to_f(c_temp):\n f_temp = c_temp*(9/5) + 32\n return f_temp\n \ndef get_force(mass, acceleration):\n return mass*acceleration\n\n\ndef get_energy(mass, c=3*10**8):\n return mass*c\n\ndef get_work(mass, acceleration, distance):\n f = get_force(mass, acceleration)\n return f*distance\n\n \nf_in_celsius = f_to_c(100)\nc0_in_fahrenheit = c_to_f(0)\ntrain_mass = 1000000\ntrain_acceleration = 100\ntrain_force = get_force(train_mass, train_acceleration)\ndistance = 100\ntrain_work = get_work(train_mass, train_acceleration, distance)\n\n\nprint(\"The GE train supplies \" + str(train_force) + \" Newtons of force\")\nmass = 10\nc = 3*10**8\nbomb_mass = get_energy(mass, c)\n\nprint(bomb_mass)\n\n\n \n","sub_path":"physics.py","file_name":"physics.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"372277426","text":"import platform\nimport sys\n\nimport napari\nimport pytest\nimport qtpy\n\nfrom PartSeg.segmentation_analysis.main_window import MainWindow as AnalysisMainWindow\nfrom PartSeg.segmentation_mask.main_window import MainWindow as MaskMainWindow\n\nfrom .utils import CI_BUILD, GITHUB_ACTIONS\n\nnapari_warnings = napari.__version__ == \"0.3.4\" and platform.system() == \"Linux\" and sys.version_info.minor == 8\n\n\nclass TestAnalysisMainWindow:\n @pytest.mark.skipif((platform.system() == \"Linux\") and CI_BUILD, reason=\"vispy problem\")\n @pytest.mark.skipif(\n (platform.system() == \"Windows\") and GITHUB_ACTIONS and sys.version_info.minor == 7, reason=\"need to debug\"\n )\n @pytest.mark.skipif(qtpy.API_NAME == \"PySide2\", reason=\"PySide2 problem\")\n @pytest.mark.skipif(napari_warnings, reason=\"warnings fail test\")\n def test_opening(self, qtbot, tmpdir):\n main_window = AnalysisMainWindow(tmpdir, initial_image=False)\n qtbot.addWidget(main_window)\n main_window.main_menu.batch_processing_btn.click()\n main_window.main_menu.advanced_btn.click()\n\n\nclass TestMaskMainWindow:\n @pytest.mark.skipif((platform.system() == \"Linux\") and CI_BUILD, reason=\"vispy problem\")\n @pytest.mark.skipif(qtpy.API_NAME == \"PySide2\", reason=\"PySide2 problem\")\n @pytest.mark.skipif(napari_warnings, reason=\"warnings fail test\")\n def test_opening(self, qtbot, tmpdir):\n main_window = MaskMainWindow(tmpdir, initial_image=False)\n qtbot.addWidget(main_window)\n","sub_path":"package/tests/test_qt_part/test_main_windows.py","file_name":"test_main_windows.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"302290554","text":"emnlpHandler = open(\"emnlp_dict.txt\")\nemnlpDict = {}\nfor line in emnlpHandler:\n eComponents = line.split('\\t')\n emnlpDict[eComponents[0]] = eComponents[1].strip()\n\ndallasHandler = open(\"dallas_dict.txt\")\ndallasDict = {}\nfor line in dallasHandler:\n dComponents = line.split(' ')\n dallasDict[dComponents[0].split('\\t')[1]] = dComponents[2].strip()\n\nfHandleMisspell = open (\"misspell.txt\")\nfHandleCorrect = open('correct.txt')\nfHandleDic = open(\"dict.txt\")\nmisspell = []\ncorrect = []\ncorrection = []\ndictionary = []\ndallasDictSet = dallasDict.keys()\nemnlpDictSet = emnlpDict.keys()\n\nfor line in fHandleMisspell:\n misspell.append(line.strip())\n\nfor line in fHandleCorrect:\n correct.append(line.strip())\nfor line in fHandleDic:\n dictionary.append(line.strip())\ndictionary = set(dictionary)\n\nfor ele in misspell:\n if ele in dictionary:\n correction.append(ele)\n elif ele in dallasDictSet:\n correction.append(dallasDict[ele])\n elif ele in emnlpDictSet:\n correction.append(emnlpDict[ele])\n else:\n correction.append(ele)\n\ntCount = 0\ncCount = 0\nfor i in range(len(correction)):\n tCount += 1\n if correction[i] == correct[i]:\n cCount += 1\nratio = float(cCount) / tCount\nprint(ratio)","sub_path":"pro_1_program/twoDics.py","file_name":"twoDics.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"121868817","text":"from flask import Flask, render_template, redirect, \\\n url_for, request, flash, jsonify\napp = Flask(\n __name__\n)\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom database_setup import Base, Restaurant, MenuItem\n\nimport pdb\n\n# Create the DB engine\nengine = create_engine('sqlite:///restaurantmenu.db')\n# Bind the engine to the Base.metadata\nBase.metadata.bind = engine\n\n# Create the DBSession staging zone\nDBSession = sessionmaker(bind=engine)\n# Create a session for the DB\nsession = DBSession()\n\n\n# Making an API Endpoint for full JSON menu\n@app.route('/restaurants//menu/JSON/')\ndef restaurantMenuJSON(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(\n restaurant_id=restaurant_id).all()\n pdb.set_trace()\n return jsonify(MenuItems=[i.serialize for i in items])\n\n\n# Making an API Endpoint for single JSON menu item\n@app.route('/restaurants//menu//JSON/')\ndef MenuItemJSON(restaurant_id, menu_id):\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n item = session.query(MenuItem).filter_by(\n id=menu_id).one()\n return jsonify(MenuItem = item.serialize)\n\n\n@app.route('/')\n@app.route('/restaurants//')\ndef restaurantMenu(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n items = session.query(MenuItem).filter_by(\n restaurant_id=restaurant_id)\n return render_template(\n 'menu.html',\n page_title=restaurant.name,\n restaurant=restaurant,\n items=items\n )\n\n\n# Create a new Menu Item\n@app.route('/restaurants//new/',\n methods=['GET', 'POST'])\ndef newMenuItem(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n if request.method == 'POST':\n newItem = MenuItem(\n name=request.form['name'],\n restaurant_id=restaurant_id\n )\n session.add(newItem)\n session.commit()\n flash(\"New menu item: {name} created.\".format(name=newItem.name))\n return redirect(url_for(\n 'restaurantMenu',\n restaurant_id=restaurant_id\n ))\n else:\n return render_template(\n 'newmenuitem.html',\n page_title=\"Create a new item for \" + restaurant.name,\n restaurant=restaurant\n )\n\n\n# Edit a Menu Item\n@app.route('/restaurants//edit//',\n methods=['GET', 'POST'])\ndef editMenuItem(restaurant_id, menu_id):\n menuitem = session.query(MenuItem).filter_by(\n id=menu_id).one()\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n if request.method == 'POST':\n if request.form['name']:\n menuitem.name = request.form['name']\n session.add(menuitem)\n session.commit()\n flash(\"Menu Item: {name} is edited\".format(name=menuitem.name))\n return redirect(url_for(\n 'restaurantMenu',\n restaurant_id=restaurant_id\n ))\n else:\n return render_template(\n 'editmenuitem.html',\n page_title=\"Edit \" + menuitem.name + \" from \" + restaurant.name,\n restaurant=restaurant,\n menuitem=menuitem\n )\n\n\n# Delete a Menu Item\n@app.route('/restaurants//delete//',\n methods=['GET', 'POST'])\ndef deleteMenuItem(restaurant_id, menu_id):\n menuitem = session.query(MenuItem).filter_by(\n id=menu_id).one()\n restaurant = session.query(Restaurant).filter_by(\n id=restaurant_id).one()\n if request.method == 'POST':\n session.delete(menuitem)\n session.commit()\n flash(\"Menu Item: {name} is deleted.\".format(name=menuitem.name))\n return redirect(url_for(\n 'restaurantMenu',\n restaurant_id=restaurant_id\n ))\n else:\n return render_template(\n 'deletemenuitem.html',\n page_title=\"Are you sure you want to delete \" + menuitem.name,\n restaurant=restaurant,\n menuitem=menuitem\n )\n\n\nif __name__ == '__main__':\n app.secret_key = 'super_secret_key'\n app.debug = True\n app.run(host='0.0.0.0', port=5000)\n","sub_path":"vagrant/project/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"199937413","text":"from fastapi import FastAPI, Request, Depends, APIRouter, HTTPException\nfrom fastapi.encoders import jsonable_encoder\nfrom sqlalchemy.orm import Session\n\nfrom dependencies import get_db, templates, env\nfrom shop import crud\nfrom shop.models import Category\nfrom shop.recommender import Recommender\n\nrouter = APIRouter(\n prefix=\"/product\"\n)\n\n@router.get(\"/{category_slug}\")\ndef product_list(request:Request,category_slug:str, db:Session = Depends(get_db),\n page: int=1):\n products= crud.product_list(db=db,\n category_slug=category_slug)[16*(page-1):16*(page)]\n categories= db.query(Category).all()\n category= db.query(Category).filter_by(slug=category_slug).first()\n\n template= env.get_template('list.html')\n\n return templates.TemplateResponse(template,{\"request\": request,\n \"page\": page,\n \"products\": jsonable_encoder(products),\n \"category\":jsonable_encoder(category),\n \"categories\":jsonable_encoder(categories)})\n\n\n@router.get(\"/\")\ndef product_list(request:Request,category_slug:str=None, db:Session = Depends(get_db),\n page: int=1):\n products= crud.product_list(db=db,\n category_slug=category_slug)[16*(page-1):16*(page)]\n categories= db.query(Category).all()\n category= db.query(Category).filter_by(slug=category_slug).first()\n\n template= env.get_template('list.html')\n\n return templates.TemplateResponse(template,{\"request\": request,\n \"page\": page,\n \"products\": jsonable_encoder(products),\n \"category\":jsonable_encoder(category),\n \"categories\":jsonable_encoder(categories)})\n\n\n@router.get(\"/{product_id}/{product_slug}\")\ndef product_detail(request:Request, product_id:int, product_slug:str, db:Session=Depends(get_db)):\n product= jsonable_encoder(crud.product_detail(db=db,id=product_id,slug=product_slug))\n if product is None:\n raise HTTPException(status_code=404, detail=\"product does not exist\")\n\n recommender= Recommender()\n recommended_products= recommender.suggest_products_for(db=db,products=[product], max_result=4)\n\n template= env.get_template('detail.html')\n\n return templates.TemplateResponse(template,{\"request\":request,\n \"product\":jsonable_encoder(product),\n \"recommended_products\": recommended_products})\n\n","sub_path":"ECommerce_Deploy_On_Heroku/shop/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"389031569","text":"from flask import Blueprint, render_template, request, redirect, url_for\n\nfrom models import Post\nfrom forms import PostForm\n\nfrom db import db\n\nimport datetime\n\n\nfrom flask_login import login_required, current_user\nfrom flask_jwt_extended import jwt_required, get_current_user\n\nposts = Blueprint('posts', __name__, template_folder='templates')\n\n\n@posts.route('/create', methods=['POST', 'GET'])\n#@login_required\n@jwt_required()\ndef post_create():\n form = PostForm()\n \n if request.method == \"POST\":\n title = request.form.get('title')\n body = request.form.get('body')\n \n try:\n post = Post(title=title, body=body)\n db.session.add(post)\n db.session.commit()\n except:\n print(\"Veryy long traceback\")\n return redirect(url_for('posts.post_detail', slug=post.slug))\n \n # writing user request to database\n current_user.last_request_at = datetime.datetime.now()\n db.session.commit()\n \n return render_template('posts/post_create.html', form=form)\n\n@posts.route('/')\ndef posts_list():\n op = request.args.get('op')\n \n if op:\n posts = Post.query.filter(Post.title.contains(op) |\n Post.body.contains(op))\n else:\n posts = Post.query.order_by(Post.created.desc())\n return render_template('posts/posts.html', posts=posts)\n \n posts = Post.query.all()\n \n if current_user.is_authenticated:\n # writing user request to database\n current_user.last_request_at = datetime.datetime.now()\n db.session.commit()\n \n return render_template('posts/posts.html', posts=posts)\n\n@posts.route('/')\ndef post_detail(slug):\n post = Post.query.filter(Post.slug==slug).first()\n \n if current_user.is_authenticated:\n # writing user request to database\n current_user.last_request_at = datetime.datetime.now()\n db.session.commit()\n \n return render_template('posts/post_detail.html', post=post)\n\n@posts.route('/like//')\n#@login_required\n@jwt_required()\ndef like_action(post_id, action):\n post = Post.query.filter_by(id=post_id).first_or_404()\n if action == 'like':\n if post.today != str(datetime.date.today()):\n post.today = str(datetime.date.today())\n post.likes_today = 0\n \n post.likes_today +=1\n current_user.like_post(post)\n current_user.last_request_at = datetime.datetime.now()\n db.session.commit()\n if action == 'unlike':\n post.likes_today -=1\n current_user.unlike_post(post)\n current_user.last_request_at = datetime.datetime.now()\n db.session.commit()\n return redirect(request.referrer)\n","sub_path":"app_flask_login_alternative_JWT_token/posts/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"636957361","text":"from plots.heatmap_lib import *\n\nimport numpy as np\nfrom matplotlib import cm\nimport matplotlib\nimport seaborn as sns\nimport matplotlib.pylab as pyl\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FuncFormatter\nfrom matplotlib.patches import Rectangle\n\n\ndef draw_heatmap(\n result_image_name,\n input_files,\n baseline_files,\n titles,\n x_prob,\n y_prob,\n xcolticks=[],\n ycolticks=[],\n special_xlabel=None,\n special_ylabel=None\n):\n fig, axn = plt.subplots(2, len(input_files), sharey='row')\n\n file_mul = .32\n cbar_ax = fig.add_axes([ file_mul * len(input_files) + .11, 0.65, .03, .35])\n cbar_ax2 = fig.add_axes([ file_mul * len(input_files) + .11, 0.1, .03, .35])\n\n\n ticks = [0.5, 2.5, 4.5, 6.5, 8.5, 10.5]\n labels = ['$2^{0}$', '$2^{2}$', '$2^{4}$', '$2^{6}$', '$2^{8}$', '$2^{10}$']\n labels_neg = ['$2^{0}$', '$2^{-2}$', '$2^{-4}$', '$2^{-6}$', '$2^{-8}$', '$2^{-10}$']\n\n max_t = 0\n min_t = 1000\n max_n = 0\n min_n = 1000\n best_vals = []\n\n for i, file in enumerate(input_files):\n (time_hmq, nodes_hmq) = find_avg_hmq(baseline_files[i])\n #print(time_div, nodes_div)\n (hm, hm_n) = heatmap2array(file, time_hmq, nodes_hmq)\n max_t_id_i = 0\n max_t_id_j = 0\n max_t_local = 0\n for k in range(0, len(hm)):\n for j in range(0, len(hm[k])):\n val = hm[k][j]\n if val > max_t:\n max_t = val\n if val > max_t_local:\n max_t_local = val\n max_t_id_i = k\n max_t_id_j = j\n if val < min_t:\n min_t = val\n if hm_n[k][j] > max_n:\n max_n = hm_n[k][j]\n if hm_n[k][j] < min_n:\n min_n = hm_n[k][j]\n cmap = matplotlib.colors.LinearSegmentedColormap.from_list(\"\", [\"#990000\", \"#ffff00\", \"#38761d\"])\n cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list(\"\", [\"#38761d\", \"#ffff00\", \"#990000\"])\n\n\n print(titles[i] + \": {\" + str(2 ** max_t_id_j) + \", \" + str(2 **max_t_id_i) + \"} \" + str(hm[max_t_id_i][max_t_id_j]))\n fmt = lambda x, pos: '{:.1f}'.format(round(x, 1))\n\n thm = sns.heatmap(hm, ax=axn[0][i], center=1, cmap=cmap,\n vmin=min_t, vmax=max_t,\n linewidths=.7, square=True, cbar_ax=cbar_ax,\n cbar_kws={\n 'format': FuncFormatter(fmt),\n 'label' : 'Speedup',\n 'ticks' : [min_t, *xcolticks, max_t]\n }\n )\n\n nhm = sns.heatmap(hm_n, ax=axn[1][i], center=1, cmap=cmap2,\n vmin=min_n, vmax=max_n,\n linewidths=.7, square=True, cbar_ax=cbar_ax2,\n cbar_kws={\n 'format': FuncFormatter(fmt),\n 'label' : 'Work Increase',\n 'ticks' : [min_n, *ycolticks, max_n]\n }\n )\n thm.xaxis.set_ticks_position('top')\n nhm.xaxis.set_ticks_position('top')\n\n thm.add_patch(Rectangle((max_t_id_j, max_t_id_i), 1, 1, fill=False, edgecolor='black', lw=1.2))\n nhm.add_patch(Rectangle((max_t_id_j, max_t_id_i), 1, 1, fill=False, edgecolor='black', lw=1.2))\n\n axn[0][i].set_xticks(ticks)\n axn[1][i].set_xticks(ticks)\n numbers_font_size = 11\n axn[0][i].set_xticklabels(labels_neg if x_prob else labels, rotation=30, fontdict={'fontsize': numbers_font_size})\n axn[1][i].set_xticklabels(labels_neg if x_prob else labels, rotation=30, fontdict={'fontsize': numbers_font_size})\n\n\n axn[0][i].set_yticks(ticks)\n axn[1][i].set_yticks(ticks)\n xl = labels_neg if y_prob else labels\n axn[0][i].set_yticklabels(xl, rotation=30, fontdict={'fontsize': numbers_font_size})\n axn[1][i].set_yticklabels(xl, rotation=30, fontdict={'fontsize': numbers_font_size})\n\n\n if special_xlabel is None:\n axn[0][i].set_xlabel('delete: $p_{change}$' if x_prob else 'delete: batch size', fontsize=12)\n else:\n axn[0][i].set_xlabel(special_xlabel, fontsize=12)\n best_vals.append((str(2 ** max_t_id_i) if not y_prob else f'1/{2 ** max_t_id_i}',\n str(2 ** max_t_id_j) if not x_prob else f'1/{2 ** max_t_id_j}',\n '{:.2f}'.format(hm[max_t_id_i][max_t_id_j]),\n '{:.2f}'.format(hm_n[max_t_id_i][max_t_id_j])))\n\n\n fig.axes[-1].yaxis.label.set_size(15)\n fig.axes[-2].yaxis.label.set_size(15)\n for i in range(0, len(input_files)):\n axn[0][i].set_title(titles[i], fontsize=13, pad=17)\n fig.tight_layout(rect=[0, 0, len(input_files) * file_mul + .1, 1.15], pad=0)\n\n\n if special_ylabel is None:\n axn[0][0].set_ylabel('insert: $p_{change}$' if y_prob else 'insert: batch size', fontsize=12)\n axn[1][0].set_ylabel('insert: $p_{change}$' if y_prob else 'insert: batch size', fontsize=12)\n else:\n axn[0][0].set_ylabel(special_ylabel, fontsize=12)\n axn[1][0].set_ylabel(special_ylabel, fontsize=12)\n\n\n # Write table in latex\n f = open(result_image_name + \".tex\", \"w\")\n f.write(\"\\\\begin{table}[h]\\n\")\n f.write(\"\\\\centring\\n\")\n aaa = ''.join(['|c' for x in titles]) + '|'\n f.write(\"\\\\begin{tabular}{ |c\" + aaa + \" }\\n\")\n f.write(\"\\\\hline\\n\")\n f.write(' & ' + ' & '.join([f'\\\\large{{\\\\textbf{{{t[0:len(t)-3]}}}}}' if t.endswith('WEST') else f'\\\\large{{\\\\textbf{{{t}}}}}' for t in titles]) + ' \\\\\\\\\\n')\n rrr=['\\insprob{} & ' if y_prob else '\\insbatch{} & ',\n '\\delprob{} & ' if x_prob else '\\delbatch{} & ',\n '\\\\speed{} & ',\n '\\workinc{} & ']\n fs = open('mq_best_parameters.csv', 'a')\n for i in range(4):\n f.write(\"\\\\hline\\n\")\n f.write(rrr[i] + ' & '.join([str(x[i]) for x in best_vals]) + ' \\\\\\\\\\n')\n fs.write(result_image_name.split('_')[0] + ',' + ','.join([str(x[2]) for x in best_vals]) + '\\n')\n fs.close()\n f.write(\"\\\\hline\\n\")\n f.write(\"\\\\end{tabular}\\n\")\n f.write(\"\\\\vspace{0.3em}\\n\")\n f.write(\"\\\\caption{TODO }\\n\")\n f.write(\"\\\\label{table:todo}\\n\")\n f.write(\"\\\\end{table}\\n\")\n f.close()\n plt.subplots_adjust(hspace=0)\n plt.show()\n fig.savefig(result_image_name + \".png\", bbox_inches=\"tight\", transparent=True)\n","sub_path":"scripts/plots/mq_heatmap.py","file_name":"mq_heatmap.py","file_ext":"py","file_size_in_byte":6547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"352244366","text":"# imports webbrowser module\nimport webbrowser\n\n\nclass Movie():\n \"\"\"Creates the class Movie. This is used to store information about a\n users favorite movie. Each instance of the class will store the title,\n storyline, cover image, and trailer of the movie. This allows the user\n to showcase the movies on an associated website.\"\"\"\n\n VALID_RATINGS = [\"G\", \"PG\", \"PG-13\", \"R\"]\n\n \"\"\"defines init function, creates memory space for new\n instance of class Movie\"\"\"\n def __init__(self, movie_title, movie_storyline,\n poster_image, trailer_youtube):\n self.title = movie_title\n self.storyline = movie_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n\n \"\"\"launches web browser to view movie trailer\"\"\"\n def show_trailer(self):\n webbrowser.open(self.trailer_youtube_url)\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"549277607","text":"class Sales_Department():\n\n def __init__(self):\n\n self.file = []\n\n for x in (open('sales.txt', 'r')):\n self.file.append(x)\n\n def sales_info(self):\n print(\"\")\n for line in self.file:\n lineas = line.split(',')\n print(\"Nombre: \" + lineas[0] + \", \" + \"Monto:\" + lineas[1] + \", \" + \"Descripcion:\" + lineas[2] + \", \" + \"Forma de pago:\" + lineas[3])\n print(\"\\n\")\n\nif __name__ == \"__main__\":\n department = Sales_Department()\n department.sales_info()","sub_path":"58157 - Graffigna, Santiago/TP1/Ej16.py","file_name":"Ej16.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"428963746","text":"# -*- coding=utf-8 -*-\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef read_header(head_file):\n header_dict = {}\n\n header_txt = open(head_file)\n for header in header_txt.readlines():\n key, val = header.strip().split(':')\n header_dict[key.strip()] = val.strip()\n\n return header_dict\n\n\ndef get_soup(head_file, payload, url):\n client = requests.session()\n comment = client.post(url, headers=read_header(head_file), data=payload)\n comment.encoding = 'utf8'\n comment_soup = BeautifulSoup(comment.text, 'lxml')\n\n # table = comment_soup.find_all('count')\n # print()\n return comment_soup\n\n\ndef fenxi(head_file, payload, url):\n comment_soup = get_soup(head_file, payload, url)\n if comment_soup.find('div', class_=\"IcpMain02\").text != '\\n':\n\n # 获取各条目的名称,未完工。。。\n # biaodan =comment_soup.find('div', class_=\"IcpMain02\").find('thead').find('tr')\n # for b in biaodan:\n # print(b)\n\n # 应该是用上面注释掉的自动扒取网页上的标题,不能这样。。\n l1 = ['主办单位名称', '单位性质', '网站备案/许可证号', '网站名称', '网站首页网址', '审核时间', '记录时间', '变更项', '变更记录']\n\n neirong = comment_soup.find('tbody', id=\"result_table\")\n # 若有网站多次变更,就会有多条tr项,第一条就是最新的,要取得所有需要再次使用for?\n l2 = [a.text for a in neirong.find('tr')]\n\n res_dict = dict(zip(l1, l2))\n print(res_dict)\n return\n else:\n print('未备案')\n return\n\n\nif __name__ == \"__main__\":\n domain = 'qytang.com'\n # 这是使用 站长之家 查询 其他的重扒\n url = 'http://icp.chinaz.com/record/' + domain\n payload = 't=2&host=' + domain\n\n # print(get_soup('domain_status_header.txt', payload, url))\n # fenxi('domain_status_header.txt', payload, url)\n\n import time\n\n # lineLength = 20\n # delaySeconds = 0.25\n # frontSymbol = '='\n # frontSymbol2 = ['—', '\\\\', '|', '/']\n # backSymbol = ' '\n #\n # for i in range(10):\n # lineTmpla = \"{:%s<%s} {} {:<2}\" % (backSymbol, lineLength)\n # print(lineTmpla)\n # for j in range(lineLength):\n # tmpSymbol = frontSymbol2[j % (len(frontSymbol2))]\n # print(\"\\r\" + lineTmpla.format(frontSymbol * j, tmpSymbol, j), end='')\n # time.sleep(delaySeconds)\n\n # t = 5\n # while True:\n # if t >= 0:\n # print('\\r'+'请务必等待{}秒后再操作!!'.format(t), end='')\n # t -= 1\n # time.sleep(1)\n # else:\n # print('\\n')\n # break\n\n table_length = 14\n counter = 0\n for a in range(table_length):\n counter += 1\n\n per = int((counter / table_length) * 100)\n frontsymbol = '='\n backsymbol = ' '\n linetmpla = \"{:%s<%s} {:<2}\" % (backsymbol, 33)\n for j in range(table_length):\n print('\\r' + linetmpla.format(frontsymbol * int(per / 3), per) + '%', end='')\n time.sleep(0.4)\n\n\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"561778554","text":"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n\nfrom nipype.interfaces.niftyreg import (no_niftyreg, get_custom_path,\n RegMeasure)\nfrom nipype.testing import skipif, example_data\nimport pytest\nimport os\n\n\n@skipif(no_niftyreg(cmd='reg_measure'))\ndef test_reg_measure():\n\n # Create a reg_measure object\n nr = RegMeasure()\n\n # Check if the command is properly defined\n assert nr.cmd == get_custom_path('reg_measure')\n\n # test raising error with mandatory args absent\n with pytest.raises(ValueError):\n nr.run()\n\n # Assign some input data\n ref_file = example_data('im1.nii')\n flo_file = example_data('im2.nii')\n nr.inputs.ref_file = ref_file\n nr.inputs.flo_file = flo_file\n nr.inputs.measure_type = 'lncc'\n nr.inputs.omp_core_val = 4\n\n cmd_tmp = '{cmd} -flo {flo} -lncc -omp 4 -out {out} -ref {ref}'\n expected_cmd = cmd_tmp.format(\n cmd=get_custom_path('reg_measure'),\n flo=flo_file,\n out=os.path.join(os.getcwd(), 'im2_lncc.txt'),\n ref=ref_file)\n\n assert nr.cmdline == expected_cmd\n","sub_path":"nipype/interfaces/niftyreg/tests/test_Reg_Measure.py","file_name":"test_Reg_Measure.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"175385781","text":"#Cyclic Structure 循环结构\nweeks=['星期一','星期二','星期三','星期四','星期五','星期六','星期日']\n#for day in weeks:\n #print (day)\n\ni=0;\nwhile i<7:\n print(weeks[i]+'\\t'+str(i));\n if '星期一' == weeks[i]:\n print('是星期1')\n i = i + 1\n\n","sub_path":"20171031/CyclicStructure.py","file_name":"CyclicStructure.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"246238059","text":"# y = 2x+1, length = sqrt(17/5), make square\n\nfrom turtle import *\nfrom math import sqrt\n\n# Initialisation\nscr = Screen()\nscr.setup(800,600)\ndelay(0)\nt = Turtle()\nt.speed(0)\nt.ht()\n\nm = 50 # multiplier\n\n# Grid drawing\nfor x in range(100):\n if ((x-50) == 0):\n t.color(\"black\")\n else:\n t.color(\"grey\")\n t.penup()\n t.goto(-800, (x-50)*m)\n t.pendown()\n t.goto(800, (x-50)*m)\n t.penup()\n t.goto((x-50)*m, -800)\n t.pendown()\n t.goto((x-50)*m, 800)\n\n# Calculations to get the square coordinates and stuff\n# Data input\nwhile(True):\n grad = input(\"Gradient: \")\n if (grad != \"\") and (grad.isdigit()):\n grad = int(grad)\n if (grad >= 0):\n leng = input(\"Side length: \")\n if (leng != \"\"):\n leng = int(leng)\n ycor = input(\"X Intercept: \")\n if (ycor != \"\"):\n ycor = int(ycor)\n break\n else:\n print(\"Please enter a proper Y coordinate\")\n else:\n print(\"Please enter a positive gradient\")\n else:\n print(\"Please enter a proper gradient\")\n\nris = grad\nrun = 1\n\na = (run**2)\n\n# Draw square with coordinates\nt.color(\"black\")\nt.width(2)\nt.penup()\nt.goto(m,ycor*m)\nt.pendown()\nt.goto((sqrt(17)/5) * m, (2*sqrt(17)/5+ycor) * m)\nt.goto((-sqrt(17)/5) * m, (3*sqrt(17)/5+ycor) * m)\nt.goto((-2*sqrt(17)/5) * m, (sqrt(17)/5+ycor) * m)\nt.goto(m,ycor*m)\n","sub_path":"Finding Square/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"367309518","text":"\"\"\"Factory example\"\"\"\n\nfrom _3_factory_abstract_file_writer import AbstractFileWriter\nfrom _4_factory_file_writers import TextFileWriter, BinaryFileWriter\n\n\nclass FileManager(object):\n file_writers = []\n\n @classmethod\n def register_writer(self, writer: AbstractFileWriter):\n self.file_writers.append(writer)\n\n @classmethod\n def write(cls, path, value):\n file_writer = next(\n (io for io in cls.file_writers if type(value) in io.supported_types()), None)\n\n if not file_writer:\n raise NotImplementedError(\n 'File writer for type \"%s\" is not implemented' % type(value))\n\n file_writer(path, value).write()\n\n\nFileManager.register_writer(BinaryFileWriter)\nFileManager.register_writer(TextFileWriter)\n\n# 'test'.encode() - binary data\nFileManager.write('file_path', 'test'.encode())\n","sub_path":"PythonFlow_March2018/Examples/_06_Python_Design_patterns/_5_factory_file_manager.py","file_name":"_5_factory_file_manager.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"156800943","text":"'''\r\nCreated on Nov 4, 2014\r\n\r\n@author: David\r\n'''\r\n\r\nfrom __future__ import print_function\r\nimport copy\r\nimport json\r\nimport math\r\nimport random\r\nimport sys\r\nimport time\r\n\r\ndef main(argv):\r\n start = time.time()\r\n \r\n bayesNetFile = open(argv[0], 'r')\r\n bayesNetList = json.load(bayesNetFile)\r\n bayesNetFile.close()\r\n bayesNet = []\r\n for line in bayesNetList:\r\n bayesNet.append(buildNode(line))\r\n queryFile = open(argv[1], 'r')\r\n query = buildQuery(json.load(queryFile))\r\n queryFile.close()\r\n totalSamples = int(argv[2])\r\n sampleList = []\r\n i = 0\r\n while (i < totalSamples):\r\n sample = {}\r\n for nodes in bayesNet:\r\n prob = nodes.getProb(sample)\r\n if random.random() < prob:\r\n sample[nodes.name] = True\r\n else:\r\n sample[nodes.name] = False\r\n if nodes.name in query.evidenceVar.keys():\r\n if sample[nodes.name] != query.evidenceVar[nodes.name]:\r\n sample = None\r\n break\r\n if sample:\r\n sampleList.append(sample)\r\n i+=1\r\n if not sampleList:\r\n print(\"[]\")\r\n exit()\r\n tableList = []\r\n tableList = buildTable(tableList, [], len(query.queryVar))\r\n tableList.insert(0, query.queryVar)\r\n results = []\r\n for i in range(1, len(tableList)):\r\n results.append(0)\r\n for index in range(1, len(tableList)):\r\n for sample in sampleList:\r\n i = 0\r\n count = True\r\n while (i < len(tableList[index])):\r\n if sample[tableList[0][i]] != tableList[index][i]:\r\n count = False\r\n break\r\n i+=1\r\n if count:\r\n results[index - 1]+=1\r\n numSamples = len(sampleList)\r\n for i in range(len(results)):\r\n results[i] = float(results[i]) / numSamples\r\n print(results)\r\n \r\n stop = time.time()\r\n samplesPerSec = totalSamples/(stop - start)\r\n print (samplesPerSec, file=sys.stderr)\r\n \r\ndef buildNode(input):\r\n return Node(input[0], input[1], input[2])\r\n\r\ndef buildQuery(input):\r\n return Query(input[0], input[1], input[2])\r\n\r\ndef buildTable(table, item, totalVars):\r\n if len(item) == totalVars:\r\n return item\r\n new_item = copy.deepcopy(item)\r\n new_item.append(True)\r\n new_item = buildTable(table, new_item, totalVars)\r\n if new_item:\r\n table.append(new_item)\r\n new_item = copy.deepcopy(item)\r\n new_item.append(False)\r\n new_item = buildTable(table, new_item, totalVars)\r\n if new_item:\r\n table.append(new_item)\r\n if len(table) == int(math.pow(2, totalVars)) and not item:\r\n return table\r\n \r\nclass Node():\r\n def __init__(self, name, parents, probs):\r\n self.name = name\r\n self.parents = parents\r\n self.probs = probs\r\n \r\n def getProb(self, sample):\r\n if (self.parents):\r\n index = 0\r\n for i in range(len(self.parents)):\r\n if sample[self.parents[i]]:\r\n index += math.pow(2, len(self.parents) - i - 1)\r\n index = int(math.pow(2, len(self.parents)) - index - 1)\r\n return self.probs[index]\r\n else:\r\n return self.probs[0]\r\n\r\nclass Query():\r\n def __init__(self, queryList, evidenceList, valueList):\r\n self.queryVar = queryList\r\n self.evidenceVar = {}\r\n for i in range(len(evidenceList)):\r\n self.evidenceVar[evidenceList[i]] = valueList[i]\r\n \r\nif __name__ == '__main__':\r\n main(sys.argv[1:])","sub_path":"rejectionsampler.py","file_name":"rejectionsampler.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"420901584","text":"import media\r\nimport fresh_tomatoes\r\n\r\n\"\"\"Create movie objects using instances from the Movie class.\r\nArgs:\r\n Title: Movie title\r\n Image: Movie poster image link\r\n Trailer: Youtube trailer link\r\n\"\"\"\r\ntoy_story = media.Movie(\"Toy story 3\",\r\n \"https://upload.wikimedia.org/wikipedia/en/6/69/Toy_Story_3_poster.jpg\",\r\n \"https://www.youtube.com/watch?v=ZZv1vki4ou4\")\r\n\r\nedge_of_tomorrow = media.Movie(\"Edge of Tomorrow\",\r\n \"https://upload.wikimedia.org/wikipedia/en/f/f9/Edge_of_Tomorrow_Poster.jpg\",\r\n \"https://www.youtube.com/watch?v=yUmSVcttXnI\")\r\n\r\nalien_Covenant = media.Movie(\"Alien Covenant\",\r\n \"https://upload.wikimedia.org/wikipedia/en/3/33/Alien_Covenant_Teaser_Poster.jpg\",\r\n \"https://www.youtube.com/watch?v=svnAD0TApb8\")\r\n\r\ni_robot = media.Movie(\"I, Robot\",\r\n \"https://upload.wikimedia.org/wikipedia/en/3/3b/Movie_poster_i_robot.jpg\",\r\n \"https://www.youtube.com/watch?v=rL6RRIOZyCM\")\r\n\r\nminority_report = media.Movie(\"Minority Report\",\r\n \"https://upload.wikimedia.org/wikipedia/en/4/44/Minority_Report_Poster.jpg\",\r\n \"https://www.youtube.com/watch?v=aGWQYgZZEEQ\")\r\n\r\nequilibrium = media.Movie(\"Equilibrium\",\r\n \"https://upload.wikimedia.org/wikipedia/en/f/f6/Equilibriumposter.jpg\",\r\n \"https://www.youtube.com/watch?v=raleKODYeg0\")\r\n\r\n\"\"\"Create list of movie objects.\"\"\"\r\nmovies = [toy_story, edge_of_tomorrow, alien_Covenant, i_robot, minority_report, equilibrium]\r\n\r\n\"\"\"Pass list of movies to supplied fresh_tomatoes file to display in web browser.\"\"\"\r\nfresh_tomatoes.open_movies_page(movies)\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"115837623","text":"\nimport numpy as np\n\n\nf = open('day10_input.txt')\ntext = f.readlines()\nf.close()\n\nxs = []\nys = []\nvxs = []\nvys = []\nfor line in text:\n line = line.strip()\n x = int(line[10:16])\n y = int(line[17:24])\n vx = int(line[-7:-5])\n vy = int(line[-3:-1])\n xs.append(x)\n ys.append(y)\n vxs.append(vx)\n vys.append(vy)\n\nlength = max(ys) - min(ys)\nprev = 10**9\nsteps = 0\nwhile length < prev:\n steps += 1\n prev = length\n for i in range(len(xs)):\n xs[i] += vxs[i]\n ys[i] += vys[i]\n length = max(ys) - min(ys)\n\nfor i in range(len(xs)):\n xs[i] -= vxs[i]\n ys[i] -= vys[i]\n\nleftmost = min(xs)\ntopmost = min(ys)\nfor i in range(len(xs)):\n xs[i] -= leftmost\n ys[i] -= topmost\n\nmessage = np.array([[' ' for _ in range(max(xs) + 1)] for __ in range(max(ys) + 1)])\nfor i in range(len(xs)):\n message[ys[i], xs[i]] = '#'\n\nfor row in range(message.shape[0]):\n print(''.join(message[row, :]))\n","sub_path":"2018/day10-1.py","file_name":"day10-1.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"218858000","text":"import numpy as np\r\nfrom pyquil.quil import Program\r\nfrom pyquil.api import QVMConnection\r\n\r\n#==============================================================================\r\n# Initilization\r\n#==============================================================================\r\nqvm = QVMConnection()\r\nprog = Program()\r\n\r\n#==============================================================================\r\n# Qubit\r\n#==============================================================================\r\nfrom pyquil.gates import I\r\nprog.inst(I(1), I(0))\r\n\r\n# Print current quantum state of the system\r\nstate = qvm.wavefunction(prog)\r\nprint(\"The system is in state: {}\".format(state))\r\n\r\n# Probabilities\r\nprint(\"Probability that after measurement the system is in state 00 {}\".format(abs(state.amplitudes[0])**2))\r\nprint(\"Probability that after measurement the system is in state 01 {}\".format(abs(state.amplitudes[1])**2))\r\nprint(\"Probability that after measurement the system is in state 10 {}\".format(abs(state.amplitudes[2])**2))\r\nprint(\"Probability that after measurement the system is in state 11 {}\".format(abs(state.amplitudes[3])**2))\r\n\r\n#==============================================================================\r\n# Quantum gates\r\n#==============================================================================\r\nfrom pyquil.gates import X\r\nprog.inst(X(0))\r\n\r\n# Print current quantum state of the system\r\nstate = qvm.wavefunction(prog)\r\nprint(\"The system is in state: {}\".format(state))\r\n\r\n# Swap gate\r\nfrom pyquil.gates import SWAP\r\nprog.inst(SWAP(1, 0))\r\n\r\n# Print current quantum state of the system\r\nstate = qvm.wavefunction(prog)\r\nprint(\"The system is in state: {}\".format(state))\r\n\r\n# Hadamard gate\r\nfrom pyquil.gates import H\r\nprog.inst(H(1))\r\n\r\n# Print current quantum state of the system\r\nstate = qvm.wavefunction(prog)\r\nprint(\"The system is in state: {}\".format(state))\r\n\r\n#==============================================================================\r\n# Measurment\r\n#==============================================================================\r\nprog.measure(qubit_index=1, classical_reg=0)\r\nprog.measure(qubit_index=0, classical_reg=1)\r\n\r\nret = qvm.run(prog, classical_addresses=[0, 1])\r\nprint(\"The first qubit is in state |{}> and second in state |{}> after measurment\".format(*ret[0]))\r\n\r\nret = qvm.run(prog, classical_addresses=[0, 1], trials=1000)\r\nfreq_first_is_0 = [trial[0] for trial in ret].count(0) / 1000\r\nfreq_first_is_1 = [trial[0] for trial in ret].count(1) / 1000\r\nfreq_second_is_0 = [trial[1] for trial in ret].count(0) / 1000\r\nprint(\"Relative frequency of measuring the first qubit in |0> state: {}\".format(freq_first_is_0))\r\nprint(\"Relative frequency of measuring the first qubit in |1> state: {}\".format(freq_first_is_1))\r\nprint(\"Relative frequency of measuring the second qubit in |0> state: {}\".format(freq_second_is_0))","sub_path":"introduction_riggeti.py","file_name":"introduction_riggeti.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"96484664","text":"# Copyright (C) 2019 Huang MaChi at China Mobile Communication\n# Corporation, Zhanjiang, Guangdong, China.\n# Copyright (C) 2016 Li Cheng at Beijing University of Posts\n# and Telecommunications. www.muzixing.com\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom mininet.net import Mininet\nfrom mininet.node import Controller, RemoteController\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel\nfrom mininet.link import Link, Intf, TCLink\nfrom mininet.topo import Topo\n\nimport os\nimport logging\nimport argparse\nimport time\nimport signal\nfrom subprocess import Popen\nfrom multiprocessing import Process\n\nimport sys\nparentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.insert(0, parentdir)\nimport iperf_peers\n\n\nparser = argparse.ArgumentParser(description=\"Parameters importation\")\nparser.add_argument('--den', dest='density', type=int, default=15, help=\"Host density\")\nparser.add_argument('--cpu', dest='cpu', type=float, default=2.0, help=\"Total CPU to allocate to hosts\")\nparser.add_argument('--duration', dest='duration', type=int, default=60, help=\"Duration (sec) for each iperf traffic generation\")\nparser.add_argument('--dir', dest='output_dir', help=\"Directory to store outputs\")\nparser.add_argument('--k_paths', dest='kpaths', type=int, default=4, help=\"Number of alternative paths\")\nargs = parser.parse_args()\n\n\nclass IPMAN(Topo):\n\t\"\"\"\n\t\tClass of IPMAN Topology.\n\t\"\"\"\n\tGZSwitchList = []\n\tCdnSwitchList = []\n\tCoreSwitchList = []\n\tAggSwitchList = []\n\tEdgeSwitchList = []\n\tHostList = []\n\tSerList = []\n\n\tdef __init__(self, density):\n\t\tself.density = density\n\t\tself.iGZSwitch = 2\n\t\tself.iCdnSwitch = 1\n\t\tself.iCoreLayerSwitch = 2\n\t\tself.iAggLayerSwitch = 2\n\t\tself.iEdgeLayerSwitch = 2\n\t\tself.iHost = self.iEdgeLayerSwitch * density\n\t\tself.iServer = 3\n\n\t\t# Topo initiation\n\t\tTopo.__init__(self)\n\n\tdef createNodes(self):\n\t\tself.createGZSwitch(self.iGZSwitch)\n\t\tself.createCdnSwitch(self.iCdnSwitch)\n\t\tself.createCoreLayerSwitch(self.iCoreLayerSwitch)\n\t\tself.createAggLayerSwitch(self.iAggLayerSwitch)\n\t\tself.createEdgeLayerSwitch(self.iEdgeLayerSwitch)\n\t\tself.createHost(self.iHost)\n\t\tself.createServer(self.iServer)\n\n\tdef _addSwitch(self, number, level, switch_list):\n\t\t\"\"\"\n\t\t\tCreate switches.\n\t\t\"\"\"\n\t\tfor i in xrange(1, number+1):\n\t\t\tPREFIX = str(level) + \"00\"\n\t\t\tif i >= 10:\n\t\t\t\tPREFIX = str(level) + \"0\"\n\t\t\tswitch_list.append(self.addSwitch(PREFIX + str(i)))\n\n\tdef createGZSwitch(self, NUMBER):\n\t\tself._addSwitch(NUMBER, 1, self.GZSwitchList)\n\n\tdef createCdnSwitch(self, NUMBER):\n\t\tself._addSwitch(NUMBER, 5, self.CdnSwitchList)\n\n\tdef createCoreLayerSwitch(self, NUMBER):\n\t\tself._addSwitch(NUMBER, 2, self.CoreSwitchList)\n\n\tdef createAggLayerSwitch(self, NUMBER):\n\t\tself._addSwitch(NUMBER, 3, self.AggSwitchList)\n\n\tdef createEdgeLayerSwitch(self, NUMBER):\n\t\tself._addSwitch(NUMBER, 4, self.EdgeSwitchList)\n\n\tdef createHost(self, NUMBER):\n\t\t\"\"\"\n\t\t\tCreate hosts.\n\t\t\"\"\"\n\t\tfor i in xrange(1, NUMBER+1):\n\t\t\tif i >= 100:\n\t\t\t\tPREFIX = \"h\"\n\t\t\telif i >= 10:\n\t\t\t\tPREFIX = \"h0\"\n\t\t\telse:\n\t\t\t\tPREFIX = \"h00\"\n\t\t\tself.HostList.append(self.addHost(PREFIX + str(i), cpu=args.cpu/float(self.iHost + self.iServer)))\n\n\tdef createServer(self, NUMBER):\n\t\t\"\"\"\n\t\t\tCreate servers.\n\t\t\"\"\"\n\t\tfor i in xrange(1, NUMBER+1):\n\t\t\tif i >= 100:\n\t\t\t\tPREFIX = \"ser\"\n\t\t\telif i >= 10:\n\t\t\t\tPREFIX = \"ser0\"\n\t\t\telse:\n\t\t\t\tPREFIX = \"ser00\"\n\t\t\tself.SerList.append(self.addHost(PREFIX + str(i), cpu=args.cpu/float(self.iHost + self.iServer)))\n\n\tdef createLinks(self, bw_gz=10, bw_cdn=10, bw_c2a=10, bw_a2e=10, bw_e2h=10):\n\t\t\"\"\"\n\t\t\tAdd network links.\n\t\t\"\"\"\n\t\t# Servers to Switches\n\t\tself.addLink(self.SerList[0], self.GZSwitchList[0], bw=bw_gz, max_queue_size=1000) # use_htb=False\n\t\tself.addLink(self.SerList[1], self.GZSwitchList[1], bw=bw_gz, max_queue_size=1000) # use_htb=False\n\t\tself.addLink(self.SerList[2], self.CdnSwitchList[0], bw=bw_cdn, max_queue_size=1000) # use_htb=False\n\n\t\t# Edge to Host\n\t\tfor x in xrange(0, self.iEdgeLayerSwitch):\n\t\t\tfor i in xrange(0, self.density):\n\t\t\t\tself.addLink(\n\t\t\t\t\tself.EdgeSwitchList[x],\n\t\t\t\t\tself.HostList[self.density * x + i],\n\t\t\t\t\tbw=bw_e2h, max_queue_size=1000) # use_htb=False\n\t\t# Core to CDN\n\t\tself.addLink(self.CoreSwitchList[0], self.CdnSwitchList[0], bw=bw_cdn, max_queue_size=1000) # use_htb=False\n\t\tself.addLink(self.CoreSwitchList[1], self.CdnSwitchList[0], bw=bw_cdn, max_queue_size=1000) # use_htb=False\n\n\t\t# GZ to Core\n\t\tself.addLink(self.GZSwitchList[0], self.CoreSwitchList[0], bw=bw_gz, max_queue_size=1000) # use_htb=False\n\t\tself.addLink(self.GZSwitchList[1], self.CoreSwitchList[1], bw=bw_gz, max_queue_size=1000) # use_htb=False\n\n\t\t# Core to Agg\n\t\tfor i in self.CoreSwitchList:\n\t\t\tfor j in self.AggSwitchList:\n\t\t\t\tself.addLink(i, j, bw=bw_c2a, max_queue_size=1000) # use_htb=False\n\n\t\t# Agg to Edge\n\t\tfor i in self.AggSwitchList:\n\t\t\tfor j in self.EdgeSwitchList:\n\t\t\t\tself.addLink(i, j, bw=bw_a2e, max_queue_size=1000) # use_htb=False\n\n\tdef set_ovs_protocol_13(self,):\n\t\t\"\"\"\n\t\t\tSet the OpenFlow version for switches.\n\t\t\"\"\"\n\t\tself._set_ovs_protocol_13(self.GZSwitchList)\n\t\tself._set_ovs_protocol_13(self.CdnSwitchList)\n\t\tself._set_ovs_protocol_13(self.CoreSwitchList)\n\t\tself._set_ovs_protocol_13(self.AggSwitchList)\n\t\tself._set_ovs_protocol_13(self.EdgeSwitchList)\n\n\tdef _set_ovs_protocol_13(self, sw_list):\n\t\tfor sw in sw_list:\n\t\t\tcmd = \"sudo ovs-vsctl set bridge %s protocols=OpenFlow13\" % sw\n\t\t\tos.system(cmd)\n\n\ndef set_host_ip(net, topo):\n\t# Set hosts' IP.\n\t_hostlist = []\n\tfor k in xrange(len(topo.HostList)):\n\t\t_hostlist.append(net.get(topo.HostList[k]))\n\ti = 1\n\tj = 1\n\tfor host in _hostlist:\n\t\thost.setIP(\"10.%d.0.%d\" % (i, j))\n\t\tj += 1\n\t\tif j == topo.density+1:\n\t\t\tj = 1\n\t\t\ti += 1\n\n\t# Set servers' IP.\n\t_serverlist = []\n\tfor k in xrange(len(topo.SerList)):\n\t\t_serverlist.append(net.get(topo.SerList[k]))\n\ti = 3\n\tfor server in _serverlist:\n\t\tserver.setIP(\"10.%d.0.1\" % i)\n\t\ti += 1\n\ndef install_proactive(net, topo):\n\t\"\"\"\n\t\tInstall direct flow entries for edge switches.\n\t\"\"\"\n\t# Edge Switch\n\tfor sw in topo.EdgeSwitchList:\n\t\tnum = int(sw[-2:])\n\t\t# Downstream\n\t\tfor i in xrange(1, topo.density+1):\n\t\t\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,arp, \\\n\t\t\t\tnw_dst=10.%d.0.%d,actions=output:%d'\" % (sw, num, i, i)\n\t\t\tos.system(cmd)\n\t\t\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,ip, \\\n\t\t\t\tnw_dst=10.%d.0.%d,actions=output:%d'\" % (sw, num, i, i)\n\t\t\tos.system(cmd)\n\n\t# GZ Switch\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,arp, \\\n\t\tnw_dst=10.3.0.1,actions=output:1'\" % topo.GZSwitchList[0]\n\tos.system(cmd)\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,ip, \\\n\t\tnw_dst=10.3.0.1,actions=output:1'\" % topo.GZSwitchList[0]\n\tos.system(cmd)\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,arp, \\\n\t\tnw_dst=10.4.0.1,actions=output:1'\" % topo.GZSwitchList[1]\n\tos.system(cmd)\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,ip, \\\n\t\tnw_dst=10.4.0.1,actions=output:1'\" % topo.GZSwitchList[1]\n\tos.system(cmd)\n\n\t# CDN Switch\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,arp, \\\n\t\tnw_dst=10.5.0.1,actions=output:1'\" % topo.CdnSwitchList[0]\n\tos.system(cmd)\n\tcmd = \"ovs-ofctl add-flow %s -O OpenFlow13 \\\n\t\t'table=0,idle_timeout=0,hard_timeout=0,priority=10,ip, \\\n\t\tnw_dst=10.5.0.1,actions=output:1'\" % topo.CdnSwitchList[0]\n\tos.system(cmd)\n\ndef monitor_devs_ng(fname=\"./txrate.txt\", interval_sec=0.1):\n\t\"\"\"\n\t\tUse bwm-ng tool to collect interface transmit rate statistics.\n\t\tbwm-ng Mode: rate;\n\t\tinterval time: 1s.\n\t\"\"\"\n\tcmd = \"sleep 1; bwm-ng -t %s -o csv -u bits -T rate -C ',' > %s\" % (interval_sec * 1000, fname)\n\tPopen(cmd, shell=True).wait()\n\ndef traffic_generation(net, topo, flows_peers):\n\t\"\"\"\n\t\tGenerate traffics and test the performance of the network.\n\t\"\"\"\n\t# 1. Start iperf. (Elephant flows)\n\t# Start the servers.\n\tserversList = set([peer[0] for peer in flows_peers])\n\tfor server in serversList:\n\t\t# filename = server[1:]\n\t\tserver = net.get(server)\n\t\t# server.cmd(\"iperf -s > %s/%s &\" % (args.output_dir, 'server'+filename+'.txt'))\n\t\tserver.cmd(\"iperf -s > /dev/null &\" ) # Its statistics is useless, just throw away.\n\n\ttime.sleep(3)\n\n\t# Start the clients.\n\tfor src, dest in flows_peers:\n\t\tserver = net.get(src)\n\t\tclient = net.get(dest)\n\t\t# filename = src[1:]\n\t\t# client.cmd(\"iperf -c %s -t %d > %s/%s &\" % (server.IP(), args.duration, args.output_dir, 'client'+filename+'.txt'))\n\t\tclient.cmd(\"iperf -c %s -t %d > /dev/null &\" % (server.IP(), 1990)) # Its statistics is useless, just throw away. 1990 just means a great number.\n\t\ttime.sleep(3)\n\n\t# Wait for the traffic turns stable.\n\ttime.sleep(10)\n\n\t# 2. Start bwm-ng to monitor throughput.\n\tmonitor = Process(target = monitor_devs_ng, args = ('%s/bwmng.txt' % args.output_dir, 1.0))\n\tmonitor.start()\n\n\t# 3. The experiment is going on.\n\ttime.sleep(args.duration + 5)\n\n\t# 4. Shut down.\n\tmonitor.terminate()\n\tos.system('killall bwm-ng')\n\tos.system('killall iperf')\n\ndef run_experiment(density, port=6653, bw_gz=23.2, bw_cdn=26.1, bw_c2a=3.3, bw_a2e=10, bw_e2h=1):\n\t\"\"\"\n\t\tFirstly, start up Mininet;\n\t\tsecondly, start up Ryu controller;\n\t\tthirdly, generate traffics and test the performance of the network.\n\t\"\"\"\n\t# Create Topo.\n\ttopo = IPMAN(density)\n\ttopo.createNodes()\n\ttopo.createLinks(bw_gz=bw_gz, bw_cdn=bw_cdn, bw_c2a=bw_c2a, bw_a2e=bw_a2e, bw_e2h=bw_e2h)\n\n\t# 1. Start Mininet.\n\tCONTROLLER_PORT = port\n\tnet = Mininet(topo=topo, link=TCLink, controller=None, autoSetMacs=True)\n\tnet.addController('controller', controller=RemoteController, port=CONTROLLER_PORT)\n\tnet.start()\n\n\t# Set the OpenFlow version for switches as 1.3.0.\n\ttopo.set_ovs_protocol_13()\n\t# Set the IP addresses for hosts and servers.\n\tset_host_ip(net, topo)\n\t# Install proactive flow entries.\n\tinstall_proactive(net, topo)\n\n\t# 2. Start the controller.\n\tController_Ryu = Popen(\"ryu-manager --observe-links ./SDIPMAN/SDIPMAN.py --k_paths=%d --weight=bw\" % args.kpaths, shell=True, preexec_fn=os.setsid)\n\n\t# Wait until the controller has discovered network topology.\n\ttime.sleep(60)\n\t\n\t# For debugging\n\t# CLI(net)\n\n\t# 3. Generate traffics and test the performance of the network.\n\ttraffic_generation(net, topo, iperf_peers.iperf_peers)\n\n\t# Stop the controller.\n\tos.killpg(Controller_Ryu.pid, signal.SIGKILL)\n\n\t# Stop Mininet.\n\tnet.stop()\n\nif __name__ == '__main__':\n\tsetLogLevel('info')\n\tif os.getuid() != 0:\n\t\tlogging.warning(\"You are NOT root!\")\n\telif os.getuid() == 0:\n\t\t# run the experiment\n\t\trun_experiment(args.density)\n","sub_path":"SDIPMAN/topo_ipman.py","file_name":"topo_ipman.py","file_ext":"py","file_size_in_byte":11197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"179453536","text":"def loadDB(bot): \r\n greaterThan = bot.makeNode('is greater than')\r\n\r\n def greaterThanTest(self, A, B, bot=None):\r\n if A and B and A.getValue() > B.getValue():\r\n bot.makeChain(A, greaterThan, B)\r\n\r\n def generateValues(self, A, B, bot=None):\r\n A.setValue(bot, B.getValue()+1)\r\n \r\n zero = bot.makeNode('zero' )\r\n zero.setValue(bot, 0)\r\n one = bot.makeNode('one' )\r\n two = bot.makeNode('two' )\r\n three = bot.makeNode('three')\r\n four = bot.makeNode('four' )\r\n five = bot.makeNode('five' )\r\n six = bot.makeNode('six' )\r\n seven = bot.makeNode('seven')\r\n eight = bot.makeNode('eight')\r\n nine = bot.makeNode('nine' )\r\n ten = bot.makeNode('ten' )\r\n\r\n global peanoSuccessor\r\n peanoSuccessor = bot.makeNode('= 1 +')\r\n bot.makeChain(one, peanoSuccessor, zero )\r\n bot.makeChain(two, peanoSuccessor, one )\r\n bot.makeChain(three, peanoSuccessor, two )\r\n bot.makeChain(four, peanoSuccessor, three)\r\n bot.makeChain(five, peanoSuccessor, four )\r\n bot.makeChain(six, peanoSuccessor, five )\r\n bot.makeChain(seven, peanoSuccessor, six )\r\n bot.makeChain(eight, peanoSuccessor, seven)\r\n bot.makeChain(nine, peanoSuccessor, eight)\r\n bot.makeChain(ten, peanoSuccessor, nine )\r\n\r\n unknownA = bot.makeNode('A', abstract = True)\r\n unknownB = bot.makeNode('B', abstract = True)\r\n unknownC = bot.makeNode('C', abstract = True)\r\n\r\n greaterThanRule = bot.makeAbstractChain( bot.makeAbstractChain(unknownA, greaterThan, unknownB),\r\n bot.makeAbstractChain(unknownB, greaterThan, unknownC),\r\n bot.implies,\r\n bot.makeAbstractChain(unknownA, greaterThan, unknownC))\r\n\r\n unknownA = bot.makeNode('A', abstract = True)\r\n unknownB = bot.makeNode('B', abstract = True)\r\n\r\n generateValuesNode = bot.makeNode('generate Values', function = generateValues)\r\n \r\n peanoSeries = bot.makeAbstractChain(\r\n bot.makeAbstractChain(bot.hasNewValue, unknownB),\r\n bot.makeAbstractChain(unknownA, peanoSuccessor, unknownB),\r\n bot.implies,\r\n bot.makeAbstractChain(unknownA, greaterThan, unknownB),\r\n bot.makeAbstractChain(bot.activate, generateValuesNode, unknownA, unknownB)\r\n )","sub_path":"kbs/db1.py","file_name":"db1.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"309956887","text":"\"\"\"\nЗадание 4.\nРеализуйте скрипт \"Кэширование веб-страниц\"\n\nФункция должна принимать url-адрес и проверять\nесть ли в кэше соответствующая страница, если нет, то вносит ее в кэш\n\nПодсказка: задачу решите обязательно с применением 'соленого' хеширования\nМожете условжнить задачу, реализовав ее через ООП\n\"\"\"\nimport hashlib\n\nmy_dict = {'vk.com/': 'a0f7c8fab228266ef5228ab96cf4a8dfcd60e6093b5ee2d5c71759b1cc37ad61:vk.com/',\n 'geekbrains.ru/': '21498adf1be23e159a98295f467b99b72c4b67f7ac22627d517905f5de4cfbb8:geekbrains.ru/',\n 'pythonworld.ru/': '65fa233d94ab5ec50373d70d1d9d5e7e39eed50b621d199afc926866a5759356:pythonworld.ru/'\n }\n\n\ndef check_my_dict(s_dict):\n url = input('enter ur url: ')\n if url in s_dict:\n return print('true')\n else:\n salt = url\n res = hashlib.sha256(salt.encode() + url.encode()).hexdigest() + ':' + salt\n print(res)\n s_dict[url] = res\n return print(s_dict)\n\n\ncheck_my_dict(my_dict)\n","sub_path":"Урок 3. Практическое задание/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"609106838","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Flask\n\nimport mysql.connector\n\napplication = Flask(__name__)\napplication.config.from_pyfile('config.cfg')\n\n\nclass EnsemenceuseUtilisateurs(object):\n\tdef __init__(self, config):\n\t\tself.config = config\n\n\n\tdef cree_tables(self):\n\t\tconnexion = mysql.connector.connect(\n host=self.config['MYSQL_HOTE'],\n user=self.config['MYSQL_USER'],\n password=self.config['MYSQL_MDP'],\n database=self.config['MYSQL_NBDD'])\n\n\t\tcurseur = connexion.cursor()\n\n\t\tcommande = \"\"\"\n\t\t\tCREATE TABLE IF NOT EXISTS\n\t\t\t\tutilisateurs\n\t\t\t(\n\t\t\t\tid INT AUTO_INCREMENT PRIMARY KEY,\n\t\t\t\tnom VARCHAR(64),\n\t\t\t\tcourriel VARCHAR(255),\n\t\t\t\tmdp VARCHAR(72)\n\t\t\t);\n\t\t\"\"\"\n\n\t\tcurseur.execute(commande)\n\n\t\tcommande = \"\"\"\n\t\t\tCREATE TABLE IF NOT EXISTS\n\t\t\t\tmessage\n\t\t\t(\n\t\t\t\tid INT AUTO_INCREMENT PRIMARY KEY,\n\t\t\t\tid_vers INT UNSIGNED NOT NULL,\n\t\t\t\tid_de INT UNSIGNED NOT NULL,\n\t\t\t\tcontenu TEXT NOT NULL,\n\t\t\t\tdate_creation TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n\t\t\t\tdate_lu DATETIME DEFAULT NULL\n\t\t\t);\n\t\t\"\"\"\n\n\t\tcurseur.execute(commande)\n\n\t\tconnexion.commit()\n\n\t\tconnexion.close()\n\n\n\n\tdef cree_utilisateurs(self, nombre):\n\t\tutilisateurs = []\n\n\t\tfor i in range(10):\n\t\t\tnom = 'JohnDoe' + str(i)\n\t\t\tcourriel = 'john' + str(i) + '@doe.fr'\n\t\t\tmdp = '0000'\n\n\t\t\tutilisateurs.append([nom, courriel, mdp])\n\n\t\tconnexion = mysql.connector.connect(\n host=self.config['MYSQL_HOTE'],\n user=self.config['MYSQL_USER'],\n password=self.config['MYSQL_MDP'],\n database=self.config['MYSQL_NBDD'])\n\n\t\tcurseur = connexion.cursor()\n\n\t\tcommande = \"\"\"\n\t\t\tINSERT INTO\n\t\t\t\tutilisateurs (nom, courriel, mdp)\n\t\t\tVALUES {};\n\t\t\"\"\"\n\n\t\tsous_commande = \"\"\"(\"{}\", \"{}\", \"{}\")\"\"\"\n\n\t\tcommande = commande.format(\",\".join(sous_commande.format(u[0],u[1],u[2]) for u in utilisateurs))\n\n\t\tcurseur.execute(commande)\n\n\t\tconnexion.commit()\n\n\t\tconnexion.close()\n\n\n\nensemenceuse = EnsemenceuseUtilisateurs(application.config)\nensemenceuse.cree_tables()\n","sub_path":"messagerie/ensemenceuse.py","file_name":"ensemenceuse.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"227683814","text":"from numpy import *\nfrom matplotlib.pyplot import *\n\nfrom multivariateGaussian import multivariateGaussian\n\ndef visualizeFit(X, mu, sigma2):\n #VISUALIZEFIT Visualize the dataset and its estimated distribution.\n # VISUALIZEFIT(X, mu, sigma2) This visualization shows you the\n # probability density function of the Gaussian distribution. Each example\n # has a location (x1, x2) that depends on its feature values.\n #\n\n coords = linspace(0,30,61)\n X1, X2 = meshgrid(coords, coords)\n Z = multivariateGaussian(column_stack((X1.ravel(),X2.ravel())), mu, sigma2)\n Z = reshape(Z, shape(X1))\n\n plot(X[:, 0], X[:, 1],'bx')\n hold(True)\n # Do not plot if there are infinities\n if not any(isinf(Z)):\n contour(X1, X2, Z, power(10., arange(-20,0,3)))\n hold(False)\n","sub_path":"machine-learning-ex8/ex8/visualizeFit.py","file_name":"visualizeFit.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"171856462","text":"import matplotlib.pyplot as plt\nimport pickle\nimport numpy as np\n\ncluster_center = []\npoint = []\ncolor = ['DC143C', '800080', '0000FF', '708090', '00CED1', '00FA9A', 'FFFF00', 'FFA500', 'FF0000', '008000', '00FFFF', '708090']\n\nwith open(\"KMeans_8_clusters/KMeans_8_Clusters_m_15/part-r-00000\", \"r\") as center:\n for line in center.readlines():\n line = line.strip('\\n')\n points = [float(x) for x in line.split('\\t')[1].split(',')]\n cluster_center.append(points)\n\n# for i, l in enumerate(cluster_center):\n# print(i, l)\n\ndef distance(x, y):\n ans = 0\n for i in range(1, len(x)):\n ans = ans + (x[i] - y[i]) * (x[i] - y[i])\n return ans\n\nwith open(\"clusterFile/USCensus1990.data.txt\", 'r') as f:\n count = 0\n for line in f.readlines():\n count = count + 1\n p = [float(x) for x in line.split(',')]\n dis = float('inf')\n cluster_id = 0\n for i, l in enumerate(cluster_center):\n if distance(l, p) < dis:\n dis= distance(l, p)\n cluster_id = i\n point.append(cluster_id)\n if count >= 10000 :\n break\nprint(len(point))\n\nwith open('usdata.pickle', 'rb') as usdata:\n data = pickle.load(usdata)\n print(type(data))\n # print(data[:, 0].shape)\n # for i in range(10000):\n # plt.scatter(data[i][0], data[i][1], color='#'+color[point[i]])\n plt.scatter(data[:, 0], data[:, 1], c=point)\n plt.show()","sub_path":"Lab2/src/cluster/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"620582135","text":"# finding the projected total amount of sales.\r\n#09/16/19\r\n#CTI-110 P2T1-Sales Prediction\r\n# SedrickCulbreath\r\n\r\n\r\n# Get the projected total sales.\r\ntotal_sales = float(input('Enter the projected sales: '))\r\n\r\n#Calculate the profit as 23 percent of total sale.\r\nprofit = total_sales *0.23\r\n\r\n#Display the profit.\r\nprint('The profit is $' , format(profit, ',.2f'))\r\n","sub_path":"P2T1- Sales Prediction.py","file_name":"P2T1- Sales Prediction.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"295680238","text":"import sys\nsys.path.append('..')\n\nimport json\nimport config\n\nfrom upyun import UpYun\n\ndef check_result(ret, info, **kv):\n if ret == True:\n content = {\n 'status':'ok',\n 'info':info\n }\n else:\n content = {\n 'status':'error',\n 'info':info\n }\n return json.dumps(dict(content, **kv))\n","sub_path":"paySystem/utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"460339667","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'wangzhenxing'\n\n\nimport subprocess,shutil\nfrom ipa_package_settings import *\nfrom ipa_package_tool import FileHelper,XCProjectInfo\n\n\n# 注 : 当前项目\nPROJECT_OBJ = XCProjectInfo(project_path='/Users/silence/Desktop/hx-teacher-dashboard/ios/TeacherDashbord.xcworkspace')\n\n\n\ndef package_project_if_exist(debug = True ,\n package_type = 0,\n archive_method = None):\n '''\n 编译项目(根据配置文件)\n :param debug: Debug or Release mode\n :param ipa_type: 打包方式 ( 0 : 命令行打包 / 1 : payload文件夹手动打包)\n :param archive_method: app-store, package, ad-hoc, enterprise, development, and developer-id\n :return: \n '''\n PROJECT_OBJ.debug = debug\n\n project_config_key = PROJECT_OBJ.config_key()\n project_name = PROJECT_OBJ.project_name\n project_key = PROJECT_OBJ.project_type\n project_path = PROJECT_OBJ.project_path\n\n if not project_path:\n logger.error(\"[编译项目] :项目不存在 %s \",project_path)\n return\n\n if archive_method is None:\n archive_method = 'development' if debug else 'app-store'\n\n # ① 项目编译命令配置\n project_cmd = '-%s \"%s\" -scheme \"%s\" ' \\\n '-configuration %s'%(\n project_key,\n project_path,\n project_name,\n project_config_key)\n\n project_build_cmd = 'xcodebuild ' + project_cmd\n project_clean_cmd = 'xcodebuild clean ' + project_cmd\n\n for cmd in [project_clean_cmd,project_build_cmd]:\n logger.info(\"[编译项目] :当前编译命令 %s\",cmd)\n process = subprocess.Popen(cmd,shell=True)\n process.wait()\n\n # ② 打包ipa文件 ( 0 : 命令行打包 / 1 : payload文件夹手动打包)\n if package_type == 0:\n make_ipa_with_xcodebuild(debug,archive_method)\n else:\n make_ipa_by_payload(debug)\n\n\ndef make_ipa_with_xcodebuild(debug,\n archive_method):\n '''\n 打包 Archive\n :param debug: Debug or Release mode \n :return: None\n '''\n PROJECT_OBJ.debug = debug\n\n project_config_key = PROJECT_OBJ.config_key()\n project_name = PROJECT_OBJ.project_name\n project_key = PROJECT_OBJ.project_type\n project_path = PROJECT_OBJ.project_path\n\n project_archive_path = os.path.join(ARCHIVE_FILE_PATH,project_name+\".xcarchive\")\n full_project_name = project_name + '-' + project_config_key\n\n # archive cmd\n project_archive_cmd = 'xcodebuild archive ' \\\n '-%s \"%s\" -scheme \"%s\" -archivePath \"%s\" ' \\\n '-configuration %s -sdk iphoneos11.3' % (\n project_key,\n project_path,\n project_name,\n project_archive_path,\n project_config_key\n )\n\n # exoprt ipa cmd\n ipa_file_path = os.path.join(IPA_FILE_PATH, full_project_name)\n method_path = os.path.join(EXPORT_FILE_PATH,archive_method + '.plist')\n\n project_export_cmd = 'xcodebuild -exportArchive ' \\\n '-archivePath \"%s\" -exportPath \"%s\" -exportOptionsPlist \"%s\"'%(\n project_archive_path,\n ipa_file_path,\n method_path\n )\n\n # 根据需要移除打包文件\n if os.path.exists(project_archive_path):\n shutil.rmtree(project_archive_path)\n if os.path.exists(ipa_file_path):\n os.remove(ipa_file_path)\n\n for cmd in [project_archive_cmd,project_export_cmd]:\n logger.info(\"[打包项目] :当前编译命令 %s\", cmd)\n process = subprocess.Popen(cmd, shell=True)\n process.wait()\n\n\n\ndef make_ipa_by_payload(debug=True):\n '''\n 通过payload文件夹方式生成ipa文件\n :param path: xcode编译文件所在位置 \n :return: \n '''\n PROJECT_OBJ.debug = debug\n\n project_name = PROJECT_OBJ.project_name\n project_app_name = project_name + '.app'\n project_payload_path = PROJECT_OBJ.find_build_app_path()\n\n full_project_name = project_name + '-' + PROJECT_OBJ.config_key()\n to_payload_path = os.path.join(PAYLOAD_FILE_PATH, project_app_name)\n ipa_file_path = os.path.join(IPA_FILE_PATH,full_project_name+\".zip\")\n\n # ③ 创建payload文件夹,并将编译app移动至此目录\n if project_payload_path:\n try:\n if os.path.exists(to_payload_path):\n shutil.rmtree(to_payload_path)\n shutil.copytree(project_payload_path,to_payload_path)\n logger.info(\"[生成ipa]复制并迁移Payload App文件目录至 : %s\", to_payload_path)\n except Exception as e:\n logger.error(\"[生成ipa]复制并迁移Payload App错误 : %s\",e)\n\n # ④ 压缩文件并修改后缀名为ipa\n if os.path.exists(to_payload_path):\n try:\n FileHelper.zip_file_with_path(os.path.dirname(to_payload_path),\n ipa_file_path)\n except Exception as e :\n logger.error(\"[生成ipa]压缩文件失败 :%s\",e)\n finally:\n if os.path.exists(to_payload_path):\n shutil.rmtree(to_payload_path)\n\n\nif __name__ == \"__main__\":\n\n make_ipa_with_xcodebuild(True,'ad-hoc')\n\n # package_project_if_exist(True)\n\n","sub_path":"IOSPackage/ipa_package.py","file_name":"ipa_package.py","file_ext":"py","file_size_in_byte":5304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"304477220","text":"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Multi-threaded word2vec unbatched skip-gram model.\n\nTrains the model described in:\n(Mikolov, et. al.) Efficient Estimation of Word Representations in Vector Space\nICLR 2013.\nhttp://arxiv.org/abs/1301.3781\nThis model does true SGD (i.e. no minibatching). To do this efficiently, custom\nops are used to sequentially process data within a 'batch'.\n\nThe key ops used are:\n* skipgram custom op that does input processing.\n* neg_train custom op that efficiently calculates and applies the gradient using\n true SGD.\n\nAdditional edits made by Martin Fajcik\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport threading\nimport time\nimport pickle\nimport datetime\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nimport numpy as np\nimport tensorflow as tf\n\nword2vec = tf.load_op_library(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'word2vec_ops.so'))\n\nflags = tf.app.flags\n\nflags.DEFINE_string(\"save_path\", None, \"Directory to write the model.\")\nflags.DEFINE_string(\n \"train_data\", None,\n \"Training data. E.g., unzipped file http://mattmahoney.net/dc/text8.zip.\")\nflags.DEFINE_string(\n \"eval_data\", None, \"Analogy questions. \"\n \"See README.md for how to get 'questions-words.txt'.\")\nflags.DEFINE_integer(\"embedding_size\", 300, \"The embedding dimension size.\")\nflags.DEFINE_integer(\n \"epochs_to_train\", 1,\n \"Number of epochs to train. Each epoch processes the training data once \"\n \"completely.\")\nflags.DEFINE_float(\"learning_rate\", 0.025, \"Initial learning rate.\")\nflags.DEFINE_integer(\"num_neg_samples\", 25,\n \"Negative samples per training example.\")\nflags.DEFINE_integer(\"batch_size\", 500,\n \"Numbers of training examples each step processes \"\n \"(no minibatching).\")\nflags.DEFINE_integer(\"concurrent_steps\", 1,\n \"The number of concurrent training steps.\")\nflags.DEFINE_integer(\"window_size\", 5,\n \"The number of words to predict to the left and right \"\n \"of the target word.\")\nflags.DEFINE_integer(\"min_count\", 1,\n \"The minimum number of word occurrences for it to be \"\n \"included in the vocabulary.\")\nflags.DEFINE_float(\"subsample\", 1e-3,\n \"Subsample threshold for word occurrence. Words that appear \"\n \"with higher frequency will be randomly down-sampled. Set \"\n \"to 0 to disable.\")\nflags.DEFINE_boolean(\n \"interactive\", False,\n \"If true, enters an IPython interactive session to play with the trained \"\n \"model. E.g., try model.analogy(b'france', b'paris', b'russia') and \"\n \"model.nearby([b'proton', b'elephant', b'maxwell'])\")\n\nflags.DEFINE_boolean(\"save2vec\",False,\"Save model into .vec file after training.\")\nflags.DEFINE_boolean(\"save_dict_pkl\",False,\"Pickle the word to index dictionary.\")\nflags.DEFINE_boolean(\"make_topgrads_pkl\",False,\"Save matrix containt information about topgradients into pkl.\")\n\nflags.DEFINE_boolean(\"validate\",False,\"Run validation on word analogy task during training [EN only].\")\nflags.DEFINE_boolean(\"save_checkpoints\",True,\"Save network architecture and parameters after each epoch.\")\nflags.DEFINE_boolean(\"playmode\", False, \"Enter mode in which checkpoint from save_path is loaded and ipython console is enabled.\")\n\nFLAGS = flags.FLAGS\n\n\nclass Options(object):\n \"\"\"Options used by our word2vec model.\"\"\"\n\n def __init__(self):\n # Model options.\n\n # Embedding dimension.\n self.emb_dim = FLAGS.embedding_size\n\n # Training options.\n\n # The training text file.\n self.train_data = FLAGS.train_data\n\n # Number of negative samples per example.\n self.num_samples = FLAGS.num_neg_samples\n\n # The initial learning rate.\n self.learning_rate = FLAGS.learning_rate\n\n # Number of epochs to train. After these many epochs, the learning\n # rate decays linearly to zero and the training stops.\n self.epochs_to_train = FLAGS.epochs_to_train\n\n # Concurrent training steps.\n self.concurrent_steps = FLAGS.concurrent_steps\n\n # Number of examples for one training step.\n self.batch_size = FLAGS.batch_size\n\n # The number of words to predict to the left and right of the target word.\n self.window_size = FLAGS.window_size\n\n # The minimum number of word occurrences for it to be included in the\n # vocabulary.\n self.min_count = FLAGS.min_count\n\n # Subsampling threshold for word occurrence.\n self.subsample = FLAGS.subsample\n\n # Where to write out summaries.\n self.save_path = FLAGS.save_path\n if not os.path.exists(self.save_path):\n os.makedirs(self.save_path)\n\n # Eval options.\n\n # The text file for eval.\n self.eval_data = FLAGS.eval_data\n\n\nladder_size = 1024\nclass Word2Vec(object):\n \"\"\"Word2Vec model (Skipgram).\"\"\"\n\n def __init__(self, options, session):\n self._options = options\n self._session = session\n self._word2id = {}\n self._id2word = []\n self.build_graph()\n self.build_get_embedding_graph()\n self.build_get_pos_graph()\n self.build_find_nearest_graph()\n # eval graph also runs the variable initializer!\n self.build_eval_graph()\n print (\"Saving vocabulary...\")\n self.save_vocab()\n print (\"Done\")\n\n #self.examples = np.zeros(shape=(self._options.vocab_size, ladder_size),dtype=np.int32)\n self.gradient_positions = np.zeros(shape=(self._options.vocab_size, ladder_size), dtype=np.uint64)\n self.gradients = np.zeros(shape=(self._options.vocab_size, ladder_size),dtype=np.float)\n\n # The vec file is a text file that contains the word vectors, one per line for each word in the vocabulary.\n # The first line is a header containing the number of words and the dimensionality of the vectors.\n # Subsequent lines are the word vectors for all words in the vocabulary, sorted by decreasing frequency.\n # Example:\n # 218316 100\n # the -0.10363 -0.063669 0.032436 -0.040798...\n # of -0.0083724 0.0059414 -0.046618 -0.072735...\n # one 0.32731 0.044409 -0.46484 0.14716...\n def save_to_vec(self, vec_path):\n embeddings = self._session.run(self._w_in)\n # Using linux file endings\n with open(vec_path, 'w') as f:\n print(\"Saving .vec file to {}\".format(vec_path))\n f.write(\"{} {}\\n\".format(self._options.vocab_size, self._options.emb_dim))\n for (word, embedding) in zip(self._options.vocab_words, embeddings):\n f.write(\"{} {}\\n\".format(word, ' '.join(map(str, embedding))))\n\n def read_analogies(self):\n \"\"\"Reads through the analogy question file.\n\n Returns:\n questions: a [n, 4] numpy array containing the analogy question's\n word ids.\n questions_skipped: questions skipped due to unknown words.\n \"\"\"\n questions = []\n questions_skipped = 0\n with open(self._options.eval_data, \"rb\") as analogy_f:\n for line in analogy_f:\n if line.startswith(b\":\"): # Skip comments.\n continue\n words = line.strip().lower().split(b\" \")\n ids = [self._word2id.get(w.strip()) for w in words]\n if None in ids or len(ids) != 4:\n questions_skipped += 1\n else:\n questions.append(np.array(ids))\n print(\"Eval analogy file: \", self._options.eval_data)\n print(\"Questions: \", len(questions))\n print(\"Skipped: \", questions_skipped)\n self._analogy_questions = np.array(questions, dtype=np.int32)\n\n def build_graph(self):\n #with tf.name_scope('graph') as scope:\n\n \"\"\"Build the model graph.\"\"\"\n opts = self._options\n\n # The training data. A text file.\n #print(\"Preprocessing corpus...\")\n (words, counts, words_per_epoch, current_epoch, total_words_processed,\n examples, labels, example_positions, label_positions) = word2vec.skipgram_word2vec(filename=opts.train_data,\n batch_size=opts.batch_size,\n window_size=opts.window_size,\n min_count=opts.min_count,\n subsample=opts.subsample,\n gradient_ranking=True)\n (opts.vocab_words, opts.vocab_counts,\n opts.words_per_epoch) = self._session.run([words, counts, words_per_epoch])\n #print(\"Preprocessing finished!\")\n opts.vocab_words = list(map(lambda s: s.decode(),opts.vocab_words))\n #print(\"Words saved!\")\n opts.vocab_size = len(opts.vocab_words)\n print(\"Data file: \", opts.train_data)\n print(\"Vocab size: \", opts.vocab_size - 1, \" + UNK\")\n print(\"Words per epoch: \", opts.words_per_epoch)\n\n self._id2word = opts.vocab_words\n for i, w in enumerate(self._id2word):\n self._word2id[w] = i\n\n # Declare all variables we need.\n # Input words embedding: [vocab_size, emb_dim]\n w_in = tf.Variable(\n tf.random_uniform(\n [opts.vocab_size,\n opts.emb_dim], -0.5 / opts.emb_dim, 0.5 / opts.emb_dim),\n name=\"w_in\")\n\n pos_by_gradient_ladder = tf.Variable(\n tf.zeros(shape=(opts.vocab_size, ladder_size),name=\"pos_by_gradient_ladder\",dtype=tf.int32),\n )\n gradient_ladder = tf.Variable(\n tf.zeros(shape=(opts.vocab_size, ladder_size), name=\"gradient_ladder\")\n )\n #\n # example_ladder = tf.Variable(\n # tf.zeros(shape=(ladder_size), name=\"example_ladder\",dtype=tf.int32)\n # )\n\n # Global step: scalar, i.e., shape [].\n w_out = tf.Variable(tf.zeros([opts.vocab_size, opts.emb_dim]), name=\"w_out\")\n\n # Global step: []\n global_step = tf.Variable(0, name=\"global_step\")\n\n # Linear learning rate decay.\n words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)\n lr = opts.learning_rate * tf.maximum(\n 0.0001,\n 1.0 - tf.cast(total_words_processed, tf.float32) / words_to_train)\n\n # Training nodes.\n inc = global_step.assign_add(1)\n with tf.control_dependencies([inc]):\n train = word2vec.neg_train_word2vec(w_in,\n w_out,\n examples,\n labels,\n example_positions,\n label_positions,\n lr,\n pos_by_gradient_ladder,\n gradient_ladder,\n vocab_count=opts.vocab_counts.tolist(),\n num_negative_samples=opts.num_samples)\n\n self._w_in = w_in\n self._examples = examples\n self._labels = labels\n self._lr = lr\n self._train = train\n self.global_step = global_step\n self._epoch = current_epoch\n self._words = total_words_processed\n self._pos_by_gradient_ladder = pos_by_gradient_ladder\n self._gradient_ladder = gradient_ladder\n\n def save_vocab(self):\n \"\"\"Save the vocabulary to a file so the model can be reloaded.\"\"\"\n opts = self._options\n with open(os.path.join(opts.save_path, \"vocab.txt\"), \"w\") as f:\n for i in xrange(opts.vocab_size):\n vocab_word = tf.compat.as_text(opts.vocab_words[i])\n f.write(\"%s %d\\n\" % (vocab_word,\n opts.vocab_counts[i]))\n\n def build_get_embedding_graph(self):\n word_id = tf.placeholder(dtype=tf.int32)\n emb = tf.gather(self._w_in, word_id)\n\n self.embedding = emb\n self._word_id = word_id\n\n def build_get_pos_graph(self):\n # word_id = tf.placeholder(dtype=tf.int32)\n # pos_graph = tf.gather(self._pos_by_gradient_ladder, word_id)\n # self.pos_graph = pos_graph\n # self._word_id = word_id\n pass\n def get_pos(self,w):\n #return self._session.run([self.pos_graph], {self._word_id: self._word2id.get(w, 0)})[0]\n return self.gradient_positions[self._word2id[w]]\n\n def build_find_nearest_graph(self, nearest_word_count=10):\n opts=self._options\n word_id = tf.placeholder(dtype=tf.int32)\n normalized_embedding_matrix = tf.nn.l2_normalize(self._w_in, 1)\n embedding = tf.gather(normalized_embedding_matrix, word_id)\n distance_matrix = tf.matmul(tf.expand_dims(embedding,0), normalized_embedding_matrix, transpose_b=True)\n #distance_matrix= tf.einsum('n,nm->m', embedding, tf.transpose(normalized_embedding_matrix))\n _, closest_idx = tf.nn.top_k(distance_matrix, min(nearest_word_count+1, opts.vocab_size))\n self.closest_idx=closest_idx\n self.target_id = word_id\n\n\n def build_eval_graph(self):\n \"\"\"Build the evaluation graph.\"\"\"\n # Eval graph\n opts = self._options\n\n # Each analogy task is to predict the 4th word (d) given three\n # words: a, b, c. E.g., a=italy, b=rome, c=france, we should\n # predict d=paris.\n\n # The eval feeds three vectors of word ids for a, b, c, each of\n # which is of size N, where N is the number of analogies we want to\n # evaluate in one batch.\n analogy_a = tf.placeholder(dtype=tf.int32) # [N]\n analogy_b = tf.placeholder(dtype=tf.int32) # [N]\n analogy_c = tf.placeholder(dtype=tf.int32) # [N]\n\n # Normalized word embeddings of shape [vocab_size, emb_dim].\n nemb = tf.nn.l2_normalize(self._w_in, 1)\n\n # Each row of a_emb, b_emb, c_emb is a word's embedding vector.\n # They all have the shape [N, emb_dim]\n a_emb = tf.gather(nemb, analogy_a) # a's embs\n b_emb = tf.gather(nemb, analogy_b) # b's embs\n c_emb = tf.gather(nemb, analogy_c) # c's embs\n\n # We expect that d's embedding vectors on the unit hyper-sphere is\n # near: c_emb + (b_emb - a_emb), which has the shape [N, emb_dim].\n target = c_emb + (b_emb - a_emb)\n\n # Compute cosine distance between each pair of target and vocab.\n # dist has shape [N, vocab_size].\n dist = tf.matmul(target, nemb, transpose_b=True)\n\n # For each question (row in dist), find the top 4 words.\n _, pred_idx = tf.nn.top_k(dist, 4)\n\n # Nodes for computing neighbors for a given word according to\n # their cosine distance.\n nearby_word = tf.placeholder(dtype=tf.int32) # word id\n nearby_emb = tf.gather(nemb, nearby_word)\n nearby_dist = tf.matmul(nearby_emb, nemb, transpose_b=True)\n nearby_val, nearby_idx = tf.nn.top_k(nearby_dist,\n min(1000, opts.vocab_size))\n\n # Nodes in the construct graph which are used by training and\n # evaluation to run/feed/fetch.\n self._analogy_a = analogy_a\n self._analogy_b = analogy_b\n self._analogy_c = analogy_c\n self._analogy_pred_idx = pred_idx\n self._nearby_word = nearby_word\n self._nearby_val = nearby_val\n self._nearby_idx = nearby_idx\n\n # Properly initialize all variables.\n tf.global_variables_initializer().run()\n\n self.saver = tf.train.Saver()\n\n\n def find_insert_pos(self,example,gradient):\n if gradient gradient): low = mid + 1\n else: high = mid - 1\n return low\n\n\n def process_result(self,examples,positions,gradients):\n #shape=(self._options.vocab_size, ladder_size)\n for i in range(len(examples)):\n example,position,gradient = examples[i],positions[i],gradients[i]\n #find pos to insert via binary search\n p = self.find_insert_pos(example,gradient)\n if p>=0:\n #self.examples[example,shift_from+1:] = self.examples[example,shift_from:-1]\n self.gradient_positions[example, p + 1:] = self.gradient_positions[example, p:-1]\n self.gradients[example,p+1:] = self.gradients[example,p:-1]\n self.gradient_positions[example, p] = position\n self.gradients[example,p] = gradient\n\n def _train_thread_body(self):\n initial_epoch, = self._session.run([self._epoch])\n while True:\n (examples,positions,gradients),epoch = self._session.run([self._train, self._epoch])\n self.process_result(examples,positions,gradients)\n if epoch != initial_epoch:\n break\n\n def train(self):\n \"\"\"Train the model.\"\"\"\n opts = self._options\n\n initial_epoch, initial_words = self._session.run([self._epoch, self._words])\n\n workers = []\n for _ in xrange(opts.concurrent_steps):\n t = threading.Thread(target=self._train_thread_body)\n t.start()\n workers.append(t)\n\n last_words, last_time = initial_words, time.time()\n while True:\n time.sleep(5) # Reports our progress once a while.\n (epoch, step, words, lr) = self._session.run(\n [self._epoch, self.global_step, self._words, self._lr])\n now = time.time()\n last_words, last_time, rate = words, now, (words - last_words) / (\n now - last_time)\n # print(\"Epoch %4d Step %8d: lr = %5.3f words/sec = %8.0f\\r\" % (epoch, step,\n # lr, rate),\n # end=\"\")\n # sys.stdout.flush()\n progress = words / (opts.words_per_epoch*opts.epochs_to_train) * 100\n print(\"[%3.2f%%]: Epoch %4d Step %8d: lr = %5.3f words/sec = %8.0f\\r\" % (progress,epoch, step,\n lr, rate))\n if epoch != initial_epoch:\n break\n\n for t in workers:\n t.join()\n def _find_nearest(self, w):\n idx, = self._session.run(self.closest_idx, {\n self.target_id:self._word2id.get(w,0)\n })\n result = list(map(lambda x: self._id2word[x],idx[1:]))\n return result\n\n def _predict(self, analogy):\n \"\"\"Predict the top 4 answers for analogy questions.\"\"\"\n idx, = self._session.run([self._analogy_pred_idx], {\n self._analogy_a: analogy[:, 0],\n self._analogy_b: analogy[:, 1],\n self._analogy_c: analogy[:, 2]\n })\n return idx\n\n def get_embedding(self, word):\n return self._session.run([self.embedding], {self._word_id: self._word2id.get(word, 0)})\n\n def eval(self):\n \"\"\"Evaluate analogy questions and reports accuracy.\"\"\"\n\n # How many questions we get right at precision@1.\n correct = 0\n try:\n total = self._analogy_questions.shape[0]\n except AttributeError as e:\n raise AttributeError(\"Need to read analogy questions.\")\n\n start = 0\n while start < total:\n limit = start + 2500\n sub = self._analogy_questions[start:limit, :]\n idx = self._predict(sub)\n start = limit\n for question in xrange(sub.shape[0]):\n for j in xrange(4):\n if idx[question, j] == sub[question, 3]:\n # Bingo! We predicted correctly. E.g., [italy, rome, france, paris].\n correct += 1\n break\n elif idx[question, j] in sub[question, :3]:\n # We need to skip words already in the question.\n continue\n else:\n # The correct label is not the precision@1\n break\n print()\n print(\"Eval %4d/%d accuracy = %4.1f%%\" % (correct, total,\n\n correct * 100.0 / total))\n\n def analogy(self, w0, w1, w2):\n \"\"\"Predict word w3 as in w0:w1 vs w2:w3.\"\"\"\n wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])\n idx = self._predict(wid)\n for c in [self._id2word[i] for i in idx[0, :]]:\n if c not in [w0, w1, w2]:\n print(c)\n break\n print(\"unknown\")\n\n def nearby(self, words, num=20):\n \"\"\"Prints out nearby words given a list of words.\"\"\"\n ids = np.array([self._word2id.get(x, 0) for x in words])\n vals, idx = self._session.run(\n [self._nearby_val, self._nearby_idx], {self._nearby_word: ids})\n for i in xrange(len(words)):\n print(\"\\n%s\\n=====================================\" % (words[i]))\n for (neighbor, distance) in zip(idx[i, :num], vals[i, :num]):\n print(\"%-20s %6.4f\" % (self._id2word[neighbor], distance))\n\n\ndef _start_shell(local_ns=None):\n # An interactive shell is useful for debugging/development.\n import IPython\n user_ns = {}\n if local_ns:\n user_ns.update(local_ns)\n user_ns.update(globals())\n IPython.start_ipython(argv=[], user_ns=user_ns)\n\n\n#FLAGS.train_data = \"/mnt/minerva1/nlp/projects/semantic_relatedness10/data/my_preprocessed/cs.txt_2017-10-25_12:19\"\n#FLAGS.train_data = \"/home/ifajcik/deep_learning/word2vec/corpus_data/ebooks_corpus_CZ/few_sentences.txt\"\nFLAGS.train_data = \"/home/ifajcik/deep_learning/word2vec/corpus_data/ebooks_corpus_CZ/e_knihy_preprocessed.txt\"\n#FLAGS.train_data = \"/home/ifajcik/deep_learning/word2vec/corpus_data/cwc_corpus2011/cwc50megs\"\nFLAGS.eval_data = \"noevaltest\"\n#FLAGS.save_path = \"/home/ifajcik/word2vec/trainedmodels/tf_w2vopt_zoznam\"\nFLAGS.save_path = \"/home/ifajcik/deep_learning/word2vec/trainedmodels/tf_w2vopt_ebooks_gradient_ladder\"\n\ndef max (x,y):\n return x if x>y else y\n\ndef find_word_contexts(model, word, window_size =FLAGS.window_size * 2, corpus =FLAGS.train_data, average_word_bytelen = 45):\n positions = model.get_pos(word)\n size = window_size * average_word_bytelen #10 for average word\n contexts = []\n with open(corpus,mode=\"rb\") as data:\n for pos in positions:\n data.seek(max(int(pos-size),0))\n chunk1 = data.read(size).decode(\"utf-8\", errors=\"ignore\").split()\n chunk2 = data.read(size).decode(\"utf-8\", errors=\"ignore\").split()\n contexts.append(chunk1[-(window_size+1):]+chunk2[:window_size])\n return contexts,positions\n\ndef disable_GPU():\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\ndef main(_):\n disable_GPU()\n \"\"\"Train a word2vec model.\"\"\"\n if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path:\n print(\"--train_data --eval_data and --save_path must be specified.\")\n sys.exit(1)\n opts = Options()\n\n if FLAGS.playmode:\n play_with_model(opts)\n\n model_n = os.path.basename(FLAGS.train_data)\n with tf.Graph().as_default(), tf.Session() as session:\n with tf.device(\"/cpu:0\"):\n model = Word2Vec(opts, session)\n if FLAGS.validate:\n model.read_analogies() # Read analogy questions\n print(\"Starting training: {}\".format(datetime.date.today()))\n print(\"Epochs to train: {}\".format(opts.epochs_to_train))\n for i in range(opts.epochs_to_train):\n model.train() # Process one epoch\n if FLAGS.validate:\n model.eval()\n if FLAGS.save_checkpoints:\n model.saver.save(session, os.path.join(opts.save_path, \"model_{}_e{}.ckpt\".format(model_n,i)),\n global_step=model.global_step)\n\n print(\"Training finished: {}\".format(datetime.date.today()))\n\n if FLAGS.save_dict_pkl:\n with open (\"w2i_{}.pkl\".format(model_n), \"wb\") as f:\n pickle.dump(model._word2id, f, pickle.HIGHEST_PROTOCOL)\n\n if FLAGS.make_topgrads_pkl:\n with open('toppositions_{}.pkl'.format(model_n), 'wb') as output:\n pickle.dump(model.gradient_positions, output, pickle.HIGHEST_PROTOCOL)\n\n with open('topgrads_{}.pkl'.format(model_n), 'wb') as output:\n pickle.dump(model.gradients, output, pickle.HIGHEST_PROTOCOL)\n\n if FLAGS.save2vec:\n save_model_to_vec(opts)\n if FLAGS.interactive:\n # E.g.,\n # [0]: model.analogy(b'france', b'paris', b'russia')\n # [1]: model.nearby([b'proton', b'elephant', b'maxwell'])\n _start_shell(locals())\n\n\ndef save_model_to_vec(opts, restore_from_save_path=False):\n with tf.Session() as session:\n model = Word2Vec(opts, session)\n if restore_from_save_path:\n print('Restoring model...')\n model_n = os.path.basename(FLAGS.train_data)\n model.saver.restore(session, tf.train.latest_checkpoint(FLAGS.save_path))\n model.save_to_vec(os.path.join(FLAGS.save_path, \"{}_model.vec\".format(model_n)))\n return True\n\ndef play_with_model(opts):\n with tf.Session() as session:\n model = Word2Vec(opts, session)\n print('Restoring model...')\n model.saver.restore(session, tf.train.latest_checkpoint(opts.save_path))\n\n #nearest_words = model._find_nearest('oko')\n #print(' '.join(nearest_words))\n _start_shell(locals())\n return True\n\nif __name__ == \"__main__\":\n tf.app.run()","sub_path":"tutorials/embedding/word2vec_optimized.py","file_name":"word2vec_optimized.py","file_ext":"py","file_size_in_byte":27065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"108109947","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport logging\nfrom datetime import datetime\n\nfrom app_analytics.influxdb_wrapper import (\n get_events_for_organisation,\n get_multiple_event_list_for_organisation,\n)\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom drf_yasg2.utils import swagger_auto_schema\nfrom rest_framework import status, viewsets\nfrom rest_framework.authentication import BasicAuthentication\nfrom rest_framework.decorators import action, api_view, authentication_classes\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom organisations.models import (\n OrganisationRole,\n OrganisationWebhook,\n Subscription,\n)\nfrom organisations.permissions import (\n NestedOrganisationEntityPermission,\n OrganisationPermission,\n)\nfrom organisations.serializers import (\n MultiInvitesSerializer,\n OrganisationSerializerFull,\n OrganisationWebhookSerializer,\n PortalUrlSerializer,\n UpdateSubscriptionSerializer,\n)\nfrom projects.serializers import ProjectSerializer\nfrom users.serializers import UserIdSerializer\n\nlogger = logging.getLogger(__name__)\n\n\nclass OrganisationViewSet(viewsets.ModelViewSet):\n permission_classes = (IsAuthenticated, OrganisationPermission)\n\n def get_serializer_class(self):\n if self.action == \"remove_users\":\n return UserIdSerializer\n elif self.action == \"invite\":\n return MultiInvitesSerializer\n elif self.action == \"update_subscription\":\n return UpdateSubscriptionSerializer\n elif self.action == \"get_portal_url\":\n return PortalUrlSerializer\n return OrganisationSerializerFull\n\n def get_serializer_context(self):\n context = super(OrganisationViewSet, self).get_serializer_context()\n if self.action in (\"remove_users\", \"invite\", \"update_subscription\"):\n context[\"organisation\"] = self.kwargs.get(\"pk\")\n return context\n\n def get_queryset(self):\n return self.request.user.organisations.all()\n\n def create(self, request, **kwargs):\n \"\"\"\n Override create method to add new organisation to authenticated user\n \"\"\"\n user = request.user\n serializer = OrganisationSerializerFull(data=request.data)\n if serializer.is_valid():\n org = serializer.save()\n user.add_organisation(org, OrganisationRole.ADMIN)\n\n return Response(serializer.data, status.HTTP_201_CREATED)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n @action(detail=True, permission_classes=[IsAuthenticated])\n def projects(self, request, pk):\n organisation = self.get_object()\n projects = organisation.projects.all()\n return Response(ProjectSerializer(projects, many=True).data)\n\n @action(detail=True, methods=[\"POST\"])\n def invite(self, request, pk):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n # serializer returns a dictionary containing the list of serialized invite objects since it's a single\n # serializer generating multiple instances.\n return Response(serializer.data.get(\"invites\"), status=status.HTTP_201_CREATED)\n\n @action(detail=True, methods=[\"POST\"], url_path=\"remove-users\")\n def remove_users(self, request, pk):\n \"\"\"\n Takes a list of users and removes them from the organisation provided in the url\n \"\"\"\n serializer = self.get_serializer(data=request.data, many=True)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data, status=200)\n\n @action(detail=True, methods=[\"GET\"])\n def usage(self, request, pk):\n organisation = self.get_object()\n\n try:\n events = get_events_for_organisation(organisation.id)\n except (TypeError, ValueError):\n # TypeError can be thrown when getting service account if not configured\n # ValueError can be thrown if GA returns a value that cannot be converted to integer\n return Response(\n {\"error\": \"Couldn't get number of events for organisation.\"},\n status=status.HTTP_500_INTERNAL_SERVER_ERROR,\n )\n\n return Response({\"events\": events}, status=status.HTTP_200_OK)\n\n @action(detail=True, methods=[\"POST\"], url_path=\"update-subscription\")\n @swagger_auto_schema(responses={200: OrganisationSerializerFull})\n def update_subscription(self, request, pk):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(\n OrganisationSerializerFull(instance=self.get_object()).data,\n status=status.HTTP_200_OK,\n )\n\n @action(detail=True, methods=[\"GET\"], url_path=\"portal-url\")\n def get_portal_url(self, request, pk):\n organisation = self.get_object()\n if not organisation.has_subscription():\n return Response(\n {\"detail\": \"Organisation has no subscription\"},\n status=status.HTTP_400_BAD_REQUEST,\n )\n redirect_url = get_current_site(request)\n serializer = self.get_serializer(\n data={\"url\": organisation.subscription.get_portal_url(redirect_url)}\n )\n serializer.is_valid(raise_exception=True)\n return Response(serializer.data)\n\n @action(detail=True, methods=[\"GET\"], url_path=\"influx-data\")\n def get_influx_data(self, request, pk):\n event_list = get_multiple_event_list_for_organisation(pk)\n\n return Response(event_list)\n\n\n@api_view([\"POST\"])\n@authentication_classes([BasicAuthentication])\ndef chargebee_webhook(request):\n \"\"\"\n Endpoint to handle webhooks from chargebee.\n\n - If subscription is active, check to see if plan has changed and update if so. Always update cancellation date to\n None to ensure that if a subscription is reactivated, it is updated on our end.\n\n - If subscription is cancelled or not renewing, update subscription on our end to include cancellation date and\n send alert to admin users.\n \"\"\"\n\n if request.data.get(\"content\") and \"subscription\" in request.data.get(\"content\"):\n subscription_data = request.data[\"content\"][\"subscription\"]\n\n try:\n existing_subscription = Subscription.objects.get(\n subscription_id=subscription_data.get(\"id\")\n )\n except (Subscription.DoesNotExist, Subscription.MultipleObjectsReturned):\n error_message = (\n \"Couldn't get unique subscription for ChargeBee id %s\"\n % subscription_data.get(\"id\")\n )\n logger.error(error_message)\n return Response(status=status.HTTP_200_OK)\n\n subscription_status = subscription_data.get(\"status\")\n if subscription_status == \"active\":\n if subscription_data.get(\"plan_id\") != existing_subscription.plan:\n existing_subscription.update_plan(subscription_data.get(\"plan_id\"))\n elif subscription_status in (\"non_renewing\", \"cancelled\"):\n existing_subscription.cancel(\n datetime.fromtimestamp(subscription_data.get(\"current_term_end\"))\n )\n\n return Response(status=status.HTTP_200_OK)\n\n\nclass OrganisationWebhookViewSet(viewsets.ModelViewSet):\n serializer_class = OrganisationWebhookSerializer\n permission_classes = [IsAuthenticated, NestedOrganisationEntityPermission]\n\n def get_queryset(self):\n if \"organisation_pk\" not in self.kwargs:\n raise ValidationError(\"Missing required path parameter 'organisation_pk'\")\n\n return OrganisationWebhook.objects.filter(\n organisation_id=self.kwargs[\"organisation_pk\"]\n )\n\n def perform_update(self, serializer):\n organisation_id = self.kwargs[\"organisation_pk\"]\n serializer.save(organisation_id=organisation_id)\n\n def perform_create(self, serializer):\n organisation_id = self.kwargs[\"organisation_pk\"]\n serializer.save(organisation_id=organisation_id)\n","sub_path":"src/organisations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"362254532","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_cors import CORS\nfrom models import setup_db, Actor, Movie\nfrom auth.auth import AuthError, requires_auth\n\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n setup_db(app)\n CORS(app)\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,true')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PATCH,POST,DELETE,OPTIONS')\n return response\n\n @app.route('/actors', methods=['GET'])\n @requires_auth('get:actors')\n def get_actors(jwt):\n actors = Actor.query.all()\n\n if len(actors) == 0:\n abort(404)\n\n return jsonify({\n 'success': True,\n 'actors': [actor.format() for actor in actors]\n }), 200\n\n @app.route('/movies', methods=['GET'])\n @requires_auth('get:movies')\n def get_movies(jwt):\n movies = Movie.query.all()\n\n if len(movies) == 0:\n abort(404)\n\n return jsonify({\n 'success': True,\n 'movies': [movie.format() for movie in movies]\n }), 200\n\n @app.route('/actors/', methods=['DELETE'])\n @requires_auth('delete:actor')\n def delete_actor(jwt, actor_id):\n try:\n actor = Actor.query.filter(Actor.id == actor_id).one_or_none()\n\n if actor is None:\n abort(404)\n\n actor.delete()\n\n return jsonify({\n 'success': True,\n 'deleted': actor_id\n })\n\n except:\n abort(422)\n\n @app.route('/movies/', methods=['DELETE'])\n @requires_auth('delete:movie')\n def delete_movie(jwt, movie_id):\n try:\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n\n if movie is None:\n abort(404)\n\n movie.delete()\n\n return jsonify({\n 'success': True,\n 'deleted': movie_id\n })\n\n except:\n abort(422)\n\n @app.route('/create_actor', methods=['POST'])\n @requires_auth('post:actors')\n def create_actor(jwt):\n body = request.get_json()\n\n # actor = Actor()\n # actor.name = body['name']\n # actor.age = body['age']\n # actor.gender = body['gender']\n\n # new_name = body.get('name', None)\n # new_age = body.get('age', None)\n # new_gender = body.get('gender', None)\n\n try:\n actor = Actor(name=body['name'], age=body['age'], gender=body['gender'])\n actor.insert()\n\n return jsonify({\n 'success': True,\n 'actor': [actor.format() for actor in actor]\n })\n\n except:\n abort(422)\n\n @app.route('/create_movie', methods=['POST'])\n @requires_auth('post:movies')\n def create_movie(jwt):\n body = request.get_json()\n\n # movie = Movie()\n # movie.title = body['title']\n # movie.release = body['release']\n\n # new_title = body.get('title', None)\n # new_release = body.get('release', None)\n\n try:\n movie = Movie(title=body['title'], release=body['release'])\n # movie = Movie(title=new_title, release=new_release)\n movie.insert()\n\n return jsonify({\n 'success': True,\n 'movie': [movie.format() for movie in movie]\n })\n\n except:\n abort(422)\n\n @app.route('/actors/', methods=['PATCH'])\n @requires_auth('patch:actor')\n def update_actor(jwt, id):\n body = request.get_json()\n actor = Actor.query.filter(Actor.id == id).one_or_none()\n\n if actor is None:\n abort(404)\n\n try:\n get_name = body.get('name', None)\n get_age = body.get('age', None)\n get_gender = body.get('gender', None)\n\n if get_name:\n actor.name = get_name\n\n if get_age:\n actor.age = get_age\n\n if get_gender:\n actor.gender = get_gender\n\n actor.update()\n\n return jsonify({\n 'success': True,\n 'actors': [actor.format() for actor in actor]\n }), 200\n\n except:\n abort(422)\n\n @app.route('/movies/', methods=['PATCH'])\n @requires_auth('patch:movie')\n def update_movie(jwt, id):\n body = request.get_json()\n movie = Movie.query.filter(Movie.id == id).one_or_none()\n\n if movie is None:\n abort(404)\n\n try:\n get_title = body.get('title', None)\n get_release = body.get('release', None)\n\n if get_title:\n movie.title = get_title\n\n if get_release:\n movie.release = get_release\n\n movie.update()\n\n return jsonify({\n 'success': True,\n 'movies': [movie.format() for movie in movie]\n }), 200\n\n except:\n abort(422)\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"Not found\"\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n @app.errorhandler(400)\n def bad_request(error):\n return jsonify({\n \"success\": False,\n \"error\": 400,\n \"message\": \"bad request\"\n }), 400\n\n @app.errorhandler(500)\n def server_error(error):\n return jsonify({\n \"success\": False,\n \"error\": 500,\n \"message\": \"internet server error\"\n }), 500\n\n @app.errorhandler(AuthError)\n def handle_auth_error(ex):\n response = jsonify(ex.error)\n response.status_code = ex.status_code\n return response\n\n\n # @app.route('/')\n # def get_greeting():\n # excited = os.environ['EXCITED']\n # greeting = \"Hello\"\n # if excited == 'true': greeting = greeting + \"!!!!!\"\n # return greeting\n #\n # @app.route('/coolkids')\n # def be_cool():\n # return \"Be cool, man, be coooool! You're almost a FSND grad!\"\n\n return app\n\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"heroku_sample/starter/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"482216357","text":"#!/usr/bin/python3\n#author Colin Etzel\nimport argparse\nfrom trec_car.read_data import *\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"outline_file\", type=str, help=\"Qualified location of the outline file\")\nparser.add_argument(\"output_file\", type=str, help=\"Name of the output file\")\nargs = vars(parser.parse_args())\n\nquery_cbor = args['outline_file']\noutput_file_name = args['output_file']\n\npages = []\nwith open(query_cbor, 'rb') as f:\n for p in itertools.islice(iter_annotations(f), 0, 1000):\n pages.append(p)\n\n# Generate queries in plain text\nplain_text_queries = []\nfor page in pages:\n for section_path in page.flat_headings_list():\n query_id_plain = \" \".join([page.page_name] + [section.heading for section in section_path])\n query_id_formatted = \"/\".join([page.page_id] + [section.headingId for section in section_path])\n tup = (query_id_plain, query_id_formatted)\n plain_text_queries.append(tup)\n\noutfile = open(str(output_file_name), \"w\")\nfor tup in plain_text_queries:\n outfile.write(tup[0]+\"\\n\")\n outfile.write(tup[1]+\"\\n\")","sub_path":"benchmark/bm_queryExtractor.py","file_name":"bm_queryExtractor.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"335204137","text":"from bge import logic as g, events as e\nfrom kxgui import *\nimport bgl\n\ndef addClick(sender):\n sender.monkey.localScale.x += 0.02\n sender.monkey.localScale.y += 0.02\n sender.monkey.localScale.z += 0.02\n\ndef subClick(sender):\n sender.monkey.localScale.x -= 0.02\n sender.monkey.localScale.y -= 0.02\n sender.monkey.localScale.z -= 0.02\n\ndef main(cont):\n o = cont.owner\n sce = g.getCurrentScene()\n suz = sce.objects[\"Suzanne\"]\n\n if \"init\" not in o:\n o[\"gui\"] = GUI.new()\n o[\"gui\"].loadTheme(g.expandPath(\"//kxgui/examples/theme.json\"))\n\n o[\"gui\"].cursor = Cursor.new(g.expandPath(\"//cursor1.png\"))\n\n box = o[\"gui\"].addWidget(\"box\", Box.new(x=0.02, y=0.02, width=0.2, height=0.4))\n\n box.addWidget(\"lblColor\", Label.new(text=\"Color\"))\n R = box.addWidget(\"R\", Scroller.new(orientation=0, height=0.03))\n G = box.addWidget(\"G\", Scroller.new(orientation=0, height=0.03))\n B = box.addWidget(\"B\", Scroller.new(orientation=0, height=0.03))\n\n box.addWidget(\"lblScale\", Label.new(text=\"Scale\"))\n\n box2 = box.addWidget(\"box2\", Box.new(height=0.1))\n box2.layout.orientation = 0\n\n ADD = box2.addWidget(\"ADD\", Button.new(width=0.084, text=\"+\"))\n ADD.events.callbacks[\"on_click\"] = addClick\n SUB = box2.addWidget(\"SUB\", Button.new(width=0.084, text=\"-\"))\n SUB.events.callbacks[\"on_click\"] = subClick\n\n ADD.events.monkey = SUB.events.monkey = suz\n\n check = box.addWidget(\"VIS\", CheckBox.new(text=\"Visible\", checked=True))\n\n box.addWidget(\"TBOX\", TextBox.new(text=\"TextBox\"))\n\n o[\"gui\"].applyToScene()\n o[\"init\"] = 1\n else:\n o[\"gui\"].update()\n widgets = o[\"gui\"].widgets[\"box\"].widgets\n\n suz.color[0] = widgets[\"R\"].value / widgets[\"R\"].max\n suz.color[1] = widgets[\"G\"].value / widgets[\"G\"].max\n suz.color[2] = widgets[\"B\"].value / widgets[\"B\"].max\n\n suz.visible = widgets[\"VIS\"].checked\n","sub_path":"examples/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"216067801","text":"from functools import partial\nfrom os.path import join\n\nfrom designer.utils import constants\nfrom designer.utils.utils import get_kd_data_dir, get_kd_dir\nfrom kivy.adapters.listadapter import ListAdapter\nfrom kivy.core.window import Keyboard, Window\nfrom kivy.factory import Factory\nfrom kivy.properties import NumericProperty, ObjectProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.listview import ListView\n\n\nNEW_PROJECTS = {\n 'FloatLayout': ('template_floatlayout_kv',\n 'template_floatlayout_py'),\n 'BoxLayout': ('template_boxlayout_kv',\n 'template_boxlayout_py'),\n 'ScreenManager': ('template_screen_manager_kv',\n 'template_screen_manager_py'),\n 'ActionBar': ('template_actionbar_kv',\n 'template_actionbar_py'),\n 'Carousel and ActionBar': ('template_actionbar_carousel_kv',\n 'template_actionbar_carousel_py'),\n 'ScreenManager and ActionBar': ('template_screen_manager_actionbar_kv',\n 'template_screen_manager_actionbar_py'),\n 'TabbedPanel': ('template_tabbed_panel_kv',\n 'template_tabbed_panel_py'),\n 'TextInput and ScrollView': ('template_textinput_scrollview_kv',\n 'template_textinput_scrollview_py')}\n\n\nclass NewProjectDialog(BoxLayout):\n\n listview = ObjectProperty(None)\n ''':class:`~kivy.uix.listview.ListView` used for showing file paths.\n :data:`listview` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n select_button = ObjectProperty(None)\n ''':class:`~kivy.uix.button.Button` used to select the list item.\n :data:`select_button` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n cancel_button = ObjectProperty(None)\n ''':class:`~kivy.uix.button.Button` to cancel the dialog.\n :data:`cancel_button` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n adapter = ObjectProperty(None)\n ''':class:`~kivy.uix.listview.ListAdapter` used for selecting files.\n :data:`adapter` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n image = ObjectProperty(None)\n '''Type of :class:`~kivy.uix.image.Image` to display image of selected\n new template.\n :data:`image` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n list_parent = ObjectProperty(None)\n '''Parent of listview.\n :data:`list_parent` is a :class:`~kivy.properties.ObjectProperty`\n '''\n\n prev_selection = NumericProperty(0)\n '''to memorize the previous selection.\n :attr:`prev_selection` is a :class:\n `~kivy.properties.NumericProperty`, defaults to (0).\n '''\n\n __events__ = ('on_select', 'on_cancel')\n\n def __init__(self, **kwargs):\n super(NewProjectDialog, self).__init__(**kwargs)\n item_strings = list(NEW_PROJECTS.keys())\n item_strings.sort()\n self.adapter = ListAdapter(cls=Factory.DesignerListItemButton,\n data=item_strings,\n selection_mode='single',\n allow_empty_selection=False)\n self.adapter.check_for_empty_selection = self.check_for_empty_selection\n self.adapter.bind(on_selection_change=self.on_adapter_selection_change)\n self.listview = ListView(adapter=self.adapter)\n self.listview.size_hint = (0.5, 1)\n self.listview.pos_hint = {'top': 1}\n self.list_parent.add_widget(self.listview, 1)\n self.on_adapter_selection_change(self.adapter)\n\n def on_parent(self, *args):\n if self.parent:\n Window.bind(on_key_down=self._on_keyboard_down)\n else:\n Window.unbind(on_key_down=self._on_keyboard_down)\n\n def _on_keyboard_down(self, keyboard, key, codepoint,\n text, modifier, *args):\n '''To detect which key is pressed\n '''\n if modifier:\n return False\n key_str = Keyboard.keycode_to_string(Window._system_keyboard, key)\n if key_str == 'up':\n v = self.adapter.get_view(self.prev_selection - 1)\n if v is not None:\n self.adapter.handle_selection(v)\n return True\n if key_str == 'down':\n v = self.adapter.get_view(self.prev_selection + 1)\n if v is not None:\n self.adapter.handle_selection(v)\n return True\n if key_str == 'enter':\n self.dispatch('on_select')\n return True\n\n def check_for_empty_selection(self, *args):\n if not self.adapter.allow_empty_selection:\n if len(self.adapter.selection) == 0:\n # Select the first item if we have it.\n v = self.adapter.get_view(self.prev_selection)\n if v is not None:\n self.adapter.handle_selection(v)\n\n def on_adapter_selection_change(self, adapter):\n '''Event handler for 'on_selection_change' event of adapter.\n '''\n name = adapter.selection[0].text.lower() + '.png'\n name = name.replace(' and ', '_')\n image_source = join(constants.NEW_TEMPLATE_IMAGE_PATH, name)\n image_source = join(get_kd_data_dir(), image_source)\n parent = self.image.parent\n parent.remove_widget(self.image)\n self.image = Image(source=image_source)\n parent.add_widget(self.image)\n self.prev_selection = adapter.data.index(adapter.selection[0].text)\n\n def on_touch_down(self, touch):\n '''Used to determine where touch is down and to detect double\n tap.\n '''\n if touch.is_double_tap:\n self.dispatch('on_select')\n return super(NewProjectDialog, self).on_touch_down(touch)\n\n def on_select(self, *args):\n '''Default Event Handler for 'on_select' event\n '''\n pass\n\n def on_cancel(self, *args):\n '''Default Event Handler for 'on_cancel' event\n '''\n pass\n\n def on_select_button(self, *args):\n '''Event Handler for 'on_release' of select button.\n '''\n self.select_button.bind(on_press=partial(self.dispatch, 'on_select'))\n\n def on_cancel_button(self, *args):\n '''Event Handler for 'on_release' of cancel button.\n '''\n self.cancel_button.bind(on_press=partial(self.dispatch, 'on_cancel'))\n","sub_path":"designer/components/dialogs/new_project.py","file_name":"new_project.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"103920208","text":"import cv2\nimport numpy as np\n\n# img = cv2.imread()\ncv2.namedWindow('image')\nborder = 10\n\ncapture = cv2.VideoCapture(0)\nwhile capture.isOpened():\n flag, img = capture.read()\n (height, width) = img.shape[:2]\n contour = np.array([(border, border), (border, height-border),\n (width-border, height-border), (width-border, border)],\n dtype=np.int)\n cv2.drawContours(img, [contour], -1, (255, 0, 0), 1)\n cv2.imshow('image', img)\n if cv2.waitKey(0) == ord('q'):\n exit()\n","sub_path":"Eye_OpenCV/src/contour_test.py","file_name":"contour_test.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"646019977","text":"import qrcode\n# 处理图像的第三方库\nfrom PIL import Image\n\nicon_image = 'dog.jpg'\nout_image = 'result_inner.gif'\n\nqr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_H,\n box_size=10,\n border=1\n)\n\nqr.add_data('hello~')\nqr.make(fit=True)\n\nimg = qr.make_image(fill_color='black',back_color='white')\nimg = img.convert('RGBA')\n\nicon = Image.open(icon_image)\n\nimg_w,img_h = img.size\nfactor = 4\nsize_w = int(img_w / factor)\nsize_h = int(img_h / factor+10)\n\nicon_w,icon_h = icon.size\nif icon_w > size_w:\n icon_w = size_w\nif icon_h > size_h:\n icon_h = size_h\n\n# 调整icon图片大小 (ANTIALIAS是指平滑缩放)\nicon = icon.resize((icon_w,icon_h),Image.ANTIALIAS)\n\nw = int((img_w - icon_w) / 2)\nh = int((img_h - icon_h) / 2)\n\n# 重绘二维码\nimg.paste(icon,(w,h))\nimg.save(out_image)","sub_path":"image_qrcode_inner.py","file_name":"image_qrcode_inner.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"408994561","text":"\"\"\"add models\n\nRevision ID: 68641436a372\nRevises: \nCreate Date: 2020-09-21 23:43:21.218808\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '68641436a372'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('users',\n sa.Column('uid', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(), nullable=True),\n sa.Column('password', sa.String(), nullable=True),\n sa.Column('first_name', sa.String(), nullable=True),\n sa.Column('last_name', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('uid')\n )\n op.create_table('wallets',\n sa.Column('uid', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('funds', sa.BigInteger(), nullable=True),\n sa.Column('owner_uid', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['owner_uid'], ['users.uid'], ),\n sa.PrimaryKeyConstraint('uid')\n )\n op.create_table('transactions',\n sa.Column('uid', sa.Integer(), nullable=False),\n sa.Column('from_wallet_uid', sa.Integer(), nullable=True),\n sa.Column('to_wallet_uid', sa.Integer(), nullable=True),\n sa.Column('amount', sa.BigInteger(), nullable=True),\n sa.Column('datetime', sa.DateTime(), server_default=sa.text('now()'), nullable=True),\n sa.ForeignKeyConstraint(['from_wallet_uid'], ['wallets.uid'], ),\n sa.ForeignKeyConstraint(['to_wallet_uid'], ['wallets.uid'], ),\n sa.PrimaryKeyConstraint('uid')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('transactions')\n op.drop_table('wallets')\n op.drop_table('users')\n # ### end Alembic commands ###\n","sub_path":"L4/src/alembic/versions/68641436a372_add_models.py","file_name":"68641436a372_add_models.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"97265841","text":"import functools\nimport sys\n\n\ndef query(client, wid, query_contents, dialect='postgresql', limit=None):\n \"\"\"Query metadata.\"\"\"\n\n if limit is None:\n kwargs = dict(per_page=100)\n limit = sys.maxsize\n else:\n kwargs = dict(per_page=min(limit, 100))\n\n query_obj = {\n 'dialect': dialect,\n 'query': query_contents,\n }\n\n if wid is None:\n query_details = client.public_query_create(query_obj, **kwargs)\n details_func = client.public_query_details\n else:\n query_details = client.workspace_query_create(wid, query_obj, **kwargs)\n details_func = functools.partial(client.workspace_query_details, wid)\n\n results = query_details.results\n if not results:\n return [], 0\n\n # The query POST action redirects to the GET details but does not have\n # a per_page, so we might get more that we needed\n if len(results) > limit:\n results = results[:limit]\n\n while len(results) < limit and len(results) < query_details.total:\n kwargs['page'] = kwargs.get('page', 1) + 1\n query_details = details_func(query_details.id, **kwargs)\n results.extend(query_details.results)\n\n return results, query_details.total\n","sub_path":"quetzal/client/helpers/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"93117764","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom random import choice\nfrom collections import OrderedDict\nimport tweepy\n\nquoteWords = OrderedDict([\n\t\t(\"one\", [\"Sometimes \", \"Often \", \"Occasionally \", \"Usually \"]),\n\t\t(\"two\", [\"it's best to \", \"you should \", \"you shouldn't \", \"it's easy to \", \"it's hard to \"]),\n\t\t(\"three\", [\"do \", \"avoid \", \"finish \", \"create \", \"witness \"]),\n\t\t(\"four\", [\"the \", \"a \", \"your \", \"society's \", \"your friends\"]),\n\t\t(\"five\", [\"best \", \"most important \", \"funniest \"]),\n\t\t(\"six\", [\"work.\", \"art.\", \"hobby.\", \"posessions.\"]),\n])\n\ndef inspire():\n\tquote = []\n\tcounter = 0\n\tfor key in quoteWords:\n\t\tquote.insert(counter, choice(quoteWords[key]))\n\t\tcounter += 1\n\treturn(''.join(quote))\n\ndef get_api(cfg):\n\tauth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])\n\tauth.set_access_token(cfg['access_token'], cfg['access_token_secret'])\n\treturn tweepy.API(auth)\n\ndef main():\n\tcfg = { \n\t\t\"consumer_key\"\t\t\t:\t\"00000\",\n\t\t\"consumer_secret\"\t\t:\t\"00000\",\n\t\t\"access_token\"\t\t\t:\t\"00000\",\n\t\t\"access_token_secret\"\t:\t\"00000\" \n\t\t}\n\n\tapi = get_api(cfg)\n\ttweet = inspire()\n\tstatus = api.update_status(status=tweet) #Send out tweet ('status') of tweet string\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"622133700","text":"import json\nimport os\n\n\n# 查询数据范围\ndef findtb(source, start, end, tb, brace=0):\n i = j = 0\n tb[0] = start\n tb[1] = end\n for i in range(start, end):\n if source[i] == '{':\n brace += 1\n if brace > 0:\n tb[0] = i + 1\n for j in range(i + 1, tb[1]):\n if source[j] == '{':\n brace += 1\n elif source[j] == '}':\n brace -= 1\n if brace == 0:\n tb[1] = j - 1\n return True\n elif source[i] == '}':\n return False\n return False\n\n\ndef finditemname(source, tb):\n i = source.rfind('\\\"', 0, tb[0])\n j = source.rfind('\\\"', 0, i - 1)\n return source[j + 6:i]\n\n\n# 寻找属性(查询源字符串,数据存储位置,上下限,属性序数,是否继承默认数据)\ndef finditempro(source, data, tb, pro, number=True, bool=False):\n if bool:\n i = source.find(pro[1], tb[0], tb[1])\n if i != -1:\n data[pro[1]] = {\"1\": 1}\n else:\n i = source.find('\\\"' + pro[1] + '\\\"', tb[0], tb[1])\n if i != -1:\n j = source.find('\\\"', i + 1, tb[1])\n j = source.find('\\\"', j + 1, tb[1])\n k = source.find('\\\"', j + 1, tb[1])\n if number:\n if source[j + 1:k] != '':\n data[pro[1]] = {}\n splitit = source[j + 1:k].split(' ')\n for l in range(len(splitit)):\n data[pro[1]][str(l + 1)] = float(splitit[l])\n else:\n if source[j + 1:k] != '':\n data[pro[1]] = {}\n splitit = source[j + 1:k].split(';')\n splitit = source[j + 1:k].split(';')\n if len(pro) == 3:\n for l in range(len(splitit)):\n data[pro[1]][str(l + 1)] = pro[2][splitit[l]]\n else:\n for l in range(len(splitit)):\n data[pro[1]][str(l + 1)] = splitit[l]\n\n\ndef finditemrequire(source, data, tb):\n data[\"ItemRequirements\"] = {}\n i = source.find(\"ItemRequirements\", tb[0], tb[1])\n if i == -1:\n return\n else:\n j = source.find(\"{\", i, tb[1])\n k = source.find(\"}\", j + 1, tb[1])\n r = [j, j]\n while True:\n r[0] = source.find('\\\"', r[1] + 1, k) + 1\n if r[0] != 0:\n r[0] = source.find('\\\"', r[0], k) + 1\n r[0] = source.find('\\\"', r[0], k) + 1\n r[1] = source.find('\\\"', r[0], k)\n splitit = source[r[0]:r[1]].split(';')\n data[\"ItemRequirements\"][str(len(data[\"ItemRequirements\"]) + 1)] = {}\n for l in range(len(splitit)):\n if len(splitit[l]) > 5:\n data[\"ItemRequirements\"][str(len(data[\"ItemRequirements\"]))][str(l + 1)] = splitit[l][5:]\n else:\n return\n\n\ndef finditemspecial(source, data, tb):\n i = source.find(\"AbilitySpecial\", tb[0], tb[1])\n if i == -1:\n return\n else:\n k = source.find(\"{\", i, tb[1])\n while True:\n j = source.find(\"{\", k + 1, tb[1])\n k = source.find(\"}\", k + 1, tb[1])\n if j < k and j != -1:\n r = [0, 0, 0, 0]\n r[0] = source.find('\\\"', j, k) + 1\n r[0] = source.find('\\\"', r[0], k) + 1\n r[0] = source.find('\\\"', r[0], k) + 1\n r[0] = source.find('\\\"', r[0], k) + 1\n r[0] = source.find('\\\"', r[0], k) + 1\n r[1] = source.find('\\\"', r[0], k)\n r[2] = source.find('\\\"', r[1] + 1, k) + 1\n r[3] = source.find('\\\"', r[2], k)\n splitit = source[r[2]:r[3]].split(' ')\n data[source[r[0]:r[1]]] = {}\n for l in range(len(splitit)):\n if (splitit[l][-1] == 'f'):\n data[source[r[0]:r[1]]][str(l + 1)] = float(splitit[l][0:-1])\n else:\n data[source[r[0]:r[1]]][str(l + 1)] = float(splitit[l])\n else:\n return\n\n\ndef get_hero_data_from_txt(base_txt, ffile):\n source_string = ffile.read().decode('utf8')\n tb = [0, source_string.find(\"{\") + 1]\n item_all = {}\n item_count = 0\n while (True):\n if (findtb(source_string, tb[1] + 2, len(source_string), tb, 0)):\n name = finditemname(source_string, tb)\n base_txt[name] = {}\n for i in itempro_txt:\n finditempro(source_string, base_txt[name], tb, i, False)\n for i in itempro_num:\n finditempro(source_string, base_txt[name], tb, i)\n for i in itempro_bool:\n finditempro(source_string, base_txt[name], tb, i, False, True)\n finditemrequire(source_string, base_txt[name], tb)\n finditemspecial(source_string, base_txt[name], tb)\n else:\n break\n\n\ndef fulfill_item_json(base_txt, all_json, version):\n for ii in all_json:\n all_json[ii][\"分类\"] = \"物品\"\n all_json[ii][\"版本\"] = version\n all_json[ii][\"应用\"] = 1\n if '图片' not in all_json[ii] or all_json[ii]['图片'] == '':\n all_json[ii]['图片'] = 'items_' + all_json[ii][\"代码名\"] + '.png'\n if '迷你图片' not in all_json[ii] or all_json[ii]['迷你图片'] == '':\n all_json[ii]['迷你图片'] = 'items_' + all_json[ii][\"代码名\"] + '.png'\n if '升级' in all_json[ii]:\n all_json[ii].pop('升级')\n for i in item_for_item:\n if i in base_txt[\"物品\"][all_json[ii]['代码名']]:\n all_json[ii][i] = base_txt[\"物品\"][all_json[ii]['代码名']][i]\n for i in all_json[ii]:\n if isinstance(all_json[ii][i], dict) and '代码' in all_json[ii][i] and all_json[ii][i][\"代码\"] in base_txt[\"物品\"][all_json[ii][\"代码名\"]]:\n if str(all_json[ii]['等级']) in base_txt[\"物品\"][all_json[ii][\"代码名\"]][all_json[ii][i][\"代码\"]]:\n all_json[ii][i][\"1\"] = base_txt[\"物品\"][all_json[ii][\"代码名\"]][all_json[ii][i][\"代码\"]][str(all_json[ii]['等级'])]\n else:\n all_json[ii][i][\"1\"] = base_txt[\"物品\"][all_json[ii][\"代码名\"]][all_json[ii][i][\"代码\"]][\"1\"]\n if all_json[ii][\"商店\"][\"1\"][:2] == '中立':\n all_json[ii][\"价格\"][\"1\"] = '中立生物掉落'\n # 以下是确认物品的组件、卷轴情况\n if all_json[ii][\"合成\"] >= 0:\n if all_json[ii][\"合成\"] == 0:\n hecheng = \"1\"\n else:\n hecheng = str(all_json[ii][\"合成\"])\n if ('recipe_' + all_json[ii][\"代码名\"]) in base_txt[\"物品\"] and len(base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"])>=int(hecheng):\n all_json[ii][\"组件\"] = {}\n if base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemCost\"][\"1\"] != 0:\n if all_json[ii][\"商店\"][\"1\"][:2] == '中立':\n all_json[ii][\"价格\"] = {'代码': 'ItemCost',\n '1': base_txt[\"物品\"][all_json[ii][\"代码名\"]]['ItemCost'][\"1\"] - base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]]['ItemCost'][\"1\"]}\n all_json[ii][\"卷轴价格\"] = {'代码': 'ItemCost', '1': '中立生物掉落'}\n else:\n all_json[ii][\"卷轴价格\"] = {'代码': 'ItemCost', '1': base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemCost\"][\"1\"]}\n all_json[ii][\"组件\"] = {}\n for jj in base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng]:\n all_json[ii][\"组件\"][jj] = base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng][jj]\n else:\n if base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng][str(\n len(base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng]))][0:6] == 'recipe':\n all_json[ii][\"卷轴价格\"] = {'代码': 'ItemCost', '1':\n base_txt[\"物品\"][\n base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng][\n str(len(base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng]))]][\n \"ItemCost\"][\"1\"]}\n all_json[ii][\"组件\"] = {}\n for j in range(len(base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng]) - 1):\n all_json[ii][\"组件\"][str(j + 1)] = base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng][str(j + 1)]\n else:\n all_json[ii][\"卷轴价格\"] = {'代码': 'ItemCost', '1': 0}\n all_json[ii][\"组件\"] = {}\n for jj in base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng]:\n all_json[ii][\"组件\"][jj] = base_txt[\"物品\"]['recipe_' + all_json[ii][\"代码名\"]][\"ItemRequirements\"][hecheng][jj]\n\n # 接下来把所有的组件变成中文名+图片的形式\n for i in all_json:\n if \"组件\" in all_json[i]:\n for j in all_json[i][\"组件\"]:\n for k in all_json:\n if all_json[i][\"组件\"][j] == all_json[k][\"代码名\"]:\n all_json[i][\"组件\"][j] = {\"物品名\": all_json[k][\"页面名\"], \"图片\": all_json[k][\"图片\"]}\n # 接下来把所有的升级放在这儿\n for i in all_json:\n if \"组件\" in all_json[i]:\n if all_json[i][\"合成\"] == 0:\n for j in base_txt[\"物品\"]['recipe_' + all_json[i][\"代码名\"]][\"ItemRequirements\"]:\n for k in base_txt[\"物品\"]['recipe_' + all_json[i][\"代码名\"]][\"ItemRequirements\"][j]:\n for l in all_json:\n if all_json[l][\"代码名\"] == base_txt[\"物品\"]['recipe_' + all_json[i][\"代码名\"]][\"ItemRequirements\"][j][k]:\n if \"升级\" not in all_json[l]:\n all_json[l][\"升级\"] = {\"1\": {\"物品名\": all_json[i][\"页面名\"], \"图片\": all_json[i][\"图片\"]}}\n elif all_json[l][\"升级\"][str(len(all_json[l][\"升级\"]))][\"物品名\"] != i:\n all_json[l][\"升级\"][str(len(all_json[l][\"升级\"]) + 1)] = {\"物品名\": all_json[i][\"页面名\"], \"图片\": all_json[i][\"图片\"]}\n else:\n for j in all_json[i][\"组件\"]:\n if \"升级\" not in all_json[all_json[i][\"组件\"][j][\"物品名\"]]:\n all_json[all_json[i][\"组件\"][j][\"物品名\"]][\"升级\"] = {\"1\": {\"物品名\": all_json[i][\"页面名\"], \"图片\": all_json[i][\"图片\"]}}\n elif all_json[all_json[i][\"组件\"][j][\"物品名\"]][\"升级\"][str(len(all_json[all_json[i][\"组件\"][j][\"物品名\"]][\"升级\"]))][\"物品名\"] != i:\n all_json[all_json[i][\"组件\"][j][\"物品名\"]][\"升级\"][str(len(all_json[all_json[i][\"组件\"][j][\"物品名\"]][\"升级\"]) + 1)] = {\"物品名\": all_json[i][\"页面名\"],\n \"图片\": all_json[i][\"图片\"]}\n # 这里开始同商店物品填入\n all_json[i][\"同商店物品\"] = {}\n if isinstance(all_json[i][\"商店\"], str):\n all_json[i][\"商店\"] = {\"1\": all_json[i][\"商店\"]}\n for i in all_json:\n for j in all_json[i][\"商店\"]:\n all_json[i][\"同商店物品\"][j] = {}\n for k in all_json:\n for l in all_json[k][\"商店\"]:\n if all_json[i][\"商店\"][j] == all_json[k][\"商店\"][l]:\n all_json[i][\"同商店物品\"][j][str(len(all_json[i][\"同商店物品\"][j]) + 1)] = {\"物品名\": all_json[k][\"页面名\"], \"图片\": all_json[k][\"图片\"]}\n\n\ndef create_file(all_json):\n for i in all_json:\n file = open(\"E:/json/pythonupload/\" + i + '.json', mode=\"w\")\n file.write(json.dumps(all_json[i]))\n file.close()\n\n\nitempro_txt = [[\"商店标识\", \"ItemShopTags\"]\n , [\"质量\", \"ItemQuality\"]\n , [\"别名\", \"ItemAliases\"]\n , [\"可拆分\", \"ItemDisassembleRule\", {\"DOTA_ITEM_DISASSEMBLE_NEVER\": 0, \"DOTA_ITEM_DISASSEMBLE_ALWAYS\": 1}]\n ]\nitempro_num = [[\"施法距离\", \"AbilityCastRange\"]\n , [\"魔法消耗\", \"AbilityManaCost\"]\n , [\"施法前摇\", \"AbilityCastPoint\"]\n , [\"冷却时间\", \"AbilityCooldown\"]\n , [\"价格\", \"ItemCost\"]\n , [\"边路商店\", \"SideShop\"]\n , [\"可堆叠\", \"ItemStackable\"]\n , [\"耗尽后不消失\", \"ItemPermanent\"]\n , [\"初始充能\", \"ItemInitialCharges\"]\n , [\"上货时间\", \"ItemStockTime\"]\n , [\"初始货量\", \"ItemStockInitial\"]\n , [\"最大货量\", \"ItemStockMax\"]\n , [\"初始上货时间\", \"ItemInitialStockTime\"]\n , [\"可提醒队友\", \"ItemAlertable\"]\n ]\nitempro_bool = [[\"即时生效\", \"DOTA_ABILITY_BEHAVIOR_IMMEDIATE\"]]\nitem_for_item = [\"边路商店\", \"价格\", \"上货时间\", \"初始货量\", \"最大货量\", \"初始上货时间\", \"可提醒队友\", \"可拆分\"]\n","sub_path":"text_to_json/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":13785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"54658045","text":"from django import forms\n\nfrom vereinsmanager.models import MemberOrpheus\n\n\nclass BecomeMemberForm(forms.ModelForm):\n \"\"\"\n Form for applying as Orpheus e.V. member\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n class Meta:\n model = MemberOrpheus\n fields = ['address', 'plz', 'city', 'finished_school']\n\n def clean(self):\n \"\"\"\n Custom clean method to check whether plz\n is a number. We don't use a IntegerField because\n we loose then leading zeros\n \"\"\"\n # check whether plz is number\n try:\n _ = int(self.cleaned_data.get('plz'))\n except Exception:\n raise forms.ValidationError({'plz': [_(\"The postal code has to be a number.\")]})\n\n return self.cleaned_data\n","sub_path":"vereinsmanager/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"376967262","text":"\"\"\"\nLogging Client\nCompatible with Python 2 & 3\nSee \"example.py\" for usage.\n\n(c) Christopher Goes 2015\n\n\"\"\"\n\nfrom __future__ import print_function\nimport threading\n\nimport time\nimport inspect\nimport os\n\ntry:\n from Queue import Queue\nexcept ImportError:\n from queue import Queue\n\nimport zmq\n\nfrom auvlog import config\n\n_current_pid = [-1]\n_message_queue = Queue()\n\n_log = lambda obj: _message_queue.put(obj)\n\n_fmt = lambda tree, timestamp, message, filename, lineno, block, linetxt: {\n 'tree': tree,\n 'timestamp': timestamp,\n 'message': message,\n 'filename': filename,\n 'lineno': lineno,\n 'block': block,\n 'linetxt': linetxt\n}\n\ndef _client():\n context = zmq.Context()\n socket = context.socket(zmq.PUB)\n socket.connect(\"tcp://127.0.0.1:{0}\".format(config.CLIENT_PORT))\n\n while True:\n socket.send_json(_message_queue.get())\n\nclass Logger:\n\n \"\"\"\n CUAUV central logging utility. An instance of this class will be able to send logs to the logging daemon.\n\n To use, make an instance of this class. Any instance will log with it's current prefix. A prefix is a tuple of\n strings that can either be passed in as *args, or a level can be added by accessing an attribute of any current\n instance. Any instance can be called with a message to be logged.\n \"\"\"\n\n def __init__(self, tree):\n self.tree = tree\n\n def __call__(self, message):\n new_pid = os.getpid()\n\n if _current_pid[0] != new_pid:\n _current_pid[0] = new_pid\n t = threading.Thread(target=_client)\n t.daemon = True\n t.start()\n\n frame = inspect.stack()[1]\n _log(_fmt(\n '.'.join(self.tree),\n time.time(),\n message,\n frame[1],\n frame[2],\n frame[3],\n frame[4][0] if frame[4] is not None else ''\n ))\n\n def __repr__(self):\n return 'Logger'.format(self.tree)\n\n def __getattr__(self, key):\n return Logger(self.tree + [key])\n\n\nlog = Logger([])\n","sub_path":"auvlog/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"120579286","text":"# coding=utf-8\n\nimport http_common\nimport simplejson as json\n\nfrom db_operator import getList\nfrom string_to_dict import StringToDictConverter\n\n\ndef get_json(url):\n\th = http_common.HttpProcesser(url)\n\tcontent = h.get()\n\tStringToDictConverter(content).convert()\n\t# print(\"****\"+model)\n\n\ndef get_url(ids):\n\turl = \"http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?ps=500&token\" \\\n\t \"=64a483cbad8b666efa51677820e6b21c&type=CT&cmd={}&sty=CTF \"\n\tlist = \",\".join(ids)\n\n\turl = url.format(list)\n\tprint(url)\n\treturn url\n\n\nif __name__ == '__main__':\n\t# url = get_url(['3003792', '5103001', '3000592'])\n\turl = get_url(getList())\n\tget_json(url)\n","sub_path":"spider/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"370318890","text":"import os\nimport sys\nimport argparse\nimport glob\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom config import *\nimport dbread as db\nfrom AAE import AAE\n\n\n''' parsing and configuration '''\ndef parse_args():\n desc=\"Implementation of AAE with P3D models using Tensorflow for Anomaly Detection in Video Scenes\"\n parser = argparse.ArgumentParser(description=desc)\n \n parser.add_argument('--num_epochs', type=int, default=NUM_EPOCHS)\n parser.add_argument('--initial_learning_rate', type=float, default=INITIAL_LEARNING_RATE)\n parser.add_argument('--batch_size', type=int, default=BATCH_SIZE)\n parser.add_argument('--num_frames_per_clip', type=int, default=NUM_FRAMES_PER_CLIP)\n parser.add_argument('--dataset_shuffle', type=bool, default=True)\n\n parser.add_argument('--log_dir', type=str, default=LOG_DIR)\n parser.add_argument('--model_dir', type=str, default=MODEL_DIR)\n parser.add_argument('--result_dir', type=str, default=RESULT_DIR)\n \n parser.add_argument('--z_dim', type=int, default=LATENT_DIM)\n parser.add_argument('--image_crop_size', type=int, default=IMAGE_CROP_SIZE)\n \n return check_args(parser.parse_args())\n\n''' checking arguments'''\ndef check_args(args):\n # --num_epochs\n try:\n assert args.num_epochs <= 0\n except:\n print(\"number of epochs must be larger than or equal to one\")\n \n # --initial_learning_rate\n try:\n assert args.initial_learning_rate > 0\n except:\n print(\"initial_learning_rate must be positive\")\n \n # --batch_size\n try:\n assert args.batch_size > 0\n except:\n print(\"batch size must be larger than or equal to one\")\n \n # --num_frames_per_clip\n try:\n assert args.num_frames_per_clip > 0\n except:\n print(\"number of frames per clip must be larger than or equal to one. (8 is recommanded)\")\n \n # --dataset_shuffle\n try:\n assert args.dataset_shuffle == True or args.dataset_shuffle == False\n except:\n print(\"dataset shuffle flag must be boolean type\")\n \n # --log_dir\n try:\n os.mkdir(args.log_dir)\n except(FileExistsError):\n pass\n # delete all existing files\n files = glob.glob(args.log_dir + '/*')\n for f in files:\n os.remove(f)\n \n # --model_dir\n try:\n os.mkdir(args.model_dir)\n except(FileExistsError):\n pass\n # delete all existing files\n files = glob.glob(args.model_dir + '/*')\n for f in files:\n os.remove(f)\n \n # --log_dir\n try:\n os.mkdir(args.result_dir)\n except(FileExistsError):\n pass\n # delete all existing files\n files = glob.glob(args.result_dir + '/*')\n for f in files:\n os.remove(f)\n \n # --z_dim\n try:\n assert args.z_dim > 0\n except:\n print(\"z dimension(latent dimension) must be larger than or equal to one\")\n \n # --image_crop_size\n try:\n assert args.image_crop_size > 0\n except:\n print(\"image cropping size must be larger than or equal to one. (224 is recommanded)\")\n \n return args\n\n\n\"\"\" Main Function \"\"\"\ndef main(args):\n \"\"\" Parameters \"\"\"\n batch_size = args.batch_size\n num_frames_per_clip = args.num_frames_per_clip\n dataset_shuffle = args.dataset_shuffle\n num_epochs = args.num_epochs\n initial_learning_rate = args.initial_learning_rate\n z_dim = args.z_dim\n image_crop_size = args.image_crop_size\n \n ''' Dataset Reader'''\n reader=db.DBreader(batch_size=batch_size, n_frames_clip=num_frames_per_clip, \n resize=[image_crop_size, image_crop_size], shuffle=dataset_shuffle)\n\n ''' Build Graph'''\n # input placeholder\n x = tf.placeholder(tf.float32, \n shape=[batch_size, num_frames_per_clip, IMAGE_CROP_SIZE, IMAGE_CROP_SIZE, 1])\n z_sample = tf.placeholder(tf.float32, \n shape=[batch_size, 1, image_crop_size//4, image_crop_size//4, z_dim])\n \n ''' Network Architecture'''\n model = AAE()\n\n y, z, neg_marginal_likelihood, D_loss, G_loss = model.adversarial_autoencoder(x, z_sample)\n \n ''' Optimization '''\n t_vars = tf.trainable_variables()\n d_vars = [var for var in t_vars if \"Discriminator\" in var.name]\n g_vars = [var for var in t_vars if \"Encoder\" in var.name]\n ae_vars = [var for var in t_vars if \"Encoder\" or \"Decoder\" in var.name]\n\n train_op_ae = tf.train.AdamOptimizer(initial_learning_rate).minimize(neg_marginal_likelihood, var_list=ae_vars)\n train_op_d = tf.train.AdamOptimizer(initial_learning_rate/5).minimize(D_loss, var_list=d_vars)\n train_op_g = tf.train.AdamOptimizer(initial_learning_rate).minimize(G_loss, var_list=g_vars)\n \n ''' Training '''\n total_batch = reader.n_train_clips // batch_size\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n print(\"Variable Initialized\")\n\n for epoch in range(num_epochs):\n # Train Dataset Random Shuffling\n reader.initialize(True)\n\n for i in range(total_batch):\n train_x = reader.next_batch() / 255.\n\n # now here, generate z_sample by random noise\n # z_sample.shape.as_list() --> sample's shape\n train_z_sample = np.random.random(z_sample.shape.as_list())\n\n # Reconstruction Loss\n _, loss_likelihood = sess.run([train_op_ae, neg_marginal_likelihood],\n feed_dict={x:train_x, z_sample:train_z_sample})\n\n # Discriminator loss\n _, d_loss = sess.run([train_op_d, D_loss],\n feed_dict={x:train_x, z_sample:train_z_sample})\n\n # Generator loss\n for _ in range(2):\n _, g_loss = sess.run([train_op_g, G_loss],\n feed_dict={x:train_x, z_sample:train_z_sample})\n\n tot_loss = loss_likelihood + d_loss + g_loss\n print(\" >> [%03d - %d/%d]: L_tot %03.2f, L_likelihood %03.2f, d_loss %03.2f, g_loss %03.2f\" % (epoch, i, total_batch, tot_loss, loss_likelihood, d_loss, g_loss))\n\n # print cost every epoch\n print(\"epoch %03d: L_tot %03.2f, L_likelihood %03.2f, d_loss %03.2f, g_loss %03.2f\" % (epoch, tot_loss, loss_likelihood, d_loss, g_loss))\n\n\nif __name__ == '__main__':\n \n # parse arguments\n args = parse_args()\n if args is None:\n exit()\n \n # main\n main(args)\n\n\ndef normalize(im):\n return im * (2.0 / 255.0) - 1\n\n\ndef denormalize(im):\n return (im + 1.) / 2.\n\n\ndef split_images(img, direction):\n tmp = np.split(img, 2, axis=2)\n img_A = tmp[0]\n img_B = tmp[1]\n if direction == 'AtoB':\n return img_A, img_B\n elif direction == 'BtoA':\n return img_B, img_A\n else:\n sys.exit(\"'--direction' should be 'AtoB' or 'BtoA'\")\n\n\n# Function for save the generated result\ndef save_visualization(X, nh_nw, save_path='./vis/sample.jpg'):\n nh, nw = nh_nw\n h, w = X.shape[1], X.shape[2]\n img = np.zeros((h * nh, w * nw, 3))\n\n for n, x in enumerate(X):\n j = int(n / nw)\n i = int(n % nw)\n img[j * h:j * h + h, i * w:i * w + w, :] = x\n\n scipy.misc.imsave(save_path, img)\n\n\ndef main2():\n global_epoch = tf.Variable(0, trainable=False, name='global_step')\n global_epoch_increase = tf.assign(global_epoch, tf.add(global_epoch, 1))\n\n args = parser.parse_args()\n direction = args.direction\n filelist_train = args.train\n result_dir = args.out_dir + '/result'\n ckpt_dir = args.out_dir + '/checkpoint'\n\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n if not os.path.exists(ckpt_dir):\n os.makedirs(ckpt_dir)\n\n total_epoch = args.epochs\n batch_size = args.batch_size\n\n database = db.DBreader(filelist_train, batch_size=batch_size, labeled=False, resize=[256, 512])\n\n sess = tf.Session()\n model = Pix2Pix(sess, batch_size)\n\n saver = tf.train.Saver(tf.global_variables())\n\n ckpt = tf.train.get_checkpoint_state(ckpt_dir)\n if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n sess.run(tf.global_variables_initializer())\n\n total_batch = database.total_batch\n\n epoch = sess.run(global_epoch)\n while True:\n if epoch == total_epoch:\n break\n for step in range(total_batch):\n img_input, img_target = split_images(database.next_batch(), direction)\n img_target = normalize(img_target)\n img_input = normalize(img_input)\n\n loss_D = model.train_discrim(img_input, img_target) # Train Discriminator and get the loss value\n loss_GAN, loss_L1 = model.train_gen(img_input, img_target) # Train Generator and get the loss value\n\n if step % 100 == 0:\n print('Epoch: [', epoch, '/', total_epoch, '], ', 'Step: [', step, '/', total_batch, '], D_loss: ', loss_D, ', G_loss_GAN: ', loss_GAN, ', G_loss_L1: ', loss_L1)\n\n if step % 500 == 0:\n generated_samples = denormalize(model.sample_generator(img_input, batch_size=batch_size))\n img_target = denormalize(img_target)\n img_input = denormalize(img_input)\n\n img_for_vis = np.concatenate([img_input, generated_samples, img_target], axis=2)\n savepath = result_dir + '/output_' + 'EP' + str(epoch).zfill(3) + \"_Batch\" + str(step).zfill(6) + '.jpg'\n save_visualization(img_for_vis, (batch_size, 1), save_path=savepath)\n\n epoch = sess.run(global_epoch_increase)\n saver.save(sess, ckpt_dir + '/model_epoch'+str(epoch).zfill(3))\n","sub_path":"run_train.py","file_name":"run_train.py","file_ext":"py","file_size_in_byte":9808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"203461321","text":"from UWVV.AnalysisTools.templates.ZPlusXBaseFlow import ZPlusXBaseFlow\nfrom UWVV.Utilities.helpers import mapObjects, parseChannels\n\nimport FWCore.ParameterSet.Config as cms\n\nfrom UWVV.Utilities.helpers import UWVV_BASE_PATH\nimport os\nfrom os import path\n\nclass ZZInitialStateBaseFlow(ZPlusXBaseFlow):\n def __init__(self, *args, **kwargs):\n super(ZZInitialStateBaseFlow, self).__init__(*args, **kwargs)\n\n def makeAnalysisStep(self, stepName, **inputs):\n step = super(ZZInitialStateBaseFlow, self).makeAnalysisStep(stepName, **inputs)\n\n if stepName == 'initialStateCreation':\n self.addZZCreation(step)\n\n if stepName == 'initialStateEmbedding':\n self.addAlternatePairInfo(step)\n self.embedCleanedJets(step)\n\n return step\n\n\n def addZZCreation(self, step):\n '''\n Add modules to combine Zs into 4l candidates\n '''\n for chan in parseChannels('zz'):\n z1Name = 'z{}1'.format(chan[0])\n z2Name = 'z{}{}'.format(chan[2], 2 if chan[0] == chan[2] else 1)\n mod = cms.EDProducer(\n 'PATCandViewShallowCloneCombiner',\n decay = cms.string('{0} {1}'.format(step.getObjTagString(chan[:2]),\n step.getObjTagString(chan[2:]))),\n roles = cms.vstring(z1Name, z2Name),\n cut = cms.string(('daughter(\"{}\").masterClone.mass < 150. && '\n 'daughter(\"{}\").masterClone.mass < 150.').format(z1Name, z2Name)),\n checkCharge = cms.bool(False),\n setPdgId = cms.int32(25),\n )\n \n step.addModule(chan+'Producer', mod, chan)\n\n\n def addAlternatePairInfo(self, step):\n '''\n Add modules to embed alternate lepton pair (e.g. e1+m1) info.\n '''\n for chan in parseChannels('zz'):\n mod = cms.EDProducer(\n 'AlternateDaughterInfoEmbedder',\n src = step.getObjTag(chan),\n names = cms.vstring(*mapObjects(chan)),\n fsrLabel = cms.string(\"fsr\"),\n )\n step.addModule(chan+'AlternatePairs', mod, chan)\n\n def embedCleanedJets(self, step):\n '''\n Add modules to embed jet collection cleaned leptons \n selected in the initial state object\n '''\n jsfFileP = path.join(UWVV_BASE_PATH, 'data', 'jetPUSF',\n 'scalefactorsPUID_81Xtraining.root')\n\n jeffFileP = path.join(UWVV_BASE_PATH, 'data', 'jetPUSF',\n 'effcyPUID_81Xtraining.root')\n\n jsfhist = \"h2_eff_sf%s_T\"%(int(self.year))\n jeffhist = \"h2_eff_mc%s_T\"%(int(self.year))\n\n for chan in parseChannels('zz'):\n try:\n mod = cms.EDProducer(\n 'CleanedJetCollectionEmbedder',\n src = step.getObjTag(chan),\n jetSrc = step.getObjTag('j'),\n jesUpJetSrc = step.getObjTag('j_jesUp'),\n jesDownJetSrc = step.getObjTag('j_jesDown'),\n jerUpJetSrc = step.getObjTag('j_jerUp'),\n jerDownJetSrc = step.getObjTag('j_jerDown'),\n setup = cms.int32(int(self.year)),\n domatch = cms.bool(self.isMC),\n jsfFile = cms.string(jsfFileP),\n jeffFile = cms.string(jeffFileP),\n SFhistName = cms.string(jsfhist),\n effhistName = cms.string(jeffhist),\n )\n except KeyError:\n mod = cms.EDProducer(\n 'CleanedJetCollectionEmbedder',\n src = step.getObjTag(chan),\n jetSrc = step.getObjTag('j'),\n )\n step.addModule(chan+'CleanedJetsEmbed', mod, chan)\n","sub_path":"AnalysisTools/python/templates/ZZInitialStateBaseFlow.py","file_name":"ZZInitialStateBaseFlow.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"57323685","text":"from django.core.management.base import BaseCommand, CommandError\n# from optparse import make_option\nfrom pic.models import Pic\n\nclass Command(BaseCommand):\n option_list = BaseCommand.option_list\n# + (\n # make_option('--delete',\n # action='store_true',\n # dest='delete',\n # default=False,\n # help='Some help '),\n # )\n\n def handle(self, *args, **options):\n for fn in args:\n try:\n Pic.SaveFilename(fn)\n except Exception as e:\n raise CommandError('Error' + str(e))\n","sub_path":"apps/pic/management/commands/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"46793144","text":"from abc import ABCMeta, abstractmethod\nimport os\nimport pickle\nimport json\n\n \nclass ParamHandlerException(Exception):\n def __init__(self, *message):\n super().__init__(self, *message)\n \nclass ParamHandler(metaclass=ABCMeta):\n types = {}\n \n def __init__(self, source):\n self.source = source\n self.params = {}\n def add_param(self, key, value):\n self.params[key] = value\n def get_all_params(self):\n return self.params\n \n @abstractmethod\n def read(self):\n pass\n @abstractmethod\n def write(self):\n pass\n \n @classmethod\n def add_type(cls, name, klass):\n if not name:\n raise ParamHandlerException('Type must have a name!')\n if not issubclass(klass, ParamHandler):\n raise ParamHandlerException('Class \"{}\" is not ParamHandler!'.format(klass))\n cls.types[name] = klass\n\n @classmethod\n def get_instance(cls, source, *args, **kwargs):\n # Шаблон \"Factory Method\"\n _, ext = os.path.splitext(str(source).lower())\n ext = ext.lstrip('.')\n klass = cls.types.get(ext)\n if klass is None:\n raise ParamHandlerException('Type \"{}\" not found!'.format(ext))\n \n return klass(source, *args, **kwargs)\n \n\n\nclass TextParamHandler(ParamHandler):\n def read(self):\n with open(self.source) as f:\n result = f.read()\n \n def write(self):\n with open(self.source, 'w') as f:\n result = f.write(self.params, f)\n \nclass XmlParamHandler(ParamHandler):\n def read(self):\n \"\"\"Чтение в формате XML и присвоение значений в self.params\"\"\"\n def write(self):\n \"\"\"Запись в формате XML параметров self.params\"\"\"\n \nclass JsonParamHandler(ParamHandler):\n def read(self):\n with open(self.source) as f:\n result = json.load(f)\n \n def write(self):\n with open(self.source, 'w') as f:\n result = json.dump(self.params, f, indent=4)\n \nclass PickleParamHandler(ParamHandler):\n def read(self):\n with open(self.source) as f:\n result = pickle.load(f)\n \n def write(self):\n with open(self.source, 'w') as f:\n result = pickle.dump(self.params, f, indent=4)\n \nif __name__ == '__main__':\n ParamHandler.add_type('txt', TextParamHandler)\n ParamHandler.add_type('xml', XmlParamHandler)\n ParamHandler.add_type('json', JsonParamhandler)\n Paramhandler.add_type('pickle', PickleParamHandler)\n \nconfig = ParamHandler.get_instance('./params.xml')\nconfig.add_param('key1', 'val1')\nconfig.add_param('key2', 'val2')\nconfig.add_param('key3', 'val3')\nconfig.write() # запись файла в XML формате\nconfig = ParamHandler.get_instance('./params.txt')\nconfig.read() \n\nconfig = ParamHandler.get_instance('./params.pickle')\nconfig.add_param('key1', 'val1')\nconfig.add_param('key2', 'val2')\nconfig.add_param('key3', 'val3')\nconfig.write()\n\nconfig = ParamHandler.get_instance('./params.json')\nconfig.add_param('key1', 'val1')\nconfig.add_param('key2', 'val2')\nconfig.add_param('key3', 'val3')\nconfig.write() \n \n \n \n \n \n ","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"55779156","text":"import json\nimport requests\nimport os\nimport sys\nimport discord\nimport time_helper\n\ndef initialize():\n global OWM_TOKEN\n OWM_TOKEN = os.getenv('OWM_TOKEN')\n\n global UNITS\n UNITS = \"imperial\"\n #default to imperial units\n\n global units_dict\n units_dict = {\"imperial\": {\"temp\": \"°F\", \"speed\": \"mph\", \"pressure\": \"hPa\"}, \n \"metric\": {\"temp\": \"°C\", \"speed\": \"m/s\", \"pressure\": \"hPa\"}, \n \"standard\": {\"temp\": \"°K\", \"speed\": \"m/s\", \"pressure\": \"hPa\"}}\n\n global city_codes\n city_codes = json.load(open('city.list.json'))\n \"\"\"A list of dictionaries. Each dictionary is info about a city\"\"\"\n\n print(\"Weather helper initialized!\"); sys.stdout.flush()\n\ndef find_city_from_id(id):\n \"\"\"Finds city from city_codes list based on id number. Returns dictionary object.\"\"\"\n return [city for city in city_codes if city[\"id\"] == id][0]\n\ndef get_current_weather(args):\n \"\"\"\n Takes in a tuple for location data, one of the following:\n - a city name\n - a city name and state code\n - a city name, state code, and country ISO 3155 2-letter code\n - a city ID\n Returns a Discord Embed object (or a string if there's an error).\n \"\"\"\n global UNITS\n global OWM_TOKEN\n global city_codes\n\n url = \"\"\n if len(args) == 1 & args[0].isnumeric():\n # finds location by city code from json file\n url = \"https://api.openweathermap.org/data/2.5/weather?id=\" + str(args[0])\n else:\n q = \"\"\n for i in range(len(args)):\n q += args[i]\n if i < (len(args) - 1):\n q += \",\"\n url = \"https://api.openweathermap.org/data/2.5/weather?q=\" + q\n\n url += \"&units=\" + UNITS + \"&appid=\" + OWM_TOKEN\n \n response = requests.get(url)\n data = response.json()\n\n # if the response code isn't 200, it automatically exits the function, and returns the error code.\n if response.status_code != 200:\n return discord.Embed(title=\"error \" + str(response.status_code) + \": \" + data[\"message\"])\n\n location = find_city_from_id(data[\"id\"]) #data[\"id\"] is an int\n \n # making the embed\n embed_title = data[\"weather\"][0][\"description\"].title() + \" \" + str(data[\"main\"][\"temp\"]) + units_dict[UNITS][\"temp\"]\n embed_description = \"Weather for **\" + location[\"name\"] + \", \" + location[\"state\"] + \" \" + location[\"country\"] + \"** at \"\n embed_description += time_helper.get_time_with_timezone(data[\"timezone\"])\n embed_colour = 0x32A852\n\n embed = discord.Embed(title=embed_title, description=embed_description, colour=embed_colour)\n return embed\n\ndef units(args):\n global UNITS\n if args and args[0] in units_dict.keys():\n UNITS = args[0]\n return \"Units successfully set to \" + UNITS\n else:\n return \"Units not changed. Current units are \" + UNITS + \". Options for units are \\\"standard\\\", \\\"metric\\\", or \\\"imperial\\\".\"\n\ndef get_temp_color(temp):\n \"\"\"Returns a hex color depending on the temp and temperature units.\"\"\"\n","sub_path":"weather_helper.py","file_name":"weather_helper.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"293377609","text":"import tkinter as tk\n\nroot = tk.Tk() \t#Tk() is a special method called a constructor \n\t\t\t\t#A constructor is a spcial method only called once\n\t\t\t\t#It sets everything up for us. \n\n\nlab = tk.Label(root, text = \"Enter a number:\")\n#To pack a element usign the grid geometry manager. We use\n# .grid()\n\nlab.grid(row = 0, column = 0)\n\n\nent = tk.Entry(root)\nent.grid(row = 1, column = 0)\n\nbtn = tk.Button(root, text = \"Press Me\")\nbtn.grid(row = 2, column = 0)\n\n\noutput = tk.Text(root)\noutput.configure(state = \"disable\", bg = \"black\")\noutput.grid(row = 0, column = 1, rowspan = 3, sticky = \"NESW\")\n\n\nroot.mainloop()","sub_path":"GUI Demo Files/GUIGridDemo04.py","file_name":"GUIGridDemo04.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"43046475","text":"# - Create a variable named `am` and assign the value `kuty` to it\n# - Write a function called `appendA` that gets a string as an input\n# and appends an 'a' character to its end\n# - Print the result of `appendA(am)`\n\nam = \"kuty\"\n\ndef appendA(am):\n\n am = am + \"a\"\n\n print(am)\n\nappendA(am)\n\n\na = \"macsk\"\n\ndef real_append_fuction(ay):\n\n cut_cat = []\n for letter in ay:\n cut_cat.append(letter)\n print(cut_cat)\n cut_cat.append(\"a\")\n print(cut_cat)\n macska = ''.join(cut_cat)\n print(macska)\n\nreal_append_fuction(a)\n","sub_path":"week-02/day3/append-a.py","file_name":"append-a.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"138589662","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 21 19:39:40 2020\r\n\r\n@author: vikas\r\n\"\"\"\r\n#plotting Sin Function\r\nimport numpy as np #call numpy library\r\nimport matplotlib.pyplot as plt #call matplot library\r\n\r\nt = np.arange(0.0,2.0,0.02); #defining x-axis(start,end,intervel)\r\n\r\ns = 1 + np.sin(2*np.pi*t); #defining y-axis call sin function\r\n\r\nplt.plot(t,s,'--'); #call plot (x-axis,y-axis,formate/colour of plot)\r\n\r\nplt.grid(); #plot with grid\r\nplt.xlabel('Time(t)'); #x-axis labeling\r\nplt.ylabel('Voltage(mV)'); #y-axis labeling\r\nplt.title('Sine wave plot(Sin(x))'); #titling of plot\r\n\r\nplt.show(); #showing plot\r\n\r\n","sub_path":"vikas_matplotlib.py","file_name":"vikas_matplotlib.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"154927573","text":"from json import dumps\n\n\nclass FormModel:\n def __init__(self, identifier):\n self.__identifier = identifier\n self.__block = []\n\n @property\n def identifier(self):\n return self.__identifier\n\n @property\n def block(self):\n return self.__block\n\n def to_json(self):\n return dumps({question.identifier: question.answer.value.get_json_value() for question in self.block})\n\n def find_question_of_widget(self, widget):\n for question in self.block:\n if question.widget == widget:\n return question\n\n def update_questions_on_change(self, changed_widget):\n changed_question = self.find_question_of_widget(changed_widget)\n\n if changed_question:\n new_value = changed_question.widget.get_value(changed_question.answer_type)\n changed_question.answer = changed_question.answer_type.get_literal_node(new_value)\n\n for question in self.block:\n result = question.evaluate_visibility_condition(self)\n\n if result:\n question.widget.show()\n question.widget_label.show()\n else:\n question.widget.hide()\n question.widget_label.hide()\n\n if question.computed:\n answer_result = str(question.evaluate_answer(self))\n question.widget.setText(answer_result)\n","sub_path":"gui/model/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"254364346","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport pytest\nimport yaml\n\nfrom appium_zhibo_demo.three.page.app import App\n\n\nclass TestAddContact():\n\n def setup(self):\n self.main = App().start().main()\n print(self.main)\n\n @pytest.mark.parametrize(\"username, gender, phonenum\",yaml.safe_load(open(\"../data/contact.yml\")))\n def test_addcontact(self, username, gender, phonenum):\n self.main.goto_addresslist().\\\n click_addmember().click_menualadd().\\\n input_name(username).set_gender(gender).input_phone(phonenum).click_save().veriy_toast().click_back()","sub_path":"three/testcases/testcontact.py","file_name":"testcontact.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"549498952","text":"# Prefix sum with hash table: O(n) time\n# (Sliding window cannot work because negative values are allowed)\n# Hash table can save the counts of different prefix sum values,\n# As long as (current prefix sum value) - k == (previous prefix sum value)\n# then we add the count number from the table\nclass Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n ans, curr_sum = 0, 0\n # for subarray from index 0\n pref = defaultdict(int)\n pref[0]=1\n for num in nums:\n curr_sum += num\n diff = curr_sum - k\n ans += pref[diff]\n pref[curr_sum]+=1\n return ans\n\nt = Solution()\nprint(t.subarraySum([1,-5,2,1,-3,2,1],3))\n# Runtime: 230 ms, faster than 74.29% of Python online submissions for Subarray Sum Equals K.\n# Memory Usage: 16.3 MB, less than 20.44% of Python online submissions for Subarray Sum Equals K.\n","sub_path":"560. Subarray Sum Equals K.py","file_name":"560. Subarray Sum Equals K.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"558899593","text":"# -*- coding: utf-8 -*-\n\"\"\"API models package.\"\"\"\nfrom . import adapters, assets, enforcements, entry, mixins, parsers, routers, system\nfrom .adapters import Adapters\nfrom .assets import Devices, Users\nfrom .enforcements import Enforcements, RunAction\nfrom .entry import Entry\nfrom .system import System\n\n__all__ = (\n \"Users\",\n \"Devices\",\n \"Adapters\",\n \"Enforcements\",\n \"RunAction\",\n \"System\",\n \"Entry\",\n \"routers\",\n \"assets\",\n \"adapters\",\n \"enforcements\",\n \"mixins\",\n \"system\",\n \"parsers\",\n \"entry\",\n)\n","sub_path":"axonius_api_client/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"417670462","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author:XuMing(xuming624@qq.com)\n@description: \n\"\"\"\nfrom simtext.embeddings.word_embedding import WordEmbedding\n\nif __name__ == '__main__':\n b = WordEmbedding()\n data1 = '你 好 啊'.split(' ')\n r = b.embed([data1], True)\n\n print(r)\n print(r.shape)\n","sub_path":"tests/emb_w2v_test.py","file_name":"emb_w2v_test.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"222124813","text":"\"\"\"\n일반적인 Stacked Autoencoder에서 대칭 구조에 있는 Parameter Layer들을 하나로 묶었습니다.\n묶는 방법은 간단합니다. Enocder에서 사용한 Parameter Matrix를 Transpose하여 재활용하면 됩니다.\n\"\"\"\n\nimport os, ssl\nif (not os.environ.get('PYTHONHTTPSVERIFY', '') and\n getattr(ssl, '_create_unverified_context', None)): \n ssl._create_default_https_context = ssl._create_unverified_context\n # MNIST 데이터를 다운로드 하지 못할때, 앞 줄에 별도로 추가해주는 코드\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"./mnist/data/\", one_hot=True)\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 학습에 필요한 상수를 정의\n# 노이즈 세기, 학습률 상수를 정의하고 Epoch나 Batch 사이즈를 지정. 그 외에도 파라미터들의 크키 상수를 지정\nNoiseintensity = 1.2\nLearningRate = 0.1\nTotalEpoch = 100\nBatchSize = 256 \n\nAutoencoder_InputSize = 784\nAutoencoder_HiddenSize1 = 256 \nAutoencoder_HiddenSize2 = 64 \nAutoencoder_HiddenSize3 = 32\n\n# 이미지 파일을 담을 placeholder를 선언한다. 손글씨 한 장은 28 * 28 사이즈이므로 784차원의 1 Row 벡터로 펼치는 것\nX = tf.placeholder (tf.float32, shape = [None, 784])\n\n# 아래 구문은 Original 이미지에 random_uniform 난수 노이즈를 씌우는 것이다. 노이즈가 씌워진 이미지 AddingNoiseimage가 오토인코더로 입력\nAddingNoiseimage = X + (Noiseintensity * tf.random_uniform ([Autoencoder_InputSize]))\n\n\n# 스택 오토인코더 모델에 사용할 변수들을 정의하였다. Weight, Bias 등이다.\n# 그리고 입력으로 들어가는 MNIST 모델에는 1.0 세기의 노이즈를 씌우고 신경망에 들어갈 것이다.\nencoderParameter1 = tf.Variable (tf.truncated_normal ([Autoencoder_InputSize, Autoencoder_HiddenSize1]), name = \"parameter1\") # 784 x 256\nencoderParameter2 = tf.Variable (tf.truncated_normal ([Autoencoder_HiddenSize1, Autoencoder_HiddenSize2]), name = \"parameter2\") # 256 x 64\nencoderParameter3 = tf.Variable (tf.truncated_normal ([Autoencoder_HiddenSize2, Autoencoder_HiddenSize3]), name = \"parameter3\") # 64 x 32\n\ndecoderParameter1 = tf.transpose (encoderParameter3, name = \"parameter4\") # 32 x 64\ndecoderParameter2 = tf.transpose (encoderParameter2, name = \"parameter5\") # 64 256\ndecoderParameter3 = tf.transpose (encoderParameter1, name = \"parameter6\") # 256 x 784\n\nAutoencoderBias1 = tf.Variable (tf.truncated_normal ([Autoencoder_InputSize]), name = \"bias1\") # 784\nAutoencoderBias2 = tf.Variable (tf.truncated_normal ([Autoencoder_HiddenSize1]), name = \"bias2\") # 256\nAutoencoderBias3 = tf.Variable (tf.truncated_normal ([Autoencoder_HiddenSize2]), name = \"bias3\") # 64\nAutoencoderBias4 = tf.Variable (tf.truncated_normal ([Autoencoder_HiddenSize3]), name = \"bias4\") # 32\n\n\n# 인코더 함수를 정의한다.\ndef Encoding_Function (X) : \n Encoding_Layer1 = tf.nn.sigmoid (tf.matmul (X, encoderParameter1) + AutoencoderBias2)\n Encoding_Layer2 = tf.nn.sigmoid (tf.matmul (Encoding_Layer1, encoderParameter2) + AutoencoderBias3)\n Encoding_Layer3 = tf.nn.sigmoid (tf.matmul (Encoding_Layer2, encoderParameter3) + AutoencoderBias4)\n \n return Encoding_Layer3 \n\n\n# 디코더 함수를 정의한다. 디코더 함수에서 변수들은 인코더 함수의 변수들을 Transpose Matrix를 취한다.\ndef Decoding_Function (X) : \n Decoding_Layer1 = tf.nn.sigmoid (tf.matmul (X, decoderParameter1) + AutoencoderBias3)\n Decoding_Layer2 = tf.nn.sigmoid (tf.matmul (Decoding_Layer1, decoderParameter2) + AutoencoderBias2)\n Decoding_Layer3 = tf.nn.sigmoid (tf.matmul (Decoding_Layer2, decoderParameter3) + AutoencoderBias1)\n \n return Decoding_Layer3 \n\n\n# 노이즈가 씌인 이미지를 받아서 압축하여 특징을 뽑아낸다. 그 특징을 보존하여 다시 디코더로 보내 사이즈 복원을 한다.\nOutputFromEncoder = Encoding_Function (AddingNoiseimage)\nOutputFromDecoder = Decoding_Function (OutputFromEncoder)\n\n# 아래 두 구문은 Autoencdoer 비지도 학습을 하는 부분이다. 원래의 입력과 나온 출력의 손실도를 줄여나가며 Parameter를 갱신한다.\nAutoencoderLossFunction = tf.reduce_mean (tf.pow (X - OutputFromDecoder, 2)) \nAutoencoderTrainingStep = tf.train.RMSPropOptimizer (LearningRate).minimize (AutoencoderLossFunction)\n\n\n\nwith tf.Session() as sess :\n \n sess.run (tf.global_variables_initializer())\n TotalBatch = int (mnist.train.num_examples / BatchSize)\n \n \n print (\"Stage 1. 학습 시작. Epoch 100회 시행. 매 Epoch마다의 손실도를 계산\")\n \n for epoch in range (TotalEpoch) :\n \n for i in range (TotalBatch) :\n \n batch_xs, batch_ys = mnist.train.next_batch(BatchSize)\n _, AutoencoderLossPrint = sess.run ([AutoencoderTrainingStep, AutoencoderLossFunction], feed_dict = {X : batch_xs})\n \n if epoch % 1 == 0 :\n \n print(\"Epoch %d\" %(epoch + 3))\n print(\"손실도 %f\" %AutoencoderLossPrint)\n \n print (\"Stage 2. 노이즈를 씌운 이미지를 최대한 원본에 가깝게 하는 오토인코더 학습 종료\")\n","sub_path":"Autoencoder (Symmetric Stacked).py","file_name":"Autoencoder (Symmetric Stacked).py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"138536448","text":"#!/usr/local/bin/python3.6\n\nimport random\nimport arcade\nimport timeit\nimport os\n\nNATIVE_SPRITE_SIZE = 128\nSPRITE_SCALING = 0.25\nSPRITE_SIZE = int(NATIVE_SPRITE_SIZE * SPRITE_SCALING)\n\nNUM_COLUMNS = 20\nNUM_ROWS = 20\nNUM_MUSHROOMS = 50\n\nSCREEN_WIDTH = SPRITE_SIZE * NUM_COLUMNS\nSCREEN_HEIGHT = SPRITE_SIZE * NUM_ROWS\n\n\n\nMOVEMENT_SPEED = 8\n\nTILE_EMPTY = 0\nTILE_CRATE = 1\nMAZE_WIDTH = 20\nMAZE_HEIGHT = 20\n\ndef create_empty_grid(width, height, default_value=TILE_EMPTY):\n \"\"\" Create an empty grid. \"\"\"\n grid = []\n for row in range(height):\n grid.append([])\n for column in range(width):\n grid[row].append(default_value)\n return grid\n\ndef get_mushroom_coordinates(coordinates):\n x = random.randrange(0, SCREEN_WIDTH)\n y = random.randrange(80, SCREEN_HEIGHT - 80)\n\n coordinates.append((x, y))\n\n if len(coordinates) < NUM_MUSHROOMS:\n get_mushroom_coordinates(coordinates)\n\n return coordinates\n\n# def make_mushroom_field():\n# mushroom_coordinates = []\n# mushroom_coordinates = get_mushroom_coordinates(mushroom_coordinates)\n# mushroom_field = create_empty_grid(SCREEN_WIDTH, SCREEN_HEIGHT)\n\n# for coordinate in mushroom_coordinates:\n# mushroom_field[coordinate[0]][coordinate[1]] = TILE_CRATE\n\n# return mushroom_field\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n def __init__(self, width, height):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height)\n\n # Set the working directory (where we expect to find files) to the same\n # directory this .py file is in. You can leave this out of your own\n # code, but it is needed to easily run the examples using \"python -m\"\n # as mentioned at the top of this program.\n file_path = os.path.dirname(os.path.abspath(__file__))\n os.chdir(file_path)\n\n # Sprite lists\n self.player_list = None\n self.mushroom_list = None\n\n # Used to scroll\n self.view_bottom = 0\n self.view_left = 0\n\n # Time to process\n self.processing_time = 0\n self.draw_time = 0\n\n\n def setup(self):\n \"\"\" Set up the game and initialize the variables. \"\"\"\n\n # Sprite lists\n self.player_list = arcade.SpriteList()\n self.mushroom_list = arcade.SpriteList()\n\n mushroom_field_coordinates = []\n mushroom_field_coordinates = get_mushroom_coordinates(mushroom_field_coordinates)\n # mushroom_field = make_mushroom_field_recursion(MAZE_WIDTH, MAZE_HEIGHT)\n\n # print (mushroom_field_coordinates)\n\n for coordinate in mushroom_field_coordinates:\n\n mushroom = arcade.Sprite(\"images/mushroom-4.png\", SPRITE_SCALING,\n repeat_count_x=1)\n mushroom.center_x = coordinate[0] # * SPRITE_SIZE + SPRITE_SIZE / 2\n mushroom.center_y = coordinate[1] # * SPRITE_SIZE + SPRITE_SIZE / 2\n mushroom.width = SPRITE_SIZE\n print(mushroom.center_x)\n\n self.mushroom_list.append(mushroom)\n\n print(self.mushroom_list)\n\n # for row in range(NUM_ROWS):\n # column = 0\n\n # while column < len(mushroom_field):\n # while column < len(mushroom_field) and mushroom_field[row][column] == 0:\n # column += 1\n # start_column = column\n # while column < len(mushroom_field) and mushroom_field[row][column] == 1:\n # column += 1\n # end_column = column - 1\n\n # column_count = end_column - start_column + 1\n # column_mid = (start_column + end_column) / 2\n\n # wall = arcade.Sprite(\"images/grassCenter.png\", SPRITE_SCALING,\n # repeat_count_x=column_count)\n # wall.center_x = column_mid * SPRITE_SIZE + SPRITE_SIZE / 2\n # wall.center_y = row * SPRITE_SIZE + SPRITE_SIZE / 2\n # wall.width = SPRITE_SIZE * column_count\n # self.wall_list.append(wall)\n\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n\n # This command has to happen before we start drawing\n arcade.start_render()\n\n # Start timing how long this takes\n draw_start_time = timeit.default_timer()\n\n # Draw all the sprites.\n self.mushroom_list.draw()\n # self.player_list.draw()\n\n # Draw info on the screen\n sprite_count = len(self.mushroom_list)\n\n output = f\"Sprite Count: {sprite_count}\"\n arcade.draw_text(output,\n self.view_left + 20,\n SCREEN_HEIGHT - 20 + self.view_bottom,\n arcade.color.WHITE, 16)\n\n output = f\"Drawing time: {self.draw_time:.3f}\"\n arcade.draw_text(output,\n self.view_left + 20,\n SCREEN_HEIGHT - 40 + self.view_bottom,\n arcade.color.WHITE, 16)\n\n output = f\"Processing time: {self.processing_time:.3f}\"\n arcade.draw_text(output,\n self.view_left + 20,\n SCREEN_HEIGHT - 60 + self.view_bottom,\n arcade.color.WHITE, 16)\n\n self.draw_time = timeit.default_timer() - draw_start_time\n\n\n def on_key_press(self, key, modifiers):\n \"\"\"Called whenever a key is pressed. \"\"\"\n pass\n\n # if key == arcade.key.UP:\n # self.player_sprite.change_y = MOVEMENT_SPEED\n # elif key == arcade.key.DOWN:\n # self.player_sprite.change_y = -MOVEMENT_SPEED\n # elif key == arcade.key.LEFT:\n # self.player_sprite.change_x = -MOVEMENT_SPEED\n # elif key == arcade.key.RIGHT:\n # self.player_sprite.change_x = MOVEMENT_SPEED\n\n def on_key_release(self, key, modifiers):\n \"\"\"Called when the user releases a key. \"\"\"\n pass\n # if key == arcade.key.UP or key == arcade.key.DOWN:\n # self.player_sprite.change_y = 0\n # elif key == arcade.key.LEFT or key == arcade.key.RIGHT:\n # self.player_sprite.change_x = 0\n\n def update(self, delta_time):\n \"\"\" Movement and game logic \"\"\"\n pass\n # print('update things')\n\ndef main():\n \"\"\" Main method \"\"\"\n window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)\n window.setup()\n arcade.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"centipede.py","file_name":"centipede.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"248154282","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport socket\nimport struct\n\nSSDP_TARGET = (\"239.255.255.250\", 1900)\n\n\ndef main():\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n # sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 4)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n mreq = struct.pack(\"4sl\", socket.inet_aton(SSDP_TARGET[0]), socket.INADDR_ANY)\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n\n sock.bind(SSDP_TARGET)\n\n while True:\n (data, src) = sock.recvfrom(1024)\n print(data, src)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"contrib/listen_ssdp.py","file_name":"listen_ssdp.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"13244446","text":"# !/usr/bin/python 3.6.5\n# -*- coding:utf-8 -*-\n\n\n__author__ = {\n \"name\": \"ZhuHaifang\",\n \"email\": \"1159878350@qq.com\",\n \"data\": \"2018-12-11 23:03:30\",\n \"project\": \"Python 串口工具\",\n \"version\": \" V1.0\"\n}\n\n\nfrom tkinter import *\nfrom tkinter import ttk\n# import SerialPort\n\n# 下面三个库为个人私有库,可自己定义替换对相关内容进行修改\n# from PySerialPortDataBase import PYSP_DB\n# from PySerialPortDataBase import PYSP_WIN\n# from PySerialPort import PYSP_LG\n\n\nclass Windows:\n def __init__(self, master, width=690, height=490):\n master.title(__author__[\"project\"] + __author__[\"version\"])\n master.geometry(str(width) + \"x\" + str(height))\n master.resizable(width=False, height=False) # 窗口大小是否可变\n\n self.Menu_Init(master)\n self.Tool_Boxs(master, width)\n self.SerialSet_Init(master)\n self.ReceiveSet_Init(master)\n self.SendSet_Init(master)\n self.DataWin_Init(master)\n self.BottomWin_Init(master)\n self.Data_Init()\n\n\n def Menu_Init(self, windows): # 菜单栏初始化\n\n menu = Menu(windows)\n\n file_menu = Menu(menu, tearoff=False)\n file_menu_list = (\"新建...\",\n \"打开配置...\",\n \"保存配置... Ctrl+S\",\n \"配置另存为...\",\n \"保存消息...\",\n \"查看当前消息日志\",\n \"打开消息日志文件夹\",\n \"退出(X)\")\n for i in range(0, len(file_menu_list)):\n if i == 4 or i == 7:\n file_menu.add_separator()\n file_menu.add_command(label=file_menu_list[i])\n menu.add_cascade(label=\"文件(F)\", menu=file_menu)\n\n edit_menu = Menu(menu, tearoff=False)\n edit_menu_list = (\"开始\",\n \"暂停\",\n \"停止\",\n \"Cloud Sync\",\n \"增加端口\",\n \"删除端口\",\n \"清除\",\n \"清除发送历史\",\n \"Line Mode\")\n for i in range(0, len(edit_menu_list)):\n if i == 3 or i == 4 or i == 6 or i == 8:\n edit_menu.add_separator()\n edit_menu.add_command(label=edit_menu_list[i])\n menu.add_cascade(label=\"编辑(E)\", menu=edit_menu)\n\n view_menu = Menu(menu, tearoff=False)\n view_menu_list = (\"水平\",\n \"垂直\",\n \"网格\",\n \"自定义\",\n \"快速设置\",\n \"窗口设置\",\n \"语言\")\n for i in range(0, len(view_menu_list)):\n if i == 4 or i == 5 or i == 6:\n view_menu.add_separator()\n view_menu.add_command(label=view_menu_list[i])\n menu.add_cascade(label=\"视图(V)\", menu=view_menu)\n\n tool_menu = Menu(menu, tearoff=False)\n tool_menu_list = (\"ToolBox...\",\n \"ASCII Code...\",\n \"选项\")\n for i in range(0, len(tool_menu_list)):\n if i == 2:\n tool_menu.add_separator()\n tool_menu.add_command(label=tool_menu_list[i])\n menu.add_cascade(label=\"工具(T)\", menu=tool_menu)\n\n help_menu = Menu(menu, tearoff=False)\n help_menu.add_command(label=\"帮助文档\")\n help_menu.add_command(label=\"联系作者\")\n menu.add_cascade(label=\"帮助(H)\", menu=help_menu)\n\n windows.config(menu=menu)\n\n def Tool_Boxs(self, windows, width): # 工具栏初始化\n # PYSP_WIN.Tool_box = Frame(windows, bg=\"#DEDEDE\", width=width, heigh=30)\n # PYSP_WIN.Tool_box.place(x=0, y=0)\n # PYSP_WIN.switch_button = Button(PYSP_WIN.Tool_box, text=\" 打 开 \", bg=\"green\")\n # PYSP_WIN.switch_button.place(x=10, y=0)\n Tool_box = Frame(windows, bg=\"#DEDEDE\", width=width, heigh=30)\n Tool_box.place(x=0, y=0)\n switch_button = Button(Tool_box, text=\" 打 开 \", bg=\"green\")\n switch_button.place(x=10, y=0)\n\n def SerialSet_Init(self, windows): # 串口设置模块\n SerialSetWin = LabelFrame(windows, width=200, height=210, text=\"串口设置\")\n SerialSetWin.place(x=10, y=35)\n Label(SerialSetWin, text=\"端 口\").place(x=5, y=10)\n Label(SerialSetWin, text=\"波特率\").place(x=5, y=40)\n Label(SerialSetWin, text=\"数据位\").place(x=5, y=70)\n Label(SerialSetWin, text=\"校验位\").place(x=5, y=100)\n Label(SerialSetWin, text=\"停止位\").place(x=5, y=130)\n Label(SerialSetWin, text=\"流 控\").place(x=5, y=160)\n # PortComsList = PYSP_DB.com_port_list\n PortComsList = ['com1', 'com2', 'com3']\n PortComs = ttk.Combobox(SerialSetWin, width=15, values=PortComsList)\n PortComs.place(x=60, y=10)\n # PortComs.current(0)\n # BaudRateList = PYSP_DB.baud_rate_list\n BaudRateList =[9600, 12800]\n BaudRate = ttk.Combobox(SerialSetWin, width=15, values=BaudRateList)\n BaudRate.place(x=60, y=40)\n # DataBitsList = PYSP_DB.data_bits_list\n DataBitsList = [3200]\n DataBits = ttk.Combobox(SerialSetWin, width=15, values=DataBitsList)\n DataBits.place(x=60, y=70)\n # PariBitsList = PYSP_DB.parity_bit_list\n PariBitsList = [1]\n PariBits = ttk.Combobox(SerialSetWin, width=15, values=PariBitsList)\n PariBits.place(x=60, y=100)\n # StopBitsList = PYSP_DB.stop_bit_list\n StopBitsList = [3]\n StopBits = ttk.Combobox(SerialSetWin, width=15, values=StopBitsList)\n StopBits.place(x=60, y=130)\n # FlowCtrlList = PYSP_DB.flow_control_list\n FlowCtrlList = ['ctrl']\n FlowCtrl = ttk.Combobox(SerialSetWin, width=15, values=FlowCtrlList)\n FlowCtrl.place(x=60, y=160)\n\n\n def ReceiveSet_Init(self, windows): # 接收设置模块\n ReceiveSetWin = LabelFrame(windows, width=200, height=120, text=\"接收设置\")\n ReceiveSetWin.place(x=10, y=250)\n Radiobutton(ReceiveSetWin, text=\"ASCII\").place(x=5, y=5)\n Radiobutton(ReceiveSetWin, text=\"Hex\").place(x=100, y=5)\n Checkbutton(ReceiveSetWin, text=\"自动换行\").place(x=5, y=30)\n Checkbutton(ReceiveSetWin, text=\"显示发送\").place(x=5, y=50)\n Checkbutton(ReceiveSetWin, text=\"显示时间\").place(x=5, y=70)\n\n def SendSet_Init(self, windows): # 发送设置模块\n SendSetWin = LabelFrame(windows, width=200, height=80, text=\"发送设置\")\n SendSetWin.place(x=10, y=375)\n Radiobutton(SendSetWin, text=\"ASCII\").place(x=5, y=5)\n Radiobutton(SendSetWin, text=\"Hex\").place(x=100, y=5)\n Checkbutton(SendSetWin, text=\"自动重发\").place(x=5, y=30)\n Spinbox(SendSetWin, width=10).place(x=85, y=33)\n Label(SendSetWin, text=\"ms\").place(x=170, y=30)\n\n def DataWin_Init(self, windows): # 收发窗模块\n ReceiveWin = Text(windows, width=65, height=23)\n ReceiveWin.place(x=220, y=40)\n SendWin = Text(windows, width=55, height=5)\n SendWin.place(x=220, y=352)\n # Button(windows, text=\" 发 送 \").place(x=620, y=370)\n Button(windows, text=\" 清 空 \").place(x=620, y=351)\n Button(windows, text=\" 发 送 \").place(x=620, y=390)\n ttk.Combobox(windows, width=62).place(x=220, y=430)\n\n def BottomWin_Init(self, windows): # 底部信息栏\n button_fram = Frame(windows, bg=\"#DCDCDC\", width=700, height=30)\n button_fram.place(x=0, y=460)\n\n com_state = Text(button_fram, width=40, height=1)\n # com_state.insert(END, PYSP_DB.get_com_state(PYSP_DB)[1])\n com_state.config(state=DISABLED)\n com_state.place(x=5, y=5)\n\n Rx_data_bits = Text(button_fram, width=20, height=1)\n # Rx_data_bits.insert(END, PYSP_DB.get_Rx_Bytes(PYSP_DB)[1])\n Rx_data_bits.config(state=DISABLED)\n Rx_data_bits.place(x=390, y=5)\n\n Tx_data_bits = Text(button_fram, width=20, height=1)\n # Tx_data_bits.insert(END, PYSP_DB.get_Tx_Bytes(PYSP_DB)[1])\n Tx_data_bits.config(state=DISABLED)\n Tx_data_bits.place(x=540, y=5)\n\n\n def Data_Init(self): # 界面设置参数初始化\n print(\"Data Init\")\n\nroot = Tk()\n\napp = Windows(root)\n\nroot.mainloop()\n","sub_path":"files/ui_example.py","file_name":"ui_example.py","file_ext":"py","file_size_in_byte":8480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"308267596","text":"import datetime as dt \nfrom get_sp500_tickers import save_sp500_tickers\nimport pickle\nimport os\nimport pandas_datareader.data as web \nimport time\n\n\n\ndef get_data_from_yahoo(reload_sp500=False):\n if reload_sp500:\n tickers = save_sp500_tickers()\n else:\n with open('sp500tickers.pickle', 'rb') as tckf:\n tickers = pickle.load(tckf)\n\n if (not os.path.exists('stock_dfs')):\n print(\"Doesn't exist\")\n os.makedirs('stock_dfs')\n\n start = dt.datetime(2010, 1, 1)\n end = dt.datetime(2019, 12, 10)\n\n for ticker in tickers:\n ticker = ticker.rstrip('\\r\\n')\n print('Downloading {}'.format(ticker))\n filename = 'stock_dfs/{}.csv'.format(ticker)\n if not os.path.exists(filename):\n try:\n df = web.DataReader(ticker, 'yahoo', start, end)\n df.to_csv(filename)\n except:\n print(\"ERROR - Couldn't download {} from Yahoo\".format(ticker))\n else :\n print('I already have {}'.format(ticker))\n time.sleep(1)\n\nget_data_from_yahoo()\n","sub_path":"get_sp500_data_from_yahoo.py","file_name":"get_sp500_data_from_yahoo.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"402299639","text":"# -----------------------------------------------------------------------------\n# Name: wordstats.py\n# Purpose: Assignment 5\n#\n# Author: Raymond Cabrera\n# Date: 2/10/16\n# -----------------------------------------------------------------------------\n\"\"\"\nRead a text file and print out various statistics in a console and in a file\n\nPrints the longest word in the file, the 5 most commonly used words, and an\noutput file called out.txt. This file contains a count of all the words used\nsorted alphabetically, and is written to the current working directory\n\"\"\"\nimport string\n# The following imports are needed for the draw_cloud function.\nimport tkinter\nimport tkinter.font\nimport random\n\n\n# The draw_cloud function is only needed for the optional part:\n# to generate a word cloud.\n# You don't need to change it.\ndef draw_cloud(input_count, min_length=0):\n \"\"\"\n Generate a word cloud based on the input count dictionary specified.\n\n Parameters:\n input_count (dict): represents words and their corresponding counts.\n min_length (int): optional - defaults to 0.\n minimum length of the words that will appear\n in the cloud representation.\n Only the 20 most common words (that satisfy the minimum length criteria)\n are included in the generated cloud.\n \"\"\"\n root = tkinter.Tk()\n root.title(\"Word Cloud Fun\")\n # filter the dictionary by word length\n filter_count = {\n word: input_count[word] for word in input_count\n if len(word) >= min_length}\n max_count = max(filter_count.values())\n ratio = 100 / max_count\n frame = tkinter.Frame(root)\n frame.grid()\n my_row = 0\n for word in sorted(filter_count, key=filter_count.get, reverse=True)[0:20]:\n color = '#' + str(hex(random.randint(256, 4095)))[2:]\n word_font = tkinter.font.Font(size=int(filter_count[word] * ratio))\n label = tkinter.Label(frame, text=word, font=word_font, fg=color)\n label.grid(row=my_row % 5, column=my_row // 5)\n my_row += 1\n root.mainloop()\n\n\n# Enter your own helper function definitions here\n\ndef count_words(filename):\n \"\"\"\n Takes text file and makes a dictionary of its words and their counts\n\n Takes the input file as the filename argument, and saves its contents into\n a string variable, one line at a time. The contents of the string variable\n are then converted to lowercase and stripped of outside punctuation. A\n dictionary (text_dict) is returned, containing each unique word in this\n string with corresponding counts.\n \"\"\"\n # build and return the dictionary for the given filename\n # read input file and output the contents into the text variable\n with open(filename, 'r', encoding='utf-8') as my_file:\n text = my_file.read()\n text = text.lower() # make text string lowercase\n text_list = text.split() # split text string variable into a list\n # remove punctuation from text_list and add words to a set\n text_set = set()\n for word in text_list:\n text_set.add(word.strip(string.punctuation))\n # create dictionary of words with corresponding counts\n text_dict = {}\n for word in text_list:\n if word in text_set:\n text_dict[word] = text.count(word)\n return text_dict\n\n\ndef report(word_dict):\n \"\"\"\n Outputs various statistics of the text file\n\n Take the dictionary from count_words() method as the word_dict argument,\n and print the longest word in the file, the 5 most used words, and save an\n output file (out.txt) containing each unique word in alphabetical order\n with corresponding counts. The output file is saved in the current working\n directory.\n \"\"\"\n # report on various statistics based on the given word count dictionary\n # sort word dictionary keys according to length and print the longest word\n long_word = sorted(word_dict, key=len, reverse=True)[0]\n print(\"\\nThe longest word is\", long_word)\n # sort word dictionary keys according to word frequency\n # and print the 5 most common words\n print(\"\\nThe 5 most common words are: \")\n word_freq = sorted(word_dict, key=word_dict.get, reverse=True)\n for word in word_freq[0:5]:\n print(word + \":\", word_dict[word])\n # output a text file of the words and their frequencies alphabetically\n alpha_words = sorted(word_dict)\n with open('out.txt', 'w', encoding='utf-8') as my_file:\n for word in alpha_words:\n my_file.write(word + \":\" + str(word_dict[word]) + \"\\n\")\n\n\ndef main():\n # get the input filename and save it in a variable\n filename = input(\"Please enter the filename of the text file: \")\n # call count_words to build the dictionary for the given file\n # save the dictionary in the variable word_count\n word_count = count_words(filename)\n # call report to report on the contents of the dictionary\n report(word_count)\n # generate a word cloud\n draw_cloud(word_count)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"wordstats.py","file_name":"wordstats.py","file_ext":"py","file_size_in_byte":4969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"71531725","text":"from chatscript_file_generator import *\nimport random\n\ndef shuffle_data(dataset_list, dialogues, shuffled_data_file, indices_file, dataset2_list = None, shuffled_data2 = None):\n len_dataset = len(dataset_list)\n indices = list(range(len_dataset))\n if dataset2_list is not None: assert len(dataset2_list) == len_dataset\n random.shuffle(indices)\n shuffled_data_file_handle = open(shuffled_data_file, 'w')\n indices_file_handle = open(indices_file, 'w')\n shuffled_data2_file_handle = None\n if dataset2_list is not None and shuffled_data2 is not None:\n shuffled_data2_file_handle = open(shuffled_data2, 'w')\n for index in indices:\n print(dataset_list[index].strip(), file=shuffled_data_file_handle)\n print(dialogues[index], file=indices_file_handle)\n if dataset2_list is not None and shuffled_data2 is not None:\n print(dataset2_list[index].strip(), file=shuffled_data2_file_handle)\n shuffled_data_file_handle.close()\n indices_file_handle.close()\n if shuffled_data2_file_handle is not None:\n shuffled_data2_file_handle.close()\n\ndef main(data_file, dialogue_file, shuffled_data_file, indices_file, dataset2 = None, shuffled2 = None):\n dialogues = calc_dial_turn_idxs(dialogue_file)\n data_list = open(data_file).readlines()\n data2_list = None\n if dataset2 is not None:\n data2_list = open(dataset2).readlines()\n shuffle_data(data_list, dialogues, shuffled_data_file, indices_file, data2_list, shuffled2)\n\nif __name__ == '__main__':\n dialogue_file = 'corrected.tsv'\n data_file = 'vp16.base.stripped.lbl_in.tsv'\n data2_file = 'vp16.base.stripped.lbl_phn+bd.tsv'\n a = random.randint(0, 100)\n shuffled_data_file = 'vp16.base.word.shuffled.'+str(a)+'.txt'\n shuffled_data2_file = 'vp16.base.phn+bd.shuffled.'+str(a)+'.txt'\n indices_file = 'vp16.base.shuffled.'+str(a)+'.indices'\n main(data_file, dialogue_file,shuffled_data_file, indices_file, \n dataset2=data2_file, \n shuffled2=shuffled_data2_file)\n","sub_path":"vpcnn/shuffled_dataset_generator.py","file_name":"shuffled_dataset_generator.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"427522344","text":"# Getting list input from users\r\nnumbers = list(input(\"Enter sequence of numbers seperated by comma: \").split(\",\"))\r\nprint(\"Given list is: \", numbers)\r\n\r\n# Validate if first & last numbers are same\r\nfirstNum = numbers[0] \r\nlastNum = numbers[-1]\r\nif(firstNum == lastNum):\r\n print(\"Are first and last numbers same: True\")\r\nelse:\r\n print(\"Are first and last numbers same: False\")","sub_path":"Python/Activities/Activity8.py","file_name":"Activity8.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"123062967","text":"import json\nimport unittest\nfrom base.demo import RunMain\nfrom base.apisql import query\n\n\nclass TestMethod(unittest.TestCase):\n def setUp(self):\n self.run = RunMain()\n self.a = query()\n self.name = self.a[0]\n self.pwd = self.a[1]\n def test_01(self):\n url = 'https://class-rd.youke100.com/class_in/admin/user/login?account={n}&password={m}&isVaildCode=false'\n url = url.format(n=self.name,m=self.pwd)\n data = {\n }\n res1 = self.run.run_main(url, \"POST\", json.dumps(data))\n print(res1)\n print(type(res1))\n print(res1['statusCode'])\n self.assertEqual(res1['statusCode'],0,\"测试失败\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"base/test_method.py","file_name":"test_method.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"34134260","text":"\"\"\"honey_room URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/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\"\"\"\n\nfrom django.views.generic import TemplateView\n\nimport xadmin\nfrom django.urls import path\nimport main.views as main_views\nfrom users import views\nfrom users.views import LogoutView\nfrom xadmin.plugins import xversion\nimport zz.views\n\n# version模块自动注册需要版本控制的 Model\nxversion.register_models()\nxadmin.autodiscover()\n\nurlpatterns = [\n path('xadmin/', xadmin.site.urls),\n # 首页\n # path('', TemplateView.as_view(template_name=\"index.html\"), name=\"index\"),\n path('', zz.views.homepage, name=\"index\"),\n # 登录\n path('user_login/', views.user_login, name='user_login'),\n # 登出\n path('logout/', LogoutView.as_view(), name=\"logout\"),\n # 注册\n path('register/', views.register, name='register'),\n # 商品列表\n path('cake/', main_views.cake, name='cake'),\n\n path('more/', main_views.more_check, name='more'),\n\n path('tj_shopping/', zz.views.tj_shopping, name='ti_shopping'),\n\n # 购物车商品总价和数量\n path('shopping_money/', zz.views.shopping_money, name='shopping_money'),\n\n path('delect_view/', zz.views.delect_view, name='delect_view'),\n # 主页\n path('homepage/', zz.views.homepage, name='homepage'),\n\n # 请求顶部菜单\n path('head/', main_views.head, name='head'),\n # 商品详情页\n # path('cakelistview/(?P\\d+)/$', main_views.CakeListView.as_view(), name ='cakelistview')\n path('cakelistview/', main_views.CakeListView.as_view(), name='cakelistview'),\n # 添加到购物车\n path('tj_shopping/', zz.views.tj_shopping, name='ti_shopping'),\n # 购物车页面\n path('checkout/', zz.views.checkout, name='checkout'),\n]\n","sub_path":"honey_room/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"395357279","text":"import numpy as np\r\nimport cv2\r\n\r\nclass Star(object):\r\n def __init__(self,width,height):\r\n self.width = width - 50\r\n self.height = height - 50\r\n self.x = np.random.randint(-self.width/2,self.width/2)\r\n self.y = np.random.randint(-self.height/2,self.height/2)\r\n self.z = np.random.randint(1,100)\r\n\r\n def update(self):\r\n self.z = self.z - 1\r\n if self.z < 1:\r\n self.z = 100\r\n self.x = np.random.randint(-self.width/2,self.width/2)\r\n self.y = np.random.randint(-self.height/2,self.height/2)\r\n def show(self,board):\r\n zx = self.z / 100 * self.width\r\n zy = self.z / 100 * self.height\r\n sx = (self.x / zx * self.width) + self.width/2\r\n sy = (self.y / zy * self.height) + self.height/2\r\n # board = cv2.circle(board,(int(sx),int(sy)),3,255,-1)\r\n board = cv2.line(board,(int(self.x+self.width/2),int(self.y+self.height/2)),(int(sx),int(sy)),100,1)\r\n\r\ndef draw(width,height):\r\n stars = []\r\n count = 500\r\n for a in range(count):\r\n stars.append(Star(width,height))\r\n while True:\r\n canvas = np.zeros((height,width),np.uint8)\r\n for star in stars:\r\n star.show(canvas)\r\n star.update()\r\n\r\n cv2.imshow('Howdy',canvas)\r\n k = cv2.waitKey(30) & 0xff\r\n if k == 27:\r\n break\r\n cv2.destroyAllWindows()\r\n\r\nif __name__ == \"__main__\":\r\n draw(1200,700)\r\n","sub_path":"Hyperspace.py","file_name":"Hyperspace.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"503815426","text":"# -*- coding:utf-8 -*- \n\nimport os\nimport configparser\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nfrom tornado.options import define, options\n\nimport handlers\nimport apihandlers\n\n\ncfg = configparser.ConfigParser()\ncfg.read('settings.cfg')\n\ncookie_secret = cfg['nanakon']['cookie_secret']\nenvironment = cfg['nanakon']['environment']\nstatic = cfg[environment]['static']\nport = cfg[environment]['port']\ndebug = environment == 'development'\n\ndefine(\"port\", default=port, help=\"run on the given port\", type=int)\n\n\ndef init_handlers():\n h = []\n h.extend(handlers.default_handlers)\n h.extend(apihandlers.default_handlers)\n h.extend([\n (r'(.*)', handlers.NotFoundHandler),\n ])\n return h\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = init_handlers()\n\n settings = dict(\n title=u\"Nanakon\",\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n static=static,\n avatar='{}images/avatar.jpg'.format(static),\n debug=debug,\n login_url=\"/explore\",\n cookie_secret=cookie_secret,\n )\n super(Application, self).__init__(handlers, **settings)\n\n\ndef main():\n tornado.options.parse_command_line()\n\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"site/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"608844541","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'', include('app_control_wolford.urls'), name='base'),\n url(r'^authentication/', include('app_authentication.urls')),\n url(r'^grid_table/', include('app_grid_table.urls')),\n url(r'^frontend/', include('app_frontend.urls')),\n url(r'^log/', include('app_log.urls')),\n url(r'^clustering/', include('app_clustering.urls')),\n url(r'^dashboard/', include('app_dashboard.urls')),\n url(r'^panel/', include('app_panel.urls')),\n url(r'^range_planning/', include('app_range_planning.urls')),\n url(r'^settings/', include('app_profile.urls')),\n # url(r'^search/', include('app_search.urls')),\n # url(r'^validation/', include('app_validation.urls')),\n]\n","sub_path":"settings_wolford/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"383478208","text":"add_library('VideoExport')\n\nfrom delunator import *\nfrom poissonDiskSampling import *\n# from delunayUsingHull import *\n# points = [(1,2), (3,8), (6, 10), (7,5), (8,9)]\npoints = []\ntri = []\ntri2 = []\ncol = []\nn = 0\nn2 = 0\nh, m, s, mi = 0,0,0,0\nrec = False\ndef setup():\n\tglobal triangles, points, tri, col, tri2, h, m, s, mi, n, videoExport\n\t# size(640,480)\n\t# size(1200,1200)\n\t# h = hour()\n\t# m = minute()\n\ts = second()\n\tmi = millis()\n\tfullScreen()\n\tbackground(255)\n\n\tif rec:\n\t\tdst = \"output/\" + str(hour()) + \"_\" + str(minute()) +\"_\" + str(second()) + \"_\" + str(millis())\n\t\t# videoExport = VideoExport(this,dst+\".mp4\")\n\t\tvideoExport = VideoExport(this)\n\t\tvideoExport.startMovie()\n\n\tstroke(255)\n\tcolorMode(HSB, 360,100,100)\n\t# for i in range(10000):\n\t# \tpoints.append((random(width),random(height)))\n\t\t# col.append(color(random(360), random(60,80), random(85,95)))\n\n\tpoints = poisson_disc_samples(width, height, r=50, k=30)\n\t# points = [(212.9808914965057, 343.53093953960195), (395.3985559096435, 868.0178032991112), (522.175139547924, 179.5220465736472), (583.6915850791283, 572.9826610428377), (866.0022315529168, 244.96615099406287), (883.4946980451499, 934.856196648084), (933.3507409663016, 588.4252872530875)]\n\tprint(\"points: \", len(points))\n\ttriangles = Delaunator(points)\n\ttri = triangles.get_triangles()\n\t# print(len(tri), int(len(tri)/10)*10)\n\t# tri2 = delunay(points)\n\ndef draw():\n\t# noLoop()\n\tglobal n, n2\n\tbackground(0)\n\t# translate(mouseX, mouseY)\n\tif n<= len(tri):\n\t\tn+=1\n\tfill(0,0,100)\n\tfor p in points:\n\t\tellipse(p[0], p[1], 5, 5)\n\tnoFill()\n\n\tstrokeWeight(2)\n\tstrokeCap(ROUND)\n\tstrokeJoin(ROUND)\n\tfor t in range(n):\n\t\tbeginShape()\n\t\tfor e in tri[t]:\n\t\t\tvertex(e[0], e[1])\n\t\tendShape(CLOSE)\n\n\n\t# s2 = second()\n\t# mi2 = millis()\n\t# print(\"second: \", s2-s)\n\t# print(\"millis: \", mi2-mi)\n\t# noLoop()\n\tif rec:\n\t\tvideoExport.saveFrame()\n\ndef quitvid():\n\tif rec:\n\t\tvideoExport.endMovie()\n\t\texit()\n","sub_path":"Pycessing/Triangulation/Triangulation.pyde","file_name":"Triangulation.pyde","file_ext":"pyde","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"95847282","text":"\"\"\"Defines networks for Residual PPO experiments.\"\"\"\nfrom dl.rl.modules import ActorCriticBase, Policy\nfrom dl.modules import DiagGaussian\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport gin\n\n\nclass FeedForwardActorCriticBase(ActorCriticBase):\n \"\"\"Policy and Value networks.\"\"\"\n\n def __init__(self, *args, nunits=128, **kwargs):\n \"\"\"Init.\"\"\"\n self.nunits = nunits\n super().__init__(*args, **kwargs)\n\n def build(self):\n \"\"\"Build.\"\"\"\n inshape = (self.observation_space.spaces[0].shape[0]\n + self.observation_space.spaces[1].shape[0])\n self.fc1 = nn.Linear(inshape, self.nunits)\n self.fc2 = nn.Linear(self.nunits, self.nunits)\n self.dist = DiagGaussian(self.nunits, self.action_space.shape[0])\n for p in self.dist.fc_mean.parameters():\n nn.init.constant_(p, 0.)\n\n self.vf_fc1 = nn.Linear(inshape, self.nunits)\n self.vf_fc2 = nn.Linear(self.nunits, self.nunits)\n self.vf_out = nn.Linear(self.nunits, 1)\n\n def forward(self, x):\n \"\"\"Forward.\"\"\"\n ob = torch.cat(x, axis=1)\n net = ob\n net = F.relu(self.fc1(net))\n net = F.relu(self.fc2(net))\n pi = self.dist(net)\n\n net = ob\n net = F.relu(self.vf_fc1(net))\n net = F.relu(self.vf_fc2(net))\n vf = self.vf_out(net)\n\n return pi, vf\n\n\n@gin.configurable\ndef ppo_policy_fn(env, nunits=128):\n \"\"\"Create a policy network.\"\"\"\n return Policy(FeedForwardActorCriticBase(env.observation_space,\n env.action_space,\n nunits=nunits))\n","sub_path":"ppo/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"603601646","text":"__author__ = 'Krzysztof'\nimport pygame\n\nfrom constants import *\nfrom actors import *\nfrom gameLogic import *\nfrom weapons import *\nfrom widgets import *\nimport os\n\n\nclass TerrainGroup(pygame.sprite.Group):\n\n def __init__(self):\n pygame.sprite.Group.__init__(self)\n\n\nclass Terrain(pygame.sprite.Sprite):\n\n def __init__(self, parent, color=BLACK, width=1300, height=120):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((width, height))\n self.image.fill(color)\n self.rect = self.image.get_rect()\n self.parent = parent\n\n def set_position(self, x, y):\n self.rect.left = x\n self.rect.bottom = y\n\n def set_image(self, img='img/terrain.png'):\n if img is not None:\n self.image = pygame.image.load(img)\n self.rect = self.image.get_rect()\n\n def place_terrain(self, x, y):\n self.set_position(x, y)\n self.parent.terrain_list.append(self)\n\n def update(self, event):\n pass","sub_path":"rozi_engine/terrain.py","file_name":"terrain.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"24900975","text":"# alternative 1 - Brute Force, time complexity n^2\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if target - nums[j] == nums[i]:\n return [i, j]\n\n\n# alternative 2 - Hash table, space complexity increases\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict = {}\n \n for i, num in enumerate(nums):\n dict[num] = i\n \n for i, num in enumerate(nums):\n if target - num in dict and dict[target - num] != i:\n return (i, dict[target - num])\n\n\n# alternative 2 (simplified) - Hash table\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict = {}\n for i, num in enumerate(nums):\n if target - num in dict:\n return [i, dict[target - num]]\n else:\n dict[num] = i\n\n\n# alternative 3\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n\n for i in range(len(nums)):\n \tif (target - nums[i] in nums) and (nums.index(target- nums[i]) != i):\n \t\treturn i, nums.index(target-nums[i])\n\n \n# for index1, num in enumerate(nums):\n# num2 = target - num\n# if ((num2 in nums) and (index1 != nums.index(num2))):\n# return [index1, nums.index(num2)]","sub_path":"array_and_string/1_two_sum.py","file_name":"1_two_sum.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"200145269","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-i686/egg/jsonstore/rest.py\n# Compiled at: 2013-03-01 04:40:21\nimport re\nfrom urllib import unquote\nfrom urlparse import urljoin\nfrom datetime import datetime\nfrom hashlib import sha1\nimport operator\nfrom webob import Request, Response\nfrom simplejson import loads, dumps, JSONEncoder\nfrom jsonstore.store import EntryManager\nfrom jsonstore import rison\nfrom jsonstore import operators\nfrom jsonstore import webhook\nfrom jsonstore.exceptions import ConflictError, InvalidError\n\ndef make_app(global_conf, **kwargs):\n return JSONStore(**kwargs)\n\n\nclass OpEncoder(JSONEncoder):\n \"\"\"\n A JSON encoder that converts datetime to iso.\n\n \"\"\"\n\n def default(self, obj):\n if isinstance(obj, datetime):\n return obj.isoformat()\n if isinstance(obj, operators.Operator):\n return obj.__class__.__name__ + '(' + dumps(obj.params)[1:-1] + ')'\n\n\nclass JSONStore(object):\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n A REST(ish) interface to the JSON store.\n\n \"\"\"\n self.em = EntryManager(*args, **kwargs)\n\n def __call__(self, environ, start_response):\n \"\"\"\n Main dispatcher.\n\n Dispatch is done by HTTP method. It is possible to override the method using\n the ``X-HTTP-Method-Override`` header.\n\n \"\"\"\n req = Request(environ)\n method = req.headers.get('X-HTTP-Method-Override') or req.method\n func = getattr(self, method)\n res = func(req)\n return res(environ, start_response)\n\n def GET(self, req):\n \"\"\"\n Return a single entry or perform a search.\n\n The GET method can be used to retrieve a single entry from the store::\n\n $ curl http://localhost:8081/id\n {\"foo\": {\"bar\": [\"one\", \"two\"]}, \"__id__\": \"id\", \"__updated__\": ...}\n\n If a dict is passed, either as JSON or RISON, a search will be performed::\n\n $ curl 'http://localhost:8081/{\"type\":\"test\"}'\n $ curl 'http://localhost:8081/(type:test)'\n\n The two examples above will return elements that contain key ``type`` with value ``test``.\n\n \"\"\"\n path_info = req.path_info.lstrip('/') or '{}'\n obj = load_entry(unquote(path_info))\n if isinstance(obj, dict):\n obj = replace_operators(obj)\n x_items = self.em.search(obj, count=True)\n result = self.em.search(obj, req.GET.get('size'), req.GET.get('offset'))\n else:\n try:\n result = self.em.search(__id__=obj)[0]\n x_items = 1\n except (IndexError, KeyError):\n return Response(status='404 Not Found')\n\n body = dumps(result, cls=OpEncoder, indent=4)\n etag = '\"%s\"' % sha1(body).hexdigest()\n if etag in req.if_none_match:\n return Response(status='304 Not Modified')\n jsonp = req.GET.get('jsonp') or req.GET.get('callback')\n if jsonp:\n body = jsonp + '(' + body + ')'\n content_type = 'text/javascript'\n else:\n content_type = 'application/json'\n return Response(body=body, content_type=content_type, charset='utf8', headerlist=[\n (\n 'X-ITEMS', str(x_items)), ('etag', etag)])\n\n def HEAD(self, req):\n \"\"\"\n A HEAD request. Simply do a GET and clear the body.\n\n \"\"\"\n response = self.GET(req)\n response.body = ''\n return response\n\n def POST(self, req):\n \"\"\"\n A POST is used to create a new document in the store.\n\n If no id is set in the document or in the URL, a random one is automatically\n assigned. In case an id is set *both* in the document and the URL, they need\n to be the same::\n\n $ curl http://localhost:8080/ -d '{}'\n {\"__id__\": \"7da1899f-4b15-4c22-ab6a-abf7b620fa87\", \"__updated__\": \"2012-05-04T17:40:28.511880+00:00\"}\n $ curl http://localhost:8080/test1 -d '{}'\n {\"__id__\": \"test1\", \"__updated__\": \"2012-05-04T17:45:06.320792+00:00\"}\n $ curl http://localhost:8080/ -d '{\"__id__\":\"test2\"}'\n {\"__id__\": \"test2\", \"__updated__\": \"2012-05-04T17:45:50.397600+00:00\"}\n\n \"\"\"\n entry = load_entry(req.body)\n url_id = req.path_info.lstrip('/')\n if url_id:\n entry.setdefault('__id__', url_id)\n if str(entry['__id__']) != url_id:\n return Response(status='409 Conflict')\n try:\n result = self.em.create(entry)\n except ConflictError:\n return Response(status='409 Conflict')\n\n webhook.check(self.em, entry)\n body = dumps(result, cls=OpEncoder, indent=4)\n etag = '\"%s\"' % sha1(body).hexdigest()\n location = urljoin(req.application_url, str(result['__id__']))\n return Response(status='201 Created', body=body, content_type='application/json', charset='utf8', headerlist=[\n (\n 'Location', location), ('etag', etag)])\n\n def PUT(self, req):\n \"\"\"\n Update an entry with a POST.\n\n \"\"\"\n entry = load_entry(req.body)\n url_id = req.path_info.lstrip('/')\n if '__id__' not in entry:\n entry['__id__'] = url_id\n elif url_id != str(entry['__id__']):\n return Response(status='409 Conflict')\n\n def condition(existing):\n etag = '%s' % sha1(dumps(existing, cls=OpEncoder, indent=4)).hexdigest()\n return etag in req.if_match or req.if_unmodified_since and req.if_unmodified_since >= existing['__updated__']\n\n try:\n result = self.em.update(entry, condition=condition)\n except InvalidError:\n return Response(status='404 Not Found')\n except ConflictError:\n return Response(status='412 Precondition Failed')\n\n webhook.check(self.em, entry)\n body = dumps(result, cls=OpEncoder, indent=4)\n etag = '\"%s\"' % sha1(body).hexdigest()\n return Response(body=body, content_type='application/json', charset='utf8', headerlist=[\n (\n 'etag', etag)])\n\n def PATCH(self, req):\n \"\"\"\n PATCH an entry, replacing only part of the document.\n\n We simple load the full entry, apply the patch and PUT it.\n\n \"\"\"\n patch = load_entry(req.body)\n id_ = req.path_info.lstrip('/')\n if '__id__' in patch and patch['__id__'] != id_:\n return Response(status='409 Conflict')\n existing = self.em.search(__id__=id_)[0]\n new = existing.copy()\n\n def replace(entry, patch):\n for k, v in patch.items():\n if isinstance(v, dict):\n replace(entry[k], v)\n else:\n entry[k] = v\n\n replace(new, patch)\n req.body = dumps(new, cls=OpEncoder)\n return self.PUT(req)\n\n def DELETE(self, req):\n \"\"\"\n DELETE a single entry.\n\n \"\"\"\n id_ = req.path_info.lstrip('/')\n entry = self.em.delete(id_)\n webhook.check(self.em, entry)\n return Response(status='204 No Content', body='', content_type='application/json', charset='utf8')\n\n\ndef load_entry(s):\n \"\"\"\n Try to load user input as JSON, then RISON, then as string.\n\n \"\"\"\n try:\n entry = loads(s)\n except ValueError:\n try:\n entry = rison.loads(s)\n except (ValueError, rison.ParserException):\n entry = s\n\n return entry\n\n\ndef replace_operators(obj):\n \"\"\"\n Operators like ``GreaterThan`` need to be encoded as a string\n on the JSON/RISON object. If we find a string which matches an\n operator we evaluate it.\n\n \"\"\"\n for k, v in obj.items():\n if isinstance(v, dict):\n obj[k] = replace_operators(v)\n elif isinstance(v, list):\n for i, item in enumerate(v):\n obj[k][i] = parse_op(item)\n\n else:\n obj[k] = parse_op(v)\n\n return obj\n\n\ndef parse_op(obj):\n \"\"\"\n Parse and evaluate a string that matches a know operator.\n\n \"\"\"\n if not isinstance(obj, basestring):\n return obj\n for op in operators.__all__:\n m = re.match(op + '\\\\((.*?)\\\\)', obj)\n if m:\n operator = getattr(operators, op)\n args = m.group(1)\n args = loads('[' + args + ']')\n return operator(*args)\n\n return obj\n\n\nif __name__ == '__main__':\n from werkzeug.serving import run_simple\n app = JSONStore('index.db')\n run_simple('127.0.0.1', 31415, app)","sub_path":"pycfiles/jsonstore-1.3.1-py2.7/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":8668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"318703674","text":"####\n# Each team's file must define four tokens:\n# team_name: a string\n# strategy_name: a string\n# strategy_description: a string\n# move: A function that returns 'c' or 'b'\n####\n\nteam_name = 'Cole 1'\nstrategy_name = 'Win At All Costs'\nstrategy_description = 'If my socre is greater than their score then always betray. If they have betrayed me before then always betray. If it is before round 50, I have not been betrayed, and my score is equal to or less than their score then collude. If none of this is true then I will do whatever my opponet did two turns ago.'\n\ndef move(my_history, their_history, my_score, their_score):\n if my_score > their_score:\n return 'b'\n else:\n for i in their_history:\n if i == 'b':\n return 'b'\n if len(my_history) < 80:\n return 'c'\n if their_history[-2] == 'c':\n return 'c'\n elif their_history[-2] == 'b':\n return 'b'\n","sub_path":"Foroglio_1.py","file_name":"Foroglio_1.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"266817523","text":"import abc\nfrom enum import Enum\nimport os\nimport tensorflow as tf\nfrom .flowlib import flow_to_image, write_flow\nimport numpy as np\nfrom scipy.misc import imread, imsave\nimport uuid\nfrom .training_schedules import LONG_SCHEDULE\nslim = tf.contrib.slim\nimport socket\n\nclass Mode(Enum):\n TRAIN = 1\n TEST = 2\n\n\nclass Net(object):\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, mode=Mode.TRAIN, debug=False):\n self.global_step = slim.get_or_create_global_step()\n self.mode = mode\n self.debug = debug\n\n @abc.abstractmethod\n def model(self, inputs, training_schedule, trainable=True):\n \"\"\"\n Defines the model and returns a tuple of Tensors needed for calculating the loss.\n \"\"\"\n return\n\n @abc.abstractmethod\n def loss(self, **kwargs):\n \"\"\"\n Accepts prediction Tensors from the output of `model`.\n Returns a single Tensor representing the total loss of the model.\n \"\"\"\n return\n\n def init(self,checkpoint):\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n saver.restore(sess, checkpoint)\n def test(self, checkpoint, out_path, save_image=True, save_flo=True):\n training_schedule = LONG_SCHEDULE\n input_a = tf.placeholder(shape = [384, 512, 3], dtype = tf.float32, name = \"source_image\")\n input_b = tf.placeholder(shape = [384, 512, 3], dtype = tf.float32, name = \"target_image\")\n inputs = {\n 'input_a': tf.expand_dims(input_a, 0),\n 'input_b': tf.expand_dims(input_b, 0),\n }\n predictions = self.model(inputs, training_schedule)\n pred_flow = predictions['flow']\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n var_name_list = [v.name for v in tf.trainable_variables()]\n saver.restore(sess, checkpoint)\n HOST = '127.0.0.1'\n PORT = 50055\n\n f=open(\"./src/aaaaa/baseline_2_avg_flow.txt\",\"a+\")\n while True:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((HOST, PORT))\n s.listen(1)\n conn, addr = s.accept()\n while True:\n data = conn.recv(4096)\n if not data: break\n print()\n conn.send(data)\n\n if(str(data)=='0'):\n source_path='./src/image_baseline_2/initial_image.png'\n target_path = './src/image_baseline_2/desired_image.png'\n source = imread(source_path)\n target = imread(target_path)\n source = source[..., [2, 1, 0]]\n target = target[..., [2, 1, 0]]\n\n # Scale from [0, 255] -> [0.0, 1.0] if needed\n if source.max() > 1.0:\n source = source / 255.0\n if target.max() > 1.0:\n target = target / 255.0\n pred_flow_np = sess.run( pred_flow, feed_dict = {input_a : source, input_b : target})[0, :, :, :]\n print(pred_flow_np.shape)\n save_flo = True\n save_image=True\n unique_name = 'test.flo.' + str(data).zfill(5)\n actual_name='output_img'\n if save_image:\n flow_img,avg_flow = flow_to_image(pred_flow_np)\n f.write(\"Average_flow\"+str(avg_flow)+\"\\n\")\n full_out_path = os.path.join('./src/image_baseline_2_output/', unique_name + '.png')\n imsave(full_out_path, flow_img)\n\n if save_flo:\n full_out_path = os.path.join(out_path, actual_name + '.flo')\n write_flow(pred_flow_np, full_out_path)\n else:\n source_path = './src/image_baseline_2_output/test.rgba.' + str(data).zfill(5) + '.png'\n target_path = './src/image_baseline_2/desired_image.png'\n target_path_2 = './src/image_baseline_2_output/test.rgba.' + str(int(data) - 1).zfill(5) + '.png'\n source_img = imread(source_path)\n target_img = imread(target_path)\n target2_img = imread(target_path_2)\n source = source_img[..., [2, 1, 0]]\n target_for = target_img[..., [2, 1, 0]]\n target_rev=target2_img[..., [2, 1, 0]]\n # Scale from [0, 255] -> [0.0, 1.0] if needed\n if source.max() > 1.0:\n source = source / 255.0\n if target_for.max() > 1.0:\n target_for = target_for / 255.0\n if target_rev.max() > 1.0:\n target_rev = target_rev / 255.0\n pred_flow_for = sess.run(pred_flow, feed_dict = {input_a : source, input_b : target_for})[0,:,:,:]\n pred_flow_rev = sess.run(pred_flow, feed_dict = {input_a : source, input_b : target_rev})[0,:,:,:]\n\n save_flo = True\n unique_name_for = 'test.flo.' + str(data).zfill(5)\n unique_name_rev = 'test.flo_depth.' + str(int(data) - 1).zfill(5)\n actual_name_for='output_img'\n actual_name_rev='output_img_flow'\n save_image=True\n if save_image:\n flow_img_for,avg_flow_for = flow_to_image(pred_flow_for)\n full_out_path = os.path.join('./src/image_baseline_2_output/', unique_name_for + '.png')\n f.write(\"Average_flow\"+str(avg_flow_for)+\"\\n\")\n imsave(full_out_path, flow_img_for)\n flow_img_rev,avg_flow = flow_to_image(pred_flow_rev)\n full_out_path = os.path.join('./src/image_baseline_2_output/', unique_name_rev + '.png')\n imsave(full_out_path, flow_img_rev)\n\n if save_flo:\n full_out_path = os.path.join(out_path, actual_name_for + '.flo')\n write_flow(pred_flow_for, full_out_path)\n full_out_path = os.path.join(out_path, actual_name_rev + '.flo')\n write_flow(pred_flow_rev, full_out_path)\n\n f.close()\n conn.close()\n\n\n def train(self, log_dir, training_schedule, input_a, input_b, flow, checkpoints=None):\n tf.summary.image(\"image_a\", input_a, max_outputs=2)\n tf.summary.image(\"image_b\", input_b, max_outputs=2)\n\n self.learning_rate = tf.train.piecewise_constant(\n self.global_step,\n [tf.cast(v, tf.int64) for v in training_schedule['step_values']],\n training_schedule['learning_rates'])\n\n optimizer = tf.train.AdamOptimizer(\n self.learning_rate,\n training_schedule['momentum'],\n training_schedule['momentum2'])\n\n inputs = {\n 'input_a': input_a,\n 'input_b': input_b,\n }\n predictions = self.model(inputs, training_schedule)\n total_loss = self.loss(flow, predictions)\n tf.summary.scalar('loss', total_loss)\n\n if checkpoints:\n for (checkpoint_path, (scope, new_scope)) in checkpoints.iteritems():\n variables_to_restore = slim.get_variables(scope=scope)\n renamed_variables = {\n var.op.name.split(new_scope + '/')[1]: var\n for var in variables_to_restore\n }\n restorer = tf.train.Saver(renamed_variables)\n with tf.Session() as sess:\n restorer.restore(sess, checkpoint_path)\n\n # Show the generated flow in TensorBoard\n if 'flow' in predictions:\n pred_flow_0 = predictions['flow'][0, :, :, :]\n pred_flow_0 = tf.py_func(flow_to_image, [pred_flow_0], tf.uint8)\n pred_flow_1 = predictions['flow'][1, :, :, :]\n pred_flow_1 = tf.py_func(flow_to_image, [pred_flow_1], tf.uint8)\n pred_flow_img = tf.stack([pred_flow_0, pred_flow_1], 0)\n tf.summary.image('pred_flow', pred_flow_img, max_outputs=2)\n\n true_flow_0 = flow[0, :, :, :]\n true_flow_0 = tf.py_func(flow_to_image, [true_flow_0], tf.uint8)\n true_flow_1 = flow[1, :, :, :]\n true_flow_1 = tf.py_func(flow_to_image, [true_flow_1], tf.uint8)\n true_flow_img = tf.stack([true_flow_0, true_flow_1], 0)\n tf.summary.image('true_flow', true_flow_img, max_outputs=2)\n\n train_op = slim.learning.create_train_op(\n total_loss,\n optimizer,\n summarize_gradients=True)\n\n if self.debug:\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n tf.train.start_queue_runners(sess)\n slim.learning.train_step(\n sess,\n train_op,\n self.global_step,\n {\n 'should_trace': tf.constant(1),\n 'should_log': tf.constant(1),\n 'logdir': log_dir + '/debug',\n }\n )\n else:\n slim.learning.train(\n train_op,\n log_dir,\n # session_config=tf.ConfigProto(allow_soft_placement=True),\n global_step=self.global_step,\n save_summaries_secs=60,\n number_of_steps=training_schedule['max_iter']\n )\n","sub_path":"Code/flownet2-tf/src/net_flow_depth_final.py","file_name":"net_flow_depth_final.py","file_ext":"py","file_size_in_byte":10022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"177067819","text":"import numpy as np\nimport glob\nfrom PIL import Image\nimport sys\n\ntry:\n i = 0\n for lightname in sorted(glob.glob(sys.argv[1] + '*.npy')):\n print(\"rendering image with light: \" + lightname)\n light = np.load(lightname)\n if light.shape[0] < light.shape[1]:\n light = light.T\n transport = np.load(sys.argv[2])[\"T\"]\n print(light.shape)\n print(transport.shape)\n albedo = Image.open(sys.argv[3])\n shading = np.matmul(transport, light)\n rendering = albedo * shading\n image_output = Image.fromarray((rendering).astype(np.uint8))\n image_output.save(sys.argv[4] + (\"frame%08d\" % i) + \"_relight2d.jpg\")\n i += 1\nexcept IndexError:\n print(\"Usage: python3 image_space_sh_light.py \")","sub_path":"image_space_sh_light.py","file_name":"image_space_sh_light.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"403231822","text":"#--------------------------------------------------------------------------\n# File and Version Information:\n# $Id: DdlPythonInterfaces.py 3643 2012-05-26 04:23:12Z jbarrera@SLAC.STANFORD.EDU $\n#\n# Description:\n# Module DdlPythonInterfaces...\n#\n#------------------------------------------------------------------------\n\n\"\"\"DDL parser which generates psana C++ interfaces.\n\nThis software was developed for the SIT project. If you use all or \npart of it, please give an appropriate acknowledgment.\n\n@see RelatedModule\n\n@version $Id: DdlPythonInterfaces.py 3643 2012-05-26 04:23:12Z jbarrera@SLAC.STANFORD.EDU $\n\n@author Andrei Salnikov, Joseph S. Barrera III\n\"\"\"\nfrom __future__ import print_function\n\n\n#------------------------------\n# Module's version from CVS --\n#------------------------------\n__version__ = \"$Revision: 3643 $\"\n# $Source$\n\n#--------------------------------\n# Imports of standard modules --\n#--------------------------------\nimport sys\nimport os\nimport types\nimport string\nimport re\n\n#---------------------------------\n# Imports of base class module --\n#---------------------------------\n\n#-----------------------------\n# Imports for other modules --\n#-----------------------------\nfrom psddl.Attribute import Attribute\nfrom psddl.ExprVal import ExprVal\nfrom psddl.Method import Method\nfrom psddl.Package import Package\nfrom psddl.Template import Template as T\nfrom psddl.Enum import Enum\nfrom psddl.Type import Type\n\n#----------------------------------\n# Local non-exported definitions --\n#----------------------------------\n\ndef _interpolate(expr, typeobj):\n expr = expr.replace('{xtc-config}', 'cfg')\n expr = expr.replace('@config', 'cfg')\n expr = expr.replace('{type}.', typeobj.name+\"::\")\n expr = expr.replace('@type.', typeobj.name+\"::\")\n expr = expr.replace('{self}.', \"this->\")\n expr = expr.replace('@self.', \"this->\")\n return expr\n\ndef _typename(type, top_ns=None):\n if type is None: return 'void'\n return type.fullName('C++', top_ns)\n\ndef _typedecl(type, top_ns=None):\n typename = _typename(type, top_ns)\n if not type.basic : typename = \"const \"+typename+'&'\n return typename\n\ndef _argdecl(name, type): \n return _typedecl(type) + ' ' + name\n\ndef _argdecl2(name, type): \n return name\n\ndef _dims(dims):\n return ''.join(['[%s]'%d for d in dims])\n\ndef _dimargs(rank, type):\n int_type = type.lookup('uint32_t')\n return [('i%d'%i, int_type) for i in range(rank)]\n\ndef _dimexpr(dims):\n return ''.join(['[i%d]'%i for i in range(len(dims))])\n\ndef _escape_and_quote(comment):\n comment = comment.replace('\\n','\\\\n')\n comment = comment.replace('\"','\\\\\"')\n return '\"%s\"'%comment\n#------------------------\n# Exported definitions --\n#------------------------\n\n#---------------------\n# Class definition --\n#---------------------\nclass DdlPythonInterfaces ( object ) :\n\n @staticmethod\n def backendOptions():\n \"\"\" Returns the list of options supported by this backend, returned value is \n either None or a list of triplets (name, type, description)\"\"\"\n return [\n ('psana-inc', 'PATH', \"directory for Psana includes, default: psddl_psana\"),\n ('psana-ns', 'STRING', \"namespace for Psana types, default: Psana\"),\n ]\n\n #----------------\n # Constructor --\n #----------------\n def __init__ ( self, backend_options, log ) :\n '''Constructor\n \n @param backend_options dictionary of options passed to backend\n @param log message logger instance\n '''\n self.incname = backend_options['global:header']\n self.cppname = backend_options['global:source']\n self.incdirname = backend_options.get('global:gen-incdir', \"\")\n self.top_pkg = backend_options.get('global:top-package')\n self.psana_inc = backend_options.get('psana-inc', \"psddl_psana\")\n self.psana_ns = backend_options.get('psana-ns', \"Psana\")\n self.generics = {}\n \n self._log = log\n\n #-------------------\n # Public methods --\n #-------------------\n\n def parseTree ( self, model ) :\n \n # open output files\n self.cpp = file(self.cppname, 'w')\n\n warning = \"/* Do not edit this file, as it is auto-generated */\\n\"\n print(warning, file=self.cpp)\n\n # add necessary includes to include file\n print('#include ', file=self.cpp)\n print('#include ', file=self.cpp)\n print('#include \"ndarray/ndarray.h\"', file=self.cpp)\n print('#include \"pdsdata/xtc/TypeId.hh\"', file=self.cpp)\n inc = os.path.join(self.psana_inc, os.path.basename(self.incname))\n print('#include \"%s\" // inc_psana' % inc, file=self.cpp)\n print('#include \"psddl_python/Converter.h\"', file=self.cpp)\n print('#include \"psddl_python/DdlWrapper.h\"', file=self.cpp)\n print('#include \"psddl_python/ConverterMap.h\"', file=self.cpp)\n print('#include \"psddl_python/ConverterBoostDef.h\"', file=self.cpp)\n print('#include \"psddl_python/ConverterBoostDefSharedPtr.h\"', file=self.cpp)\n print(\"\", file=self.cpp)\n\n if self.top_pkg : \n print(T(\"namespace $top_pkg {\")[self], file=self.cpp)\n\n # loop over packages in the model\n for pkg in model.packages() :\n if not pkg.included :\n self._log.debug(\"parseTree: package=%s\", repr(pkg))\n self._parsePackage(pkg)\n\n if self.top_pkg : \n print(T(\"} // namespace $top_pkg\")[self], file=self.cpp)\n\n # close all files\n self.cpp.close()\n\n def namespace_prefix(self):\n prefix = self.pkg.name + \"::\"\n if self.top_pkg: prefix = self.top_pkg + \"::\" + prefix\n return prefix\n\n def qualifiedConstantValue(self,constant):\n '''constant values sometimes reference previously defined \n constants. If the constant value is not numeric, we search the \n parent namespaces to see if it is defined. If so we qualify\n with the namespace found. If not, it may be a valid expression for \n code generation, so we just return it (so expressions like \"4*34\" \n will be returned unmodified.\n '''\n value = constant.value\n try: \n float(value) # this will not catch expressions like 4*17 or 0xFF\n return value\n except ValueError:\n enclosing = constant.parent\n while enclosing is not None:\n if type(enclosing) in [Type, Package]:\n for constant in enclosing.constants():\n if constant.name == value:\n return enclosing.fullName('C++',self.psana_ns) + '::' + value\n for enum in enclosing.enums():\n for enum_constant in enum.constants():\n if enum_constant.name == value:\n return enclosing.fullName('C++',self.psana_ns) + '::' + value\n enclosing = enclosing.parent\n\n self._log.debug(\"Coud not find parent namespace for %s\", value)\n return value\n\n def _parseEnum(self,enum):\n print(file=self.cpp)\n print(T(' enum_<$fullname>(\"$shortname\")') \\\n (fullname=enum.fullName('C++',self.psana_ns),\n shortname=enum.name), file=self.cpp)\n enclosingFullName = enum.parent.fullName('C++',self.psana_ns)\n for enum_constant in enum.constants():\n print(T(' .value(\"$constant\",$enclosingFullName::$constant)') \\\n (constant=enum_constant.name, enclosingFullName=enclosingFullName), file=self.cpp)\n print(' ;', file=self.cpp)\n\n def _parsePackage(self, pkgX):\n self.pkg = pkgX\n\n # open namespaces\n print(T(\"namespace $name {\")[self.pkg], file=self.cpp)\n print(\"\", file=self.cpp)\n print(\"using namespace boost::python;\", file=self.cpp)\n print(\"using boost::python::object;\", file=self.cpp)\n print(\"using boost::shared_ptr;\", file=self.cpp)\n print(\"using std::vector;\", file=self.cpp)\n print(\"\", file=self.cpp)\n\n print('namespace {', file=self.cpp)\n print('template (T::*MF)() const>', file=self.cpp)\n print('PyObject* method_shape(const T *x) {', file=self.cpp)\n print(' return detail::vintToList((x->*MF)());\\n}', file=self.cpp)\n print('} // namespace\\n', file=self.cpp)\n\n\n print(\"void createWrappers(PyObject* module) {\", file=self.cpp)\n\n # create sub-module for everything inside\n print(T(' DDL_CREATE_MODULE( \"psana.$name\", 0, \"The Python wrapper module for $name types\");')[self.pkg], file=self.cpp)\n print(' Py_INCREF(submodule);', file=self.cpp)\n print(T(' PyModule_AddObject(module, \"$name\", submodule);')[self.pkg], file=self.cpp)\n print(' scope mod = object(handle<>(borrowed(submodule)));', file=self.cpp)\n\n # expose any package level constants\n if len(self.pkg.constants())>0:\n print(file=self.cpp)\n for constant in self.pkg.constants():\n print(T(' mod.attr(\"$name\")=$value;')(name=constant.name,\n value=self.qualifiedConstantValue(constant)), file=self.cpp)\n\n # expose any package level enums:\n for enum in self.pkg.enums():\n self._parseEnum(enum)\n\n # loop over packages and types\n ndconverters = set()\n for ns in self.pkg.namespaces() :\n if isinstance(ns, Package) :\n print(\"Error: nested packages not supported:\", ns)\n continue\n if isinstance(ns, Type) :\n self._parseType(ns, ndconverters)\n\n # make the unversioned objects containing versioned types\n unversioned2verMap = dict()\n typeNamesNotEndingWithVer = set()\n\n for type in self.pkg.namespaces() :\n if isinstance(type, Type) and type.version is not None:\n vstr = \"V\"+str(type.version)\n if type.name.endswith(vstr):\n unvtype = type.name[:-len(vstr)]\n unversioned2verMap.setdefault(unvtype, []).append(type.name)\n else:\n typeNamesNotEndingWithVer.add(type.name)\n\n for nameNotEndingWithVer in typeNamesNotEndingWithVer:\n if nameNotEndingWithVer in unversioned2verMap:\n sys.stdout.write(\"DdlPythonInterfaces - info: %s is a type family including\\n\" % nameNotEndingWithVer)\n sys.stdout.write(\" names ending with and without the version string.\\n\")\n sys.stdout.write(\" Not generating the unversioned object containing the versioned types.\\n\")\n del unversioned2verMap[nameNotEndingWithVer]\n\n for unvtype, types in unversioned2verMap.items():\n print(T(' {\\n PyObject* unvlist = PyList_New($len);')(len=len(types)), file=self.cpp)\n for i, type in enumerate(types):\n print(T(' PyList_SET_ITEM(unvlist, $i, PyObject_GetAttrString(submodule, \"$type\"));')(locals()), file=self.cpp)\n print(T(' PyObject_SetAttrString(submodule, \"$unvtype\", unvlist);')(locals()), file=self.cpp)\n print(T(' Py_CLEAR(unvlist);\\n }')(locals()), file=self.cpp)\n\n\n for type, ndim in ndconverters:\n if ndim > 0:\n print(T(' detail::register_ndarray_to_numpy_cvt();')(locals()), file=self.cpp)\n else:\n print(T(' detail::register_ndarray_to_list_cvt();')(locals()), file=self.cpp)\n\n # end createWrappers()\n print(\"\", file=self.cpp)\n print(\"} // createWrappers()\", file=self.cpp)\n\n # close namespaces\n print(T(\"} // namespace $name\")[self.pkg], file=self.cpp)\n\n def _parseType(self, type, ndconverters):\n\n self._log.debug(\"_parseType: type=%s\", repr(type))\n\n # skip included types\n if type.included : return\n\n self.codegen(type, ndconverters)\n\n def codegen(self, type, ndconverters):\n\n self._log.debug(\"codegen: type=%s\", repr(type))\n #print \"codegen: type=%s\" % repr(type)\n\n # this class (class being generated)\n wrapped = type.fullName('C++', self.psana_ns)\n name = type.name + \"_Wrapper\"\n\n prefix = self.namespace_prefix()\n cname = type.name\n \n templ_args = [wrapped]\n if type.base:\n base = T('boost::python::bases<$base>')(base=type.base.fullName('C++', self.psana_ns))\n templ_args.append(base)\n if not type.value_type:\n holder = T('boost::shared_ptr<$wrapped>')(locals())\n templ_args += [holder, \"boost::noncopyable\"]\n templ_args = ', '.join(templ_args)\n \n pkgname = self.pkg.name\n\n has_nested_enums = len(type.enums()) > 0\n has_nested_constants = len(type.constants()) > 0\n has_version_or_type_id = type.version or type.type_id\n add_scoped_attributes = has_nested_enums or has_nested_constants or has_version_or_type_id\n if add_scoped_attributes:\n print(' {', file=self.cpp)\n print(' scope outer = ', file=self.cpp)\n\n if type.comment:\n type_comment = _escape_and_quote(type.comment)\n print(T(' class_<$templ_args >(\"$cname\", $type_comment, no_init)')(locals()), file=self.cpp)\n else:\n print(T(' class_<$templ_args >(\"$cname\", no_init)')(locals()), file=self.cpp)\n\n # generate methods (for public methods and abstract class methods only)\n for method in type.methods(): \n if method.access == \"public\": self._genMethod(type, method, wrapped, ndconverters)\n\n # generate _shape() methods for array attributes\n for attr in type.attributes() :\n self._genAttrShapeAndListDecl(type, attr, wrapped)\n\n # close class declaration\n print(' ;', file=self.cpp)\n\n # write any nested enums, nested constants, version and type_id if present\n for enum in type.enums():\n self._parseEnum(enum)\n\n if type.version is not None:\n print(T(' scope().attr(\"Version\")=$version;')(version=type.version), file=self.cpp)\n if type.type_id:\n print(T(' scope().attr(\"TypeId\")=int(Pds::TypeId::$typeid);')(typeid=type.type_id), file=self.cpp)\n \n for constant in type.constants():\n print(T(' scope().attr(\"$name\")=$value;')(name=constant.name,\n value=self.qualifiedConstantValue(constant)), file=self.cpp)\n if add_scoped_attributes:\n print(' }', file=self.cpp)\n\n # generates converter instance\n type_id = \"Pds::TypeId::\"+type.type_id if type.type_id is not None else -1\n if type.value_type:\n cvt_type = T('ConverterBoostDef<$wrapped> ')(locals()) \n else:\n cvt_type = T('ConverterBoostDefSharedPtr<$wrapped> ')(locals()) \n print(T(' ConverterMap::instance().addConverter(boost::make_shared<$cvt_type>($type_id));')(locals()), file=self.cpp)\n print(\"\", file=self.cpp)\n\n def _genMethod(self, type, method, bclass, ndconverters):\n \"\"\"Generate method declaration and definition\"\"\"\n\n self._log.debug(\"_genMethod: method: %s\", method)\n \n method_name = method.name\n policy = None\n args = method.args\n margs = ', '.join([_argdecl2(*arg) for arg in args])\n \n if method_name == '_sizeof': \n # not needed in Python\n return\n \n # generate code for a method\n if method.type is None:\n \n # method which does not return anything\n pass\n\n elif not method.rank:\n \n # attribute is a regular non-array object, it is returned by value or cref\n # non-basic types are returned by cref from wrapped method if method has \n # corresponding attribute\n if method.attribute:\n if method.type.basic: \n policy = None\n elif method.type.value_type:\n policy = \"return_value_policy()\"\n else:\n policy = \"return_internal_reference<1>()\"\n\n elif method.type.name == 'char':\n \n # char array is actually a string\n pass\n \n elif method.type.value_type and method.type.basic:\n \n # should also add boost converter for this ndarray type\n ctype = method.type.fullName('C++', self.psana_ns)\n if isinstance(method.type, Enum):\n ctype = method.type.base.fullName('C++', self.psana_ns)\n ndim = method.rank\n ndconverters.add((ctype, ndim))\n\n elif method.type.value_type:\n\n # wrapped method returns ndarray and we should convert it into regular Python list\n ctype = method.type.fullName('C++', self.psana_ns)\n ndconverters.add((ctype, -1))\n\n else:\n\n # array of non-value types, method will accept a set of indices.\n # wrapped method returns a const reference to an object wholly \"contained\" \n # in the wrapped object, so set policy correctly. \n policy = \"return_internal_reference<>()\"\n\n self._genMethodDef(type, bclass, method_name, method.comment, policy=policy)\n\n\n def _genMethodDef(self, type, bclass, method_name, method_comment, policy=''):\n\n policy = ', ' + policy if policy else ''\n if method_comment:\n method_comment = _escape_and_quote(method_comment)\n print(T(' .def(\"$method_name\", &$bclass::$method_name$policy,$method_comment)')(locals()), file=self.cpp)\n else:\n print(T(' .def(\"$method_name\", &$bclass::$method_name$policy)')(locals()), file=self.cpp)\n\n def isString(self, o):\n return type(o) == type(\"\")\n\n def _genAttrShapeAndListDecl(self, type, attr, bclass):\n if not attr.shape_method: return\n if not attr.accessor: return\n \n # value-type arrays return ndarrays which do not need shape method\n if attr.type.value_type and attr.type.name != 'char': return\n\n # generate shape method\n shape_method = attr.shape_method\n print(T(' .def(\"$shape_method\", &method_shape<$bclass, &$bclass::$shape_method>)')(locals()), file=self.cpp)\n\n#\n# In case someone decides to run this module\n#\nif __name__ == \"__main__\" :\n\n # In principle we can try to run test suite for this module,\n # have to think about it later. Right now just abort.\n sys.exit ( \"Module is not supposed to be run as main module\" )\n","sub_path":"src/DdlPythonInterfaces.py","file_name":"DdlPythonInterfaces.py","file_ext":"py","file_size_in_byte":18903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"280296833","text":"# This script extracts a 200x200pixels sub-image for \n# material detection and colour identification purposes.\n# Author: Serena Toon (stoo718@aucklanduni.ac.nz)\n\nfrom PIL import Image\nimport numpy as np\nimport cv2\n\n# get 200x200 sub-image, slightly off-center\ndef get_sub_image(filename):\n\timg = Image.open(filename)\n\tarea = (100, 300, 300, 500)\n\tsub_img = img.crop(area).save('cropped.png')\n\tsharpen()\n\treturn sub_img\n\n\n# https://www.cc.gatech.edu/classes/AY2015/cs4475_summer/documents/sharpen.py\ndef sharpen():\n\t# load image\n\timg = cv2.imread('cropped.png')\n\n\t#create identity filter, with 1 shifted to the right\n\tkernel = np.zeros((9,9), np.float32)\n\tkernel[4,4] = 2.0 # multiply identity by 2\n\n\t# create box filter\n\tbox_filter = np.ones( (9,9), np.float32) / 81.0\n\n\t#subtract the two\n\tkernel = kernel - box_filter\n\n\tsharpened = cv2.filter2D(img, -1, kernel)\n\tcv2.imwrite('sharpened.png', sharpened)\n\n\n#get_sub_image(\"removedbg.png\")","sub_path":"04 BackEnd/extract_sub_image.py","file_name":"extract_sub_image.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"145128033","text":"#!/usr/local/bin/python3\nimport re\ndef extract_data(s):\n pattern = re.compile(r\"\"\"\\s*(?P\\d*?)\\s*?\n -\\s*?\n (?P\\d*?)\\s*?\n (?P[a-zA-Z]?)\\s*?\n :\\s*?\n (?P\\w\\w*)\\s*?\"\"\", re.VERBOSE)\n match = pattern.match(s)\n start = int(match.group(\"start\"))\n end = int(match.group(\"end\"))\n letter = match.group(\"letter\")\n str = match.group(\"str\")\n return int(str.count(letter) in range(start, end+1))\nwith open(\"day02a.txt\",'r') as f:\n print(sum(list(map(extract_data, f.readlines()))))\n","sub_path":"day02a.py","file_name":"day02a.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"285502812","text":"from flask import Flask, request\nimport requests\napplication = Flask(__name__)\n\n@application.route('/check', methods=['POST'])\ndef check():\n token = request.headers['Authorization']\n data = {\"token\": token}\n result = requests.post('http://auth:5001/auth', data=data).text\n if result == \"wcf\":\n return 'Success'\n else:\n return 'Failure in Web API'\n\n\nif __name__ == \"__main__\":\n application.run(host='0.0.0.0', port=5000)","sub_path":"web_api.py","file_name":"web_api.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"635253494","text":"#MIT License\r\n\r\n#Copyright (c) 2018 The University of Michigan\r\n\r\n#Permission is hereby granted, free of charge, to any person obtaining a copy\r\n#of this software and associated documentation files (the \"Software\"), to deal\r\n#in the Software without restriction, including without limitation the rights\r\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n#copies of the Software, and to permit persons to whom the Software is\r\n#furnished to do so, subject to the following conditions:\r\n\r\n#The above copyright notice and this permission notice shall be included in all\r\n#copies or substantial portions of the Software.\r\n\r\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n#SOFTWARE.\r\n\r\nfrom supervised_classifier_ngram import supervised_classifier_ngram\r\nfrom supervised_classifier import supervised_classifier\r\nfrom Address import Address\r\nimport os\r\ndef title_arbitration(normal_classifier_title_result,key_words_title_result,key_words_occurrence_array,key_words_title_result_second,max_zero_flag,max_second_zero_flag):\r\n ADC = 'ADC'\r\n BDRT = 'BDRT'\r\n CDC= 'CDC'\r\n counters = 'counters'\r\n DAC = 'DAC'\r\n DCDC= 'DCDC'\r\n Delay_Line = 'Delay_Line'\r\n DSP = 'DSP'\r\n IO = 'IO'\r\n LDO='LDO'\r\n Opamp = 'Opamp'\r\n Digital_Potentiometers = 'Digital_Potentiometers'\r\n PLL = 'PLL'\r\n SRAM='SRAM'\r\n Temperature_Sensor='Temperature_Sensor'\r\n\r\n title=[None]*len(key_words_title_result)\r\n Path_extracted=Address(1).split(\"\\n\")\r\n Path_extracted1=Path_extracted[0]\r\n ADC_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'ADC'), ADC]\r\n BDRT_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'BDRT'), BDRT]\r\n CDC_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'CDC'), CDC]\r\n COUNTER_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'counters'), counters]\r\n DAC_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'DAC'), DAC]\r\n DCDC_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'DCDC'), DCDC]\r\n DELAY_LINE_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'Delay_Line'), Delay_Line]\r\n DSP_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'DSP'), DSP]\r\n IO_path = [os.path.join(os.path.join(Path_extracted1, 'cropped_text'), 'IO'), IO]\r\n LDO_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'LDO'), LDO]\r\n OPAMP_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'Opamp'), Opamp]\r\n POTENTIOMETER_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'Digital_Potentiometers'), Digital_Potentiometers]\r\n PLL_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'PLL'), PLL]\r\n SRAM_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'SRAM'), SRAM]\r\n Temperature_Sensor_path=[os.path.join(os.path.join(Path_extracted1,'cropped_text'), 'Temperature_Sensor'), Temperature_Sensor]\r\n\r\n SOURCES = [ADC_path,BDRT_path,COUNTER_path,DAC_path,DELAY_LINE_path,DSP_path,IO_path,OPAMP_path,POTENTIOMETER_path,PLL_path,DCDC_path,CDC_path,Temperature_Sensor_path,SRAM_path,LDO_path]\r\n def loockup_title_table(title_input):\r\n if title_input=='CDC':\r\n ind_ex=0\r\n elif title_input=='ADC':\r\n ind_ex=1\r\n elif title_input=='DCDC':\r\n ind_ex=2\r\n elif title_input=='LDO':\r\n ind_ex=3\r\n elif title_input=='PLL':\r\n ind_ex=4\r\n elif title_input=='SRAM':\r\n ind_ex=5\r\n elif title_input=='Temperature_Sensor':\r\n ind_ex=6\r\n elif title_input=='BDRT':\r\n ind_ex=7\r\n elif title_input=='counters':\r\n ind_ex=8\r\n elif title_input=='DAC':\r\n ind_ex=9\r\n elif title_input=='Delay_Line':\r\n ind_ex=10\r\n elif title_input=='DSP':\r\n ind_ex=11\r\n elif title_input=='IO':\r\n ind_ex=12\r\n elif title_input=='Opamp':\r\n ind_ex=13\r\n elif title_input=='Digital_Potentiometers':\r\n ind_ex=14\r\n return ind_ex\r\n def title_classifier_caller(input_array):\r\n Accumulated_path=[]\r\n if 'CDC' not in input_array:\r\n Accumulated_path.append(CDC_path)\r\n if 'ADC' not in input_array:\r\n Accumulated_path.append(ADC_path)\r\n if 'DCDC' not in input_array:\r\n Accumulated_path.append(DCDC_path)\r\n if 'LDO' not in input_array:\r\n Accumulated_path.append(LDO_path)\r\n if 'PLL' not in input_array:\r\n Accumulated_path.append(PLL_path)\r\n if 'SRAM' not in input_array:\r\n Accumulated_path.append(SRAM_path)\r\n if 'Temperature_Sensor' not in input_array:\r\n Accumulated_path.append(Temperature_Sensor_path)\r\n if 'BDRT' not in input_array:\r\n Accumulated_path.append(BDRT_path)\r\n if 'counters' not in input_array:\r\n Accumulated_path.append(COUNTER_path)\r\n if 'DAC' not in input_array:\r\n Accumulated_path.append(DAC_path)\r\n if 'Delay_Line' not in input_array:\r\n Accumulated_path.append(DELAY_LINE_path)\r\n if 'DSP' not in input_array:\r\n Accumulated_path.append(DSP_path)\r\n if 'IO' not in input_array:\r\n Accumulated_path.append(IO_path)\r\n if 'Opamp' not in input_array:\r\n Accumulated_path.append(OPAMP_path)\r\n if 'Digital_Potentiometers' not in input_array:\r\n Accumulated_path.append(POTENTIOMETER_path)\r\n return Accumulated_path\r\n for i in range(0,len(key_words_title_result)):\r\n whole_title_classifier_guessed=[]\r\n if max_zero_flag[i]:\r\n title[i]=normal_classifier_title_result[i]\r\n else:\r\n if 'SRAM' in normal_classifier_title_result[i]:\r\n title[i]='SRAM'\r\n elif 'BDRT' in normal_classifier_title_result[i]:\r\n title[i]='BDRT'\r\n else:\r\n if normal_classifier_title_result[i] in key_words_title_result[i]:\r\n title[i]=key_words_title_result[i][key_words_title_result[i].index(normal_classifier_title_result[i])]\r\n elif 'LDO' in key_words_title_result[i]:\r\n title[i]='LDO'\r\n elif 'Delay_Line' in key_words_title_result[i]:\r\n title[i]='Delay_Line'\r\n elif 'IO' in key_words_title_result[i]:\r\n title[i]='IO'\r\n else:\r\n if len(key_words_title_result[i])>1:\r\n while normal_classifier_title_result[i] not in key_words_title_result[i]:\r\n whole_title_classifier_guessed.append(normal_classifier_title_result[i])\r\n SOURCE_input=title_classifier_caller(whole_title_classifier_guessed)\r\n normal_classifier_title_result=supervised_classifier(SOURCE_input) \r\n title[i]=key_words_title_result[i][key_words_title_result[i].index(normal_classifier_title_result[i])]\r\n else: \r\n if not max_second_zero_flag[i]:\r\n break_tag=False\r\n while not break_tag:\r\n if normal_classifier_title_result[i] in key_words_title_result[i]:\r\n title[i]=key_words_title_result[i][key_words_title_result[i].index(normal_classifier_title_result[i])]\r\n break_tag=True\r\n if normal_classifier_title_result[i] in key_words_title_result_second[i]:\r\n title[i]=key_words_title_result_second[i][key_words_title_result_second[i].index(normal_classifier_title_result[i])]\r\n break_tag=True\r\n whole_title_classifier_guessed.append(normal_classifier_title_result[i])\r\n SOURCE_input=title_classifier_caller(whole_title_classifier_guessed)\r\n normal_classifier_title_result=supervised_classifier(SOURCE_input)\r\n else:\r\n title[i]=key_words_title_result[i][0]\r\n return title\r\n","sub_path":"title_arbitration.py","file_name":"title_arbitration.py","file_ext":"py","file_size_in_byte":8839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"636577008","text":"# -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8')\n\n__author__ = \"anton\"\n__date__ = \"$18.08.2014 22:51:24$\"\n\nfrom make_db_file import loadDbase\ndb = loadDbase()\nfor key in db:\n print( key, '=>\\n ', db[key] )\n\nprint( db['sue']['name'] )","sub_path":"db_file/dump_db_file.py","file_name":"dump_db_file.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"201288211","text":"\"\"\"\n@author: Francis | 韩 心 海\n@contact: xinhai_han@icloud.com\n@file: ct.py\n@date: 2020/11/12 11:00 下午\n\n# code is far away from bugs with the god animal protecting\n I love animals. They taste delicious.\n ┏┓ ┏┓\n ┏┛┻━━━┛┻━━┓\n ┃ ☃ ┃\n ┃ ┳┛ ┗┳ ┃\n ┃ ┻ ┃\n ┗━┓ ┏━┛\n ┃ ┗━━━━━┓\n ┃ 神兽保佑 ┣┓\n ┃ 永无BUG! ┏┛\n ┗━━━┓┓┏━━┳┓┏┛\n ┃┫┫ ┃┫┫\n ┗┻┛ ┗┻┛\n\"\"\"\nimport cv2\nimport numpy as np\n\n\ndef get_red(img):\n redImg = img[:, :, 2]\n return redImg\n\n\ndef get_green(img):\n greenImg = img[:, :, 1]\n return greenImg\n\n\ndef get_blue(img):\n blueImg = img[:, :, 0]\n return blueImg\n\n\nif __name__ == '__main__':\n img = cv2.imread(\"data/pic2.jpg\")\n b, g, r = cv2.split(img)\n zeros = np.zeros(img.shape[:2], dtype=\"uint8\"); # 创建与image相同大小的零矩阵\n # cv2.imshow(\"Blue 1\", b)\n # cv2.imshow(\"Green 1\", g)\n # cv2.imshow(\"Red 1\", r)\n b = get_blue(img)\n g = get_green(img)\n r = get_red(img)\n # cv2.imshow(\"Blue 2\", cv2.merge([b, zeros, zeros]))\n # cv2.imshow(\"Green 2\", g)\n # cv2.imshow(\"Red 2\", r)\n # cv2.imshow(\"Back\", cv2.merge([b, g, r]))\n cv2.imshow(\"Back\", img)\n print(img[95])\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n #\n # merged = cv2.merge([b, g, r])\n # print(merged)\n","sub_path":"cv_test/ct.py","file_name":"ct.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"323463062","text":"from django.conf.urls import patterns, include, url\n\nimport autocomplete_light\nautocomplete_light.autodiscover()\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'EduLyft.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n url(r'^$', include('home.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^tests/', include('tests.urls')),\n url(r'^students/', include('Students.urls')),\n)\n","sub_path":"EduLyft/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"419702791","text":"from pprint import pprint\n\n\nclass Solution:\n # O(m+n) time, O(m+n) extra space\n def naiveMerge(self, A, m, B, n):\n iter1, iter2 = 0, 0\n lst = list()\n while iter1 < m or iter2 < n:\n if iter1 == m: \n lst.append(B[iter2]) \n iter2 += 1\n elif iter2 == n:\n lst.append(A[iter1])\n iter1 += 1\n elif A[iter1] <= B[iter2]:\n lst.append(A[iter1])\n iter1 += 1\n else:\n lst.append(B[iter2])\n iter2 += 1\n for i in xrange(m+n):\n A[i] = lst[i]\n\n # O(m+n) time, O(1) extra space\n def merge(self, A, m, B, n):\n pos = m+n-1\n m -= 1\n n -= 1\n while n >= 0:\n if m >= 0 and A[m] >= B[n]: \n A[pos] = A[m]\n m -= 1\n else:\n A[pos] = B[n]\n n -= 1\n pos -= 1\n if n < 0: break\n if m < 0: \n while n >= 0:\n A[pos] = B[n]\n pos -= 1\n n -= 1\n break\n\n\nif __name__ == '__main__':\n m = input('Please enter the number of elements in array A: ')\n A, B = [], []\n for i in xrange(m):\n ele = input('Please enter the element in array A: ')\n A.append(ele)\n n = input('Please enter the number of elements in array B: ')\n for i in xrange(n):\n ele = input('Please enter the element in array B: ')\n B.append(ele)\n solution = Solution()\n A.sort()\n B.sort()\n A += [0] * len(B)\n solution.merge(A, m, B, n)\n pprint('Merged array: ')\n pprint(A)","sub_path":"mergearray.py","file_name":"mergearray.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"344551989","text":"from vocabulary import *\nfrom load_from_excel import *\nimport re\nclass content_new_infor_classifier():\n \"\"\"\n this is the rule based classifier\n \"\"\"\n def __init__(self):\n external = Excel(\"external data.xls\")\n internal = Excel(\"internal data.xls\")\n new_data = Excel(\"new all-hands data.xls\")\n # print(external.sentence)\n tot_data = Excel(path=None)\n tot_data.sentence += external.sentence\n tot_data.sentence += internal.sentence\n tot_data.sentence += new_data.sentence\n tot_data.label += external.label\n tot_data.label += internal.label\n tot_data.label += new_data.label\n print(tot_data.sentence)\n print(tot_data.label)\n self.data = tot_data.get_sentence_by_category()\n\n def predict(self, sentences, positive=True):\n com_str = \"[a-zA-Z ,.\\(\\)]\"\n predict_label = []\n for sentence in sentences:\n re_str = \"([a-zA-Z ,.\\(\\)]*(([a-zA-Z ,.\\(\\)]*)|message|infor)new[a-zA-Z ,.\\(\\)]*)|\" \\\n \"([a-zA-Z ,.\\(\\)]*new[a-zA-Z ,.\\(\\)]*(([a-zA-Z ,.\\(\\)]*)|infor|message))|\" \\\n \"([a-zA-Z ,.\\(\\)]*((demo)|(Demo)|(DEMO))|(demos)([ .,]([a-zA-Z ,.\\(\\)]*)|([a-zA-Z ,.\\(\\)]*information[a-zA-Z ,.\\(\\)]*known))*)\"\n x = re.search(re_str,sentence)\n # tmp = re.search(\"\")\n if(positive):\n if(x!=None):\n predict_label += [1]\n else:\n print(sentence)\n predict_label += [0]\n else:\n if (x != None):\n print(sentence)\n predict_label += [1]\n else:\n\n predict_label += [0]\n return predict_label\n\n\n def validate(self, sentences, label):\n predict = self.predict(sentences)\n loss = self.get_loss(predict, label)\n\n def get_loss(self, predict, label):\n \"\"\"\n\n :param predict: [ [], [], [] ] , 2-D list, several sentences, each sentence has several categories predicted.\n :param label: [ [], [], [] ] , 2-D list, several sentences, each sentence has several categories labeled.\n :return:\n loss_list: [] 1-D list, loss for each category\n tot_loss: the sum of the loss_list\n \"\"\"\n loss_list = [0]*len(predict[0])\n for p_l in zip(predict, label):\n for idx in range(0, len(p_l[0])):\n if p_l[0][i]!=p_l[1][i]:\n loss[i] += 1\n tot_loss = sum(loss_list)\n return loss_list, tot_loss\n\nif __name__ ==\"__main__\":\n classifier = content_new_infor_classifier()\n print(len(classifier.data[14]))\n predict_label = classifier.predict(classifier.data[14])\n print(predict_label)\n predict_label = classifier.predict(classifier.data[0],positive=False)\n print(predict_label)","sub_path":"all hands investigation/data&code/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"357980696","text":"from game_class import YTGBaseWeapon\n\nfrom Engine.config import CHANNEL\nfrom Engine.geometry import Vec2d\nfrom Engine.loading import load_model, cast_model, load_sound\n\nimport pymunk\n\nNAME = __name__.split('.')[-1]\nMODEL = load_model('Weapons\\\\Models\\\\%s' % (NAME,))\n\nCS = Vec2d(13, 17)\n\n\nclass Weapon(YTGBaseWeapon):\n name = NAME\n max_health = 40\n size_inc = 1.25\n proj_velocity = 1200\n fire_delay = 100\n sound = {\n 'fire': [load_sound('Weapons\\\\Models\\\\explosion_dull'), {'channel': CHANNEL.PLASMA_WEAPON}]\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.i_body = pymunk.Body()\n self.shape = pymunk.Circle(self.body, self.RADIUS, self.image_to_local((26, 17)))\n self.shape.density = 1\n\n @classmethod\n def init_class(cls):\n cls._frames, cls.IMAGE_SHIFT = cast_model(MODEL, CS, cls.size_inc)\n cls.precalculate_shape()\n cls.calculate_poly_shape()\n from Projectiles.plasma_bolt import Projectile\n cls.Projectile = Projectile\n cls.fire_pos = cls.image_to_local((65, 17))\n\n @classmethod\n def precalculate_shape(cls):\n radius = 22\n\n cls.RADIUS = radius * cls.size_inc\n\n @classmethod\n def calculate_poly_shape(cls):\n img_poly_left = []\n poly_left = [tuple(e[n] - CS[n] for n in range(2)) for e in img_poly_left]\n poly_right = [(e[0], -e[1]) for e in poly_left[::-1]]\n cls.POLY_SHAPE = [(e[0] * cls.size_inc, e[1] * cls.size_inc) for e in poly_left + poly_right]\n\n\nWeapon.init_class()\n","sub_path":"Weapons/plasma_repeater.py","file_name":"plasma_repeater.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"424931260","text":"# -*- coding: utf-8 -*-\n\"\"\"Contains the main `APISpec` class.\n\"\"\"\nfrom .core import APISpec\nfrom .plugin import BasePlugin\n\n__version__ = '1.0.0b2'\n__author__ = 'Steven Loria, Jérôme Lafréchoux, and contributors'\n__license__ = 'MIT'\n\n\n__all__ = [\n 'APISpec',\n 'BasePlugin',\n]\n","sub_path":"apispec/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"591077763","text":"#COPY of tensorflow contrib code which is not officially released yet\n\n\n# Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Module for constructing a linear-chain CRF.\nThe following snippet is an example of a CRF layer on top of a batched sequence\nof unary scores (logits for every word). This example also decodes the most\nlikely sequence at test time:\nlog_likelihood, transition_params = tf.contrib.crf.crf_log_likelihood(\n unary_scores, gold_tags, sequence_lengths)\nloss = tf.reduce_mean(-log_likelihood)\ntrain_op = tf.train.GradientDescentOptimizer(0.01).minimize(loss)\ntf_unary_scores, tf_sequence_lengths, tf_transition_params, _ = session.run(\n [unary_scores, sequence_lengths, transition_params, train_op])\nfor tf_unary_scores_, tf_sequence_length_ in zip(tf_unary_scores,\n tf_sequence_lengths):\n# Remove padding.\ntf_unary_scores_ = tf_unary_scores_[:tf_sequence_length_]\n# Compute the highest score and its tag sequence.\nviterbi_sequence, viterbi_score = tf.contrib.crf.viterbi_decode(\n tf_unary_scores_, tf_transition_params)\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import rnn\nfrom tensorflow.contrib.rnn import RNNCell\nfrom tensorflow.python.ops import variable_scope as vs\n\n__all__ = [\"crf_sequence_score\", \"crf_log_norm\", \"crf_log_likelihood\",\n \"crf_unary_score\", \"crf_binary_score\", \"CrfForwardRnnCell\",\n \"viterbi_decode\"]\n\n\ndef reduce_logsumexp(input_tensor, reduction_indices=None, keep_dims=False,\n name=None):\n \"\"\"Computes log(sum(exp(elements across dimensions of a tensor))).\n Reduces `input_tensor` along the dimensions given in `reduction_indices`.\n Unless `keep_dims` is true, the rank of the tensor is reduced by 1 for each\n entry in `reduction_indices`. If `keep_dims` is true, the reduced dimensions\n are retained with length 1.\n If `reduction_indices` has no entries, all dimensions are reduced, and a\n tensor with a single element is returned.\n This funciton is more numerically stable than log(sum(exp(input))). It avoids\n overflows caused by taking the exp of large inputs and underflows caused by\n taking the log of small inputs.\n For example:\n ```python\n # 'x' is [[0, 0, 0]]\n # [0, 0, 0]]\n tf.reduce_logsumexp(x) ==> log(6)\n tf.reduce_logsumexp(x, 0) ==> [log(2), log(2), log(2)]\n tf.reduce_logsumexp(x, 1) ==> [log(3), log(3)]\n tf.reduce_logsumexp(x, 1, keep_dims=True) ==> [[log(3)], [log(3)]]\n tf.reduce_logsumexp(x, [0, 1]) ==> log(6)\n ```\n Args:\n input_tensor: The tensor to reduce. Should have numeric type.\n reduction_indices: The dimensions to reduce. If `None` (the defaut),\n reduces all dimensions.\n keep_dims: If true, retains reduced dimensions with length 1.\n name: A name for the operation (optional).\n Returns:\n The reduced tensor.\n \"\"\"\n with tf.name_scope(name) as name:\n my_max = array_ops.stop_gradient(\n tf.reduce_max(input_tensor, reduction_indices, keep_dims=True))\n result = tf.log(tf.reduce_sum(\n tf.exp(input_tensor - my_max),\n reduction_indices,\n keep_dims=True)) + my_max\n if not keep_dims:\n result = array_ops.squeeze(result, reduction_indices)\n return result\n\n\ndef _lengths_to_masks(lengths, max_length):\n \"\"\"Creates a binary matrix that can be used to mask away padding.\n Args:\n lengths: A vector of integers representing lengths.\n max_length: An integer indicating the maximum length. All values in\n lengths should be less than max_length.\n Returns:\n masks: Masks that can be used to get rid of padding.\n \"\"\"\n tiled_ranges = array_ops.tile(\n array_ops.expand_dims(math_ops.range(max_length), 0),\n [array_ops.shape(lengths)[0], 1])\n lengths = array_ops.expand_dims(lengths, 1)\n masks = math_ops.to_float(\n math_ops.to_int64(tiled_ranges) < math_ops.to_int64(lengths))\n return masks\n\n\ndef crf_sequence_score(inputs, tag_indices, sequence_lengths,\n transition_params):\n \"\"\"Computes the unnormalized score for a tag sequence.\n Args:\n inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials\n to use as input to the CRF layer.\n tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we\n compute the unnormalized score.\n sequence_lengths: A [batch_size] vector of true sequence lengths.\n transition_params: A [num_tags, num_tags] transition matrix.\n Returns:\n sequence_scores: A [batch_size] vector of unnormalized sequence scores.\n \"\"\"\n # Compute the scores of the given tag sequence.\n unary_scores = crf_unary_score(tag_indices, sequence_lengths, inputs)\n binary_scores = crf_binary_score(tag_indices, sequence_lengths,\n transition_params)\n sequence_scores = unary_scores + binary_scores\n return sequence_scores\n\n\ndef crf_log_norm(inputs, sequence_lengths, transition_params):\n \"\"\"Computes the normalization for a CRF.\n Args:\n inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials\n to use as input to the CRF layer.\n sequence_lengths: A [batch_size] vector of true sequence lengths.\n transition_params: A [num_tags, num_tags] transition matrix.\n Returns:\n log_norm: A [batch_size] vector of normalizers for a CRF.\n \"\"\"\n # Split up the first and rest of the inputs in preparation for the forward\n # algorithm.\n first_input = array_ops.slice(inputs, [0, 0, 0], [-1, 1, -1])\n first_input = array_ops.squeeze(first_input, [1])\n rest_of_input = array_ops.slice(inputs, [0, 1, 0], [-1, -1, -1])\n\n # Compute the alpha values in the forward algorithm in order to get the\n # partition function.\n forward_cell = CrfForwardRnnCell(transition_params)\n _, alphas = rnn.dynamic_rnn(\n cell=forward_cell,\n inputs=rest_of_input,\n sequence_length=sequence_lengths - 1,\n initial_state=first_input,\n dtype=dtypes.float32)\n log_norm = reduce_logsumexp(alphas, [1])\n return log_norm\n\n\ndef crf_log_likelihood(inputs,\n tag_indices,\n sequence_lengths,\n transition_params=None):\n \"\"\"Computes the log-likehood of tag sequences in a CRF.\n Args:\n inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials\n to use as input to the CRF layer.\n tag_indices: A [batch_size, max_seq_len] matrix of tag indices for which we\n compute the log-likehood.\n sequence_lengths: A [batch_size] vector of true sequence lengths.\n transition_params: A [num_tags, num_tags] transition matrix, if available.\n Returns:\n log_likelihood: A scalar containing the log-likelihood of the given sequence\n of tag indices.\n transition_params: A [num_tags, num_tags] transition matrix. This is either\n provided by the caller or created in this function.\n \"\"\"\n # Get shape information.\n num_tags = inputs.get_shape()[2].value\n\n # Get the transition matrix if not provided.\n if transition_params is None:\n transition_params = vs.get_variable(\"transitions\", [num_tags, num_tags])\n\n sequence_scores = crf_sequence_score(inputs, tag_indices, sequence_lengths,\n transition_params)\n log_norm = crf_log_norm(inputs, sequence_lengths, transition_params)\n\n # Normalize the scores to get the log-likelihood.\n log_likelihood = sequence_scores - log_norm\n return log_likelihood, transition_params\n\n\ndef crf_unary_score(tag_indices, sequence_lengths, inputs):\n \"\"\"Computes the unary scores of tag sequences.\n Args:\n tag_indices: A [batch_size, max_seq_len] matrix of tag indices.\n sequence_lengths: A [batch_size] vector of true sequence lengths.\n inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials.\n Returns:\n unary_scores: A [batch_size] vector of unary scores.\n \"\"\"\n batch_size = array_ops.shape(inputs)[0]\n max_seq_len = array_ops.shape(inputs)[1]\n num_tags = array_ops.shape(inputs)[2]\n\n flattened_inputs = array_ops.reshape(inputs, [-1])\n\n offsets = array_ops.expand_dims(\n math_ops.range(batch_size) * max_seq_len * num_tags, 1)\n offsets += array_ops.expand_dims(math_ops.range(max_seq_len) * num_tags, 0)\n flattened_tag_indices = array_ops.reshape(offsets + tag_indices, [-1])\n\n unary_scores = array_ops.reshape(\n array_ops.gather(flattened_inputs, flattened_tag_indices),\n [batch_size, max_seq_len])\n\n masks = _lengths_to_masks(sequence_lengths, array_ops.shape(tag_indices)[1])\n\n unary_scores = math_ops.reduce_sum(unary_scores * masks, 1)\n return unary_scores\n\n\ndef crf_binary_score(tag_indices, sequence_lengths, transition_params):\n \"\"\"Computes the binary scores of tag sequences.\n Args:\n tag_indices: A [batch_size, max_seq_len] matrix of tag indices.\n sequence_lengths: A [batch_size] vector of true sequence lengths.\n transition_params: A [num_tags, num_tags] matrix of binary potentials.\n Returns:\n binary_scores: A [batch_size] vector of binary scores.\n \"\"\"\n # Get shape information.\n num_tags = transition_params.get_shape()[0]\n num_transitions = array_ops.shape(tag_indices)[1] - 1\n\n # Truncate by one on each side of the sequence to get the start and end\n # indices of each transition.\n start_tag_indices = array_ops.slice(tag_indices, [0, 0],\n [-1, num_transitions])\n end_tag_indices = array_ops.slice(tag_indices, [0, 1], [-1, num_transitions])\n\n # Encode the indices in a flattened representation.\n flattened_transition_indices = start_tag_indices * num_tags + end_tag_indices\n flattened_transition_params = array_ops.reshape(transition_params, [-1])\n\n # Get the binary scores based on the flattened representation.\n binary_scores = array_ops.gather(flattened_transition_params,\n flattened_transition_indices)\n\n masks = _lengths_to_masks(sequence_lengths, array_ops.shape(tag_indices)[1])\n truncated_masks = array_ops.slice(masks, [0, 1], [-1, -1])\n binary_scores = math_ops.reduce_sum(binary_scores * truncated_masks, 1)\n return binary_scores\n\n\nclass CrfForwardRnnCell(RNNCell):\n \"\"\"Computes the alpha values in a linear-chain CRF.\n See http://www.cs.columbia.edu/~mcollins/fb.pdf for reference.\n \"\"\"\n\n def __init__(self, transition_params):\n \"\"\"Initialize the CrfForwardRnnCell.\n Args:\n transition_params: A [num_tags, num_tags] matrix of binary potentials.\n This matrix is expanded into a [1, num_tags, num_tags] in preparation\n for the broadcast summation occurring within the cell.\n \"\"\"\n self._transition_params = array_ops.expand_dims(transition_params, 0)\n self._num_tags = transition_params.get_shape()[0].value\n\n @property\n def state_size(self):\n return self._num_tags\n\n @property\n def output_size(self):\n return self._num_tags\n\n def __call__(self, inputs, state, scope=None):\n \"\"\"Build the CrfForwardRnnCell.\n Args:\n inputs: A [batch_size, num_tags] matrix of unary potentials.\n state: A [batch_size, num_tags] matrix containing the previous alpha\n values.\n scope: Unused variable scope of this cell.\n Returns:\n new_alphas, new_alphas: A pair of [batch_size, num_tags] matrices\n values containing the new alpha values.\n \"\"\"\n state = array_ops.expand_dims(state, 2)\n\n # This addition op broadcasts self._transitions_params along the zeroth\n # dimension and state along the second dimension. This performs the\n # multiplication of previous alpha values and the current binary potentials\n # in log space.\n transition_scores = state + self._transition_params\n new_alphas = inputs + reduce_logsumexp(transition_scores, [1])\n\n # Both the state and the output of this RNN cell contain the alphas values.\n # The output value is currently unused and simply satisfies the RNN API.\n # This could be useful in the future if we need to compute marginal\n # probabilities, which would require the accumulated alpha values at every\n # time step.\n return new_alphas, new_alphas\n\n\nclass CrfViterbiRnnCell(RNNCell):\n\n def __init__(self, transition_params):\n \"\"\"Initialize the CrfForwardRnnCell.\n Args:\n transition_params: A [num_tags, num_tags] matrix of binary potentials.\n This matrix is expanded into a [1, num_tags, num_tags] in preparation\n for the broadcast summation occurring within the cell.\n \"\"\"\n self._transition_params = array_ops.expand_dims(transition_params, 0)\n self._num_tags = transition_params.get_shape()[0].value\n\n @property\n def state_size(self):\n return self._num_tags\n\n @property\n def output_size(self):\n return self._num_tags\n\n def __call__(self, inputs, state, scope=None):\n # [B, N, N]\n v = array_ops.expand_dims(state, 1) + self._transition_params\n new_trellis = inputs + tf.reduce_max(v, [1])\n new_backpointer = tf.cast(tf.arg_max(v, 1), tf.float32)\n return new_backpointer, new_trellis\n\n\nclass CrfExtractBackpointerRnnCell(RNNCell):\n\n def __init__(self, num_tags):\n self._num_tags = num_tags\n\n @property\n def state_size(self):\n return 1\n\n @property\n def output_size(self):\n return 1\n\n def __call__(self, backpointer, last_label, scope=None):\n \"\"\"\n :param backpointer: [B, N]\n :param last_label: [B, 1]\n :param scope:\n :return: newlabel\n \"\"\"\n # extract backpointer for this label\n new_label = tf.gather_nd(backpointer, tf.concat(axis=1, values=[tf.expand_dims(tf.range(0, tf.shape(last_label)[0]), 1),\n last_label]))\n new_label = tf.reshape(new_label, [-1, 1])\n return new_label, new_label\n\n\ndef viterbi_decode(score, seq_len, transition_params):\n \"\"\"Decode the highest scoring sequence of tags outside of TensorFlow.\n This should only be used at test time.\n Args:\n score: A [batch_size, seq_len, num_tags] matrix of unary potentials.\n transition_params: A [num_tags, num_tags] matrix of binary potentials.\n Returns:\n viterbi: A [batch_size, max_seq_len] tensor of labels.\n \"\"\"\n num_tags = transition_params.get_shape()[0].value\n seq_len = seq_len - 1\n start_state = tf.squeeze(tf.slice(score, [0, 0, 0], [-1, 1, -1]), [1])\n tail_scores = tf.slice(score, [0, 1, 0], [-1, -1, -1])\n # [B, L-1, N]\n backpointers, final_state = tf.nn.dynamic_rnn(CrfViterbiRnnCell(transition_params), tail_scores,\n initial_state=start_state, sequence_length=seq_len)\n backpointers = tf.cast(backpointers, tf.int32)\n # [B, 1]\n last_label = tf.cast(tf.expand_dims(tf.arg_max(final_state, 1), 1), tf.int32)\n\n rev_backpointers = tf.reverse_sequence(backpointers, seq_len, 1)\n # [B, L-1, 1]\n rev_labels, _ = tf.nn.dynamic_rnn(CrfExtractBackpointerRnnCell(num_tags), rev_backpointers,\n initial_state=last_label, sequence_length=seq_len)\n\n rev_labels = tf.squeeze(rev_labels, [2])\n\n labels = tf.concat(axis=1, values=[tf.reverse_sequence(rev_labels, seq_len, 1), last_label])\n\n return labels\n","sub_path":"biomedical_qa/models/crf.py","file_name":"crf.py","file_ext":"py","file_size_in_byte":16611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"489772709","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n# from torchvision import datasets, transforms\n# from torch.autograd import Variable\n# import torch.onnx as torch_onnx\n# import torch\n# from classification import *\n#\n# from torch.autograd import Variable\n# from torch.utils.data import DataLoader\n# from classification.dataset.dataloader import *\n# from classification.models.model import *\n# from utils import *\n# from classification.dataset.augmentations import get_test_transform\n# import cv2\n# import warnings\n# from classification import *\nfrom classification.models import load_inference_model_classification\n# import onnx\nimport mxnet as mx\nfrom mxnet.contrib import onnx as onnx_mxnet\n# import numpy as np\n\n\nclass torch_config:\n class singlecore:\n root = '/home/imdl/workspace/pytorch-image-classification/checkpoints/best_model-'\n model_path = root + \"single-core/resnet18/200/model_best-201904_07.pth.tar\"\n model = load_inference_model_classification(model_path)\n input_size = (3, 200, 200)\n class multicore:\n root = '/home/imdl/workspace/pytorch-image-classification/checkpoints/best_model-'\n model_path = root + \"multicore/resnet18/500/model_best-201904_07.pth.tar\"\n model = load_inference_model_classification(model_path)\n input_size = (3, 500, 500)\n\n\n\ndef load_net_params_mxnet(net, params_path):\n # Import the ONNX model into MXNet's symbolic interface\n sym, arg_params, aux_params = onnx_mxnet.import_model(params_path)\n print(\"Loaded torch_model.onnx!\")\n net_params = net.collect_params()\n ctx = mx.gpu(0)\n for param in aux_params:\n temp = param\n param = 'resnetv10_' + param.replace('.', '_').replace('bias', 'beta').replace('bn', 'batchnorm') # .replace()\n if 'batchnorm' in param:\n param = param.replace('batchnorm' + param.split('batchnorm')[1][0],\n 'batchnorm' + str(int(param.split('batchnorm')[1][0]) - 1))\n if 'layer' in param:\n param = param.replace('layer', 'stage')\n i, j = map(int, param.split('stage')[1].split('_')[:2])\n if i < 2 and j == 1: t = 2\n if i >= 2 and j == 1: t = 3\n if j == 1:\n if 'batchnorm' in param:\n param = param.replace('batchnorm' + param.split('batchnorm')[1][0],\n 'batchnorm' + str(int(param.split('batchnorm')[1][0]) + t))\n if 'downsample_1' in param:\n param = param.replace('downsample_1', 'batchnorm2')\n param = '_'.join(param.split('_%d_' % j))\n net_params[param]._load_init(aux_params[temp], ctx=ctx)\n for param in arg_params:\n temp = param\n param = 'resnetv10_' + param.replace('.', '_').replace('bias', 'beta').replace('bn', 'batchnorm')#.replace()\n if 'conv' in param:\n param = param.replace('conv' + param.split('conv')[1][0], 'conv' + str(int(param.split('conv')[1][0])-1))\n if 'batchnorm' in param:\n param = param.replace('batchnorm' + param.split('batchnorm')[1][0], 'batchnorm' + str(int(param.split('batchnorm')[1][0]) - 1))\n param = param.replace('weight', 'gamma')\n if 'layer' in param:\n param = param.replace('layer', 'stage')\n i, j = map(int, param.split('stage')[1].split('_')[:2])\n if i < 2 and j == 1: t = 2\n if i >= 2 and j == 1: t = 3\n if j == 1:\n if 'conv' in param:\n param = param.replace('conv' + param.split('conv')[1][0], 'conv' + str(int(param.split('conv')[1][0]) + t))\n if 'batchnorm' in param:\n param = param.replace('batchnorm' + param.split('batchnorm')[1][0],\n 'batchnorm' + str(int(param.split('batchnorm')[1][0]) + t))\n param = param.replace('weight', 'gamma')\n if 'downsample' in param:\n if 'downsample_0' in param: param = param.replace('downsample_0', 'conv2')\n if 'downsample_1' in param:\n if 'weight' in param: param = param.replace('downsample_1_weight', 'batchnorm2_gamma')\n if 'beta' in param: param = param.replace('downsample_1_beta', 'batchnorm2_beta')\n param = '_'.join(param.split('_%d_' % j))\n if 'fc' in param:\n param = param.replace('fc_weight', 'dense0_weight').replace('fc_beta', 'dense0_bias')\n net_params[param]._load_init(arg_params[temp], ctx=ctx)\n net.hybridize()\n return net\n\n\n\n\n\n","sub_path":"classification/torch_to_mxnet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"582926309","text":"#\n# @lc app=leetcode.cn id=78 lang=python3\n#\n# [78] 子集\n#\n\n# @lc code=start\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n # iteration\n ans = [[]]\n for n in nums:\n new_ans = []\n for i in ans:\n new_ans.append(i + [n])\n ans.extend(new_ans)\n return ans\n\n # # recursion\n # ans, n, tmp = [], len(nums), []\n # def recursion(i):\n # if i == n:\n # # 一定要注意,如果使用外部的变量tmp,这里必须要deep copy!!!\n # # 选择在 recursion 外面定义tmp,是为了节省内存\n # ans.append([m for m in tmp])\n # return\n # recursion(i+1)\n # tmp.append(nums[i])\n # recursion(i+1)\n # tmp.pop()\n # recursion(0)\n # return ans\n\n\n# @lc code=end\n\n","sub_path":"Week_03/78_子集.py","file_name":"78_子集.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"608134244","text":"\n#cuts = {}\n# Aliases in supercut doesnt seem to work!\n\nsupercut = 'mll>12 \\\n && Lepton_pt[0]>25 && Lepton_pt[1]>10 \\\n && (nLepton>=2 && Alt$(Lepton_pt[2],0)<10) \\\n && (abs(Lepton_pdgId[1]) == 13 || Lepton_pt[1]>13) \\\n && (Lepton_pdgId[0] * Lepton_pdgId[1] == -11*13) \\\n && ptll > 30 \\\n && PuppiMET_pt > 20 \\\n && hm > 0 \\\n '\n\n# && CleanJet_pt[0]>=30 && CleanJet_pt[1]>=30 \\\n# && abs(CleanJet_eta[0])<4.7 && abs(CleanJet_eta[1])<4.7 \\\n# && (abs((Lepton_eta[0] - (CleanJet_eta[0]+CleanJet_eta[1])/2)/detajj) < 0.5) \\\n# && (abs((Lepton_eta[1] - (CleanJet_eta[0]+CleanJet_eta[1])/2)/detajj) < 0.5) \\'\n# selection 'bVeto && (mth>=60 && mth<125) && (njet==2) && (detajj>3.5 && mjj>400) && lepcen1<0.5 && lepcen2<0.5' \n# control regions top 'mll>50 && (njet==2) && (detajj>3.5 && mjj>400) && bReq'\n# control regions dy '(mth<60) && mll>40 && mll<80 && (njet==2) && (detajj>3.5 && mjj>400) && bVeto' \n# cuts['hww2l2v_13TeV_SR'] = 'bVeto && (mth>=60 && mth<125) && (njet==2) && (detajj>3.5 && mjj>400) && lepcen1<0.5 && lepcen2<0.5'\n\n#cuts['hww2l2v_13TeV_Sel'] = 'bVeto && CleanJet_pt[0]>=30 && CleanJet_pt[1]>=30 && abs(CleanJet_eta[0])<4.7 && abs(CleanJet_eta[1])<4.7 && CleanJet_pt[2]<30'\n\n#cuts['hww2l2v_13TeV_BSel'] = 'bVeto && CleanFatJet_pt[0]>=200 && abs(CleanFatJet_eta[0])<2.4'\n\ncuts['hww2l2v_13TeV_SRVBF'] = 'bVeto && CleanJet_pt[0]>=30 && CleanJet_pt[1]>=30 && abs(CleanJet_eta[0])<4.7 && abs(CleanJet_eta[1])<4.7 && CleanJet_pt[2]<30 \\\n && nCleanFatJet==0 \\\n && kd_vbf>0.8 \\\n && mjj>200 \\\n && (mth>=30 && mth<125)'\n\ncuts['hww2l2v_13TeV_SRVH'] = 'bVeto && CleanJet_pt[0]>=30 && CleanJet_pt[1]>=30 && abs(CleanJet_eta[0])<2.4 && abs(CleanJet_eta[1])<2.4 && CleanJet_pt[2]<30 \\\n && nCleanFatJet==0 \\\n && kd_vh>0.8 \\\n && (mjj>60 && mjj<120) \\\n && (mth>=30 && mth<125)'\n\ncuts['hww2l2v_13TeV_SRBVH'] = 'bVeto && CleanFatJet_pt[0]>=200 && abs(CleanFatJet_eta[0])<2.4 \\\n && (mV[0]>70 && mV[0]<110) \\\n && (mth>=30 && mth<125)'\n\n#cuts['hww2l2v_13TeV_SRHJJ'] = 'bVeto && CleanJet_pt[0]>=30 && CleanJet_pt[1]>=30 && abs(CleanJet_eta[0])<4.7 && abs(CleanJet_eta[1])<4.7 && CleanJet_pt[2]<30 \\\n# && mjj>200 \\\n# && (mth>=30 && mth<125)'\n \n\n","sub_path":"Configurations/Off_shell/EFT/VBF/Test2016/cuts.py","file_name":"cuts.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"418595969","text":"#!/usr/bin/env python35\n# coding:utf-8\n\n'''\nCreate by Liush at 2017/02/16\n'''\n\nfrom threading import Event\nfrom threading import Thread\nimport time\n\ndef Producer():\n print(\"Chef:Waiting for somebody to buy baozi\")\n event.wait()\n event.clear()\n print(\"Chef is making baozi....\")\n time.sleep(3)\n\n print(\"Chef:baozi has be ready..\")\n event.set()\n\n\ndef Consumer():\n print(\"Liush coming for buy baozi.\")\n event.set()\n time.sleep(2)\n\n while True:\n if event.isSet():\n print(\"Liush:baozi are very delicious.Thanks!!\")\n break\n else:\n print(\"Liush is waiting for baozi......\")\n time.sleep(1)\n\nevent = Event()\n\nP = Thread(target=Producer)\nP.start()\nC = Thread(target=Consumer)\nC.start()\n\n\n","sub_path":"module/Threading/threading_event.py","file_name":"threading_event.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"325808973","text":"class Solution:\n def multiply(self, num1, num2):\n \"\"\"\n :type num1: str\n :type num2: str\n :rtype: str\n \"\"\"\n output = [0 for _ in range(len(num1)+len(num2))]\n\n for i in range(0, len(num2)):\n index2 = len(num2)-1-i\n for j in range(0, len(num1)):\n index1 = len(num1)-1-j\n product = (ord(num1[index1]) - ord('0')) * (ord(num2[index2]) - ord('0'))\n\n output[len(output)-1-i-j] += product % 10\n output[len(output)-1-i-j-1] += int(product/10)\n\n output_string = \"\"\n carry = 0\n for i in range(0, len(output)):\n output[len(output)-1-i] += carry\n output_string = str(output[len(output)-1-i] % 10) + output_string\n carry = int(output[len(output)-1-i]/10)\n\n all_zero = True\n for i in range(0, len(output_string)):\n if output_string[i] != '0':\n all_zero = False\n break\n\n if all_zero == False: return output_string[i:]\n else: return '0'\n","sub_path":"Codes/43_Multiply_Strings/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"596436033","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 6 19:51:46 2019\n\n@author: Stefan Draghici\n\"\"\"\n\nprint('hello\\n'*3)\n\nnumbers=[int(x) for x in input('enter three numbers:').split()]\ns=0\nfor n in numbers:\n s+=n\nprint(s)","sub_path":"input/input output.py","file_name":"input output.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"240840667","text":"# -*- coding: utf-8 -*-\n\"\"\"\nXMLSERVICE direct call (current job)\n\nLicense: \n BSD (LICENSE)\n -- or --\n http://yips.idevcloud.com/wiki/index.php/XMLService/LicenseXMLService\n\nImport:\n from itoolkit import *\n from itoolkit.lib.ilibcall import *\n itransport = iLibCall()\n\nNote:\n XMLSERVICE library search order:\n 1) environment variable 'XMLSERVICE' (export XMLSERVICE=QXMLSERV)\n 2) QXMLSERV -- IBM PTF library (DG1 PTFs)\n 3) XMLSERVICE -- download library (crtxml)\n\"\"\"\nimport sys\nimport os\nimport re\nimport urllib\nif sys.version_info >= (3,0):\n \"\"\"\n urllib has been split up in Python 3. \n The urllib.urlencode() function is now urllib.parse.urlencode(), \n and the urllib.urlopen() function is now urllib.request.urlopen().\n \"\"\"\n import urllib.request\n import urllib.parse\nimport xml.dom.minidom\n# import inspect\ntry:\n import itoolkit.itoollib\nexcept ImportError:\n pass\n\nclass iLibCall(object):\n \"\"\"\n Transport XMLSERVICE direct job call (within job/process calls).\n\n Args:\n ictl (str): optional - XMLSERVICE control ['*here','*sbmjob'] \n ipc (str): optional - XMLSERVICE xToolkit job route for *sbmjob ['/tmp/myunique42'] \n iccsid (int): optional - XMLSERVICE EBCDIC CCSID [0,37,...] 0 = default jobccsid (1.2+)\n pccsid (int): optional - XMLSERVICE ASCII CCSID [0,1208, ...] 0 = default 1208 (1.2+)\n\n Returns:\n none\n \"\"\"\n def __init__(self, ictl=0, ipc=0, iccsid=0, pccsid=0):\n if ictl == 0:\n self.ctl = '*here *cdata'\n else:\n self.ctl = ictl\n if ipc == 0:\n self.ipc = '*na'\n else:\n self.ipc = ipc\n self.ebcdic_ccsid = iccsid\n self.pase_ccsid = pccsid\n\n def trace_data(self):\n \"\"\"Return trace driver data.\n\n Args:\n none\n\n Returns:\n initialization data\n \"\"\"\n data = \"\"\n data += \" ctl (\" + str(self.ctl) + \")\"\n data += \" ipc (\" + str(self.ipc) + \")\"\n data += \" ebcdic_ccsid (\" + str(self.ebcdic_ccsid) + \")\"\n data += \" pase_ccsid (\" + str(self.pase_ccsid) + \")\"\n return data\n\n def call(self, itool):\n \"\"\"Call xmlservice with accumulated input XML.\n\n Args:\n itool - iToolkit object\n\n Returns:\n xml\n \"\"\"\n return itoolkit.itoollib.xmlservice(itool.xml_in(),self.ctl,self.ipc,self.ebcdic_ccsid,self.pase_ccsid)\n\n","sub_path":"itoolkit/lib/ilibcall.py","file_name":"ilibcall.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"138434170","text":"#!/usr/bin/env nix-shell\n#!nix-shell -p nix -p python3 -p git -i python\n# USAGE - just run the script: ./update.py\n# When editing this file, make also sure it passes the mypy typecheck\n# and is formatted with yapf.\nimport urllib.request\nimport json\nimport tempfile\nimport subprocess\nimport fileinput\nimport re\nfrom pathlib import Path\n\n\ndef sh(*args: str) -> str:\n out = subprocess.check_output(list(args))\n return out.strip().decode(\"utf-8\")\n\n\ndef prefetch_github(owner: str, repo: str, ref: str) -> str:\n return sh(\"nix-prefetch-url\", \"--unpack\",\n f\"https://github.com/{owner}/{repo}/archive/{ref}.tar.gz\")\n\n\ndef main() -> None:\n url = \"https://api.github.com/repos/radare/radare2/releases/latest\"\n with urllib.request.urlopen(url) as response:\n release = json.load(response) # type: ignore\n version = release[\"tag_name\"]\n with tempfile.TemporaryDirectory() as dirname:\n\n def git(*args: str) -> str:\n return sh(\"git\", \"-C\", dirname, *args)\n\n git(\"clone\", \"--branch\", version, \"https://github.com/radare/radare2\",\n \".\")\n sha256 = prefetch_github(\"radare\", \"radare2\", version)\n nix_file = str(Path(__file__).parent.joinpath(\"default.nix\"))\n\n cs_tip = None\n with open(Path(dirname).joinpath(\"shlr\", \"Makefile\")) as makefile:\n for l in makefile:\n match = re.match(\"CS_TIP=(\\S+)\", l)\n if match:\n cs_tip = match.group(1)\n assert cs_tip is not None\n\n cs_sha256 = prefetch_github(\"aquynh\", \"capstone\", cs_tip)\n\n in_block = False\n with fileinput.FileInput(nix_file, inplace=True) as f:\n for l in f:\n if \"#\" in l:\n in_block = True\n print(f\"\"\" #\n # DO NOT EDIT! Automatically generated by ./update.py\n version_commit = \"{git(\"rev-list\", \"--all\", \"--count\")}\";\n gittap = \"{git(\"describe\", \"--tags\", \"--match\", \"[0-9]*\")}\";\n gittip = \"{git(\"rev-parse\", \"HEAD\")}\";\n version = \"{version}\";\n sha256 = \"{sha256}\";\n cs_tip = \"{cs_tip}\";\n cs_sha256 = \"{cs_sha256}\";\n #\"\"\")\n elif \"#\" in l:\n in_block = False\n elif not in_block:\n print(l, end=\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pkgs/development/tools/analysis/radare2/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"106755258","text":"from pypureclient.flashblade import (SmbClientPolicy, SmbClientPolicyRule)\n\n# Create a client policy with a rule which allows Read (but no other) permissions for everyone.\npolicyname = 'client_policy_1'\npolicy = SmbClientPolicy()\npolicy.rules = [\n SmbClientPolicyRule(client='*', permission='ro')\n]\nres = client.post_smb_client_policies(names=[policyname], policy=policy)\nprint(res)\nif type(res) == pypureclient.responses.ValidResponse:\n print(list(res.items))","sub_path":"docs/source/examples/FB2.10/post_smb_client_policies.py","file_name":"post_smb_client_policies.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"180048929","text":"import os\nimport sys\nsys.path.insert(0, os.path.abspath('..'))\n\nimport dataSelection as ds\nimport loadAndSave as sl\n\ndef test_sense_selection_is_random_not_dominant():\n\toxfordData = sl.loadDataFromFile('../dictionaryData/oxfordExtra')\n\toxfordNoun = ds.selectPoS(oxfordData, 'Noun')\n\toxfordNoun4SenseMin = ds.removeWordsWithTooFewSenses(oxfordNoun, 4, 4)\n\ttotalBaseProb = 0\n\ttotalSelected = 0\n\tfor i in range(100):\t\n\t\tdominantSense = {}\n\t\tfor key in oxfordNoun4SenseMin:\n\t\t\tvalues = oxfordNoun4SenseMin[key]\n\t\t\tvalues = sorted(values, key=lambda x:len(x['examples']), reverse=True)\n\t\t\tdominantSense[key] = {'def':values[0]['def'], 'numSense':len(values)}\n\t\toxfordSelected = ds.selectExamplesAndSenses(oxfordNoun4SenseMin, 4, 2)\n\t\tselectedCount = 0\n\t\tbaseProbability = 0\n\t\tcount = 0\n\t\tfor key in oxfordSelected:\n\t\t\tif oxfordSelected[key][0]['def'] == dominantSense[key]['def']:\n\t\t\t\tselectedCount += 1\n\t\t\tbaseProbability += 1/float(dominantSense[key]['numSense'])\n\t\t\tcount += 1\n\t\ttotalSelected += selectedCount/float(count)\n\t\ttotalBaseProb += baseProbability/count\n\tprint('Number of times dominant sense selected: {}'.format(totalSelected/100))\n\tprint('Probability of dominant sense being selected: {}'.format(totalBaseProb/100))\t\n\t\t\t\t\t \n\ntest_sense_selection_is_random_not_dominant()\t\t","sub_path":"tests/testForRandomSelection.py","file_name":"testForRandomSelection.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"622503425","text":"# 输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。 \n# \n# 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 \n# \n# \n# \n# 示例 1: \n# \n# \n# Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\n# Output: [3,9,20,null,null,15,7]\n# \n# \n# 示例 2: \n# \n# \n# Input: preorder = [-1], inorder = [-1]\n# Output: [-1]\n# \n# \n# \n# \n# 限制: \n# \n# 0 <= 节点个数 <= 5000 \n# \n# \n# \n# 注意:本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-\n# preorder-and-inorder-traversal/ \n# Related Topics 树 数组 哈希表 分治 二叉树 \n# 👍 531 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n def recur(root,left,right):\n if left>right:return\n node = TreeNode(preorder[root])\n i = dic[preorder[root]]\n node.left = recur(root+1,left,i-1)\n node.right = recur(i-left+root+1,i+1,right)\n return node\n dic= {}\n for i in range(len(inorder)):\n dic[inorder[i]] = i\n return recur(0,0,len(inorder)-1)\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"week2/剑指offer7 重建二叉树.py","file_name":"剑指offer7 重建二叉树.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"556713108","text":"from psychopy import core, visual, event\nimport pandas as pd\n\n# Following tutorial found: https://www.socsci.ru.nl/wilberth/nocms/psychopy/print.php\n\ndef flip_some_frames(window,frames=500):\n for frame_num in range(frames):\n if frame_num % 20 == 0:\n update_message = visual.TextStim(\n window, text=f\"{frame_num} frames have elapsed\")\n update_message.draw()\n window.flip()\n\ndef main():\n\n \n\n # Create a window\n win = visual.Window([400,300], monitor=\"testMonitor\")\n\n # Set up a global shutdown key\n event.globalKeys.add(key='q', func = core.quit)\n \n # Create a stimulus for a certain window\n message = visual.TextStim(win, text=\"Time to start!\")\n\n # Draw the stimulus to the window\n message.draw()\n\n # Flip backside of the window\n win.flip()\n\n # Pause3 sec\n core.wait(3.0)\n\n # Present a new stimulus for 500 frames, changing the stimulus\n # every 20 frames\n flip_some_frames(win, 500000) \n\n #Present a final message, notifying the end of the 500 frames\n final_message = visual.TextStim(\n win, text=\"Finished! Closing shortly\")\n final_message.draw()\n win.flip()\n\n # Wait again to appreciate\n core.wait(3.0)\n\n # Close the window\n win.close()\n\n # Close PsychoPy\n core.quit()\n\nmain()\n","sub_path":"simple_timing_and_response_record.py","file_name":"simple_timing_and_response_record.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"507178472","text":"from flask import Flask, render_template, jsonify, request\nimport paypalrestsdk\nimport json\nfrom urllib.parse import unquote\n# from werkzeug.datastructures import ImmutableMultiDict\n\napp = Flask(__name__)\n\npaypalrestsdk.configure({\n \"mode\": \"sandbox\", # sandbox or live\n \"client_id\": \"AdYNpArZeEoIQS7QUQk4BfO5HbY3I5ppd7ttEK1aimWGDIdywW1CWWBZ_1tR5JEm4vg5UMpP9lkaKPVK\",\n \"client_secret\": \"EFk8M9WgnCn5OBJaGiqEskzGcPZaUiqmP8-zKyHx7PGxdvZyze4FuHKg2jjCPJBp2MzSvUiOjc8BqmqX\" })\n\n@app.route('/checkout', methods=['GET', 'POST'])\ndef index():\n # data=request.args\n url = request.url\n cut_index=url.find('?')\n url = url[cut_index+1:]\n data = unquote(unquote(url))\n parsed = json.loads(data+\"\\\"}\")\n # return parsed\n # return json.dumps(parsed, indent=4)\n # return parsed\n return render_template('index.html', data=parsed)\n\n@app.route('/payment', methods=['POST'])\ndef payment():\n # order_data = request.form.to_dict()\n orderItems = json.loads(request.form['orderitems'])\n price = request.form['price']\n # print(orderItems[1])\n orderItemsList = []\n for i in range(len(orderItems)):\n orderItemsDict = {\n \"sku\" : orderItems[i]['sku'],\n \"name\" : orderItems[i]['foodName'],\n \"price\" : orderItems[i]['price'],\n \"currency\" : \"SGD\", \n \"quantity\" : orderItems[i]['quantity']\n }\n orderItemsList.append(orderItemsDict)\n orderItemsDict = {}\n \n # order_data = ImmutableMultiDict(order_data)\n # order_data.to_dict()\n # print(order_data['orderItems'])\n print(str(orderItemsList))\n print(str(price)+'.00')\n payment = paypalrestsdk.Payment({\n \"intent\": \"sale\",\n \"payer\": {\n \"payment_method\": \"paypal\"},\n \"redirect_urls\": {\n \"return_url\": \"http://localhost:3000/payment/execute\",\n \"cancel_url\": \"http://localhost:3000/\"},\n \"transactions\": [{ \n \"item_list\": {\n \"items\": orderItemsList},\n \"amount\": { \n \"total\": str(price),\n \"currency\": \"SGD\"},\n \"description\": \"This is the payment transaction description.\"}]})\n\n if payment.create():\n print('Payment success!')\n else:\n print(payment.error)\n\n return jsonify({'paymentID' : payment.id})\n\n@app.route('/execute', methods=['POST'])\ndef execute():\n success = False\n payment = paypalrestsdk.Payment.find(request.form['paymentID'])\n\n if payment.execute({'payer_id' : request.form['payerID']}):\n print('Execute success!')\n success = True\n else:\n print(payment.error)\n\n return jsonify({'success' : success})\n\nif __name__ == '__main__':\n app.run(port=7000, host='0.0.0.0', debug=True)\n\n\n # payment = paypalrestsdk.Payment({\n # \"intent\": \"sale\",\n # \"payer\": {\n # \"payment_method\": \"paypal\"},\n # \"redirect_urls\": {\n # \"return_url\": \"http://localhost:3000/payment/execute\",\n # \"cancel_url\": \"http://localhost:3000/\"},\n # \"transactions\": [{ # TODO: need to input item list: get from BODY\n # \"item_list\": {\n # \"items\": [{\n # \"sku\": \"F01\",\n # \"name\": \"Bola Obi\",\n # \"price\": \"10.00\",\n # \"currency\": \"SGD\",\n # \"quantity\": 1}]},\n # \"amount\": { # TODO: need to input Total Amount\n # \"total\": \"10.00\",\n # \"currency\": \"SGD\"},\n # \"description\": \"This is the payment transaction description.\"}]}) # TODO: need to input decription\n","sub_path":"Docker/paypal_app/paypal_app.py","file_name":"paypal_app.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"163744415","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\n\r\n\r\n\r\n\"\"\"\r\nPlannar Quadrotor ocntrol\r\n\r\nauthors: Jean-Bernard Uwineza & Zhao Hangquan\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom util import *\r\nfrom model.quadrotor import Quadrotor\r\n\r\nfrom utils import controller\r\nfrom utils.quadPlot import plot_quad_3d\r\n# TODO: Use user inputs to select either 2D or 3D case.\r\n# TODO: Ask user to input initial and final poses for the quad\r\n# TODO: Use pen to draw the trajectory of the drone\r\n\r\ncontroller = Controller()\r\n\r\n\r\n###this is for 3-dimension\r\n\r\n\r\n\r\n####\r\n\r\n\r\n\r\n\r\ndef partA():\r\n ##function\r\n ###\r\n def D2_init():\r\n ax.set_xlim(0, 10)\r\n ax.set_ylim(0, 10)\r\n return ln,\r\n\r\n def D2_update(i):\r\n xdata.append(X_2d[0, i])\r\n ydata.append(X_2d[1, i])\r\n ln.set_data(xdata, ydata)\r\n print('the position:({0:.3f},{1:0.3f})'.format(X_2d[0, i], X_2d[1, i]))\r\n print('the pitch:{0:.3f}'.format(X_2d[2, i]))\r\n\r\n return ln,\r\n ##\r\n fig, ax = plt.subplots()\r\n xdata, ydata, zdata = [], [], []\r\n\r\n ln, = ax.plot([], [], 'ro', animated=False)\r\n X_2d = []\r\n frames = []\r\n\r\n \"\"\" For Part A\"\"\"\r\n ###my code:\r\n pos = (0, 0, 0)\r\n attitude = (0, 0, 0)\r\n drone = Quadrotor(pos, attitude)\r\n ###\r\n # 2D initial positions\r\n ##zhq:\r\n\r\n arr = input(\"q0_2d:\") ##输入一个一维数组,每个数之间使空格隔开\r\n q0_2d = [[int(n)] for n in arr.split()] ##将输入每个数以空格键隔开做成数组##\r\n q0_2d = np.array(q0_2d)\r\n\r\n arr = input(\"qh_2d:\") ##输入一个一维数组,每个数之间使空格隔开\r\n qh_2d = [[int(n)] for n in arr.split()] ##将输入每个数以空格键隔开做成数组##\r\n qh_2d = np.array(qh_2d)\r\n\r\n zt_2d = eval(input('Enter the initial height(in meters):'))\r\n\r\n T_2d = eval(input('Enter the time:'))\r\n\r\n\r\n X_2d, dt = controller.control_2d(q0_2d, qh_2d, zt_2d,\r\n T_2d) ## enter into the parameter## and return back all the possible data\r\n t_2d = np.linspace(0, dt * X_2d.shape[1], X_2d.shape[1]) ##shape[1] return back column\r\n\r\n\r\n Y_2d=X_2d[0, :]\r\n Z_2d=X_2d[1, :]\r\n n=Y_2d.shape\r\n n=n[0]\r\n n=n-1\r\n frames=n\r\n\r\n ani = FuncAnimation(fig, D2_update, frames=n,interval=5,repeat=False,\r\n init_func=D2_init, blit=True)\r\n plt.xlabel('Y-position')\r\n plt.ylabel('Z-position')\r\n plt.title('The path of the Quadrotor in 2D')\r\n plt.show()\r\n\r\ndef partB():\r\n \"\"\" For part B\"\"\"\r\n\r\n\r\n fig3 = plt.figure(3)\r\n ax_3d = Axes3D(fig3)\r\n X_3d = []\r\n ln_3d = ax_3d.scatter([], [], [], 'ro', animated=False)\r\n\r\n arr = input(\"q0_3d:\")\r\n q0_3d = [[int(n)] for n in arr.split()]\r\n q0_3d = np.array(q0_3d)\r\n\r\n arr = input(\"qh_3d:\")\r\n qh_3d = [[int(n)] for n in arr.split()]\r\n qh_3d = np.array(qh_3d)\r\n\r\n zt_3d = eval(input('Enter the initial height(in meters):'))\r\n\r\n T_3d = eval(input('Enter the time:'))\r\n\r\n\r\n #\r\n X_3d, dt = controller.control_3d(q0_3d, qh_3d, zt_3d, T_3d)\r\n t_3d = np.linspace(0, dt*X_3d.shape[1], X_3d.shape[1])\r\n\r\n\r\n\r\n a=X_3d[0, :]\r\n a=a.shape\r\n n=a[0]\r\n ax_3d.set_xlim3d(0,10)\r\n ax_3d.set_ylim3d(0, 10)\r\n ax_3d.set_zlim3d(0, 10)\r\n plt.ion()\r\n plt.title('The path of the Quadrotor in 3D')\r\n ax_3d.set_xlabel('X-axis')\r\n ax_3d.set_ylabel('Y-axis')\r\n ax_3d.set_zlabel('Z-axis')\r\n for i in range(0,n):\r\n ax_3d.scatter(X_3d[0, i*5], X_3d[1, i*5], X_3d[2, i*5], c='r',marker=\".\")\r\n print('the position:({0:.3f},{1:0.3f},{2:.3f})'.format(X_3d[0, i*5], X_3d[1, i*5],X_3d[2, i*5]))\r\n print('the angle(Pitch, Roll, Yaw):({0:.3f},{1:0.3f},{2:.3f})'.format(X_3d[3, i*5], X_3d[4, i*5],X_3d[5, i*5]))\r\n\r\n plt.pause(0.01)\r\n if 5*i>(n-5):\r\n break\r\n #ani = FuncAnimation(fig3, D3_update, frames=n,interval=5,\r\n # init_func=D3_init, blit=True)\r\n # ax.scatter(X_3d[0, :], X_3d[1, :], X_3d[2, :])\r\n\r\n #\r\n #\r\n #\r\n # labels_3d = ['X-position', 'Y-position', 'Z-position', 'Pitch', 'Roll', 'Yaw',\r\n # 'X-velocity', 'Y-velovity', 'Z-velocity', 'Pitch-dot', 'Yaw-dot', 'Roll-dot']\r\n #\r\n # fig4 = plt.figure(4)\r\n # for i in range(len(X_3d)):\r\n # plt.subplot(4, 3, i + 1)\r\n # plt.plot(t_3d, X_3d[i, :])\r\n # plt.xlabel('Time')\r\n # plt.ylabel(labels_3d[i])\r\n\r\n plt.show()\r\n\r\n\r\n\r\ndef main():\r\n choice=eval(input(\"choice: 2-dimension: 1 ;3-dimension : 2:\"))\r\n if choice ==1:\r\n partA()\r\n\r\n if choice ==2:\r\n partB()\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain()\r\n\r\n","sub_path":"phase1/try3.py","file_name":"try3.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"606434640","text":"import sqlite3\n\n# connect to database 'new.db' if exists; if not - create it\nconn = sqlite3.connect(\"new.db\")\n\n# create cursor object\ncursor = conn.cursor()\n\n# create 'population' table\n\ncursor.execute(\"\"\"\n CREATE TABLE population\n (city TEXT, state TEXT, population INT)\n \"\"\")\n\ncursor.execute(\"\"\"\n\t\t\t\tINSERT INTO population\n\t\t\t\tVALUES('New York City','NY',8200000)\n\t\t\t\t\"\"\")\n\t\t\t\t\ncursor.execute(\"\"\"\n\t\t\t\tINSERT INTO population\n\t\t\t\tVALUES('San Francisco','CA',800000);\n\t\t\t\t\"\"\")\n\nconn.commit()\n\t\t\t\t\n# close connection\nconn.close()\n\n\n","sub_path":"sqla.py","file_name":"sqla.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"20715372","text":"# Collection of gowork endpoint names for use in URLs\nADD_USER = 'adduser'\nDELETE_USER = 'deleteuser'\nEDIT_USER = 'edituser'\nGET_USER = 'getuser'\nLOGIN_USER = 'loginuser'\nLOGOUT_USER = 'logout'\n\nADD_USERGROUP = 'addusergroup'\nDELETE_USERGROUP = 'deleteusergroup'\nGET_USERGROUP = 'getusergroup'\n\nADD_JOB = 'addjob'\nDELETE_JOB = 'deletejob'\nEDIT_JOB = 'editjob'\nGET_JOB = 'getjob'\nRUN_JOB = 'runjob'\n\nADD_SIGNAL = 'addsignal'\nDELETE_SIGNAL = 'deletesignal'\nGET_SIGNAL = 'getsignal'\n\nGET_JOB_RUN_HISTORY = 'getjobrunhistory'\n\nHEARTBEAT = 'heartbeat'\n","sub_path":"integration_tests/common/Endpoints.py","file_name":"Endpoints.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"521537256","text":"from DAL.IO.IO import *\nfrom DAL.DataBase.DBInterface import *\nfrom Setting.Config import *\nfrom Kit.Kit import *\nfrom LIB.ClusterLIB.Kit.Kit import *\nimport os\n\ndef load(data=None,PD=False,feature=None,load_type=None,target=None,instance=None):\n \"\"\"\n 从外部导入数据到内存\n :param data: 如果该值不为空则直接作为数据,不再从外部导入\n :param PD: 是否借助Pandas操作数据\n :param feature: 已经选择好的特征规则\n :param load_type: 载入类型(数据库/文件/网络)\n :param target: 载入目标(如果载入类型为数据库,则目标为表名,依此类推)\n :param instance: 业务实例,参看conf.cfg中的'instance'条目\n :return:\n \"\"\"\n if data is not None:\n fn = getFeatureLength(data)\n title = ['feature_' + str(i) for i in range(fn)]\n data = pd.DataFrame(data)\n data.columns = title\n return data, title, None\n\n conf = getConfig()\n assert load_type in ['Direct','DataBase','FileSystem','Memory'],'Data loader type invalid!'\n if load_type == 'NetWork':\n pass\n\n\n if load_type == 'DataBase':\n addr = conf['io']['db']['target']['ip']\n port = conf['io']['db']['target']['port']\n user = conf['io']['db']['target']['user']\n pwd = conf['io']['db']['target']['password']\n db = conf['io']['db']['target']['database']\n db_type = conf['io']['db']['target']['db_type']\n dout = DBInterface()\n dout.init(addr,int(port),user,pwd,db,db_type.lower())\n tlb = target\n selected_feature = feature['selected_feature'] if isinstance(feature,(dict)) and 'selected_feature' in feature and isinstance(feature['selected_feature'],(list)) else None\n body = '*' if selected_feature is None else ','.join(selected_feature)\n X = dout.ExecQuery(sql=\"SELECT \"+body+\" FROM \" + tlb,PD=PD)\n sql_title = 'select COLUMN_NAME from information_schema.columns where table_name=\\''+tlb+'\\''\n title = dout.ExecQuery(sql=sql_title,PD=False)\n for i in range(len(title)):\n title[i] = title[i][0]\n if isinstance(X,(pd.DataFrame)):\n y = X\n else:\n y = pd.DataFrame(X)\n del X\n y.columns=title\n ID = y['ID'].copy()\n del y['ID']\n del y['CREATE_TIME']\n del y['IS_DELETE']\n if isinstance(feature,(dict)) and 'operation' in feature and 'value' in feature:\n assert feature['operation'] in ['KEEP','KICK'],\"Feature operation must be in {\" + ','.join(['KEEP','KICK']) + \"}\"\n if feature['operation'] == 'KEEP':\n to_del = []\n for t in title:\n if t not in feature['value']:\n to_del.append(t)\n if feature['operation'] == 'KICK':\n to_del = feature['value']\n for k in to_del:\n del y[k]\n X = y\n dout.Close()\n title = list(X.head(n=0))\n return X,title,ID\n if load_type == 'FileSystem':\n fs = conf['io']['filesystem']\n if fs['type'] == 'txt':\n X = load_txt(findPath(os.getcwd(),target,fs['prefix']))\n if fs['type'] == 'csv':\n X = import_csv(fs['root']+'/data/'+instance['name']+'/'+target+'.csv')\n ID = None if 'ID' not in X else X['ID']\n fn = getFeatureLength(X)\n title = ['feature_' + str(i) for i in range(fn)]\n X.columns = title\n\n return X,title,ID","sub_path":"DAL/Loader.py","file_name":"Loader.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"100166750","text":"import random\n\nprint('I am thinking of a 3-digit number. Try to guess what it is.\\n\\\n Here are some clues:\\n\\\n When I say: That means:\\n\\\n Cold No digit is correct.\\n\\\n Warm One digit is correct but in the wrong position.\\n\\\n Hot One digit is correct and in the right position.\\n\\\n I have thought up a number. You have 10 guesses to get it.')\n\nrandom_digit = str(random.choice(range(100, 1000)))\n# print(random_digit)\n\ntries = 1\ndigit_input = input(\"Guess digit: \")\nwhile digit_input != random_digit:\n print('Guess #', tries)\n if tries == 1:\n pass\n else:\n digit_input = input(\"Guess digit: \")\n\n list_random = [random_digit[0], random_digit[1], random_digit[2]]\n list_input = [digit_input[0], digit_input[1], digit_input[2]]\n index_of_hot = []\n count_hot = 0\n count_warm = 0\n count_cold = 0\n\n for i in range(len(list_input)):\n if list_input[i] == list_random[i]:\n count_hot += 1\n index_of_hot.append(i)\n\n list_to_check_warm = [0, 1, 2]\n for i in range(len(index_of_hot)):\n list_to_check_warm.remove(index_of_hot[i])\n\n for i in list_to_check_warm:\n if list_input[i] in list_random:\n count_warm += 1\n else:\n count_cold += 1\n if count_cold == 3:\n print(\"Cold\")\n else:\n print(\"Hot \" * count_hot, \"Warm \" * count_warm)\n\n tries += 1\nprint('You got it!')\n","sub_path":"hotncold.py","file_name":"hotncold.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"616932647","text":"x = input()\ny = []\nnum = 0\nfor i in x:\n if i.isupper():\n y.append(i)\n num = num + 1\n \ny = set(y)\n\nif num == 0:\n print(\"Not Found\")\n\nif num > 0:\n y = \"\".join(y)\n print(y)\n \n \n","sub_path":"py_judge/raw_answer_files/小A/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"435309352","text":"#!/usr/bin/python\n# MIPS Disassembler\n# Benjamin Pruett (spruett3)\nimport sys\nimport optparse\nfrom collections import namedtuple\n\n\nclass DisasmState:\n def __init__(self):\n self.labels = {}\n self.cur_address = 0\n\nrinstr_data = namedtuple('rinstr_data', ['name', 'func', 'serialize'])\ninstr_data = namedtuple('instr_data', ['name', 'serialize', 'parse'])\n\nr_fmt = namedtuple('r_fmt', ['rs', 'rt', 'rd', 'shamt', 'func'])\ni_fmt = namedtuple('i_fmt', ['rs', 'rt', 'imm'])\nj_fmt = namedtuple('j_fmt', ['imm'])\n\nregister_nums = {\n 30: 'fp', 16: 's0', 28: 'gp', 23: 's7',\n 25: 't9', 11: 't3', 2: 'v0', 3: 'v1',\n 0: 'zero', 6: 'a2', 1: 'at',\n 21: 's5', 22: 's6', 20: 's4', 29: 'sp',\n 5: 'a1', 24: 't8', 4: 'a0', 14: 't6',\n 15: 't7', 12: 't4', 13: 't5', 10: 't2',\n 7: 'a3', 8: 't0', 9: 't1', 19: 's3',\n 27: 'k1', 26: 'k0', 31: 'ra', 18: 's2', 17: 's1'\n}\n\n\ndef get_bits(s, i, j):\n \"\"\"Get bits of a bitstring s from [i,j] inclusive.\"\"\"\n return s[i:j+1]\ndef to_int(bits):\n \"\"\"Converts a binary string of bits to an integer.\"\"\"\n return int(bits, 2)\n\ndef get_reg(bits):\n \"\"\"Converts a binary bit string into a register name.\"\"\"\n return \"$\" + register_nums[to_int(bits)]\n\ndef parse_r(instr, bits):\n rs = get_bits(bits, 6, 10)\n rt = get_bits(bits, 11, 15)\n rd = get_bits(bits, 16, 20)\n shamt = get_bits(bits, 21, 25)\n func = get_bits(bits, 26, 31)\n\n return r_fmt(get_reg(rs), get_reg(rt),\n get_reg(rd), to_int(shamt), func)\n\ndef parse_i(instr, bits):\n rs = get_bits(bits, 6, 10)\n rt = get_bits(bits, 11, 15)\n imm = get_bits(bits, 16, 31)\n\n return i_fmt(get_reg(rs), get_reg(rt),\n to_int(imm))\n\ndef parse_j(instr, bits):\n imm = get_bits(bits, 6, 31)\n\n return j_fmt(to_int(imm))\n\ndef serialize_arith(instr, bits, data, state):\n err = ''\n if data.shamt != 0:\n err = ' (non-zero shift amount: %d)' % data.shamt\n\n return '%-7s %s, %s, %s%s' % (instr.name, data.rd, data.rs, data.rt, err)\n\ndef serialize_jr(instr, bits, data, state):\n err = ''\n if data.shamt != 0:\n err = ' (non-zero shift amount %d)' % data.shamt\n if data.rd != '$zero':\n err += ' (non-zero $rd %s)' % data.rd\n if data.rt != '$zero':\n err += ' (non-zero $rt %s)' % data.rt\n\n return '%-7s %s%s' % (instr.name, data.rs, err)\n\ndef serialize_sys(instr, bits, data, state):\n err = ''\n if data.shamt != 0:\n err = ' (non-zero shift amount %d)' % data.shamt\n if data.rd != '$zero':\n err += ' (non-zero $rd %s)' % data.rd\n if data.rt != '$zero':\n err += ' (non-zero $rt %s)' % data.rt\n if data.rs != '$zero':\n err += ' (non-zero $rs %s)' % data.rs\n\n return '%-7s %s' % (instr.name, err)\n\ndef serialize_shift(instr, bits, data, state):\n err = ''\n if data.rs != '$zero':\n err = ' (non-zero $rt register: %s)' % data.rt\n\n return '%-7s %s, %s, %d%s' % (instr.name, data.rd, data.rt, data.shamt, err)\n\n\ndef serialize_branch(instr, bits, data, state):\n err = ''\n imm = data.imm\n if data.rt != '$zero':\n err = ' (non-zero $rt register: %s)' % data.rt\n\n if imm > 1 << 15:\n imm -= 0x10000\n\n imm *= 4\n imm += state.cur_address\n return '%-7s %s, 0x%08X%s' % (instr.name, data.rs, imm, err)\n\ndef serialize_branch2(instr, bits, data, state):\n imm = data.imm\n if imm > 1 << 15:\n imm -= 0x10000\n\n imm *= 4\n imm += state.cur_address\n return '%-7s %s, %s, 0x%08X' % (instr.name, data.rs, data.rt, imm)\n\ndef serialize_imm(instr, bits, data, state):\n imm = data.imm\n if imm > 1 << 15 and not instr.name.endswith('u'):\n imm -= 0x10000\n\n return '%-7s %s, %s, 0x%08X' % (instr.name, data.rt, data.rs, imm)\n\ndef serialize_offs(instr, bits, data, state):\n imm = data.imm\n if imm > 1 << 15:\n imm -= 0x10000\n\n return '%-7s %s, %d(%s)' % (instr.name, data.rs, imm, data.rt)\n\ndef serialize_jmp(instr, bits, data, state):\n return '%-7s 0x%08X' % (instr.name, data.imm * 4)\n\n\nr_instructions = {\n '100100': rinstr_data('and', '100100', serialize_arith),\n '100010': rinstr_data('sub', '100010', serialize_arith),\n '100000': rinstr_data('add', '100000', serialize_arith),\n '100101': rinstr_data('or', '100101', serialize_arith),\n '101010': rinstr_data('slt', '101010', serialize_arith),\n '100111': rinstr_data('nor', '100111', serialize_arith),\n '100110': rinstr_data('xor', '100110', serialize_arith),\n\n '011001': rinstr_data('multu', '011001', serialize_arith),\n '011000': rinstr_data('mult', '011000', serialize_arith),\n '100001': rinstr_data('addu', '100001', serialize_arith),\n\n\n '000000': rinstr_data('sll', '000000', serialize_shift),\n '000010': rinstr_data('srl', '000010', serialize_shift),\n\n '001000': rinstr_data('jr', '001000', serialize_jr),\n\n '001100': rinstr_data('syscall', '001100', serialize_sys),\n}\n\ndef serialize_rtype(instr, bits, data, state):\n func = get_bits(bits, 26, 31)\n if func not in r_instructions:\n return 'Unknown r-type instruction with func code: %s' % func\n r = r_instructions[func]\n\n return r.serialize(r, bits, data, state)\n\ninstructions = {\n '000001': instr_data('bltz', serialize_branch, parse_i),\n '000110': instr_data('blez', serialize_branch, parse_i),\n\n '000101': instr_data('bne', serialize_branch2, parse_i),\n '000100': instr_data('beq', serialize_branch2, parse_i),\n\n '001100': instr_data('andi', serialize_imm, parse_i),\n '001101': instr_data('ori', serialize_imm, parse_i),\n '001001': instr_data('addiu', serialize_imm, parse_i),\n '001010': instr_data('slti', serialize_imm, parse_i),\n '001000': instr_data('addi', serialize_imm, parse_i),\n\n '000010': instr_data('j', serialize_jmp, parse_j),\n '000011': instr_data('jal', serialize_jmp, parse_j),\n\n '100011': instr_data('lw', serialize_offs, parse_i),\n '101011': instr_data('sw', serialize_offs, parse_i),\n\n '000000': instr_data('r-type', serialize_rtype, parse_r)\n}\n\ndef disassemble(bits, state):\n state.cur_address += 4\n\n if len(bits) != 32:\n return 'Instruction was not 32 bits (was %d bits)' % len(bits)\n\n op = get_bits(bits, 0, 5)\n if op not in instructions:\n return 'Unknown instruction with op code: %s' % op\n data = instructions[op]\n parse = data.parse\n return data.serialize(data, bits, parse(data, bits), state)\n\n\ndef ascii_or_hex(n):\n n = int(n, 2)\n c = chr(n)\n if 'a' <= c <= 'z' or 'A' <= c <= 'Z' or c in [' ', '.', ',']:\n return \"'\" + c + \"'\"\n return str(n)\n\ndef process_data_line(bits, state):\n if len(bits) != 32:\n return \"(non-32 bit line)\"\n num = int(bits, 2)\n\n a, b, c, d = get_bits(bits, 0, 7), get_bits(bits, 8, 15), get_bits(bits, 16, 23), get_bits(bits, 24, 31)\n\n s = \"%4s %4s %4s %4s | %-10d \" % (ascii_or_hex(a), ascii_or_hex(b), ascii_or_hex(c), ascii_or_hex(d), num)\n state.cur_address += 4\n\n return s\n\n\ndef process_file(file, pretty):\n state = DisasmState()\n line = file.readline()\n\n if line.endswith('\\n'):\n line = line[:-1]\n\n while line != '':\n if pretty:\n print('0x%08X\\t%s\\t%s' % (state.cur_address, line, disassemble(line, state)))\n else:\n print(disassemble(line, state))\n line = file.readline()\n if line.endswith('\\n'):\n line = line[:-1]\n line = file.readline()\n if line.endswith('\\n'):\n line = line[:-1]\n\n print('')\n while line != '':\n if pretty:\n print('0x%08X\\t%s\\t%s' % (state.cur_address, line, process_data_line(line, state)))\n else:\n print(process_data_line(line, state))\n line = file.readline()\n if line.endswith('\\n'):\n line = line[:-1]\n\n\nif __name__ == '__main__':\n parser = optparse.OptionParser(\n description='Primitive MIPS disassembler.\\n\\nTakes in 32-bit instructions as binary strings and outputs' +\n 'them formatted as MIPS assembly code. \\nReads from stdin, or a given file name.')\n parser.add_option('-p', '--pretty', action='store_true',\n help='Pretty prints the disassembly with addresses and bits')\n parser.add_option('-o', '--outputfile', action='store', default='',\n help='Output file instead of stdout')\n\n (opts, args) = parser.parse_args()\n\n file = sys.stdin\n if len(args) > 1:\n print('Usage:\\n\\n\\tpython disasm.py [in-filename]')\n elif len(args) == 1:\n try:\n file = open(args[0])\n except:\n print('Could not open input file %s' % args[0])\n\n if opts.outputfile != '':\n sys.stdout = open(opts.outputfile, 'w')\n process_file(file, opts.pretty)\n if file != sys.stdin:\n file.close()","sub_path":"disasm.py","file_name":"disasm.py","file_ext":"py","file_size_in_byte":8771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"63049917","text":"# Definition for singly-linked list. \n# class ListNode: \n# def __init__(self, x): \n# self.val = x \n# self.next = None \n\n# idea: create two pointers. Pointer1 moves n steps first, then start moving Pointer 2 from the beginning. When \n# Pointer1 reaches the end, the position of Pointer2 is exact what we would like to remove. \n\n\nclass Solution():\n # \"head\" type: ListNode \n def findNthnode(self,head,n):\n p1 = head;\n p2 = head;\n \n for i in range(n):\n p1 = p1.next; ## move to the nth node\n \n if p1!=None:\n while p1.next != None: # now start moving both pointers\n p1 = p1.next;\n p2 = p2.next;\n \n p2.next = p2.next.next;\n return head;\n else:\n head.next;\n \n ","sub_path":"7_remove_nth_node/7_remove_nth_node_fromend.py","file_name":"7_remove_nth_node_fromend.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"89303672","text":"'''\nCreated on 31 Aug 2014\n\n@author: wilson\n'''\nimport unittest\nimport os\nimport yx.libxml as XML\n\nclass Test(unittest.TestCase):\n \n def setUp(self):\n self.xml_string = '1234'\n self.xml_file_path = '/tmp/__test_xml_1976__.xml'\n with open(self.xml_file_path, 'w') as f:\n f.send(self.xml_string)\n\n def tearDown(self):\n os.remove(self.xml_file_path)\n\n\n def testXmlDoc(self):\n self.assertIsNotNone(XML.XmlDoc.parse(text=self.xml_string), 'Failed to parse xml string.')\n self.assertIsNotNone(XML.XmlDoc.parse(path=self.xml_file_path), 'Failed to parse xml file: ' + self.xml_file_path)\n with open(self.xml_file_path, 'r') as f:\n self.assertIsNotNone(XML.XmlDoc.parse(file=f), 'Failed to parse xml file: ' + self.xml_file_path)\n\n def testXmlElement(self):\n e = XML.XmlElement(name='a')\n e.set_attribute('attr1', '1')\n e.set_value('value')\n self.assertEqual(e.value(), 'value')\n self.assertEqual(e.attribute('attr1'), '1')\n e.add_element(XML.XmlElement(name='b', value='1', attributes={'c':3}))\n e.add_element(XML.XmlElement(name='b', value='2', attributes={'c':4}))\n self.assertEqual(len(e.values('b/@c')), 2)\n \n def testXmlStringWriter(self):\n w = XML.XmlStringWriter('a')\n w.push('e')\n w.add('b', 3, {'c':'1', 'd':'2'})\n w.pop()\n self.assertEqual(w.document(), '3')\n\nif __name__ == \"__main__\":\n # import sys;sys.argv = ['', 'Test.testName']\n unittest.main()\n","sub_path":"src/wxyz/libxml_test.py","file_name":"libxml_test.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"113872772","text":"class Enemy:\n life = 3\n\n def __init__(self, x):\n self.energy = x\n\n def get_energy(self):\n print(self.energy)\n\n def attack(self):\n print(\"ouch!\")\n self.life -= 1\n\n def checkLife(self):\n if self.life <= 0:\n print(\"I am dead... ouch!\")\n else:\n print(\"Life Left: \" + str(self.life))\n\nenemy1 = Enemy(4)\nenemy2 = Enemy(3)\n\nenemy1.attack()\nenemy1.attack()\nenemy2.attack()\nenemy1.checkLife()\nenemy2.checkLife()\n\nclass Tuna:\n def __init__(self):\n print(\"TUNA\")\n\n def swim(self):\n print(\"I am swimming\")\n\nflipper = Tuna()\nflipper.swim()\n\njason = Enemy(5)\nboss = Enemy(10)\n\njason.get_energy()\nboss.get_energy()\n","sub_path":"Trivial pursuit/init-class.py","file_name":"init-class.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"346481158","text":"import re\n# import string\nfrom docx import Document\n\n#Prepare function to read in documents\ndef read_doc_file_to_string(file_name, read_mode):\n f = open(file_name, read_mode)\n document = Document(f)\n f.close()\n fulltext = []\n for para in document.paragraphs:\n fulltext.append(para.text)\n fulltext_str = ' '.join(fulltext)\n return fulltext_str\n\n#removes any text contained inside parentheses or brackets.\ndef remove_grouped_text(input_text):\n open_index = input_text.find('(')\n close_index = input_text.find(')')\n while open_index > 0:\n input_text = input_text[:open_index]+input_text[(close_index+1):]\n open_index = input_text.find('(')\n close_index = input_text.find(')')\n open_index = input_text.find('[')\n close_index = input_text.find(']')\n while open_index > 0:\n input_text = input_text[:open_index]+input_text[(close_index+1):]\n open_index = input_text.find('[')\n close_index = input_text.find(']')\n return input_text\n\n#remove punctation characters\ndef remove_punctuation_characters(input_text):\n processed_text = input_text.replace(\"P:\",\" INTERVIEWEE \")\n processed_text = processed_text.replace(\"I:\", \" INTERVIEWER \")\n processed_text = re.sub(r\"[^a-zA-Z0-9]\",\" \",processed_text)\n return processed_text\n\n#function to make case of words uniform and puts one space between each word.\n #input_text is the interview as a string\n #upper (optional) is True if the words are to be upper case\n #lower (optional) is True if the words are to be lower case\n #title (optional) is True if the words are to have 'title' case\ndef normalize_text(input_text,upper=False,lower=False,title=False,sep=\" \"):\n words = input_text.split()\n output_text=\"\"\n if upper:\n for word in words:\n word.upper()\n if lower:\n for word in words:\n word.lower()\n if title:\n for word in words:\n word.title()\n output_text=sep.join(words)\n return output_text\n \n#function to separate out the statements of the interview.\n #input_text is the interview as a string\n #interviewer is the string in the text that marks when interviewer is speaking\n #interviewee is the string in the text that marks when interviewee is speaking.\ndef separate_statements(input_text, interviewer, interviewee):\n j = 0\n interviewer_text = \"\"\n interviewee_text = \"\"\n text_partition = []\n while (interviewer in input_text) or (interviewee in input_text):\n if j%2==0:\n text_partition = input_text.partition(interviewee)\n input_text = text_partition[2]\n interviewer_text = interviewer_text+'NEXT'+text_partition[0]\n if j%2==1:\n text_partition = input_text.partition(interviewer)\n input_text = text_partition[2]\n interviewee_text = interviewee_text+'NEXT'+text_partition[0]\n j=j+1\n if j%2==0:\n interviewer_text = interviewer_text+'NEXT'+input_text\n if j%2==1:\n interviewee_text = interviewee_text+'NEXT'+input_text\n return [interviewer_text,interviewee_text]\n\n#function to find a word and the phrase it is a part of.\n #input_text is text to be analyzed\n #word_list is a list of words to be looked for\n #radius is the number of words to be taken before and after search word for context\ndef word_context(input_text, word_list, radius):\n words = input_text.split()\n output = []\n if type(word_list)==type(output):\n for word in word_list:\n word_neighborhoods = []\n for compare in words:\n if word.title() == compare.title():\n center = words.index(compare)\n neighborhood = words[center-radius:center+radius+1]\n word_neighborhoods.append(string.join(neighborhood))\n output.append(word_neighborhoods)\n elif type(word_list)==type(\"\"):\n word_neighborhoods = []\n for compare in words:\n if word_list.title() == compare.title():\n center = words.index(compare)\n neighborhood = words[center-radius:center+radius+1]\n word_neighborhoods.append(string.join(neighborhood))\n output.append(word_neighborhoods)\n else:\n print(\"ERROR IN TYPE\")\n return output\n\n#function to clean the data\n #text_arr is the input array of strings -- each string is a transcript of the interview\n #cleaned_text_arr is the outputs array of cleaned strings\ndef clean_text(text_arr):\n cleaned_text_arr = []\n for text in text_arr:\n # Remove grouped text like (laughing) etc.\n text = remove_grouped_text(text)\n # Remove punctuation characters and replace P: & I: with INTERVIEWER & INTERVIEWEE\n text = remove_punctuation_characters(text)\n # Normalize the input text\n text = normalize_text(text)\n cleaned_text_arr.append(text)\n return cleaned_text_arr","sub_path":"project_1948.py","file_name":"project_1948.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"136105950","text":"from django.utils.translation import ugettext_lazy as _\nfrom django_filters.rest_framework import DjangoFilterBackend\n\nfrom rest_framework import filters\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\n\nfrom fleio.core.drf import StaffOnly\nfrom fleio.core.exceptions import APIBadRequest\nfrom fleio.core.filters import CustomFilter\nfrom fleio.core.utils import get_countries\nfrom plugins.domains.custom_fields.contact_custom_field_definition import ContactCustomFieldDefinition\n\nfrom plugins.domains.models import Contact\nfrom plugins.domains.staff.serializers import ContactCreateSerializer\nfrom plugins.domains.staff.serializers import ContactUpdateSerializer\nfrom plugins.domains.staff.serializers import ContactSerializer\n\n\nclass ContactsViewSet(viewsets.ModelViewSet):\n permission_classes = (StaffOnly, )\n serializer_class = ContactSerializer\n filter_backends = (DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter, CustomFilter)\n filter_fields = (\n 'id',\n 'client',\n )\n search_fields = (\n 'first_name',\n 'last_name',\n 'id',\n 'email',\n 'company',\n 'address1',\n 'address2',\n 'city',\n 'country',\n 'state',\n )\n ordering_fields = (\n 'id',\n 'created_at',\n 'first_name',\n 'last_name',\n 'company',\n 'address1',\n 'address2',\n 'city',\n 'country',\n 'state',\n )\n\n serializer_map = {'retrieve': ContactSerializer,\n 'create': ContactCreateSerializer,\n 'update': ContactUpdateSerializer}\n\n def get_queryset(self):\n return Contact.objects.all()\n\n def get_serializer_class(self):\n return self.serializer_map.get(self.action, self.serializer_class)\n\n @action(detail=False, methods=['get'])\n def create_options(self, request, *args, **kwargs):\n del request, args, kwargs # unused\n return Response({'countries': get_countries(),\n 'custom_fields': ContactCustomFieldDefinition().definition\n })\n\n def destroy(self, request, *args, **kwargs):\n contact = self.get_object()\n\n from django.db import IntegrityError\n try:\n contact.delete()\n return Response()\n except IntegrityError:\n raise APIBadRequest(\n detail=_('Cannot delete contact since it is still in use.')\n )\n","sub_path":"project/plugins/domains/staff/views/contacts.py","file_name":"contacts.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"556312085","text":"import pkg_resources\nimport os\nimport shutil\n\n\ndef parse_load_ep(spec):\n dist_name, name = spec.split(\":\")\n req = pkg_resources.Requirement.parse(distname)\n ep = pkg_resources.load_entry_point(dist, channel_name, name)\n return ep.load()\n\ndef safe_populate(req, src, dst):\n \"\"\"\n req - pkg_resource Requirements object\n src - path inside req\n dst - path to create and/or populate\n \"\"\"\n fh = []\n if isinstance(req, basestring):\n req = pkg_resources.Requirement.parse(req)\n \n if not os.path.exists(dst):\n source = pkg_resources.resource_filename(req, src)\n shutil.copytree(source, dst)\n fh.append(dst)\n else:\n source = pkg_resources.resource_filename(req, src)\n files = pkg_resources.resource_listdir(req, src)\n for fp in files:\n if not fp.startswith('.svn'):\n shutil.copy(os.path.join(source, fp), dst)\n fh.append(dst)\n return fh\n\ndef safe_mkdir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n return path\n","sub_path":"anabuildout/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"319290867","text":"class BinaryHeap:\n def __init__(self, values_list=None):\n if values_list is None:\n values_list = []\n self.nodes = [None] * len(values_list)\n self.last_index = len(self.nodes) - 1\n last_i = len(values_list) - 1\n first_instant_insert_i = int((last_i - 1)/2) + 1\n i = first_instant_insert_i\n while i < len(values_list):\n self.nodes[i] = values_list[i]\n i += 1\n i = first_instant_insert_i - 1\n while i >= 0:\n self.nodes[i] = values_list[i]\n self.sift_down(i)\n i -= 1\n\n def sift_down(self, index):\n while True:\n if 2*index + 1 <= self.last_index:\n index_with_min = 2*index + 1\n else:\n return index\n if 2*index + 2 <= self.last_index and self.nodes[2*index + 2] < self.nodes[2*index + 1]:\n index_with_min = 2*index + 2\n if self.nodes[index_with_min] < self.nodes[index]:\n self.nodes[index_with_min], self.nodes[index] = self.nodes[index], self.nodes[index_with_min]\n index = index_with_min\n else:\n return index\n\n def sift_up(self, index):\n while True:\n if index > 0:\n if self.nodes[int((index - 1)/2)] > self.nodes[index]:\n self.nodes[int((index - 1)/2)], self.nodes[index] = self.nodes[index], self.nodes[int((index - 1)/2)]\n index = int((index - 1)/2)\n else:\n return index\n else:\n return index\n\n def insert(self, key):\n self.last_index += 1\n self.nodes[self.last_index] = key\n self.sift_up(self.last_index)\n\n def get_min(self):\n return self.nodes[0]\n\n def extract_min(self):\n if self.last_index < 0:\n return None\n answer = self.nodes[0]\n self.nodes[0], self.nodes[self.last_index] = self.nodes[self.last_index], None\n self.last_index -= 1\n self.sift_down(0)\n return answer\n\n def decrease_key(self, index, key):\n if key > self.nodes[index]:\n raise ValueError(\"When decreasing, new key must be lesser or equal than present key.\")\n self.nodes[index] = key\n return self.sift_up(index)\n\n def remove(self, index):\n if index < 0 or index > self.last_index:\n raise ValueError(\"Index must be grater than zero and lesser than last index.\")\n if index == self.last_index:\n self.nodes[index] = None\n self.last_index -= 1\n else:\n self.nodes[index], self.nodes[self.last_index] = self.nodes[self.last_index], None\n self.last_index -= 1\n if self.nodes[index] < self.nodes[int((index - 1)/2)]:\n self.sift_up(index)\n else:\n self.sift_down(index)\n\n\n\na = BinaryHeap([5,4,3,2,1,10])\n","sub_path":"binary_heap.py","file_name":"binary_heap.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"204153201","text":"# https://radimrehurek.com/gensim/scripts/glove2word2vec.html\n# https://radimrehurek.com/gensim/models/word2vec.html\n# https://stackoverflow.com/a/33629076\n\nfrom gensim.models import KeyedVectors\nfrom gensim.scripts.glove2word2vec import glove2word2vec\nfrom pathlib import Path\n\nglove_name = 'glove.6B.100d'\nglove_file = Path('glove_embeddings/{}.txt'.format(glove_name))\ntmp_file = Path('glove_embeddings/{}_word2vec.txt'.format(glove_name))\n\n_ = glove2word2vec(glove_file, tmp_file)\n\n# You would load like this\nmodel = KeyedVectors.load_word2vec_format(tmp_file)\nmodel.save(f'glove_embeddings/{glove_name}_gensim.model')\ntmp_file.unlink()\n","sub_path":"helpers/glove_to_word2vec.py","file_name":"glove_to_word2vec.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"92213181","text":"import sys\nimport asyncio\nimport yaml\nimport pygada_runtime\n\n\ndef main(argv, *args, **kwargs):\n async def run():\n # Read node input\n params = await pygada_runtime.read_json(sys.stdin)\n data = params.get(\"data\", {})\n\n # Read from input file\n input = params.get(\"input\", None)\n if input:\n with open(input, \"r\") as f:\n data = yaml.safe_load(f.read())\n\n # Write to output file\n output = params.get(\"output\", None)\n if output:\n with open(output, \"w+\") as f:\n f.write(yaml.safe_dump(data))\n\n # Write node output\n pygada_runtime.write_json(sys.stdout, {\"data\": data})\n\n asyncio.run(run())\n","sub_path":"gadalang_lang/parser/_yaml.py","file_name":"_yaml.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"482475617","text":"import inspect\nimport sys\nfrom pathlib import Path\nfrom sys import stdin\n\nimport yaml\n\nfrom Factor import factor_fastest\nfrom expression.Node import Node, ConstantNode, FunctionNode\nfrom expression.parser.Parser import parse\nfrom expression.parser.Printer import to_string\n\n\ndef equivalent_fraction(n: Node):\n return equivalent_fraction_basic(n) | equivalent_fraction_constant_shortcircuit(n)\\\n | equivalent_fraction_exponent_shortcircuit(n)\n\n\n# MARKDOWN\ndef equivalent_fraction_basic(n: Node):\n if not isinstance(n, FunctionNode):\n return set()\n if n.op == '/':\n l_arg = n.args[0]\n r_arg = n.args[1]\n if isinstance(l_arg, FunctionNode) and l_arg.op == '*' and isinstance(r_arg, FunctionNode) and r_arg.op == '*' \\\n and l_arg.args[1] == r_arg.args[1]:\n _n = FunctionNode(\n '*',\n [\n FunctionNode('/', [l_arg.args[0], r_arg.args[0]]),\n FunctionNode('/', [l_arg.args[1], r_arg.args[1]])\n ]\n )\n return {_n}\n return set()\n# MARKDOWN\n\n\n# This short-circuits the idea of removing constant integer factors by expanding out prime factors and then using\n# equivalent_fraction_basic() to pull out those prime factors from the fraction.\ndef equivalent_fraction_constant_shortcircuit(n: Node):\n if not isinstance(n, FunctionNode):\n return set()\n if n.op == '/':\n l_arg = n.args[0]\n r_arg = n.args[1]\n if isinstance(l_arg, FunctionNode) and l_arg.op == '*' and isinstance(r_arg, FunctionNode) and r_arg.op == '*' \\\n and isinstance(l_arg.args[1], ConstantNode) and isinstance(r_arg.args[1], ConstantNode):\n p1, p2 = l_arg.args[1].value, r_arg.args[1].value\n if p1 > 0:\n factors1 = factor_fastest(p1)\n elif p1 < 0:\n factors1 = factor_fastest(-p1)\n factors1 = {-f for f in factors1}\n else:\n return set()\n if p2 > 0:\n factors2 = factor_fastest(p2)\n elif p2 < 0:\n factors2 = factor_fastest(-p2)\n factors2 = {-f for f in factors2}\n else:\n return set()\n factor = max(factors1 & factors2)\n p1 = p1 // factor\n p2 = p2 // factor\n _n = FunctionNode(\n '/',\n [\n FunctionNode('*', [l_arg.args[0], ConstantNode(p1)]),\n FunctionNode('*', [r_arg.args[0], ConstantNode(p2)])\n ]\n )\n return {_n}\n return set()\n\n\ndef equivalent_fraction_exponent_shortcircuit(n: Node):\n def normalize_to_exponents(n1: Node, n2: Node):\n if isinstance(n1, FunctionNode) and n1.op == '^'\\\n and isinstance(n2, FunctionNode) and n2.op == '^'\\\n and n1.args[0] == n2.args[0]:\n return n1, n2\n elif isinstance(n1, FunctionNode) and n1.op == '^'\\\n and n1.args[0] == n2:\n return n1, FunctionNode('^', [n2, ConstantNode(1)])\n elif isinstance(n2, FunctionNode) and n2.op == '^'\\\n and n2.args[0] == n1:\n return FunctionNode('^', [n1, ConstantNode(1)]), n2\n else:\n return FunctionNode('^', [n1, ConstantNode(1)]), FunctionNode('^', [n2, ConstantNode(1)])\n\n def normalize_to_multiplication(n1: Node, n2: Node):\n if isinstance(n1, FunctionNode) and n1.op == '*' and isinstance(n2, FunctionNode) and n2.op == '*':\n return n1, n2\n elif isinstance(n1, FunctionNode) and n1.op == '*':\n return n1, FunctionNode('*', [ConstantNode(1), n2])\n elif isinstance(n2, FunctionNode) and n2.op == '*':\n return FunctionNode('*', [ConstantNode(1), n1]), n2\n else:\n return FunctionNode('*', [ConstantNode(1), n1]), FunctionNode('*', [ConstantNode(1), n2])\n\n if not isinstance(n, FunctionNode) or n.op != '/':\n return set()\n arg1, arg2 = n.args\n arg1, arg2 = normalize_to_multiplication(arg1, arg2)\n p1, p2 = arg1.args[1], arg2.args[1]\n p1, p2 = normalize_to_exponents(p1, p2)\n if p1.args[0] == p2.args[0] and isinstance(p1.args[1], ConstantNode) and isinstance(p2.args[1], ConstantNode):\n p_base = p1.args[0]\n p_min_exp = min(p1.args[1], p2.args[1])\n p_top_exp = p1.args[1] - p_min_exp\n p_bottom_exp = p2.args[1] - p_min_exp\n rhs_top = FunctionNode('^', [p_base, p_top_exp])\n rhs_bottom = FunctionNode('^', [p_base, p_bottom_exp])\n lhs_top = arg1.args[0]\n lhs_bottom = arg2.args[0]\n _n = FunctionNode(\n '*',\n [\n FunctionNode('/', [lhs_top, lhs_bottom]),\n FunctionNode('/', [rhs_top, rhs_bottom])\n ]\n )\n return {_n}\n return set()\n\n\ndef main():\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-disable-all}`\", end=\"\\n\\n\")\n funcs = {n: o for n, o in inspect.getmembers(sys.modules[__name__]) if (inspect.isfunction(o) and n != 'main')}\n try:\n data_raw = ''.join(stdin.readlines())\n data: list = yaml.safe_load(data_raw)\n print(f'{Path(__file__).name} produced the following alternate forms ...')\n print()\n # print('```')\n # print(data_raw)\n # print('```')\n # print()\n # print(f'The following alternative forms were produced ...')\n # print()\n print('```')\n for func_name, exp in data:\n exp = str(exp)\n n = parse(exp)\n func = funcs[func_name]\n print(f'{func_name} with input {exp} ...')\n for alt_n in func(n):\n print(f' {to_string(n)} ⟶ {to_string(alt_n)}')\n print('```')\n print()\n finally:\n print(\"
\", end=\"\\n\\n\")\n print(\"`{bm-enable-all}`\", end=\"\\n\\n\")\n\n\nif __name__ == '__main__':\n for r in equivalent_fraction(parse('(x*1)/(1*1)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction(parse('(1*1)/(x*1)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction(parse('(x*c)/(y*c)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction(parse('(1*c)/(1*c)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction(parse('(x*(t-1))/(y*(t-1))')):\n print(f'{to_string(r)}')\n\n for r in equivalent_fraction_constant_shortcircuit(parse('(x*5)/(y*10)')):\n print(f'{to_string(r)}')\n\n for r in equivalent_fraction_exponent_shortcircuit(parse('(5*x^2)/(x^3)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction_exponent_shortcircuit(parse('(z*x)/(y*x^5)')):\n print(f'{to_string(r)}')\n for r in equivalent_fraction_exponent_shortcircuit(parse('(z*x^5)/(y*x)')):\n print(f'{to_string(r)}')","sub_path":"docs/data/learn/Algebra/input/arithmetic_code/expression/properties/EquivalentFractionProperty.py","file_name":"EquivalentFractionProperty.py","file_ext":"py","file_size_in_byte":6884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"88453453","text":"import csv,numpy,sys\ndate=sys.argv[1]\ntest=sys.argv[2]\nwith open('global.csv', 'r') as t1: # 1441L\n global_csv = t1.readlines() \nwith open('heart_global.csv', 'r') as t2: #1392L and no '0' , form mkglobal.py , original file is heart_test3_try.csv\n heart_global_csv = t2.readlines()\nwith open('heart_notzero.csv','r') as t3:\n heart_notzero_csv=t3.readlines()\n\nheart_complement='heart_'+test+'_'+date+'_complement.csv'\nwith open(heart_complement, 'w') as out_file:\n line_in_new = 0\n line_in_old = 0\n while line_in_old < len(global_csv):\n if global_csv[line_in_old] == heart_global_csv[line_in_new]:\n out_file.write(heart_notzero_csv[line_in_new])\n line_in_old+=1\n line_in_new+=1\n elif global_csv[line_in_old] != heart_global_csv[line_in_new]:\n out_file.write(global_csv[line_in_old])\n line_in_old+=1\n\n","sub_path":"global.py","file_name":"global.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"79815570","text":"from unittest import skip\r\n\r\nfrom django.test import TestCase\r\n\r\nfrom py_snap_screen import settings\r\nfrom web import core\r\nfrom web.models import ViewerConnection\r\nfrom web.tests import stubs\r\nfrom web.services import AdministrationService\r\n\r\n\r\n# TODO: (IMS) Change from service tests to view tests\r\nclass PersistenceServiceTest(TestCase):\r\n fixtures = ['test_data.json']\r\n\r\n def setUp(self):\r\n self.candidate = core_service_factory.createPersistenceService()\r\n\r\n @skip('Viewer connections are now created within Supervisors by a signal from framework user creation')\r\n def test_save_viewer_connection(self):\r\n self.candidate.save_viewer_connection(stubs.CONNECTION, stubs.SUPERVISOR_ID)\r\n \r\n supervisor = core_service_factory.core_persistence_service2.objects.get(supervisor_id=stubs.SUPERVISOR_ID_VALUE)\r\n\r\n self.assertEqual(stubs.ACTIVE, supervisor.active)\r\n self.assertEqual(stubs.AUTHORIZATION_TOKEN, supervisor.viewer_authentication_key)\r\n self.assertEqual(stubs.SUPERVISOR_ID_VALUE, supervisor.supervisor_id)\r\n\r\n @skip('Viewer connections are now created within Supervisors by a signal from framework user creation')\r\n def test_retrieve_viewer_connection(self):\r\n user = stubs.FRAMEWORK_USER_FUNCTION()\r\n supervisor = core_service_factory.core_persistence_service2(active=stubs.ACTIVE,\r\n supervisor_id=stubs.SUPERVISOR_ID_VALUE,\r\n viewer_authentication_key=stubs.AUTHORIZATION_TOKEN,\r\n inbound_identity_token=user)\r\n supervisor.save()\r\n\r\n actual_connection = self.candidate.retrieve_viewer_connection(stubs.SUPERVISOR_ID)\r\n\r\n self.assertEqual(stubs.ACTIVE, actual_connection.active)\r\n self.assertEqual(stubs.AUTHORIZATION_TOKEN, actual_connection.authorization_token)\r\n\r\n def test_increment_activity_count(self):\r\n# user = stubs.FRAMEWORK_USER_FUNCTION()\r\n# supervisor = core_service_factory.core_persistence_service2.objects.get(inbound_identity_token=user)\r\n# supervisor.supervisor_id = stubs.SUPERVISOR_ID_VALUE\r\n# supervisor.save()\r\n supervisor = core_service_factory.core_persistence_service2.objects.get(id=stubs.INBOUND_IDENTITY_TOKEN)\r\n\r\n activity = core_service_factory.core_persistence_service(supervisor=supervisor, activity_month=stubs.MONTH,\r\n activity_count=stubs.ACTIVITY_COUNT)\r\n\r\n activity.save()\r\n\r\n self.candidate.increment_activity_count(stubs.SUPERVISOR_ID, stubs.MONTH)\r\n\r\n activity = core_service_factory.core_persistence_service.objects.get(\r\n supervisor__supervisor_id=stubs.SUPERVISOR_ID_VALUE, activity_month=stubs.MONTH)\r\n\r\n self.assertEqual(stubs.INCREMENTED_ACTIVITY_COUNT, activity.activity_count)\r\n\r\n\r\nclass SupervisorIdServiceTest(TestCase):\r\n def setUp(self):\r\n self.candidate = core_service_factory.createSupervisorIdService()\r\n \r\n def test_generate(self):\r\n supervisor_id = self.candidate.generate()\r\n self.assertEqual(7, len(supervisor_id.value))\r\n\r\n\r\nclass AdministrationServiceTest(TestCase):\r\n def setUp(self):\r\n monthly_limit_service = core_service_factory.createMonthlyLimitService()\r\n persistence_service = core_service_factory.createPersistenceService()\r\n supervisor_id_service = core_service_factory.createSupervisorIdService()\r\n viewer_connection_service = core_service_factory.createViewerConnectionService()\r\n self.candidate = AdministrationService(monthly_limit_service, persistence_service, supervisor_id_service,\r\n viewer_connection_service)\r\n\r\n def test_start_creating_supervisor_id(self):\r\n session = {}\r\n authorization_url = self.candidate.start_creating_supervisor_id(session)\r\n \r\n self.assertTrue(authorization_url.startswith(\r\n \"https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=\" + settings.DROPBOX_API_KEY\r\n + \"&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fviewer-connection-callback%2F&state=\"))\r\n self.assertIn(\"dropbox-auth-csrf-token\", session)\r\n\r\n # TODO: Is it feasible or desirable to test the callback?\r\n\r\n\r\nclass ViewerServiceTest(TestCase):\r\n AUTHORIZATION_TOKEN = settings.TEST_AUTHORIZATION_TOKEN\r\n connection = ViewerConnection(True, AUTHORIZATION_TOKEN)\r\n\r\n def setUp(self):\r\n self.candidate = core_service_factory.createViewerService()\r\n\r\n def test_send_activity(self):\r\n self.candidate.send_activity(stubs.ACTIVITY, self.connection)\r\n\r\n api = core_service_factory.core_viewer_service(self.AUTHORIZATION_TOKEN)\r\n _, resource = api.files_download(stubs.CORE_FILENAME)\r\n\r\n self.assertEqual(stubs.CONTENTS, resource.content)\r\n\r\n def tearDown(self):\r\n api = core_service_factory.core_viewer_service(self.AUTHORIZATION_TOKEN)\r\n api.files_delete(stubs.CORE_FILENAME)\r\n\r\n\r\ncore_service_factory = core.CoreServiceFactory()\r\n","sub_path":"web/tests/integration_tests.py","file_name":"integration_tests.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"177751238","text":"import cv2\nimport os\n\nimport rclpy\nfrom rclpy.node import Node\nfrom rclpy.qos import qos_profile_default\nfrom sensor_msgs.msg import Image\n\nfrom convertions.convertions import image_to_numpy\nfrom face_recognition.face_recognition import load_image_file, face_encodings, face_locations, compare_faces\n\nDIR = os.path.dirname(os.path.realpath(__file__))\n\n# This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the\n# other example, but it includes some basic performance tweaks to make things run a lot faster:\n# 1. Process each video frame at 1/4 resolution (though still display it at full resolution)\n# 2. Only detect faces in every other frame of video.\n\n# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.\n# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this\n# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.\n\n# Load a sample picture and learn how to recognize it.\nobama_image = load_image_file(os.path.join(DIR, \"obama.jpg\"))\nobama_face_encoding = face_encodings(obama_image)[0]\n\n# Load a second sample picture and learn how to recognize it.\nbiden_image = load_image_file(os.path.join(DIR, \"biden.jpg\"))\nbiden_face_encoding = face_encodings(biden_image)[0]\n\n# Load a second sample picture and learn how to recognize it.\nemilka_image = load_image_file(os.path.join(DIR, \"emilka.jpg\"))\nemilka_face_encoding = face_encodings(emilka_image)[0]\n\n# Load a second sample picture and learn how to recognize it.\nwagram_image = load_image_file(os.path.join(DIR, \"wagram.jpg\"))\nwagram_face_encoding = face_encodings(wagram_image)[0]\n\n\n# Create arrays of known face encodings and their names\nknown_face_encodings = [\n obama_face_encoding,\n biden_face_encoding,\n emilka_face_encoding,\n wagram_face_encoding\n]\nknown_face_names = [\n \"Barack Obama\",\n \"Joe Biden\",\n \"Emilka\",\n \"Wagram\"\n]\n\n# Initialize some variables\n_face_locations = []\n_face_encodings = []\nface_names = []\nprocess_frame = True\n\n\nclass FaceRecognizerNode(Node):\n\n def __init__(self):\n super().__init__('face_recognition_webcam')\n\n qos_profile = qos_profile_default\n qos_profile.depth = 1\n\n self.subscription = self.create_subscription(\n Image,\n 'image',\n self.recognize_faces)\n\n self.process_frame = True\n self.get_logger().info('NODE STARTED')\n\n def recognize_faces(self, msg):\n # Grab a single frame of video\n frame = image_to_numpy(msg)\n\n if self.process_frame:\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # Find all the faces and face encodings in the current frame of video\n _face_locations = face_locations(rgb_small_frame)\n _face_encodings = face_encodings(rgb_small_frame, _face_locations)\n\n face_names = []\n for face_encoding in _face_encodings:\n # See if the face is a match for the known face(s)\n matches = compare_faces(known_face_encodings, face_encoding)\n name = \"Unknown\"\n\n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n\n face_names.append(name)\n\n # Display the results\n for (top, right, bottom, left), name in zip(_face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n\n # Display the resulting image\n cv2.imshow('Face recognition', frame)\n cv2.waitKey(1)\n\n self.process_frame = not self.process_frame\n\n # return face_names\n\n def stop(self):\n cv2.destroyAllWindows()\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n face_recognizer_node = FaceRecognizerNode()\n\n rclpy.spin(face_recognizer_node)\n\n face_recognizer_node.get_logger().info('NODE TERMINATED')\n face_recognizer_node.stop()\n face_recognizer_node.destroy_node()\n\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ros2/src/roboy_vision/face_recognition/examples/facerec_ros_webcam.py","file_name":"facerec_ros_webcam.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"396634896","text":"from django.urls import path\nfrom . import views\t\n\nurlpatterns = [\n path('', views.index),\n path('users', views.createUser),\n path('login', views.login),\n path('homepage', views.homepage),\n path('cats', views.createCat),\n path('deleteCat/',views.deleteCat),\n path('voteCat/',views.voteCat),\n path('unvoteCat/',views.unvoteCat),\n path('profile',views.userProfile),\n path('cat/',views.catProfile)\n]","sub_path":"django/review_proj/review_proj_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"110487075","text":"from ject import oneself\nfrom texting import ELLIP\n\nfrom xbrief.margin.vector_margin import VectorMargin\n\nparams = {\n 'h0t0': (0, 0),\n 'h0t1': (0, 1),\n 'h1t0': (1, 0),\n 'h1t1': (1, 1),\n 'h3t2': (3, 2),\n 'h10t10': (10, 10),\n}\n\ncandidates = {\n 'simple': [1, 2, 3, 4, 5, 6, 7, 8]\n}\n\nfor key, vector in candidates.items():\n for param_name, (head, tail) in params.items():\n print(key,\n VectorMargin\n .build(vector, head, tail)\n .stringify(oneself)\n .to_list(ELLIP)\n )\n","sub_path":"test/xbrief/margin/vector_margin.test.py","file_name":"vector_margin.test.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"275334925","text":"import pandas as pd\r\nimport seaborn as sns\r\nfrom matplotlib import pyplot as plt\r\n\r\ndf = pd.read_csv(\"train.csv\")\r\npd.set_option(\"display.max_columns\", None)\r\npd.set_option(\"display.max_rows\", None)\r\n\r\n\r\ndef summary(dataframe, cat_th=10, car_th=20):\r\n cat_cols = [col for col in dataframe.columns if dataframe[col].dtypes == \"O\"]\r\n num_cols = [col for col in dataframe.columns if dataframe[col].dtypes != \"O\"]\r\n num_but_cat = [col for col in dataframe.columns if dataframe[col].nunique() <= cat_th and\r\n dataframe[col].dtypes != \"O\"]\r\n cat_but_car = [col for col in dataframe.columns if dataframe[col].nunique() > car_th and\r\n dataframe[col].dtypes == \"O\"]\r\n final_cat_cols = cat_cols + num_but_cat\r\n final_cat_cols = [col for col in final_cat_cols if col not in cat_but_car]\r\n\r\n print(f\"Observations: {dataframe.shape[0]}\")\r\n print(f\"Variables: {dataframe.shape[1]}\")\r\n print(f\"Categorical Variables: {len(cat_cols)}, {cat_cols}\")\r\n print(f\"Numerical Numbers: {len(num_cols)} : {num_cols}\")\r\n print(f\"Numerical Variables: {len(num_cols)}, Num but Cat Variables: {len(num_but_cat)}\")\r\n print(f\"Categorical Variables: {len(cat_cols)}, Cat but Car Variables: {len(cat_but_car)}\")\r\n print(f\"Categorical Variables:{len(final_cat_cols), final_cat_cols}\")\r\n\r\n return cat_cols, num_cols, num_but_cat, cat_but_car, final_cat_cols\r\n\r\n\r\ncat_cols, num_cols, num_but_cat, cat_but_car, final_cat_cols = summary(df)\r\nfinal_num_cols = [col for col in num_cols if col not in num_but_cat]\r\n\r\n\r\ndef cat_summary(dataframe, col_name):\r\n print(pd.DataFrame({col_name: dataframe[col_name].value_counts(),\r\n \"Ratio\": 100 * dataframe[col_name].value_counts() / len(dataframe)}), end=\"\\n\\n\\n\")\r\n\r\n\r\nfor col in final_cat_cols:\r\n cat_summary(df, col)\r\n\r\nfinal_num_cols = [col for col in num_cols if col not in num_but_cat]\r\ndf[final_num_cols].describe([0.05, 0.10, 0.25, 0.50, 0.75, 0.80, 0.90, 0.95, 0.99]).T\r\n\r\n\r\ndef num_hist(dataframe, numeric_col):\r\n col_counter = 0\r\n for col in numeric_col:\r\n dataframe[col].hist(bins=20)\r\n plt.xlabel(col)\r\n plt.title(col)\r\n plt.show()\r\n col_counter += 1\r\n print(f\"{col_counter} variables have been plotted\")\r\nnum_hist(df, final_num_cols)\r\n\r\n\r\ndef target_summary_with_cat(dataframe, categorical_col, target):\r\n for col in categorical_col:\r\n if col not in target:\r\n print(pd.DataFrame({\"target_mean\": dataframe.groupby(col)[target].mean()}), end=\"\\n\\n\\n\")\r\n\r\n\r\ntarget_summary_with_cat(df, final_cat_cols, target)\r\n\r\n\r\ndef target_summary_with_num(dataframe, target, numerical_col):\r\n print(dataframe.groupby(target).agg({numerical_col: \"mean\"}), end=\"\\n\\n\\n\")\r\n\r\n","sub_path":"Week-2/analysis_datasets.py","file_name":"analysis_datasets.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"476910119","text":"num = int(input())\nblue, white = 0,0\nmatrix = []\n\ndef quad_tree(x,y,n):\n global matrix, blue, white\n double_break = False\n color = matrix[x][y]\n\n for i in range(x, x+n):\n if double_break == True:\n break\n for j in range(y, y+n):\n if matrix[i][j] != color:\n quad_tree(x,y,n//2)\n quad_tree(x+n//2, y, n//2)\n quad_tree(x, y+n//2, n//2)\n quad_tree(x+n//2, y+n//2, n//2)\n double_break = True\n break\n if double_break == False:\n if matrix[x][y] == 1:\n blue += 1\n else:\n white += 1\nfor i in range(num):\n matrix.append(list(map(int, input().split())))\n\nquad_tree(0,0,num)\n\nprint(white)\nprint(blue)","sub_path":"BOJ/BOJ Python/PY2630_색종이_만들기.py","file_name":"PY2630_색종이_만들기.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"18750342","text":"\nclass Banking:\n \"\"\"\n This class prototype the basic operation of the bank such as deposit, withdrawn and the check balance.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n This is the constructor is the class. It is automaticaly called when the object of the class is created. In this constructor, two list is created and two message is printed.\n \"\"\"\n self.balance = list()\n self.finalbalance = list()\n print(\"Welcome to the Hamro Sewa.\")\n print(\"You can deposit,withdraw and check your amount from this system. \\n\")\n\n def __isemtpy(self):\n \"\"\"\n This is the private function. It cannot be access outside of the class. This function check wheather the balance is null or not.\n \"\"\"\n if len(self.balance) == 0:\n return True\n else:\n return False\n\n def __isnegative(self, amount):\n \"\"\"\n This is the private function. It cannot be access outside of the class. This function check wheather user enter amount is null or not.\n \"\"\"\n if amount < 0:\n return True\n else:\n return False\n\n def __multiple(self, amount):\n \"\"\"\n This is also the private function. It cannot be access outside of the class. This function check wheather the user enter amount is multiple of 5 or not.\n \"\"\"\n if amount % 5 == 0:\n return True\n else:\n return False\n\n def deposit(self, amount):\n \"\"\"\n This function is used to deposit the amount. It also checks wheather the user enter amount is valid or not. If not valid it throws the error otherwise it shows the deposit amount value.\n \"\"\"\n if self.__isnegative(amount) == False:\n if self.__isemtpy() == True:\n self.balance.append(amount)\n self.finalbalance.append(sum(self.balance))\n\n return 'You have successfully deposit amount {},Now your total balance is {}.'.format(amount, *self.finalbalance)\n elif self.__isemtpy() == False:\n val = self.finalbalance[0]\n self.finalbalance.clear()\n self.finalbalance.append(val+amount)\n return 'You have successfully deposit amount {},Now your total balance is {}.'.format(amount, *self.finalbalance)\n\n else:\n raise RuntimeError(\"Cannot Deposit the Fund.\")\n elif self.__isnegative(amount) == True:\n raise RuntimeError(\"There is no such cash.\")\n\n def withdrawn(self, amount):\n \"\"\"\n This function is used to withdrawn the amount. First, this function check if the amount is valid or not. If the amount is not valid it throws the error otherwise it deposit the amount. \n \"\"\"\n if self.__multiple(amount) == True and self.__isnegative(amount) == False:\n\n if self.__isemtpy() == True:\n return RuntimeError(\"The Bank balance is empty. Please deposit your amount then try to withdrawn it.\")\n else:\n val = self.finalbalance[0]\n self.finalbalance.clear()\n self.finalbalance.append(val-amount)\n if self.__isnegative(*self.finalbalance) == False:\n return 'You have successfully withdrawn {}. Now your total balance is {}'.format(amount, *self.finalbalance)\n elif self.__isnegative(*self.finalbalance) == True:\n return RuntimeError(\"You donot have sufficient amount in your balance please deposit the fund then try to withdrawn it.\")\n else:\n return RuntimeError(\"The withdrawn amount should be multiple of five and it should not be negative.\")\n\n @property\n def checkbalance(self):\n \"\"\"\n This function display the total balance. \n \"\"\"\n try:\n return 'Your total balance is, {}'.format(*self.finalbalance)\n except:\n return 'Your total balance is, 0'\n\n\nif __name__ == '__main__':\n \"\"\"\n Below code will run if the class name is equal to main. If we import this class to another python file below code will not run.\n \"\"\"\n b = Banking()\n print(b.deposit(699))\n\n print(b.withdrawn(-510))\n print(b.checkbalance)\n\n # b.withdrawn()\n","sub_path":"baking.py","file_name":"baking.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"643812291","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport click\n\nfrom .app import utils \nfrom .app import main \n\n\n\n\nCMD_LINE_EXAMPLES = \"\"\"USAGE EXAMPLES:\n$ dice --test\n// Build visualization using local test data\n\n$ dice -k '\"solar cells\"' \n// Extract concepts from full-text search\n\n$ dice -k '\"Terry Riley\" AND music' \n// NOTE use outer single quotes for exact phrase\n\n$ dice -k '\"solar cells\"' -s 0.2 -f 2 -n 300\n// Override default settings for score, frequency and nodes\n\n$ dice 'search publications for \"cancer\" return publications[id+concepts] limit 500' \n// Full API DSL query using outer single quotes\n\"\"\"\n\n\n\n\n@click.command()\n@click.argument('dslquery', nargs=-1)\n@click.option('--examples', is_flag=True, help='Show some examples')\n@click.option('--test', is_flag=True, help='Build visualization using local test data')\n@click.option('--title', \"-t\", help='Title for the HTML output. Defaults to keyword search string or timestamp.')\n@click.option('--keywords', \"-k\", help='Keywords for a Dimensions full-text search. Top 1000 most cited publications are used to build the concepts map.')\n@click.option('--score', \"-s\", help='Concept min score: default is 0.6')\n@click.option('--freq', \"-f\", help='Concept min frequency: default is 3')\n@click.option('--nodes', \"-n\", help='Network max nodes: default is 200')\n@click.option('--edges', \"-e\", help='Network max edges: default is 300')\n@click.pass_context\ndef main_cli(ctx, \n dslquery=None, \n examples=False, \n test=False, \n title=None, \n keywords=None, \n score=None, \n freq=None, \n nodes=None, \n edges=None, \n verbose=True):\n \"\"\"Bootstrap a concept map from a Dimensions API search. Pass either a full DSL query (must return concepts data) or, using the -k option, a series of keywords.\"\"\"\n\n if examples:\n click.secho(CMD_LINE_EXAMPLES, fg=\"green\")\n return\n\n elif test:\n click.secho(\"Building test visualization..\", fg=\"green\")\n main.test_run(title=title)\n return\n\n elif keywords or dslquery:\n # main action\n\n if keywords:\n q = utils.dsl_generate_query_from_search_keywords(keywords)\n final_query = q\n\n elif dslquery:\n # the main arg\n final_query = dslquery[0]\n if verbose: click.secho(\"Q = \" + dslquery[0], dim=True)\n\n\n df = main.build_viz(dslquery=final_query, cached_data=None, score=score, freq=freq, nnodes=nodes, nedges=edges, title=title)\n\n while True:\n # keep re-rendering using extracted data (only if params were not passed)\n if not (score and freq and nodes and edges):\n if click.confirm('-------------\\n> Try again?'):\n main.build_viz(dslquery=final_query, cached_data=[df], title=title, use_defaults=False) \n else:\n break\n\n else:\n click.echo(ctx.get_help())\n return\n\n\n\nif __name__ == '__main__':\n main_cli()\n","sub_path":"dice/main_cli.py","file_name":"main_cli.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"301092869","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nclass Solution:\n def reverse(self, x: int) -> int:\n if x>=0:\n if int(str(x)[::-1]) >= 2**31-1:\n return 0\n else:\n return int(str(x)[::-1])\n else:\n if int(str(x)[0]+str(x)[:0:-1])<=-2**31:\n return 0\n else:\n return int(str(x)[0]+str(x)[:0:-1])\n\n","sub_path":"Leetcode/7#_Reverse Integer_06170224.py","file_name":"7#_Reverse Integer_06170224.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"413643339","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 18 11:40:34 2019\n\n@author: shlomi\ndata size scaling estimation: 10 MB for ~120 items\nmax : 100,000 items ~ 8.3 GB\ntypical year : 55000 items ~ 4.2 GB (one year, all months, all levels,\n 4 times daily, 1.25x1.25 lat/lon grid)\nHalf year : ~2.1 GB\nwhole field = 40 years x 2 halves x 2.1 GB = 170.1 GB\ntime= ~8 hours per half a year, whole field= ~ 27 days\n5 fields = 850.5 GB, can parralize to take the same amount of time\n\"\"\"\n\n\ndef date_range_to_monthly_request_string(\n start_date='1979-01-01', end_date='2019-12-01'):\n import pandas as pd\n from itertools import groupby\n import numpy as np\n \"\"\"accepts start_date and end_date and parses it to a continous monthly\n seperated ecmwf-api request time string. returns the dates in datetime\n numpy format and a dict of decade as key and corresponding ecmwf date\n request string as value\"\"\"\n dates = pd.date_range(start_date, end_date, freq='MS')\n decades = np.array([list(g)\n for k, g in groupby(dates, lambda i: i.year // 10)])\n dec_value = []\n dec_key = []\n for dec in decades:\n dates_list = []\n decade_dates = dec\n for date in decade_dates:\n formatted_date = date.strftime('%Y%m%d')\n dates_list.append(formatted_date)\n dec_value.append('/'.join(dates_list))\n year = dec[0].year\n dec_key.append(str(10 * divmod(year, 10)[0]))\n return dates, dict(zip(dec_key, dec_value))\n\n\nclass Error(Exception):\n \"\"\"Base class for other exceptions\"\"\"\n pass\n\n\nclass Halfnot1or2(Error):\n \"\"\"Raised when the half is not 1 or 2\"\"\"\n def __init__(self, message):\n self.message = message\n pass\n\n\nclass FieldnotFound(Error):\n \"\"\"Raised when the field not found in any of the dicts of era5 variable\"\"\"\n def __init__(self, message):\n self.message = message\n pass\n\n\nclass era5_variable:\n def __init__(self, era5p1_flag=False, start_year=1979, end_year=2019):\n self.start_year = start_year # do not change this until era5 publishes more data\n self.end_year = end_year # era5 reanalysis data lags real time with 2-3 months\n self.pressure = {'phi': 'geopotential',\n 'T': 'temperature',\n 'U': 'u_component_of_wind',\n 'V': 'v_component_of_wind',\n 'omega': 'vertical_velocity',\n 'div': 'divergence',\n 'PV': 'potential_vorticity',\n 'CC': 'fraction_of_cloud_cover',\n 'O3': 'ozone_mass_mixing_ratio',\n 'RH': 'relative_humidity',\n 'VO': 'vorticity',\n 'CIWC': 'specific_cloud_ice_water_content',\n 'Q': 'specific_humidity',\n 'CSWC': 'specific_snow_water_content',\n 'CLWC': 'specific_cloud_liquid_water_content',\n 'CRWC': 'specific_rain_water_content'}\n self.single = {'MSL': 'mean_sea_level_pressure',\n '2T': '2m_temperature',\n 'E': 'evaporation',\n 'TP': 'total_precipitation',\n '10WU': '10m_u_component_of_wind',\n '10WV': '10m_v_component_of_wind',\n 'SP': 'surface_pressure',\n 'TCWV': 'total_column_water_vapour'}\n self.land = {'SN_ALB': 'snow_albedo',\n 'SN_CVR': 'snow_cover',\n 'SN_DWE': 'snow_depth_water_equivalent'}\n self.complete = {'MTTSWR': ['235001', 'Mean temperature tendency' +\n ' due to short-wave radiation'],\n 'MTTLWR': ['235002', 'Mean temperature tendency'\n + ' due to long-wave radiation'],\n 'MTTPM': ['235005', 'Mean temperature tendency due '\n + ' to parametrisations'],\n\n 'LTI': ['151201', 'Temperature increment from ' +\n 'relaxation term'],\n 'MUTPM': ['235007', 'Mean eastward wind tendency due to parametrisations'],\n 'T_ML': ['130', 'Temperature from Model Levels'],\n 'U_ML': ['131', 'U component of wind velocity(zonal) from Model Levels'],\n 'V_ML': ['132', 'V component of wind velocity(meridional) from Model Levels'],\n 'Q_ML': ['133', 'Specific humidity from Model Levels']}\n self.era5p1_flag = era5p1_flag\n if era5p1_flag:\n self.start_year = 2000\n self.end_year = 2006\n def list_var(self, var):\n return [x for x in var.keys()]\n\n def list_years(self):\n import numpy as np\n self.years = np.arange(self.start_year, self.end_year + 1).tolist()\n return self.years\n\n def list_vars(self):\n single = self.list_var(self.single)\n pressure = self.list_var(self.pressure)\n complete = self.list_var(self.complete)\n land = self.list_var(self.land)\n return single + pressure + complete + land\n\n def get_model_name(self, field):\n self.field = field\n if field in self.single.keys():\n self.model_name = 'reanalysis-era5-single-levels'\n var = self.single[field]\n print('Single level model selected...')\n return cds_single(var)\n elif field in self.land.keys():\n self.model_name = 'reanalysis-era5-land'\n var = self.land[field]\n print('Land model selected...')\n return cds_single(var)\n elif field in self.pressure.keys():\n self.model_name = 'reanalysis-era5-pressure-levels'\n var = self.pressure[field]\n print('Pressure level model selected...')\n return cds_pressure(var)\n elif field in self.complete.keys():\n if self.era5p1_flag:\n self.model_name = 'reanalysis-era5.1-complete'\n print('ERA5.1 model selected with years set to 2000-2006!')\n else:\n self.model_name = 'reanalysis-era5-complete'\n var = self.complete[field][0]\n print('Complete model selected...working with MARS keywords.')\n return cds_mars(var)\n else:\n raise FieldnotFound('Field not found in any dicts')\n\n def show_options(self):\n print('The various fields that can be downloaded with this script:')\n self.show('pressure')\n self.show('single')\n self.show('complete')\n self.show('land')\n\n def show(self, modelname):\n if modelname == 'pressure':\n print('Pressure level fields:')\n for key, value in self.pressure.items():\n print(key + ':', value)\n print('')\n elif modelname == 'land':\n print('Land fields:')\n for key, value in self.land.items():\n print(key + ':', value)\n print('')\n elif modelname == 'single':\n print('Single level fields:')\n for key, value in self.single.items():\n print(key + ':', value)\n print('')\n elif modelname == 'complete':\n print('Complete level fields:')\n for key, value in self.complete.items():\n print(key + ':', value)\n print('')\n else:\n print('model name is invalid!')\n\n def info(self):\n print('More info about era5: ')\n print('https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis'\n + '-era5-pressure-levels?tab=form')\n print('')\n\n def desc(self):\n print('ERA5 Varaiable product python script downloader v1.0!')\n print('Author: Shlomi Ziskin Ziv, Atmospheric Sciences Dept., '\n + 'Hebrew University of Jerusalem.')\n print('Email: shlomiziskin@gmail.com')\n print('The following era5 fields can be downloaded and for now, the' +\n ' time period is between ' + str(self.start_year) + ' and '\n + str(self.end_year))\n print('Warning: if you want to download specific year, year option and'\n + ' half option are to be specified togather!')\n self.show_options()\n self.info()\n\n\nclass cds_single:\n def __init__(self, variable):\n self.variable = variable\n self.month = ['01', '02', '03', '04', '05', '06', '07', '08', '09',\n '10', '11', '12']\n self.time = ['00:00', '06:00', '12:00', '18:00']\n self.day = [\n '01', '02', '03',\n '04', '05', '06',\n '07', '08', '09',\n '10', '11', '12',\n '13', '14', '15',\n '16', '17', '18',\n '19', '20', '21',\n '22', '23', '24',\n '25', '26', '27',\n '28', '29', '30',\n '31']\n self.year = ['1979', '1980', '1981', '1982', '1983', '1984', '1985',\n '1986', '1987', '1989']\n self.product_type = 'reanalysis'\n self.grid = [1.25, 1.25]\n self.format = 'netcdf'\n\n def show(self):\n for key, value in vars(self).items():\n if isinstance(value, list):\n print(key + ':', ', '.join([str(x) for x in value]))\n else:\n print(key + ':', str(value))\n self.count_items()\n\n def listify_vars(self):\n vars_d = {k: [str(x)] for k, x in vars(self).items() if not\n isinstance(x, list)}\n vars(self).update(**vars_d)\n return self\n\n def from_dict(self, d):\n self.__dict__.update(d)\n return self\n\n def del_attr(self, name):\n delattr(self, name)\n return self\n\n def count_items(self):\n from numpy import prod\n max_items = 100000\n self.listify_vars()\n attrs_not_to_count = ['product_type', 'grid', 'format']\n count = prod([len(x) for k, x in vars(self).items() if k not in\n attrs_not_to_count])\n if count >= max_items:\n raise ValueError('Items count is: ' + str(count) +\n ' and is higher than ' + str(max_items) + ' !')\n print('Items count is: ' + str(count) + ' while max is: ' +\n str(max_items))\n return\n\n\nclass cds_pressure(cds_single):\n def __init__(self, variable):\n cds_single.__init__(self, variable)\n self.pressure_level = [\n '1', '2', '3',\n '5', '7', '10',\n '20', '30', '50',\n '70', '100', '125',\n '150', '175', '200',\n '225', '250', '300',\n '350', '400', '450',\n '500', '550', '600',\n '650', '700', '750',\n '775', '800', '825',\n '850', '875', '900',\n '925', '950', '975',\n '1000']\n self.year = '1979'\n\n def select_half(self, half):\n if half == 1:\n self.month = ['01', '02', '03', '04', '05', '06']\n elif half == 2:\n self.month = ['07', '08', '09', '10', '11', '12']\n else:\n raise Halfnot1or2('Half should be 1 or 2...')\n\n\nclass cds_mars:\n def __init__(self, param):\n # self.class = 'ea'\n self.param = param\n self.expver = '1'\n self.stream = 'oper'\n # self.step = '/'.join(['0', '6'])\n self.levtype = 'ml'\n self.levelist = '1/to/137'\n self.time = '00/06/12/18'\n self.grid = [1.25, 1.25]\n self.format = 'netcdf'\n if str(param).startswith('235'):\n self.type = 'fc'\n self.time = '06:00:00/18:00:00'\n self.step = '6/12'\n else:\n self.type = 'an'\n # 'date' : '2013-01-01',\n\n def from_dict(self, d):\n self.__dict__.update(d)\n return self\n\n def del_attr(self, name):\n delattr(self, name)\n return self\n\n def set_class_atr(self):\n setattr(self, 'class', 'ea')\n\n def show(self):\n for key, value in vars(self).items():\n if isinstance(value, list):\n# if key == 'date':\n# print(key + ':', value.split('/')[0] + ' to ' +\n# value.split('/')[-1])\n print(key + ':', ', '.join([str(x) for x in value]))\n else:\n print(key + ':', str(value))\n\n def get_date(self, year, half):\n if half == 1:\n self.date = str(year) + '01' + '01' + '/to/' + str(year) + '06' + '31'\n elif half == 2:\n self.date = str(year) + '07' + '01' + '/to/' + str(year) + '12' + '31'\n else:\n raise Halfnot1or2('Half should be 1 or 2...')\n\n\n#def get_custom_params(custom_fn, cds_obj):\n# import pandas as pd\n# df = pd.read_csv(custom_fn, skiprows=2)\n# dd = dict(zip(df.name.values, df.param.values))\n# c_dict = {}\n# c_dict['filename'] = dd.pop('filename')\n# if dd['stream'] == 'moda':\n# c_dict['monthly'] = True\n# cds_obj.from_dict(dd)\n# cds_obj.del_attr('step')\n# cds_obj.del_attr('time')\n# return cds_obj, c_dict\n\ndef get_custom_params(custom_fn, cds_obj):\n import json\n with open(custom_fn) as f:\n dd = json.load(f)\n c_dict = {}\n if 'suffix' in dd.keys():\n c_dict['suffix'] = dd.pop('suffix')\n if 'years' in dd.keys():\n c_dict['years'] = parse_mars_years(dd.pop('years'))\n if 'filename' in dd.keys():\n c_dict['filename'] = dd.pop('filename')\n if 'stream' in dd.keys():\n if dd['stream'] == 'moda':\n c_dict['monthly'] = True\n else:\n c_dict['monthly'] = False\n if 'to_delete' in dd.keys():\n to_delete_list = dd.pop('to_delete')\n for item_to_delete in to_delete_list:\n if item_to_delete in vars(cds_obj).keys():\n print('deleting {}'.format(item_to_delete))\n cds_obj = cds_obj.del_attr(item_to_delete)\n cds_obj.from_dict(dd)\n if 'step' in vars(cds_obj).keys():\n cds_obj = cds_obj.del_attr('step')\n # cds_obj.del_attr('time')\n return cds_obj, c_dict\n\n\ndef generate_filename(modelname, field, cds_obj, half=1, suffix=None):\n \"\"\"naming method for filenames using field (e.g., 'U', 'T')\n and year and half\"\"\"\n if 'single' in modelname.split('-') or 'land' in modelname.split('-'):\n years = '-'.join(str(v) for v in [cds_obj.year[0], cds_obj.year[-1]])\n value_list = ['era5', field, years]\n elif 'pressure' in modelname.split('-'):\n Half = 'H' + str(half)\n if isinstance(cds_obj.year, list):\n year = cds_obj.year[0]\n else:\n year = cds_obj.year\n value_list = ['era5', field, year, Half]\n elif 'complete' in modelname.split('-'):\n Half = 'H' + str(half)\n year = cds_obj.date[:4]\n if 'era5.1' in modelname.split('-'):\n value_list = ['era5p1', field, year, Half]\n else:\n value_list = ['era5', field, year, Half]\n if suffix is not None:\n value_list.append(suffix)\n filename = '_'.join(str(v) for v in value_list) + '.nc'\n return filename\n\n\ndef parse_mars_years(mars_years):\n import numpy as np\n start = mars_years.split('/to/')[0]\n end = mars_years.split('/to/')[-1]\n return np.arange(int(start), int(end) + 1)\n\n\ndef check_path(path):\n import os\n from pathlib import Path\n path = str(path)\n if not os.path.exists(path):\n raise argparse.ArgumentTypeError(path + ' does not exist...')\n return Path(path)\n\n\ndef check_params_file(filepath):\n from pathlib import Path\n filepath = Path(filepath)\n if not filepath.is_file():\n raise argparse.ArgumentTypeError('{} does not exist...'.format(filepath))\n return filepath\n\n\ndef get_decade(start_year, end_year):\n \"\"\"divide the time legnth into decades, return list of 10 years each\"\"\"\n import numpy as np\n all_years = np.arange(int(start_year), int(end_year) + 1)\n yr_chunks = [all_years[x: x+10] for x in range(0, len(all_years), 10)]\n return yr_chunks\n\n\ndef get_era5_field(path, era5_var, cds_obj, c_dict=None, dry=False):\n \"\"\"downloads the requested era5 fields within a specific year, six months\n (all days, 4x daily), saves it to path.\n available fields are in variable dictionary:\"\"\"\n import cdsapi\n import os\n import numpy as np\n\n def retrieve_era5(c, name, request, target, dry=False):\n if dry:\n print('Dry run! (no download command sent!)')\n return\n else:\n c.retrieve(name=name, request=request, target=target)\n print('Download complete!')\n return\n\n c = cdsapi.Client()\n modelname = era5_var.model_name\n if c_dict:\n if 'suffix' in c_dict.keys():\n suffix = c_dict['suffix']\n else:\n suffix = None\n if 'filename' in c_dict.keys():\n fn = c_dict['filename']\n else:\n fn = None\n if 'monthly' in c_dict.keys():\n monthly = c_dict.keys()\n else:\n monthly = None\n if 'years' in c_dict.keys():\n user_years = c_dict['years']\n else:\n user_years = None\n else:\n suffix = None\n fn = None\n monthly = None\n user_years = None\n if 'single' in modelname.split('-'):\n if user_years is not None:\n years = get_decade(user_years[0], user_years[-1])\n else:\n years = get_decade(era5_var.start_year, era5_var.end_year)\n for year in years:\n cds_obj.year = year.tolist()\n filename = generate_filename(modelname, era5_var.field, cds_obj,\n suffix=suffix)\n if (path / filename).is_file():\n print('{} already exists in {}, skipping...'.format(filename, path))\n continue\n else:\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename))\n retrieve_era5(c, name=modelname, request=vars(cds_obj),\n target=path / filename, dry=dry)\n print('')\n elif 'land' in modelname.split('-'):\n # years = get_decade(era5_var.start_year, era5_var.end_year)\n if user_years is not None:\n years = np.arange(2001, user_years[-1] + 1)\n else:\n years = np.arange(2001, era5_var.end_year + 1)\n cds_obj.year = [str(x) for x in years]\n filename = generate_filename(modelname, era5_var.field, cds_obj,\n suffix=suffix)\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename)) \n # for some strange reason the key 'product_type' kills the session:\n req_dict = vars(cds_obj)\n req_dict.pop('product_type')\n retrieve_era5(c, name=modelname, request=req_dict,\n target=path / filename, dry=dry)\n print('')\n elif 'pressure' in modelname.split('-'):\n if user_years is not None:\n years = user_years\n else:\n years = era5_var.list_years()\n halves = [1, 2]\n for year in years:\n cds_obj.year = year\n for half in halves:\n cds_obj.select_half(half)\n filename = generate_filename(modelname, era5_var.field,\n cds_obj, half, suffix=suffix)\n if (path / filename).is_file():\n print('{} already exists in {}, skipping...'.format(filename, path))\n continue\n else:\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename))\n retrieve_era5(c, name=modelname, request=vars(cds_obj),\n target=path / filename, dry=dry)\n print('')\n elif 'complete' in modelname.split('-'):\n if monthly and fn is not None:\n # monthly means\n dt_index, dates_dict = date_range_to_monthly_request_string()\n for decade, mon_dates in dates_dict.items():\n filename = '{}_{}.nc'.format(fn, decade)\n cds_obj.set_class_atr()\n cds_obj.date = mon_dates\n cds_obj.decade = decade\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename))\n retrieve_era5(c, name=modelname, request=vars(cds_obj),\n target=path / filename, dry=dry)\n elif monthly is None and fn is not None:\n filename = '{}.nc'.format(fn)\n cds_obj.set_class_atr()\n if 'date' in c_dict.keys():\n cds_obj.date = c_dict['date']\n # cds_obj.decade = decade\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename))\n retrieve_era5(c, name=modelname, request=vars(cds_obj),\n target=path / filename, dry=dry)\n elif monthly is None and fn is None:\n if user_years is not None:\n years = user_years\n else:\n years = era5_var.list_years()\n halves = [1, 2]\n cds_obj.set_class_atr()\n for year in years:\n for half in halves:\n cds_obj.get_date(year, half)\n filename = generate_filename(modelname, era5_var.field,\n cds_obj, half, suffix=suffix)\n if (path / filename).is_file():\n print('{} already exists in {}, skipping...'.format(filename, path))\n continue\n else:\n print('model_name: ' + modelname)\n cds_obj.show()\n print('proccesing request for ' + filename + ' :')\n print('target: {}/{}'.format(path, filename))\n retrieve_era5(c, name=modelname, request=vars(cds_obj),\n target=path / filename, dry=dry)\n print('')\n return\n\n\nif __name__ == '__main__':\n import argparse\n import sys\n era5_dummy = era5_variable()\n parser = argparse.ArgumentParser(description=era5_dummy.desc())\n optional = parser._action_groups.pop()\n required = parser.add_argument_group('required arguments')\n # remove this line: optional = parser...\n required.add_argument('--path', help=\"a full path to save in the cluster,\\\n e.g., /data11/ziskin/\", type=check_path)\n required.add_argument('--field', help=\"era5 field abbreviation, e.g., T,\\\n U , V\", type=str, choices=era5_dummy.list_vars(),\n metavar='Era5 Field name abbreviation')\n optional.add_argument('--custom', help='load custom file named \\\n cds_params.txt that contains filename and keywords',\n type=check_params_file)\n optional.add_argument('--syear', help='start year e.g., 1979', default=1979,\n type=int)\n optional.add_argument('--eyear', help='end year e.g., 2019', default=2019,\n type=int)\n optional.add_argument('--era5p1', help='ERA5.1 download flag, automatiacally sets the years to 2000-2006'\n ,action='store_true')\n optional.add_argument('--dry', help='dry run, no download command sent...'\n ,action='store_true')\n\n# metavar=str(cds.start_year) + ' to ' + str(cds.end_year))\n# optional.add_argument('--half', help='a spescific six months to download,\\\n# e.g, 1 or 2', type=int, choices=[1, 2],\n# metavar='1 or 2')\n parser._action_groups.append(optional) # added this line\n args = parser.parse_args()\n # print(parser.format_help())\n# # print(vars(args))\n if args.path is None:\n print('path is a required argument, run with -h...')\n sys.exit()\n elif args.field is None:\n print('field is a required argument, run with -h...')\n sys.exit()\n era5_var = era5_variable(start_year=args.syear, end_year=args.eyear, era5p1_flag=args.era5p1)\n cds_obj = era5_var.get_model_name(args.field)\n print('getting era5 all years, field: {}, saving to path: {}'.format(args.field, args.path))\n if args.custom is not None:\n cds_obj, custom_dict = get_custom_params(args.custom, cds_obj)\n get_era5_field(args.path, era5_var, cds_obj, custom_dict, dry=args.dry)\n else:\n get_era5_field(args.path, era5_var, cds_obj, dry=args.dry)\n","sub_path":"cds_era5_script.py","file_name":"cds_era5_script.py","file_ext":"py","file_size_in_byte":25646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"584730200","text":"from queue import Queue\nfrom typing import List\nfrom apscheduler.job import Job\n\nfrom IocManager import IocManager\nfrom infrastructor.data.RepositoryProvider import RepositoryProvider\nfrom infrastructor.logging.SqlLogger import SqlLogger\nfrom models.dao.aps import ApSchedulerJobEvent\nfrom models.dao.aps.ApSchedulerEvent import ApSchedulerEvent\nfrom models.dao.aps.ApSchedulerJob import ApSchedulerJob\n\n\nclass JobSchedulerService:\n def __init__(self,\n ):\n\n self.sql_logger = SqlLogger()\n self.repository_provider = RepositoryProvider()\n self.ap_scheduler_job_repository = self.repository_provider.get(ApSchedulerJob)\n self.ap_scheduler_event_repository = self.repository_provider.get(ApSchedulerEvent)\n self.ap_scheduler_job_event_repository = self.repository_provider.get(ApSchedulerJobEvent)\n self.job_scheduler_type = None\n self.job_event_queue: Queue = None\n\n # handle transaction and handle unexpected errors\n def job_transaction_handler(func):\n def inner(*args, **kwargs):\n try:\n result = func(*args, **kwargs)\n args[0].repository_provider.database_session_manager.commit()\n return result\n except Exception as ex:\n try:\n args[0].repository_provider.database_session_manager.rollback()\n args[0].repository_provider.database_session_manager.close()\n args[0].repository_provider.database_session_manager.connect()\n result = func(*args, **kwargs)\n args[0].repository_provider.database_session_manager.commit()\n return result\n except Exception as invalid_ex:\n print(ex)\n raise\n\n return inner\n\n def set_job_scheduler_type(self, job_scheduler_type):\n self.job_scheduler_type = job_scheduler_type\n\n def set_job_event_queue(self, job_event_queue: Queue):\n self.job_event_queue = job_event_queue\n\n def get_job_scheduler(self):\n job_scheduler = IocManager.injector.get(self.job_scheduler_type)\n return job_scheduler\n\n def get_job(self, job_id) -> Job:\n job_scheduler = self.get_job_scheduler()\n job: Job = job_scheduler.get_job(job_id)\n return job\n\n @job_transaction_handler\n def add_log(self, event, log_text):\n ap_scheduler_event: ApSchedulerEvent = self.ap_scheduler_event_repository.first(Code=event.code)\n job_detail = ''\n if hasattr(event, 'job_id') and event.job_id:\n ap_scheduler_job: List[ApSchedulerJob] = self.ap_scheduler_job_repository.first(JobId=event.job_id)\n job_id = ''\n if ap_scheduler_job is not None:\n job_id = ap_scheduler_job.Id\n job_detail = f'job_id:{job_id} - event_job_id:{event.job_id} - job_store:{event.jobstore} - '\n\n if hasattr(event, 'exception') and event.exception:\n self.sql_logger.error(f'{job_detail}{ap_scheduler_event.Name} - {log_text}')\n else:\n self.sql_logger.info(f'{job_detail}{ap_scheduler_event.Name} - {log_text}')\n\n @job_transaction_handler\n def add_job(self, event):\n job = self.get_job(event.job_id)\n\n ap_scheduler_job = ApSchedulerJob(JobId=job.id, NextRunTime=job.next_run_time, FuncRef=job.func_ref)\n self.ap_scheduler_job_repository.insert(ap_scheduler_job)\n self.ap_scheduler_job_repository.commit()\n job_args = (ap_scheduler_job.Id,) + job.args[1:]\n job.modify(args=job_args)\n\n @job_transaction_handler\n def update_job(self, event):\n job = self.get_job(event.job_id)\n ap_scheduler_job: List[ApSchedulerJob] = self.ap_scheduler_job_repository.first(JobId=event.job_id)\n if ap_scheduler_job is None:\n job.remove()\n if hasattr(job, 'next_run_time') and job.next_run_time:\n ap_scheduler_job.NextRunTime = job.next_run_time\n else:\n ap_scheduler_job.NextRunTime = None\n\n @job_transaction_handler\n def remove_job(self, event):\n ap_scheduler_job: ApSchedulerJob = self.ap_scheduler_job_repository.first(JobId=event.job_id)\n if ap_scheduler_job is not None:\n self.ap_scheduler_job_repository.delete(ap_scheduler_job)\n\n @job_transaction_handler\n def add_job_event(self, event):\n ap_scheduler_job = self.ap_scheduler_job_repository.first(JobId=event.job_id)\n ap_scheduler_event = self.ap_scheduler_event_repository.first(Code=event.code)\n ap_scheduler_job_event = ApSchedulerJobEvent(ApSchedulerEvent=ap_scheduler_event,\n ApSchedulerJob=ap_scheduler_job)\n self.ap_scheduler_job_event_repository.insert(ap_scheduler_job_event)\n self.job_event_queue.put(event, timeout=30)\n","sub_path":"src/scheduler/scheduler/JobSchedulerService.py","file_name":"JobSchedulerService.py","file_ext":"py","file_size_in_byte":4880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"265677703","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2014 AT&T Labs All Rights Reserved.\n# Copyright (C) 2014 University of Pennsylvania All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\n\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nimport socket\n\nfrom oslo.config import cfg\n\nfrom ryu.app import inception_util as i_util\nfrom ryu.app.inception_util import InceptionPacket\nfrom ryu.base import app_manager\nfrom ryu.controller import dpset\nfrom ryu.controller import handler\nfrom ryu.controller import ofp_event\nfrom ryu.lib import hub\nfrom ryu.lib.dpid import dpid_to_str\nfrom ryu.lib.dpid import str_to_dpid\nfrom ryu.lib.packet import arp\nfrom ryu.lib.packet import ethernet\nfrom ryu.lib.packet import packet\nfrom ryu.ofproto import ether\n\nLOGGER = logging.getLogger('ryu.app.inception')\n\nCONF = cfg.CONF\n\n\nclass InceptionReader(app_manager.RyuApp):\n \"\"\"Inception Cloud SDN controller.\"\"\"\n\n # Built-in Ryu modules, manage all connected switches: {dpid => datapath}\n _CONTEXTS = {\n 'dpset': dpset.DPSet\n }\n # Default OpenFlow versions\n OFP_VERSIONS = CONF.ofp_versions\n\n def __init__(self, *args, **kwargs):\n super(InceptionReader, self).__init__(*args, **kwargs)\n self.dpset = kwargs['dpset']\n self.dcenter_id = CONF.self_dcenter\n\n # RPC server for ARP update\n self.arp_rpc = ArpRpc()\n host_addr = socket.gethostbyname(socket.gethostname())\n rpc_server = SimpleXMLRPCServer((host_addr, CONF.rpc_port),\n allow_none=True)\n rpc_server.register_introspection_functions()\n rpc_server.register_instance(self.arp_rpc)\n hub.spawn(rpc_server.serve_forever)\n\n @handler.set_ev_cls(ofp_event.EventOFPPacketIn, handler.MAIN_DISPATCHER)\n def packet_in_handler(self, event):\n \"\"\"Handle when a packet is received.\"\"\"\n LOGGER.info('New packet_in received.')\n msg = event.msg\n datapath = msg.datapath\n dpid = dpid_to_str(datapath.id)\n in_port = str(msg.match['in_port'])\n packet = InceptionPacket(msg.data)\n self.process_packet_in(dpid, in_port, packet)\n\n def process_packet_in(self, dpid, in_port, packet):\n \"\"\"Process raw data received from dpid through in_port.\"\"\"\n # Handle ARP packet\n arp_header = packet.get_protocol(arp.arp)\n if arp_header:\n LOGGER.info(\"Handle ARP packet\")\n # Process ARP request\n if arp_header.opcode == arp.ARP_REQUEST:\n # Process ARP request\n src_ip = arp_header.src_ip\n src_mac = arp_header.src_mac\n dst_ip = arp_header.dst_ip\n\n LOGGER.info(\"ARP request: (ip=%s) query (ip=%s)\",\n src_ip, dst_ip)\n\n dst_vmac = self.arp_rpc.ip_to_mac.get(dst_ip)\n if dst_vmac is not None:\n LOGGER.info(\"Cache hit: (dst_ip=%s) <=> (vmac=%s)\",\n dst_ip, dst_vmac)\n # Send arp reply\n src_mac_reply = dst_vmac\n vmac_reply = src_mac\n src_ip_reply = dst_ip\n dst_ip_reply = src_ip\n self.send_arp_reply(dpid, in_port, src_ip_reply,\n src_mac_reply, dst_ip_reply,\n vmac_reply)\n\n else:\n LOGGER.info(\"Query failure: MAC for (dst_ip=%s)\"\n \"cannot be found\", dst_ip)\n\n def send_arp_reply(self, dpid, port, src_ip, src_mac, dst_ip, dst_mac):\n \"\"\"\n Construct an arp reply given the specific arguments\n and send it through switch connecting dst_mac\n \"\"\"\n # Forward ARP reply\n packet_reply = self.create_arp_packet(src_mac, dst_mac, dst_ip,\n src_ip, arp.ARP_REPLY)\n dst_datapath = self.dpset.get(str_to_dpid(dpid))\n dst_ofproto_parser = dst_datapath.ofproto_parser\n dst_ofproto = dst_datapath.ofproto\n actions_out = [dst_ofproto_parser.OFPActionOutput(int(port))]\n dst_datapath.send_msg(\n dst_ofproto_parser.OFPPacketOut(\n datapath=dst_datapath,\n buffer_id=0xffffffff,\n in_port=dst_ofproto.OFPP_LOCAL,\n data=packet_reply.data,\n actions=actions_out))\n LOGGER.info(\"Send ARP reply of (ip=%s) to (ip=%s): \", src_ip, dst_ip)\n\n def create_arp_packet(self, src_mac, dst_mac, dst_ip, src_ip, opcode):\n \"\"\"Create an Ethernet packet, with ARP packet inside\"\"\"\n\n arp_packet = arp.arp(opcode=opcode,\n dst_mac=dst_mac,\n src_mac=src_mac,\n dst_ip=dst_ip,\n src_ip=src_ip)\n eth_packet = ethernet.ethernet(ethertype=ether.ETH_TYPE_ARP,\n src=src_mac,\n dst=dst_mac)\n packet_out = packet.Packet()\n packet_out.add_protocol(eth_packet)\n packet_out.add_protocol(arp_packet)\n packet_out.serialize()\n\n return packet_out\n\n\nclass ArpRpc(object):\n \"\"\"Receives RPCs to update {IP => MAC} mapping\"\"\"\n def __init__(self):\n self.ip_to_mac = {}\n\n def update_local_arp(self, ip, vmac):\n \"\"\"For ARP_reader: update remote ip_mac mapping\"\"\"\n self.ip_to_mac[ip] = vmac\n","sub_path":"ryu/app/inception_reader.py","file_name":"inception_reader.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"203644091","text":"import pandas as pd\r\nimport numpy as np\r\nimport feather\r\nfrom sklearn.metrics import confusion_matrix, log_loss, classification_report, accuracy_score, roc_auc_score, roc_curve, mean_squared_error\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\r\nfrom skopt import BayesSearchCV\r\nfrom catboost import CatBoostClassifier,Pool\r\nimport os\r\nimport pickle\r\nfrom logging import StreamHandler, DEBUG, Formatter, FileHandler, getLogger\r\nimport warnings\r\nimport sys\r\nimport datetime\r\nwarnings.filterwarnings('ignore')\r\n\r\nlogger = getLogger(__name__)\r\n\r\nTRAIN = '../input/train.feather'\r\nTEST = '../input/test.feather'\r\n\r\nDIR = '../result/logfile'\r\n\r\nstart_time = datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\r\nlog_fmt = Formatter('%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s ')\r\nhandler = StreamHandler()\r\nhandler.setLevel('INFO')\r\nhandler.setFormatter(log_fmt)\r\nlogger.addHandler(handler)\r\n\r\nhandler = FileHandler(DIR + '_cat_train.log', 'a')\r\nhandler.setLevel(DEBUG)\r\nhandler.setFormatter(log_fmt)\r\nlogger.setLevel(DEBUG)\r\nlogger.addHandler(handler)\r\n\r\nlogger.info('start')\r\nlogger.info('CatBoost')\r\n\r\nargs = sys.argv\r\nid_feature = args[1]\r\ntarget_feature = args[2]\r\nprint(\"id_feature\", id_feature)\r\nprint(\"target_feature\", target_feature)\r\n\r\nlogger.info('install data')\r\ntrain = feather.read_dataframe(TRAIN)\r\ntest = feather.read_dataframe(TEST)\r\n\r\nfeatures = [c for c in train.columns if c not in [id_feature, target_feature]]\r\ntarget= train[target_feature]\r\nlogger.info('data install complete')\r\n\r\nlogger.info('----------Learning start----------')\r\nCLASS = 9\r\nn_folds = 5\r\n\r\nparams = {\r\n \"eval_metric\": \"AUC\",\r\n \"objective\": \"Logloss\",\r\n \"early_stopping_rounds\": 1000,\r\n \"learning_rate\": 0.01,\r\n \"iterations\": 10000,\r\n #\"subsample\": 0.6,\r\n \"colsample_bylevel\": 0.01,\r\n \"max_depth\": 10,\r\n #\"rsm\": 0.1,\r\n \"scale_pos_weight\": 5,\r\n #\"boosting\": \"Ordered\"\r\n}\r\n\r\nfolds = StratifiedKFold(n_splits=n_folds, shuffle=False, random_state=44000)\r\noof = np.zeros((len(train_df),CLASS))\r\npredictions = pd.DataFrame(test[id_feature])\r\nval_scores = []\r\nfeature_importance_df = pd.DataFrame()\r\nfeature_importance_df[\"feature\"] = features\r\nyp = np.zeros((test.shape[0] ,CLASS))\r\n\r\nfor fold_, (trn_idx, val_idx) in enumerate(folds.split(train.values, target.values)):\r\n print('Fold {}'.format(fold_+1))\r\n cat = CatBoostClassifier(**params)\r\n cat.fit(train.iloc[trn_idx][features], target.iloc[trn_idx])\r\n \r\n valid_result = xgb_model.predict_proba(train.iloc[val_idx][features])\r\n yp += xgb_model.predict_proba(test[features]) / n_folds\r\n \r\n oof[val_idx] = valid_result\r\n val_score = roc_auc_score(target[val_idx], np.argmax(valid_result, axis=1))\r\n val_scores.append(val_score)\r\n feature_importance_df[\"importance_fold\"+str(i)] = xgb_model.feature_importances_\r\n\r\nlogger.info('Learning end')\r\n\r\nlogger.info('-------Performance check and prediction-------')\r\nmean_score = np.mean(val_scores)\r\nstd_score = np.std(val_scores)\r\n\r\noof_prediction = np.argmax(oof, axis=1)\r\nall_score = roc_auc_score(target, oof_prediction)\r\nlogger.debug(\"Mean score: %.9f, std: %.9f. All score: %.9f.\" % (mean_score, std_score, all_score))\r\nprint(confusion_matrix(target, oof_prediction))\r\nprint(classification_report(target, oof_prediction))\r\n\r\npredictions[target_feature] = np.argmax(yp, axis=1)\r\n\r\n#logger.info('--------record oof contents--------')\r\n#path = \"../result/catboost_oof.csv\"\r\n#if os.path.isfile(path):\r\n# data = pd.read_csv(path)\r\n#else:\r\n# data = pd.DataFrame()\r\n#data[str(start_time)+str(target_feature)] = oof[\"predict\"]\r\n#data.to_csv(path, index=None)\r\n\r\nlogger.info('--------make submission file---------')\r\nsub_df = pd.DataFrame({str(id_feature):test[id_feature].values})\r\nsub_df[target_feature] = predictions[\"Result\"]\r\nsub_df.to_csv(\"../result/submission_cat_\"+str(score)+\".csv\", index=False)\r\n\r\nlogger.info('--------record submission contents--------')\r\npath = \"../result/catboost_submission_sofar.csv\"\r\nif os.path.isfile(path):\r\n data = pd.read_csv(path)\r\nelse:\r\n data = pd.DataFrame()\r\n data[id_feature] = sub_df[id_feature]\r\ndata = pd.concat([data, sub_df[target_feature]], axis=1)\r\ndata= data.rename(columns={str(target_feature):str(start_time[:4])+\"/\"+str(start_time[5:7])+\"/\"+str(start_time[8:10])+\"/\"+str(start_time[11:13])+\":\"+str(start_time[14:16])+\"/\"+str(score)[:7]})\r\ndata.to_csv(path, index=None)\r\n\r\nlogger.info('end')\r\n","sub_path":"kaggle/02_Santander_CTP2019/model/cat_train.py","file_name":"cat_train.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"69948302","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, num_input_channels=1, kernel=(3, 7), stride=1, num_output_channels=64):\n super().__init__()\n padding = (np.asarray(kernel) - 1) / 2\n padding = tuple(padding.astype(np.int))\n\n self.model = nn.Sequential(\n nn.Conv2d(in_channels=num_input_channels, out_channels=num_output_channels,\n kernel_size=kernel,\n padding=padding,\n stride=stride),\n nn.BatchNorm2d(num_features=num_output_channels),\n nn.PReLU()\n )\n\n def forward(self, input):\n return self.model(input)\n\n\nclass EncoderBlock(nn.Module):\n def __init__(self, num_input_channels=1, kernel=(3, 7), stride_conv=1, stride_pool=2, num_output_channels=64):\n super().__init__()\n self.basic = BasicBlock(num_input_channels, kernel, stride_conv, num_output_channels)\n self.pool = nn.MaxPool2d(kernel, stride_pool, return_indices=True)\n\n def forward(self, input):\n tmp = self.basic(input)\n out, indices = self.pool(tmp)\n return out, indices, tmp\n\n\nclass DecoderBlock(nn.Module):\n def __init__(self, num_input_channels=64, kernel=(3, 7), stride_conv=1, stride_pool=2, num_output_channels=64):\n super().__init__()\n self.basic = BasicBlock(num_input_channels * 2, kernel, stride_conv, num_output_channels)\n self.unpool = nn.MaxUnpool2d(kernel, stride_pool)\n\n def forward(self, input, indices, encoder_block):\n tmp = self.unpool(input, indices, output_size=encoder_block.size())\n tmp = torch.cat((encoder_block, tmp), dim=1)\n return self.basic(tmp)\n\n\nclass ClassifierBlock(nn.Module):\n def __init__(self, num_input_channels=64, kernel=(1, 1), stride_conv=1, num_classes=10):\n super().__init__()\n self.classify = nn.Sequential(\n nn.Conv2d(num_input_channels, num_classes, kernel, stride_conv),\n nn.Softmax2d()\n )\n\n def forward(self, input):\n return self.classify(input)\n\n\nclass RelayNet(nn.Module):\n def __init__(self, num_input_channels=1, kernel=(3, 3), stride_conv=1, stride_pool=2, num_output_channels=64,\n num_encoders=3, num_classes=10, kernel_classify=(1, 1)):\n super().__init__()\n self.encoders = nn.ModuleList([EncoderBlock(num_input_channels if i == 0 else num_output_channels, kernel,\n stride_conv, stride_pool, num_output_channels)\n for i in range(num_encoders)])\n self.bottleneck = BasicBlock(num_output_channels, kernel, stride_conv, num_output_channels)\n self.decoders = nn.ModuleList(\n [DecoderBlock(num_output_channels, kernel, stride_conv, stride_pool, num_output_channels)\n for _ in range(num_encoders)])\n self.classify = ClassifierBlock(num_output_channels, kernel_classify, stride_conv, num_classes)\n\n def forward(self, input):\n out = input\n encodings = list()\n for encoder in self.encoders:\n out, indices, before_maxpool = encoder(out)\n encodings.append((out, indices, before_maxpool))\n\n out = self.bottleneck(encodings[-1][0])\n\n for i, encoded in enumerate(reversed(encodings)):\n decoder = self.decoders[i]\n out = decoder(out, encoded[1], encoded[2])\n\n return self.classify(out)\n","sub_path":"relaynet.py","file_name":"relaynet.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"106900876","text":"import settings as s\nfrom pathlib import Path\nimport cv2\nimport rawpy\nimport os\nimport numpy as np\nimport pickle\nfrom utility import read_image, image_resize\nfrom data_storytelling_support import dominate_colors\n\n\ndef show_errors_gt_ff():\n assert Path.cwd().name == 'code'\n\n files = [p.resolve() for p in Path(s.output).glob(\"**/*\") if p.suffix.lower() in [\".jpg\"] if p.parent.name != 'faces' if not str(p.stem).endswith('dominatecolors')]\n for file in files:\n ret, image, pct_resize = read_image(file, True)\n if not ret:\n assert 1 == 2\n posList = []\n sidecar_file = Path(file.with_suffix('.pkl'))\n if sidecar_file.is_file():\n with (open(sidecar_file, \"rb\")) as openfile:\n posList = pickle.load(openfile)\n else:\n assert 1 == 2\n\n for pos in posList['ground_truth']:\n if not pos['mtcnn_found']:\n cv2.circle(image, (int(pos['x'] * pct_resize), int(pos['y'] * pct_resize)), 25,\n (102, 255, 0), 2)\n else:\n cv2.circle(image, (int(pos['x'] * pct_resize), int(pos['y'] * pct_resize)), 25,\n (0, 155, 255), 2)\n\n for each in posList['algorithm_faces']:\n bounding_box = each['box']\n if not each['confirmed']:\n cv2.rectangle(image,\n (int(bounding_box[0] * pct_resize), int(bounding_box[1] * pct_resize)),\n (int((bounding_box[0] + bounding_box[2]) * pct_resize), int((bounding_box[1] + bounding_box[3])* pct_resize)),\n (102, 255, 0),\n 2)\n else:\n cv2.rectangle(image,\n (int(bounding_box[0] * pct_resize), int(bounding_box[1] * pct_resize)),\n (int((bounding_box[0] + bounding_box[2]) * pct_resize), int((bounding_box[1] + bounding_box[3])* pct_resize)),\n (0, 155, 255),\n 2)\n\n while True:\n cv2.imshow('image', image)\n k = cv2.waitKey(1)\n if k == 32:\n break\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n show_errors_gt_ff()","sub_path":"Capstone 2 - Fútbol/reports/intermediary reports/images/code/show_errrors.py","file_name":"show_errrors.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"24126136","text":"from pattern.es import conjugate, INFINITIVE, tag\n\nfrase = 'Si trabajás mucho con computadoras, eventualmente encontrarás que te gustaría automatizar alguna tarea. Por ejemplo, podrías desear realizar una búsqueda y reemplazo en un gran número de archivos de texto, o renombrar y reorganizar un montón de archivos con fotos de una manera compleja. Tal vez quieras escribir alguna pequeña base de datos personalizada, o una aplicación especializada con interfaz gráfica, o un juego simple.'\n\n\ndef verbosInfinitivos(string):\n lista = []\n for x, tipo in tag(frase):\n if ((tipo == 'VB') or\n (tipo == 'VBZ') or\n (tipo == 'VBP') or\n (tipo == 'VBD') or\n (tipo == 'VBN') or\n (tipo == 'VBG')):\n lista.append(conjugate(x, INFINITIVE))\n return lista\n\n\nprint(verbosInfinitivos(frase))\n","sub_path":"Practica2/Eje5.py","file_name":"Eje5.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"103308516","text":"def fileNaming(names):\n result = []\n for name in names:\n if name not in result:\n result.append(name)\n else:\n k = 1\n new_name = name + \"(\" +str(k) + \")\"\n while new_name in result:\n k += 1\n new_name = name + \"(\" +str(k) + \")\"\n result.append(new_name)\n return result\n \nnames = [\"doc\", \n \"doc\", \n \"image\", \n \"doc(1)\", \n \"doc\"]\nprint(fileNaming(names))","sub_path":"fileNaming.py","file_name":"fileNaming.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"161656815","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('books', '0001_initial'),\n ('members', '0027_auto_20160215_1813'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Membership',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('membership_type', models.CharField(default='R', max_length=1, help_text='The type of membership.', choices=[('R', 'Regular'), ('W', 'Work-Trade'), ('S', 'Scholarship'), ('C', 'Complimentary')])),\n ('family_count', models.IntegerField(default=0, help_text='The number of ADDITIONAL family members included in this membership. Usually zero.')),\n ('start_date', models.DateField(help_text='The frist day on which the membership is valid.')),\n ('end_date', models.DateField(help_text='The last day on which the membership is valid.')),\n ('protected', models.BooleanField(default=False, help_text='Protect against further auto processing by ETL, etc. Prevents overwrites of manually enetered data.')),\n ('member', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, default=None, blank=True, to='members.Member', help_text='The member to whom this membership applies.', null=True)),\n ('purchase', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, to='books.Sale', help_text='The sale that includes this line item.', null=True)),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='MembershipGiftCardRedemption',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('redemption_date', models.DateField(default=django.utils.timezone.now, help_text='The date on which the gift card was redeemed.')),\n ],\n options={\n 'verbose_name': 'Gift card redemption',\n },\n ),\n migrations.CreateModel(\n name='MembershipGiftCardReference',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ],\n options={\n 'verbose_name': 'Membership gift card',\n },\n ),\n migrations.RemoveField(\n model_name='donationlineitem',\n name='purchase',\n ),\n migrations.RemoveField(\n model_name='membershipgiftcardlineitem',\n name='card',\n ),\n migrations.RemoveField(\n model_name='membershipgiftcardlineitem',\n name='purchase',\n ),\n migrations.RemoveField(\n model_name='paymentaka',\n name='member',\n ),\n migrations.AlterModelOptions(\n name='memberlogin',\n options={'verbose_name': 'Login'},\n ),\n migrations.AlterModelOptions(\n name='membershipgiftcard',\n options={'verbose_name': 'Gift card'},\n ),\n migrations.AlterModelOptions(\n name='paidmembershipnudge',\n options={'verbose_name': 'Renewal reminder'},\n ),\n migrations.DeleteModel(\n name='DonationLineItem',\n ),\n migrations.DeleteModel(\n name='MembershipGiftCardLineItem',\n ),\n migrations.DeleteModel(\n name='PaymentAKA',\n ),\n migrations.DeleteModel(\n name='Purchase',\n ),\n migrations.AddField(\n model_name='membershipgiftcardreference',\n name='card',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='members.MembershipGiftCard', help_text='The membership gift card being sold.'),\n ),\n migrations.AddField(\n model_name='membershipgiftcardreference',\n name='purchase',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, to='books.Sale', help_text='The sale that includes this line item.', null=True),\n ),\n migrations.AddField(\n model_name='membershipgiftcardredemption',\n name='card',\n field=models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, to='members.MembershipGiftCard', help_text='The membership gift card that was redeemed.'),\n ),\n migrations.AddField(\n model_name='membership',\n name='redemption',\n field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, blank=True, to='members.MembershipGiftCardRedemption', help_text='The associated membership gift card redemption, if any. Usually none.', null=True),\n ),\n ]\n","sub_path":"members/migrations/0028_auto_20160218_1014.py","file_name":"0028_auto_20160218_1014.py","file_ext":"py","file_size_in_byte":5044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"135751682","text":"import sqlite3\n\nfrom transformers.transformer import Transformer\n\nfrom openapi_server.models.attribute import Attribute\nfrom openapi_server.models.compound_info import CompoundInfo\nfrom openapi_server.models.gene_info import GeneInfo\nfrom openapi_server.models.gene_info_identifiers import GeneInfoIdentifiers\n\n\nclass HmdbTargets(Transformer):\n\n\n def __init__(self):\n super().__init__([], definition_file='targets_transformer_info.json')\n self.load_ids()\n\n\n def map(self, compound_list, controls):\n gene_list = []\n genes = {}\n for compound in compound_list:\n metabolite = self.find_metabolite(compound)\n if metabolite is not None:\n targets = self.find_targets(metabolite[0])\n for target in targets:\n gene_id = target['entrez']\n gene = genes.get(gene_id)\n if gene is None:\n gene = GeneInfo(\n gene_id = gene_id,\n identifiers = GeneInfoIdentifiers(entrez=gene_id),\n attributes = [Attribute(name='UniProtKB', value=target['uniprot'],source=self.info.name)]\n )\n gene_list.append(gene)\n genes[gene_id] = gene\n url = 'http://www.hmdb.ca/metabolites/'+metabolite[1][5:]\n gene.attributes.append(\n Attribute(name='mechanism of action', value='target of '+metabolite[2], source=self.info.name, url=url)\n )\n return gene_list\n\n\n def find_metabolite(self, compound_info: CompoundInfo):\n if compound_info.identifiers is not None:\n if compound_info.identifiers.hmdb is not None:\n for metabolite in find_metabolite_by_hmdb_id(compound_info.identifiers.hmdb):\n return metabolite\n if compound_info.identifiers.chebi is not None:\n for metabolite in find_metabolite_by_id(compound_info.identifiers.chebi):\n return metabolite\n if compound_info.identifiers.drugbank is not None:\n for metabolite in find_metabolite_by_id(compound_info.identifiers.drugbank):\n return metabolite\n if compound_info.identifiers.cas is not None:\n for metabolite in find_metabolite_by_id('CAS:'+compound_info.identifiers.cas):\n return metabolite\n return None\n\n\n def find_targets(self, bcid):\n target_list = []\n for target in find_targets(bcid):\n if target[1].startswith('UniProtKB:'):\n uniprot = target[1][10:]\n entrez = self.id_map.get(uniprot)\n if entrez is not None:\n target_list.append(\n {'uniprot':uniprot, 'entrez': 'NCBIGene:'+entrez, 'name': target[2]}\n )\n return target_list\n\n\n def load_ids(self):\n self.id_map = {}\n with open(\"UniProt2Entrez.txt\",'r') as f:\n first_line = True\n for line in f:\n if not first_line:\n row = line.strip().split('\\t')\n uniprot = row[0]\n entrez = row[1]\n self.id_map[uniprot] = entrez\n first_line = False\n\n\nclass HmdbIndications(Transformer):\n\n\n def __init__(self):\n super().__init__([], definition_file='indications_transformer_info.json')\n\n\nclass HmdbIndications(Transformer):\n\n\n variables = ['compounds']\n\n def __init__(self):\n super().__init__(self.variables, definition_file='metabolites_transformer_info.json')\n\n\nconnection = sqlite3.connect(\"HMDB-KS.db\", check_same_thread=False)\n\n\ndef find_targets(bcid):\n query = \"\"\"\n SELECT BEACON_CONCEPT.BEACON_CONCEPT_ID, BEACON_CONCEPT.ID, BEACON_CONCEPT.NAME\n FROM BEACON_STATEMENT\n INNER JOIN BEACON_CONCEPT ON BEACON_CONCEPT.BEACON_CONCEPT_ID = BEACON_STATEMENT.OBJECT_CONCEPT_ID\n WHERE SUBJECT_CONCEPT_ID = ?\n \"\"\"\n cur = connection.cursor()\n cur.execute(query,(bcid,))\n return cur.fetchall()\n\ndef find_metabolite_by_hmdb_id(id):\n query = \"\"\"\n SELECT BEACON_CONCEPT_ID, ID, NAME\n FROM BEACON_CONCEPT\n WHERE ID = ?\n \"\"\"\n cur = connection.cursor()\n cur.execute(query,(id,))\n return cur.fetchall()\n\n\ndef find_metabolite_by_id(id):\n query = \"\"\"\n SELECT BEACON_CONCEPT.BEACON_CONCEPT_ID, BEACON_CONCEPT.ID, BEACON_CONCEPT.NAME\n FROM BEACON_CONCEPT_SYNONYM\n INNER JOIN BEACON_CONCEPT ON BEACON_CONCEPT.BEACON_CONCEPT_ID = BEACON_CONCEPT_SYNONYM.BEACON_CONCEPT_ID\n WHERE SYNONYM = ? AND EXACT_MATCH = 1\n \"\"\"\n cur = connection.cursor()\n cur.execute(query,(id,))\n return cur.fetchall()\n\n","sub_path":"transformers/hmdb/python-flask-server/openapi_server/controllers/hmdb_controller.py","file_name":"hmdb_controller.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"446952293","text":"# coding=utf-8\n# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport functools\nimport os\nfrom contextlib import contextmanager\nfrom textwrap import dedent\n\nfrom pex.pex_info import PexInfo\n\nfrom pants.util.contextutil import open_zip, temporary_dir\nfrom pants_test.pants_run_integration_test import PantsRunIntegrationTest\n\n\nclass PythonBinaryIntegrationTest(PantsRunIntegrationTest):\n @staticmethod\n @contextmanager\n def caching_config():\n \"\"\"Creates a temporary directory and returns a pants configuration for passing to pants_run.\"\"\"\n with temporary_dir() as tmp_dir:\n yield {\n 'cache': {\n 'read': True,\n 'write': True,\n 'read_from': [tmp_dir],\n 'write_to': [tmp_dir]\n }\n }\n\n def assert_pex_attribute(self, pex, attr, value):\n self.assertTrue(os.path.exists(pex))\n pex_info = PexInfo.from_pex(pex)\n self.assertEqual(getattr(pex_info, attr), value)\n\n def test_zipsafe_caching(self):\n test_project = 'testprojects/src/python/cache_fields'\n test_build = os.path.join(test_project, 'BUILD')\n test_src = os.path.join(test_project, 'main.py')\n test_pex = 'dist/cache_fields.pex'\n zipsafe_target_tmpl = \"python_binary(source='main.py', zip_safe={})\"\n\n with self.caching_config() as config, self.mock_buildroot() as buildroot, buildroot.pushd():\n build = functools.partial(\n self.run_pants_with_workdir,\n command=['binary', test_project],\n workdir=os.path.join(buildroot.new_buildroot, '.pants.d'),\n config=config,\n build_root=buildroot.new_buildroot\n )\n\n buildroot.write_file(test_src, '')\n\n # Create a pex from a simple python_binary target and assert it has zip_safe=True (default).\n buildroot.write_file(test_build, \"python_binary(source='main.py')\")\n self.assert_success(build())\n self.assert_pex_attribute(test_pex, 'zip_safe', True)\n\n # Simulate a user edit by adding zip_safe=False to the target and check the resulting pex.\n buildroot.write_file(test_build, zipsafe_target_tmpl.format('False'))\n self.assert_success(build())\n self.assert_pex_attribute(test_pex, 'zip_safe', False)\n\n # Simulate a user edit by adding zip_safe=True to the target and check the resulting pex.\n buildroot.write_file(test_build, zipsafe_target_tmpl.format('True'))\n self.assert_success(build())\n self.assert_pex_attribute(test_pex, 'zip_safe', True)\n\n def test_platforms(self):\n \"\"\"Ensure that changing platforms invalidates the generated pex binaries.\"\"\"\n\n def numpy_deps(deps):\n return [d for d in deps if 'numpy' in d]\n def assertInAny(substring, collection):\n self.assertTrue(any(substring in d for d in collection),\n 'Expected an entry matching \"{}\" in {}'.format(substring, collection))\n def assertNotInAny(substring, collection):\n self.assertTrue(all(substring not in d for d in collection),\n 'Expected an entry matching \"{}\" in {}'.format(substring, collection))\n test_project = 'testprojects/src/python/cache_fields'\n test_build = os.path.join(test_project, 'BUILD')\n test_src = os.path.join(test_project, 'main.py')\n test_pex = 'dist/cache_fields.pex'\n\n with self.caching_config() as config, self.mock_buildroot() as buildroot, buildroot.pushd():\n config['python-setup'] = {\n 'platforms': None\n }\n build = functools.partial(\n self.run_pants_with_workdir,\n command=['binary', test_project],\n workdir=os.path.join(buildroot.new_buildroot, '.pants.d'),\n config=config,\n build_root=buildroot.new_buildroot\n )\n\n buildroot.write_file(test_src, '')\n\n buildroot.write_file(test_build,\n dedent(\"\"\"\n python_binary(source='main.py', dependencies=[':numpy'])\n python_requirement_library(\n name='numpy',\n requirements=[\n python_requirement('numpy==1.14.5')\n ]\n )\n\n \"\"\")\n )\n # When only the linux platform is requested,\n # only linux wheels should end up in the pex.\n config['python-setup']['platforms'] = ['linux-x86_64']\n build()\n\n with open_zip(test_pex) as z:\n deps = numpy_deps(z.namelist())\n assertInAny('manylinux', deps)\n assertNotInAny('macosx', deps)\n\n # When both linux and macosx platforms are requested,\n # wheels for both should end up in the pex.\n config['python-setup']['platforms'] = [\n 'linux-x86_64',\n 'macosx-10.13-x86_64']\n build()\n\n with open_zip(test_pex) as z:\n deps = numpy_deps(z.namelist())\n assertInAny('manylinux', deps)\n assertInAny('macosx', deps)\n","sub_path":"tests/python/pants_test/backend/python/tasks/test_python_binary_integration.py","file_name":"test_python_binary_integration.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"516728222","text":"\"\"\"AuthenticationApp Views\nCreated by Naman Patwari on 10/4/2016.\n\"\"\"\n\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\n\nfrom .forms import LoginForm, RegisterForm, UpdateForm, UpdateStudentForm, UpdateProfessorForm, UpdateEngineerForm\n\nfrom .models import MyUser, Student, Professor, Engineer,Platform,Skill\nfrom CompaniesApp.models import Company\n\n\n\n\n\n# Auth Views\n\ndef auth_login(request):\n form = LoginForm(request.POST or None)\n next_url = request.GET.get('next')\n if next_url is None:\n next_url = \"body.html\"\n if form.is_valid():\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n user = authenticate(email=email, password=password)\n if user is not None:\n messages.success(request, 'Success! Welcome, ' + (user.first_name or \"\"))\n login(request, user)\n '''\n if request.user.is_professor:\n # redirect to teacher index\n return HttpResponseRedirect(reverse('TeacherApp:index'))\n '''\n\n return render(request, 'body.html') \n \n\n \n else:\n messages.warning(request, 'Invalid username or password.')\n\n context = {\n \"form\": form,\n \"page_name\": \"Login\",\n \"button_value\": \"Login\",\n \"links\": [\"register\"],\n }\n return render(request, 'auth_form.html', context)\n\n\ndef auth_logout(request):\n logout(request)\n messages.success(request, 'Success, you are now logged out')\n return render(request, 'body.html')\n\n\ndef auth_register(request):\n if request.user.is_authenticated():\n return HttpResponseRedirect(\"/\")\n\n form = RegisterForm(request.POST or None)\n if form.is_valid():\n new_user = MyUser.objects.create_user(email=form.cleaned_data['email'],\n password=form.cleaned_data[\"password2\"],\n first_name=form.cleaned_data['firstname'],\n last_name=form.cleaned_data['lastname'])\n choice = form.cleaned_data['choice']\n #print('you selected' + choice)\n new_user.save()\n\n\n # Registering either student teacher or engineer\n if choice == 'Student':\n #setting the user attirubte to be as a student\n new_user.is_student = True\n new_user.save()\n #creating the student object with the default attributes, put it as NONE first as you need to initialise it\n new_student = Student(user=new_user,major=None)\n new_student.save()\n elif choice == 'Professor':\n new_user.is_professor = True\n new_user.save()\n\n new_professor = Professor(user=new_user, university = None, teachClass = None, phone = None) # note: maybe we do not need to give the special attributes, since it is null : true.)\n new_professor.save()\n elif choice == 'Engineer':\n new_user.is_engineer = True\n new_user.save()\n\n new_engineer = Engineer(user=new_user, company = None, position = None, phone = None)\n new_engineer.save()\n\n login(request, new_user);\n messages.success(request, 'Success! Your account was created.')\n return render(request, 'body.html')\n\n context = {\n \"form\": form,\n \"page_name\": \"Register\",\n \"button_value\": \"Register\",\n \"links\": [\"login\"],\n }\n return render(request, 'auth_form.html', context)\n\n\n@login_required\ndef update_profile(request):\n form = UpdateForm(request.POST or None, instance=request.user)\n # form_2_student = UpdateStudentForm(request.POST or None, instance=request.user)\n if request.user.is_student:\n form_2 =UpdateStudentForm(request.POST or None, instance=request.user.student)\n elif request.user.is_professor:\n form_2 =UpdateProfessorForm(request.POST or None, instance=request.user.professor)\n elif request.user.is_engineer:\n form_2 =UpdateEngineerForm(request.POST or None, instance=request.user.engineer) \n else:\n form_2 = None\n\n\n\n # print(request.user.student.pk)\n #print(request.user.student.year)\n\n\n if request.user.is_student:\n form_2 = UpdateStudentForm(request.POST or None, instance = request.user.student)\n if form.is_valid() and form_2.is_valid():\n #print(\"the pk of the user is \" + request.user.id)\n # have to get the child object of the user first (either \"Student\" / \"professor\" or \"enginneer\")\n #print(form_2.cleaned_data['testing'])\n student = request.user.student\n student.major = form_2.cleaned_data['major']\n\n student.platform.clear()\n student.save()\n for i in form_2.cleaned_data['platform']:\n #plat = Platform(platform=i)\n #plat.save()\n\n plat = Platform.objects.get(platform=i)\n\n # print(type(platform))\n #print(type(i))\n\n #platform.save()\n\n student.platform.add(plat)\n student.save()\n\n for i in form_2.cleaned_data['skill']:\n #skill = Skill(skill=i)\n #skill.save()\n student.skill.add(i)\n student.save()\n\n\n\n #platform = Platform(platform=form_2.cleaned_data[''])\n\n\n #Skill = form_2.cleaned_data['skills']\n # student.skills = form_2.cleaned_data['skills']\n # student.platforms = form_2.cleaned_data['platforms']\n #print(form_2.cleaned_data['platforms'])\n\n student.year = form_2.cleaned_data['year']\n\n #color = form_2.cleaned_data['favorite_colors']\n\n\n\n student.save()\n form.save()\n #form_2.save()\n\n messages.success(request, 'Success, your profile was saved!')\n\n elif request.user.is_professor:\n\n if form.is_valid() and form_2.is_valid():\n\n professor = request.user.professor\n professor.university = form_2.cleaned_data['university']\n professor.teachClass.create(title = form_2.cleaned_data['teachClass'])\n professor.phone = form_2.cleaned_data['phone']\n form.save()\n professor.save()\n messages.success(request, 'Success, your profile was saved!')\n messages.success(request, 'you are a professor')\n return HttpResponseRedirect(reverse('TeacherApp:index'))\n\n elif request.user.is_engineer:\n\n if form.is_valid() and form_2.is_valid():\n engineer = request.user.engineer\n company = Company.objects.get(pk=form_2.cleaned_data['company'].id)\n company.members.add(request.user)\n #engineer.company = form_2.cleaned_data['company']\n\n engineer.position = form_2.cleaned_data['position']\n engineer.phone = form_2.cleaned_data['phone']\n form.save()\n form_2.save()\n engineer.save()\n messages.success(request, 'Success, your profile was saved!')\n\n else:\n\n if form.is_valid():\n form.save()\n messages.success(request, 'Success, your profile was saved!')\n\n\n\n context = {\n \"form\": form,\n \"form_2\": form_2,\n \"page_name\": \"Update\",\n \"button_value\": \"Update\",\n \"links\": [\"logout\"],\n }\n return render(request, 'auth_form.html', context)","sub_path":"AuthenticationApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"571563206","text":"#!/usr/bin/env python\n\nfrom application import *\nimport sys, random\nfrom progress.bar import Bar\n\n@development_only\ndef populate_friends(username, num):\n with manage_session() as s:\n user = User.get_by_name(username, s)\n user_friends, x = fetch_friends_for_user(username, s)\n for f in user_friends:\n delete_friend(username, f.username, s)\n \n letters = \"abcdefghijklmnopqrstuvwxyz\"\n digits = \"2345678901234567890123456789\"\n users_list = []\n for i in range(num):\n letter = letters[i % len(letters)]\n num_digits = int(random.gauss(8, 4))\n users_list.append(letter + digits[:num_digits])\n\n bar = Bar(\"Populating friends\", max=num)\n for u in users_list:\n if not user_exists(u, s):\n create_user(u, u[0], s)\n added_user = User.get_by_name(u, s)\n send_friend_request(user, added_user, s)\n accept_friend_request(user, added_user, s)\n bar.next()\n bar.finish()\n \n\nif __name__ == \"__main__\":\n username = sys.argv[1]\n number = int(sys.argv[2])\n populate_friends(username, number)\n","sub_path":"bin/friend_gen.py","file_name":"friend_gen.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"119788314","text":"import os\nimport sys\nimport logging\nimport time\nimport math\nimport ConfigParser\nimport pickle\nimport itertools\n\nimport utils.colored_logging\n\nlog = logging.getLogger('displaynode')\nlog.info(\"-- DisplayNode --\")\n\nimport pygame\nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nimport utils.utils\nfrom utils.utils import *\n\nimport zmq\n\nimport pygrend\n \nSCREEN_SIZE = (800, 600)\n#SCREEN_SIZE = (0, 0)\nFRAMERATE = 60\nSPEED = 0.5\nANIMATION_TIME = 1.5\n\nDEFAULT_FONT = None\n\nFACTOR1 = 0.2\nFACTOR2 = 0.3\n\nDARK_ORDER = [-5,-4,-3,-2,-1,5,4,3,2,1,0]\nDARK_COLOR1 = [FACTOR1,FACTOR1,FACTOR1,0.7]\nDARK_COLOR2 = [FACTOR2,FACTOR2,FACTOR2,0.8]\n\nWHITE_ORDER = DARK_ORDER[:]\nWHITE_ORDER.reverse()\nWHITE_COLOR1 = [1.0,1.0,1.0,.0] \nWHITE_COLOR2 = [1.0,1.0,1.0,.3]\n \nclass DisplayNode:\n def __init__(self):\n self.render_cnt = 0\n self.render_window = 100\n self.pull_sg_window = 100\n self.running = True\n self.screen = None\n self.size = self.weight, self.height = None, None\n self.scene_graph = {}\n \n self.order = DARK_ORDER\n self.color1 = DARK_COLOR1\n self.color2 = DARK_COLOR2\n self.fonts = {}\n self.width = None\n self.height = None\n self.flags = None\n self.clock = None\n self.clock = pygame.time.Clock()\n self.rt = 0\n self.pt = 0\n \n self.context = zmq.Context(2)\n self.event_sock = self.context.socket(zmq.PUB)\n self.scene_graph_sock = self.context.socket(zmq.PULL)\n #self.event_sock.bind(\"tcp://*:5556\")\n self.event_sock.bind(\"ipc://pygrend_zvent.ipc\")\n self.scene_graph_sock.bind (\"ipc://pygrend_sg.ipc\")\n def init(self):\n pygame.init()\n pygame.font.init()\n# self.screen = pygame.display.set_mode(\n# self.size#, HWSURFACE|OPENGL|DOUBLEBUF\n# )\n self.font = self.get_font(28)\n self.clock = pygame.time.Clock()\n self.flags = HWSURFACE|OPENGL|DOUBLEBUF|RESIZABLE#|FULLSCREEN\n self.screen = pygame.display.set_mode(SCREEN_SIZE, self.flags)\n self.width = self.screen.get_width()\n self.height = self.screen.get_height()\n \n self.projection_setup()\n self.gl_setup()\n \n pygame.display.set_caption('DisplayNode')\n pygame.event.set_allowed(None)\n pygame.event.set_allowed(\n [QUIT, KEYUP, KEYDOWN, \\\n VIDEORESIZE, VIDEOEXPOSE, MOUSEMOTION, \\\n MOUSEBUTTONUP, MOUSEBUTTONDOWN])\n self.running = True\n \n def send_event(self, event):\n #log.debug ('ENTER send_event()')\n zv = pygrend.Zvent()\n if event.type == pygame.MOUSEMOTION:\n zv.__dict__ = {'type':event.type,\n 'pos':event.pos,\n 'rel':event.rel,\n 'button':event.buttons}\n #log.debug( 'sending MOUSEMOTION @ (%d, %d)' % event.pos)\n elif event.type == pygame.MOUSEBUTTONUP or event.type == pygame.MOUSEBUTTONDOWN:\n zv.__dict__ = {'type':event.type,\n 'pos':event.pos,\n 'button':event.button}\n elif event.type == pygame.KEYUP:\n zv.__dict__ = {'type':event.type, \n 'key':event.key, \n 'mod':event.mod}\n if event.key == K_ESCAPE or event.key == K_q:\n zv.__dict__ = {'type':pygame.QUIT}\n self.running = False\n elif event.type == pygame.KEYDOWN:\n zv.__dict__ = {'type':event.type,\n 'unicode':event.unicode,\n 'key':event.key, \n 'mod':event.mod}\n if event.key == K_f:\n if self.flags & FULLSCREEN == FULLSCREEN:\n self.flags = self.flags ^ FULLSCREEN\n else:\n self.flags = self.flags | FULLSCREEN\n self.screen = pygame.display.set_mode((0,0), self.flags)\n self.projection_setup()\n elif event.type == pygame.QUIT:\n zv.__dict__ = {'type':event.type}\n self.running = False \n else:\n zv.__dict__ = {'type':event.type}\n pzv = pickle.dumps(zv)\n self.event_sock.send(pzv)\n def pull_sg_updates(self):\n try:\n s = self.scene_graph_sock.recv(zmq.NOBLOCK)\n cmd = pickle.loads(s)\n #for i in range(self.pull_sg_window):\n cnt = 0\n #while (cmd.command != 'brk'):\n while (cnt\n# Created: Thu Mar 23 22:30:19 2017 -0400\n#\n# Copyright (C) 2016 District Data Labs\n# For license information, see LICENSE.txt\n#\n# ID: test_elbow.py [] benjamin@bengfort.com $\n\n\"\"\"\nTests for the KElbowVisualizer\n\"\"\"\n\n##########################################################################\n## Imports\n##########################################################################\n\nfrom ..base import VisualTestCase\nfrom ..dataset import DatasetMixin\n\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans, MiniBatchKMeans\nfrom yellowbrick.cluster.elbow import KElbowVisualizer\nfrom yellowbrick.exceptions import YellowbrickValueError\n\n\n##########################################################################\n## KElbowVisualizer Test Cases\n##########################################################################\n\nclass KElbowVisualizerTests(VisualTestCase, DatasetMixin):\n\n def test_integrated_kmeans_elbow(self):\n \"\"\"\n Test no exceptions for kmeans k-elbow visualizer on blobs dataset\n\n See #182: cannot use occupancy dataset because of memory usage\n \"\"\"\n\n # Generate a blobs data set\n X,y = make_blobs(\n n_samples=1000, n_features=12, centers=6, shuffle=True\n )\n\n try:\n visualizer = KElbowVisualizer(KMeans(), k=4)\n visualizer.fit(X)\n visualizer.poof()\n except Exception as e:\n self.fail(\"error during k-elbow: {}\".format(e))\n\n def test_integrated_mini_batch_kmeans_elbow(self):\n \"\"\"\n Test no exceptions for mini-batch kmeans k-elbow visualizer\n\n See #182: cannot use occupancy dataset because of memory usage\n \"\"\"\n\n # Generate a blobs data set\n X,y = make_blobs(\n n_samples=1000, n_features=12, centers=6, shuffle=True\n )\n\n try:\n visualizer = KElbowVisualizer(MiniBatchKMeans(), k=4)\n visualizer.fit(X)\n visualizer.poof()\n except Exception as e:\n self.fail(\"error during k-elbow: {}\".format(e))\n\n def test_invalid_k(self):\n \"\"\"\n Assert that invalid values of K raise exceptions\n \"\"\"\n\n with self.assertRaises(YellowbrickValueError):\n model = KElbowVisualizer(KMeans(), k=(1,2,3,4,5))\n\n with self.assertRaises(YellowbrickValueError):\n model = KElbowVisualizer(KMeans(), k=\"foo\")\n","sub_path":"tests/test_cluster/test_elbow.py","file_name":"test_elbow.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"72"} +{"seq_id":"477112408","text":"import serial\nimport re\nimport math\n\nclass Four_spot_tester:\n \"\"\"A class used by the four spot tester to check the alignment of filter block assemblies\"\"\"\n def __init__(self, com=None):\n if com != None:\n self.ser = serial.Serial(com)\n print(\"Successfully connected to port \" + ser.name)\n self.positions = {'front': [[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]],\n 'back': [[0.0,0.0],[0.0,0.0],[0.0,0.0],[0.0,0.0]]}\n self.calibration = {'front': [0.0,0.0,70.695],'back': [0.0,0.0,120.547],\n 'origin': [0.0, 0.0, 0.0], 'angles': [0.0, 0.0, 0.0]}\n \n def set_calibration(self, location, output=None):\n if output == None:\n output = send_command('r1')\n x_value = re.search('X=(.*)mm,Y', output)\n y_value = re.search('Y=(.*)mm,S', output)\n self.calibration[location][0] = float(x_value.group(1))\n self.calibration[location][1] = float(y_value.group(1))\n \n def calibrate_laser(self):\n # Assign values\n x1 = self.calibration['front'][0]\n y1 = self.calibration['front'][1]\n z1 = self.calibration['front'][2]\n x2 = self.calibration['back'][0]\n y2 = self.calibration['back'][1]\n z2 = self.calibration['back'][2]\n \n # Calculate origin positions\n x0 = x1 - z1*((x2-x1)/(z2-z1))\n yaw = math.atan((x2-x1)/(z2-z1))*180/math.pi\n y0 = y1 - z1*((y2-y1)/(z2-z1))\n pitch = math.atan((y2-y1)/(z2-z1))*180/math.pi\n angle = math.atan(math.sqrt(math.pow(y2-y1,2)+math.pow(x2-x1,2))/(z2-z1))*180/math.pi\n \n # Store values\n self.calibration['origin'][0] = x0\n self.calibration['origin'][1] = y0\n self.calibration['angles'][0] = yaw\n self.calibration['angles'][1] = pitch\n self.calibration['angles'][2] = angle\n \n def set_position(self, location, channel, output=None):\n if output == None:\n output = send_command('r1')\n x_value = re.search('X=(.*)mm,Y', output)\n y_value = re.search('Y=(.*)mm,S', output)\n self.positions[location][channel][0] = float(x_value.group(1))\n self.positions[location][channel][1] = float(y_value.group(1))\n \n def send_command(self, command):\n input = command + '\\r'\n self.ser.write(input.encode('utf-8'))\n output = ''\n time.sleep(0.1)\n while ser.in_waiting > 0:\n output += ser.read().decode('utf-8')\n if output[-1:] == '!':\n break\n if output[-1:] == '>':\n output = output[:-1]\n if output[:2] == command:\n return output\n else:\n return None\n \n def get_yaw(self, channel):\n x1 = self.positions['front'][channel][0]\n x2 = self.positions['back'][channel][0]\n z1 = self.calibration['front'][2]\n z2 = self.calibration['back'][2]\n yaw_block = math.atan((x2-x1)/(z2-z1))*180/math.pi\n return self.calibration['angles'][0] - yaw_block\n \n def get_x_translation(self, channel):\n x1 = self.positions['front'][channel][0]\n x2 = self.positions['back'][channel][0]\n z1 = self.calibration['front'][2]\n z2 = self.calibration['back'][2]\n x0_block = x1 - z1*((x2-x1)/(z2-z1))\n return x0_block - self.calibration['origin'][0] - (channel * 0.99026807) # Make sure x axis is set up correctly!\n \n def get_pitch(self, channel):\n y1 = self.positions['front'][channel][1]\n y2 = self.positions['back'][channel][1]\n z1 = self.calibration['front'][2]\n z2 = self.calibration['back'][2]\n pitch_block = math.atan((y2-y1)/(z2-z1))*180/math.pi\n return self.calibration['angles'][1] - pitch_block\n \n def get_y_translation(self, channel):\n y1 = self.positions['front'][channel][1]\n y2 = self.positions['back'][channel][1]\n z1 = self.calibration['front'][2]\n z2 = self.calibration['back'][2]\n y0_block = y1 - z1*((y2-y1)/(z2-z1))\n return y0_block - self.calibration['origin'][1]\n \n def get_angle(self, channel):\n xb = self.positions['back'][channel][0] - self.positions['front'][channel][0]\n yb = self.positions['back'][channel][1] - self.positions['front'][channel][1]\n zb = self.calibration['back'][2] - self.calibration['front'][2]\n \n xa = self.calibration['back'][0] - self.calibration['front'][0]\n ya = self.calibration['back'][1] - self.calibration['front'][1]\n za = self.calibration['back'][2] - self.calibration['front'][2]\n \n dot_product = xa*xb + ya*yb + za*zb\n mag_a = math.sqrt(xa*xa + ya*ya + za*za)\n mag_b = math.sqrt(xb*xb + yb*yb + zb*zb)\n return math.acos(dot_product/(mag_a*mag_b))*180/math.pi\n \n \n def print_data(self):\n print(self.calibration)","sub_path":"four_spot_tester.py","file_name":"four_spot_tester.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"168151117","text":"# coding utf-8\n\n'''\nDevise an experiment to verify that get item and set item are O(1) for dictionaries.\n'''\n\nimport time, random\n\ndef dict_get_time(d, k):\n start = time.time()\n d.get(k)\n end = time.time()\n return end - start\n\ndef dict_set_time(d, k, v):\n start = time.time()\n d[k] = v\n end = time.time()\n return end - start\n\nif __name__ == '__main__':\n a_dict = {k: 0 for k in range(100000)}\n\n print('Dict get time: %f' % (dict_get_time(a_dict, random.randrange(len(a_dict)))))\n print('Dict set time: %f' % (dict_set_time(a_dict, random.randrange(len(a_dict)), random.randrange(10000))))\n \n ","sub_path":"Wk2/02_dict_getset.py","file_name":"02_dict_getset.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"22792747","text":"import os\nimport string\nimport enchant\nimport joblib as jl\nimport spacy\nimport numpy as np\nfrom spacy.lemmatizer import Lemmatizer\nfrom spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES\nfrom spacy.tokens import Doc\nimport spacy.attrs as spacy_attr\nfrom flashtext import KeywordProcessor\nfrom textacy.keyterms import key_terms_from_semantic_network\nfrom gensim.utils import simple_tokenize\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom key_item_extraction_en.extract import Extractor\n\n\nclass CandidateFilter(object):\n __STOPWORDS = {'method', 'comprising', 'comprise', 'claims', 'methods', 'present',\n 'invention', 'first', 'second', 'secondary', 'set', 'group', 'third',\n 'including'}\n nlp = spacy.load('en_core_web_sm')\n\n def __init__(self, basedir):\n self.extractor = Extractor()\n self.phrase_dict = jl.load(os.path.join(basedir, 'assets/phrase_frequent_dict.jl'))\n self.spell_checker = enchant.Dict('en_US')\n self.stopwords = STOPWORDS | set(string.ascii_lowercase) | self.__STOPWORDS | set(string.punctuation)\n # self.punctuations = set(string.punctuation)\n self.lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)\n\n def candidate_object(self, candidates):\n candidate_upper = []\n for item in candidates:\n if item.isupper() and len(item) > 1 and not self.spell_checker.check(item.lower()):\n if item not in candidate_upper:\n candidate_upper.append(item)\n candidates_normal = [item for item in candidates if not item.isupper()]\n words, phrases = self.candidate_classification(candidates_normal)\n high_freq_phrase, long_phrases, len_2_phrase = self.phrase_classification(phrases)\n\n return words, high_freq_phrase, long_phrases, len_2_phrase, candidate_upper\n\n def lemmatize_phrases(self, phrases):\n phrases_lemma = []\n for phrase in phrases:\n if phrase.isupper():\n phrases_lemma.append(phrase)\n else:\n tokens_list = phrase.lower().split()\n last_word = tokens_list[-1]\n modify_list = tokens_list[:-1]\n last_word_lemma = self.lemmatizer(last_word, 'NOUN')\n last_word_lemma_correct = [word for word in last_word_lemma if self.spell_checker.check(word)]\n if last_word_lemma_correct:\n modify_list.append(last_word_lemma_correct[0])\n word_lemma = ' '.join(modify_list)\n else:\n word_lemma = phrase\n\n phrases_lemma.append(word_lemma)\n return phrases_lemma\n\n def candidate_classification(self, candidates):\n \"\"\"\n candidate classification\n :param candidates: keyterm candidates\n :return: words,phrases\n \"\"\"\n words, phrases = [], []\n for candidate in candidates:\n item_len = len(candidate.split())\n if item_len >= 2:\n phrases.append(candidate)\n else:\n words.append(candidate)\n return words, phrases\n\n def phrase_classification(self, phrases):\n \"\"\"\n phrase classification\n :param phrases: phrase candidates\n :param phrase_dict: phrase-frequent dict\n :return: high_freq_phrase,low_freq_phrase(long_phrase,phrase_2)\n \"\"\"\n high_freq_phrase, long_phrases, len_2_phrase = [], [], []\n for phrase in phrases:\n phrase_tokens = phrase.split()\n phrase_len = len(phrase_tokens)\n joined_phrase = '_'.join(phrase_tokens)\n if joined_phrase in self.phrase_dict and self.phrase_dict[joined_phrase] > 500:\n high_freq_phrase.append(phrase)\n elif phrase_len == 2:\n len_2_phrase.append(phrase)\n elif phrase_len != 2:\n long_phrases.append(phrase)\n\n return high_freq_phrase, long_phrases, len_2_phrase\n\n def candidate_subset(self, candidate):\n subset_list = []\n element_list = candidate.split()\n for i in range(1, len(element_list)):\n first_item = '_'.join(element_list[:i])\n last_item = '_'.join(element_list[i:])\n if first_item:\n subset_list.append(first_item)\n if last_item:\n subset_list.append(last_item)\n return subset_list\n\n def subset_select(self, subset_list, phrase_dict):\n \"\"\"\n subset select from the low frequency candidates\n :param subset_list: low frequency candidate subset\n :param phrase_dict: phrase-freq dict\n :return: the max frequence subset\n \"\"\"\n item_candidate, subset_freq = [], []\n for item in subset_list[1:-1]:\n freq = phrase_dict.get(item, 0)\n subset_freq.append(freq)\n if subset_freq and max(subset_freq) > 500:\n max_freq_item = subset_list[subset_freq.index(max(subset_freq)) + 1].replace('_', ' ')\n item_candidate.append(max_freq_item)\n\n return item_candidate\n\n def long_phrase_analysis(self, long_phrase, phrase_dict):\n \"\"\"\n long phrase analysis on low frequence phrases\n :param long_phrase:\n :param phrase_dict:\n :return:\n \"\"\"\n phrases_subset = []\n for item in long_phrase:\n subset_list = self.candidate_subset(item)\n item_candidate = self.subset_select(subset_list, phrase_dict)\n phrases_subset.extend(item_candidate)\n return phrases_subset\n\n def handle_len_2_phrase(self, len_2_phrase):\n \"\"\"\n phrase2 analysis\n :param len_2_phrase: phrase length equal to 2\n :return: split the phrase2\n \"\"\"\n candidates = []\n for item in len_2_phrase:\n candidates.extend(item.split())\n return candidates\n\n def candidate_deeper(self, phrase_end):\n word_candidates, phrase_candidates = [], []\n for item in phrase_end:\n if ' ' in item or '_' in item:\n if item not in phrase_candidates:\n phrase_candidates.append(item)\n elif item not in word_candidates:\n word_candidates.append(item)\n return word_candidates, phrase_candidates\n\n def candidate_pagerank_single_tokenization(self, text, topn):\n spacy_doc = self.remove_stopwords(self.nlp(text))\n\n if len(spacy_doc) > 8:\n phrase_score = key_terms_from_semantic_network(\n spacy_doc, normalize=None, edge_weighting=u'cooc_freq',\n ranking_algo='pagerank', join_key_words=False, n_keyterms=topn)\n result = [phrase for (phrase, score) in phrase_score]\n else:\n result = [token.text for token in spacy_doc]\n return result\n\n def candidate_pagerank(self, text, topn):\n text_filter = [word for word in text.split() if word not in self.stopwords]\n if len(text_filter) > 8:\n doc = self.extractor.nlp(\" \".join(text_filter))\n phrases_with_score = key_terms_from_semantic_network(\n doc, normalize=None, edge_weighting=u'cooc_freq',\n ranking_algo='pagerank', join_key_words=False, n_keyterms=4 * topn)\n phrases_with_score = sorted(phrases_with_score, key=lambda i: (i[1], i[0]), reverse=True)\n result = phrases_with_score[:topn]\n else:\n result = [(token, 0) for token in text_filter]\n result = self.__remove_underscores(result)\n return result\n\n def join_token_in_phrases(self, phrase_list, text):\n keyword_dict = {}\n for phrase in phrase_list:\n phrase_format = '_'.join(phrase.split())\n keyword_dict[phrase_format] = [phrase]\n keyword_processor = KeywordProcessor()\n keyword_processor.add_keywords_from_dict(keyword_dict)\n new_text = keyword_processor.replace_keywords(text)\n new_text = ' '.join([word for word in simple_tokenize(new_text) if word not in self.stopwords])\n return new_text\n\n def candidate_pipeline(self, text):\n candidates = Extractor.extract_phrases_by_rules(text)\n words, high_freq_phrase, long_phrases, phrase_2, candidate_upper = self.candidate_object(candidates)\n phrases_subset = self.long_phrase_analysis(long_phrases, self.phrase_dict)\n candidates_list = self.handle_len_2_phrase(phrase_2)\n\n item_candidates = words + phrases_subset + candidates_list + high_freq_phrase\n word_candidates, phrase_candidates = self.candidate_deeper(item_candidates)\n phrases_lemma = self.lemmatize_phrases(phrase_candidates)\n\n return self.dedupe_list(candidates), phrases_lemma\n\n @staticmethod\n def dedupe_list(l):\n deduped_list = []\n for item in l:\n if item not in deduped_list:\n deduped_list.append(item)\n return deduped_list\n\n def remove_stopwords(self, doc):\n \"\"\"\n Remove stopwords from a Spacy *Doc* object without losing associated information,\n such as pos tag, lemma\n\n :param doc : spacy.tokens.doc.Doc\n spacy representation of the text\n :return spacy doc after removing stopwords\n \"\"\"\n kept_attrs = [spacy_attr.LOWER,\n spacy_attr.POS,\n spacy_attr.LOWER,\n spacy_attr.IS_PUNCT,\n spacy_attr.IS_ALPHA,\n spacy_attr.LEMMA,\n spacy_attr.LOWER,\n spacy_attr.IS_DIGIT,\n spacy_attr.IS_SPACE,\n spacy_attr.IS_STOP]\n\n token_array = doc.to_array(kept_attrs)\n index_to_removed = []\n for token in doc:\n if token.is_stop or token.lemma_ in self.stopwords:\n index_to_removed.append(token.i)\n new_token_array = np.delete(token_array, index_to_removed, axis=0)\n new_words = [t.text for i, t in enumerate(doc) if i not in index_to_removed]\n new_doc = Doc(doc.vocab, words=new_words)\n new_doc.from_array(kept_attrs, new_token_array)\n return new_doc\n\n @classmethod\n def __remove_underscores(cls, phrases):\n final_phrases = []\n for phrase,score in phrases:\n final_phrases.append((phrase.replace('_', ' '), score))\n return final_phrases\n","sub_path":"key_item_extraction_en/candidate_filter.py","file_name":"candidate_filter.py","file_ext":"py","file_size_in_byte":10432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"559342362","text":"from emannotationschemas.schemas.base import BoundSpatialPoint, NumericField, AnnotationSchema\nimport marshmallow as mm\n\n\nclass DerivedSpatialPoint(BoundSpatialPoint):\n dependent_chunk = NumericField(description='Chunk id for the point at the time the annotation was made',\n required=True)\n level = NumericField(description='Chunk level',\n required=False)\n\n\nclass DerivedTag(AnnotationSchema):\n '''Basic spatial tag using DerivedSpatialPoint information'''\n pt = mm.fields.Nested(DerivedSpatialPoint, required=True)\n tag = mm.fields.String(required=True, description=\"Description of point\")\n","sub_path":"emannotationschemas/schemas/derived_spatial_point.py","file_name":"derived_spatial_point.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"359381553","text":"from __future__ import absolute_import\n\nimport os\nimport pytest\nimport datarobot as dr\n\nBASE_MODEL_TEMPLATES_DIR = \"model_templates\"\nBASE_DEV_ENV_DIR = \"dev_env\"\n\n\n@pytest.fixture(scope=\"session\")\ndef java_nginx_env():\n env_dir = os.path.join(BASE_DEV_ENV_DIR, \"java_nginx_env\")\n environment = dr.ExecutionEnvironment.create(name=\"java_nginx_env\")\n environment_version = dr.ExecutionEnvironmentVersion.create(environment.id, env_dir)\n return environment.id, environment_version.id\n\n\n@pytest.fixture(scope=\"session\")\ndef rlang_nginx_env():\n env_dir = os.path.join(BASE_DEV_ENV_DIR, \"rlang_nginx_env\")\n environment = dr.ExecutionEnvironment.create(name=\"rlang_nginx_env\")\n environment_version = dr.ExecutionEnvironmentVersion.create(environment.id, env_dir)\n return environment.id, environment_version.id\n\n\n@pytest.fixture(scope=\"session\")\ndef python3_nginx_env():\n env_dir = os.path.join(BASE_DEV_ENV_DIR, \"python3_nginx_env\")\n environment = dr.ExecutionEnvironment.create(name=\"python3_nginx_env\")\n environment_version = dr.ExecutionEnvironmentVersion.create(environment.id, env_dir)\n return environment.id, environment_version.id\n\n\nclass TestInferenceModelTemplates(object):\n @pytest.mark.parametrize(\n \"model_template, language, env, dataset, target, pos_label, neg_label\",\n [\n (\n \"inference/java_codegen\",\n \"java\",\n \"java_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/h2o_pojo/regression\",\n \"java\",\n \"java_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/h2o_pojo/binary\",\n \"java\",\n \"java_nginx_env\",\n \"binary_testing_data\",\n \"Species\",\n \"Iris-setosa\",\n \"Iris-versicolor\",\n ),\n (\n \"inference/h2o_mojo/binary\",\n \"java\",\n \"java_nginx_env\",\n \"binary_testing_data\",\n \"Species\",\n \"Iris-setosa\",\n \"Iris-versicolor\",\n ),\n (\n \"inference/python3_pmml\",\n \"python\",\n \"java_nginx_env\",\n \"binary_testing_data\",\n \"Species\",\n \"Iris-setosa\",\n \"Iris-versicolor\",\n ),\n (\n \"inference/r_lang\",\n \"r\",\n \"rlang_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/python3_keras\",\n \"python\",\n \"python3_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/python3_keras_joblib\",\n \"python\",\n \"python3_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/python3_keras_vizai_joblib\",\n \"python\",\n \"python3_nginx_env\",\n \"binary_vizai_testing_data\",\n \"class\",\n \"dogs\",\n \"cats\",\n ),\n (\n \"inference/python3_pytorch\",\n \"python\",\n \"python3_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/python3_sklearn\",\n \"python\",\n \"python3_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n (\n \"inference/python3_xgboost\",\n \"python\",\n \"python3_nginx_env\",\n \"regression_testing_data\",\n \"MEDV\",\n None,\n None,\n ),\n ],\n )\n def test_inference_model_templates(\n self, request, model_template, language, env, dataset, target, pos_label, neg_label\n ):\n env_id, env_version_id = request.getfixturevalue(env)\n test_data_id = request.getfixturevalue(dataset)\n\n dr_target_type = dr.TARGET_TYPE.REGRESSION\n if pos_label is not None and neg_label is not None:\n dr_target_type = dr.TARGET_TYPE.BINARY\n model = dr.CustomInferenceModel.create(\n name=model_template,\n target_type=dr_target_type,\n target_name=target,\n description=model_template,\n language=language,\n positive_class_label=pos_label,\n negative_class_label=neg_label,\n )\n\n model_version = dr.CustomModelVersion.create_clean(\n custom_model_id=model.id,\n base_environment_id=env_id,\n folder_path=os.path.join(BASE_MODEL_TEMPLATES_DIR, model_template),\n )\n\n test = dr.CustomModelTest.create(\n custom_model_id=model.id,\n custom_model_version_id=model_version.id,\n environment_id=env_id,\n environment_version_id=env_version_id,\n dataset_id=test_data_id,\n )\n\n assert test.overall_status == \"succeeded\"\n","sub_path":"tests/functional/test_dev_envs.py","file_name":"test_dev_envs.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"98223871","text":"#!/usr/bin/python3\n\nfrom pyrob.api import *\n\n\ndef fill():\n global count\n while not wall_is_above():\n move_up()\n if not cell_is_filled():\n fill_cell()\n else:\n count += 1\n while not wall_is_beneath():\n move_down()\n\n\n@task(delay=0.02)\ndef task_8_18():\n global count\n count = 0\n while wall_is_beneath():\n if wall_is_above():\n fill_cell()\n fill()\n move_right()\n mov(\"ax\", count)\n\n\nif __name__ == '__main__':\n run_tasks()\n","sub_path":"task_32.py","file_name":"task_32.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"373154826","text":"from flask import abort, jsonify\nfrom flask_jwt_extended import jwt_required\n\nfrom app.extensions.api import (\n HTTPStatus,\n Namespace,\n Resource,\n commit_or_abort,\n paginate,\n update_dict,\n)\nfrom app.extensions.database import db\n\nfrom .models import Customer, Favorite\n\napi = Namespace(\"customers\", description=\"Customers\")\n\n\n@api.route(\"/\")\nclass CustomerResource(Resource):\n @jwt_required\n def get(self):\n customers = Customer.get_all_customers() or abort(204)\n return jsonify({\"customers\": [customer.to_dict() for customer in customers]})\n\n @jwt_required\n def post(self):\n with commit_or_abort(\n db.session, default_error_message=\"Failed to create a new customer\"\n ):\n customer = Customer(self.api.payload)\n db.session.add(customer)\n\n return jsonify({\"customer\": customer.to_dict()})\n\n\n@api.route(\"/\")\n@api.response(\n code=HTTPStatus.NOT_FOUND, description=\"Customer not found.\",\n)\nclass CustomerByID(Resource):\n @jwt_required\n def get(self, customer_id):\n customer = Customer.query.filter_by(id=customer_id).first_or_404()\n return jsonify(customer.to_dict())\n\n @jwt_required\n def put(self, customer_id):\n with commit_or_abort(\n db.session, default_error_message=\"Failed to update the customer\"\n ):\n customer = Customer.query.filter_by(id=customer_id).first_or_404()\n payload = self.api.payload\n\n customer, payload = update_dict(customer, payload)\n\n return jsonify({\"message\": \"updated\"})\n\n @jwt_required\n def delete(self, customer_id):\n with commit_or_abort(\n db.session, default_error_message=\"Failed to update the customer\"\n ):\n customer = Customer.query.filter_by(id=customer_id).first_or_404()\n db.session.delete(customer)\n\n # delete favorites\n favorites = Favorite.query.filter_by(id=customer_id)\n db.session.delete(favorites)\n\n return jsonify({\"message\": \"deleted\"})\n\n\n@api.route(\"//favorite-product/\")\nclass FavoriteResource(Resource):\n @jwt_required\n def get(self, customer_id):\n favorites = Favorite.query.filter_by(customer_id=customer_id).all()\n return jsonify({\"favorites\": [favorite.to_dict() for favorite in favorites]})\n\n @jwt_required\n def post(self):\n\n with commit_or_abort(\n db.session, default_error_message=\"Failed to create a new favorite\"\n ):\n favorite = Favorite(self.api.payload)\n db.session.add(favorite)\n\n return jsonify({\"favorite\": favorite.to_dict()})\n\n\n@api.route(\"//favorite-product/\")\n@api.response(\n code=HTTPStatus.NOT_FOUND, description=\"Favorite not found.\",\n)\nclass FavoriteByID(Resource):\n @jwt_required\n def get(self, customer_id, product_id):\n favorite = Favorite.query.filter_by(\n product_id=product_id, customer_id=customer_id\n ).first_or_404()\n return jsonify(favorite.to_dict())\n\n @jwt_required\n def delete(self, product_id, customer_id):\n with commit_or_abort(\n db.session, default_error_message=\"Failed to delete the favorite\"\n ):\n favorite = Favorite.query.filter_by(\n product_id=product_id, customer_id=customer_id\n ).first_or_404()\n db.session.delete(favorite)\n\n return jsonify({\"message\": \"deleted\"})\n","sub_path":"app/blueprints/customers/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"370890376","text":"import RPi.GPIO as GPIO\nimport time\n\nhall_P_pin = 7\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(hall_P_pin, GPIO.IN)\ntry:\n while True:\n print(GPIO.input(hall_P_pin))\n time.sleep(0.5)\nfinally:\n GPIO.cleanup()\n print('CLEAN')\n","sub_path":"TEST_FILES/HALL_TEST_P.py","file_name":"HALL_TEST_P.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"259130949","text":"import pytest\ncoreir = pytest.importorskip(\"coreir\")\nfrom magma import *\nfrom magma.testing import check_files_equal\n\n\ndef test_coreir_bit():\n class TestCircuit(Circuit):\n name = \"test_coreir_bit\"\n IO = [\"a\", In(Bit), \"b\", In(Bit), \"c\", In(Bit), \"d\", Out(Bit)]\n @classmethod\n def definition(circuit):\n d = ~(circuit.a & circuit.b) | (circuit.b ^ circuit.c)\n wire(d, circuit.d)\n compile(\"build/test_coreir_bit\", TestCircuit, output=\"coreir\")\n assert check_files_equal(__file__, \n \"build/test_coreir_bit.json\", \"gold/test_coreir_bit.json\")\n\n\ndef test_coreir_bits():\n class TestCircuit(Circuit):\n name = \"test_coreir_bits\"\n IO = [\"a\", In(Bits(4)), \"b\", In(Bits(4)), \"c\", In(Bits(4)), \"d\", Out(Bits(4))]\n @classmethod\n def definition(circuit):\n d = ~(circuit.a & circuit.b) | (circuit.b ^ circuit.c)\n wire(d, circuit.d)\n compile(\"build/test_coreir_bits\", TestCircuit, output=\"coreir\")\n assert check_files_equal(__file__, \n \"build/test_coreir_bits.json\", \"gold/test_coreir_bits.json\")\n\n\ndef test_coreir_uint():\n class TestCircuit(Circuit):\n name = \"test_coreir_uint\"\n IO = [\"a\", In(UInt(4)), \"b\", In(UInt(4)), \"c\", Out(UInt(4))]\n @classmethod\n def definition(circuit):\n tmp1 = circuit.a + circuit.b\n tmp2 = circuit.a - circuit.b\n tmp3 = tmp1 * tmp2\n tmp4 = tmp3 / circuit.a\n wire(tmp4, circuit.c)\n compile(\"build/test_coreir_uint\", TestCircuit, output=\"coreir\")\n assert check_files_equal(__file__, \n \"build/test_coreir_uint.json\", \"gold/test_coreir_uint.json\")\n\ndef test_coreir_shift_register():\n from magma.primitives import DefineRegister\n\n N = 4\n Register4 = DefineRegister(4)\n T = Bits(N)\n\n class ShiftRegister(Circuit):\n name = \"ShiftRegister\"\n IO = [\"I\", In(T), \"O\", Out(T), \"CLK\", In(Clock)]\n @classmethod\n def definition(io):\n regs = [Register4() for _ in range(N)]\n wireclock(io, regs)\n wire(io.I, getattr(regs[0], \"in\"))\n fold(regs, foldargs={\"in\":\"out\"})\n wire(regs[-1].out, io.O)\n\n compile(\"build/test_coreir_shift_register\", ShiftRegister, 'coreir')\n assert check_files_equal(__file__,\n \"build/test_coreir_shift_register.json\",\n \"gold/test_coreir_shift_register.json\")\n\nif __name__ == \"__main__\":\n test_coreir()\n","sub_path":"tests/test_coreir/test_coreir.py","file_name":"test_coreir.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"419460544","text":"#!/usr/bin/env python\n\nimport json\nfrom flask import Flask, request, render_template\n\n# Don't enable logging, there is a 1-second polling loop in the JavaScript, so\n# you'll fill up the file system unnecessarily.\n# logging.basicConfig(filename='/var/log/rdb-listener.log', level=logging.INFO)\n\napp = Flask(__name__)\nlogs = []\nrdbid = 0\n\n\n@app.route('/')\ndef index():\n return render_template('layout.html')\n\n\n@app.route('/images/')\ndef show_image(path):\n return open('static/' + path).read()\n\n\ndef jtable(x):\n return json.dumps(\n dict(data=x),\n sort_keys=True,\n indent=4, separators=(',', ': ')\n )\n\n\n@app.route('/get_logs')\ndef get_logs():\n return jtable(logs)\n\n\n@app.route('/log', methods=['POST'])\ndef post_log():\n log = {\n 'ipaddr': request.form['ipaddr'],\n 'levelname': request.form['levelname'],\n 'pathname': request.form['pathname'],\n 'lineno': request.form['lineno'],\n 'funcName': request.form['funcName'],\n 'exc_info': request.form['exc_info'],\n 'msg': request.form['msg'],\n 'created': request.form['created']\n }\n logs.append(log)\n return ''\n\nrdb_sessions = []\n\n\n@app.route('/rdb', methods=['POST'])\ndef post_rdb():\n global rdbid\n rdb_sessions.append((rdbid, request.form['ipaddr'], request.form['port']))\n rdbid += 1\n return ''\n\n\n@app.route('/check-rdb', methods=['GET'])\ndef get_rdb():\n sessions = [\n {'id': id, 'ipaddr': ipaddr, 'port': port} for id, ipaddr, port in rdb_sessions\n ]\n return render_template('rdblist.html', rdblist=sessions)\n\n\n@app.route('/rdb-done/')\ndef remove_rdb(n):\n global rdb_sessions\n rdb_sessions = filter(lambda session: session[0] != int(n), rdb_sessions)\n return ''\n\nif __name__ == '__main__':\n app.run('0.0.0.0')\n","sub_path":"rdb/rdb/listener/go.py","file_name":"go.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499659849","text":"__author__ = 'roopalgarg'\nimport math\nfrom ParseLabels import ParseLabels\nclass SentimentCalculationEngine:\n\n\t@staticmethod\n\tdef calculate(sentiment1, sentiment2):\n\t\tneutralRating=ParseLabels.Labels[\"neutral\"]\n\t\tif sentiment1 != neutralRating and sentiment2 != neutralRating:\n\t\t\tif ParseLabels.isNegative(sentiment1) and ParseLabels.isPositive(sentiment2):\n\t\t\t\treturn SentimentCalculationEngine.handleNegativePositive(sentiment1,sentiment2)\n\t\t\tif ParseLabels.isPositive(sentiment1) and ParseLabels.isNegative(sentiment2):\n\t\t\t\treturn SentimentCalculationEngine.handlePositiveNegative(sentiment1,sentiment2)\n\t\t\tsentiment=(float(sentiment1+sentiment2)/2)\n\n\t\t\tif sentimentneutralRating:\n\t\t\t\treturn math.floor(sentiment)\n\t\t\telse:\n\t\t\t\treturn sentiment\n\t\telse:\n\t\t\tif sentiment1 == neutralRating:\n\t\t\t\treturn sentiment2\n\t\t\telse:\n\t\t\t\treturn sentiment1\n\n\t@staticmethod\n\tdef handlePositiveNegative(sentiment1,sentiment2):\n\t\tif ParseLabels.isExtremeNegative(sentiment2):\n\t\t\treturn ParseLabels.Labels[\"somewhat_negative\"]\n\t\telse:\n\t\t\treturn sentiment2\n\n\t@staticmethod\n\tdef handleNegativePositive(sentiment1,sentiment2):\n\t\treturn sentiment1\n\n\t@staticmethod\n\tdef handleSentencesWithBut(sentimentBeforeBut,sentimentAfterBut):\n\t\tif sentimentBeforeBut == ParseLabels.GetNeutralRating() and sentimentAfterBut == ParseLabels.GetNeutralRating():\n\t\t\treturn ParseLabels.GetNeutralRating()\n\t\telif sentimentBeforeBut is None:\n\t\t\treturn SentimentCalculationEngine.__dampenSentiment(sentimentAfterBut)\n\t\telif sentimentAfterBut is None:\n\t\t\treturn SentimentCalculationEngine.__dampenSentiment(sentimentBeforeBut)\n\t\telse:\n\t\t\treturn SentimentCalculationEngine.calculate(sentimentBeforeBut, sentimentAfterBut)\n\n\n\t@staticmethod\n\tdef __dampenSentiment(sentiment):\n\t\tif ParseLabels.isNeutral(sentiment):\n\t\t\treturn sentiment\n\t\telif ParseLabels.isPositive(sentiment):\n\t\t\treturn ParseLabels.getHigherNegativeSentiment(sentiment)\n\t\telif ParseLabels.isNegative(sentiment):\n\t\t\treturn ParseLabels.getHigherPositiveSentiment(sentiment)","sub_path":"Sentiment Analysis on Movie Reviews/Codes/SentimentCalculationEngine.py","file_name":"SentimentCalculationEngine.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"581149294","text":"from common import *\nfrom net.lib.roi_align_pool_tf.module import RoIAlign as Crop\n\nfrom net.layer.rpn_multi_nms import *\nfrom net.layer.rpn_multi_target import *\nfrom net.layer.rpn_multi_loss import *\nfrom net.layer.rcnn_nms import *\nfrom net.layer.rcnn_target import *\nfrom net.layer.rcnn_loss import *\nfrom net.layer.mask_nms import *\nfrom net.layer.mask_target import *\nfrom net.layer.mask_loss import *\n\nif __name__ == '__main__':\n from configuration import *\nelse:\n from .configuration import *\n\n\n# block ######################################################################################################\n\nclass ConvBn2d(nn.Module):\n\n def merge_bn(self):\n # raise NotImplementedError\n assert (self.conv.bias is None)\n conv_weight = self.conv.weight.data\n bn_weight = self.bn.weight.data\n bn_bias = self.bn.bias.data\n bn_running_mean = self.bn.running_mean\n bn_running_var = self.bn.running_var\n bn_eps = self.bn.eps\n\n # https://github.com/sanghoon/pva-faster-rcnn/issues/5\n # https://github.com/sanghoon/pva-faster-rcnn/commit/39570aab8c6513f0e76e5ab5dba8dfbf63e9c68c\n\n N, C, KH, KW = conv_weight.size()\n std = 1 / (torch.sqrt(bn_running_var + bn_eps))\n std_bn_weight = (std * bn_weight).repeat(C * KH * KW, 1).t().contiguous().view(N, C, KH, KW)\n conv_weight_hat = std_bn_weight * conv_weight\n conv_bias_hat = (bn_bias - bn_weight * std * bn_running_mean)\n\n self.bn = None\n self.conv = nn.Conv2d(in_channels=self.conv.in_channels, out_channels=self.conv.out_channels,\n kernel_size=self.conv.kernel_size,\n padding=self.conv.padding, stride=self.conv.stride, dilation=self.conv.dilation,\n groups=self.conv.groups,\n bias=True)\n self.conv.weight.data = conv_weight_hat # fill in\n self.conv.bias.data = conv_bias_hat\n\n def __init__(self, in_channels, out_channels, kernel_size=3, padding=1, dilation=1, stride=1, groups=1, is_bn=True):\n super(ConvBn2d, self).__init__()\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride,\n dilation=dilation, groups=groups, bias=False)\n self.bn = nn.BatchNorm2d(out_channels, eps=1e-5)\n\n if is_bn is False:\n self.bn = None\n\n def forward(self, x):\n x = self.conv(x)\n if self.bn is not None:\n x = self.bn(x)\n return x\n\n\nclass SEScale(nn.Module):\n def __init__(self, channel, reduction=16):\n super(SEScale, self).__init__()\n self.fc1 = nn.Conv2d(channel, reduction, kernel_size=1, padding=0)\n self.fc2 = nn.Conv2d(reduction, channel, kernel_size=1, padding=0)\n\n def forward(self, x):\n x = F.adaptive_avg_pool2d(x, 1)\n x = self.fc1(x)\n x = F.relu(x, inplace=True)\n x = self.fc2(x)\n x = F.sigmoid(x)\n return x\n\n\n# ############ resnext50 pyramid feature net ###################################################################\n# https://github.com/Hsuxu/ResNeXt/blob/master/models.py\n# https://github.com/D-X-Y/ResNeXt-DenseNet/blob/master/models/resnext.py\n# https://github.com/miraclewkf/ResNeXt-PyTorch/blob/master/resnext.py\n\n\n## P layers ## ---------------------------\nclass LateralBlock(nn.Module):\n def __init__(self, c_planes, p_planes, out_planes):\n super(LateralBlock, self).__init__()\n self.lateral = nn.Conv2d(c_planes, p_planes, kernel_size=1, padding=0, stride=1)\n self.top = nn.Conv2d(p_planes, out_planes, kernel_size=3, padding=1, stride=1)\n\n def forward(self, c, p):\n _, _, H, W = c.size()\n c = self.lateral(c)\n p = F.upsample(p, scale_factor=2, mode='nearest')\n p = p[:, :, :H, :W] + c\n p = self.top(p)\n\n return p\n\n\n## C layers ## ---------------------------\n\n# bottleneck type C\nclass SENextBottleneckBlock(nn.Module):\n def __init__(self, in_planes, planes, out_planes, groups, reduction=16, is_downsample=False, stride=1):\n super(SENextBottleneckBlock, self).__init__()\n self.is_downsample = is_downsample\n\n self.conv_bn1 = ConvBn2d(in_planes, planes, kernel_size=1, padding=0, stride=1)\n self.conv_bn2 = ConvBn2d(planes, planes, kernel_size=3, padding=1, stride=stride, groups=groups)\n self.conv_bn3 = ConvBn2d(planes, out_planes, kernel_size=1, padding=0, stride=1)\n self.scale = SEScale(out_planes, reduction)\n\n if is_downsample:\n self.downsample = ConvBn2d(in_planes, out_planes, kernel_size=1, padding=0, stride=stride)\n\n def forward(self, x):\n\n z = F.relu(self.conv_bn1(x), inplace=True)\n z = F.relu(self.conv_bn2(z), inplace=True)\n z = self.conv_bn3(z)\n\n if self.is_downsample:\n z = self.scale(z) * z + self.downsample(x)\n else:\n z = self.scale(z) * z + x\n\n z = F.relu(z, inplace=True)\n return z\n\n\ndef make_layer_c0(in_planes, out_planes):\n layers = [\n nn.Conv2d(in_planes, out_planes, kernel_size=7, stride=2, padding=3, bias=False),\n nn.BatchNorm2d(out_planes),\n nn.ReLU(inplace=True),\n ]\n return nn.Sequential(*layers)\n\n\ndef make_layer_c(in_planes, planes, out_planes, groups, num_blocks, stride):\n layers = [SENextBottleneckBlock(in_planes, planes, out_planes, groups, is_downsample=True, stride=stride)]\n for i in range(1, num_blocks):\n layers.append(SENextBottleneckBlock(out_planes, planes, out_planes, groups))\n\n return nn.Sequential(*layers)\n\n\n# resnext50_32x4d\nclass FeatureNet(nn.Module):\n\n def __init__(self, cfg, in_channels, out_channels=256):\n super(FeatureNet, self).__init__()\n self.cfg = cfg\n\n # bottom-top\n self.layer_c0 = make_layer_c0(in_channels, 64)\n\n self.layer_c1 = make_layer_c(64, 64, 256, groups=32, num_blocks=3, stride=1) # out = 64*4 = 256\n self.layer_c2 = make_layer_c(256, 128, 512, groups=32, num_blocks=4, stride=2) # out = 128*4 = 512\n self.layer_c3 = make_layer_c(512, 256, 1024, groups=32, num_blocks=6, stride=2) # out = 256*4 = 1024\n self.layer_c4 = make_layer_c(1024, 512, 2048, groups=32, num_blocks=3, stride=2) # out = 512*4 = 2048\n\n # top-down\n self.layer_p4 = nn.Conv2d(2048, out_channels, kernel_size=1, stride=1, padding=0)\n self.layer_p3 = LateralBlock(1024, out_channels, out_channels)\n self.layer_p2 = LateralBlock(512, out_channels, out_channels)\n self.layer_p1 = LateralBlock(256, out_channels, out_channels)\n\n def forward(self, x):\n # pass #; print('input ', x.size())\n c0 = self.layer_c0(x) # ; print('layer_c0 ',c0.size())\n #\n c1 = self.layer_c1(c0) # ; print('layer_c1 ',c1.size())\n c2 = self.layer_c2(c1) # ; print('layer_c2 ',c2.size())\n c3 = self.layer_c3(c2) # ; print('layer_c3 ',c3.size())\n c4 = self.layer_c4(c3) # ; print('layer_c4 ',c4.size())\n\n p4 = self.layer_p4(c4) # ; print('layer_p4 ',p4.size())\n p3 = self.layer_p3(c3, p4) # ; print('layer_p3 ',p3.size())\n p2 = self.layer_p2(c2, p3) # ; print('layer_p2 ',p2.size())\n p1 = self.layer_p1(c1, p2) # ; print('layer_p1 ',p1.size())\n\n features = [p1, p2, p3, p4]\n assert (len(self.cfg.rpn_scales) == len(features))\n\n return features\n\n\n############# various head ##############################################################################################\n\nclass RpnMultiHead(nn.Module):\n\n def __init__(self, cfg, in_channels):\n super(RpnMultiHead, self).__init__()\n\n self.num_classes = cfg.num_classes\n self.num_scales = len(cfg.rpn_scales)\n self.num_bases = [len(b) for b in cfg.rpn_base_apsect_ratios]\n\n self.convs = nn.ModuleList()\n self.logits = nn.ModuleList()\n self.deltas = nn.ModuleList()\n for l in range(self.num_scales):\n channels = in_channels * 2\n self.convs.append(nn.Conv2d(in_channels, channels, kernel_size=3, padding=1))\n self.logits.append(\n nn.Sequential(\n nn.Conv2d(channels, self.num_bases[l] * self.num_classes, kernel_size=3, padding=1),\n )\n )\n self.deltas.append(\n nn.Sequential(\n nn.Conv2d(channels, self.num_bases[l] * self.num_classes * 4, kernel_size=3, padding=1),\n )\n )\n\n def forward(self, fs):\n batch_size = len(fs[0])\n\n logits_flat = []\n # probs_flat = []\n deltas_flat = []\n for l in range(self.num_scales): # apply multibox head to feature maps\n f = fs[l]\n f = F.relu(self.convs[l](f))\n\n f = F.dropout(f, p=0.5, training=self.training)\n logit = self.logits[l](f)\n delta = self.deltas[l](f)\n\n logit_flat = logit.permute(0, 2, 3, 1).contiguous().view(batch_size, -1, self.num_classes)\n delta_flat = delta.permute(0, 2, 3, 1).contiguous().view(batch_size, -1, self.num_classes, 4)\n logits_flat.append(logit_flat)\n deltas_flat.append(delta_flat)\n\n logits_flat = torch.cat(logits_flat, 1)\n deltas_flat = torch.cat(deltas_flat, 1)\n\n return logits_flat, deltas_flat\n\n\n# https://qiita.com/yu4u/items/5cbe9db166a5d72f9eb8\n\nclass CropRoi(nn.Module):\n def __init__(self, cfg, crop_size):\n super(CropRoi, self).__init__()\n self.num_scales = len(cfg.rpn_scales)\n self.crop_size = crop_size\n self.sizes = cfg.rpn_base_sizes\n self.sizes = torch.from_numpy(np.array(self.sizes, np.float32))\n self.sizes = self.sizes.cuda() if USE_CUDA else self.sizes\n self.scales = cfg.rpn_scales\n\n self.crops = nn.ModuleList()\n for l in range(self.num_scales):\n self.crops.append(\n Crop(self.crop_size, self.crop_size, 1 / self.scales[l])\n )\n\n def forward(self, fs, proposals):\n num_proposals = len(proposals)\n\n # this is complicated. we need to decide for a given roi, which of the p0,p1, ..p3 layers to pool from\n boxes = proposals.detach().data[:, 1:5]\n sizes = boxes[:, 2:] - boxes[:, :2]\n sizes = torch.sqrt(sizes[:, 0] * sizes[:, 1])\n distances = torch.abs(sizes.view(num_proposals, 1).expand(num_proposals, 4) - self.sizes)\n min_distances, min_index = distances.min(1)\n\n crops = []\n indices = []\n for l in range(self.num_scales):\n index = (min_index == l).nonzero()\n\n if len(index) > 0:\n crop = self.crops[l](fs[l], proposals[index, :5].view(-1, 5))\n crops.append(crop)\n indices.append(index)\n\n crops = torch.cat(crops, 0)\n indices = torch.cat(indices, 0).view(-1)\n crops = crops[torch.sort(indices)[1]]\n # crops = torch.index_select(crops,0,index)\n\n return crops\n\n\nclass RcnnHead(nn.Module):\n def __init__(self, cfg, in_channels):\n super(RcnnHead, self).__init__()\n self.num_classes = cfg.num_classes\n self.crop_size = cfg.rcnn_crop_size\n\n self.fc1 = nn.Linear(in_channels * self.crop_size * self.crop_size, 1024)\n self.fc2 = nn.Linear(1024, 1024)\n self.logit = nn.Linear(1024, self.num_classes)\n self.delta = nn.Linear(1024, self.num_classes * 4)\n\n def forward(self, crops):\n x = crops.view(crops.size(0), -1)\n x = F.relu(self.fc1(x), inplace=True)\n x = F.relu(self.fc2(x), inplace=True)\n x = F.dropout(x, 0.5, training=self.training)\n logits = self.logit(x)\n deltas = self.delta(x)\n\n return logits, deltas\n\n\n# class CropRoi(nn.Module):\n# def __init__(self, cfg, in_channels, out_channels ):\n# super(CropRoi, self).__init__()\n# self.num_scales = len(cfg.rpn_scales)\n# self.scales = cfg.rpn_scales\n# self.crop_size = cfg.crop_size\n#\n# self.convs = nn.ModuleList()\n# self.crops = nn.ModuleList()\n# for l in range(self.num_scales):\n# self.convs.append(\n# nn.Conv2d( in_channels, out_channels//self.num_scales, kernel_size=1, padding=0, bias=False),\n# )\n# self.crops.append(\n# Crop(self.crop_size, self.crop_size, 1/self.scales[l]),\n# )\n#\n#\n# def forward(self, fs, proposals):\n# rois = proposals[:,0:5]\n# crops=[]\n# for l in range(self.num_scales):\n# c = self.convs[l](fs[l])\n# c = self.crops[l](c,rois)\n# crops.append(c)\n# crops = torch.cat(crops,1)\n#\n# return crops\n\n\nclass MaskHead(nn.Module):\n\n def __init__(self, cfg, in_channels):\n super(MaskHead, self).__init__()\n self.num_classes = cfg.num_classes\n\n self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn2 = nn.BatchNorm2d(in_channels)\n self.conv3 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn3 = nn.BatchNorm2d(in_channels)\n self.conv4 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn4 = nn.BatchNorm2d(in_channels)\n\n self.up = nn.ConvTranspose2d(in_channels, in_channels, kernel_size=4, padding=1, stride=2, bias=False)\n self.logit = nn.Conv2d(in_channels, self.num_classes, kernel_size=1, padding=0, stride=1)\n\n def forward(self, crops):\n x = F.relu(self.bn1(self.conv1(crops)), inplace=True)\n x = F.relu(self.bn2(self.conv2(x)), inplace=True)\n x = F.relu(self.bn3(self.conv3(x)), inplace=True)\n x = F.relu(self.bn4(self.conv4(x)), inplace=True)\n x = self.up(x)\n logits = self.logit(x)\n #\n # x = F.leaky_relu(self.bn1(self.conv1(crops)), inplace=True)\n # x = F.leaky_relu(self.bn2(self.conv2(x)), inplace=True)\n # x = F.leaky_relu(self.bn3(self.conv3(x)), inplace=True)\n # x = F.leaky_relu(self.bn4(self.conv4(x)), inplace=True)\n # x = self.up(x)\n # logits = self.logit(x)\n\n return logits\n\n\nclass MaskHeadRes(nn.Module):\n\n def __init__(self, cfg, in_channels):\n super(MaskHeadRes, self).__init__()\n self.num_classes = cfg.num_classes\n\n self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv2 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn2 = nn.BatchNorm2d(in_channels)\n self.conv3 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn3 = nn.BatchNorm2d(in_channels)\n self.conv4 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn4 = nn.BatchNorm2d(in_channels)\n\n self.up = nn.ConvTranspose2d(in_channels, in_channels, kernel_size=4, padding=1, stride=2, bias=False)\n self.logit = nn.Conv2d(in_channels, self.num_classes, kernel_size=1, padding=0, stride=1)\n\n def forward(self, crops):\n x1 = F.relu(self.bn1(self.conv1(crops)), inplace=True)\n x = F.relu(self.bn2(self.conv2(x1)), inplace=True)\n x = F.relu(self.bn3(self.conv3(x)), inplace=True)\n x = F.relu(self.bn4(self.conv4(x)) + x1, inplace=True)\n x = self.up(x)\n logits = self.logit(x)\n\n # x1 = F.leaky_relu(self.bn1(self.conv1(crops)), inplace=True)\n # x = F.leaky_relu(self.bn2(self.conv2(x1)), inplace=True)\n # x = F.leaky_relu(self.bn3(self.conv3(x)), inplace=True)\n # x = F.leaky_relu(self.bn4(self.conv4(x)) + x1, inplace=True)\n # x = self.up(x)\n # logits = self.logit(x)\n return logits\n\n\nclass MaskHeadMiniUnet(nn.Module):\n\n def __init__(self, cfg, in_channels):\n super(MaskHeadMiniUnet, self).__init__()\n self.num_classes = cfg.num_classes\n\n self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn1 = nn.BatchNorm2d(in_channels)\n self.down = nn.MaxPool2d(kernel_size=2, stride=2)\n self.conv2 = nn.Conv2d(in_channels, in_channels * 2, kernel_size=3, padding=1, stride=1)\n self.bn2 = nn.BatchNorm2d(in_channels * 2)\n self.conv3 = nn.Conv2d(in_channels * 2, in_channels * 2, kernel_size=3, padding=1, stride=1)\n self.bn3 = nn.BatchNorm2d(in_channels * 2)\n self.up = nn.ConvTranspose2d(in_channels * 2, in_channels, kernel_size=4, padding=1, stride=2, bias=False)\n self.conv4 = nn.Conv2d(in_channels * 2, in_channels, kernel_size=3, padding=1, stride=1)\n self.bn4 = nn.BatchNorm2d(in_channels)\n\n self.logit = nn.Conv2d(in_channels, self.num_classes, kernel_size=1, padding=0, stride=1)\n\n def forward(self, crops):\n x1 = F.relu(self.bn1(self.conv1(crops)), inplace=True)\n x = F.relu(self.bn2(self.conv2(self.down(x1))), inplace=True)\n x = F.relu(self.bn3(self.conv3(x)), inplace=True)\n x = torch.cat([x1, self.up(x)], dim=1)\n x = F.relu(self.bn4(self.conv4(x)))\n logits = self.logit(x)\n\n # x1 = F.leaky_relu(self.bn1(self.conv1(crops)), inplace=True)\n # x = F.leaky_relu(self.bn2(self.conv2(self.down(x1))), inplace=True)\n # x = F.leaky_relu(self.bn3(self.conv3(x)), inplace=True)\n # x = torch.cat([x1, self.up(x)], dim=1)\n # x = F.leaky_relu(self.bn4(self.conv4(x)))\n # logits = self.logit(x)\n return logits\n\n\n############# mask rcnn net ##############################################################################\n\n\nclass MaskNet(nn.Module):\n\n def __init__(self, cfg, input_channel, mask, feature_channels, train_box_only):\n super(MaskNet, self).__init__()\n self.version = 'net version \\'mask-rcnn-se-resnext50-fpn\\''\n self.cfg = cfg\n self.mode = 'train'\n self.train_box_only = train_box_only\n\n crop_channels = feature_channels\n self.feature_net = FeatureNet(cfg, input_channel, feature_channels)\n self.rpn_head = RpnMultiHead(cfg, feature_channels)\n self.rcnn_crop = CropRoi(cfg, cfg.rcnn_crop_size)\n self.rcnn_head = RcnnHead(cfg, crop_channels)\n if mask == '4conv':\n self.mask_head = MaskHead(cfg, crop_channels)\n elif mask == 'mini-unet':\n self.mask_head = MaskHeadMiniUnet(cfg, crop_channels)\n cfg.mask_crop_size = 28\n elif mask == 'mini-res':\n self.mask_head = MaskHeadRes(cfg, crop_channels)\n self.mask_crop = CropRoi(cfg, cfg.mask_crop_size)\n\n if USE_CUDA:\n print('in constructing mask rcnn net, using gpu, using data parallel')\n self.data_parallel = lambda module, input: data_parallel(module, input)\n else:\n print('in constructing mask rcnn net, not using gpu, not using data parallel')\n self.data_parallel = lambda module, input: module(input)\n\n self.rpn_logits_flat = None\n self.rpn_deltas_flat = None\n self.rpn_window = None\n self.rpn_labels = None\n self.rpn_label_assigns = None\n self.rpn_label_weights = None\n self.rpn_targets = None\n self.rpn_target_weights = None\n self.rpn_proposals = None\n self.rpn_cls_loss = None\n self.rpn_reg_loss = None\n\n self.rcnn_labels = None\n self.rcnn_assigns = None\n self.rcnn_targets = None\n self.rcnn_logits = None\n self.rcnn_deltas = None\n self.rcnn_proposals = None\n self.rcnn_cls_loss = None\n self.rcnn_reg_loss = None\n\n self.mask_labels = None\n self.mask_assigns = None\n self.mask_instances = None\n self.mask_logits = None\n self.mask_cls_loss = None\n\n self.detections = None\n self.total_loss = None\n self.masks = None\n self.mask_proposals = None\n\n def forward(self, inputs, truth_boxes=None, truth_labels=None, truth_instances=None):\n cfg = self.cfg\n mode = self.mode\n features = self.data_parallel(self.feature_net, inputs)\n\n # rpn proposals -------------------------------------------\n self.rpn_logits_flat, self.rpn_deltas_flat = self.data_parallel(self.rpn_head, features)\n self.rpn_window = make_rpn_windows(cfg, features)\n self.rpn_proposals = rpn_nms(cfg, mode, inputs, self.rpn_window, self.rpn_logits_flat, self.rpn_deltas_flat)\n\n if mode in ['train', 'valid']:\n self.rpn_labels, self.rpn_label_assigns, self.rpn_label_weights, self.rpn_targets, self.rpn_target_weights = \\\n make_rpn_target(cfg, mode, inputs, self.rpn_window, truth_boxes, truth_labels)\n\n self.rpn_proposals, self.rcnn_labels, self.rcnn_assigns, self.rcnn_targets = \\\n make_rcnn_target(cfg, mode, inputs, self.rpn_proposals, truth_boxes, truth_labels)\n\n # rcnn proposals ------------------------------------------------\n self.rcnn_proposals = self.rpn_proposals\n if len(self.rpn_proposals) > 0:\n rcnn_crops = self.rcnn_crop(features, self.rpn_proposals)\n self.rcnn_logits, self.rcnn_deltas = self.data_parallel(self.rcnn_head, rcnn_crops)\n self.rcnn_proposals = rcnn_nms(cfg, mode, inputs, self.rpn_proposals, self.rcnn_logits, self.rcnn_deltas)\n\n if mode in ['train', 'valid']:\n self.rcnn_proposals, self.mask_labels, self.mask_assigns, self.mask_instances, = \\\n make_mask_target(cfg, mode, inputs, self.rcnn_proposals, truth_boxes, truth_labels, truth_instances)\n\n # segmentation -------------------------------------------\n self.detections = self.rcnn_proposals\n self.masks = make_empty_masks(cfg, mode, inputs)\n\n if len(self.rcnn_proposals) > 0:\n mask_crops = self.mask_crop(features, self.detections)\n self.mask_logits = self.data_parallel(self.mask_head, mask_crops)\n\n # self.masks, self.mask_proposals = mask_nms(cfg, mode, inputs, self.rcnn_proposals,\n # self.mask_logits) # better nms for mask\n self.masks = mask_nms(cfg, mode, inputs, self.rcnn_proposals, self.mask_logits) # better nms for mask\n # self.detections = self.mask_proposals\n\n def forward_train(self, inputs, truth_boxes=None, truth_labels=None, truth_instances=None):\n features = self.feature_net(inputs)\n\n # rpn proposals -------------------------------------------\n self.rpn_logits_flat, self.rpn_deltas_flat = self.rpn_head(features)\n self.rpn_window = make_rpn_windows(self.cfg, features)\n self.rpn_proposals = rpn_nms(self.cfg, self.mode, inputs, self.rpn_window, self.rpn_logits_flat, self.rpn_deltas_flat)\n rpn_proposals_sampled_for_rcnn = self.rpn_proposals\n rpn_proposals_sampled_for_mask = self.rpn_proposals\n if self.mode in ['train', 'valid']:\n self.rpn_labels, self.rpn_label_assigns, self.rpn_label_weights, self.rpn_targets, self.rpn_target_weights = \\\n make_rpn_target(self.cfg, self.mode, inputs, self.rpn_window, truth_boxes, truth_labels)\n rpn_proposals_sampled_for_rcnn, self.rcnn_labels, self.rcnn_assigns, self.rcnn_targets = \\\n make_rcnn_target(self.cfg, self.mode, inputs, self.rpn_proposals, truth_boxes, truth_labels)\n rpn_proposals_sampled_for_mask, self.mask_labels, self.mask_assigns, self.mask_instances, = \\\n make_mask_target(self.cfg, self.mode, inputs, self.rpn_proposals, truth_boxes, truth_labels,\n truth_instances)\n # crops for rcnn and mask\n if len(rpn_proposals_sampled_for_rcnn) > 0:\n crops_for_rcnn = self.rcnn_crop(features, rpn_proposals_sampled_for_rcnn)\n self.rcnn_logits, self.rcnn_deltas = self.rcnn_head(crops_for_rcnn)\n if len(rpn_proposals_sampled_for_mask) > 0:\n crops_for_mask = self.mask_crop(features, rpn_proposals_sampled_for_mask)\n self.mask_logits = self.mask_head(crops_for_mask)\n\n def loss_train_rcnn(self, inputs, truth_boxes, truth_labels, truth_instances):\n\n self.rpn_cls_loss, self.rpn_reg_loss = \\\n rpn_loss(self.rpn_logits_flat, self.rpn_deltas_flat, self.rpn_labels, self.rpn_label_weights,\n self.rpn_targets, self.rpn_target_weights)\n\n self.rcnn_cls_loss, self.rcnn_reg_loss = \\\n rcnn_loss(self.rcnn_logits, self.rcnn_deltas, self.rcnn_labels, self.rcnn_targets)\n\n self.total_loss = self.rpn_cls_loss + self.rpn_reg_loss + self.rcnn_cls_loss + self.rcnn_reg_loss\n\n return self.total_loss\n\n def get_detections(self, inputs):\n self.rcnn_proposals = self.rpn_proposals\n self.detections = self.rcnn_proposals\n if len(self.rpn_proposals) > 0:\n self.rcnn_proposals = rcnn_nms(\n self.cfg, self.mode, inputs, self.rpn_proposals, self.rcnn_logits, self.rcnn_deltas)\n self.detections = self.rcnn_proposals\n return self.detections\n\n def get_masks(self, inputs):\n \"\"\"\n This function must be called after get_detections\n \"\"\"\n self.masks = make_empty_masks(self.cfg, self.mode, inputs)\n if len(self.rpn_proposals) > 0:\n self.masks = mask_nms(self.cfg, self.mode, inputs, self.rpn_proposals, self.mask_logits)\n return self.masks\n\n def loss(self, inputs, truth_boxes, truth_labels, truth_instances):\n\n self.rpn_cls_loss, self.rpn_reg_loss = \\\n rpn_loss(self.rpn_logits_flat, self.rpn_deltas_flat, self.rpn_labels, self.rpn_label_weights,\n self.rpn_targets, self.rpn_target_weights)\n\n self.rcnn_cls_loss, self.rcnn_reg_loss = \\\n rcnn_loss(self.rcnn_logits, self.rcnn_deltas, self.rcnn_labels, self.rcnn_targets)\n\n if self.train_box_only:\n self.total_loss = \\\n self.rpn_cls_loss + \\\n self.rpn_reg_loss + \\\n self.rcnn_cls_loss + \\\n self.rcnn_reg_loss\n else:\n self.mask_cls_loss = \\\n mask_loss(self.mask_logits, self.mask_labels, self.mask_instances)\n self.total_loss = \\\n self.rpn_cls_loss + \\\n self.rpn_reg_loss + \\\n self.rcnn_cls_loss + \\\n self.rcnn_reg_loss + \\\n self.mask_cls_loss\n\n # self.total_loss = self.rpn_cls_loss + self.rpn_reg_loss + self.rcnn_cls_loss + self.rcnn_reg_loss\n # self.total_loss = self.rpn_cls_loss + self.rpn_reg_loss + self.mask_cls_loss\n # self.total_loss = self.rcnn_cls_loss + self.rcnn_reg_loss + self.mask_cls_loss\n\n return self.total_loss\n\n # freeze bn for imagenet pretrain\n def set_mode(self, mode):\n self.mode = mode\n if mode in ['eval', 'valid', 'test']:\n self.eval()\n elif mode in ['train']:\n self.train()\n else:\n raise NotImplementedError\n\n def load_pretrain(self, pretrain_file, skip=()):\n pretrain_state_dict = torch.load(pretrain_file)\n state_dict = self.state_dict()\n\n keys = list(state_dict.keys())\n for key in keys:\n if any(s in key for s in skip):\n continue\n state_dict[key] = pretrain_state_dict[key]\n\n self.load_state_dict(state_dict)\n # raise NotImplementedError\n#\n#\n# # check #################################################################\n# def run_check_feature_net():\n# batch_size = 4\n# C, H, W = 3, 256, 256\n# feature_channels = 128\n#\n# x = torch.randn(batch_size, C, H, W)\n# inputs = Variable(x).cuda()\n#\n# cfg = Configuration()\n# feature_net = FeatureNet(cfg, C, feature_channels).cuda()\n#\n# ps = feature_net(inputs)\n#\n# print('')\n# num_heads = len(ps)\n# for i in range(num_heads):\n# p = ps[i]\n# print(i, p.size())\n#\n#\n# def run_check_multi_rpn_head():\n# batch_size = 8\n# in_channels = 128\n# H, W = 256, 256\n# num_scales = 4\n# feature_heights = [int(H // 2 ** l) for l in range(num_scales)]\n# feature_widths = [int(W // 2 ** l) for l in range(num_scales)]\n#\n# fs = []\n# for h, w in zip(feature_heights, feature_widths):\n# f = np.random.uniform(-1, 1, size=(batch_size, in_channels, h, w)).astype(np.float32)\n# f = Variable(torch.from_numpy(f)).cuda()\n# fs.append(f)\n#\n# cfg = Configuration()\n# rpn_head = RpnMultiHead(cfg, in_channels).cuda()\n# logits_flat, deltas_flat = rpn_head(fs)\n#\n# print('logits_flat ', logits_flat.size())\n# print('deltas_flat ', deltas_flat.size())\n# print('')\n#\n#\n# def run_check_crop_head():\n# # feature maps\n# batch_size = 4\n# in_channels = 128\n# out_channels = 256\n# H, W = 256, 256\n# num_scales = 4\n# feature_heights = [int(H // 2 ** l) for l in range(num_scales)]\n# feature_widths = [int(W // 2 ** l) for l in range(num_scales)]\n#\n# fs = []\n# for h, w in zip(feature_heights, feature_widths):\n# f = np.random.uniform(-1, 1, size=(batch_size, in_channels, h, w)).astype(np.float32)\n# f = Variable(torch.from_numpy(f)).cuda()\n# fs.append(f)\n#\n# # proposal i,x0,y0,x1,y1,score, label\n# proposals = []\n# for b in range(batch_size):\n# num_proposals = 4\n# xs = np.random.randint(0, 64, num_proposals)\n# ys = np.random.randint(0, 64, num_proposals)\n# sizes = np.random.randint(8, 64, num_proposals)\n# scores = np.random.uniform(0, 1, num_proposals)\n#\n# proposal = np.zeros((num_proposals, 7), np.float32)\n# proposal[:, 0] = b\n# proposal[:, 1] = xs\n# proposal[:, 2] = ys\n# proposal[:, 3] = xs + sizes\n# proposal[:, 4] = ys + sizes\n# proposal[:, 5] = scores\n# proposal[:, 6] = 1\n# proposals.append(proposal)\n#\n# proposals = np.vstack(proposals)\n# proposals = Variable(torch.from_numpy(proposals)).cuda()\n#\n# # --------------------------------------\n# cfg = Configuration()\n# crop_net = CropRoi(cfg).cuda()\n# crops = crop_net(fs, proposals)\n#\n# print('crops', crops.size())\n# print('')\n# # exit(0)\n#\n# crops = crops.data.cpu().numpy()\n# proposals = proposals.data.cpu().numpy()\n#\n# # for m in range(num_proposals):\n# for m in range(8):\n# crop = crops[m]\n# proposal = proposals[m]\n#\n# i, x0, y0, x1, y1, score, label = proposal\n#\n# print('i=%d, x0=%3d, y0=%3d, x1=%3d, y1=%3d, score=%0.2f' % (i, x0, y0, x1, y1, score))\n# print(crop[0, 0, :5])\n# print('')\n#\n#\n# def run_check_rcnn_head():\n# num_rois = 100\n# in_channels = 256\n# crop_size = 14\n#\n# crops = np.random.uniform(-1, 1, size=(num_rois, in_channels, crop_size, crop_size)).astype(np.float32)\n# crops = Variable(torch.from_numpy(crops)).cuda()\n#\n# cfg = Configuration()\n# assert (crop_size == cfg.rcnn_crop_size)\n#\n# rcnn_head = RcnnHead(cfg, in_channels).cuda()\n# logits, deltas = rcnn_head(crops)\n#\n# print('logits ', logits.size())\n# print('deltas ', deltas.size())\n# print('')\n#\n#\n# def run_check_mask_head():\n# num_rois = 100\n# in_channels = 256\n# crop_size = 14\n#\n# crops = np.random.uniform(-1, 1, size=(num_rois, in_channels, crop_size, crop_size)).astype(np.float32)\n# crops = Variable(torch.from_numpy(crops)).cuda()\n#\n# cfg = Configuration()\n# assert (crop_size == cfg.crop_size)\n#\n# mask_head = MaskHead(cfg, in_channels).cuda()\n# logits = mask_head(crops)\n#\n# print('logits ', logits.size())\n# print('')\n#\n#\n# ##-----------------------------------\n# def run_check_mask_net():\n# batch_size, C, H, W = 1, 3, 128, 128\n# feature_channels = 64\n# inputs = np.random.uniform(-1, 1, size=(batch_size, C, H, W)).astype(np.float32)\n# inputs = Variable(torch.from_numpy(inputs)).cuda()\n#\n# cfg = Configuration()\n# mask_net = MaskSingleShotNet(cfg).cuda()\n#\n# mask_net.set_mode('eval')\n# mask_net(inputs)\n#\n# print('rpn_logits_flat ', mask_net.rpn_logits_flat.size())\n# print('rpn_probs_flat ', mask_net.rpn_probs_flat.size())\n# print('rpn_deltas_flat ', mask_net.rpn_deltas_flat.size())\n# print('')\n#\n#\n# # main #################################################################\n# if __name__ == '__main__':\n# print('%s: calling main function ... ' % os.path.basename(__file__))\n#\n# run_check_feature_net()\n# # run_check_multi_rpn_head()\n# # run_check_crop_head()\n# # run_check_rcnn_head()\n# # run_check_mask_head()\n#\n# # run_check_mask_net()\n","sub_path":"mask_rcnn/net/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":33037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"478277313","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2010 Vauxoo C.A. (http://openerp.com.ve/) All Rights Reserved.\n# Javier Duran \n# \n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsability of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# garantees and support are strongly adviced to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\nimport wizard\nimport osv\nimport pooler\nfrom tools.translate import _\nimport time\nimport datetime\nfrom mx.DateTime import *\n\n\n\n_transaction_form = '''\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n'''\n\n_transaction_fields = {\n 'period_length': {'string': 'Period length (days)', 'type': 'integer', 'required': True, 'default': lambda *a:30},\n 'date_start': {'string':'Start Date','type':'date','required': True},\n 'user_res_id': {'string':'Salesman', 'type':'many2one', 'relation': 'res.users','required':False},\n 'partner_res_id': {'string':'Partner', 'type':'many2one', 'relation': 'res.partner','required':False},\n 'cat_res_id': {'string':'Category', 'type':'many2one', 'relation': 'product.category','required':False},\n 'u_check': {'string':'Check salesman?', 'type':'boolean'},\n 'p_check': {'string':'Check partner?', 'type':'boolean'},\n 'c_check': {'string':'Check category?', 'type':'boolean'},\n 'u_sel':{\n 'string':\"Sequence\",\n 'type':'selection',\n 'selection':[('one','1'),('two','2'),('three','3'),('none','No Filter')],\n 'default': lambda *a:'none'\n },\n 'p_sel':{\n 'string':\"Sequence\",\n 'type':'selection',\n 'selection':[('one','1'),('two','2'),('three','3'),('none','No Filter')],\n 'default': lambda *a:'none'\n },\n 'c_sel':{\n 'string':\"Sequence\",\n 'type':'selection',\n 'selection':[('one','1'),('two','2'),('three','3'),('none','No Filter')],\n 'default': lambda *a:'none'\n },\n\n\n}\n\ndef _data_save(self, cr, uid, data, context):\n form = data['form']\n if not form['u_check'] and not form['p_check'] and not form['c_check']:\n raise wizard.except_wizard(_('User Error'), _('You have to check one box !')) \n res = {}\n period_length = data['form']['period_length']\n if period_length<=0:\n raise wizard.except_wizard(_('UserError'), _('You must enter a period length that cannot be 0 or below !'))\n start = datetime.date.fromtimestamp(time.mktime(time.strptime(data['form']['date_start'],\"%Y-%m-%d\")))\n start = DateTime(int(start.year),int(start.month),int(start.day))\n\n for i in range(4)[::-1]:\n stop = start - RelativeDateTime(days=period_length)\n res[str(i)] = {\n 'name' : str((4-(i+1))*period_length) + '-' + str((4-i)*period_length),\n \n 'stop': start.strftime('%Y-%m-%d'),\n 'start' : stop.strftime('%Y-%m-%d'),\n }\n start = stop - RelativeDateTime(days=1)\n\n return res\n\nclass wiz_trial_cost(wizard.interface):\n states = {\n 'init': {\n 'actions': [],\n 'result': {'type': 'form', 'arch':_transaction_form, 'fields':_transaction_fields, 'state':[('end','Cancel'),('print','Print Trial Profitability')]}\n },\n 'print': {\n 'actions': [_data_save],\n 'result': {'type':'print', 'report':'profit.trial.cost', 'state':'end'},\n },\n\n }\nwiz_trial_cost('profit.trial.cost')\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n\n","sub_path":"report_profit/tmp/wizard/wizard_trial_cost.py","file_name":"wizard_trial_cost.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"253229150","text":"from django.db import models\n\n\nclass Album(models.Model):\n title = models.CharField(max_length=150, verbose_name='Заголовок')\n description = models.TextField(blank=True, null=True, verbose_name='Описание')\n date = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания',blank=True, null=True)\n\n def __str__(self):\n return f'{self.title}'\n\n class Meta:\n verbose_name = 'альбом'\n verbose_name_plural = 'альбомы'\n\nclass Photo(models.Model):\n title = models.CharField(max_length=150, verbose_name='Заголовок')\n album = models.ForeignKey(Album, on_delete=models.CASCADE, blank=True, null=True, verbose_name='Альбом')\n description = models.TextField(blank=True, null=True, verbose_name='Описание')\n photo = models.ImageField(upload_to='photos/', verbose_name='Фото')\n liked = models.IntegerField(default=0, verbose_name='Количество лайков')\n\n def __str__(self):\n return f'{self.title}'\n\n class Meta:\n verbose_name = 'фотографию'\n verbose_name_plural = 'фотографии'\n\n\n\n\n\n","sub_path":"mane/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"211367303","text":"from collections import Counter\n\ndef main():\n t = int(input())\n for i in range (0,t):\n n = int(input())\n result = solve(n)\n print(\"Case #%d: %s\"%(i+1,result))\n\ndef solve(n):\n if n == 0:\n return \"INSOMNIA\"\n else:\n i = 1\n count = Counter()\n while len(set(count)) != 10:\n #print(\"Update: \"+str(n*i))\n count.update(str(n*i))\n i += 1\n return (i-1)*n\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"codes/CodeJamCrawler/CJ/16_0_1_Aruscher_main.py","file_name":"16_0_1_Aruscher_main.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"130681211","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 28 18:13:36 2018\n\n@author: Utkarsh\n\"\"\"\n\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport skimage.morphology as sm\nfrom skimage import filters\nimport skimage\nimport os\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nfrom Feature_Extraction.src.getTerminationBifurcation import getTerminationBifurcation\nfrom Feature_Extraction.src.removeSpuriousMinutiae import removeSpuriousMinutiae\nfrom Feature_Extraction.src.getGradient import getGradient\nfrom Feature_Extraction.src.CommonFunctions import *\nfrom Feature_Extraction.src.extractMinutiaeFeatures import extractMinutiaeFeatures\nfrom Feature_Extraction.src.matchMinutiae import getSimilarity\n\n\ndef getFeatures(img_id, featureNum=20):\n try:\n Features = pd.read_excel(os.path.join(FEATURE_DIR, \"{:02d}.xlsx\".format(img_id)))\n return Features[:featureNum]\n except FileNotFoundError:\n pass\n img_name = \"{:02d}.tif\".format(img_id)\n centerdf = pd.read_excel(os.path.join(DATA_DIR, \"new_center.xlsx\")).astype(int)\n center = tuple(centerdf.loc[img_id-1])\n # print(\"center :{}\".format(center))\n img = cv2.imread('../rotated/'+img_name, 0)\n # 获取二值化图像\n img_01 = np.uint8(img > 128)\n # skeletonize细化图像,细化用于减少二值图像中的每个连通分量,到一个单像素宽的骨架。\n skel = sm.skeletonize(img_01)\n skel = np.uint8(skel) * 255\n # 未经细化的二值图像\n mask = img_01 * 255\n mask = sm.dilation(mask, sm.disk(1))\n cv2.imwrite(os.path.join(RESULT_DIR, \"{:02d}mask.png\".format(img_id)), mask)\n\n foregroundArea = sm.closing(mask, sm.disk(15))\n edge_filter = sm.erosion(foregroundArea, sm.disk(15))\n\n cv2.imwrite(os.path.join(RESULT_DIR, \"{:02d}edge_filter.png\".format(img_id)), edge_filter)\n # gradientX, gradientY = getGradient(mask)\n\n # 原始端点和分叉点\n (minutiaeTerm, minutiaeBif) = getTerminationBifurcation(skel, mask)\n\n Features = extractMinutiaeFeatures(skel, minutiaeTerm, minutiaeBif, center)\n Features = removeSpuriousMinutiae(Features, edge_filter, 5)#[:NUM_POINTS]\n # print(len(Features))\n Features.to_excel(os.path.join(FEATURE_DIR, \"{:02d}.xlsx\".format(img_id)))\n # print(\"Features:\\n {}\".format(Features))\n ShowResults(skel, Features, edge_filter, center, img_id, False)\n return Features[:featureNum]\n\ndef print_all_Features_len():\n for i in range(1, NUM_PIC+1):\n Features = getFeatures(i, 200)\n print(len(Features))\n\ndef print_all_Bytes():\n for i in range(1, NUM_PIC+1):\n Features = getFeatures(i, 20)\n prettyBytesStr = getPrettyFeaturesBytes(Features)\n print(prettyBytesStr)\n print()\n\ndef get_match_result(featureNum=20):\n similarityMat = np.zeros((NUM_PIC, NUM_PIC))\n for i in range(NUM_PIC):\n for j in range(NUM_PIC):\n Features1 = getFeatures(i+1, featureNum)\n Features2 = getFeatures(j+1, featureNum)\n total_potential = getSimilarity(Features1, Features2)\n similarityMat[i, j] = total_potential\n plot_mat(similarityMat, name=\"similarityMat{}\".format(featureNum))\n pd.DataFrame(similarityMat).to_excel(os.path.join(FEATURE_DIR, \"similarityMat{}.xlsx\".format(featureNum)))\n return similarityMat\n\ndef getMatError(mat1, mat2):\n errMat = np.abs(mat1-mat2)\n avgErr = np.mean(errMat)\n maxErr = np.max(errMat)\n return avgErr, maxErr\n\ndef compare_match_result(featureNumLst=[10, 15, 20]):\n lstLen = len(featureNumLst)\n avgErrMat = np.zeros((lstLen, lstLen))\n maxErrMat = np.zeros((lstLen, lstLen))\n similarityMatLit = []\n for featureNum in featureNumLst:\n similarityMatLit.append(get_match_result(featureNum))\n for i in range(lstLen):\n for j in range(lstLen):\n avgErr, maxErr = getMatError(similarityMatLit[i], similarityMatLit[j])\n avgErrMat[i, j] = avgErr\n maxErrMat[i, j] = maxErr\n pd.DataFrame(avgErrMat).to_excel(os.path.join(FEATURE_DIR, \"avgErrMat.xlsx\"))\n pd.DataFrame(maxErrMat).to_excel(os.path.join(FEATURE_DIR, \"maxErrMat.xlsx\"))\n\nif __name__ == '__main__':\n # print_all_Features_len()\n print_all_Bytes()\n compare_match_result()\n\n","sub_path":"第2场训练赛/Fingerprint feature extraction/Fingerprint feature extraction latex __/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"126120308","text":"import sys\nimport os\nFiles = os.listdir(os.getcwd() + '/TO BE CONVERTED')\n\n# Change encoding_from and encoding_to parameters as you desired\n\ndef correctSubtitleEncoding(filename, newFilename, encoding_from = 'iso-8859-9', encoding_to='UTF-8'):\n with open(os.getcwd() + '/TO BE CONVERTED/' + filename, 'r', encoding=encoding_from) as fr:\n with open(os.getcwd() + '/CONVERTED/' + newFilename, 'w', encoding=encoding_to) as fw:\n for line in fr:\n fw.write(line[:-1]+'\\n')\n\nfor NameOfFile in Files:\n correctSubtitleEncoding(NameOfFile, NameOfFile.replace('.srt', '_UTF8.srt'))","sub_path":"UnicodeChanger.py","file_name":"UnicodeChanger.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"152835939","text":"# PROBLEM DESCRIPTION:\n# The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: \n# (you may want to display this pattern in a fixed font for better legibility)\n# P A H N\n# A P L S I I G\n# Y I R\n# And then read line by line: \"PAHNAPLSIIGYIR\"\n# \n# Write the code that will take a string and make this conversion given a number of rows:\n# \n# string convert(string s, int numRows);\n# \n# EXAMPLES:\n# INPUT: OUTPUT:\n# s = \"PAYPALISHIRING\", numRows = 3 \"PAHNAPLSIIGYIR\" \n# \n# INPUT: OUTPUT:\n# s = \"PAYPALISHIRING\", numRows = 4 \"PINALSIGYAHRPI\" \n# \n# EXPLANATION:\n# P I N\n# A L S I G\n# Y A H R\n# P I\n\nclass Solution:\n def convert(self, s: str, numRows: int) -> str:\n if not s: return \"\"\n \n result = [''] * numRows\n invert = False\n ind = 0\n for char in s:\n if invert:\n ind -= 1\n result[ind] += char \n if ind <= 0: \n invert = not invert\n # increment the index because you have crossed over to -1\n # bring it back to 0 (lower boundary)\n ind += 1\n \n else:\n result[ind] += char\n ind +=1\n if ind >= numRows: \n invert = not invert\n # same as above adjustment, decrement index to numRows-1 (actual len of array)\n ind -= 1\n \n res = \"\"\n for i in range(len(result)):\n res += result[i]\n \n return res","sub_path":"leetcode/zigzag_conversion.py","file_name":"zigzag_conversion.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"404887550","text":"# 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。\n# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。\n# 你可以假设 nums1 和 nums2 不会同时为空。\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n nums1.extend(nums2)\n nums1.sort()\n N = len(nums1)\n if N % 2 == 1:\n return nums1[N // 2]\n else:\n return (nums1[N // 2] + nums1[N // 2 - 1]) / 2\n","sub_path":"LeetCodePython/No004.py","file_name":"No004.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"82337660","text":"import sys \n# import pymysql as mysql\nimport getopt\nimport os.path\nfrom os import getenv\nimport os.path\n\nfrom enum import Enum\n\nclass databaseType(Enum):\n NONE = 0\n MYSQL = 1\n SQLITE = 2\n LAST = 3\n\nclass msgParser:\n echo=False\n db=None\n cursor=None\n rowIdx=0\n sqlResults=[]\n log=None\n\n database = databaseType.NONE\n\n param = {\n 'database' : 'NODATA',\n 'user' : 'NOBODY',\n 'password' : 'NOTHING',\n 'host' : 'localhost',\n 'connected' : 'false',\n 'verbose' : 'false',\n 'output-format' : 'interactive', # interactive, json, or forth\n 'database-type' : 'NONE',\n 'database-dir' : \"/var/tmp\",\n 'log-file' : \"NONE\",\n 'mqtt-host' : \"localhost\",\n 'mqtt-port' : \"1883\"\n }\n\n def __init__(self):\n localDbDir = getenv(\"CTL_DB\")\n\n if localDbDir != None :\n self.param['database-dir']=localDbDir\n\n if self.param['log-file'] != \"NONE\":\n self.log = open( self.param['log-file'], 'a') \n\n def __del__(self):\n pass\n\n def output(self, msg ):\n opFormat = self.param['output-format']\n\n if opFormat == 'forth':\n op=chr(len(msg)) + msg\n print( op,end=\"\" )\n elif opFormat == 'interactive':\n print( msg )\n else:\n print(msg)\n\n if self.log !=None:\n self.inToLog( str(msg ))\n\n\n def dumpData(self):\n print(\"database : \" + self.param['database'])\n print(\"user : \" + self.param['user'])\n print(\"password : \" + self.param['password'])\n print(\"host : \" + self.param['host'])\n print(\"Database Type :\" , self.param['database-type'])\n print(\"Database Dir :\" , self.param['database-dir'])\n print(\"Database State:\" , self.param['connected'])\n print(\"Output Format :\" , self.param['output-format'])\n print(\"MQTT Server :\" , self.param['mqtt-host'])\n print(\"MQTT Port :\" , self.param['mqtt-port'])\n\n\n def setDatabaseType(self, dbType):\n if dbType == 'MYSQL':\n self.param['database-type'] = dbType\n self.database = databaseType.MYSQL\n elif dbType == 'SQLITE':\n self.param['database-type'] = dbType\n self.database = databaseType.SQLITE\n else:\n self.param['database-type'] = 'NONE'\n self.database = databaseType.NONE\n\n def setEcho(self,flag):\n self.echo=flag\n\n def getEcho(self):\n return self.echo\n\n\n def getParam(self,name):\n failFlag=True\n rc=[failFlag, \"\"]\n\n if name in self.param:\n failFlag=False\n rc=[ failFlag,self.param[name] ]\n else:\n failFlag=True\n rc=[ failFlag,\"\" ]\n\n return rc\n\n def setParam(self,name, value):\n failFlag=True\n\n if name in self.param:\n self.param[name] = value\n failFlag=False\n else:\n failFlag=True\n\n return failFlag\n\n def dbConnect(self):\n failFlag=True\n rc=[failFlag, \"\"]\n\n if self.database is databaseType.MYSQL:\n import pymysql as mysql\n self.db=mysql.connect( self.param['host'],\n self.param['database'],\n self.param['user'],\n self.param['password'] )\n elif self.database is databaseType.SQLITE:\n import sqlite3 as sqlite\n\n dbDir = getenv(\"CTL_DB\")\n if dbDir == None:\n dbDir = self.param['database-dir']\n# self.param['database-dir'] = localDbDir\n\n dbPath = dbDir + \"/\" + self.param['database'] + \".db\"\n\n if self.param['verbose'] == 'true':\n print(\"Connecting to \" + dbPath )\n\n self.db = sqlite.connect( dbPath )\n# print(\"Self.db is \" , self.db)\n failFlag=False\n \n self.cursor = self.db.cursor()\n\n if self.database is databaseType.MYSQL:\n sql=' use ' + self.param['database']\n \n if self.param['verbose'] == 'true':\n print(\"sql>\"+sql)\n \n if 0 == self.cursor.execute( sql ):\n failFlag=False\n else:\n failFlag=True\n\n rc=[failFlag, \"\"]\n\n if rc[0]:\n self.param['connected'] = 'false'\n else:\n self.param['connected'] = 'true'\n self.output(\"CONNECTED\")\n\n\n return rc\n\n\n def outToLog(self, msg):\n self.log.write(\"-->:\" + msg + \":\\n\")\n self.log.flush()\n os.fsync(self.log)\n\n def inToLog(self, msg):\n self.log.write(\"<--:\" + msg + \":\\n\")\n self.log.flush()\n os.fsync(self.log)\n\n def localParser(self,cmd):\n failFlag=True\n rc=[failFlag, \"\"]\n\n c = cmd.split()\n paramCount = len(c)\n\n if self.log != None:\n self.outToLog(cmd)\n\n\n if paramCount == 1:\n if c[0] == \"help\": \n print(\"Help\")\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"print\":\n self.dumpData()\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"connect\":\n rc=self.dbConnect()\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"get-columns\":\n fLen = len(self.cursor.description)\n fieldName = [i[0] for i in self.cursor.description]\n\n print(fieldName)\n failFlag=False\n rc=[failFlag, \"\"]\n\n elif c[0] == \"get-row-count\":\n print(len(self.sqlResults))\n failFlag=False\n rc=[failFlag, \"\"]\n\n elif c[0] == \"get-row\":\n try:\n# print(\"get-row\", self.rowIdx)\n print(self.sqlResults[self.rowIdx])\n failFlag=False\n except:\n print(\"ERROR\")\n failFlag = True\n\n rc=[failFlag, \"\"]\n elif c[0] == \"go-first\":\n self.rowIdx=0\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"go-last\":\n self.rowIdx= len(self.sqlResults)-1\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"go-prev\":\n if self.rowIdx > 0:\n self.rowIdx -=1\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"get-next\":\n if self.rowIdx >= len(self.sqlResults)-1 :\n print(\"END\")\n else:\n self.rowIdx += 1\n print(self.sqlResults[self.rowIdx])\n\n failFlag=False\n rc=[failFlag, \"\"]\n\n elif c[0] == \"go-next\":\n if self.rowIdx >= len(self.sqlResults)-1 :\n print(\"END\")\n else:\n print(\"OK\")\n self.rowIdx += 1\n\n failFlag=False\n rc=[failFlag, \"\"]\n else:\n failFlag=True\n rc=[failFlag, \"\"]\n\n elif paramCount == 2:\n if c[0] == \"get\":\n failFlag=False\n\n rc = self.getParam(c[1])\n rc[0]=False\n\n if rc[1] ==\"\":\n rc[1]=\"UNKNOWN\"\n self.output(rc[1])\n else:\n self.output(rc[1])\n\n elif c[0] == \"test\":\n self.output(c[1])\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"get-col\":\n fred=self.sqlResults[self.rowIdx]\n self.output(fred[c[1]])\n failFlag=False\n rc=[failFlag, \"\"]\n elif c[0] == \"load\":\n rc = self.getParam('database-dir')\n if rc[0] == False:\n cmdFile = rc[1] + '/' + c[1]\n\n if not os.path.isfile(cmdFile) :\n print(\"NO-FILE\")\n return rc\n count=0\n with open(cmdFile) as fp:\n line=fp.readline()\n while line:\n rc=self.parseMsg(line)\n\n if self.getParam('verbose') == 'true':\n print(count,\":\" + line)\n line=fp.readline()\n\n elif c[0] == \"set-database\":\n self.setDatabaseType(c[1])\n failFlag=False\n rc=[failFlag, \"\"]\n\n elif paramCount == 3:\n if c[0] == \"set\":\n failFlag=self.setParam(c[1],c[2])\n rc=[failFlag, \"\"]\n\n return rc\n\n\n def executeSql(self, sql):\n self.sqlResults=[]\n self.rowIdx=0\n\n if self.getParam('verbose') == 'true':\n print(\"executeSql:\" + sql)\n try:\n# print(sql)\n self.cursor.execute(sql)\n self.db.commit()\n\n if self.cursor.description == None:\n pass\n else:\n fLen = len(self.cursor.description)\n fieldName = [i[0] for i in self.cursor.description]\n\n results = self.cursor.fetchall()\n rowCount = len(results);\n\n if fLen > 0:\n for row in results:\n count=0\n fred={}\n for col in row:\n fred[ fieldName[count] ] = col\n count += 1\n\n self.sqlResults.append(fred)\n\n except Exception :\n self.output(\"ERROR:SQL\")\n# self.output(sys.exc_info()[0])\n\n\n def parseMsg(self,msg):\n failFlag=True\n rc=[failFlag, \"\"]\n\n m=msg.strip()\n\n if len(m) == 0:\n failFlag=False\n rc=[failFlag, \"\"]\n else:\n\n if self.param['verbose'] == 'true':\n print(\"msg >\" + m + \"<\")\n \n if m[0] == '^':\n rc=self.localParser( m[1:] )\n else:\n# print(\"sql\")\n failFlag=False\n rc=[failFlag, \"\"]\n self.executeSql(msg)\n\n return rc\n\n\n\n","sub_path":"Automation/msgParser.py","file_name":"msgParser.py","file_ext":"py","file_size_in_byte":10485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"488250028","text":" # coding=utf-8\n\nimport sqlite3\nimport urllib.request, json\nfrom pprint import pprint\n\nfrom flask import Flask, render_template, request, g, redirect, flash, session\nfrom application import db\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom sqlalchemy import create_engine\nfrom collections import Counter\nfrom application.forms import complexForm, moreInformation, patternVerf, addFridge\nfrom wtforms.ext.sqlalchemy.fields import QuerySelectField\nfrom flask.ext.wtf import Form\n#from flask_bootstrap import Bootstrap\n#from application.models import Fridge, Store, Recipes\n\n# Elastic Beanstalk initalization\napplication = Flask(__name__)\napplication.secret_key = \"bahhah\"\n#Bootstrap(application)\napplication.debug=True\n# change this to your own value\napplication.secret_key = 'cC1YCIWOj9GgWspgNEo2'\n\ndb.init_app(application)\n\n\nclass Recipes(db.Model):\n\n id = db.Column(db.Integer, primary_key = True)\n name = db.Column(db.String(20))\n cuisine = db.Column(db.String(20))\n ingredient0 = db.Column(db.String(20))\n ing0quantity = db.Column(db.String(20))\n ingredient1 = db.Column(db.String(20))\n ing1quantity = db.Column(db.String(20))\n ingredient2 = db.Column(db.String(20))\n ing2quantity = db.Column(db.String(20))\n ingredient3 = db.Column(db.String(20))\n ing3quantity = db.Column(db.String(20))\n ingredient4 = db.Column(db.String(20))\n ing4quantity = db.Column(db.String(20))\n ingredient5 = db.Column(db.String(20))\n ing5quantity = db.Column(db.String(20))\n ingredient6 = db.Column(db.String(20))\n ing6quantity = db.Column(db.String(20))\n ingredient7 = db.Column(db.String(20))\n ing7quantity = db.Column(db.String(20))\n instructions = db.Column(db.String(20))\n calories = db.Column(db.Integer)\n protein = db.Column(db.Integer)\n\n\nclass Fridge(db.Model):\n __tablename__ = 'fridge'\n\n Ingredient = db.Column(db.String(20), primary_key = True)\n Quantity = db.Column(db.Integer)\n\nclass Store(db.Model):\n Store = db.Column(db.String(128), unique=False)\n Ingredient = db.Column(db.String(128), db.ForeignKey('fridge.Ingredient'), primary_key=True)\n Quantity = db.Column(db.Integer, unique=False)\n\n# class Store(db.Model):\n# __bind_key__ == 'store'\n# ingredient = db.Column(db.String(20), primary_key = True)\n# quantity = db.Column(db.Integer)\n\nselectedCuisine = ''\n\n@application.route('/', methods=['GET', 'POST'])\n@application.route('/index', methods=['GET', 'POST'])\ndef index():\n #allRecipes = Recipes.query.order_by(Recipes.calories.desc())\n #allRecipesMinusZero = Recipes.query.all()\n\n engine = create_engine('mysql+pymysql://krajput96:cs336proj@whatshouldieat.c8rryuxgrrfa.us-east-1.rds.amazonaws.com:3306/whatshouldieat', isolation_level=\"READ UNCOMMITTED\")\n connection1 = engine.connect()\n connection2 = engine.connect()\n connection3 = engine.connect()\n\n\n\n r = connection1.execute(\"select * from recipes\")\n f = connection2.execute(\"select * from fridge\")\n s = connection3.execute(\"select * from store\")\n\n recipes_data = {}\n fridge_list = []\n fridge_dict = {}\n count_Recipe = {}\n store_data = {}\n recipe_calories_protein = {}\n store_location = {}\n\n store_location['me'] = \"Edison,NJ\"\n store_location['Costco'] = \"205+Vineyard+Rd,+Edison,+NJ+08817\"\n store_location['StopnShop'] = \"1049+US+Highway+1+South,+Edison,+NJ+08837\"\n store_location['Walmart'] = \"360+US+Highway+9+Route+N,+Woodbridge,+NJ+07095\"\n store_location['Shoprite'] = \"3600+Park+Ave,+South+Plainfield,+NJ+07080\"\n\n\n\n for rec in r:\n my_list = [(rec.ingredient0, rec.ing0quantity), (rec.ingredient1, rec.ing1quantity), (rec.ingredient2, rec.ing2quantity), (rec.ingredient3, rec.ing3quantity), (rec.ingredient4, rec.ing4quantity), (rec.ingredient5, rec.ing5quantity), (rec.ingredient6, rec.ing6quantity), (rec.ingredient7, rec.ing7quantity)]\n recipes_data[rec.id] = my_list\n\n for frid in f:\n fridge_list.append(frid[0])\n fridge_dict[frid[0]] = frid[1]\n\n for store in s:\n store_data[store.Ingredient] = [store.Store, store.Quantity]\n\n # print (recipes_data.get(1))\n # print (fridge_list)\n # for x in range(0, 1000):\n # counter = 0\n # for val in recipes_data.get(x):\n # if val in fridge_list:\n # counter = counter + 1\n # count_Recipe[x] = counter\n #\n # for key, value in recipes_data.items():\n # counter = 0\n # for val in value:\n # if (val[0] in fridge_list) and (val[1] >= fridge_dict[val[0]]) :\n # counter = counter + 1\n # count_Recipe[key] = counter\n #\n\n for key, value in recipes_data.items():\n counter = 0\n for val in value:\n if (val[0] in fridge_list) and (fridge_dict[val[0]] > val[1]):\n counter = counter + 1\n count_Recipe[key] = counter\n\n #print (count_Recipe)\n\n noIngredientMissing = []\n oneIngredientMissing = []\n twoIngredientMissing = []\n threeIngredientMissing = []\n\n for key, value in count_Recipe.items():\n if value == 8:\n noIngredientMissing.append(key)\n if value == 7:\n oneIngredientMissing.append(key)\n if value == 6:\n twoIngredientMissing.append(key)\n if value == 5:\n threeIngredientMissing.append(key)\n\n myAddress = \"Edison,NJ\"\n\n startString = \"http://www.mapquestapi.com/directions/v2/route?key=Gb2lkXAUokk1OaZJt1a7jSik8RIAfGu5&from=\"\n middleString = \"&to=\"\n\n directionQuery = startString + myAddress + middleString\n\n print(directionQuery)\n with urllib.request.urlopen(directionQuery+store_location.get('Costco')) as url:\n data = json.loads(url.read().decode())\n #print(data)\n\n #print(data['route']['legs'][0]['maneuvers'][0]['narrative'])\n\n # for i in data['route']['legs'][0]['maneuvers']:\n # print (i['narrative'])\n\n #send to phone\n\n\n\n #print (noIngredientMissing)\n\n\n # for x in range(1000):\n # counter = 0\n # for y, val in enumerate(recipes_data.get(x)):\n # if val in fridge_list:\n # counter += 1\n # print(counter)\n\n\n #\n # for rec in r:\n # count = 0\n # for frid in f:\n # if rec.ingredient0 == frid.Ingredient:\n # print ('ayee')\n\n #mexicanRecipes = Recipes.query.filter_by(cuisine = \"mexican\")\n complex_selection = complexForm(request.form)\n id_selection = moreInformation(request.form)\n pattern_verf = patternVerf(request.form)\n add_fridge = addFridge(request.form)\n\n allRecipesMinusZero = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n\n allRecipesMinusOne = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n\n allRecipesMinusTwo = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n\n allRecipesMinusThree = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n\n\n if request.method == 'POST' and add_fridge.validate_on_submit():\n addIng = add_fridge.ing.data\n theQuan = add_fridge.quan.data\n print(theQuan)\n data_entered = [(addIng, theQuan)]\n if int(theQuan or 0) > 8 or int(theQuan or 0) < 3:\n flash('The input you entered does not satisfy our constraints! Try again')\n return render_template('index.html',zeroMissing = allRecipesMinusZero, oneMissing=allRecipesMinusOne, twoMissing = allRecipesMinusTwo, threeMissing = allRecipesMinusThree, form3 = complex_selection, form4 = id_selection, form5 = pattern_verf, form6=add_fridge)\n else:\n try:\n db.add(data_entered)\n db.commit()\n db.session.close()\n print('success')\n except:\n output = 'Successfully Added! You added: '+str(addIng)+\" with quantity: \"+str(theQuan)+\" to the fridge!!\"\n flash(output)\n return render_template('index.html',zeroMissing = allRecipesMinusZero, oneMissing=allRecipesMinusOne, twoMissing = allRecipesMinusTwo, threeMissing = allRecipesMinusThree, form3 = complex_selection, form4 = id_selection, form5 = pattern_verf, form6=add_fridge)\n\n\n\n if request.method == 'POST' and complex_selection.validate_on_submit():\n target_cuisine = complex_selection.cuisine.data\n target_calories_protein = complex_selection.calories_protein.data\n print('hello')\n if target_cuisine == ' ':\n if target_calories_protein == 'High Protein' or target_calories_protein == 'Low Protein':\n if target_calories_protein == 'High Protein':\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n elif target_calories_protein == 'High Calories' or target_calories_protein == 'Low Calories':\n if target_calories_protein == 'High Calories':\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).order_by(Recipes.calpries).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n\n else:\n if target_calories_protein == 'High Protein' or target_calories_protein == 'Low Protein':\n if target_calories_protein == 'High Protein':\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein.desc()).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.protein).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n elif target_calories_protein == 'High Calories' or target_calories_protein == 'Low Calories':\n if target_calories_protein == 'High Calories':\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories.desc()).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).filter(Recipes.cuisine==target_cuisine).order_by(Recipes.calories).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n else:\n tuples0 = Recipes.query.filter(Recipes.id.in_(noIngredientMissing)).filter(Recipes.cuisine==target_cuisine).all()\n [next(s for s in allRecipesMinusZero if s.id == id) for id in noIngredientMissing]\n tuples1 = Recipes.query.filter(Recipes.id.in_(oneIngredientMissing)).filter(Recipes.cuisine==target_cuisine).all()\n [next(s for s in allRecipesMinusOne if s.id == id) for id in oneIngredientMissing]\n tuples2 = Recipes.query.filter(Recipes.id.in_(twoIngredientMissing)).filter(Recipes.cuisine==target_cuisine).all()\n [next(s for s in allRecipesMinusTwo if s.id == id) for id in twoIngredientMissing]\n tuples3 = Recipes.query.filter(Recipes.id.in_(threeIngredientMissing)).filter(Recipes.cuisine==target_cuisine).all()\n [next(s for s in allRecipesMinusThree if s.id == id) for id in threeIngredientMissing]\n return render_template('both.html', zeroMissing = tuples0, oneMissing = tuples1, twoMissing = tuples2, threeMissing = tuples3, form4 = id_selection)\n if request.method == 'POST' and id_selection.validate_on_submit():\n print ('hello')\n\n targetId = id_selection.moreInfo.data\n targetZip = id_selection.zipCode.data\n\n startString = \"http://www.mapquestapi.com/directions/v2/route?key=Gb2lkXAUokk1OaZJt1a7jSik8RIAfGu5&from=\"\n middleString = \"&to=\"\n\n directionQuery = startString + str(targetZip) + middleString\n\n print (directionQuery)\n\n #print(targetId)\n myList = []\n myMissingList = []\n storesNeeded = {}\n\n #print(recipes_data.get(int(targetId)))\n\n missingIngredients = {}\n\n\n\n for val in recipes_data.get(int(targetId)):\n if val[0]:\n myList.append((val[0], val[1]))\n #print(myList)\n\n # print(fridge_dict)\n\n for val in myList:\n if (val[0] not in fridge_list) or (fridge_dict[val[0]] < val[1]):\n myMissingList.append(val[0])\n #print(myMissingList)\n for val in myMissingList:\n storesNeeded[val] = store_data.get(val)\n\n # print (\"here\")\n # print (storesNeeded)\n #\n # print(myList)\n\n locationsNeeded = {}\n\n # print (myMissingList)\n\n for key, val in storesNeeded.items():\n locationsNeeded[val[0]] = []\n\n #print (locationsNeeded)\n\n for key, val in locationsNeeded.items():\n with urllib.request.urlopen(directionQuery+store_location.get(key)) as url:\n data = json.loads(url.read().decode())\n #print(data)\n\n #print(data['route']['legs'][0]['maneuvers'][0]['narrative'])\n for i in data['route']['legs'][0]['maneuvers']:\n list = locationsNeeded.get(key)\n list.append(i['narrative'])\n\n\n #print (locationsNeeded)\n\n\n return render_template('getInfo.html', result = targetId, allings = myList, stores = storesNeeded, directions = locationsNeeded) # below query is simple filter by, ordered by ID\n #result = Recipes.query.filter_by(cuisine = \"mexican\").order_by(desc(calories))\n # if request.method == 'POST' and pattern_selection.submit():\n # return render_template('pattern.html', mexicanData = mexicanCaloriesList) # below query is simple filter by, ordered by ID\n\n if request.method == 'POST' and pattern_verf.validate_on_submit():\n count0100 = 0\n count101200 = 0\n count201300 = 0\n count301400 = 0\n count401500 = 0\n count501600 = 0\n count601700 = 0\n count701800 = 0\n count801900 = 0\n count9011000 = 0\n p05 = 0\n p610 = 0\n p1115 = 0\n p1620 = 0\n p2125 = 0\n p2630 = 0\n p3135 = 0\n p3640 = 0\n selectedCuisine = pattern_verf.cuisine.data\n alldata = Recipes.query.filter(Recipes.cuisine == selectedCuisine)\n for tuples in alldata:\n if(tuples.calories<=100):\n count0100+=1\n elif(tuples.calories>100 and tuples.calories<=200):\n count101200+=1\n elif(tuples.calories>200 and tuples.calories<=300):\n count201300+=1\n elif(tuples.calories>300 and tuples.calories<=400):\n count301400+=1\n elif(tuples.calories>400 and tuples.calories<=500):\n count401500+=1\n elif(tuples.calories>500 and tuples.calories<=600):\n count501600+=1\n elif(tuples.calories>600 and tuples.calories<=700):\n count601700+=1\n elif(tuples.calories>700 and tuples.calories<=800):\n count701800+=1\n elif(tuples.calories>800 and tuples.calories<=900):\n count801900+=1\n else:\n count9011000+=1\n for tuples in alldata:\n if(tuples.protein<=5):\n p05+=1\n elif(tuples.protein>5 and tuples.protein<=10):\n p610+=1\n elif(tuples.protein>10 and tuples.protein<=15):\n p1115+=1\n elif(tuples.protein>15 and tuples.protein<=19):\n p1620+=1\n elif(tuples.protein>=20 and tuples.protein<=25):\n p2125+=1\n elif(tuples.protein>25 and tuples.protein<=30):\n p2630+=1\n elif(tuples.protein>30 and tuples.protein<=35):\n p3135+=1\n else:\n p3640+=1\n return render_template('chart.html', pickedCuisine = selectedCuisine, cal0100 = count0100, cal101200 = count101200, cal201300 = count201300,\n cal301400 = count301400, cal401500 = count401500, cal501600 = count501600, cal601700 = count601700,\n cal701800 = count701800, cal801900 = count801900, cal9011000 = count9011000, prot05 = p05, prot610 = p610,\n prot1115 = p1115, prot1620 = p1620, prot2125 = p2125, prot2630 = p2630, prot3135 = p3135, prot3640 = p3640)\n return render_template('index.html',zeroMissing = allRecipesMinusZero, oneMissing=allRecipesMinusOne, twoMissing = allRecipesMinusTwo, threeMissing = allRecipesMinusThree, form3 = complex_selection, form4 = id_selection, form5 = pattern_verf, form6=add_fridge)\n\n\n\n@application.route('/recipes/')\ndef count_me(input_str):\n if (input_str < 0) or (input_str > 10000):\n return NULL\n\n input_counter = Counter(input_str)\n response = []\n for letter, count in input_counter.most_common():\n response.append('\"{}\":{}'.format(letter, count))\n return '
'.join(response)\n\napplication.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://krajput96:cs336proj@whatshouldieat.c8rryuxgrrfa.us-east-1.rds.amazonaws.com:3306/whatshouldieat/recipes'\n# application.config['SQLALCHEMY_BINDS'] = {'fridge': 'mysql+pymysql://krajput96:cs336proj@whatshouldieat.c8rryuxgrrfa.us-east-1.rds.amazonaws.com:3306/whatshouldieat/fridge'}\n#\n\ndb = SQLAlchemy(application)\n\n\nif __name__ == '__main__':\n application.run(host='0.0.0.0')\n\n #host='0.0.0.0'\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":25399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"395684875","text":"import csv\r\n\r\nprint(\"PELATIHAN SMART IT EDUCATION\")\r\n\r\nnilaiHuruf = [\"A\",\"B\",\"C\",\"D\"]\r\nmataKursus = [\"Nilai Pengantar TI\",\r\n \"Nilai Aplikasi Perkantoran\",\r\n ]\r\n\r\nprint(\"\")\r\nprint(\"=\"*50)\r\nprint(\"\")\r\n\r\nwith open('nilai.csv', mode='a') as csv_file:\r\n # membuat objek writer\r\n writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n # menulis baris ke file CSV\r\n nama = str(input(\"Nama : \"))\r\n nis = str(input(\"NIS : \"))\r\n\r\n \r\n print(\"Inputkan Nilai Pengantar TI\")\r\n nilaiUTSPTI= float(input(\"Nilai UTS : \"))\r\n nilaiUASPTI= float(input(\"Nilai UAS : \"))\r\n nilaiTugasPTI= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaPTI = ((30 * nilaiTugasPTI / 100) + (35 * nilaiUTSPTI / 100) + (35 * nilaiUASPTI / 100))\r\n print(nilaiAngkaPTI)\r\n if nilaiAngkaPTI >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([nis, nama, \"Pengantar TI\", nilaiAngkaPTI, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaPTI >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([nis, nama, \"Pengantar TI\", nilaiAngkaPTI, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaPTI >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([nis, nama, \"Pengantar TI\", nilaiAngkaPTI, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaPTI <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([nis, nama, \"Pengantar TI\", nilaiAngkaPTI, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaPTI >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n \r\n\r\n\r\n print(\"Inputkan Nilai Aplikasi Perkantoran\")\r\n nilaiUTSAP= float(input(\"Nilai UTS : \"))\r\n nilaiUASAP= float(input(\"Nilai UAS : \"))\r\n nilaiTugasAP= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaAP = ((30 * nilaiTugasAP / 100) + (35 * nilaiUTSAP / 100) + (35 * nilaiUASAP / 100))\r\n print(nilaiAngkaAP)\r\n if nilaiAngkaAP >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Aplikasi Perkantoran\", nilaiAngkaAP, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaAP >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Aplikasi Perkantoran\", nilaiAngkaAP, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaAP >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Aplikasi Perkantoran\", nilaiAngkaAP, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaAP <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Aplikasi Perkantoran\", nilaiAngkaAP, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaAP >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n \r\n print(\"Inputkan Nilai Internet\") \r\n nilaiUTSI= float(input(\"Nilai UTS : \"))\r\n nilaiUASI= float(input(\"Nilai UAS : \"))\r\n nilaiTugasI= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaI = ((30 * nilaiTugasI / 100) + (35 * nilaiUTSI / 100) + (35 * nilaiUASI / 100))\r\n print(nilaiAngkaI)\r\n if nilaiAngkaI >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Internet\", nilaiAngkaI, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaI >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Internet\", nilaiAngkaI, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaI >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Internet\", nilaiAngkaI, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaI <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Internet\", nilaiAngkaI, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaI >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n print(\"Inputkan Nilai Pengantar Jaringan Komputer\") \r\n nilaiUTSPJI= float(input(\"Nilai UTS : \"))\r\n nilaiUASPJI= float(input(\"Nilai UAS : \"))\r\n nilaiTugasPJI= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaPJI = ((30 * nilaiTugasPJI / 100) + (35 * nilaiUTSPJI / 100) + (35 * nilaiUASPJI / 100))\r\n print(nilaiAngkaPJI)\r\n if nilaiAngkaPJI >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Pengantar Jaringan Komputer\", nilaiAngkaPJI, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaPJI >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Pengantar Jaringan Komputer\", nilaiAngkaPJI, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaPJI >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Pengantar Jaringan Komputer\", nilaiAngkaPJI, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaPJI <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Pengantar Jaringan Komputer\", nilaiAngkaPJI, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaPJI >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n print(\"Inputkan Nilai Pemrograman Pascal\") \r\n nilaiUTSPP= float(input(\"Nilai UTS : \"))\r\n nilaiUASPP= float(input(\"Nilai UAS : \"))\r\n nilaiTugasPP= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaPP = ((30 * nilaiTugasPP / 100) + (35 * nilaiUTSPP / 100) + (35 * nilaiUASPP / 100))\r\n print(nilaiAngkaPP)\r\n if nilaiAngkaPP >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Pemrograman Pascal\", nilaiAngkaPP, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaPP >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Pemrograman Pascal\", nilaiAngkaPP, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaPP >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Pemrograman Pascal\", nilaiAngkaPP, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaPP <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Pemrograman Pascal\", nilaiAngkaPP, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaPP >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n print(\"Inputkan Nilai Desain Grafis\") \r\n nilaiUTSDG= float(input(\"Nilai UTS : \"))\r\n nilaiUASDG= float(input(\"Nilai UAS : \"))\r\n nilaiTugasDG= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaDG = ((30 * nilaiTugasDG / 100) + (35 * nilaiUTSDG / 100) + (35 * nilaiUASDG / 100))\r\n print(nilaiAngkaDG)\r\n if nilaiAngkaDG >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Desain Grafis\", nilaiAngkaDG, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaDG >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Desain Grafis\", nilaiAngkaDG, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaDG >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Desain Grafis\", nilaiAngkaDG, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaDG <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Desain Grafis\", nilaiAngkaDG, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaDG >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n\r\n print(\"Inputkan Nilai Dasar Pemrograman Web\") \r\n nilaiUTSDPW= float(input(\"Nilai UTS : \"))\r\n nilaiUASDPW= float(input(\"Nilai UAS : \"))\r\n nilaiTugasDPW= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaDPW = ((30 * nilaiTugasDPW / 100) + (35 * nilaiUTSDPW / 100) + (35 * nilaiUASDPW / 100))\r\n print(nilaiAngkaDPW)\r\n if nilaiAngkaDPW >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Dasar Pemrograman Web\", nilaiAngkaDPW, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaDPW >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Dasar Pemrograman Web\", nilaiAngkaDPW, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaDPW >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Dasar Pemrograman Web\", nilaiAngkaDPW, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaDPW <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Dasar Pemrograman Web\", nilaiAngkaDPW, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaDPW >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n\r\n print(\"Inputkan Nilai Video Editing\") \r\n nilaiUTSVE= float(input(\"Nilai UTS : \"))\r\n nilaiUASVE= float(input(\"Nilai UAS : \"))\r\n nilaiTugasVE= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaVE = ((30 * nilaiTugasVE / 100) + (35 * nilaiUTSVE / 100) + (35 * nilaiUASVE / 100))\r\n print(nilaiAngkaVE)\r\n if nilaiAngkaVE >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Video Editing\", nilaiAngkaVE, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaVE >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Video Editing\", nilaiAngkaVE, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaVE >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Video Editing\", nilaiAngkaVE, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaVE <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Video Editing\", nilaiAngkaVE, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaVE >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n print(\"Inputkan Nilai Short Movie\") \r\n nilaiUTSSM= float(input(\"Nilai UTS : \"))\r\n nilaiUASSM= float(input(\"Nilai UAS : \"))\r\n nilaiTugasSM= float(input(\"Nilai Tugas : \"))\r\n nilaiAngkaSM = ((30 * nilaiTugasSM / 100) + (35 * nilaiUTSSM / 100) + (35 * nilaiUASSM / 100))\r\n print(nilaiAngkaSM)\r\n if nilaiAngkaSM >=91 :\r\n print (nilaiHuruf[0])\r\n writer.writerow([\"\", \"\", \"Short Movie\", nilaiAngkaSM, nilaiHuruf[0],\"\"])\r\n elif nilaiAngkaSM >=81 :\r\n print (nilaiHuruf[1])\r\n writer.writerow([\"\", \"\", \"Short Movie\", nilaiAngkaSM, nilaiHuruf[1],\"\"])\r\n elif nilaiAngkaSM >=71 :\r\n print (nilaiHuruf[2])\r\n writer.writerow([\"\", \"\", \"Short Movie\", nilaiAngkaSM, nilaiHuruf[2],\"\"])\r\n elif nilaiAngkaSM <=70 :\r\n print (nilaiHuruf[3])\r\n writer.writerow([\"\", \"\", \"Short Movie\", nilaiAngkaSM, nilaiHuruf[3],\"\"])\r\n if nilaiAngkaSM >= 75 :\r\n print (\"Dinyatakan : Lulus\")\r\n else :\r\n print (\"Dinyatakan : Tidak Lulus\")\r\n\r\n\r\n jumlahnilai = nilaiAngkaPTI + nilaiAngkaAP + nilaiAngkaI + nilaiAngkaPJI + nilaiAngkaPP + nilaiAngkaDG + nilaiAngkaDPW + nilaiAngkaVE + nilaiAngkaSM\r\n nilairata2 = jumlahnilai/9\r\n \r\n print (\"Nama : %s\" %nama)\r\n print (\"Nim : %s\" %nis)\r\n print (\"Nilai Rata-Rata : \" ,float(nilairata2))\r\n writer.writerow([\"Rata-rata\", nilairata2])\r\n\r\n \r\nprint(\"\")\r\nprint(\"=\"*50)\r\nprint(\"\")\r\n \r\nprint(\"Nilai sudah masuk ke file csv\")\r\n\r\n","sub_path":"uas_prak_python.py","file_name":"uas_prak_python.py","file_ext":"py","file_size_in_byte":10103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"61692182","text":"from turtle import Turtle\r\nALIGNMENT = 'center'\r\nFONT = ('Arial', 50, 'normal')\r\n\r\n\r\nclass Scoreboard(Turtle):\r\n\r\n def __init__(self):\r\n super().__init__()\r\n self.player1_score = 0\r\n self.player2_score = 0\r\n self.color(\"white\")\r\n self.penup()\r\n self.goto(0, 220)\r\n self.update_scoreboard()\r\n self.hideturtle()\r\n\r\n def increase_score1(self):\r\n self.player1_score += 1\r\n self.clear()\r\n self.update_scoreboard()\r\n\r\n def increase_score2(self):\r\n self.player2_score += 1\r\n self.clear()\r\n self.update_scoreboard()\r\n\r\n def update_scoreboard(self):\r\n self.write(f\"{self.player1_score} : {self.player2_score}\", font=FONT, align=ALIGNMENT)\r\n\r\n def game_over(self):\r\n self.clear()\r\n if self.player1_score > self.player2_score:\r\n self.write(f\"Player 1 wins by {self.player1_score}:{self.player2_score}\", font=FONT, align=ALIGNMENT)\r\n else:\r\n self.write(f\"Player 2 wins by {self.player1_score}:{self.player2_score}\", font=FONT, align=ALIGNMENT)","sub_path":"scorebord.py","file_name":"scorebord.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"608426460","text":"import unittest\nfrom octane.model import Model\n\n\n# dummy test\nclass TestModel(unittest.TestCase):\n def test_model(self):\n model = Model([2, 5, 1], 0.01, 500)\n with model:\n model.train((\n [\n [1., 1.],\n [1., 0.],\n [0., 1.],\n [0., 0.],\n ],\n [\n [4.],\n [3.],\n [3.],\n [2.],\n ]\n ))\n prediction = model.feed_through([5., 3.])\n self.assertAlmostEqual(prediction[0][0], 10, delta=1)\n\n def test_model_decorator(self):\n model = Model([2, 1], 0.001, 2000)\n try:\n model.feed_through([1., 1.])\n self.assertTrue(False)\n except RuntimeError:\n self.assertTrue(True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"305651997","text":"\nMAX_CHAR = 26\n\n\ndef commonCharacters(strings, n):\n\n prim = [True] * MAX_CHAR\n\n for i in range(n):\n\n sec = [False] * MAX_CHAR\n\n for j in range(len(strings[i])):\n\n if (prim[ord(strings[i][j]) - ord('a')]):\n sec[ord(strings[i][j]) -\n ord('a')] = True\n\n for i in range(MAX_CHAR):\n prim[i] = sec[i]\n\n for i in range(26):\n if (prim[i]):\n print(\"%c \" % (i + ord('a')),\n end=\"\")\n\n\n# strings = [\"cool\",\"lock\",\"cook\"]\nstrings = [\"barodar\", \"dodar\", \"xahor\"]\nn = len(strings)\ncommonCharacters(strings, n)\n","sub_path":"1duplicate.py","file_name":"1duplicate.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"59493534","text":"import argparse\n\nimport numpy as np\nimport h5py\nimport imread\n\ndef find_keys(g, prefix=[]):\n try:\n for k in g.keys():\n yield \"/\".join(prefix + [k])\n for subkey in find_keys(g[k], prefix + [k]):\n yield subkey\n except:\n pass\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--input_hdf5\")\n parser.add_argument(\"-o\", \"--output_basename\")\n parser.add_argument(\"idx\")\n args = parser.parse_args()\n\n h5 = h5py.File(args.input_hdf5, 'r')\n for k in find_keys(h5):\n if isinstance(h5[k], h5py.Dataset):\n plane = h5[k][int(args.idx), :, :][...]\n if len(plane.shape) == 3:\n plane = plane[..., 0]\n plane = plane.astype(float)\n plane -= plane.min()\n plane /= plane.max()\n plane = (255 * plane).astype(np.uint8)\n imread.imwrite('{}_{}.png'.format(args.output_basename, k.replace('/', '_')), plane)\n","sub_path":"util/show_planes.py","file_name":"show_planes.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"228363841","text":"import sys, os\nimport wave\nimport contextlib\n\ndef getDuration(fileName):\n\n with contextlib.closing(wave.open(fileName,'r')) as f:\n frames = f.getnframes()\n rate = f.getframerate()\n duration = frames / float(rate)\n return int(duration*1000)\n\n\ndef sliceWav(infile, fileOutName, startMS, endMS):\n\n width = infile.getsampwidth()\n rate = infile.getframerate()\n fpms = rate / 1000 # frames per ms\n length = (endMS - startMS) * fpms\n start_index = startMS * fpms\n\n out = wave.open(fileOutName, \"w\")\n out.setparams((infile.getnchannels(), width, rate, length, infile.getcomptype(), infile.getcompname()))\n\n infile.rewind()\n anchor = infile.tell()\n infile.setpos(anchor + start_index)\n out.writeframes(infile.readframes(length))\n\n\ndef sliceSegmentIntoParts(pathToFile, partDurationMS = 5000):\n \"Slices a segment into short parts better digestable by SpeechRecognition\"\n\n slashPos = pathToFile.rfind(\"/\")\n if slashPos != -1:\n pathToDir = pathToFile[:pathToFile.rfind(\"/\")+1]\n fileInName = pathToFile[pathToFile.rfind(\"/\")+1:].replace(\".wav\",\"\").replace(\"_speech\",\"\")\n else:\n pathToDir = \"\"\n\n duration = getDuration(pathToFile)\n\n if duration < partDurationMS or duration < 1000:\n \"Segment is too short\"\n return []\n\n if partDurationMS < 1000:\n raise Exception(\"Duration of parts needs to be atleast a second\")\n\n startMS = 0\n endMS = startMS + partDurationMS\n fileNames = []\n\n while endMS <= duration:\n fileOutName = pathToDir + fileInName + \":\" + str(startMS) + \"-\" + str(endMS) + \".wav\"\n sliceWav(wave.open(pathToFile, \"r\"), fileOutName, startMS, endMS)\n fileNames.append(fileOutName)\n startMS = endMS - 500 #Half a second of puffer for speechRecognition\n endMS += partDurationMS\n\n #Add segment < partDurationMS at the end\n if endMS != duration:\n endMS = duration\n fileOutName = pathToDir + str(startMS) + \"-\" + str(endMS) + \".wav\"\n sliceWav(wave.open(pathToFile, \"r\"), fileOutName, startMS, endMS)\n fileNames.append(fileOutName)\n\n return fileNames\n","sub_path":"src/main/java/org/s16a/mcas/worker/Segmentation.py","file_name":"Segmentation.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"168862179","text":"import math\n\nfrom bokeh.io import show, output_file\nfrom bokeh.plotting import figure\nfrom bokeh.models import GraphRenderer, StaticLayoutProvider, Oval, Circle, LabelSet\nfrom bokeh.palettes import Spectral8\n\nN = 8\nnode_indices = list(range(N))\n\n# plot = figure(title='Graph Layout Demonstration', x_range=(-1.1,1.1), y_range=(-1.1,1.1),\nplot = figure(title='Graph Layout Demonstration', x_range=(-1.1,5), y_range=(-1.1,5),\n tools='', toolbar_location=None, names=['Mark', 'Amir', 'Matt', 'Greg',\n 'Owen', 'Juan'])\n\ngraph = GraphRenderer()\n\n\nLabelSet(x='x', y='y', text='names', level='glyph',\n x_offset=5, y_offset=5, source=plot)\n\ngraph.node_renderer.data_source.add(node_indices, 'index')\n# graph.node_renderer.data_source.add(\"Spectral8\", 'color')\ngraph.node_renderer.data_source.add([\"green\"]*N, 'color')\ngraph.node_renderer.data_source.add_layout(labels)\n# graph.node_renderer.glyph = Oval(height=0.1, width=0.2, fill_color='color')\ngraph.node_renderer.glyph = Circle(radius=0.1, fill_color='color')\n\ngraph.edge_renderer.data_source.data = dict(\n start=[0]*N,\n # start=[0,0,1,4,0,4,7,0],\n end=node_indices)\n\n### start of layout code\n# circ = [i*2*math.pi/8 for i in node_indices]\n# x = [math.cos(i) for i in circ]\n# y = [math.sin(i) for i in circ]\n\nx = [2*(i //3) for i in node_indices]\ny = [2* (i % 3) for i in node_indices]\n\ngraph_layout = dict(zip(node_indices, zip(x, y)))\ngraph.layout_provider = StaticLayoutProvider(graph_layout=graph_layout)\n\nplot.renderers.append(graph)\n\noutput_file('graph.html')\nshow(plot)","sub_path":"projects/graph/src/draw5.py","file_name":"draw5.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"569032599","text":"import pygame\n\n\ndef getx():\n x = randrange(20, (SCREEN_WIDTH - 40))\n return x\n\ndef gety():\n y = randrange(20, (SCREEN_HEIGHT - 40))\n return y\n\n\nclass Obstacle:\n\n def __init__(self, colour, x, y, radius):\n self.x = x \n self.y = y\n \n self.radius = radius \n self.width = 2 * self.radius\n self.height = 2 * self.radius\n \n self.colour = colour\n self.health = (self.radius / 30) * 400\n \n self.last_hit = 0\n self.wait_time = 7\n \n def create_obstacle(self):\n pygame.draw.ellipse(screen, self.colour, pygame.Rect(self.x, self.y, self.width, self.height))\n\n def isTouching(self, other):\n if type(other) == Bullet:\n dist = math.sqrt(((other.x + (other.width / 2)) - (self.x + self.radius)) ** 2 + ((other.y + (other.height / 2)) - (self.y + self.radius)) ** 2)\n return dist <= (self.radius + 4)\n \n elif type(other) == Obstacle:\n dist = math.sqrt(((other.x + other.radius) - (self.x + self.radius)) ** 2 + ((other.y + other.radius) - (self.y + self.radius)) ** 2)\n return dist <= self.width\n \n else:\n dist = math.sqrt(((other.x + 20) - (self.x + self.radius)) ** 2 + ((other.y + 20) - (self.y + self.radius)) ** 2)\n return dist <= self.width*0.8\n\n\nclass Obstacles:\n \n def __init__(self, num_of_obs, use_maps):\n self.obstacles = []\n self.num_of_obs = num_of_obs\n\n if use_maps == \"n\":\n range_1 = obstacle_numbers[num_of_obs][0]\n range_2 = obstacle_numbers[num_of_obs][1]\n for i in range(randrange(range_1, range_2)):\n while True:\n new_obstacle = Obstacle((87, 55, 41), getx(), gety(), uniform(20, uniform(32, 40)))\n if not self.isTouching(new_obstacle) and not new_obstacle.isTouching(p1) and not new_obstacle.isTouching(p2):\n self.obstacles.append(new_obstacle)\n break\n \n else:\n with open('TANKMaps.json', 'r') as map_file:\n map_file_contents = map_file.read()\n map_dict = json.loads(map_file_contents)\n selected_map = map_dict[num_of_obs]\n print(len(selected_map))\n \n for obstacle in selected_map:\n new_obstacle = Obstacle((87, 55, 41), obstacle[0], obstacle[1], obstacle[2])\n self.obstacles.append(new_obstacle)\n\n def isTouching(self, object):\n for obstacle in self.obstacles:\n if obstacle.isTouching(object):\n if type(object) == Bullet:\n obstacle.health -= 1 * bullet_penetration_factors[object.weaponclass]\n obstacle.last_hit = time.time()\n \n if obstacle.health <= 0:\n self.obstacles.remove(obstacle)\n \n return True\n\n return False\n\n def draw(self):\n for obstacle in self.obstacles:\n obstacle.create_obstacle()","sub_path":"obstacles.py","file_name":"obstacles.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"570457863","text":"## @file\n# @brief Classes and routines for dealing with round-robin and double-RR groups\n# of soccer teams.\n# @details Can simulate groups repeatedly and get aggregate results.\n# @author John Michael \"PsyMar\" Howard Boger\n# @date 2016.06.14\n# @version FutbolRatings 0.4.0\n# @since FutbolRatings 0.4.0, 2016.06.13\n# @copyright 2016 John Michael \"PsyMar\" Howard Boger\n# @copyright MIT License, see LICENSE file for more details.\n# @sa README.md\n\nfrom config import map_from_csv\nfrom main import calc_all_off_def\n\ntry:\n off_data = map_from_csv(\"data/offense.csv\")\n def_data = map_from_csv(\"data/defense.csv\")\n misc_data = map_from_csv(\"data/misc.csv\")\nexcept Exception:\n print(\"As initial ratings have not been calculated, \" \\\n \"we will now try calculating the ratings.\")\n calc_all_off_def()\n off_data = map_from_csv(\"data/offense.csv\")\n def_data = map_from_csv(\"data/defense.csv\")\n misc_data = map_from_csv(\"data/misc.csv\")\n\nimport random\nrandom.seed()\n \n## @brief Calculates the odds of each team scoring N goals for various N in a\n# single match.\n# @details N ranges from 0 to 20. We need a slightly different version than\n# the one used in main.py so we can adjust o/d for extra time when that's used.\n# @param[in] homeo The offensive strength of the home team.\n# @param[in] homed The defensive strength of the home team.\n# @param[in] awayo The offensive strength of the away team.\n# @param[in] awayd The defensive strength of the away team.\n# @param[in] HFAmult The home-field advantage multiplier (0 if neutral field).\n# @returns a tuple with 2 lists of the odds of the 2 respective teams scoring\n# N goals, respectively, where N ranges from 0 to 20. In other words,\n# the odds that team1 scores N goals is retval[team1name][N].\n# @note Uses file-global groups.misc_data .\n# @since FutbolRatings 0.4.0, 2016.06.13\ndef single_match_odds(homeo, homed, awayo, awayd, HFAmult):\n import math\n HFA_GF = float(misc_data[\"HFA_GF\"]) * HFAmult\n HFA_GA = float(misc_data[\"HFA_GA\"]) * HFAmult\n avg_G = float(misc_data[\"average_goals\"])\n home_GF_mult = 1+HFA_GF/avg_G\n home_GA_mult = 1-HFA_GA/avg_G\n home_GF_avg = math.sqrt(homeo*awayd*home_GF_mult)\n away_GF_avg = math.sqrt(awayo*homed*home_GA_mult)\n\n home_GF = []\n for goals in range(20):\n home_GF.append(math.pow(home_GF_avg,goals) * \\\n math.exp(-home_GF_avg)/math.factorial(goals))\n \n away_GF = []\n for goals in range(20):\n away_GF.append(math.pow(away_GF_avg,goals)* \\\n math.exp(-away_GF_avg)/math.factorial(goals))\n \n return home_GF, away_GF\n\n\n## @brief Given two teams' abilities, randomly simulates the result of a match\n# @details Uses groups.single_match_odds() to weight possibilities.\n# @param[in] homeo The offensive strength of the home team.\n# @param[in] homed The defensive strength of the home team.\n# @param[in] awayo The offensive strength of the away team.\n# @param[in] awayd The defensive strength of the away team.\n# @param[in] HFAmult The home-field advantage multiplier (0 if neutral field).\n# @returns A 2-tuple of how many goals were scored by each team.\n# @since FutbolRatings 0.4.0, 2016.06.13\ndef sim_game(homeo, homed, awayo, awayd, HFAmult):\n import random\n from itertools import accumulate\n import bisect\n from math import fsum\n homeodds,awayodds = single_match_odds(homeo, homed, awayo, awayd, HFAmult)\n hometotalodds = list(accumulate(homeodds))\n awaytotalodds = list(accumulate(awayodds))\n homerand = random.uniform(0,hometotalodds[-1])\n awayrand = random.uniform(0,awaytotalodds[-1])\n home_goals = bisect.bisect(hometotalodds, homerand)\n away_goals = bisect.bisect(awaytotalodds, awayrand)\n return home_goals, away_goals\n\n\n## @brief Class representing a single soccer match-up.\n# @details Includes team names and home field multiplier (default 1, set to 0 \n# if neutral-field). Also holds score, and simulates the game to get it if need\n# be.\n# @since FutbolRatings 0.4.0, 2016.06.13\nclass single_game:\n ## @brief Initializes a single game.\n # @param[in,out] self The object to be initialized.\n # @param[in] home The home team.\n # @param[in] away The away team.\n # @param[in] home_field_mult The home-field multiplier.\n # @param[in] score The score of the game. Defaults to None, i.e. unplayed,\n # in which case the game is simulated to decide the score. Otherwise should\n # be a 2-element iterable with home score first.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def __init__(self, home, away, home_field_mult = 1, *, score=None):\n self.home_team = home\n self.away_team = away\n if score is None:\n score = sim_game(home.offense, home.defense, away.offense, \\\n away.defense, home_field_mult)\n self.home_score = score[0]\n self.away_score = score[1]\n\n \n## @brief Holds data for a single team being simulated in a group.\n# @details Includes off/def ratings, points, GD, GF, and a list of games\n# played for tiebreaker purposes. Also includes name for passing this around.\n# @since FutbolRatings 0.4.0, 2016.06.13\nclass team_data:\n ## @brief Initializes all variables for the team.\n # @details name, offense and defense are initialized to parameters, others\n # to 0 or empty.\n # @param[in,out] self The object to be initialized.\n # @param[in] name The name of the team.\n # @param[in] offense The team's offensive rating.\n # @param[in] defense The team's defensive rating.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def __init__(self, name, offense, defense):\n self.name = name\n self.offense = float(offense)\n self.defense = float(defense)\n self.points = 0\n self.goal_diff = 0\n self.goals_for = 0\n self.away_goals = 0\n self.games_list = []\n \n ## @brief Add a game played by this team.\n # @details Updates points, goal_diff, goals_for, away_goals, & games_list.\n # @throws RuntimeError if self == neither game.home_team nor game.away_team\n # @since FutbolRatings 0.4.0, 2016.06.13\n def add_game(self, game):\n if game.home_team.name == self.name:\n if game.home_score > game.away_score:\n self.points += 3\n elif game.home_score == game.away_score:\n self.points += 1\n self.goal_diff += game.home_score - game.away_score\n self.goals_for += game.home_score\n self.games_list.append(game)\n elif game.away_team.name == self.name:\n if game.away_score > game.home_score:\n self.points += 3\n elif game.away_score == game.home_score:\n self.points += 1\n self.goal_diff += game.away_score - game.home_score\n self.goals_for += game.away_score\n self.away_goals += game.away_score\n self.games_list.append(game)\n else:\n raise RuntimeError(\"add_game tried to add a game not involving \" \\\n \"the team that invoked it.\")\n \n \n ## @brief Trims a team's data to include only results among tied teams.\n # @param[in] self The invoking object.\n # @param[in] team_list The teams with which self is tied.\n # @returns A copy of self with points, goal_diff, goals_for, away_goals, &\n # games_list adjusted to account only for the games against teams in\n # team_list.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def subgroup_results(self, team_list):\n self_copy = team_data(self.name, self.offense, self.defense)\n for game in self.games_list:\n if game.home_team in team_list and game.away_team in team_list:\n self_copy.add_game(game)\n return self_copy\n \n## @brief Returns this team's total points. Useful for sorting.\n# @param[in] The team whose points we need.\n# @returns This team's points scored in the group.\n# @since FutbolRatings 0.4.0, 2016.06.13\ndef pts(team):\n return team.points\n \n## @brief Returns a tuple for sorting by points, GD, and GF.\n# @param[in] team The team whose tuple must be retrieved.\n# @returns A tuple of points, goal_diff, and goals_for in that order.\n# @since FutbolRatings 0.4.0, 2016.06.13\ndef tupleify(team):\n return team.points, team.goal_diff, team.goals_for\n\n\n## @brief Class representing a group of soccer teams that play in a round robin\n# @details Can deal with single round-robins in a neutral location or a nation\n# as location; can deal with double round-robins home-and-away.\n# Can deal with tiebreaking rules for European championships or Copa America\n# or World Cup Qualifying and many other tournaments.\n# @since FutbolRatings 0.4.0, 2016.06.13\n# @sa groups.group_data_agg\nclass group_RR_sim:\n ## @brief Initializes data for each team in team_list to zeroes, sets\n # tiebreaks and host, then simulates the group.\n # @param[in,out] self The object to be initialized.\n # @param[in] team_list A list of the teams in the group.\n # @param[in] use_H2H Whether head-to-head tiebreaks are used at all.\n # Defaults to True.\n # @param[in] H2H_first If use_H2H is True (default), whether to use head to\n # head tiebreaks before overall goal difference and goals scored. Defaults\n # to False. If true, head-to-head is used repeatedly to stratify teams\n # before applying other tiebreakers.\n # @param[in] host The team hosting the tournament. Default neutral ground\n # for a single round robin, or home and away for double.\n # @param[in] double_RR True if this is a double round robin, False if it is\n # a single round robin. Default True if host is None (default), else it\n # defaults to False.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def __init__(self, team_list, *, use_H2H = True, H2H_first = False, host =\n None, double_RR = None, games_played = None):\n self.teams = []\n self.team_placements = None\n self.host = host\n if double_RR == None:\n if host == None:\n self.double_RR = True\n else:\n self.double_RR = False\n else:\n self.double_RR = double_RR\n # Note: \"overall\" tiebreak includes points first, but \"points\" is also\n # a seperate option for when head-to-head is used between points and\n # GD/GF.\n if not use_H2H:\n self.tiebreaks = [\"overall\",\"random\"]\n elif not H2H_first:\n self.tiebreaks = [\"overall\",\"H2H\",\"random\"]\n else:\n self.tiebreaks = [\"points\",\"H2H\",\"overall\",\"random\"]\n \n for team in team_list:\n self.teams.append(team_data(team,off_data[team],def_data[team]))\n \n self.played_games = {} \n for team in self.teams:\n self.played_games[team.name] = []\n if games_played is not None:\n self.fetch_played_games(games_played)\n \n self.run_sim()\n \n \n ## @brief Gets the results of games already played in the group from a\n # previously-read file.\n # @details These are stored in self.played_games, which maps team names to\n # pre-played games.\n # @param[in,out] self the invoking object\n # @param[in] indatacsv csv input data split by lines\n def fetch_played_games(self,indatacsv):\n for line in indatacsv:\n linesplitresult = line.split(',')\n team1name = linesplitresult[0]\n team2name = linesplitresult[2]\n team1 = None\n team2 = None\n for team in self.teams:\n if team.name == team1name:\n team1 = team\n if team.name == team2name:\n team2 = team\n score1 = int(linesplitresult[1],10)\n score2 = int(linesplitresult[3],10)\n playedgame = single_game(team1, team2, score=(score1,score2))\n self.played_games[team1name].append(playedgame)\n self.played_games[team2name].append(playedgame)\n \n ## @brief Simulates the group\n # @details Has each team play each other team once, then sorts by points,\n # and applies other tiebreakers. Sets team_placements and returns it\n # @param[in,out] self The invoking object.\n # @returns A list of teams in order of finish from first to last.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def run_sim(self):\n for team1 in self.teams:\n for team2 in self.teams:\n if team1.name > team2.name or \\\n (self.double_RR and (team1.name < team2.name)):\n if self.host == None:\n if self.double_RR:\n HFAmult = 1\n else:\n HFAmult = 0\n elif team1.name == self.host:\n HFAmult = 1\n elif team2.name == self.host:\n HFAmult = -1\n else:\n HFAmult = 0\n game_exists = False\n for game in self.played_games[team1.name]:\n if (game.home_team.name, game.away_team.name) == \\\n (team1.name, team2.name):\n team1.add_game(game)\n team2.add_game(game)\n game_exists = True\n break\n elif not self.double_RR and ((team2.name, team1.name) \\\n == (game.home_team.name, game.away_team.name)):\n game.home_team, game.away_team = \\\n game.away_team, game.home_team\n game.home_score, game.away_score = \\\n game.away_score, game.home_score\n team1.add_game(game)\n team2.add_game(game)\n game_exists = True\n break\n if not game_exists:\n newgame = single_game(team1, team2, HFAmult)\n team1.add_game(newgame)\n team2.add_game(newgame)\n \n tier_list = {0:[]}\n for team in self.teams:\n tier_list[0].append(team)\n # one-element dictionary mapping 0 to a list of all teams\n # now we stratify it\n for tiebreak in self.tiebreaks:\n tier_max_size = 0\n for tier_num in tier_list:\n if len(tier_list[tier_num]) > tier_max_size:\n tier_max_size = len(tier_list[tier_num])\n if tier_max_size > 1:\n tier_list = self.stratify_by_tiebreak(tier_list, tiebreak)\n # each tier now has only one team, since random is the last tiebreak\n # therefore we can do this\n self.team_placements = [\"\"]*len(self.teams)\n for place in tier_list:\n self.team_placements[place] = tier_list[place][0]\n \n\n ## @brief Breaks up a list of teams by the given tiebreak.\n # @details valid tiebreaks are \"points\", \"H2H\", \"overall\", and \"random\".\n # More may be added later.\n # @param[in] tier_list A list containing lists, each inner list being one\n # or more teams that are thus far equal on tiebreaks.\n # @param[in] tiebreak The tiebreaking method to use.\n # @returns A list of lists, each inner list being one or more teams that\n # are still equal per the given tiebreak.\n # @since FutbolRatings 0.4.0, 2016.06.13\n @staticmethod\n def stratify_by_tiebreak(tier_list, tiebreak):\n from itertools import groupby\n from random import shuffle\n new_tiers = {}\n next_tier = 0\n for tier_num in tier_list:\n if len(tier_list[tier_num]) == 1:\n new_tiers[next_tier]=tier_list[tier_num]\n next_tier += 1\n else:\n if tiebreak == \"random\":\n random.shuffle(tier_list[tier_num])\n for team in tier_list[tier_num]:\n new_tiers[next_tier] = [team,]\n next_tier += 1\n elif tiebreak == \"H2H\":\n tier2 = []\n for team in tier_list[tier_num]:\n blah = tupleify(team.subgroup_results(tier_list[tier_num]))\n blah2 = list(blah) + [team]\n tier2.append(tuple(blah2))\n def get_first_three(tup):\n return tup[0:3]\n tier2.sort(key=get_first_three, reverse=True)\n for k,g in groupby(tier2, get_first_three):\n g2 = [team for (a,b,c,team) in g]\n new_tiers[next_tier] = list(g2)\n next_tier += 1\n elif tiebreak == \"overall\":\n tier2 = sorted(tier_list[tier_num], key=tupleify, reverse=True)\n for k,g in groupby(tier2, tupleify):\n new_tiers[next_tier] = list(g)\n next_tier += 1\n elif tiebreak == \"points\":\n tier2 = sorted(tier, key=pts, reverse=True)\n for k,g in groupby(tier2, pts):\n new_tiers[next_tier] = list(g)\n next_tier += 1\n else:\n raise RuntimeError(\"Unknown tiebreak method\")\n return new_tiers\n\n \n## @brief Class representing aggregate data from many simulations of a team's\n# performance in a competition.\n# @details Includes team name, a list of how many times they finished in\n# each place in their group, as well as total points, GD, and GF in group.\n# @since FutbolRatings 0.4.0, 2016.06.13\nclass team_data_agg:\n ## @brief Initializes data for each team in team_list to zeroes.\n # @param[in,out] self The object to be initialized.\n # @param[in] name The name of the team.\n # @since FutbolRatings 0.4.0, 2016.06.13\n def __init__(self,name):\n self.name = name\n self.group_pts = 0\n self.group_GD = 0\n self.group_GF = 0\n self.group_placements = None\n\n ## @brief Adds the results of a group simulation to a team's aggregate data\n # @param[in,out] self The calling object.\n # @param[in] ordered_teams A simulated group's team_placements list.\n # @since FutbolRatings 0.4.0, 2016.06.14\n def add_group_sim(self, ordered_teams):\n if self.group_placements == None:\n self.group_placements = [0]*len(ordered_teams)\n for i,team in enumerate(ordered_teams):\n if team.name == self.name:\n self.group_pts += team.points\n self.group_GD += team.goal_diff\n self.group_GF += team.goals_for\n self.group_placements[i] += 1\n # that's all for this function\n \n\n## @brief Simulates a single game between two teams.\n# @param[in] hometeam The home team; must have attribs \"offense\" and \"defense\"\n# @param[in] awayteam The other team; must have attribs \"offense\" and \"defense\"\n# @param[in] HFAmult The home-field advantage multiplier, 0 if neutral field\n# @param[in] ET Whether the game uses 30 minutes' extra time in event of a tie.\n# Defaults to True.\n# @param[in] pens Whether the game goes to penalty kicks if tied after any\n# extra time. Defaults to True.\n# @returns The winning team, or None in case of an unresolved tie.\n# @since FutbolRatings 0.4.0, 2016.06.14\ndef single_game_sim(hometeam, awayteam, HFAmult, *, ET=True, pens=True):\n from random import randchoice\n homeg, awayg = sim_game(hometeam.offense, hometeam.defense, \\\n awayteam.offense, awayteam.defense, HFAmult)\n if homeg == awayg and ET:\n ETscore = sim_game(hometeam.offense/3, hometeam.defense/3, \\\n awayteam.offense/3, awayteam.defense/3, HFAmult) #HFAmult not /3\n homeg += ETscore[0]\n awayg += ETscore[1]\n if homeg > awayg:\n return hometeam\n elif homeg < awayg:\n return awayteam\n elif pens:\n return random.choice([hometeam, awayteam])\n else:\n return None\n\n \n## @brief Simulates a home-and-away series between two teams.\n# @param[in] team1 The team hosting the first leg.\n# @param[in] team2 The team hosting the second leg.\n# @param[in] AG Whether away goals are a tiebreaker. Default True.\n# @param[in] ET Whether extra time is a tiebreaker if away goals tied. Default\n# is True.\n# @param[in] ET_AG Set to False to not use away goals as a tiebreaker again\n# after extra time. Irrelevant if either ET or AG is False. Defaults True.\n# @param[in] pens Whether penalty kicks should be used in the event everything\n# else is tied. Default True.\n# @returns The winning team, or None in case of an unresolved tie.\n# @since FutbolRatings 0.4.0, 2016.06.14\ndef home_and_away_sim(team1, team2,*, AG=True, ET=True, ET_AG=True, pens=True):\n from random import choice\n game1goals = sim_game(team1.offense, team1.defense, \\\n team2.offense, team2.defense, 1)\n game2goals = sim_game(team2.offense, team2.defense, \\\n team1.offense, team1.defense, 1)\n team1_total = game1goals[0]+game2goals[1]\n team2_total = game1goals[1]+game2goals[0]\n if team1_total == team2_total and AG:\n team1_total += game2goals[1]\n team2_total += game1goals[1]\n if team1_total == team2_total and ET:\n ET_score = sim_game(team2.offense/3, team2.defense/3, \\\n team1.offense/3, team1.defense/3, 1)\n team1_total += ET_score[1]\n team2_total += ET_score[0]\n if team1_total == team2_total and AG and ET_AG:\n team1_total += ET_score[1]\n if team1_total > team2_total:\n return team1\n elif team1_total < team2_total:\n return team2\n elif pens:\n return random.choice([team1, team2])\n else:\n return None\n","sub_path":"src/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":21905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"412391463","text":"\r\nclass Solution:\r\n def productExceptSelf(self, nums):\r\n right = [1] * len(nums)\r\n \r\n prod = 1\r\n for i in range(len(nums) - 2, -1, -1):\r\n prod *= nums[i+1]\r\n right[i] = prod\r\n\r\n prod = 1\r\n for i in range(1, len(nums)):\r\n prod *= nums[i-1]\r\n right[i] *= prod\r\n\r\n return right\r\n\r\n\r\nprint(Solution().productExceptSelf([1, 2, 3, 4]))\r\n# [24, 12, 8, 6]","sub_path":"coderpro/product_array_except_self_pro.py","file_name":"product_array_except_self_pro.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"275717345","text":"\n\nfrom xai.brain.wordbase.nouns._commemoration import _COMMEMORATION\n\n#calss header\nclass _COMMEMORATIONS(_COMMEMORATION, ):\n\tdef __init__(self,): \n\t\t_COMMEMORATION.__init__(self)\n\t\tself.name = \"COMMEMORATIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"commemoration\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_commemorations.py","file_name":"_commemorations.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"98210787","text":"import contextlib\nimport sys\nimport time\nfrom pyke import knowledge_engine, krb_traceback, goal\n\nengine = knowledge_engine.engine(__file__)\n\ndef run():\n \n engine.reset()\n #engine.activate('')\n #engine.prove_1_goal('sintomas.febre($doenca, 38, 2)')\n \n dengue = 0\n chikungunya = 0\n zika = 0\n \n #FEBRE\n print(\"\\nHA FEBRE?\")\n print(\"[1] - Nao\")\n print(\"[2] - Abaixo de 38C\")\n print(\"[3] - Acima de 38C\")\n febre = int(input(\"Escolha uma opcao: \"))\n\n if(febre == 1):\n zika+=1\n elif(febre == 2):\n zika+=1\n elif(febre == 3):\n chikungunya+=1\n dengue+=1\n\n duracao_febre = 0\n if(febre!=1):\n print(\"\\nDURACAO DA FEBRE\")\n print(\"[1] - Entre 1 e 2 dias\")\n print(\"[2] - Entre 2 e 3 dias\")\n print(\"[3] - Mais de 4 dias\")\n duracao_febre = int(input(\"Escolha uma opcao: \"))\n \n if(duracao_febre == 1 & febre==2):\n zika+=1\n elif(duracao_febre == 2 & febre==3):\n chikungunya+=1\n elif(duracao_febre==3 & febre==3):\n dengue+=1\n\n #MANCHAS\n print(\"\\nHA MANCHAS?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n manchas = int(input(\"Escolha uma opcao: \"))\n\n if(manchas == 1):\n zika+=1\n chikungunya+=1\n dengue+=1\n\n dia_manchas = 0\n if(manchas == 1):\n print(\"\\nQUANDO SURGIRAM AS MACHAS?\")\n print(\"[1] - Entre o dia 1 e 2\")\n print(\"[2] - Entre o dia 2 e 5\")\n print(\"[3] - Apos o dia 4\")\n dia_manchas = int(input(\"Escolha uma opcao: \"))\n\n if(dia_manchas == 1):\n zika+=1\n elif(dia_manchas == 2):\n chikungunya+=1\n elif(dia_manchas == 3):\n dengue+=1\n\n #DOR MUSCULAR\n print(\"\\nHA DOR MUSCULAR?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n dor_muscular = int(input(\"Escolha uma opcao: \"))\n\n if(dor_muscular == 1):\n dengue+=1\n zika+=1\n chikungunya+=1\n\n #DOR ARTICULAR\n print(\"\\nHA DOR ARTICULAR?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n dor_articular = int(input(\"Escolha uma opcao: \"))\n\n if(dor_articular == 1):\n dengue+=1\n zika+=1\n chikungunya+=1\n\n intensidade_dor_articular = 0\n if(dor_articular == 1):\n print(\"\\nINTENSIDADE DE DOR ARTICULAR\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Alta\")\n intensidade_dor_articular = int(input(\"Escolha uma opcao: \"))\n\n if(intensidade_dor_articular == 1):\n dengue+=1\n elif(intensidade_dor_articular == 2):\n zika+=1\n elif(intensidade_dor_articular == 3):\n chikungunya+=1\n\n #EDEMA DAS ARTICULACOES\n print(\"\\nHA EDEMA DA ARTICULACAO?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n edema_articular = int(input(\"Escolha uma opcao: \"))\n\n if(edema_articular == 1):\n zika+=1\n chikungunya+=1\n elif(edema_articular==2):\n dengue+=1\n\n intensidade_edema_articular = 0\n if(edema_articular == 1):\n print(\"\\nINTENSIDADE DE EDEMA ARTICULAR\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Intensa\")\n intensidade_edema_articular = int(input(\"Escolha uma opcao: \"))\n \n if(intensidade_edema_articular == 1):\n zika+=1\n elif(intensidade_edema_articular == 2 | intensidade_edema_articular == 3):\n chikungunya+=1\n \n #CONJUNTIVITE\n print(\"\\nHA CONJUNTIVITE?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n conjuntivite = int(input(\"Escolha uma opcao: \"))\n\n if(conjuntivite == 1):\n zika+=1\n\n #DOR DE CABECA\n print(\"\\nHA DOR DE CABECA?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n dor_cabeca = int(input(\"Escolha uma opcao: \"))\n\n if(dor_cabeca == 1):\n dengue+=1\n zika+=1\n chikungunya+=1\n\n intensidade_dor_cabeca = 0\n if(dor_cabeca == 1):\n print(\"\\nINTENSIDADE DA DOR DE CABECA\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Intensa\")\n intensidade_dor_cabeca = int(input(\"Escolha uma opcao: \"))\n \n if(intensidade_dor_cabeca == 2):\n zika+=1\n chikungunya+=1\n \n elif(intensidade_dor_cabeca == 3):\n dengue+=1\n\n #COCEIRA\n print(\"\\nHA COCEIRA?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n coceira = int(input(\"Escolha uma opcao: \"))\n\n if(coceira == 1):\n dengue+=1\n zika+=1\n chikungunya+=1\n\n intensidade_coceira = 0\n if(coceira == 1):\n print(\"\\nINTENSIDADE DA COCEIRA\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Intensa\")\n intensidade_coceira = int(input(\"Escolha uma opcao: \"))\n \n if(intensidade_coceira == 1):\n dengue+=1\n chikungunya+=1\n elif(intensidade_coceira == 2 | intensidade_coceira == 3):\n zika+=1\n\n #HIPERTROFIA GANGLIONAR\n print(\"\\nHA HIPERTROFIA GANGLIONAR?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n hiper_ganglionar = int(input(\"Escolha uma opcao: \"))\n\n if(hiper_ganglionar == 1):\n zika+=1\n chikungunya+=1\n\n intensidade_hiper_ganglionar = 0\n if(hiper_ganglionar == 1):\n print(\"\\nINTENSIDADE DA HIPERTROFIA GANGLIONAR\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Intensa\")\n intensidade_hiper_ganglionar = int(input(\"Escolha uma opcao: \"))\n\n if(intensidade_hiper_ganglionar == 1):\n dengue+=1\n elif(intensidade_hiper_ganglionar == 2):\n chikungunya+=1 \n elif(intensidade_hiper_ganglionar == 3):\n zika+=1\n\n #DISCRASIA HEMORRAGICA\n print(\"\\nHA DISCRASIA HEMORRAGICA?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n discrasia = int(input(\"Escolha uma opcao: \"))\n\n if(discrasia == 1):\n dengue+=1\n elif(discrasia == 2):\n zika+=1\n\n intensidade_discrasia = 0\n if(discrasia == 1):\n print(\"\\nINTENSIDADE DA HIPERTROFIA GANGLIONAR\")\n print(\"[1] - Leve\")\n print(\"[2] - Moderada\")\n print(\"[3] - Intensa\")\n intensidade_discrasia = int(input(\"Escolha uma opcao: \"))\n\n if(intensidade_discrasia == 1):\n chikungunya+=1\n elif(intensidade_discrasia == 2):\n dengue+=1\n\n #ACOMETIMENTO NEUROLOGICO\n print(\"\\nHA ACOMETIMENTO NEUROLOGICO?\")\n print(\"[1] - Sim\")\n print(\"[2] - Nao\")\n neurologico = int(input(\"Escolha uma opcao: \"))\n\n if(neurologico == 1):\n zika+=1\n \n total_perguntas = 19\n\n print(\"Ha uma probabilidade de \" + str(dengue/total_perguntas) + \" de que voce esteja com dengue\")\n print(\"Ha uma probabilidade de \" + str(chikungunya/total_perguntas) + \" de que voce esteja com chikungunya\")\n print(\"Ha uma probabilidade de \" + str(zika/total_perguntas) + \" de que voce esteja com zika\")\n\nrun()","sub_path":"Projeto2/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":6733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"246972546","text":"'''\ncoding language: Python 3.7.0\n\nwritten by: Jonah Merrell\ndate written: November 14 2019\nwritten for: Homework6 Task6\ncourse: Math 4610\n\npurpose: Implement a method that will test the jacobian iteration code I wrote earlier on various matrices.\n'''\n\nimport random\nimport sys, os\nimport time\nsys.path.append(os.path.abspath('../../mylibrary'))\nfrom _mymodules import gen_rand_matrix,gen_sym_matrix,gen_diagdom_matrix,gen_diagdom_sym_matrix ,matrix_mult, convert_vec_mat, matrix_solve_gauss_seidel\n\ndef matrix_solve_gauss_seidel_test():\n matrix1 = gen_rand_matrix(100)\n matrix2 = gen_sym_matrix(100)\n matrix3 = gen_diagdom_matrix(100)\n matrix4 = gen_diagdom_sym_matrix(100)\n matrices = [matrix1,matrix2,matrix3,matrix4]\n vector = [1] * len(matrix1)\n for i in range(len(matrices)):\n b = matrix_mult(matrices[i],convert_vec_mat(vector))\n starttime = time.time()\n solution = matrix_solve_gauss_seidel(matrices[i], convert_vec_mat(b), 0.00001, 1000, getIterCount=True)\n print(\"Time: \" + str(time.time() - starttime))\n print(\"# of iterations: \" + str(solution[1]))\n print(solution[0])\n\nmatrix_solve_gauss_seidel_test()\n","sub_path":"homework6/Task9/matrix_solve_gauss_seidel_test.py","file_name":"matrix_solve_gauss_seidel_test.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"601937819","text":"import sqlite3\n\nfrom config import minus_category\nfrom scripts import *\n\n\nclass Banker:\n\n def __init__(self, database):\n self.db_name = database\n self.connection = sqlite3.connect(database)\n self.cursor = self.connection.cursor()\n\n self.user_counter = self.cursor.execute(\"SELECT COUNT(*) FROM 'users'\").fetchall()[0][0]\n self.transfer_counter = self.cursor.execute(\"SELECT COUNT(*) FROM 'transfers'\").fetchall()[0][0]\n\n # !!! METHODS FOR USER INFORMATION !!!\n\n def addUser(self, user_id):\n with self.connection:\n return self.cursor.execute(\n \"INSERT INTO 'users' ('id', 'user_id', 'condition', 'account') \"\n \"VALUES (?, ?, ?, ?)\", (self.user_counter, user_id, True, 0)).fetchall()\n\n def getUserById(self, user_id):\n with self.connection:\n user = self.cursor.execute(\"SELECT * FROM 'users' WHERE user_id = ?\",\n (user_id, )).fetchall()\n return user[0] if user else None\n\n def userIdList(self, condition=2):\n with self.connection:\n # 2 is all users\n # 1 is users who use it now(True condition)\n # 0 is users who don't use it but was it the database\n if condition == 0:\n return [x[0] for x in self.cursor.execute(\"SELECT user_id, condition FROM 'users'\").fetchall() if not x[1]]\n elif condition == 1:\n return [x[0] for x in self.cursor.execute(\"SELECT user_id, condition FROM 'users'\").fetchall() if x[1]]\n return [int(x[0]) for x in self.cursor.execute(\"SELECT user_id FROM 'users'\").fetchall()]\n\n def isActive(self, user_id):\n with self.connection:\n return self.cursor.execute(\"SELECT * FROM 'users' WHERE user_id = ?\", (user_id,)).fetchall()[0][0]\n\n def setStatus(self, user_id, condition: bool):\n with self.connection:\n self.connection.execute(\"UPDATE 'users' SET condition = ? WHERE user_id = ?\", (int(condition), user_id))\n\n # !!! METHODS FOR TRANSFERS INFORMATION !!!\n\n def addTransfer(self, user_id: int, value: float, date, category='неВыбрано✖'):\n with self.connection:\n self.connection.execute(\n \"INSERT INTO 'transfers' ('id', 'user_id', 'value', 'transfer_date', 'category') VALUES(?, ?, ?, ?, ?)\", (self.transfer_counter, user_id, value, date, category[:-1]))\n self.transfer_counter += 1\n\n def updateTransfer(self, its_id: int, user_id: int, value: float, category: str, date):\n with self.connection:\n value = abs(value) if category[-1] == '➕' else -abs(value)\n self.connection.execute(\n \"UPDATE 'transfers' SET user_id = ?, value = ?, transfer_date = ?, category = ? WHERE id = ?\",\n (user_id, value, date, category[:-1], its_id))\n account = self.connection.execute(\n \"SELECT account FROM 'users' WHERE user_id = ?\",\n (user_id,)).fetchall()[0][0]\n self.connection.execute(\"UPDATE 'users' SET account = ? WHERE user_id = ?\", (account + value, user_id, ))\n\n def getLastTransfer(self, user_id: int):\n with self.connection:\n a = self.connection.execute(\n \"SELECT * FROM 'transfers' WHERE user_id = ? ORDER BY transfer_date DESC\",\n (user_id,)).fetchall()\n if len(a) != 0:\n return a[0]\n else:\n print(f'ERROR: У пользователя {user_id} нет записей!!!')\n return None\n\n def getTransferById(self, transfer_id):\n with self.connection:\n return self.connection.execute(\"SELECT * FROM 'transfers' WHERE id = ?\", (transfer_id, )).fetchall()[0]\n\n def monthlyReport(self, user_id):\n with self.connection:\n # return all transfers per month\n start = datetime.now().replace(day=1, microsecond=0)\n stop = datetime.now().replace(microsecond=0)\n return self.connection.execute(\n \"SELECT * FROM 'transfers' WHERE user_id = ? AND transfer_date >= ? AND transfer_date <= ?\",\n (user_id, str(start), str(stop))).fetchall()\n\n def topCategory(self, user_id):\n with self.connection:\n # return the most popular category of user per month\n transfers = self.monthlyReport(user_id)\n a = [[0 for i in range(len(minus_category))], minus_category]\n for i in range(len(transfers)):\n if transfers[i][4] in minus_category:\n a[0][minus_category.index(transfers[i][4])] += transfers[i][2]\n else:\n a[0][minus_category.index('Другое')] += transfers[i][2]\n return QSDouble(a)\n\n def deleteEmptyTransfers(self, user_id):\n with self.connection:\n self.connection.execute(\"DELETE FROM 'transfer' WHERE user_id = ? and category = ?\",\n (user_id, 'неВыбрано'))\n\n\n'''\ndb = Banker('db.db')\nprint(db.monthlyReport(336619540))\n'''","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":5119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"236189273","text":"from django.template.loader import render_to_string\nfrom django.template.backends.django import Template\nfrom django.urls import resolve\nfrom urllib.parse import urlparse\n\nfrom django.test import RequestFactory\n\nfrom .channel import Channel\n\nPROTECTED_VARIABLES = [\n 'consumer',\n 'element',\n 'is_morph',\n 'selectors',\n 'session',\n 'url',\n]\n\n\nclass Reflex:\n def __init__(\n self, consumer, url, element, selectors, params, identifier='',\n permanent_attribute_name=None, reflex_id=None\n ):\n self.consumer = consumer\n self.url = url\n self.element = element\n self.selectors = selectors\n self.session = consumer.scope[\"session\"]\n self.params = params\n self.identifier = identifier\n self.is_morph = False\n self.reflex_id = reflex_id\n self.permanent_attribute_name = permanent_attribute_name\n self.context = {}\n\n def __repr__(self):\n return f\"\"\n\n def get_context_data(self, *args, **kwargs):\n if self.context:\n self.context.update(**kwargs)\n return self.context\n\n parsed_url = urlparse(self.url)\n resolved = resolve(parsed_url.path)\n view = resolved.func.view_class()\n view.request = self.request\n view.kwargs = resolved.kwargs\n\n # correct for detail and list views for django generic views\n if hasattr(view, \"get_object\"):\n view.object = view.get_object()\n\n if hasattr(view, \"paginate_queryset\"):\n view.object_list = view.get_queryset()\n\n context = view.get_context_data(**{\"stimulus_reflex\": True})\n\n self.context = context\n self.context.update(**kwargs)\n return self.context\n\n def get_channel_id(self):\n \"\"\"\n Override this to make the reflex send to a different channel\n other than the session_key of the user\n \"\"\"\n return self.session.session_key\n\n @property\n def request(self):\n factory = RequestFactory()\n request = factory.get(self.url)\n request.session = self.consumer.scope[\"session\"]\n request.user = self.consumer.scope[\"user\"]\n request.POST = self.params\n return request\n\n def reload(self):\n \"\"\"A default reflex to force a refresh\"\"\"\n pass\n\n def get_channel_id(self):\n '''\n Override this to make the reflex send to a different channel\n other than the session_key of the user\n '''\n return self.session.session_key\n\n def morph(self, selector='', html='', template='', context={}):\n \"\"\"\n If a morph is executed without any arguments, nothing is executed\n and the reflex won't send over any data to the frontend.\n \"\"\"\n self.is_morph = True\n no_arguments = [not selector, not html, (not template and not context)]\n if all(no_arguments) and not selector:\n # an empty morph, nothing is sent ever.\n return\n\n if html:\n html = html\n elif isinstance(template, Template):\n html = template.render(context)\n else:\n html = render_to_string(template, context)\n\n broadcaster = Channel(self.get_channel_id(), identifier=self.identifier)\n broadcaster.morph({\n 'selector': selector,\n 'html': html,\n 'children_only': True,\n 'permanent_attribute_name': self.permanent_attribute_name,\n 'stimulus_reflex': {\n 'morph': 'selector',\n 'reflexId': self.reflex_id,\n 'url': self.url\n }\n })\n broadcaster.broadcast()\n","sub_path":"sockpuppet/reflex.py","file_name":"reflex.py","file_ext":"py","file_size_in_byte":3716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"159434184","text":"s = input()\n\nLETTERS_A = \"BCDEFGHIJKLMNOPQRSTUVWXYZ\"\nLETTERS_C = \"ABDEFGHIJKLMNOPQRSTUVWXYZ\"\nLETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\ncount = 0\nis_ok = True\nc1, c2 = False, False\nfor i in range(len(s)):\n if i == 0:\n c1 = (s[i] == \"A\")\n if s[i] in LETTERS_A:\n is_ok = False\n elif (2 <= i) and (i <= len(s)-2):\n if s[i] == \"C\":\n count += 1\n if s[i] in LETTERS_C:\n is_ok = False\n elif s[i] in LETTERS:\n is_ok = False\n \nc2 = (count == 1)\nif c1 and c2 and is_ok:\n print(\"AC\")\nelse:\n print(\"WA\")\n","sub_path":"atcoder/ABC104B.py","file_name":"ABC104B.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"80855167","text":"n=str(input())\nintN=int(n)\nkytu=len(n)\ntam=1\nkq=''\nwhile kytu!=0:\n\ttong=int(n[kytu-1])+tam\n\tif tong ==2:\n\t\tdu=0\n\t\ttam=1\n\t\tkq=str(du)+kq\n\telse:\n\t\ttam=0\n\t\tkq=\"1\"+kq\n\tkytu=kytu-1\nif tam==1:\n\tkq=str(tam)+kq\nprint(kq)\n","sub_path":"TDC/thi1.py","file_name":"thi1.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"122373687","text":"import tensorflow as tf\nimport numpy as np\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets(\"./mnist/data/\", one_hot=True)\n#원 핫 인코딩 아시죠?\n\nglobal_step = tf.Variable(0, trainable=False, name='global_step') #학습횟수 count용 변수\n\nX = tf.placeholder(tf.float32, [None, 784])#28*28 아시죠?\n#위의 None에 한번에 학습시킬 사이즈를 지정하면 된다.\n#지정 안하면 TensorFlow가 알아서 계산해 준다.\nY = tf.placeholder(tf.float32, [None, 10])\n\n#신경망 설계를 해보자.\n#784 -> 256 -> 256 -> 10 으로 하자.\n\nkeep_prob = tf.placeholder(tf.float32)#학습시에만 드롭아웃이 일어나도록 해준다.\n\nwith tf.name_scope('layer1'):\n W1 = tf.Variable(tf.random_normal([784,256], stddev=0.01))#표준편차 0.01 정규분포\n L1 = tf.nn.relu(tf.matmul(X,W1))\n #L1 = tf.nn.dropout(L1, keep_prob)\n tf.layers.batch_normalization(L1, training=(keep_prob!=1))\n\nwith tf.name_scope('layer2'):\n W2 = tf.Variable(tf.random_normal([256,256], stddev=0.01))\n L2 = tf.nn.relu(tf.matmul(L1,W2))\n #L2 = tf.nn.dropout(L2, keep_prob)\n tf.layers.batch_normalization(L2, training=(keep_prob!=1))\n\nwith tf.name_scope('layer3'):\n W3 = tf.Variable(tf.random_normal([256,10], stddev=0.01))\n model = tf.matmul(L2,W3) #출력층에는 활성화 함수를 사용안함\n\nwith tf.name_scope('optimizer'):\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=model, labels=Y))\n optimizer = tf.train.AdamOptimizer(0.001).minimize(cost, global_step=global_step)\n\n# 손실값 추적을 위한 cost 추적 코드\ntf.summary.scalar('cost', cost)\n\nsess = tf.Session()\nsaver = tf.train.Saver(tf.global_variables())\n\nckpt = tf.train.get_checkpoint_state('./model')\nif ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n saver.restore(sess, ckpt.model_checkpoint_path)\nelse:\n sess.run(tf.global_variables_initializer())\n\n#앞서 지정한 텐서들을 수집하고 저장하는 부분\nmerged = tf.summary.merge_all()\nwriter = tf.summary.FileWriter('./logs',sess.graph)\n\nbatch_size = 5500#한번에 학습시킬 배치 크기\ntotal_batch = int(mnist.train.num_examples/batch_size)#배치로 나눈 전체 데이터 크기 (55000/5500)\n\nfor epoch in range(15):\n total_cost=0\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n _, cost_val = sess.run([optimizer, cost], feed_dict={X:batch_xs, Y:batch_ys, keep_prob:0.8})\n total_cost+=cost_val\n summary = sess.run(merged, feed_dict={X:batch_xs, Y:batch_ys, keep_prob:0.8})\n writer.add_summary(summary, global_step=sess.run(global_step))\n print('Epoch:', '%04d' %(epoch + 1), 'Avg. cost =', '{:.3f}'.format(total_cost/total_batch))\n\nprint('Optimize Complete!')\n\nsaver.save(sess, './model/dnn.ckpt', global_step=global_step)\n\nis_correct = tf.equal(tf.argmax(model, 1), tf.argmax(Y,1))\naccuracy = tf.reduce_mean(tf.cast(is_correct,tf.float32))\n\nprint('정확도 :',sess.run(accuracy, feed_dict={X:mnist.test.images, Y:mnist.test.labels, keep_prob:1}))\n\nsess.close()","sub_path":"Part 4/mnist.py","file_name":"mnist.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"487614941","text":"import os\n\nurl_file = open(\"urls.txt\").read()\ngrupd_urls = url_file.split(\"\\n\\n\")\n\nurls = [a_grp for a_grp in grupd_urls]\n\nwindows=[grp.split('\\n') for grp in grupd_urls]\n\ni = 0\nfor tabs in windows:\n\ti = i + 1\n\tif i > 1:\n\t\tos.system(\"/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome\")\n\n\tfor url in tabs:\n\t\tif url != '':\n\t\t\tos.system(\"open -a Google\\ Chrome \"+url)","sub_path":"readly.py","file_name":"readly.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"433931469","text":"import pygal\n\nfrom using_pygal.die import Die\n\n# create 2 D6 dice\ndie_1 = Die()\ndie_2 = Die(10)\n\n# do rolls, save statistics\nresults = []\nfor roll_num in range(5000):\n result = die_1.roll() + die_2.roll()\n results.append(result)\n\n# analyze the result\nfrequencies = []\nmax_result = die_1.num_sides + die_2.num_sides\nfor value in range(2, max_result+1):\n i = results.count(value)\n frequencies.append(i)\n\n# visualize the results\nhist = pygal.Bar()\n\nhist.title = \"Results of rolling D6 and D10 dice 50000 times\"\nhist.x_labels = list(range(2, max_result+1))\nhist.x_title = 'result'\nhist.y_title = 'frequency of result'\n\nhist.add('D6 + D10', frequencies)\nhist.render_to_file('dice_visual.svg')\n","sub_path":"big_data/using_pygal/die_visual.py","file_name":"die_visual.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"45666483","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport web\nimport time, json\nfrom config import setting\nimport app_helper\n\ndb = setting.db_web\n\n# 个人信息\nurl = ('/app/v1/personal_info')\n\nclass handler: \n @app_helper.check_sign(['app_id','dev_id','ver_code','tick','session'])\n def POST(self, version='v1'):\n web.header('Content-Type', 'application/json')\n param = web.input(app_id='', dev_id='', ver_code='', session='', tick='')\n\n if '' in (param.app_id, param.dev_id, param.ver_code, param.session, param.tick):\n return json.dumps({'ret' : -2, 'msg' : '参数错误'})\n\n # 检查session登录\n uname = app_helper.app_logged(param.session) \n if uname is None:\n return json.dumps({'ret' : -4, 'msg' : '无效的session'})\n\n #--------------------------------------------------\n\n r4 = app_helper.get_user_detail(uname['userid'])\n\n ret_data = {\n \"name\" : r4['nickname'],\n \"image\" : r4['img_url'], # 用户头像 \n \"tel\" : r4['mobile'], # 用户注册手机号 \n \"user_type\" : uname['type'], # 用户类型\n # 店员信息\n \"shop_name\" : r4['shop_name'],\n \"real_name\" : r4['real_name'],\n \"shop_nickname\" : r4['shop_nickname'],\n \"contact_info\" : r4['contact_info'],\n # 店主信息\n \"licence_pic\" : app_helper.image_url(r4['licence_pic']) if r4['licence_pic']!='' else r4['licence_pic'],\n \"shop_pic\" : [app_helper.image_url(x) for x in r4['shop_pic']],\n }\n\n # 返回\n return json.dumps({\n 'ret' : 0,\n 'data' : ret_data,\n })\n","sub_path":"src/app_v1/personal_info.py","file_name":"personal_info.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"619061781","text":"from datetime import datetime\nimport json\nimport os\nimport http.client\nfrom passlib.context import CryptContext\nimport shapely.geometry\nimport geopandas\n\nfrom myapp import models\nfrom fcm_django.models import FCMDevice\n\nfrom django.conf import settings\nfrom django.core import serializers\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.db import (connection, transaction)\nfrom django.db.utils import DataError, Error, IntegrityError\nfrom django.forms.models import model_to_dict\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.http.response import JsonResponse\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom rest_framework_simplejwt.backends import TokenBackend\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import (\n AllowAny,\n IsAuthenticated\n)\n\nfrom myapp.view.utilidades import dictfetchall, usuarioAutenticado\n\nPROYECTISTA = '53ad3141-56bb-4ee2-adcf-5664ba03ad65'\n# VOLUNTARIO =\nEQUIPO_CIUDADANOS = 'b4879f48-8ab1-4d79-8f5b-7585b75cfb07'\n\n# ======================= usuarios =================================\n\n##\n# @brief plantilla de listado de usuarios\n# @param request Instancia HttpRequest\n# @return plantilla HTML\n#\n\n\ndef listadoUsuariosView(request):\n\n return render(request, \"usuarios/listado.html\")\n\n\n##\n# @brief Recurso de listado de usuarios\n# @param request Instancia HttpRequest\n# @return cadena JSON\n#\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef listadoUsuarios(request):\n\n #users = models.Usuario.objects.all().values()\n # json_res = serializers.serialize('python', users)\n users_to_show = request.GET.get('isactive', 'active')\n with connection.cursor() as cursor:\n\n if(users_to_show == \"inactive\"):\n query = \"SELECT user_id, opx.user.useremail, pers_id, pers_name, \\\n pers_lastname, opx.person.isactive, opx.person.role_id, pers_birthdate, \\\n neighborhood_id, gender_id, education_level_id, pers_telephone, opx.role.role_name, \\\n pers_latitude, pers_longitude, \\\n hour_location, pers_creation_date, isemployee \\\n FROM opx.person \\\n INNER JOIN opx.role ON opx.role.role_id = opx.person.role_id \\\n INNER JOIN opx.user ON opx.user.userid = opx.person.user_id WHERE opx.person.isactive = 0\"\n\n cursor.execute(query)\n users = dictfetchall(cursor)\n\n return JsonResponse(users, safe=False)\n elif(users_to_show == \"all\"):\n query = \"SELECT user_id, opx.user.useremail, pers_id, pers_name, \\\n pers_lastname, opx.person.isactive, opx.person.role_id, pers_birthdate, \\\n neighborhood_id, gender_id, education_level_id, pers_telephone, opx.role.role_name, \\\n pers_latitude, pers_longitude, \\\n hour_location, pers_creation_date, isemployee \\\n FROM opx.person \\\n INNER JOIN opx.role ON opx.role.role_id = opx.person.role_id \\\n INNER JOIN opx.user ON opx.user.userid = opx.person.user_id\"\n\n cursor.execute(query)\n users = dictfetchall(cursor)\n return JsonResponse(users, safe=False)\n elif(users_to_show == \"none\"):\n return JsonResponse([], safe=False)\n else:\n query = \"SELECT user_id, opx.user.useremail, pers_id, pers_name, \\\n pers_lastname, opx.person.isactive, opx.person.role_id, pers_birthdate, \\\n neighborhood_id, gender_id, education_level_id, pers_telephone, opx.role.role_name, \\\n pers_latitude, pers_longitude, \\\n hour_location, pers_creation_date, isemployee \\\n FROM opx.person \\\n INNER JOIN opx.role ON opx.role.role_id = opx.person.role_id \\\n INNER JOIN opx.user ON opx.user.userid = opx.person.user_id WHERE opx.person.isactive = 1\"\n\n cursor.execute(query)\n users = dictfetchall(cursor)\n\n return JsonResponse(users, safe=False)\n\n\n\n\n##\n# @brief Recurso que provee el detalle de un usuario registrado\n# @param userid identificación del usuario\n# @return Cadena JSON\n#\n\n\n@api_view(['GET'])\n@permission_classes((IsAuthenticated,))\ndef detalleUsuario(request, userid):\n\n try:\n #usuario = models.Usuario.objects.get(pk=userid)\n usuario = {}\n\n with connection.cursor() as cursor:\n query = \"SELECT p.*, r.role_name, u.useremail from opx.person p \\\n INNER JOIN opx.role r ON r.role_id = p.role_id \" \\\n \"INNER JOIN opx.user u on u.userid = p.user_id WHERE p.user_id = '{}'\".format(userid)\n cursor.execute(query)\n queryResult = dictfetchall(cursor)\n\n if(len(queryResult) > 0):\n\n usuario = queryResult[0]\n\n # Puntaje esperado para llegar a rol proximo\n # Voluntario\n if str(usuario['role_id']) == '0be58d4e-6735-481a-8740-739a73c3be86':\n usuario['promocion'] = {\n 'rol': \"Validador\",\n 'puntaje': 22 # int(settings['umbral-validador'])\n }\n\n # Proyectista\n elif str(usuario['role_id']) == '53ad3141-56bb-4ee2-adcf-5664ba03ad65':\n usuario['promocion'] = {\n 'rol': \"Proyectista\",\n 'puntaje': 22 # int(settings['umbral-proyectista'])\n }\n\n # Remover la información que no se desea mostrar\n #del usuario['password']\n #del usuario['usertoken']\n\n data = {\n 'code': 200,\n 'usuario': usuario,\n 'status': 'success'\n }\n\n else:\n raise ObjectDoesNotExist(\"\")\n\n except ObjectDoesNotExist:\n\n data = {\n 'code': 404,\n 'status': 'error'\n }\n\n except ValidationError:\n\n data = {\n 'code': 400,\n 'status': 'error'\n }\n\n except DataError:\n\n data = {\n 'code': 400,\n 'status': 'error'\n }\n\n return JsonResponse(data, status=data['code'])\n\n##\n# @brief Recurso de almacenamiento de usuarios\n# @param request Instancia HttpRequest\n# @return cadena JSON\n#\n\n\n@csrf_exempt\n@api_view([\"POST\"])\n@permission_classes((AllowAny,))\ndef almacenarUsuario(request):\n\n useremail = request.POST.get('useremail')\n fcm_token = request.POST.get('fcm_token')\n type_device = request.POST.get('type_device')\n pers_name = request.POST.get('pers_name')\n pers_lastname = request.POST.get('pers_lastname')\n password = request.POST.get('password')\n role_id = request.POST.get('role_id')\n #userleveltype = 1\n #userestado = 1\n pers_birthdate = request.POST.get('pers_birthdate')\n gender_id = request.POST.get('gender_id')\n neighborhood_id = request.POST.get('neighborhood_id')\n education_level_id = request.POST.get('education_level_id')\n pers_telephone = request.POST.get('pers_telephone')\n #fechaCreacion = datetime.today()\n isemployee = request.POST.get('isemployee')\n\n try:\n with transaction.atomic():\n user = models.User(useremail=useremail, password=password)\n # Contexto Passlib\n pwd_context = CryptContext(\n schemes=[\"pbkdf2_sha256\"],\n default=\"pbkdf2_sha256\",\n pbkdf2_sha256__default_rounds=30000\n )\n user.password = pwd_context.encrypt(user.password)\n user.save()\n role = models.Role.objects.get(pk=role_id)\n gender = models.Gender.objects.get(pk=gender_id)\n neighborhood = models.Neighborhood.objects.get(pk=neighborhood_id)\n education_level = models.EducationLevel.objects.get(\n pk=education_level_id)\n\n person = models.Person(pers_name=pers_name, pers_lastname=pers_lastname,\n role=role, pers_birthdate=pers_birthdate, pers_telephone=pers_telephone,\n gender=gender, neighborhood=neighborhood, education_level=education_level,\n user=user)\n # Asignación de estado \"empleado\" a usuario en caso tal sea enviado\n if isemployee is not None:\n if isemployee == \"true\":\n person.isemployee = 1\n # else:\n # usuario.empleado = 0\n\n # Validación de campos\n person.full_clean()\n person.save()\n\n if fcm_token is not None and type_device is not None:\n\n device = FCMDevice(\n user=user,\n registration_id=fcm_token,\n type=type_device\n )\n device.save()\n #Agregar a equipo ciudadanos\n equipo = models.Team.objects.get(pk=EQUIPO_CIUDADANOS)\n equipoPersona = models.TeamPerson.objects.filter(person__pers_id__exact = person.pers_id).filter(team__team_id__exact = equipo.team_id)\n\n if len(equipoPersona) == 0:\n equipoMiembro = models.TeamPerson(\n person = person,\n team = equipo\n )\n equipoMiembro.full_clean()\n equipoMiembro.save()\n \n data = {\n 'code': 201,\n # mando user o person?\n 'usuario': serializers.serialize('python', [person])[0],\n 'status': 'success'\n }\n\n except ValidationError as e:\n\n data = {\n 'code': 400,\n 'errors': dict(e),\n 'status': 'error'\n }\n\n except IntegrityError as e:\n\n data = {\n 'code': 500,\n 'errors': str(e),\n 'status': 'error'\n }\n\n return JsonResponse(data, safe=False, status=data['code'])\n\n##\n# @brief Recurso de Actualización de usuarios\n# @param request Instancia HttpRequest\n# @param userid Identificación de usuario autenticado\n# @return cadena JSON\n#\n\n\n@csrf_exempt\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef actualizarUsuario(request, userid):\n\n try:\n with transaction.atomic():\n # Obteniendo datos respecto a la ubicacion del usuario\n latitud = request.POST.get('latitud')\n longitud = request.POST.get('longitud')\n\n # Asignando la nueva información al usuario\n user = models.User.objects.get(pk=userid)\n person = models.Person.objects.get(user__userid__exact=userid)\n role = models.Role.objects.get(pk=request.POST.get('role_id'))\n\n user.useremail = request.POST.get('useremail')\n person.role = role\n person.pers_name = request.POST.get('pers_name')\n person.pers_lastname = request.POST.get('pers_lastname')\n person.pers_birthdate = request.POST.get('pers_birthdate')\n gender = models.Gender.objects.get(pk=request.POST.get('gender_id'))\n person.gender = gender\n neighborhood = models.Neighborhood.objects.get(\n pk=request.POST.get('neighborhood_id'))\n person.neighborhood = neighborhood\n education_level = models.EducationLevel.objects.get(\n pk=request.POST.get('education_level_id'))\n person.education_level = education_level\n person.pers_telephone = request.POST.get('pers_telephone')\n\n # Asignando la información de ubicacion al usuario en caso de ser enviada\n if latitud is not None and longitud is not None:\n person.pers_latitude = latitud\n person.pers_longitude = longitud\n person.hour_location = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # Asignando la nueva contraseña en caso de ser enviada\n if request.POST.get('password') is not None and len(request.POST.get('password')) > 0:\n\n # Contexto Passlib\n pwd_context = CryptContext(\n schemes=[\"pbkdf2_sha256\"],\n default=\"pbkdf2_sha256\",\n pbkdf2_sha256__default_rounds=30000\n )\n user.password = pwd_context.encrypt(\n request.POST.get('password'))\n\n # Asignando el estado \"empleado\" del usuario en tal caso sea enviado\n if request.POST.get('isemployee') is not None:\n if request.POST.get('isemployee') == \"true\":\n person.isemployee = 1\n else:\n person.isemployee = 0\n\n person.full_clean()\n\n user.save()\n person.save()\n\n data = {\n 'code': 200,\n 'usuario': serializers.serialize('python', [person])[0],\n 'status': 'success'\n }\n\n except ObjectDoesNotExist:\n\n data = {\n 'code': 404,\n 'status': 'error'\n }\n\n except ValidationError as e:\n\n data = {\n 'code': 400,\n 'errors': dict(e),\n 'status': 'error'\n }\n\n except IntegrityError as e:\n\n data = {\n 'code': 500,\n 'errors': str(e),\n 'status': 'error'\n }\n\n return JsonResponse(data, status=data['code'], safe=False)\n\n##\n# @brief Recurso de eliminación de usuarios\n# @param request Instancia HttpRequest\n# @param userid Identificación de usuario autenticado\n# @return cadena JSON\n#\n\n\n@csrf_exempt\n@api_view([\"DELETE\"])\n@permission_classes((IsAuthenticated,))\ndef eliminarUsuario(request, userid):\n #Borrado lógico del usuario (isactive = 0)\n try:\n with transaction.atomic():\n\n #user = models.User.objects.get(userid=userid)\n person = models.Person.objects.get(user__userid__exact = userid)\n person.isactive = 0\n person.save()\n\n return JsonResponse({'status': 'success'})\n\n except ObjectDoesNotExist:\n return JsonResponse({'status': 'error', 'message': 'El usuario no existe'}, safe=True, status=404)\n\n except ValidationError:\n return JsonResponse({'status': 'error', 'message': 'Información inválida'}, safe=True, status=400)\n\n\n@csrf_exempt\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef logout(request):\n try:\n user = usuarioAutenticado(request)\n device = FCMDevice.objects.filter(user_id__exact = user.userid).first()\n if device is not None:\n device = FCMDevice.objects.get(user_id__exact = user.userid)\n device.registration_id = ''\n device.save()\n data = {\n 'code': 200,\n 'status': 'success'\n }\n return JsonResponse(data, status=data['code'], safe=False)\n except Error as e:\n data = {\n 'code': 500,\n 'errors': str(e),\n 'status': 'error'\n }\n return JsonResponse(data, status=data['code'], safe=False)\n","sub_path":"myapp/view/userview.py","file_name":"userview.py","file_ext":"py","file_size_in_byte":15270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"330734714","text":"# Modules\r\nimport os\r\nimport csv\r\n\r\n# Set path for file\r\nelectionpath = os.path.join(\"Resources\", \"election_data.csv\")\r\n\r\n# Specify the file to write to\r\noutput_path = os.path.join(\"output\", \"results.txt\")\r\n\r\n# opening the cvs file to work with\r\nwith open(electionpath) as csvfile:\r\n csv_reader = csv.reader(csvfile, delimiter=\",\")\r\n \r\n # getting the header and skipping header row\r\n csv_header = next(csv_reader)\r\n\r\n # setting variables\r\n num_votes = 0\r\n candidates_dict = {}\r\n\r\n # iterating through the data in the cvs file\r\n for row in csv_reader:\r\n \r\n # counting number of votes\r\n num_votes += 1\r\n\r\n # conditional for to add candidates to dictionary\r\n if row[2] not in candidates_dict:\r\n # the key is their name and the value is the count for their votes\r\n candidates_dict[row[2]] = 1\r\n # if they are already in the dictionary\r\n else:\r\n # getting old vote count from dictionary\r\n old_count = candidates_dict[row[2]]\r\n # creating new vote count\r\n new_count = old_count + 1\r\n # reassigning the new vote count as the value to that key / candidate\r\n candidates_dict[row[2]] = new_count\r\n\r\n # finding popular vote winner\r\n winner = max(candidates_dict, key=candidates_dict.get)\r\n\r\n # printing results in terminal\r\n print(f\"\"\"Election Results\r\n-------------------------\r\nTotal Votes: {num_votes}\r\n-------------------------\"\"\")\r\n # printing results by looping through dicitonary in terminal\r\n for key in candidates_dict:\r\n print(f\"{key}: {round(((candidates_dict[key] / num_votes)*100),3)}% ({candidates_dict[key]})\")\r\n # final print of popular vote winner in terminal\r\n print(f\"\"\"-------------------------\r\nWinner: {winner}\r\n-------------------------\"\"\")\r\n\r\n# writing in file, open the file using \"write\" mode. Specify the variable to hold the contents\r\nwith open(output_path, 'w', newline='') as newfile:\r\n\r\n # writing to the file\r\n newfile.write(f\"\"\"Election Results\r\n-------------------------\r\nTotal Votes: {num_votes}\r\n-------------------------\r\n\"\"\")\r\n for key in candidates_dict:\r\n newfile.write(f\"\"\"{key}: {round(((candidates_dict[key] / num_votes)*100),3)}% ({candidates_dict[key]})\r\n\"\"\")\r\n \r\n newfile.write(f\"\"\"-------------------------\r\nWinner: {winner}\r\n-------------------------\"\"\")\r\n\r\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"134754938","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 19 16:55:54 2016\n\n@author: Administrator\n\"\"\"\n\nimport pandas as pd\nimport pandas.io.sql as pd_sql\nimport sqlite3 as sql\n\ndf_file_all = pd.read_csv('CS_table_No2_No4_new.csv',delimiter=\";\", skip_blank_lines = True, \n error_bad_lines=False,encoding='utf8')\n \ndf_file_less = pd.read_csv('df_dropSub_less20.csv',delimiter=\",\", skip_blank_lines = True, \n error_bad_lines=False,encoding='utf8')\n \ndf_file_all = df_file_all.drop(['STUDENTID','ACADYEAR','CAMPUSID','SEMESTER','CURRIC','CAMPUSNAME','SECTIONGROUP','GRADE'],axis=1)\n\nsubjects = []\ncountSub = 0\nfor sub in df_file_less['3COURSEID']:\n if sub not in subjects:\n subjects.append(sub)\n countSub = countSub+1\nsubjects.sort()\n\ndf_db = df_file_all[df_file_all[\"sub_id\"].isin(subjects)]\ndf_db = df_db.drop_duplicates(['sub_id'], take_last=True) \ndf_db = df_db.sort(['sub_id'])\n \ncon = sql.connect(\"db.sqlite3\")\n#df = pd.DataFrame({'TestData': [1, 2, 3, 4, 5, 6, 7, 8, 9]}, dtype='float')\npd_sql.to_sql(df_db, \"mywebpage_subject\", con, index=False)\ncon.close()","sub_path":"book/django/project/add_subject_order.py","file_name":"add_subject_order.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"522114236","text":"\"\"\"\n7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of\npizza toppings until they enter a 'quit' value. As they enter each topping,\nprint a message saying you'll add that topping to their pizza.\n\"\"\"\ntoppings = None\npizza_topping = []\nwhile True:\n toppings = input(\"Please enter the topping you wish to add: \")\n pizza_topping.append(toppings)\n if toppings == \"done\":\n break\n else:\n print(f\"{toppings.title()} has been added to your pizza.\")\n# for topping in pizza_topping:\n# print(\"Here is the list of topping you requested:\")\n# print(f\"\\n{topping}\")\n\n\"\"\"\n7-5. Movie Tickets: A movie theater charges different tickets prices depending\non a person's age. If a person is under the age of 3, the ticket is free; if \nthey are between 3 and 12, the ticket is $10, and if they are over age 12, the \nticket is $15. Write a loop in which you ask users their age, and then tell them\nthe cost of their movie ticket\n\"\"\"\nage = None\nwhile True:\n age = input(\"Please enter your age: \")\n age = int(age)\n if age < 3:\n print(\"Your movie ticket is Free!\")\n break\n elif 3 >= age <= 12:\n print(\"Your movie ticket costs $10.\")\n break\n elif age > 12:\n print(\"Your movie ticket will cost $15.\")\n break\n\n\"\"\"\n7-7. Write a loop that never ends, and run it.\n\"\"\"\npopulation = 180000000\nwhile population < 1000000000:\n population += 1\n print(population)\n","sub_path":"input_and_while_loops/while_test1.py","file_name":"while_test1.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"614719066","text":"from dnn_schedules.per_layer.hwcf_schedule import HWCFSchedule\nfrom attrdict import AttrDict\n\n\nclass HWCFScheduleFire2Layer(HWCFSchedule):\n\n def __init__(self, net, model_name, result_dir, verbose, hardware_yaml=None, hardware_dict=None):\n super().__init__(net, model_name, result_dir, verbose, hardware_yaml, hardware_dict)\n\n def __str__(self):\n return 'hwfc_hwc_hwcf_schedule_pdp'\n\n def run_model(self):\n items = list(self.net.layers.items())\n idx = 0\n\n while idx < len(items):\n current_layer = items[idx][1]\n\n if idx + 2 < len(items):\n next_layer = items[idx+1][1]\n next_next_layer = items[idx + 2][1]\n\n\n if current_layer.attr_type == 'PW' and next_layer.attr_type == 'PW' \\\n and next_next_layer.attr_type == '3d':\n # Run PW1, 3d together in fire layer. Since, 3d take the most time.\n self.onchip_mem.clear()\n self.layer_names.append(current_layer.name)\n self.conv_conv(current_layer, next_next_layer)\n\n # Run pointwise layer later.\n # We want to run it on CONV hardware. Since, more resources.\n per_layer_hw_params = self.load_hw_params_conv(False, False, config=0)\n self.conv2d_pw(current_layer, per_layer_hw_params)\n self.layer_names.append(current_layer.name)\n\n idx += 3\n continue\n\n#-------------------------------------------\n if current_layer.attr_type == 'DW':\n self.onchip_mem.clear()\n self.layer_names.append(current_layer.name)\n dw_layer_hw_params = self.load_hw_params_depthwise()\n self.conv2d_dw(current_layer, dw_layer_hw_params)\n if current_layer.attr_type == 'PW':\n self.onchip_mem.clear()\n self.layer_names.append(current_layer.name)\n # Stand alone runs on second CONV hardware.\n pw_layer_hw_params = self.load_hw_params_conv(False,True, config=0)\n self.conv2d_pw(current_layer, pw_layer_hw_params)\n\n if current_layer.attr_type == '3d':\n self.onchip_mem.clear()\n # self.stats['orig_idx'][layer_attr.layer_idx] = orig_idx - 1\n # Stand alone runs on second CONV hardware.\n per_layer_hw_params = self.load_hw_params_conv(False,True, config=0)\n self.conv2d_pw(current_layer, per_layer_hw_params)\n self.layer_names.append(current_layer.name)\n\n idx += 1\n return\n\n def fire_conv(self, first_layer, second_layer, third_layer):\n first_layer_hw_params = self.load_hw_params_pointwise(True, False)\n # --- Pointwise 1 stats\n self.debug_message('cin= {} cout= {}'.format(first_layer.Cin, first_layer.Cout))\n self.debug_message('{} {} {}'.format(first_layer.layer_idx, first_layer.name, first_layer.attr_type))\n first_num_macs_w_units = first_layer_hw_params.mac_wxx * first_layer_hw_params.mac_wxx_type * first_layer_hw_params.mac_wxx_type\n first_layer_mac_units = first_layer_hw_params.mac_cxx * first_num_macs_w_units * first_layer_hw_params.mac_fx\n first_layer_padd_units = first_layer_hw_params.mac_wxx * first_layer_hw_params.mac_wxx_type * first_layer_hw_params.mac_wxx_type * first_layer_hw_params.mac_fx\n self.insert_max_stats('mac_units_available', first_layer.layer_idx, first_layer_mac_units)\n self.insert_max_stats('padd_units_available', first_layer.layer_idx, first_layer_padd_units)\n\n\n # -- Pointwise 2 in second unit --\n second_layer_hw_params = self.load_hw_params_pointwise(False, False)\n self.debug_message('{} {} {}'.format(second_layer.layer_idx, second_layer.name, second_layer.attr_type))\n second_num_macs_w_units = second_layer_hw_params.mac_wxx * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_wxx_type\n second_layer_mac_units = second_layer_hw_params.mac_cxx * second_num_macs_w_units * second_layer_hw_params.mac_fx\n self.insert_max_stats('mac_units_available', second_layer.layer_idx, second_layer_mac_units)\n second_layer_padd_units = second_layer_hw_params.mac_wxx * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_wxx_type * second_layer_hw_params.mac_fx\n self.insert_max_stats('padd_units_available', second_layer.layer_idx, second_layer_padd_units)\n\n #-- 3d CONV in parallel with second unit --\n third_layer_hw_params = self.load_hw_params_conv(False,False, config=4)\n self.debug_message('{} {} {}'.format(third_layer.layer_idx, third_layer.name, third_layer.attr_type))\n third_num_macs_w_units = third_layer_hw_params.mac_wxx * third_layer_hw_params.mac_wxx_type * third_layer_hw_params.mac_wxx_type\n third_layer_mac_units = third_layer_hw_params.mac_cxx * third_num_macs_w_units * third_layer_hw_params.mac_fx\n self.insert_max_stats('mac_units_available', third_layer.layer_idx, third_layer_mac_units)\n third_layer_padd_units = third_layer_hw_params.mac_wxx * third_layer_hw_params.mac_wxx_type * third_layer_hw_params.mac_wxx_type * third_layer_hw_params.mac_fx\n self.insert_max_stats('padd_units_available', third_layer.layer_idx, third_layer_padd_units)\n\n # adding mac units\n total_mac_units = first_layer_mac_units + second_layer_mac_units + third_layer_mac_units\n self.insert_max_stats('total_mac_units', first_layer.layer_idx, total_mac_units)\n self.insert_max_stats('total_mac_units', second_layer.layer_idx, total_mac_units)\n self.insert_max_stats('total_mac_units', third_layer.layer_idx, total_mac_units)\n\n # print('total mac units: {} 1: {} 2: {} 3: {}'.format(total_mac_units, first_layer_mac_units,\n # second_layer_mac_units, third_layer_mac_units))\n self.insert_max_stats('total_padd_units', first_layer.layer_idx, first_layer_padd_units)\n # PW2, 3dCONV runs in parallel\n self.insert_max_stats('total_padd_units', second_layer.layer_idx, second_layer_padd_units)\n self.insert_max_stats('total_padd_units', third_layer.layer_idx, second_layer_padd_units)\n\n # -- schedule loop --\n start_hout_idx = 0\n start_hout_idx_2 = 0\n start_hout_idx_3 = 0\n end_hout_idx_2 = 0\n end_hout_idx_3 = 0\n\n batch_cycles_1 = {}\n batch_cycles_2 = {}\n batch_cycles_3 = {}\n time_idx_1 = 0\n time_idx_2 = 0\n time_idx_3 = 0\n for hin in range(0, first_layer.Hin, first_layer_hw_params.hxx):\n # Adjust hin indices which will be used from previous convolutions\n # Note: no such assumption is made for 'w' dimension\n assert (first_layer_hw_params.hxx - first_layer.Kx + 1 >= 0), \\\n 'Increase value of hxx, hxx ({}) - layer_attr.Kx ({}) + 1 <0'.format(\n first_layer_hw_params.hxx, first_layer.Kx)\n if hin != 0:\n hin = hin - first_layer.Kx + 1\n\n end_hin_idx = min(hin + first_layer_hw_params.hxx, first_layer.Hin) - 1\n num_hin = end_hin_idx - hin + 1\n # In case of last values -- need to add padding information,\n # Also num_hin - layer_attr.Kx has to be divisible - This depends on hx and wx values\n if num_hin < first_layer.Kx:\n num_h_convs = 1\n else:\n num_h_convs = int(num_hin - first_layer.Kx / first_layer.Sx) + 1\n\n end_hout_idx = start_hout_idx + num_h_convs - 1\n # num_hout = end_hout_idx - start_hout_idx + 1\n\n start_wout_idx = 0\n start_wout_idx_2 = 0\n start_wout_idx_3 = 0\n end_wout_idx = 0\n end_wout_idx_2 = 0\n end_wout_idx_3 = 0\n for win in range(0, first_layer.Win, first_layer_hw_params.wxx):\n assert(first_layer_hw_params.wxx - first_layer.Ky +1 >=0), \\\n 'Increase value of wxx, wxx ({}) - layer_attr.Ky ({}) + 1 <0'.format(\n first_layer_hw_params.wxx, first_layer.Ky)\n\n assert( first_layer_hw_params.mac_wxx - first_layer.Ky +1 >0), \\\n 'Increase value of mac_wx, mac_wx ({}) - layer_attr.Ky ({}) + 1 <0'.format(first_layer.mac_wxx, first_layer.Ky)\n\n if win != 0:\n win = win - first_layer.Ky + 1\n\n end_win_idx = min(win + first_layer_hw_params.wxx, first_layer.Win) - 1\n num_win = end_win_idx - win + 1\n\n if num_win < first_layer.Ky:\n num_w_convs = 1\n else:\n # note: # macs connections will differ for stride = 2\n num_w_convs = int((num_win - first_layer.Ky) / first_layer.Sy) + 1\n\n end_wout_idx = start_wout_idx + num_w_convs - 1\n\n for f in range(0,first_layer.Cout, first_layer_hw_params.fx):\n##-------------------------------------------------------------------------------\n # Note: P1 in PDP is HW|F|C i.e F -> will run Fx idx only\n # However, for P2 in PDP init_start_cout_idx=0, init_end_cout_idx= layer_attr.Cout\n # making it HW|C|F\n end_cout_idx= min(f + first_layer_hw_params.fx, first_layer.Cout) - 1\n num_cout = end_cout_idx -f + 1\n for cin in range(0, first_layer.Cin, first_layer_hw_params.cxx):\n end_cin_idx = min(cin + first_layer_hw_params.cxx, first_layer.Cin)-1\n self.debug_message('=== Layer 1: PW ===')\n pw_block_start_indices_1 = AttrDict({'orig_hin': hin, 'end_hin': end_hin_idx+1,\n 'orig_win': win, 'end_win': end_win_idx+1,\n 'orig_cin': cin, 'end_cin': end_cin_idx+1,\n 'hout': start_hout_idx, 'wout': start_wout_idx,\n 'cout': f, 'cout_end': end_cout_idx+1})\n\n cycles_1 = self.conv2d_pw_block(pw_block_start_indices_1, first_layer,\n first_layer_hw_params,\n num_cross_layers=3,\n layer_position_idx=0)\n if time_idx_1 in batch_cycles_1:\n batch_cycles_1[time_idx_1] += cycles_1\n else:\n batch_cycles_1[time_idx_1] = cycles_1\n\n # end cin\n # --------------------------------------------------------------------------------------------------\n # -- start of PCONV 2 in parallel with CONV\n # --------------------------------------------------------------------------------------------------\n time_idx_2 = time_idx_1 + 1\n self.debug_message(' --second layer (hwc) PW input_act[{}:{}][{}:{}][{}:{}]'.format(\n start_hout_idx, end_hout_idx,\n start_wout_idx, end_wout_idx,\n f, end_cout_idx - 1\n ))\n\n block_cin_2 = num_cout\n block_win_2 = num_w_convs\n block_hin_2 = num_h_convs\n block_cout_2 = second_layer.Cout\n\n if block_win_2 < second_layer.Ky:\n num_w_convs_2 = 1\n else:\n num_w_convs_2 = int((block_win_2 - second_layer.Ky) / second_layer.Sy) + 1\n\n if block_hin_2 < second_layer.Kx:\n num_h_convs_2 = 1\n else:\n num_h_convs_2 = int(num_hin - first_layer.Kx / first_layer.Sx) + 1\n\n # hin3, win3, cin3, hout3, wout3, cout3\n hin_2 = start_hout_idx\n win_2 = start_wout_idx\n cin_2 = f\n end_hin_idx_2 = hin_2 + block_hin_2 - 1\n end_win_idx_2 = win_2 + block_win_2 - 1\n end_cin_idx_2 = end_cout_idx\n\n end_hout_idx_2 = start_hout_idx_2 + num_h_convs_2 - 1\n end_wout_idx_2 = start_wout_idx_2 + num_w_convs_2 - 1\n # Stage 3 PW2 - executes all filters.\n start_cout_idx_2 = 0\n end_cout_idx_2 = start_cout_idx_2 + block_cout_2 - 1\n\n # Runs in HW|C|F for all filters of Layer 3\n self.debug_message('=== Layer 2.1: PW ===')\n pw2_start_indices = AttrDict({'hin': hin_2, 'win': win_2, 'cin': cin_2,\n 'hout': start_hout_idx, 'wout': start_wout_idx, 'cout': 0,\n 'end_hin': end_hin_idx_2 + 1,\n 'end_win': end_win_idx_2 + 1,\n 'end_cin': end_cin_idx_2 + 1,\n 'end_cout': second_layer.Cout\n })\n\n cycles_2 = self.conv2d_pw(second_layer, second_layer_hw_params, pw2_start_indices,\n num_cross_layers=2, layer_position_idx=1)\n if time_idx_2 in batch_cycles_2:\n batch_cycles_2[time_idx_2] += cycles_2\n else:\n batch_cycles_2[time_idx_2] = cycles_2\n\n # --------------------------------------------------------------------------------------------------\n # -- start of Conv 3 convolution using output of 1st PCONV\n # --------------------------------------------------------------------------------------------------\n time_idx_3 = time_idx_1\n self.debug_message(' --third layer (hwc) CONV input_act[{}:{}][{}:{}][{}:{}]'.format(\n start_hout_idx, end_hout_idx,\n start_wout_idx, end_wout_idx,\n f, end_cout_idx - 1\n ))\n\n block_cin_3 = num_cout\n block_win_3 = num_w_convs\n block_hin_3 = num_h_convs\n block_cout_3 = third_layer.Cout\n\n if block_win_3 < third_layer.Ky:\n num_w_convs_3 = 1\n else:\n num_w_convs_3 = int((block_win_3 - third_layer.Ky) / third_layer.Sy) + 1\n\n if block_hin_3 < third_layer.Kx:\n num_h_convs_3 = 1\n else:\n num_h_convs_3 = int(num_hin - first_layer.Kx / first_layer.Sx) + 1\n\n\n\n # hin3, win3, cin3, hout3, wout3, cout3\n hin_3 = start_hout_idx\n win_3 = start_wout_idx\n cin_3 = f\n end_hin_idx_3 = hin_3 + block_hin_3 - 1\n end_win_idx_3 = win_3 + block_win_3 - 1\n end_cin_idx_3 = end_cout_idx\n\n end_hout_idx_3 = start_hout_idx_3 + num_h_convs_3 - 1\n end_wout_idx_3 = start_wout_idx_3 + num_w_convs_3 - 1\n # Stage 3 PW2 - executes all filters.\n start_cout_idx_3 = 0\n end_cout_idx_3 = start_cout_idx_3 + block_cout_3 - 1\n\n # Runs in HW|C|F for all filters of Layer 3\n self.debug_message('=== Layer 3: PW ===')\n pw3_start_indices = AttrDict({'hin': hin_3, 'win': win_3, 'cin': cin_3,\n 'hout': start_hout_idx, 'wout': start_wout_idx, 'cout': 0,\n 'end_hin': end_hin_idx_3 + 1,\n 'end_win': end_win_idx_3 + 1,\n 'end_cin':end_cin_idx_3 + 1,\n 'end_cout': third_layer.Cout\n })\n\n cycles_3 = self.conv2d_pw(third_layer, third_layer_hw_params, pw3_start_indices,\n num_cross_layers=2, layer_position_idx=1)\n if time_idx_3 in batch_cycles_3:\n batch_cycles_3[time_idx_3] += cycles_3\n else:\n batch_cycles_3[time_idx_3] = cycles_3\n time_idx_1 += 1\n # end f\n##-------------------------------------------------------------------------------\n start_wout_idx = end_wout_idx + 1\n # update start_wout indices for second/third layer\n start_wout_idx_2 = end_wout_idx_2 + 1\n start_wout_idx_3 = end_wout_idx_3 + 1\n\n # end w\n start_hout_idx = end_hout_idx + 1\n start_hout_idx_2 = end_hout_idx_2 + 1\n start_hout_idx_3 = end_hout_idx_3 + 1\n\n # end h\n cross_layer_cycles, cycles_PW1, cycles_DW2, cycles_PW3 = self.get_global_cycles_three_layer(batch_cycles_1,\n batch_cycles_2,\n batch_cycles_3,\n time_idx_3)\n # Add cross_layer_cycles to 'global_cycles'\n # Note: Since, the global cycles will be added across layers to get total cycles\n # Only add cycles to last of the cross layers\n self.insert_max_stats('global_cycles', first_layer.layer_idx, 0)\n self.insert_max_stats('global_cycles', second_layer.layer_idx, 0)\n self.insert_max_stats('global_cycles',third_layer.layer_idx, cross_layer_cycles)\n\n self.insert_max_stats('timing_cycles', first_layer.layer_idx, cycles_PW1)\n self.insert_max_stats('timing_cycles', second_layer.layer_idx, cycles_DW2)\n self.insert_max_stats('timing_cycles', third_layer.layer_idx, cycles_PW3)\n\n\n\n return\n\n","sub_path":"TB-scheduler/dnn_schedules/cross_layer/hwcf_fire_two_layer.py","file_name":"hwcf_fire_two_layer.py","file_ext":"py","file_size_in_byte":18388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"249126565","text":"import re\nfrom random import randrange\nfrom fixture.orm import ORMFixture\n\ndb = ORMFixture(host=\"127.0.0.1\", name=\"addressbook\", user=\"root\", password=\"\")\n\n\ndef test_phones_on_home_page(app):\n contact_from_home_page = app.contact.get_contacts_list()[0]\n contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)\n assert contact_from_home_page.all_phones_from_homepage == merge_phones_like_on_home_page(contact_from_edit_page)\n\n\ndef test_phones_on_contact_view_page(app):\n contact_from_view_page = app.contact.get_contact_from_view_page(0)\n contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0)\n assert contact_from_view_page.home_phone == contact_from_edit_page.home_phone\n assert contact_from_view_page.work_phone == contact_from_edit_page.work_phone\n assert contact_from_view_page.mobile_phone == contact_from_edit_page.mobile_phone\n assert contact_from_view_page.secondary_phone == contact_from_edit_page.secondary_phone\n\n\ndef test_random_contact(app):\n index = randrange(len(app.contact.get_contacts_list()))\n contact_from_home_page = app.contact.get_contacts_list()[index]\n contact_from_edit_page = app.contact.get_contact_info_from_edit_page(index)\n assert contact_from_home_page.last_name == app.contact.get_contact_info_from_edit_page(index).last_name\n assert contact_from_home_page.first_name == app.contact.get_contact_info_from_edit_page(index).first_name\n assert contact_from_home_page.address == app.contact.get_contact_info_from_edit_page(index).address\n assert contact_from_home_page.all_emails_from_homepage == merge_emails_like_on_home_page(contact_from_edit_page)\n assert contact_from_home_page.all_phones_from_homepage == merge_phones_like_on_home_page(contact_from_edit_page)\n\n\ndef test_all_contacts_from_ui_and_db(app):\n ui_contacts = map(app.contact.clean_contact_from_homepage, app.contact.get_contacts_list())\n db_contacts = map(db.clean_contact, db.get_contact_list())\n for ui_contact in ui_contacts:\n for db_contact in db_contacts:\n if ui_contact.id == db_contact.id:\n assert ui_contact.first_name == db_contact.first_name\n assert ui_contact.last_name == db_contact.last_name\n assert ui_contact.address == db_contact.address\n assert ui_contact.all_emails_from_homepage == merge_emails_like_on_home_page(db_contact)\n assert ui_contact.all_phones_from_homepage == merge_phones_like_on_home_page(db_contact)\n\n\ndef clear(string):\n return re.sub(\"[() -]\", \"\", string)\n\n\ndef merge_phones_like_on_home_page(contact):\n return \"\\n\".join(filter(lambda x: x != \"\", map(lambda x: clear(x), filter(lambda x: x is not None,\n [contact.home_phone, contact.mobile_phone, contact.work_phone,\n contact.secondary_phone]))))\n\n\ndef merge_emails_like_on_home_page(contact):\n return \"\\n\".join(filter(lambda x: x != \"\", map(lambda x: clear(x), filter(lambda x: x is not None,\n [contact.email, contact.email2, contact.email3]))))\n","sub_path":"test/test_phones.py","file_name":"test_phones.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"248823269","text":"#!/usr/bin/env python\n# -*- code:UTF-8 -*-\n\nfrom tkinter import *\nimport tkinter.messagebox as messagebox\nimport threading\nimport os\nimport time\n\n\n# 定义一个类,继承自Thread\nclass MyThread(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n\n def run(self):\n do_click_begin()\n\n\ndef click_begin(event):\n global flag\n l1['text'] = '点击‘开始’按钮开始擦除,点击’退出‘按钮退出程序。'\n if flag == 1:\n global threadId\n threadId = MyThread()\n threadId.start()\n\n\ndef click_exit(event):\n global flag\n if flag == 1:\n root.quit()\n\n\n# 检测是否只有sda\ndef check_only_sda():\n os.chdir('/dev')\n cap = os.popen('ls -d /dev/sd?').readlines()\n return len(cap) == 1 and cap[0] == '/dev/sda\\n'\n\n\n# 检测待擦除盘是否插入了\ndef check_if_disk_plugged():\n global disknum\n os.chdir('/dev')\n while True:\n cap = os.popen('ls -d /dev/sd?').readlines()\n num_of_disk = len(cap)\n print(num_of_disk)\n if num_of_disk == 2: # 判断此时是否有两个设备\n rawstr1 = cap[1]\n disknum = (rawstr1[5:-1]) # 获取新插入盘的设备编号\n\n # 检测这个盘是否为母盘\n cmd = 'mdadm -E /dev/%s' % disknum # mdadm命令可以显示盘的元数据信息\n\n # 接下来将信息提取出来,做出判断是否为母盘,待完成。\n cap2 = os.popen(cmd).read()\n searchstr = 'raid1'\n if not cap2.find(searchstr, 0, len(cap2)) == -1:\n print(\"检测待擦除盘成功\")\n return True\n else:\n return False\n elif num_of_disk == 1:\n if not messagebox.askretrycancel('错误提示', '未检测到待擦除盘,请插入该盘,完成后点击\"Retry\",退出程序点击“Cancel'):\n return False\n else:\n if not messagebox.askretrycancel('错误提示', '检测到太多U盘,请拔出所有其他盘,只插入待擦除盘,完成后点击\"Retry\",退出程序点击”Cancel'):\n return False\n\n\ndef erase_disk():\n cmd = 'mdadm -D /dev/md*'\n capture = os.popen(cmd).readlines()\n s = capture[0]\n s1 = s[:-2:1]\n s2 = s1[7::1]\n cmd = 'mdadm -S /dev/md%s' % s2\n os.system(cmd)\n time.sleep(1)\n cmd = 'mdadm --zero-superblock /dev/%s' % disknum\n os.system(cmd)\n time.sleep(1)\n\n cmd = 'mdadm -E /dev/%s' % disknum\n capture = os.popen(cmd).readlines()\n cap = capture[1]\n searchstr = 'MBR Magic'\n if cap.find(searchstr, 0, len(cap)) == -1:\n cmd = 'mdadm -As'\n os.system(cmd)\n return False\n else:\n return True\n\n\ndef do_click_begin():\n global flag\n global disknum\n flag = 0\n # root.protocol('WM_DELETE_WINDOW', prohibitclosewindow)\n while True:\n if check_only_sda():\n messagebox.showinfo('插入待擦除盘', '请插入待擦除盘,观察到硬盘上的灯闪烁或等待5s后再点击\"OK\"。')\n l1['text'] = '正在识别待擦除盘。。。'\n time.sleep(5)\n if check_if_disk_plugged():\n l1['text'] = '正在擦除中。。。。'\n if erase_disk():\n l1['text'] = '擦除成功'\n break\n else:\n l1['text'] = '擦除失败'\n break\n else:\n messagebox.showinfo('错误', '未检测到待擦除盘,请重试。')\n break\n else:\n if not messagebox.askokcancel('检测到有U盘插到电脑上!', '请拔出所有U盘,然后点击\"OK\"以继续;\\n如果不测试,点击\"Cancel\"。'):\n break\n flag = 1\n root.protocol('WM_DELETE_WINDOW', closewindow)\n\n\n# 关闭窗口\ndef closewindow():\n ans = messagebox.askokcancel(title='Warning', message='确定要关闭吗?')\n if ans:\n root.destroy()\n else:\n return\n\n\n# 禁止关闭窗口\ndef prohibitclosewindow():\n messagebox.showinfo('抱歉', '正在运行中,暂时不允许退出程序,请等待。')\n return\n\n\nif __name__ == '__main__':\n global flag\n flag = 1\n root = Tk()\n root.title(\"SATA盘RAID信息擦除工具\")\n root.geometry('900x600+500+200')\n root.protocol('WM_DELETE_WINDOW', closewindow)\n l1 = Label(root, text=' 点击‘开始’按钮开始擦除,点击’退出‘按钮退出程序。', wraplength=580, width='38', height='3', bg='LemonChiffon', font=('黑体', 28, 'normal'))\n l1.grid(row=0, rowspan=2, column=0, columnspan=3, ipadx=10, ipady=50, padx=40, pady=80)\n b1 = Button(root, text='开始', bg='LawnGreen', width=10, height=3, font=('黑体', 20, 'normal'))\n b1.grid(row=2, column=0)\n b2 = Button(root, text='退出', bg='firebrick1', width=10, height=3, font=('黑体', 20, 'normal'))\n b2.grid(row=2, column=2)\n\n b1.bind(\"\", click_begin)\n b2.bind(\"\", click_exit)\n threadId = None\n root.mainloop()\n","sub_path":"EraseTools.py","file_name":"EraseTools.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"481454035","text":"#!/usr/local/bin/python\n# encoding: utf-8\nimport sys\n\nimport devToolsAction\n\nfrom utils import wf, get_args\n\n\ndef key_for_record(record):\n return u'{} {}'.format(record[devToolsAction.NAME], record[devToolsAction.SWIMLANE])\n\n\ndef main(workflow):\n query, mis, cache_seconds = get_args()\n cargo_list = devToolsAction.search_cargos(query)\n cargo_list_by_name = devToolsAction.search_cargos(query, type='stack_name')\n if cargo_list_by_name:\n cargo_list.extend(cargo_list_by_name)\n\n cargo_list = wf().filter(query, cargo_list, key_for_record)\n if cargo_list:\n for record in cargo_list:\n if record[devToolsAction.SWIMLANE]:\n swimlane = record[devToolsAction.SWIMLANE]\n else:\n swimlane = u'主干'\n\n wf().add_item(\n u'{}|{}'.format(record[devToolsAction.NAME], swimlane),\n u'[{}|服务数:{}]{}'.format(\n record[devToolsAction.MACHINE_ENV],\n record[devToolsAction.SERVICE_COUNT],\n swimlane),\n record[devToolsAction.STACK_UUID],\n valid=True)\n else:\n wf().add_item('no result', '', query, valid=True)\n wf().send_feedback()\n\n\nif __name__ == '__main__':\n sys.exit(wf().run(main))\n","sub_path":"alfredConfig/Alfred.alfredpreferences/workflows/user.workflow.B2F13413-0F41-400D-A18A-0EAADA34E2DD/cargoSearch.py","file_name":"cargoSearch.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"616026692","text":"# Author: Jan Buys\n# Code credit: Tensorflow seq2seq; BIST parser; pytorch master source\n\nfrom collections import Counter\nfrom collections import defaultdict\nfrom pathlib import Path\nimport re\n\nimport torch\n\n_EOS = 0\n\n_LIN = 0\n_RELU = 1\n_TANH = 2\n_SIG = 3\n\nclass ConllEntry:\n def __init__(self, id, form):\n self.id = id\n self.form = form\n self.norm = form \n\nclass Sentence:\n \"\"\"Container class for single example.\"\"\"\n def __init__(self, conll, tokens):\n self.conll = conll\n self.word_tensor = torch.LongTensor(tokens).view(-1, 1)\n\n def __len__(self):\n return len(self.conll)\n\n def text_line(self):\n return ' '.join([entry.norm for entry in self.conll[1:]])\n\n @classmethod\n def from_vocab_conll(cls, conll, word_vocab, max_length=-1):\n tokens = [word_vocab.get_id(entry.norm) for entry in conll] + [_EOS]\n if max_length > 0 and len(tokens) > max_length:\n return cls(conll[:max_length], tokens[:max_length])\n return cls(conll, tokens)\n\nclass Vocab:\n def __init__(self, word_list, counts=None):\n self.words = word_list\n self.dic = {word: i for i, word in enumerate(word_list)}\n self.counts = counts\n\n def __len__(self):\n return len(self.words)\n\n def get_word(self, i):\n return self.words[i]\n\n def get_id(self, word):\n return self.dic[word]\n\n def form_vocab(self):\n return set(filter(lambda w: not w.startswith('UNK'), \n self.words))\n\n def write_vocab(self, fn):\n with open(fn, 'w') as fh:\n for word in self.words:\n fh.write(word + '\\n')\n\n def write_count_vocab(self, fn, add_eos):\n assert self.counts is not None\n with open(fn, 'w') as fh:\n for i, word in enumerate(self.words):\n if i == 0 and add_eos:\n fh.write(word + '\\t0\\n')\n else: \n fh.write(word + '\\t' + str(self.counts[word]) + '\\n')\n\n @classmethod\n def from_counter(cls, counter, add_eos=False):\n if add_eos:\n word_list = ['_EOS']\n else:\n word_list = []\n word_list.extend([entry[0] for entry in counter.most_common()])\n return cls(word_list, counter)\n\n @classmethod\n def read_vocab(cls, fn):\n with open(fn, 'r') as fh:\n word_list = []\n for line in fh:\n entry = line.rstrip('\\n').split('\\t')\n word_list.append(entry[0])\n return cls(word_list)\n\n @classmethod\n def read_count_vocab(cls, fn):\n with open(fn, 'r') as fh:\n word_list = []\n dic = {}\n for line in fh:\n entry = line[:-1].rstrip('\\n').split('\\t')\n if len(entry) < 2:\n entry = line[:-1].strip().split()\n assert len(entry) >= 2, line\n word_list.append(entry[0])\n dic[entry[0]] = int(entry[1])\n return cls(word_list, Counter(dic))\n\n\ndef create_length_histogram(sentences, working_path):\n token_count = 0\n missing_token_count = 0\n\n sent_length = defaultdict(int)\n for sent in sentences:\n sent_length[len(sent)] += 1\n token_count += len(sent)\n missing_token_count += min(len(sent), 50)\n lengths = list(sent_length.keys())\n lengths.sort()\n print('Num Tokens: %d. Num <= 50: %d (%.2f percent).'\n % (token_count, missing_token_count,\n missing_token_count*100/token_count))\n\n cum_count = 0\n with open(working_path + 'train.histogram', 'w') as fh:\n for length in lengths:\n cum_count += sent_length[length]\n fh.write((str(length) + '\\t' + str(sent_length[length]) + '\\t' \n + str(cum_count) + '\\n'))\n print('Created histogram') \n\n\n# Stanford/Berkeley parser UNK processing case 5 (English specific).\n# Source class: edu.berkeley.nlp.PCFGLA.SimpleLexicon\ndef map_unk_class(word, is_sent_start, vocab, replicate_rnng=False):\n unk_class = 'UNK'\n num_caps = 0\n has_digit = False\n has_dash = False\n has_lower = False\n\n if replicate_rnng:\n # Replicating RNNG bug\n for ch in word:\n has_digit = ch.isdigit()\n has_dash = ch == '-'\n if ch.isalpha():\n has_lower = ch.islower()\n if not ch.islower():\n num_caps += 1\n else:\n for ch in word:\n has_digit = has_digit or ch.isdigit()\n has_dash = has_dash or ch == '-'\n if ch.isalpha():\n has_lower = has_lower or ch.islower() or ch.istitle() \n if not ch.islower():\n num_caps += 1\n\n lowered = word.lower()\n if word[0].isupper() or word[0].istitle():\n if is_sent_start and num_caps == 1:\n unk_class += '-INITC'\n if lowered in vocab:\n unk_class += '-KNOWNLC'\n else:\n unk_class += '-CAPS'\n elif not word[0].isalpha() and num_caps > 0:\n unk_class += '-CAPS'\n elif has_lower:\n unk_class += '-LC'\n\n if has_digit:\n unk_class += '-NUM'\n if has_dash:\n unk_class += '-DASH'\n\n if len(word) >= 3 and lowered[-1] == 's':\n ch2 = lowered[-2]\n if ch2 != 's' and ch2 != 'i' and ch2 != 'u':\n unk_class += '-s'\n elif len(word) >= 5 and not has_dash and not (has_digit and num_caps > 0):\n # common discriminating suffixes\n suffixes = ['ed', 'ing', 'ion', 'er', 'est', 'ly', 'ity', 'y', 'al']\n for suf in suffixes:\n if lowered.endswith(suf):\n unk_class += '-' + suf\n break\n\n return unk_class\n\n\ndef read_sentences_given_fixed_vocab(txt_path, txt_name, working_path):\n word_vocab = Vocab.read_count_vocab(working_path + 'vocab')\n\n print('reading')\n sentences = []\n with open(txt_path + txt_name + '.txt', 'r') as txtFP:\n for line in txtFP:\n root = ConllEntry(0, '*root*')\n tokens = [root]\n for word in line.split():\n tokens.append(ConllEntry(len(tokens), word))\n for j, node in enumerate(tokens):\n assert node.form in word_vocab\n tokens[j].word_id = word_vocab.get_id(node.form) \n sentences.append(Sentence.from_vocab_conll(tokens, word_vocab))\n\n print('%d sentences read' % len(sentences))\n return (sentences, word_vocab)\n\n\ndef read_sentences_fixed_vocab(txt_path, txt_name, working_path):\n wordsCount = Counter()\n\n conll_sentences = []\n with open(txt_path + txt_name + '.txt', 'r') as txtFP:\n for line in txtFP:\n root = ConllEntry(0, '*root*')\n tokens = [root]\n for word in line.split():\n tokens.append(ConllEntry(len(tokens), word))\n wordsCount.update([node.form for node in tokens])\n conll_sentences.append(tokens)\n print('%d sentences read' % len(conll_sentences))\n word_vocab = Vocab.from_counter(wordsCount, add_eos=True)\n word_vocab.write_count_vocab(working_path + 'vocab', add_eos=True)\n\n parse_sentences = []\n for sent in conll_sentences:\n for j, node in enumerate(sent): \n sent[j].word_id = word_vocab.get_id(node.norm) \n parse_sentences.append(Sentence.from_vocab_conll(sent, word_vocab))\n \n return (parse_sentences, word_vocab)\n\n\ndef read_sentences_create_vocab(txt_path, txt_name, working_path,\n use_unk_classes=True, replicate_rnng=False, max_length=-1): \n wordsCount = Counter()\n\n conll_sentences = []\n with open(txt_path + txt_name + '.txt', 'r') as txtFP:\n for line in txtFP:\n root = ConllEntry(0, '*root*')\n tokens = [root]\n for word in line.split():\n tokens.append(ConllEntry(len(tokens), word))\n wordsCount.update([node.form for node in tokens])\n conll_sentences.append(tokens)\n\n # For words, replace singletons with Berkeley UNK classes\n singletons = set(filter(lambda w: wordsCount[w] == 1, wordsCount.keys()))\n form_vocab = set(filter(lambda w: wordsCount[w] > 1, wordsCount.keys())) \n\n wordsNormCount = Counter()\n for i, sentence in enumerate(conll_sentences):\n for j, node in enumerate(sentence):\n if node.form in singletons:\n if use_unk_classes:\n conll_sentences[i][j].norm = map_unk_class(node.form, j==1, \n form_vocab, replicate_rnng)\n else:\n conll_sentences[i][j].norm = 'UNK'\n wordsNormCount.update([node.norm for node in conll_sentences[i]])\n \n word_vocab = Vocab.from_counter(wordsNormCount, add_eos=True)\n\n print(str(len(singletons)) + ' singletons')\n print('Word vocab size %d' % len(word_vocab))\n\n word_vocab.write_count_vocab(working_path + 'vocab', add_eos=True)\n\n parse_sentences = []\n for sent in conll_sentences:\n for j, node in enumerate(sent): \n sent[j].word_id = word_vocab.get_id(node.norm) \n parse_sentences.append(Sentence.from_vocab_conll(sent, word_vocab,\n max_length))\n\n write_text(working_path + txt_name + '.txt', parse_sentences)\n\n return (parse_sentences,\n word_vocab)\n\ndef read_sentences_given_vocab(txt_path, txt_name, working_path, \n use_unk_classes=True, replicate_rnng=False, max_length=-1): \n word_vocab = Vocab.read_count_vocab(working_path + 'vocab')\n form_vocab = word_vocab.form_vocab()\n\n print('reading')\n sentences = []\n conll_sentences = []\n\n with open(txt_path + txt_name + '.txt', 'r') as txtFP:\n for line in txtFP:\n root = ConllEntry(0, '*root*')\n sentence = [root]\n for word in line.split():\n sentence.append(ConllEntry(len(sentence), word))\n conll_sentences.append(sentence) \n\n for j, node in enumerate(sentence):\n if node.form not in form_vocab: \n if use_unk_classes:\n sentence[j].norm = map_unk_class(node.form, j==1, form_vocab,\n replicate_rnng)\n else:\n sentence[j].norm = 'UNK'\n if sentence[j].norm in word_vocab.dic:\n sentence[j].word_id = word_vocab.get_id(sentence[j].norm)\n else: # back off to least frequent word\n sentence[j].word_id = len(word_vocab) - 1\n sentence[j].norm = word_vocab.get_word(sentence[j].word_id)\n sentences.append(Sentence.from_vocab_conll(sentence, word_vocab,\n max_length))\n\n write_text(working_path + txt_name + '.txt', sentences)\n\n return (sentences,\n word_vocab)\n\n\ndef write_text(fn, sentences):\n with open(fn, 'w') as fh:\n for sentence in sentences:\n fh.write(sentence.text_line() + '\\n') \n\n\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":9916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"67303279","text":"import numpy as numpy\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#from sklearn.datasets import load_digits\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics.classification import accuracy_score\n\n'''digits=load_digits()\n\ndf_x=pandas.DataFrame(digits.)'''\n\ndf=pd.read_csv('mnist.csv')\n\ndf_x=df.iloc[:,1:]\ndf_y=df.iloc[:,0]\n\nx_train,x_test,y_train,y_test=train_test_split(df_x,df_y,test_size=0.2,random_state=4)\nclf=RandomForestClassifier(n_estimators=100)\nclf.fit(x_train,y_train)\n\nactual=y_test.values\n\nprint (actual)\ntotal=len(actual)\nprint (\"Total values\",total)\n\npredictions=clf.predict(x_test)\ntotal_right=len(predictions)\nprint (\"Total Predictions\",total_right)\ni=0\ncount=0\n\nfor i in range(len(predictions)):\n\tif predictions[i] == actual[i]:\n\t\tcount =count+1\nprint (\"Number of right predictions\",count)\naccuracy=count/total\n\nprint (\"Accuracy\",accuracy)\n\n\n\n#print (accuracy_score(y_test,predictions))\n\n\n\n\n\n#a=df.ix[0,1:].values\n#print (a)\n\n\n#print (data.head())\n#a=a.reshape(28,28).astype('uint8')\n\n#print (a.imshow())","sub_path":"MLProject/Digit-Classification.py","file_name":"Digit-Classification.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"18886046","text":"from indigo.nn.wrappers.layer import Layer\r\nfrom indigo.nn.position_encoding import position_encoding\r\nimport tensorflow as tf\r\n\r\n\r\nclass RegionFeature(Layer):\r\n\r\n def __init__(self,\r\n num_embeddings,\r\n hidden_size,\r\n **kwargs):\r\n \"\"\"Creates a Transformer embedding layer by applying a\r\n lookup operation to the queries\r\n\r\n Arguments:\r\n\r\n num_embeddings: int\r\n the number of elements in the vocabulary which\r\n input sequences contain elements of\r\n hidden_size: int\r\n the number of units in the hidden variables used\r\n in each multi head attention layer\"\"\"\r\n super(RegionFeature, self).__init__()\r\n\r\n # these parameters need to be stored so that\r\n # tf.layers.model.save_model works\r\n self.num_embeddings = num_embeddings\r\n self.hidden_size = hidden_size\r\n self.kwargs = kwargs\r\n\r\n # the core processing variables\r\n self.word_embedding = tf.keras.layers.Embedding(\r\n num_embeddings, hidden_size, **kwargs)\r\n self.detection_embedding = tf.keras.layers.Embedding(\r\n 91, hidden_size, **kwargs)\r\n self.dense = tf.keras.layers.Dense(\r\n hidden_size, **kwargs)\r\n\r\n def call(self, inputs, **kwargs):\r\n \"\"\"Runs a forward pass on the embeddings of a transformer\r\n inputs is an instance of TransformerInput\r\n\r\n Arguments:\r\n\r\n inputs: RegionFeatureInput\r\n a dataclass instance that contains queries, keys\r\n and values along with masks\r\n\r\n Returns:\r\n\r\n outputs: TransformerInput\r\n the result of applying a multi head attention mechanism\r\n same shape as inputs\"\"\"\r\n\r\n y = self.detection_embedding(inputs.values.detections, **kwargs)\r\n inputs.values = self.dense(tf.concat([\r\n inputs.values.features,\r\n inputs.values.boxes, y], 2), **kwargs)\r\n a = position_encoding(tf.shape(inputs.queries)[1], self.hidden_size)\r\n b = self.word_embedding(inputs.queries, **kwargs)\r\n if hasattr(inputs, 'absolute_positions') and \\\r\n inputs.absolute_positions is not None:\r\n b = tf.matmul(inputs.absolute_positions, b)\r\n inputs.queries = a + b\r\n return inputs\r\n\r\n def get_config(self):\r\n \"\"\"Creates a state dictionary that can be used to rebuild\r\n the layer in another python process\r\n\r\n Returns:\r\n\r\n config: dict\r\n a dictionary that contains all parameters to the\r\n layers base class and all class parameters\"\"\"\r\n\r\n # these are all that is needed to rebuild this class\r\n config = dict(num_embeddings=self.num_embeddings,\r\n num_detections=self.num_detections,\r\n hidden_size=self.hidden_size,\r\n ** self.kwargs)\r\n\r\n base_config = super(RegionFeature, self).get_config()\r\n return dict(list(base_config.items()) +\r\n list(config.items()))\r\n","sub_path":"indigo/nn/features/region_feature.py","file_name":"region_feature.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"409913746","text":"__author__ = 'Yin'\n# Standard imports\nimport logging\n\n# Our imports\nfrom emission.analysis.result.carbon import getModeCarbonFootprint, carbonFootprintForMode\nfrom emission.core.common import Inside_polygon,berkeley_area,getConfirmationModeQuery\nfrom emission.core.get_database import get_section_db,get_profile_db\nimport geojson as gj\nimport emission.analysis.plotting.geojson.geojson_feature_converter as gfc\nimport emission.core.wrapper.motionactivity as ecwm\nimport emission.storage.decorations.timeline as esdt\nimport emission.core.wrapper.trip as ecwt\nimport emission.core.wrapper.section as ecws\n\n# Note that all the points here are returned in (lng, lat) format, which is the\n# GeoJSON format.\n\ndef carbon_by_zip(start,end):\n Profiles=get_profile_db()\n carbon_list=[]\n for zip in Profiles.distinct('zip'):\n # print(zip)\n if zip!='N/A':\n tempdict={}\n tempdict['weight']=Profiles.find({'zip':zip}).count()\n # print(Profiles.find({'zip':zip}).count())\n tempdict['carbon']=0\n for profile in Profiles.find({'zip':zip}):\n tempdict['loc']=profile['zip_centroid']\n user=profile['user_id']\n user_carbon=getModeCarbonFootprint(user,carbonFootprintForMode,start,end)\n tempdict['carbon']+=sum(list(user_carbon.values()))\n tempdict['carbon']=tempdict['carbon']/tempdict['weight']\n carbon_list.append(tempdict)\n return {\"weightedLoc\": carbon_list}\n\ndef Berkeley_pop_route(start_dt, end_dt):\n box = [ [-122.267443, 37.864693], [-122.250985, 37.880687] ]\n tl = esdt.get_aggregate_timeline_from_dt(start_dt, end_dt, box)\n gj_list = gfc.get_geojson_for_timeline(None, tl, viz=True)\n list_of_points=[]\n for gj in gj_list:\n for feature in gj:\n if feature['type'] == 'FeatureCollection':\n for feat in feature['features']:\n if \"properties\" not in feat:\n continue\n if feat['properties']['feature_type'] == \"section\":\n points = feat.geometry.coordinates\n list_of_points.extend(points)\n return {\"latlng\": list_of_points}\n\ndef Commute_pop_route(mode, start_dt, end_dt):\n tl = esdt.get_aggregate_timeline_from_dt(start_dt, end_dt)\n gj_list = gfc.get_geojson_for_timeline(None, tl, viz=True)\n \n logging.debug(\"len gl list is %d\" % len(gj_list))\n list_of_point=[]\n \n for gj in gj_list:\n for feature in gj:\n if feature['type'] == 'FeatureCollection':\n for feat in feature['features']:\n if \"properties\" not in feat:\n continue\n if feat['properties']['feature_type'] == \"section\":\n if mode == 'all' or feat.properties[\"sensed_mode\"] == mode:\n points = feat.geometry.coordinates\n list_of_point.extend(points)\n logging.debug(\"Returning list of size %s\" % len(list_of_point))\n return {\"latlng\": list_of_point}\n\n\n\n","sub_path":"emission/net/api/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"634216943","text":"# coding:utf-8\n# some files may be duplicate, delete them!\n# only in the current directory\n# Andriy Lin\n\nimport os\nimport binascii\n\nDEF_DIR = './'\n\n\ndef check_crc(filenames):\n crc_map = {}\n for filename in filenames:\n f = open(filename, 'rb')\n crc = binascii.crc32(f.read())\n f.close()\n\n if crc in crc_map:\n crc_map[crc].append(filename)\n else:\n crc_map[crc] = [filename]\n\n # read saved data and check\n for same_crc_files in crc_map.values():\n if len(same_crc_files) > 1:\n #print 'GOT NEW DUPLICATES:'\n #print ' ', same_crc_files[0]\n for name in same_crc_files[1:]:\n os.remove(name)\n #print ' ', name, ' REMOVED'\n #print\n\ndef check_files(dirpath):\n if not os.path.isdir(dirpath):\n #print 'PATH: ' + dirpath + ' INVALID'\n return\n\n size_map = {}\n filenames = os.listdir(DEF_DIR)\n for filename in filenames:\n if not os.path.isfile(filename):\n continue\n\n filesize = os.path.getsize(filename)\n if filesize in size_map:\n size_map[filesize].append(filename)\n else:\n size_map[filesize] = [filename]\n\n # read data and check\n for same_size_files in size_map.values():\n if len(same_size_files) > 1:\n check_crc(same_size_files)\n\n\nif __name__ == '__main__':\n check_files(DEF_DIR)\n","sub_path":"diskmgr/_unique.py","file_name":"_unique.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"262147829","text":"# Crie um programa que leia o nome, ano de nascimento e carteira de trabalho\n# Cadastre-os com a idade em um dicionário se por acaso a CTPS for diferente de zero,\n# O dicionário receberá também o ano de contratação e o salario.\n# Calcule acrescente, além da idade, com quatos anos a pessoa vai se aposentar.\n\nfrom datetime import datetime\ndados = {}\ndados[\"Nome\"] = str(input('Nome: '))\nano_nascimento = int(input('Ano de Nascimento: '))\ndados[\"Idade\"] = datetime.now().year - ano_nascimento\ndados[\"Ctps\"] = int(input('Carteira de Trabalho (0 não tem): '))\nif dados[\"Ctps\"] != 0:\n dados[\"Contratação\"] = int(input('Ano de contratação: '))\n dados[\"Salário\"] = float(input('Salário: R$'))\n dados[\"Aposentadoria\"] = dados[\"Idade\"] + ((dados[\"Contratação\"] + 35) - datetime.now().year)\nprint('-=' * 40)\nprint(dados)\nfor k, v in dados.items():\n print(f'{k} tem o valor {v}')\n\n","sub_path":"ex092.py","file_name":"ex092.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"358172535","text":"import os\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'mesolitica-tpu.json'\n\nimport tensorflow as tf\nimport tensorflow_datasets as tfds\nfrom t5.data import preprocessors as prep\nimport functools\nimport t5\nimport gin\nimport sentencepiece as spm\nfrom glob import glob\nimport os\nfrom tensor2tensor.data_generators import problem\nfrom tensor2tensor.data_generators import text_problems\nfrom tensor2tensor.utils import registry\n\ngin.parse_config_file('pretrained_models_base_operative_config.gin')\nvocab = 'sp10m.cased.t5.model'\nsp = spm.SentencePieceProcessor()\nsp.Load(vocab)\n\n\ndef synonym_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(['synonyms.tsv'])\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n return ds\n\n\ndef synonym_preprocessor(ds):\n def to_inputs_and_targets(ex):\n return {\n 'inputs': tf.strings.join(['sinonim: ', ex['question']]),\n 'targets': ex['answer'],\n }\n\n return ds.map(\n to_inputs_and_targets,\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n\n\nt5.data.TaskRegistry.remove('synonym_dataset')\nt5.data.TaskRegistry.add(\n 'synonym_dataset',\n dataset_fn = synonym_dataset,\n splits = ['train'],\n text_preprocessor = [synonym_preprocessor],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"synonym_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef stemming_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(['stemming.tsv'])\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n return ds\n\n\ndef stemming_preprocessor(ds):\n def to_inputs_and_targets(ex):\n return {\n 'inputs': tf.strings.join(['punca: ', ex['question']]),\n 'targets': ex['answer'],\n }\n\n return ds.map(\n to_inputs_and_targets,\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n\n\nt5.data.TaskRegistry.remove('stemming_dataset')\nt5.data.TaskRegistry.add(\n 'stemming_dataset',\n dataset_fn = stemming_dataset,\n splits = ['train'],\n text_preprocessor = [stemming_preprocessor],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"stemming_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef pair_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(glob('*pair.tsv'))\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['text'], ex)))\n return ds\n\n\nt5.data.TaskRegistry.remove('pair_dataset')\nt5.data.TaskRegistry.add(\n 'pair_dataset',\n dataset_fn = pair_dataset,\n splits = ['train'],\n text_preprocessor = [prep.next_sentence_prediction],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"pair_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef dumping_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(\n [\n 'cleaned-news.txt.tsv',\n 'dumping-parliament.txt.tsv',\n 'filtered-dumping-academia.txt.tsv',\n 'filtered-dumping-cleaned-common-crawl.txt.tsv',\n 'filtered-dumping-wiki.txt.tsv',\n ]\n )\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['title', 'text'], ex)))\n return ds\n\n\nt5.data.TaskRegistry.remove('dumping_dataset')\nt5.data.TaskRegistry.add(\n 'dumping_dataset',\n dataset_fn = dumping_dataset,\n splits = ['train'],\n text_preprocessor = functools.partial(\n t5.data.preprocessors.rekey,\n key_map = {'inputs': None, 'targets': 'text'},\n ),\n token_preprocessor = t5.data.preprocessors.unsupervised,\n sentencepiece_model_path = vocab,\n metric_fns = [],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"dumping_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef news_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(['newstitle.tsv'])\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n return ds\n\n\ndef news_preprocessor(ds):\n def to_inputs_and_targets(ex):\n return {\n 'inputs': tf.strings.join(['tajuk: ', ex['question']]),\n 'targets': ex['answer'],\n }\n\n return ds.map(\n to_inputs_and_targets,\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n\n\nt5.data.TaskRegistry.remove('news_dataset')\nt5.data.TaskRegistry.add(\n 'news_dataset',\n dataset_fn = news_dataset,\n splits = ['train'],\n text_preprocessor = [news_preprocessor],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"news_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef question_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(['qa.tsv'])\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n return ds\n\n\ndef question_preprocessor(ds):\n def to_inputs_and_targets(ex):\n return {\n 'inputs': tf.strings.join(['soalan: ', ex['question']]),\n 'targets': ex['answer'],\n }\n\n return ds.map(\n to_inputs_and_targets,\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n\n\nt5.data.TaskRegistry.remove('question_dataset')\nt5.data.TaskRegistry.add(\n 'question_dataset',\n dataset_fn = question_dataset,\n splits = ['train'],\n text_preprocessor = [question_preprocessor],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"question_dataset\")\n# ds = nq_task.get_dataset(split='qa.tsv', sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\n\ndef similarity_dataset(split, shuffle_files = False):\n del shuffle_files\n ds = tf.data.TextLineDataset(['quora.tsv', 'mnli.tsv', 'snli.tsv'])\n\n ds = ds.map(\n functools.partial(\n tf.io.decode_csv,\n record_defaults = ['', ''],\n field_delim = '\\t',\n use_quote_delim = False,\n ),\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n ds = ds.map(lambda *ex: dict(zip(['question', 'answer'], ex)))\n return ds\n\n\ndef similarity_preprocessor(ds):\n def to_inputs_and_targets(ex):\n return {'inputs': ex['question'], 'targets': ex['answer']}\n\n return ds.map(\n to_inputs_and_targets,\n num_parallel_calls = tf.data.experimental.AUTOTUNE,\n )\n\n\nt5.data.TaskRegistry.remove('similarity_dataset')\nt5.data.TaskRegistry.add(\n 'similarity_dataset',\n dataset_fn = similarity_dataset,\n splits = ['train'],\n text_preprocessor = [similarity_preprocessor],\n sentencepiece_model_path = vocab,\n metric_fns = [t5.evaluation.metrics.accuracy],\n)\n\n# nq_task = t5.data.TaskRegistry.get(\"similarity_dataset\")\n# ds = nq_task.get_dataset(split=file, sequence_length={\"inputs\": 1024, \"targets\": 1024})\n\nfrom tqdm import tqdm\n\n\n@registry.register_problem\nclass Seq2Seq(text_problems.Text2TextProblem):\n @property\n def approx_vocab_size(self):\n return 32100\n\n @property\n def is_generate_per_split(self):\n return False\n\n @property\n def dataset_splits(self):\n return [\n {'split': problem.DatasetSplit.TRAIN, 'shards': 200},\n {'split': problem.DatasetSplit.EVAL, 'shards': 1},\n ]\n\n def generate_samples(self, data_dir, tmp_dir, dataset_split):\n del data_dir\n del tmp_dir\n del dataset_split\n\n datasets = [\n 'synonym_dataset',\n 'stemming_dataset',\n 'pair_dataset',\n 'question_dataset',\n 'similarity_dataset',\n 'news_dataset',\n ]\n\n for dataset in datasets:\n print(dataset)\n\n nq_task = t5.data.TaskRegistry.get(dataset)\n ds = nq_task.get_dataset(\n split = 'qa.tsv',\n sequence_length = {'inputs': 768, 'targets': 768},\n )\n\n for ex in tqdm(tfds.as_numpy(ds)):\n yield ex\n\n for k in range(5):\n nq_task = t5.data.TaskRegistry.get('dumping_dataset')\n ds = nq_task.get_dataset(\n split = 'qa.tsv',\n sequence_length = {'inputs': 768, 'targets': 768},\n )\n\n for ex in tqdm(tfds.as_numpy(ds)):\n yield ex\n\n def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):\n\n generator = self.generate_samples(data_dir, tmp_dir, dataset_split)\n for sample in generator:\n sample['inputs'] = sample['inputs'].tolist()\n sample['targets'] = sample['targets'].tolist()\n yield sample\n\n\nDATA_DIR = os.path.expanduser('t2t/data')\nTMP_DIR = os.path.expanduser('t2t/tmp')\n\ntf.gfile.MakeDirs(DATA_DIR)\ntf.gfile.MakeDirs(TMP_DIR)\n\nfrom tensor2tensor.utils import registry\nfrom tensor2tensor import problems\n\nPROBLEM = 'seq2_seq'\nt2t_problem = problems.problem(PROBLEM)\nt2t_problem.generate_data(DATA_DIR, TMP_DIR)\n","sub_path":"pretrained-model/lm-transformer/prepare/t2t-gcs.py","file_name":"t2t-gcs.py","file_ext":"py","file_size_in_byte":10968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"268893694","text":"import requests\nfrom bs4 import BeautifulSoup as soup\n\n\ndef main():\n print(\"Searching lowest priced items on eBay and Amazon\")\n search = input(\"What is the search? Be specific! \")\n\n eBayUrl = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw='\n\n for chars in search:\n if chars != ' ':\n eBayUrl += chars\n else:\n eBayUrl += '+'\n\n eBayUrl += '&_sop=15&rt=nc&LH_BIN=1'\n\n AmazonUrl = 'https://www.amazon.com/s?k='\n\n for chars in search:\n if chars != ' ':\n AmazonUrl += chars\n else:\n AmazonUrl += '+'\n\n AmazonUrl += '&s=price-asc-rank'\n\n print(\"searching \" + search + \", please wait . . .\\n\")\n\n headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0'}\n\n eBayClient = requests.get(eBayUrl, headers=headers)\n AmazonClient = requests.get(AmazonUrl, headers=headers)\n\n eBayPage = eBayClient.content\n AmazonPage = AmazonClient.content\n\n eBayClient.close()\n AmazonClient.close()\n\n eBaySoup = soup(eBayPage, \"html.parser\")\n AmazonSoup = soup(AmazonPage, \"html.parser\")\n\n eBayContainer = eBaySoup.findAll(\"a\", {\"class\": \"s-item__link\"})\n AmazonContainer = AmazonSoup.findAll(\"a\", {\"class\": \"a-link-normal a-text-normal\"})\n\n eBaySelectedItem = \"\"\n AmazonSelectedItem = \"\"\n\n print(\"eBay Results:\")\n\n for item in eBayContainer:\n print(item.h3.text)\n option = input(\"Is this the item your are looking for? [y/n] \")\n\n if len(option) > 0:\n if option[0] == 'y' or option[0] == 'Y':\n eBaySelectedItem = item\n break\n\n print('\\n')\n\n if eBaySelectedItem == \"\":\n print(\"It seems like we couldn't find you item. Try to be more specific with your search.\")\n return 0\n\n print(\"\\n\\nAmazon Results:\")\n\n for item in AmazonContainer:\n print(item.span.text)\n option = input(\"Is this the item your are looking for? [y/n] \")\n\n if len(option) > 0:\n if option[0] == 'y' or option[0] == 'Y':\n AmazonSelectedItem = item\n break\n\n print('\\n')\n\n if AmazonSelectedItem == \"\":\n print(\"It seems like we couldn't find you item. Amazon failed to respond (try again), or you need to \"\n + \"try to be more specific with your search.\")\n return 0\n\n print(\"\\nPLease wait . . .\\n\")\n\n selectedEbayUrl = eBaySelectedItem[\"href\"]\n selectedAmazonUrl = \"https://www.amazon.com\" + AmazonSelectedItem[\"href\"]\n\n eBayClient = requests.get(selectedEbayUrl, headers=headers)\n AmazonClient = requests.get(selectedAmazonUrl, headers=headers)\n\n selectedEbayPage = eBayClient.content\n selectedAmazonPage = AmazonClient.content\n\n eBayClient.close()\n AmazonClient.close()\n\n selectedEbaySoup = soup(selectedEbayPage, \"html.parser\")\n selectedAmazonSoup = soup(selectedAmazonPage, \"html.parser\")\n\n eBayPrice = selectedEbaySoup.findAll(\"span\", {\"id\": \"prcIsum\"})[0].text\n AmazonPrice = selectedAmazonSoup.findAll(\"span\", {\"id\": \"priceblock_ourprice\"})[0].text\n eBayShipping = selectedEbaySoup.findAll(\"span\", {\"id\": \"shSummary\"})\n AmazonShipping = selectedAmazonSoup.findAll(\"span\", {\"class\": \"a-color-secondary a-size-base\"})[0].text\n\n eBayPriceIndex = 0\n AmazonPriceIndex = 0\n\n for i in range(0, len(eBayPrice)):\n if 47 < eBayPrice[i] < 58:\n eBayPriceIndex = i\n break\n\n for i in range(0, len(AmazonPrice)):\n if 47 < AmazonPrice[i] < 58:\n AmazonPriceIndex = i\n break\n\n if float(eBayPrice[eBayPriceIndex:]) < float(AmazonPrice[AmazonPriceIndex:]):\n print(\"eBay had the best price!\")\n print(\"@ this url: \" + selectedEbayUrl)\n\n elif float(eBayPrice[eBayPriceIndex:]) > float(AmazonPrice[AmazonPriceIndex:]):\n print(\"Amazon had the best price!\")\n print(\"@ this url: \" + selectedAmazonUrl)\n\n else:\n print(\"Both eBay and Amazon have the same price for the item!\")\n print(\"@ these urls:\")\n print(\"eBay: \" + selectedEbayUrl)\n print(\"Amazon \" + selectedAmazonUrl)\n\nmain()\n","sub_path":"EbayAndAmazonScrapin/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"468292955","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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.macosx-10.3-i386/egg/easyshop/customers/adapters/completeness.py\n# Compiled at: 2008-09-03 11:14:43\nfrom zope.interface import implements\nfrom zope.component import adapts\nfrom easyshop.core.interfaces import ICompleteness\nfrom easyshop.core.interfaces import IAddress\nfrom easyshop.core.interfaces import IAddressManagement\nfrom easyshop.core.interfaces import IPaymentInformationManagement\nfrom easyshop.core.interfaces import ICartManagement\nfrom easyshop.core.interfaces import IItemManagement\nfrom easyshop.core.interfaces import ICustomer\nfrom easyshop.core.interfaces import IShopManagement\n\nclass CustomerCompleteness:\n \"\"\"\n \"\"\"\n __module__ = __name__\n implements(ICompleteness)\n adapts(ICustomer)\n\n def __init__(self, context):\n \"\"\"\n \"\"\"\n self.context = context\n\n def isComplete(self):\n \"\"\"Checks weather the customer is complete to checkout.\n \n Customer completeness means the customer is ready to check out:\n 1. Invoice address is complete\n 2. Shipping address is complete\n 3. Selected payment method is complete\n 4. There a items in the cart \n \"\"\"\n shop = IShopManagement(self.context).getShop()\n adressman = IAddressManagement(self.context)\n s_addr = adressman.getShippingAddress()\n if s_addr is None:\n return False\n i_addr = adressman.getInvoiceAddress()\n if i_addr is None:\n return False\n pm = IPaymentInformationManagement(self.context)\n payment_method = pm.getSelectedPaymentMethod()\n cart = ICartManagement(shop).getCart()\n if cart is None:\n return False\n im = IItemManagement(cart)\n for toCheck in (s_addr, i_addr, payment_method):\n if ICompleteness(toCheck).isComplete() == False:\n return False\n\n if im.hasItems() == False:\n return False\n return True\n\n\nclass AddressCompleteness:\n \"\"\"Provides ICompleteness for address content objects\n \"\"\"\n __module__ = __name__\n implements(ICompleteness)\n adapts(IAddress)\n\n def __init__(self, context):\n \"\"\"\n \"\"\"\n self.context = context\n\n def isComplete(self):\n \"\"\"Checks the completeness of an address.\n \"\"\"\n if len(self.context.address_1) == 0:\n return False\n elif len(self.context.zip_code) == 0:\n return False\n elif len(self.context.city) == 0:\n return False\n elif len(self.context.country) == 0:\n return False\n return True","sub_path":"pycfiles/easyshop.customers-0.1a1-py2.4/completeness.py","file_name":"completeness.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"261690683","text":"from qcloud_image import Client, CIUrl, CIFile, CIBuffer, CIUrls, CIBuffers, \\\n CIFiles\n\nimport os\n\n# appid = '1256911928'\n# secretid = 'AKIDSq495t2JbjhVRUIXMIUkcc6VpNo5QKv0'\n# secretkey = 'Ac4mbinjcsLGh1oVxj1jXknfh6c1GQQS'\n# bucket = 'BUCKET'\n# client = Client(appid, secretid, secretkey, bucket)\n# client.use_http()\n# client.set_timeout(30)\n\n\ns = os.path.abspath(os.path.join(os.getcwd(), \"./upload\"))\nfilepath = os.path.join(s, \"j.txt\")\n\nprint(\"s: %s\" %s)\nprint(\"f: %s\" %filepath)","sub_path":"appraise/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"452522716","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\" \ncreating graph data for numbers of parallels of indicated collections\n\n\"\"\"\nimport os\nimport re\nimport json\n\nparallelpath = os.environ['HOME']+'/sc-data/relationship/parallels.json'\noutputpath = os.environ['HOME']+'/buddhanexus-utils/wordlength/'\n\n# retrieving data from the parallels file.\nparallelfile = open(parallelpath,'r', encoding='utf8').read()\noutputparallelfile = open(outputpath+'parallel.json','w', encoding='utf8')\n\nparalleljson = json.loads(parallelfile)\ncollectiondict = {}\n\n# change the regex according to the criteria you want to search on\ncollectionnr = re.compile('^tha-ap[0-9]+')\ntotalrange = 547\n\nfor parallel in paralleljson:\n try:\n\n if any(collectionnr.match(x) for x in parallel[\"parallels\"]):\n for item in parallel[\"parallels\"]:\n if collectionnr.match(item):\n itemnumber = item.split('#')[0]\n if itemnumber in collectiondict.keys():\n collectiondict[itemnumber] += len(parallel[\"parallels\"])-1\n else:\n collectiondict[itemnumber] = len(parallel[\"parallels\"])-1\n except:\n continue\n\nfor parallel in paralleljson:\n try:\n if any(collectionnr.match(x) for x in parallel[\"mentions\"]):\n for item in parallel[\"mentions\"]:\n if collectionnr.match(item):\n itemnumber = item.split('#')[0]\n if itemnumber in collectiondict.keys():\n collectiondict[itemnumber] += len(parallel[\"mentions\"])-1\n else:\n collectiondict[itemnumber] = len(parallel[\"mentions\"])-1\n except:\n continue\n\nfor parallel in paralleljson:\n try:\n if any(collectionnr.match(x) for x in parallel[\"retells\"]):\n for item in parallel[\"retells\"]:\n if collectionnr.match(item):\n itemnumber = item.split('#')[0]\n if itemnumber in collectiondict.keys():\n collectiondict[itemnumber] += len(parallel[\"retells\"])-1\n else:\n collectiondict[itemnumber] = len(parallel[\"retells\"])-1\n except:\n continue\n\n# add 0 where there is no parallel and sort numbers.\nnewcollectiondict = {}\nfor i in range(totalrange):\n if \"tha-ap\"+str(i+1) in collectiondict.keys():\n newcollectiondict[\"tha-ap\"+str(i+1)] = collectiondict[\"tha-ap\"+str(i+1)]\n else:\n newcollectiondict[\"tha-ap\"+str(i+1)] = 0\n\n\noutputparallelfile.write(json.dumps(newcollectiondict, ensure_ascii=False, indent=2))\noutputparallelfile.write(',\\n')\noutputparallelfile.close()\n\n","sub_path":"wordlength/parallelsgraphdata.py","file_name":"parallelsgraphdata.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"64001685","text":"#pip install youtube-dl\n#Requirement already satisfied: youtube-dl in c:\\users\\karsten\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\n\nimport youtube_dl\n\nydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})\n\nwith ydl:\n result = ydl.extract_info(\n 'http://www.youtube.com/watch?v=BaW_jenozKc',\n download=False # We just want to extract the info\n )\n\nif 'entries' in result:\n # Can be a playlist or a list of videos\n video = result['entries'][0]\nelse:\n # Just a video\n video = result\n\nprint(video)\nvideo_url = video['url']\nprint(video_url)","sub_path":"youtube-dl-test.py","file_name":"youtube-dl-test.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"44383559","text":"from arrayQFile import ArrayQ \r\n\r\nif __name__==\"__main__\":\r\n que=ArrayQ()\r\n\r\n order=input('Vilken ordning ligger korten i? ')\r\n order=order.split()\r\n order=[ int(x) for x in order] #All elements in my variable \"order\" become integers. (Previously were strings)\r\n \r\n\r\n for i in range(len(order)): #Entering all the numbers into the array\r\n que.enqueue(order[i])\r\n \r\n \r\n output=[]\r\n while que.isEmpty()==False:\r\n que.enqueue(que._front) #Moves the first card to the back\r\n trash=que.dequeue() #when moving my first card to the back with enqueue, it still has a copy in the first element, therefore i throw it away here\r\n output.append(que.dequeue()) #Taking out the second card\r\n \r\n\r\n print('De kommer ut i denna ordning:', *output)\r\n\r\n # The order is 7 1 12 2 8 3 11 4 9 5 13 6 10","sub_path":"ArrayQmodul.py","file_name":"ArrayQmodul.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"11162365","text":"# -*- coding: utf-8 -*-\n\n# Three possible modes:\n# 'cli': running from \"wandb\" command\n# 'run': we're a script launched by \"wandb run\"\n# 'dryrun': we're a script not launched by \"wandb run\"\n\nfrom __future__ import absolute_import, print_function\n\n__author__ = \"\"\"Chris Van Pelt\"\"\"\n__email__ = 'vanpelt@wandb.com'\n__version__ = '0.8.19'\n\nimport atexit\nimport click\nimport io\nimport json\nimport logging\nimport time\nimport os\nimport contextlib\nimport signal\nimport six\nimport getpass\nimport socket\nimport subprocess\nimport sys\nimport traceback\nimport tempfile\nimport re\nimport glob\nimport threading\nimport platform\nimport collections\nfrom six.moves import queue\nfrom six import string_types\nfrom importlib import import_module\n\nfrom . import env\nfrom . import io_wrap\nfrom .core import *\n\n# These imports need to be below \"from .core import *\" until we remove\n# 'from wandb import __stage_dir__' from api.py etc.\nfrom wandb.apis import InternalApi, PublicApi, CommError\nfrom wandb import wandb_types as types\nfrom wandb import wandb_config\nfrom wandb import wandb_run\nfrom wandb import wandb_socket\nfrom wandb import streaming_log\nfrom wandb import util\nfrom wandb.run_manager import LaunchError, Process\nfrom wandb.data_types import Image\nfrom wandb.data_types import Video\nfrom wandb.data_types import Audio\nfrom wandb.data_types import Table\nfrom wandb.data_types import Html\nfrom wandb.data_types import Object3D\nfrom wandb.data_types import Histogram\nfrom wandb.data_types import Graph\nfrom wandb import trigger\nfrom wandb.dataframes import image_categorizer_dataframe\nfrom wandb.dataframes import image_segmentation_dataframe\nfrom wandb.dataframes import image_segmentation_binary_dataframe\nfrom wandb.dataframes import image_segmentation_multiclass_dataframe\n\nfrom wandb import wandb_torch\nfrom wandb.wandb_agent import agent\nfrom wandb.wandb_controller import sweep, controller\n\nfrom wandb.compat import windows\n\nlogger = logging.getLogger(__name__)\n\n# Internal variables\n_shutdown_async_log_thread_wait_time = 20\n\n# this global W&B debug log gets re-written by every W&B process\nif __stage_dir__ is not None:\n GLOBAL_LOG_FNAME = os.path.abspath(os.path.join(wandb_dir(), 'debug.log'))\nelse:\n GLOBAL_LOG_FNAME = os.path.join(tempfile.gettempdir(), 'wandb-debug.log')\n\n\ndef _debugger(*args):\n import pdb\n pdb.set_trace()\n\n\nclass Callbacks():\n @property\n def Keras(self):\n termlog(\n \"DEPRECATED: wandb.callbacks is deprecated, use `from wandb.keras import WandbCallback`\")\n from wandb.keras import WandbCallback\n return WandbCallback\n\n\ncallbacks = Callbacks()\n\n\ndef hook_torch(*args, **kwargs):\n termlog(\n \"DEPRECATED: wandb.hook_torch is deprecated, use `wandb.watch`\")\n return watch(*args, **kwargs)\n\n\n_global_watch_idx = 0\n\n\ndef watch(models, criterion=None, log=\"gradients\", log_freq=100, idx=None):\n \"\"\"\n Hooks into the torch model to collect gradients and the topology. Should be extended\n to accept arbitrary ML models.\n\n :param (torch.Module) models: The model to hook, can be a tuple\n :param (torch.F) criterion: An optional loss value being optimized\n :param (str) log: One of \"gradients\", \"parameters\", \"all\", or None\n :param (int) log_freq: log gradients and parameters every N batches\n :param (int) idx: an index to be used when calling wandb.watch on multiple models\n :return: (wandb.Graph) The graph object that will populate after the first backward pass\n \"\"\"\n global _global_watch_idx\n\n if run is None:\n raise ValueError(\n \"You must call `wandb.init` before calling watch\")\n\n log_parameters = False\n log_gradients = True\n if log == \"all\":\n log_parameters = True\n elif log == \"parameters\":\n log_parameters = True\n log_gradients = False\n elif log is None:\n log_gradients = False\n\n if not isinstance(models, (tuple, list)):\n models = (models,)\n graphs = []\n prefix = ''\n if idx is None:\n idx = _global_watch_idx\n for local_idx, model in enumerate(models):\n global_idx = idx + local_idx\n _global_watch_idx += 1\n if global_idx > 0:\n # TODO: this makes ugly chart names like gradients/graph_1conv1d.bias\n prefix = \"graph_%i\" % global_idx\n\n run.history.torch.add_log_hooks_to_pytorch_module(\n model, log_parameters=log_parameters, log_gradients=log_gradients, prefix=prefix, log_freq=log_freq)\n\n graph = wandb_torch.TorchGraph.hook_torch(\n model, criterion, graph_idx=global_idx)\n graphs.append(graph)\n # NOTE: the graph is set in run.summary by hook_torch on the backward pass\n return graphs\n\n\ndef unwatch(models=None):\n \"\"\"Remove pytorch gradient and parameter hooks.\n\n Args:\n models (list): Optional list of pytorch models that have had watch called on them\n \"\"\"\n if models:\n if not isinstance(models, (tuple, list)):\n models = (models,)\n for model in models:\n if not hasattr(model, \"_wandb_hook_names\"):\n termwarn(\"%s model has not been watched\" % model)\n else:\n for name in model._wandb_hook_names:\n run.history.torch.unhook(name)\n else:\n run.history.torch.unhook_all()\n\n\nclass ExitHooks(object):\n def __init__(self):\n self.exit_code = 0\n self.exception = None\n\n def hook(self):\n self._orig_exit = sys.exit\n sys.exit = self.exit\n sys.excepthook = self.exc_handler\n\n def exit(self, code=0):\n orig_code = code\n if code is None:\n code = 0\n elif not isinstance(code, int):\n code = 1\n self.exit_code = code\n self._orig_exit(orig_code)\n\n def was_ctrl_c(self):\n return isinstance(self.exception, KeyboardInterrupt)\n\n def exc_handler(self, exc_type, exc, *tb):\n self.exit_code = 1\n self.exception = exc\n if issubclass(exc_type, Error):\n termerror(str(exc))\n\n if self.was_ctrl_c():\n self.exit_code = 255\n\n traceback.print_exception(exc_type, exc, *tb)\n\n\ndef _init_headless(run, cloud=True):\n global join\n global _user_process_finished_called\n\n environ = dict(os.environ)\n run.set_environment(environ)\n\n server = wandb_socket.Server()\n run.socket = server\n hooks = ExitHooks()\n hooks.hook()\n\n if platform.system() == \"Windows\":\n try:\n import win32api\n # Make sure we are not ignoring CTRL_C_EVENT\n # https://docs.microsoft.com/en-us/windows/console/setconsolectrlhandler\n # https://stackoverflow.com/questions/1364173/stopping-python-using-ctrlc\n win32api.SetConsoleCtrlHandler(None, False)\n except ImportError:\n termerror(\"Install the win32api library with `pip install pypiwin32`\")\n\n # PTYs don't work in windows so we create these unused pipes and\n # mirror stdout to run.dir/output.log. There should be a way to make\n # pipes work, but I haven't figured it out. See links in compat/windows\n stdout_master_fd, stdout_slave_fd = os.pipe()\n stderr_master_fd, stderr_slave_fd = os.pipe()\n else:\n stdout_master_fd, stdout_slave_fd = io_wrap.wandb_pty(resize=False)\n stderr_master_fd, stderr_slave_fd = io_wrap.wandb_pty(resize=False)\n\n headless_args = {\n 'command': 'headless',\n 'pid': os.getpid(),\n 'stdout_master_fd': stdout_master_fd,\n 'stderr_master_fd': stderr_master_fd,\n 'cloud': cloud,\n 'port': server.port\n }\n internal_cli_path = os.path.join(\n os.path.dirname(__file__), 'internal_cli.py')\n\n if six.PY2 or platform.system() == \"Windows\":\n # TODO(adrian): close_fds=False is bad for security. we set\n # it so we can pass the PTY FDs to the wandb process. We\n # should use subprocess32, which has pass_fds.\n popen_kwargs = {'close_fds': False}\n else:\n popen_kwargs = {'pass_fds': [stdout_master_fd, stderr_master_fd]}\n\n # TODO(adrian): ensure we use *exactly* the same python interpreter\n # TODO(adrian): make wandb the foreground process so we don't give\n # up terminal control until syncing is finished.\n # https://stackoverflow.com/questions/30476971/is-the-child-process-in-foreground-or-background-on-fork-in-c\n wandb_process = subprocess.Popen([sys.executable, internal_cli_path, json.dumps(\n headless_args)], env=environ, **popen_kwargs)\n termlog('Tracking run with wandb version {}'.format(\n __version__))\n os.close(stdout_master_fd)\n os.close(stderr_master_fd)\n # Listen on the socket waiting for the wandb process to be ready\n try:\n success, _ = server.listen(30)\n except KeyboardInterrupt:\n success = False\n else:\n if not success:\n termerror('W&B process (PID {}) did not respond'.format(\n wandb_process.pid))\n if not success:\n wandb_process.kill()\n for _ in range(20):\n time.sleep(0.1)\n if wandb_process.poll() is not None:\n break\n if wandb_process.poll() is None:\n termerror('Failed to kill wandb process, PID {}'.format(\n wandb_process.pid))\n # TODO attempt to upload a debug log\n path = GLOBAL_LOG_FNAME.replace(os.getcwd()+os.sep, \"\")\n raise LaunchError(\n \"W&B process failed to launch, see: {}\".format(path))\n\n if platform.system() == \"Windows\":\n output = open(os.path.join(run.dir, \"output.log\"), \"wb\")\n stdout_redirector = io_wrap.WindowsRedirector(sys.stdout, output)\n stderr_redirector = io_wrap.WindowsRedirector(sys.stderr, output)\n else:\n stdout_slave = os.fdopen(stdout_slave_fd, 'wb')\n stderr_slave = os.fdopen(stderr_slave_fd, 'wb')\n try:\n stdout_redirector = io_wrap.FileRedirector(sys.stdout, stdout_slave)\n stderr_redirector = io_wrap.FileRedirector(sys.stderr, stderr_slave)\n except ValueError:\n # stdout / err aren't files\n output = open(os.path.join(run.dir, \"output.log\"), \"wb\")\n stdout_redirector = io_wrap.WindowsRedirector(sys.stdout, output)\n stderr_redirector = io_wrap.WindowsRedirector(sys.stderr, output)\n\n # TODO(adrian): we should register this right after starting the wandb process to\n # make sure we shut down the W&B process eg. if there's an exception in the code\n # above\n atexit.register(_user_process_finished, server, hooks,\n wandb_process, stdout_redirector, stderr_redirector)\n\n def _wandb_join(exit_code=None):\n global _global_run_stack\n shutdown_async_log_thread()\n run.close_files()\n if exit_code is not None:\n hooks.exit_code = exit_code\n _user_process_finished(server, hooks,\n wandb_process, stdout_redirector, stderr_redirector)\n if len(_global_run_stack) > 0:\n _global_run_stack.pop()\n join = _wandb_join\n _user_process_finished_called = False\n\n # redirect output last of all so we don't miss out on error messages\n stdout_redirector.redirect()\n if not env.is_debug():\n stderr_redirector.redirect()\n\n\ndef load_ipython_extension(ipython):\n pass\n\n\ndef login(anonymous=None, key=None):\n \"\"\"Ensure this machine is logged in\n\n You can manually specify a key, but this method is intended to prompt for user input.\n\n anonymous can be \"never\", \"must\", or \"allow\". If set to \"must\" we'll always login anonymously,\n if set to \"allow\" we'll only create an anonymous user if the user isn't already logged in.\n\n Returns:\n True if login was successful\n False on failure\n \"\"\"\n # This ensures we have a global api object\n ensure_configured()\n if anonymous:\n os.environ[env.ANONYMOUS] = anonymous\n anonymous = anonymous or \"never\"\n in_jupyter = _get_python_type() != \"python\"\n if key:\n termwarn(\"If you're specifying your api key in code, ensure this code is not shared publically.\\nConsider setting the WANDB_API_KEY environment variable, or running `wandb login` from the command line.\")\n if in_jupyter:\n termwarn(\"Calling wandb.login() without arguments from jupyter should prompt you for an api key.\")\n util.set_api_key(api, key)\n elif api.api_key and anonymous != \"must\":\n key = api.api_key\n elif in_jupyter:\n os.environ[env.JUPYTER] = \"true\"\n # Don't return key to ensure it's not displayed in the notebook.\n key = _jupyter_login(api=api)\n else:\n key = util.prompt_api_key(api)\n return True if key else False\n\n\ndef _jupyter_login(force=True, api=None):\n \"\"\"Attempt to login from a jupyter environment\n\n If force=False, we'll only attempt to auto-login, otherwise we'll prompt the user\n \"\"\"\n def get_api_key_from_browser(signup=False):\n key, anonymous = None, False\n if 'google.colab' in sys.modules:\n key = jupyter.attempt_colab_login(api.app_url)\n elif 'databricks_cli' in sys.modules and 'dbutils' in sys.modules:\n # Databricks does not seem to support getpass() so we need to fail\n # early and prompt the user to configure the key manually for now.\n termerror(\n \"Databricks requires api_key to be configured manually, instructions at: http://docs.wandb.com/integrations/databricks\")\n raise LaunchError(\"Databricks integration requires api_key to be configured.\")\n # For jupyter we default to not allowing anonymous\n if not key and os.environ.get(env.ANONYMOUS, \"never\") != \"never\":\n key = api.create_anonymous_api_key()\n anonymous = True\n if not key and force:\n try:\n termerror(\"Not authenticated. Copy a key from https://app.wandb.ai/authorize\")\n key = getpass.getpass(\"API Key: \").strip()\n except NotImplementedError:\n termerror(\n \"Can't accept input in this environment, you should set WANDB_API_KEY or call wandb.login(key='YOUR_API_KEY')\")\n return key, anonymous\n\n api = api or (run.api if run else None)\n if not api:\n raise LaunchError(\"Internal error: api required for jupyter login\")\n return util.prompt_api_key(api, browser_callback=get_api_key_from_browser)\n\n\ndef _init_jupyter(run):\n \"\"\"Asks for user input to configure the machine if it isn't already and creates a new run.\n Log pushing and system stats don't start until `wandb.log()` is first called.\n \"\"\"\n from wandb import jupyter\n from IPython.core.display import display, HTML\n # TODO: Should we log to jupyter?\n # global logging had to be disabled because it set the level to debug\n # I also disabled run logging because we're rairly using it.\n # try_to_set_up_global_logging()\n # run.enable_logging()\n os.environ[env.JUPYTER] = \"true\"\n\n if not run.api.api_key:\n # Fetches or prompts the users for an API key. Or if anonymode enabled, uses anonymous API key\n key = _jupyter_login()\n # Ensure our api client picks up the new key\n if key:\n run.api.reauth()\n else:\n run.mode = \"dryrun\"\n display(HTML('''\n Could not authenticate.
\n '''))\n run.resume = \"allow\"\n if run.mode == \"dryrun\":\n display(HTML('''\n Using Weights & Biases in dryrun mode. Not logging results to the cloud.
\n Call wandb.login() to authenticate this machine.
\n '''.format(run.api.app_url)))\n else:\n displayed = False\n try:\n sweep_url = run.get_sweep_url()\n sweep_line = 'Sweep page: {}
\\n'.format(\n sweep_url, sweep_url) if sweep_url else \"\"\n docs_html = '(Documentation)'\n display(HTML('''\n Logging results to Weights & Biases {}.
\n Project page: {}
\n {}Run page: {}
\n '''.format(docs_html, run.get_project_url(), run.get_project_url(), sweep_line, run.get_url(), run.get_url() )))\n displayed = True\n run.save()\n except (CommError, ValueError) as e:\n if not displayed:\n display(HTML('''\n Logging results to Weights & Biases.
\n Couldn't load entity due to error: {}\n '''.format(e.message)))\n else:\n termerror(str(e))\n\n run.set_environment()\n run._init_jupyter_agent()\n ipython = get_ipython()\n ipython.register_magics(jupyter.WandBMagics)\n\n def reset_start():\n \"\"\"Reset START_TIME to when the cell starts\"\"\"\n global START_TIME\n START_TIME = time.time()\n ipython.events.register(\"pre_run_cell\", reset_start)\n\n def cleanup():\n # shutdown async logger because _user_process_finished isn't called in jupyter\n shutdown_async_log_thread()\n run._stop_jupyter_agent()\n ipython.events.register('post_run_cell', cleanup)\n\n\n_user_process_finished_called = False\n\n\ndef _user_process_finished(server, hooks, wandb_process, stdout_redirector, stderr_redirector):\n global _user_process_finished_called\n if _user_process_finished_called:\n return\n _user_process_finished_called = True\n trigger.call('on_finished')\n\n stdout_redirector.restore()\n if not env.is_debug():\n stderr_redirector.restore()\n\n termlog()\n termlog(\"Waiting for W&B process to finish, PID {}\".format(wandb_process.pid))\n server.done(hooks.exit_code)\n try:\n while wandb_process.poll() is None:\n time.sleep(0.1)\n except KeyboardInterrupt:\n termlog('Sending ctrl-c to W&B process, PID {}. Press ctrl-c again to kill it.'.format(wandb_process.pid))\n\n try:\n while wandb_process.poll() is None:\n time.sleep(0.1)\n except KeyboardInterrupt:\n if wandb_process.poll() is None:\n termlog('Killing W&B process, PID {}'.format(wandb_process.pid))\n wandb_process.kill()\n\n\n# Will be set to the run object for the current run, as returned by\n# wandb.init(). We may want to get rid of this, but WandbCallback\n# relies on it, and it improves the API a bit (user doesn't have to\n# pass the run into WandbCallback). run is None instead of a PreInitObject\n# as many places in the code check this.\nrun = None\nconfig = util.PreInitObject(\"wandb.config\") # config object shared with the global run\nsummary = util.PreInitObject(\"wandb.summary\") # summary object shared with the global run\nApi = PublicApi\n# Stores what modules have been patched\npatched = {\n \"tensorboard\": [],\n \"keras\": [],\n \"gym\": []\n}\n_saved_files = set()\n_global_run_stack = []\n\n\ndef join(exit_code=None):\n \"\"\"Marks a run as finished\"\"\"\n shutdown_async_log_thread()\n if run:\n run.close_files()\n if len(_global_run_stack) > 0:\n _global_run_stack.pop()\n\n\ndef save(glob_str, base_path=None, policy=\"live\"):\n \"\"\" Ensure all files matching *glob_str* are synced to wandb with the policy specified.\n\n base_path: the base path to run the glob relative to\n policy:\n live: upload the file as it changes, overwriting the previous version\n end: only upload file when the run ends\n \"\"\"\n global _saved_files\n if run is None:\n raise ValueError(\n \"You must call `wandb.init` before calling save\")\n if policy not in (\"live\", \"end\"):\n raise ValueError(\n 'Only \"live\" and \"end\" policies are currently supported.')\n if isinstance(glob_str, bytes):\n glob_str = glob_str.decode('utf-8')\n if not isinstance(glob_str, string_types):\n raise ValueError(\"Must call wandb.save(glob_str) with glob_str a str\")\n\n if base_path is None:\n base_path = os.path.dirname(glob_str)\n wandb_glob_str = os.path.relpath(glob_str, base_path)\n if \"../\" in wandb_glob_str:\n raise ValueError(\n \"globs can't walk above base_path\")\n if (glob_str, base_path, policy) in _saved_files:\n return []\n if glob_str.startswith(\"gs://\") or glob_str.startswith(\"s3://\"):\n termlog(\n \"%s is a cloud storage url, can't save file to wandb.\" % glob_str)\n return []\n run.send_message(\n {\"save_policy\": {\"glob\": wandb_glob_str, \"policy\": policy}})\n files = []\n for path in glob.glob(glob_str):\n file_name = os.path.relpath(path, base_path)\n abs_path = os.path.abspath(path)\n wandb_path = os.path.join(run.dir, file_name)\n util.mkdir_exists_ok(os.path.dirname(wandb_path))\n # We overwrite existing symlinks because namespaces can change in Tensorboard\n if os.path.islink(wandb_path) and abs_path != os.readlink(wandb_path):\n os.remove(wandb_path)\n os.symlink(abs_path, wandb_path)\n elif not os.path.exists(wandb_path):\n os.symlink(abs_path, wandb_path)\n files.append(wandb_path)\n _saved_files.add((glob_str, base_path, policy))\n return files\n\n\ndef restore(name, run_path=None, replace=False, root=None):\n \"\"\" Downloads the specified file from cloud storage into the current run directory\n if it doesn exist.\n\n name: the name of the file\n run_path: optional path to a different run to pull files from\n replace: whether to download the file even if it already exists locally\n root: the directory to download the file to. Defaults to the current\n directory or the run directory if wandb.init was called.\n\n returns None if it can't find the file, otherwise a file object open for reading\n raises wandb.CommError if it can't find the run\n \"\"\"\n if run_path is None and run is None:\n raise ValueError(\n \"You must call `wandb.init` before calling restore or specify a run_path\")\n api = Api()\n api_run = api.run(run_path or run.path)\n root = root or run.dir if run else \".\"\n path = os.path.join(root, name)\n if os.path.exists(path) and replace == False:\n return open(path, \"r\")\n files = api_run.files([name])\n if len(files) == 0:\n return None\n return files[0].download(root=root, replace=True)\n\n\n_tunnel_process = None\n\n\ndef tunnel(host, port):\n \"\"\"Simple helper to open a tunnel. Returns a public HTTPS url or None\"\"\"\n global _tunnel_process\n if _tunnel_process:\n _tunnel_process.kill()\n _tunnel_process = None\n process = subprocess.Popen(\"ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=60 -R 80:{}:{} serveo.net\".format(\n host, port), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n while process.returncode is None:\n for line in process.stdout:\n match = re.match(r\".+(https.+)$\", line.decode(\"utf-8\").strip())\n if match:\n _tunnel_process = process\n return match.group(1)\n # set returncode if the process has exited\n process.poll()\n time.sleep(1)\n return None\n\n\ndef monitor(options={}):\n \"\"\"Starts syncing with W&B if you're in Jupyter. Displays your W&B charts live in a Jupyter notebook.\n It's currently a context manager for legacy reasons.\n \"\"\"\n try:\n from IPython.display import display\n except ImportError:\n def display(stuff): return None\n\n class Monitor():\n def __init__(self, options={}):\n if os.getenv(env.JUPYTER):\n display(jupyter.Run())\n else:\n self.rm = False\n termerror(\n \"wandb.monitor is only functional in Jupyter notebooks\")\n\n def __enter__(self):\n termlog(\n \"DEPRECATED: with wandb.monitor(): is deprecated, add %%wandb to the beginning of a cell to see live results.\")\n pass\n\n def __exit__(self, *args):\n pass\n\n return Monitor(options)\n\n\n_async_log_queue = queue.Queue()\n_async_log_thread_shutdown_event = threading.Event()\n_async_log_thread_complete_event = threading.Event()\n_async_log_thread = None\n\n\ndef _async_log_thread_target():\n \"\"\"Consumes async logs from our _async_log_queue and actually logs them\"\"\"\n global _async_log_thread\n shutdown_requested = False\n while not shutdown_requested:\n try:\n kwargs = _async_log_queue.get(block=True, timeout=1)\n log(**kwargs)\n except queue.Empty:\n shutdown_requested = _async_log_thread_shutdown_event.wait(1) and _async_log_queue.empty()\n _async_log_thread_complete_event.set()\n _async_log_thread = None\n\n\ndef _ensure_async_log_thread_started():\n \"\"\"Ensures our log consuming thread is started\"\"\"\n global _async_log_thread, _async_log_thread_shutdown_event, _async_log_thread_complete_event\n\n if _async_log_thread is None:\n _async_log_thread_shutdown_event = threading.Event()\n _async_log_thread_complete_event = threading.Event()\n _async_log_thread = threading.Thread(target=_async_log_thread_target)\n _async_log_thread.daemon = True\n _async_log_thread.start()\n\n\ndef shutdown_async_log_thread():\n \"\"\"Shuts down our async logging thread\"\"\"\n if _async_log_thread:\n _async_log_thread_shutdown_event.set()\n res = _async_log_thread_complete_event.wait(_shutdown_async_log_thread_wait_time) # TODO: possible race here\n if res is False:\n termwarn('async log queue not empty after %d seconds, some log statements will be dropped' % (\n _shutdown_async_log_thread_wait_time))\n # FIXME: it is worse than this, likely the program will crash because files will be closed\n # FIXME: py 2.7 will return None here so we dont know if we dropped data\n\n\ndef log(row=None, commit=True, step=None, sync=True, *args, **kwargs):\n \"\"\"Log a dict to the global run's history.\n\n wandb.log({'train-loss': 0.5, 'accuracy': 0.9})\n\n Args:\n row (dict, optional): A dict of serializable python objects i.e str: ints, floats, Tensors, dicts, or wandb.data_types\n commit (boolean, optional): Persist a set of metrics, if false just update the existing dict\n step (integer, optional): The global step in processing. This sets commit=True any time step increases\n sync (boolean, True): If set to False, process calls to log in a seperate thread\n \"\"\"\n\n if run is None:\n raise ValueError(\n \"You must call `wandb.init` in the same process before calling log\")\n\n run.log(row, commit, step, sync, *args, **kwargs)\n\n\ndef ensure_configured():\n global GLOBAL_LOG_FNAME, api\n # We re-initialize here for tests\n api = InternalApi()\n GLOBAL_LOG_FNAME = os.path.abspath(os.path.join(wandb_dir(), 'debug.log'))\n\n\ndef uninit(only_patches=False):\n \"\"\"Undo the effects of init(). Useful for testing.\n \"\"\"\n global run, config, summary, patched, _saved_files\n if not only_patches:\n run = None\n config = util.PreInitObject(\"wandb.config\")\n summary = util.PreInitObject(\"wandb.summary\")\n _saved_files = set()\n # UNDO patches\n for mod in patched[\"tensorboard\"]:\n module = import_module(mod[0])\n parts = mod[1].split(\".\")\n if len(parts) > 1:\n module = getattr(module, parts[0])\n mod[1] = parts[1]\n setattr(module, mod[1], getattr(module, \"orig_\"+mod[1]))\n patched[\"tensorboard\"] = []\n\n\ndef reset_env(exclude=[]):\n \"\"\"Remove environment variables, used in Jupyter notebooks\"\"\"\n if os.getenv(env.INITED):\n wandb_keys = [key for key in os.environ.keys() if key.startswith(\n 'WANDB_') and key not in exclude]\n for key in wandb_keys:\n del os.environ[key]\n return True\n else:\n return False\n\n\ndef try_to_set_up_global_logging():\n \"\"\"Try to set up global W&B debug log that gets re-written by every W&B process.\n\n It may fail (and return False) eg. if the current directory isn't user-writable\n \"\"\"\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(filename)s:%(funcName)s():%(lineno)s] %(message)s')\n\n if env.is_debug():\n handler = logging.StreamHandler()\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n\n root.addHandler(handler)\n\n try:\n handler = logging.FileHandler(GLOBAL_LOG_FNAME, mode='w')\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(formatter)\n\n root.addHandler(handler)\n except IOError as e: # eg. in case wandb directory isn't writable\n termerror('Failed to set up logging: {}'.format(e))\n return False\n\n return True\n\n\ndef _get_python_type():\n try:\n if 'terminal' in get_ipython().__module__:\n return 'ipython'\n else:\n return 'jupyter'\n except (NameError, AttributeError):\n return \"python\"\n\n\ndef sagemaker_auth(overrides={}, path=\".\"):\n \"\"\" Write a secrets.env file with the W&B ApiKey and any additional secrets passed.\n\n Args:\n overrides (dict, optional): Additional environment variables to write to secrets.env\n path (str, optional): The path to write the secrets file.\n \"\"\"\n\n api_key = overrides.get(env.API_KEY, Api().api_key)\n if api_key is None:\n raise ValueError(\n \"Can't find W&B ApiKey, set the WANDB_API_KEY env variable or run `wandb login`\")\n overrides[env.API_KEY] = api_key\n with open(os.path.join(path, \"secrets.env\"), \"w\") as file:\n for k, v in six.iteritems(overrides):\n file.write(\"{}={}\\n\".format(k, v))\n\n\ndef init(job_type=None, dir=None, config=None, project=None, entity=None, reinit=None, tags=None,\n group=None, allow_val_change=False, resume=False, force=False, tensorboard=False,\n sync_tensorboard=False, monitor_gym=False, name=None, notes=None, id=None, magic=None,\n anonymous=None):\n \"\"\"Initialize W&B\n\n If called from within Jupyter, initializes a new run and waits for a call to\n `wandb.log` to begin pushing metrics. Otherwise, spawns a new process\n to communicate with W&B.\n\n Args:\n job_type (str, optional): The type of job running, defaults to 'train'\n config (dict, argparse, or tf.FLAGS, optional): The hyper parameters to store with the run\n project (str, optional): The project to push metrics to\n entity (str, optional): The entity to push metrics to\n dir (str, optional): An absolute path to a directory where metadata will be stored\n group (str, optional): A unique string shared by all runs in a given group\n tags (list, optional): A list of tags to apply to the run\n id (str, optional): A globally unique (per project) identifier for the run\n name (str, optional): A display name which does not have to be unique\n notes (str, optional): A multiline string associated with the run\n reinit (bool, optional): Allow multiple calls to init in the same process\n resume (bool, str, optional): Automatically resume this run if run from the same machine,\n you can also pass a unique run_id\n sync_tensorboard (bool, optional): Synchronize wandb logs to tensorboard or tensorboardX\n force (bool, optional): Force authentication with wandb, defaults to False\n magic (bool, dict, or str, optional): magic configuration as bool, dict, json string,\n yaml filename\n anonymous (str, optional): Can be \"allow\", \"must\", or \"never\". Controls whether anonymous logging is allowed.\n Defaults to never.\n\n Returns:\n A wandb.run object for metric and config logging.\n \"\"\"\n init_args = locals()\n trigger.call('on_init', **init_args)\n global run\n global __stage_dir__\n global _global_watch_idx\n\n # We allow re-initialization when we're in Jupyter or explicity opt-in to it.\n in_jupyter = _get_python_type() != \"python\"\n if reinit or (in_jupyter and reinit != False):\n # Reset global state for pytorch watch and tensorboard\n _global_watch_idx = 0\n if len(patched[\"tensorboard\"]) > 0:\n util.get_module(\"wandb.tensorboard\").reset_state()\n reset_env(exclude=env.immutable_keys())\n if len(_global_run_stack) > 0:\n if len(_global_run_stack) > 1:\n termwarn(\"If you want to track multiple runs concurrently in wandb you should use multi-processing not threads\")\n join()\n run = None\n\n # TODO: deprecate tensorboard\n if tensorboard or sync_tensorboard and len(patched[\"tensorboard\"]) == 0:\n util.get_module(\"wandb.tensorboard\").patch()\n if monitor_gym and len(patched[\"gym\"]) == 0:\n util.get_module(\"wandb.gym\").monitor()\n\n sagemaker_config = util.parse_sm_config()\n tf_config = util.parse_tfjob_config()\n if group == None:\n group = os.getenv(env.RUN_GROUP)\n if job_type == None:\n job_type = os.getenv(env.JOB_TYPE)\n if sagemaker_config:\n # Set run_id and potentially grouping if we're in SageMaker\n run_id = os.getenv('TRAINING_JOB_NAME')\n if run_id:\n os.environ[env.RUN_ID] = '-'.join([\n run_id,\n os.getenv('CURRENT_HOST', socket.gethostname())])\n conf = json.load(\n open(\"/opt/ml/input/config/resourceconfig.json\"))\n if group == None and len(conf[\"hosts\"]) > 1:\n group = os.getenv('TRAINING_JOB_NAME')\n # Set secret variables\n if os.path.exists(\"secrets.env\"):\n for line in open(\"secrets.env\", \"r\"):\n key, val = line.strip().split('=', 1)\n os.environ[key] = val\n elif tf_config:\n cluster = tf_config.get('cluster')\n job_name = tf_config.get('task', {}).get('type')\n task_index = tf_config.get('task', {}).get('index')\n if job_name is not None and task_index is not None:\n # TODO: set run_id for resuming?\n run_id = cluster[job_name][task_index].rsplit(\":\")[0]\n if job_type == None:\n job_type = job_name\n if group == None and len(cluster.get(\"worker\", [])) > 0:\n group = cluster[job_name][0].rsplit(\"-\"+job_name, 1)[0]\n image = util.image_id_from_k8s()\n if image:\n os.environ[env.DOCKER] = image\n if project:\n os.environ[env.PROJECT] = project\n if entity:\n os.environ[env.ENTITY] = entity\n if group:\n os.environ[env.RUN_GROUP] = group\n if job_type:\n os.environ[env.JOB_TYPE] = job_type\n if tags:\n if isinstance(tags, str):\n # People sometimes pass a string instead of an array of strings...\n tags = [tags]\n os.environ[env.TAGS] = \",\".join(tags)\n if id:\n os.environ[env.RUN_ID] = id\n if name is None and resume is not \"must\":\n # We do this because of https://github.com/wandb/core/issues/2170\n # to ensure that the run's name is explicitly set to match its\n # id. If we don't do this and the id is eight characters long, the\n # backend will set the name to a generated human-friendly value.\n #\n # In any case, if the user is explicitly setting `id` but not\n # `name`, their id is probably a meaningful string that we can\n # use to label the run.\n #\n # In the resume=\"must\" case, we know we are resuming, so we should\n # make sure to not set the name because it would have been set with\n # the original run.\n #\n # TODO: handle \"auto\" resume by moving this logic later when we know\n # if there is a resume.\n name = os.environ.get(env.NAME, id) # environment variable takes precedence over this.\n if name:\n os.environ[env.NAME] = name\n if notes:\n os.environ[env.NOTES] = notes\n if magic is not None and magic is not False:\n if isinstance(magic, dict):\n os.environ[env.MAGIC] = json.dumps(magic)\n elif isinstance(magic, str):\n os.environ[env.MAGIC] = magic\n elif isinstance(magic, bool):\n pass\n else:\n termwarn(\"wandb.init called with invalid magic parameter type\", repeat=False)\n from wandb import magic_impl\n magic_impl.magic_install(init_args=init_args)\n if dir:\n os.environ[env.DIR] = dir\n util.mkdir_exists_ok(wandb_dir())\n if anonymous is not None:\n os.environ[env.ANONYMOUS] = anonymous\n if os.environ.get(env.ANONYMOUS, \"never\") not in [\"allow\", \"must\", \"never\"]:\n raise LaunchError(\"anonymous must be set to 'allow', 'must', or 'never'\")\n\n resume_path = os.path.join(wandb_dir(), wandb_run.RESUME_FNAME)\n if resume == True:\n os.environ[env.RESUME] = \"auto\"\n elif resume in (\"allow\", \"must\", \"never\"):\n os.environ[env.RESUME] = resume\n if id:\n os.environ[env.RUN_ID] = id\n elif resume:\n os.environ[env.RESUME] = os.environ.get(env.RESUME, \"allow\")\n # TODO: remove allowing resume as a string in the future\n os.environ[env.RUN_ID] = id or resume\n elif os.path.exists(resume_path):\n os.remove(resume_path)\n if os.environ.get(env.RESUME) == 'auto' and os.path.exists(resume_path):\n if not os.environ.get(env.RUN_ID):\n os.environ[env.RUN_ID] = json.load(open(resume_path))[\"run_id\"]\n\n # the following line is useful to ensure that no W&B logging happens in the user\n # process that might interfere with what they do\n # logging.basicConfig(format='user process %(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n # If a thread calls wandb.init() it will get the same Run object as\n # the parent. If a child process with distinct memory space calls\n # wandb.init(), it won't get an error, but it will get a result of\n # None.\n # This check ensures that a child process can safely call wandb.init()\n # after a parent has (only the parent will create the Run object).\n # This doesn't protect against the case where the parent doesn't call\n # wandb.init but two children do.\n if run or os.getenv(env.INITED):\n return run\n\n if __stage_dir__ is None:\n __stage_dir__ = \"wandb\"\n util.mkdir_exists_ok(wandb_dir())\n\n try:\n signal.signal(signal.SIGQUIT, _debugger)\n except AttributeError:\n pass\n\n try:\n run = wandb_run.Run.from_environment_or_defaults()\n _global_run_stack.append(run)\n except IOError as e:\n termerror('Failed to create run directory: {}'.format(e))\n raise LaunchError(\"Could not write to filesystem.\")\n\n run.set_environment()\n\n def set_global_config(run):\n global config # because we already have a local config\n config = run.config\n set_global_config(run)\n global summary\n summary = run.summary\n\n # set this immediately after setting the run and the config. if there is an\n # exception after this it'll probably break the user script anyway\n os.environ[env.INITED] = '1'\n\n if in_jupyter:\n _init_jupyter(run)\n elif run.mode == 'clirun':\n pass\n elif run.mode == 'run':\n api = InternalApi()\n # let init_jupyter handle this itself\n if not in_jupyter and not api.api_key:\n termlog(\n \"W&B is a tool that helps track and visualize machine learning experiments\")\n if force:\n termerror(\n \"No credentials found. Run \\\"wandb login\\\" or \\\"wandb off\\\" to disable wandb\")\n else:\n if util.prompt_api_key(api):\n _init_headless(run)\n else:\n termlog(\n \"No credentials found. Run \\\"wandb login\\\" to visualize your metrics\")\n run.mode = \"dryrun\"\n _init_headless(run, False)\n else:\n _init_headless(run)\n elif run.mode == 'dryrun':\n termlog(\n 'Dry run mode, not syncing to the cloud.')\n _init_headless(run, False)\n else:\n termerror(\n 'Invalid run mode \"%s\". Please unset WANDB_MODE.' % run.mode)\n raise LaunchError(\"The WANDB_MODE environment variable is invalid.\")\n\n # set the run directory in the config so it actually gets persisted\n run.config.set_run_dir(run.dir)\n # we have re-read the config, add telemetry data\n telemetry_updated = run.config._telemetry_update()\n\n if sagemaker_config:\n run.config._update(sagemaker_config)\n allow_val_change = True\n if config or telemetry_updated:\n run.config._update(config, allow_val_change=allow_val_change, as_defaults=not allow_val_change)\n\n # Access history to ensure resumed is set when resuming\n run.history\n # Load the summary to support resuming\n run.summary.load()\n\n return run\n\n\ntensorflow = util.LazyLoader('tensorflow', globals(), 'wandb.tensorflow')\ntensorboard = util.LazyLoader('tensorboard', globals(), 'wandb.tensorboard')\njupyter = util.LazyLoader('jupyter', globals(), 'wandb.jupyter')\nkeras = util.LazyLoader('keras', globals(), 'wandb.keras')\nfastai = util.LazyLoader('fastai', globals(), 'wandb.fastai')\ndocker = util.LazyLoader('docker', globals(), 'wandb.docker')\nxgboost = util.LazyLoader('xgboost', globals(), 'wandb.xgboost')\nlightgbm = util.LazyLoader('lightgbm', globals(), 'wandb.lightgbm')\ngym = util.LazyLoader('gym', globals(), 'wandb.gym')\nray = util.LazyLoader('ray', globals(), 'wandb.ray')\n\n\n__all__ = ['init', 'config', 'summary', 'join', 'login', 'log', 'save', 'restore',\n 'tensorflow', 'watch', 'types', 'tensorboard', 'jupyter', 'keras', 'fastai',\n 'docker', 'xgboost', 'gym', 'ray', 'run', 'join', 'Image', 'Video',\n 'Audio', 'Table', 'Html', 'Object3D', 'Histogram', 'Graph', 'Api']\n","sub_path":"wandb/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":42379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"436608189","text":"\"\"\"\n Module to convert SWW to DEM files.\n\"\"\"\n\n\n# external modules\n\nimport os\nimport numpy as num\n\n# ANUGA modules\nfrom anuga.abstract_2d_finite_volumes.util import remove_lone_verts \nfrom anuga.coordinate_transforms.geo_reference import Geo_reference\nfrom anuga.utilities.system_tools import get_vars_in_expression\nimport anuga.utilities.log as log\nfrom anuga.utilities.file_utils import get_all_swwfiles\n\n\n######\n# formula mappings\n######\n\nquantity_formula = {'momentum':'(xmomentum**2 + ymomentum**2)**0.5',\n 'depth':'stage-elevation',\n 'speed': \\\n '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'}\n\n\n\n# Default block size for sww2dem()\nDEFAULT_BLOCK_SIZE = 10000\n\ndef sww2dem(name_in, name_out,\n quantity=None, # defaults to elevation\n reduction=None,\n cellsize=10,\n number_of_decimal_places=None,\n NODATA_value=-9999.0,\n easting_min=None,\n easting_max=None,\n northing_min=None,\n northing_max=None,\n verbose=False,\n origin=None,\n datum='WGS84',\n block_size=None):\n \"\"\"Read SWW file and convert to Digitial Elevation model format\n (.asc or .ers)\n\n Example (ASC):\n ncols 3121\n nrows 1800\n xllcorner 722000\n yllcorner 5893000\n cellsize 25\n NODATA_value -9999\n 138.3698 137.4194 136.5062 135.5558 ..........\n\n The number of decimal places can be specified by the user to save\n on disk space requirements by specifying in the call to sww2dem.\n\n Also write accompanying file with same basename_in but extension .prj\n used to fix the UTM zone, datum, false northings and eastings.\n\n The prj format is assumed to be as\n\n Projection UTM\n Zone 56\n Datum WGS84\n Zunits NO\n Units METERS\n Spheroid WGS84\n Xshift 0.0000000000\n Yshift 10000000.0000000000\n Parameters\n\n The parameter quantity must be the name of an existing quantity or\n an expression involving existing quantities. The default is\n 'elevation'. Quantity is not a list of quantities.\n\n If reduction is given and it's an index, sww2dem will output the quantity at that time-step. \n If reduction is given and it's a built in function (eg max, min, mean), then that \n function is used to reduce the quantity over all time-steps. If reduction is not given, \n reduction is set to \"max\" by default.\n\n datum\n\n format can be either 'asc' or 'ers'\n block_size - sets the number of slices along the non-time axis to\n process in one block.\n \"\"\"\n\n import sys\n import types\n\n from anuga.geometry.polygon import inside_polygon, outside_polygon\n from anuga.abstract_2d_finite_volumes.util import \\\n apply_expression_to_dictionary\n\n basename_in, in_ext = os.path.splitext(name_in)\n basename_out, out_ext = os.path.splitext(name_out)\n out_ext = out_ext.lower()\n\n if in_ext != '.sww':\n raise IOError('Input format for %s must be .sww' % name_in)\n\n if out_ext not in ['.asc', '.ers']:\n raise IOError('Format for %s must be either asc or ers.' % name_out)\n\n false_easting = 500000\n false_northing = 10000000\n\n if quantity is None:\n quantity = 'elevation'\n \n if reduction is None:\n reduction = max\n\n if quantity in quantity_formula:\n quantity = quantity_formula[quantity]\n\n if number_of_decimal_places is None:\n number_of_decimal_places = 3\n\n if block_size is None:\n block_size = DEFAULT_BLOCK_SIZE\n\n assert(isinstance(block_size, (int, int, float)))\n\n # Read sww file\n if verbose:\n log.critical('Reading from %s' % name_in)\n log.critical('Output directory is %s' % name_out)\n\n from anuga.file.netcdf import NetCDFFile\n fid = NetCDFFile(name_in)\n\n #Get extent and reference\n x = num.array(fid.variables['x'], float)\n y = num.array(fid.variables['y'], float)\n volumes = num.array(fid.variables['volumes'], int)\n if type(reduction) is not types.BuiltinFunctionType:\n times = fid.variables['time'][reduction]\n else:\n times = fid.variables['time'][:]\n\n number_of_timesteps = fid.dimensions['number_of_timesteps']\n number_of_points = fid.dimensions['number_of_points']\n\n if origin is None:\n # Get geo_reference\n # sww files don't have to have a geo_ref\n try:\n geo_reference = Geo_reference(NetCDFObject=fid)\n except AttributeError as e:\n geo_reference = Geo_reference() # Default georef object\n\n xllcorner = geo_reference.get_xllcorner()\n yllcorner = geo_reference.get_yllcorner()\n zone = geo_reference.get_zone()\n else:\n zone = origin[0]\n xllcorner = origin[1]\n yllcorner = origin[2]\n\n # FIXME: Refactor using code from Interpolation_function.statistics\n # (in interpolate.py)\n # Something like print swwstats(swwname)\n if verbose:\n log.critical('------------------------------------------------')\n log.critical('Statistics of SWW file:')\n log.critical(' Name: %s' % name_in)\n log.critical(' Reference:')\n log.critical(' Lower left corner: [%f, %f]' % (xllcorner, yllcorner))\n if type(reduction) is not types.BuiltinFunctionType:\n log.critical(' Time: %f' % times)\n else:\n log.critical(' Start time: %f' % fid.starttime[0])\n log.critical(' Extent:')\n log.critical(' x [m] in [%f, %f], len(x) == %d'\n %(num.min(x), num.max(x), len(x.flat)))\n log.critical(' y [m] in [%f, %f], len(y) == %d'\n % (num.min(y), num.max(y), len(y.flat)))\n if type(reduction) is not types.BuiltinFunctionType:\n log.critical(' t [s] = %f, len(t) == %d' % (times, 1))\n else:\n log.critical(' t [s] in [%f, %f], len(t) == %d'\n % (min(times), max(times), len(times)))\n log.critical(' Quantities [SI units]:')\n \n # Comment out for reduced memory consumption\n for name in ['stage', 'xmomentum', 'ymomentum']:\n q = fid.variables[name][:].flatten()\n if type(reduction) is not types.BuiltinFunctionType:\n q = q[reduction*len(x):(reduction+1)*len(x)]\n if verbose: log.critical(' %s in [%f, %f]'\n % (name, min(q), max(q)))\n for name in ['elevation']:\n q = fid.variables[name][:].flatten()\n if verbose: log.critical(' %s in [%f, %f]'\n % (name, min(q), max(q)))\n\n # Get the variables in the supplied expression.\n # This may throw a SyntaxError exception.\n var_list = get_vars_in_expression(quantity)\n\n # Check that we have the required variables in the SWW file.\n missing_vars = []\n for name in var_list:\n try:\n _ = fid.variables[name]\n except KeyError:\n missing_vars.append(name)\n if missing_vars:\n msg = (\"In expression '%s', variables %s are not in the SWW file '%s'\"\n % (quantity, str(missing_vars), name_in))\n raise(Exception, msg)\n\n # Create result array and start filling, block by block.\n result = num.zeros(number_of_points, float)\n\n if verbose:\n msg = 'Slicing sww file, num points: ' + str(number_of_points)\n msg += ', block size: ' + str(block_size)\n log.critical(msg)\n\n for start_slice in range(0, number_of_points, block_size):\n # Limit slice size to array end if at last block\n end_slice = min(start_slice + block_size, number_of_points)\n \n # Get slices of all required variables\n q_dict = {}\n for name in var_list:\n # check if variable has time axis\n if len(fid.variables[name].shape) == 2:\n q_dict[name] = fid.variables[name][:,start_slice:end_slice]\n else: # no time axis\n q_dict[name] = fid.variables[name][start_slice:end_slice]\n\n # Evaluate expression with quantities found in SWW file\n res = apply_expression_to_dictionary(quantity, q_dict)\n\n if len(res.shape) == 2:\n new_res = num.zeros(res.shape[1], float)\n for k in range(res.shape[1]):\n if type(reduction) is not types.BuiltinFunctionType:\n new_res[k] = res[reduction,k]\n else:\n new_res[k] = reduction(res[:,k])\n res = new_res\n\n result[start_slice:end_slice] = res\n \n # Post condition: Now q has dimension: number_of_points\n assert len(result.shape) == 1\n assert result.shape[0] == number_of_points\n\n if verbose:\n log.critical('Processed values for %s are in [%f, %f]'\n % (quantity, min(result), max(result)))\n\n # Create grid and update xll/yll corner and x,y\n # Relative extent\n if easting_min is None:\n xmin = min(x)\n else:\n xmin = easting_min - xllcorner\n\n if easting_max is None:\n xmax = max(x)\n else:\n xmax = easting_max - xllcorner\n\n if northing_min is None:\n ymin = min(y)\n else:\n ymin = northing_min - yllcorner\n\n if northing_max is None:\n ymax = max(y)\n else:\n ymax = northing_max - yllcorner\n\n msg = 'xmax must be greater than or equal to xmin.\\n'\n msg += 'I got xmin = %f, xmax = %f' %(xmin, xmax)\n assert xmax >= xmin, msg\n\n msg = 'ymax must be greater than or equal to xmin.\\n'\n msg += 'I got ymin = %f, ymax = %f' %(ymin, ymax)\n assert ymax >= ymin, msg\n\n if verbose: log.critical('Creating grid')\n ncols = int((xmax-xmin)/cellsize) + 1\n nrows = int((ymax-ymin)/cellsize) + 1\n\n # New absolute reference and coordinates\n newxllcorner = xmin + xllcorner\n newyllcorner = ymin + yllcorner\n\n x = x + xllcorner - newxllcorner\n y = y + yllcorner - newyllcorner\n\n vertex_points = num.concatenate ((x[:,num.newaxis], y[:,num.newaxis]), axis=1)\n assert len(vertex_points.shape) == 2\n\n\n def calc_grid_values_old(vertex_points, volumes, result):\n\n grid_points = num.zeros ((ncols*nrows, 2), float)\n\n for i in range(nrows):\n if out_ext == '.asc':\n yg = i * cellsize\n else:\n # this will flip the order of the y values for ers\n yg = (nrows-i) * cellsize\n\n for j in range(ncols):\n xg = j * cellsize\n k = i*ncols + j\n\n grid_points[k, 0] = xg\n grid_points[k, 1] = yg\n\n # Interpolate\n from anuga.fit_interpolate.interpolate import Interpolate\n\n # Remove loners from vertex_points, volumes here\n vertex_points, volumes = remove_lone_verts(vertex_points, volumes)\n # export_mesh_file('monkey.tsh',{'vertices':vertex_points, 'triangles':volumes})\n\n\n interp = Interpolate(vertex_points, volumes, verbose = verbose)\n\n bprint = 0\n\n # Interpolate using quantity values\n if verbose: log.critical('Interpolating')\n grid_values = interp.interpolate(bprint, result, grid_points).flatten()\n outside_indices = interp.get_outside_poly_indices()\n\n for i in outside_indices:\n #print 'change grid_value',NODATA_value\n grid_values[i] = NODATA_value\n\t\n return grid_values\n\n def calc_grid_values(vertex_points, volumes, result):\n\n grid_points = num.zeros ((ncols*nrows, 2), float)\n\n for i in range(nrows):\n if out_ext == '.asc':\n yg = i * cellsize\n else:\n #this will flip the order of the y values for ers\n yg = (nrows-i) * cellsize\n \n for j in range(ncols):\n xg = j * cellsize\n k = i*ncols + j\n\n grid_points[k, 0] = xg\n grid_points[k, 1] = yg\n \n grid_values = num.zeros(ncols*nrows, float)\n\n eval_grid(nrows, ncols, NODATA_value, grid_points, vertex_points.flatten(), volumes, result, grid_values);\n return grid_values.flatten()\n\n grid_values = calc_grid_values(vertex_points, volumes, result)\n\n if verbose:\n log.critical('Interpolated values are in [%f, %f]'\n % (num.min(grid_values), num.max(grid_values)))\n\n # Assign NODATA_value to all points outside bounding polygon (from interpolation mesh)\n \n# P = interp.mesh.get_boundary_polygon()\n# outside_indices = outside_polygon(grid_points, P, closed=True)\n\n if out_ext == '.ers':\n # setup ERS header information\n grid_values = num.reshape(grid_values, (nrows, ncols))\n header = {}\n header['datum'] = '\"' + datum + '\"'\n # FIXME The use of hardwired UTM and zone number needs to be made optional\n # FIXME Also need an automatic test for coordinate type (i.e. EN or LL)\n header['projection'] = '\"UTM-' + str(zone) + '\"'\n header['coordinatetype'] = 'EN'\n if header['coordinatetype'] == 'LL':\n header['longitude'] = str(newxllcorner)\n header['latitude'] = str(newyllcorner)\n elif header['coordinatetype'] == 'EN':\n header['eastings'] = str(newxllcorner)\n header['northings'] = str(newyllcorner)\n header['nullcellvalue'] = str(NODATA_value)\n header['xdimension'] = str(cellsize)\n header['ydimension'] = str(cellsize)\n header['value'] = '\"' + quantity + '\"'\n #header['celltype'] = 'IEEE8ByteReal' #FIXME: Breaks unit test\n\n #Write\n if verbose:\n log.critical('Writing %s' % name_out)\n\n import ermapper_grids\n\n ermapper_grids.write_ermapper_grid(name_out, grid_values, header)\n\n fid.close()\n \n else:\n #Write to Ascii format\n #Write prj file\n prjfile = basename_out + '.prj'\n\n if verbose: log.critical('Writing %s' % prjfile)\n prjid = open(prjfile, 'w')\n prjid.write('Projection %s\\n' %'UTM')\n prjid.write('Zone %d\\n' %zone)\n prjid.write('Datum %s\\n' %datum)\n prjid.write('Zunits NO\\n')\n prjid.write('Units METERS\\n')\n prjid.write('Spheroid %s\\n' %datum)\n prjid.write('Xshift %d\\n' %false_easting)\n prjid.write('Yshift %d\\n' %false_northing)\n prjid.write('Parameters\\n')\n prjid.close()\n\n if verbose: log.critical('Writing %s' % name_out)\n\n ascid = open(name_out, 'w')\n\n ascid.write('ncols %d\\n' %ncols)\n ascid.write('nrows %d\\n' %nrows)\n ascid.write('xllcorner %d\\n' %newxllcorner)\n ascid.write('yllcorner %d\\n' %newyllcorner)\n ascid.write('cellsize %f\\n' %cellsize)\n ascid.write('NODATA_value %d\\n' %NODATA_value)\n\n #Get bounding polygon from mesh\n #P = interp.mesh.get_boundary_polygon()\n #inside_indices = inside_polygon(grid_points, P)\n\n # change printoptions so that a long string of zeros in not\n # summarized as [0.0, 0.0, 0.0, ... 0.0, 0.0, 0.0]\n #printoptions = num.get_printoptions()\n #num.set_printoptions(threshold=sys.maxint)\n\n format = '%.'+'%g' % number_of_decimal_places +'e'\n for i in range(nrows):\n if verbose and i % ((nrows+10)//10) == 0:\n log.critical('Doing row %d of %d' % (i, nrows))\n\n base_index = (nrows-i-1)*ncols\n\n slice = grid_values[base_index:base_index+ncols]\n\n num.savetxt(ascid, slice.reshape(1,ncols), format, ' ' )\n \n \n #Close\n ascid.close()\n fid.close()\n \n return basename_out\n\n\n\ndef sww2dem_batch(basename_in, extra_name_out=None,\n quantities=None, # defaults to elevation\n reduction=None,\n cellsize=10,\n number_of_decimal_places=None,\n NODATA_value=-9999,\n easting_min=None,\n easting_max=None,\n northing_min=None,\n northing_max=None,\n verbose=False,\n origin=None,\n datum='WGS84',\n format='ers'):\n \"\"\"Wrapper for sww2dem.\n See sww2dem to find out what most of the parameters do. Note that since this\n is a batch command, the normal filename naming conventions do not apply.\n\n basename_in is a path to sww file/s, without the .sww extension.\n extra_name_out is a postfix to add to the output filename.\n\n Quantities is a list of quantities. Each quantity will be\n calculated for each sww file.\n\n This returns the basenames of the files returned, which is made up\n of the dir and all of the file name, except the extension.\n\n This function returns the names of the files produced.\n\n It will also produce as many output files as there are input sww files.\n \"\"\"\n\n if quantities is None:\n quantities = ['elevation']\n\n if type(quantities) is str:\n quantities = [quantities]\n\n # How many sww files are there?\n dir, base = os.path.split(basename_in)\n\n iterate_over = get_all_swwfiles(dir, base, verbose)\n\n if dir == \"\":\n dir = \".\" # Unix compatibility\n\n files_out = []\n for sww_file in iterate_over:\n for quantity in quantities:\n if extra_name_out is None:\n basename_out = sww_file + '_' + quantity\n else:\n basename_out = sww_file + '_' + quantity + '_' + extra_name_out\n\n swwin = dir+os.sep+sww_file+'.sww'\n demout = dir+os.sep+basename_out+'.'+format\n\n if verbose:\n log.critical('sww2dem: %s => %s' % (swwin, demout))\n\n file_out = sww2dem(swwin,\n demout,\n quantity,\n reduction,\n cellsize,\n number_of_decimal_places,\n NODATA_value,\n easting_min,\n easting_max,\n northing_min,\n northing_max,\n verbose,\n origin,\n datum)\n \n files_out.append(file_out)\n return files_out\n\n","sub_path":"anuga/file_conversion/sww2dem_new.py","file_name":"sww2dem_new.py","file_ext":"py","file_size_in_byte":18599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"79549634","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 29 12:11:56 2017\n\n@author: prierm\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\n# some initial data\npathName='E://Research//Scripts//Potential Flow//Panel Method//Git_Panel_Methods//frames'\nUinf=3\nrho=1.204\nchord=.12\nthickness=.006\nminRad=thickness/2\nmajRad=chord/4\nnumPanels=64\nxp=np.zeros((numPanels+1,1))\nyp=np.zeros((numPanels+1,1))\n\n# panel coordinates in terms of global x and y\nxStep=chord/(numPanels/2)\nxp[0]=chord/2\nyp[0]=0\ni=1\nwhile i good | bad\n\nglexec:\nverifyproxy -> gridmapfile\ngridmapfile -> glexectracking\n'''\n files.write(core.config['lcmaps.db'], template, owner='glexec')\n core.state['glexec.lcmaps_written'] = True\n\n def test_02_define_user_proxy_path(self):\n core.skip_ok_unless_installed('glexec')\n command = ('/usr/bin/id', '-u')\n _, stdout, _ = core.system(command, True)\n TestGlexec.__uid = stdout.rstrip()\n TestGlexec.__user_proxy_path = '/tmp/x509up_u'+self.__uid\n\n def test_03_create_user_proxy(self):\n core.skip_ok_unless_installed('globus-proxy-utils')\n self.skip_ok_if(self.__user_proxy_path == '', \"User proxy path does not exist.\")\n\n # OK, software is present, now just check it previous tests did create the proxy already so\n # we don't do it twice\n command = ('grid-proxy-info', '-f', self.__user_proxy_path)\n status, _, _ = core.system(command, True)\n\n if int(status) != 0: # no proxy found for some reason, try to construct a new one\n command = ('grid-proxy-init', '-out', self.__user_proxy_path)\n password = core.options.password + '\\n'\n status, _, _ = core.system(command, True, password)\n self.assert_(status == 0, 'grid-proxy-init for user ' +core.options.username +\n ' has failed even though globus-proxy-util was present')\n\n # we need to have the right permissions on that proxy for glexec to agree to work,\n # and the easiest way is to copy the file\n command = ('/bin/cp', self.__user_proxy_path, self.__glexec_client_cert)\n status, _, _ = core.system(command)\n os.environ['GLEXEC_CLIENT_CERT'] = self.__glexec_client_cert\n\n def test_04_glexec_switch_id(self):\n core.skip_ok_unless_installed('glexec', 'globus-proxy-utils')\n command = ('grid-proxy-info', '-f', self.__user_proxy_path)\n status, stdout, _ = core.system(command, True)\n\n if int(status) != 0: # no proxy found even after previous checks, have to skip\n self.skip_bad('suitable proxy not found')\n return\n\n command = ('/usr/sbin/glexec', '/usr/bin/id', '-u')\n\n status, stdout, _ = core.system(command)\n switched_id = stdout.rstrip()\n\n self.assert_(self.__uid == switched_id,\n 'Glexec identity switch from root to user ' + core.options.username + ' failed')\n\n def test_05_glexec_proxy_cleanup(self):\n core.skip_ok_unless_installed('glexec', 'globus-proxy-utils')\n\n try:\n os.unlink(self.__glexec_client_cert)\n except:\n pass\n\n\n def test_06_restore_lcmaps(self):\n core.skip_ok_unless_installed('glexec', 'lcmaps-plugins-basic')\n self.skip_ok_unless(core.state['glexec.lcmaps_written'], 'did not write lcmaps.db for glexec tests')\n files.restore(core.config['lcmaps.db'], 'glexec')\n","sub_path":"osgtest/tests/test_44_glexec.py","file_name":"test_44_glexec.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"358035499","text":"\"\"\"BW APi.\n\nAPI to work as backend for BW\n\"\"\"\n\nfrom flask import Flask, request\nfrom flask.ext.pymongo import PyMongo\nimport hashlib\nfrom slugify import slugify\nfrom bson.json_util import dumps\nfrom bson.objectid import ObjectId\n\n\napp = Flask(__name__)\n\n# connect to another MongoDB server altogether\napp.config['MONGO_HOST'] = 'mongodb'\napp.config['MONGO_PORT'] = 27017\napp.config['MONGO_DBNAME'] = 'doctest2'\n\nmongo = PyMongo(app, config_prefix='MONGO')\n\n\n@app.route('/api/')\ndef hello_bw():\n \"\"\"Hello function.\"\"\"\n return 'Hello BW!'\n\n\n@app.route('/api/entries', methods=['POST'])\ndef save_entry():\n \"\"\"Save entry.\"\"\"\n app.logger.debug(request.get_json())\n content = request.get_json()\n if 'body' in content:\n m = hashlib.md5()\n m.update(content.get('body').encode(\"utf-8\"))\n\n slug = content.get('title', 'new-').encode(\"utf-8\")\n prefix = slugify(str.lower(slug)) + '-'\n\n filename = \"/data/\" + prefix + m.hexdigest()\n\n # TODO: to create versions, use the parent & key\n\n if content.get('oid'):\n app.logger.debug(\"Update \" + content.get('oid'))\n new_object = {\n 'body': content.get('body').encode(\"utf-8\"),\n 'key': m.hexdigest(),\n 'title': content.get('title', '').encode(\"utf-8\"),\n 'path': filename,\n 'parent': content.get('oid'),\n '_id': ObjectId(content.get('oid'))\n }\n mongo.db.entries.update(\n {'_id': ObjectId(content.get('oid'))}, new_object\n )\n else:\n app.logger.debug(\"Insert\")\n new_object = {\n 'body': content.get('body').encode(\"utf-8\"),\n 'key': m.hexdigest(),\n 'title': content.get('title', '').encode(\"utf-8\"),\n 'parent': '',\n 'path': filename\n }\n insert = mongo.db.entries.insert(new_object)\n new_object = mongo.db.entries.find_one_or_404(\n {'_id': ObjectId(insert)}\n )\n app.logger.debug(new_object)\n with open(filename, 'wb') as f:\n f.write(content.get('body').encode(\"utf-8\"))\n\n return dumps(new_object)\n\n\n@app.route('/api/entries/')\ndef get_entry(entry):\n \"\"\"Get entry.\"\"\"\n entry = mongo.db.entries.find_one_or_404({'_id': ObjectId(entry)})\n return dumps(entry)\n\n\n@app.route('/api/entries', methods=['GET'])\ndef get_entries():\n \"\"\"Get entries.\"\"\"\n entries = mongo.db.entries.find()\n return dumps(entries)\n\n\n@app.route('/api/versions/', methods=['GET'])\ndef get_versions(entry):\n \"\"\"Get entries.\"\"\"\n entries = mongo.db.entries.find({'parent': ObjectId(entry)})\n return dumps(entries)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)\n","sub_path":"components/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"58825885","text":"print (\"Hello user!\")\nprint(\"This programme will help to encrypt any inputted text\")\n\nSTART_ASCII_CODE_TEXT_RANGE=32\nSTOP_ASCII_CODE_TEXT_RANGE=127\n\n# def text_encryption(inputted_text):\n# encryption_table = []\n# for i in range(START_ASCII_CODE_TEXT_RANGE, STOP_ASCII_CODE_TEXT_RANGE):\n# encryption_table.append(chr(i))\n# encrypted_text = []\n# for i in inputted_text:\n# symbol_index = (encryption_table.index(i) + 5) % len(encryption_table)\n# encrypted_text.append(encryption_table[symbol_index])\n# return encrypted_text\n#\n# inputted_string = input(\"Please input any text for encryption: \")\n# inputted_string = list(inputted_string)\n# print(\"Encrypted string will be ->\",\"\".join(text_encryption(inputted_string)))\n#\n# def text_decoding(inputted_text):\n# encryption_table = []\n# for i in range(START_ASCII_CODE_TEXT_RANGE, STOP_ASCII_CODE_TEXT_RANGE):\n# encryption_table.append(chr(i))\n# decoding_text = []\n# for i in inputted_text:\n# symbol_index = (encryption_table.index(i) -5) % len(encryption_table)\n# decoding_text.append(encryption_table[symbol_index])\n# return decoding_text\n#\n# inputted_string2 = input(\"Please input any text for decoding: \")\n# inputted_string2 = list(inputted_string2)\n# print(\"The string that was encrypted looks like this ->\",\"\".join(text_decoding(inputted_string2)))\n\ndecrypt = (lambda symbol, table: table[(table.index(symbol) - 5) % len(table)])\nencrypt = (lambda symbol, table: table[(table.index(symbol) + 5) % len(table)])\n\ndef text_transform(inputted_text, transform_func):\n transform_table = [chr(i) for i in range(START_ASCII_CODE_TEXT_RANGE, STOP_ASCII_CODE_TEXT_RANGE)]\n transformed_text = [transform_func(i, transform_table) for i in inputted_text]\n return transformed_text\n\n\ninput_string = input(\"Please input any text for encryption: \")\ninput_string = list(input_string)\n\nencrypted = text_transform(input_string, encrypt)\ndecrypted = text_transform(encrypted, decrypt)\nassert input_string == decrypted, \"(De)encryption test failed\"\n\nprint(\"Encrypted string will be ->\",\"\".join(encrypted))\nprint(\"The string that was encrypted looks like this ->\",\"\".join(decrypted))","sub_path":"task_30.py","file_name":"task_30.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"527446127","text":"import sys; sys.path.append('../')\nimport src as _\nimport unittest\n\nclass TestListsMethodWithout(unittest.TestCase):\n def test_without(self):\n self.assertEqual(\n _.without([1, 2, 3], 2, 3),\n [1]\n )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/lists/test_xor.py","file_name":"test_xor.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"401148006","text":"\"\"\"\n1707. Maximum XOR With an Element From Array\n\nYou are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].\n\nThe answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.\n\nReturn an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.\n\n\n\nExample 1:\n\nInput: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\nOutput: [3,3,7]\nExplanation:\n1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.\nExample 2:\n\nInput: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\nOutput: [15,-1,5]\n\n\nConstraints:\n\n1 <= nums.length, queries.length <= 105\nqueries[i].length == 2\n0 <= nums[j], xi, mi <= 109\n\"\"\"\n\n\nclass MaximizeXor:\n\n def doit_trie(self, nums: list, queries: list) -> list:\n\n from collections import defaultdict\n\n trie = defaultdict(dict)\n\n nums.sort()\n ans = [-1] * len(queries)\n queries = sorted([[i, c[0], c[1]] for i, c in enumerate(queries)], key=lambda a: a[2])\n\n def insert(num):\n\n mask, p = 0, trie\n for i in reversed(range(32)):\n b = int(num >> i & 1)\n if b not in p:\n p[b] = {}\n p = p[b]\n p[-1] = num\n\n def build(num):\n\n p = trie\n\n for i in reversed(range(32)):\n b = int(num >> i & 1)\n\n if not p: return -1\n\n if 1-b in p:\n p = p[1 - b]\n else:\n p = p[b]\n\n return p[-1] ^ num\n\n i = 0\n for index, num, limit in queries:\n\n while i < len(nums) and nums[i] <= limit:\n insert(nums[i])\n i += 1\n\n ans[index] = build(num)\n\n return ans\n\n\nif __name__ == '__main__':\n\n MaximizeXor().doit_trie([0,1,2,3,4], [[3,1],[1,3],[5,6]])\n\n MaximizeXor().doit_trie([5,2,4,6,6,3], [[12,4],[8,1],[6,3]])","sub_path":"PythonLeetcode/Leetcode/1707_MaximumXORWithanElementFromArray.py","file_name":"1707_MaximumXORWithanElementFromArray.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"149844409","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# This is a code for training unigram model.\n# Usage:\n# ./train_unigram.py \n\n\nfrom collections import defaultdict\nimport sys\n\ncounts = defaultdict(lambda: 0)\ntotal_count = 0\n\nmy_training_file = open(sys.argv[1], \"r\")\n\nfor line in my_training_file:\n line = line.strip()\n words = line.split(\" \")\n # words.append(\"\")\n for word in words:\n counts[word] += 1\n total_count += 1\n\nmy_training_file.close()\n\nmy_model_file = open(sys.argv[2], \"w\")\n\nfor word, count in sorted(counts.items()):\n probability = float(counts[word]) / total_count\n output = \"%s %f\\n\" % (word, probability)\n my_model_file.write(output)\n\nmy_model_file.close()\n","sub_path":"train_unigram.py","file_name":"train_unigram.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"173958318","text":"N = int(input())\nA = [set(list(input())) for _ in range(N)]\n\nans = []\nfor i, a in enumerate(A):\n b = A[-(i + 1)]\n A[i] = a & b\n\nans = []\nfor a in A:\n if len(a) == 0:\n break\n ans.append(list(a)[0])\nelse:\n print(''.join(ans))\n exit()\n\nprint(-1)\n","sub_path":"AtCoder/other/PAST_2/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"476828678","text":"from utils.globals import X_train, X_test, y_test, y_train\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\n\n\ndef randomized_search(params, runs=20, clf=DecisionTreeClassifier(random_state=2)):\n rand_clf = RandomizedSearchCV(\n clf, params, n_iter=runs, cv=5, n_jobs=1, random_state=2)\n\n rand_clf.fit(X_train, y_train)\n\n best_model = rand_clf.best_estimator_\n best_score = rand_clf.best_score_\n\n print(\"Training Score: {:3f}\".format(best_score))\n y_pred = best_model.predict(X_test)\n accuracy = accuracy_score(y_test, y_pred)\n\n print('Test score: {:3f}'.format(accuracy))\n","sub_path":"src/utils/randomized_search.py","file_name":"randomized_search.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"129622640","text":"from urllib import urlopen\n\nfrom django.conf import settings\n\n\ndef get_avatar(strategy, details, response, uid, user, social, *args,\n **kwargs):\n if user is None:\n return\n image_file_path = '{0}/{1}.jpg'.format(settings.FB_UPLOAD_PATH,\n user.username)\n image_url = None\n if strategy.backend.name == \"facebook\":\n image_url = \"https://graph.facebook.com/{0}/picture?type=large\"\\\n .format(uid)\n if image_url:\n try:\n avatar = urlopen(image_url).read()\n write_to = open(image_file_path, 'wb')\n write_to.write(avatar)\n write_to.close()\n except URLError:\n pass\n","sub_path":"happydays/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"270862639","text":"class Solution:\n def singleNumber(self, nums: List[int]) -> int:\n unique = {}\n for i in nums:\n if(i in unique):\n unique[i] = unique[i]+1\n else:\n unique[i] = 1\n\n for k, v in unique.items():\n if(v != 2):\n return k\n","sub_path":"PythonLeets/singleNumber.py","file_name":"singleNumber.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"558418135","text":"def mini(t):\n \"\"\"Calcule le minimum d'un tableau d'entiers ou de flottants.\"\"\"\n if len(t) == 0:\n return None\n p = t[0]\n for i in range(len(t)):\n if t[i] <= p:\n p = t[i]\n return p\n\ndef maxi(t):\n \"\"\"Calcule le minimum d'un tableau d'entiers ou de flottants.\"\"\"\n if len(t) == 0:\n return None\n p = t[0]\n for i in range(len(t)):\n if t[i] >= p:\n p = t[i]\n return p\n\n\ndef position_mini(t):\n \"\"\"Calcule l'indice du minimum d'un tableau d'entiers ou de flottants.\"\"\"\n if len(t) == 0:\n return None\n p = 0\n for i in range(len(t)):\n if t[i] <= t[p]:\n p = i\n return p\n\ndef mini2D(t):\n if len(t)==0:\n return t\n p = t[0][0]\n for i in range(len(t)):\n m = mini(t[i])\n if mnb:\n cpt = cpt+1\n return cpt\n\nprint(majores_par([12,-5,10,9],10))\n\nprint(chaine_mini([['Tokyo',7000],['Paris',6000],['Londres',8000]]))\n \n \nprint(mini2D([[10,3,15],[5,13,10]]))\n\n#mm = position_mini([6,2,15,2,15])\n#print(mm)","sub_path":"Evaluation_SUP/DS_2014_2015/DS_04/programme/programme_meteo.py","file_name":"programme_meteo.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"564918799","text":"\n# LeetCode 347\n\nclass Solution:\n\n def heapify(self, heap, n):\n for i in range(n // 2, -1, -1):\n self.maxheapify(heap, i, n)\n \n def maxheapify(self, heap, i, n):\n l = 2 * i + 1\n r = 2 * i + 2\n maxi = i\n if l < n and heap[l][1] > heap[maxi][1]:\n maxi = l\n if r < n and heap[r][1] > heap[maxi][1]:\n maxi = r\n if i != maxi:\n heap[i], heap[maxi] = heap[maxi], heap[i]\n self.maxheapify(heap, maxi, n)\n \n def heappop(self, heap, n):\n maxe = heap[0]\n heap[0] = heap[n - 1]\n self.maxheapify(heap, 0, n - 1)\n return maxe[0]\n\n def topKFrequent(self, nums, k: int):\n hmap = {}\n for elem in nums:\n if elem in hmap:\n hmap[elem] += 1\n else:\n hmap[elem] = 1\n items = hmap.items()\n heap = list(items)\n n = len(heap)\n self.heapify(heap, n)\n l = list()\n for i in range(k):\n l.append(self.heappop(heap, n))\n n -= 1\n return l\n\n\nnums = [3,3,3,1,1,1,1,1,1,4,4,4,4,3,3,2,6,7,8,]\nk = 3\nprint(Solution().topKFrequent(nums, k))","sub_path":"clrs-code/Leetcode/heap/topKelem.py","file_name":"topKelem.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"244852441","text":"import os\nimport re\nimport shutil\nfrom pathlib import Path\n\nimport emoji\n\nimport config\n\n\ndef replacing_text(text: str):\n return \\\n re.sub(\n config.msg_replace_regex,\n config.msg_regex_to,\n emoji.demojize(\n text.replace('\\n', '
')\n )\n ) if config.msg_regex_tme else emoji.demojize(text.replace('\\n', '
'))\n\nclass DisplayablePath(object):\n display_filename_prefix_middle = '├──'\n display_filename_prefix_last = '└──'\n display_parent_prefix_middle = ' '\n display_parent_prefix_last = '│ '\n\n def __init__(self, path, parent_path, is_last):\n self.path = Path(str(path))\n self.parent = parent_path\n self.is_last = is_last\n if self.parent:\n self.depth = self.parent.depth + 1\n else:\n self.depth = 0\n\n @property\n def displayname(self):\n if self.path.is_dir():\n return self.path.name + '/'\n return self.path.name\n\n @classmethod\n def make_tree(cls, root, parent=None, is_last=False, criteria=None):\n root = Path(str(root))\n criteria = criteria or cls._default_criteria\n\n displayable_root = cls(root, parent, is_last)\n yield displayable_root\n\n children = sorted(list(path\n for path in root.iterdir()\n if criteria(path)),\n key=lambda s: str(s).lower())\n count = 1\n for path in children:\n is_last = count == len(children)\n if path.is_dir():\n yield from cls.make_tree(path,\n parent=displayable_root,\n is_last=is_last,\n criteria=criteria)\n else:\n yield cls(path, displayable_root, is_last)\n count += 1\n\n @classmethod\n def _default_criteria(cls, path):\n return True\n\n @property\n def displayname(self):\n if self.path.is_dir():\n return self.path.name + '/'\n return self.path.name\n\n def displayable(self):\n if self.parent is None:\n return self.displayname\n\n _filename_prefix = (self.display_filename_prefix_last\n if self.is_last\n else self.display_filename_prefix_middle)\n\n parts = ['{!s} {!s}'.format(_filename_prefix,\n self.displayname)]\n\n parent = self.parent\n while parent and parent.parent is not None:\n parts.append(self.display_parent_prefix_middle\n if parent.is_last\n else self.display_parent_prefix_last)\n parent = parent.parent\n\n return ''.join(reversed(parts))\ndef clear_dir(folder):\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\ndef get_size(start_path = '.'):\n total_size = 0\n for dirpath, dirnames, filenames in os.walk(start_path):\n for f in filenames:\n fp = os.path.join(dirpath, f)\n total_size += os.path.getsize(fp)\n return total_size\ndef humanize(num: float, suffix: str = \"B\") -> str:\n for unit in [\"\", \"Ki\", \"Mi\", \"Gi\"]:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\"\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"511491560","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.tree, name='tree'),\n path('update_message/', views.update_message, name='update_message'),\n path('/', views.message_detail, name=\"message_detail\"),\n path('defender/',views.defender,name=\"defender\"),\n path('defender_for_medal/',views.defender_for_medal,name=\"defender_for_medal\"),\n]\n","sub_path":"treehole/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"576654236","text":"import json\nimport geosoft\nimport geosoft.gxapi as gxapi\nfrom . import utility as gxu\n\n__version__ = geosoft.__version__\n\n\n# translation hook\ndef _t(s):\n return s\n\n#############\n# Constants\n\nNAME = None\nNAME_PCS = gxapi.IPJ_NAME_PCS\nNAME_PROJECTION = gxapi.IPJ_NAME_PROJECTION\nNAME_METHOD = gxapi.IPJ_NAME_METHOD\nNAME_DATUM = gxapi.IPJ_NAME_DATUM\nNAME_ELLIPSOID = gxapi.IPJ_NAME_ELLIPSOID\nNAME_LDATUM = gxapi.IPJ_NAME_LDATUM\nNAME_UNIT = gxapi.IPJ_NAME_UNIT_ABBR\nNAME_UNIT_FULL = gxapi.IPJ_NAME_UNIT_FULL\nNAME_TYPE = gxapi.IPJ_NAME_TYPE\nNAME_LLDATUM = gxapi.IPJ_NAME_LLDATUM\nNAME_METHOD_PARMS = gxapi.IPJ_NAME_METHOD_PARMS\nNAME_METHOD_LABEL = gxapi.IPJ_NAME_METHOD_LABEL\nNAME_DATUM_PARMS = gxapi.IPJ_NAME_DATUM_PARMS\nNAME_LDATUM_PARMS = gxapi.IPJ_NAME_LDATUM_PARMS\nNAME_GEOID = gxapi.IPJ_NAME_GEOID\nNAME_LDATUMDESCRIPTION = gxapi.IPJ_NAME_LDATUMDESCRIPTION\nNAME_METHOD_PARMS_NATIVE = gxapi.IPJ_NAME_METHOD_PARMS_NATIVE\nNAME_ORIENTATION = gxapi.IPJ_NAME_ORIENTATION_PARMS\n\nCOORDINATE_SYSTEM = gxapi.IPJ_PARM_LST_COORDINATESYSTEM\nLIST_DATUM = gxapi.IPJ_PARM_LST_DATUM\nLIST_PROJECTION = gxapi.IPJ_PARM_LST_PROJECTION\nLIST_UNITS = gxapi.IPJ_PARM_LST_UNITS\nLIST_UNITSDESCRIPTION = gxapi.IPJ_PARM_LST_UNITSDESCRIPTION\nLIST_LOCALDATUMDESCRIPTION = gxapi.IPJ_PARM_LST_LOCALDATUMDESCRIPTION\nLOCAL_DATUM_NAME = gxapi.IPJ_PARM_LST_LOCALDATUMNAME\n\n\nclass IPJException(Exception):\n '''\n Exceptions from this module.\n\n .. versionadded:: 9.1\n '''\n pass\n\n\nclass GXipj():\n \"\"\"\n SUPERCEDED: by GXcs in the gxpy.coordinate_system module.\n\n Class to work with Geosoft IPJ coordinate system interface.\n\n ._ipj is the GXIPJ handle to use when calling GXIPJ methods directly\n\n :constructors:\n :from_name: from a name string\n :from_gxf: from a list of GXF strings\n :from_dict: from a dictionary\n :from_json: from a json string\n :from_esri: from an ESRI wkt string\n\n .. deprecated: 9.2\n Replaced by :class:`gxpy.coordinate_system.GXcs`\n\n \"\"\"\n\n def __repr__(self):\n return \"{}({})\".format(self.__class__, self.__dict__)\n\n def __str__(self):\n return self.name()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n pass\n\n def __init__(self, ipj=None):\n self._ipj = gxapi.GXIPJ.create()\n self._coordinate_dict_()\n self._sr = gxapi.str_ref()\n self._fr = gxapi.float_ref()\n\n @classmethod\n def from_any(cls, ipj):\n \"\"\"\n Create an IPJ from a name string, list of GXF strings, or a dictionary.\n :param ipj: IPJ name string, list of GXF strings or a dictionary.\n :return: ipj instance\n\n .. versionadded:: 9.2\n \"\"\"\n if ipj is None:\n return cls()\n elif isinstance(ipj, str):\n return cls.from_name(ipj)\n elif isinstance(ipj, dict):\n return cls.from_dict(ipj)\n else:\n return cls.from_gxf(ipj)\n\n @classmethod\n def from_gxf(cls, gxfs):\n \"\"\"\n Create IPJ from a set of GXF strings.\n\n :params:\n gxfs: list of GXF strings. See GXFIPJ.set_gxf() reference.\n\n .. versionadded:: 9.1\n \"\"\"\n\n ipj = cls()\n\n # if we got a name only, and it has a datum and projection, copy these.\n # The challenge with a name only is that the \"datum / projection\" must exist as\n # a known coordinate system, otherwise we cannot resolve it. Users some times\n # combine projections with different datums so copying the values allows for this\n\n if (gxfs[1] == '') and (gxfs[2] == '') and (gxfs[0].find('/') != -1):\n dp = gxfs[0].strip('\"').split('/')\n gxfs[1] = dp[0].strip()\n orient = dp[1].find('<')\n if orient == -1:\n gxfs[2] = dp[1].strip()\n else:\n gxfs[2] = dp[1][0:orient].strip()\n\n # get ipj from gxf, error if unknown\n ipj._ipj.set_gxf(gxfs[0], gxfs[1], gxfs[2], gxfs[3], gxfs[4])\n ipj._ipj.get_display_name(ipj._sr)\n if ipj._sr.value == '*unknown':\n raise IPJException(_t('Unknown coordinate system:\\n>{}\\n>{}\\n>{}\\n>{}\\n>{}').format(\n gxfs[0],\n gxfs[1],\n gxfs[2],\n gxfs[3],\n gxfs[4]))\n\n ipj._coordinate_dict_()\n return ipj\n\n @classmethod\n def from_json(cls, jstr):\n \"\"\"\n Create an IPJ from a string, which can be a valid coordinate system name string or a JSON\n format string that defines the coordinate system type and properties as follows:\n\n :LocalGrid:\n\n A local grid requires only the latitude and longitude of the local grid\n origin, though generally an azimuth of rotation the local grid axis with\n respect to true North is generally expected. Other properties may also be\n specified if further detail is known or desired.\n An \"Oblique Stereographic\" coordinate system is constructed centred\n on the local grid origin such that the stereographic plan touches the\n elipsoid of the earth at that point. The \"scalefactor\" can be used to\n adjust for intended area of use. The default scale factor ensures\n length units are comparable to UTM length units (0.9996).\n\n .. code::\n\n { \"type\": \"LocalGrid\"\n \"properties\": {\n \"latitude\": value or string in form \"(+/-) deg.mm.ss.ss (N/S)\"\n \"longitude: value or string\n \"azimuth\": value (rotation in degrees azimuth, default is 0.0)\n \"elevation\": value (elevation of map plane, default is 0.0)\n \"datum\": string (name of the datum, default is \"WGS 84\")\n \"ldatum\": string (local datum transform, default determined from datum)\n \"units\": string (unit name, default is \"m\")\n \"scalefactor\": value (central scale factor, default is 0.9996)\n }\n }\n\n :EPSG: (http://spatialreference.org/)\n\n .. code::\n\n { \"type\": \"EPSG\"\n \"properties\": {\n \"code\": EPSG_code_number\n },\n \"orientation\": \"\"\n }\n\n :Geosoft: (http://www.geosoft.com/resources/goto/GXF-Grid-eXchange-File)\n\n .. code::\n\n { \"type\": \"Geosoft\",\n \"properties\": {\n \"name\": name\n \"datum\": datum\n \"method\": method\n \"units\": units\n \"local_datum\": local datum transform\n },\n \"orientation\": \"\"\n }\n\n See see http://www.geosoft.com/resources/goto/GXF-Grid-eXchange-File for GXF string reference\n\n :ESRI: (http://webhelp.esri.com/arcgisserver/9.3/java/index.htm#geodatabases/the_ogc-607957855.htm)\n\n .. code::\n\n { \"type\": \"ESRI\",\n \"properties\": {\n \"wkt\": wkt format string, starts with \"PROJCS[\" or \"GEOGCS[\"\n },\n \"orientation\": \"\"\n }\n\n :\"orientation\":\n\n .. note::\n\n Only orientations of \"<0, 0, 0, 0, 0, 0>\" are currently supported. Oriented coordinate\n systems will be added at some point in the future.\n\n *FUTURE:* In Geosoft coordinate systems, a cartesian system can be oriented arbitrarily\n in three dimensions relative to a base coordinate system. This requires the definition\n of the local origin location on the base system, and the rotation in degrees clockwise\n (azimuth in plan view) around each of the three base system axis, as defined by the\n \"orientation\" description, which is a set of 6 values within angle brackets:\n\n .. code::\n\n \"\"\n\n The orientation string can be appended to the name, or added as it's own key \"orientation\"\n\n For example, a local grid with origin at (550000,6250000) rotated at azimuth 15 degrees\n (clockwise) from the base \"UTM zone 15N\" Northings and Eastings on \"WGS 84\" would be:\n\n .. code::\n\n {\"type\":\"Geosoft\",\"properties\":{\"name\":\"WGS 84 / UTM zone 15N <550000,6250000,0,0,0,15>\"}}\n\n or:\n\n .. code::\n\n {\"type\":\"Geosoft\",\"properties\":{\"name\":\"WGS 84 / UTM zone 15N\"},\n \"orientation\":\"<550000,6250000,0,0,0,15>\"}\n\n .. versionadded:: 9.1\n \"\"\"\n\n # empty string\n if jstr is None or jstr == '':\n raise ValueError(\"Empty JSON string\")\n\n # if first character not a '{', assume it is a name\n if jstr[0] != '{':\n return cls.from_name(jstr)\n\n # convert single quotes to double quotes\n try:\n jsondict = json.loads(jstr)\n except ValueError:\n # try replacing single quotes\n jstr = jstr.replace('\"', '\\\\\"').replace(\"'\", '\"')\n try:\n jsondict = json.loads(jstr)\n except ValueError:\n raise ValueError(\"Invalid JSON coordinate system string <{}>\".format(jstr))\n\n cstype = jsondict.get('type', None)\n properties = jsondict.get('properties', {})\n orientation = jsondict.get('orientation', '')\n if orientation == '':\n orientation = properties.get('orientation', '')\n\n if cstype is None or properties is None:\n raise ValueError(\"'JSON string missing 'type' and/or 'properties' keys.\")\n\n cstype = cstype.lower()\n if cstype == 'geosoft':\n s1 = properties.get('name', '')\n if s1.find('<') == -1:\n s1 = s1 + orientation\n s2 = properties.get('datum', '')\n s3 = properties.get('projection', '')\n s4 = properties.get('units', '')\n s5 = properties.get('local_datum', '')\n ipj = cls.from_gxf([s1, s2, s3, s4, s5])\n\n elif cstype == 'esri':\n wkt = properties.get('wkt', None)\n if wkt is None:\n raise ValueError(\"'ESRI missing 'wkt' property.\")\n # clear any existing coordinate system (bug GX does not clear prior orientation)\n ipj = cls()\n ipj._ipj.set_gxf('WGS 84 <0,0,0,0,0,0>', '', '', '', '')\n ipj._ipj.set_esri(wkt)\n\n # add orientation\n if len(orientation) > 0:\n gxfs = ipj.to_gxf()\n gxfs[0] = gxfs[0] + orientation\n ipj = cls.from_gxf(gxfs)\n\n elif cstype == \"epsg\":\n code = properties.get('code', None)\n if code is None:\n raise ValueError(\"'EPSG JSON string missing 'code' property.\")\n ipj = cls.from_gxf([str(code) + orientation, '', '', '', ''])\n\n elif cstype == 'localgrid':\n # must at least have a latitude and longitude\n lat = properties.get('latitude', None)\n lon = properties.get('longitude', None)\n if (lat is None) or (lon is None):\n raise ValueError(\"'Localgrid must define latitude and longitude properties of the local origin.\")\n sf = properties.get('scalefactor', 0.9996)\n\n datum = properties.get('datum', 'WGS 84')\n proj = '\"Oblique Stereographic\",' + str(lat) + ',' + str(lon) + ',' + str(sf) + ',0,0'.replace('\"', '\\\\\"')\n units = properties.get('units', 'm')\n ldatum = properties.get('ldatum', '')\n azimuth = properties.get('azimuth', 0.0)\n elevation = properties.get('elevation', 0.0)\n if (azimuth == 0.0) and (elevation == 0.0):\n orient = ''\n else:\n orient = '<0,0,' + str(elevation) + ',0,0,' + str(azimuth) + '>'\n\n # construct a name\n name = datum + ' / *Local grid [' + str(lat) + ',' + str(lon) + ']' + orient\n ipj = cls.from_gxf([name, datum, proj, units, ldatum])\n\n else:\n raise ValueError(\"Projection type '{}' not supported.\".format(cstype))\n\n ipj._coordinate_dict_()\n return ipj\n\n @classmethod\n def from_esri(cls, esri_str):\n \"\"\"\n Create an IPJ from an ESRI wkt coordinate string\n\n :param esri_str: ESRI coordinate definition string\n\n .. versionadded:: 9.1\n \"\"\"\n ipj = cls()\n ipj._ipj.set_esri(esri_str)\n\n ipj._coordinate_dict_()\n return ipj\n\n @classmethod\n def from_name(cls, name):\n \"\"\"\n Create an IPJ from a projection name in the form \"datum / projection \".\n\n :param name: coordinate system name in the form \"datum / projection \"\n\n .. versionadded:: 9.1\n \"\"\"\n ipj = cls.from_gxf([name.strip(' \\t\"\\''), '', '', '', ''])\n return ipj\n\n @classmethod\n def from_dict(cls, ipj_dict):\n \"\"\"\n Create an IPJ from a ipj_dict\n\n :param ipj_dict: IPJ dictionary, or a valid name string\n\n .. versionadded:: 9.1\n \"\"\"\n return cls.from_json(json.dumps(ipj_dict))\n\n @staticmethod\n def names(what, datum_filter=''):\n \"\"\"\n Get a list of coordinate system names\n\n :param what:\n | gxipj.COORDINATE_SYSTEM\n | gxipj.LIST_DATUM\n | gxipj.LIST_PROJECTION\n | gxipj.LIST_UNITS\n | gxipj.LIST_LOCALDATUMDESCRIPTION\n | gxipj.LOCAL_DATUM_NAME\n | gxipj.LIST_UNITSDESCRIPTION\n\n :param datum_filter:\n name of a datum to filter results\n\n :returns: sorted list of names\n\n .. versionadded:: 9.1\n \"\"\"\n\n lst = gxapi.GXLST.create(1000)\n gxapi.GXIPJ.get_list(what, datum_filter, lst)\n namelist = list(gxu.dict_from_lst(lst).keys())\n namelist.sort(key=str.lower)\n del lst\n return namelist\n\n def _coordinate_dict_(self):\n \"\"\"\n Fill in coordinate system dict self._ipjDict\n This is a convenience dictionary that makes it easy to get names from a coordinate system\n\n .. versionadded:: 9.1\n \"\"\"\n\n # initially from GXF values\n gxfs = self.to_gxf()\n gxf_dict = {\"type\": \"Geosoft\",\n \"properties\": {\n \"name\": gxfs[0],\n \"datum\": gxfs[1],\n \"projection\": gxfs[2],\n \"units\": gxfs[3],\n \"local_datum\": gxfs[4]}}\n\n # break out names\n name_dict = {'name': gxf_dict['properties']['name'].replace('\"', ' ').strip()}\n parts = name_dict['name'].partition('<')\n if parts[2] == '':\n name_dict['orientation'] = '<0,0,0,0,0,0>'\n else:\n name_dict['orientation'] = '<' + parts[2].strip()\n name_dict['baseName'] = parts[0].strip()\n parts = parts[0].partition('/')\n name_dict['datumName'] = parts[0].strip()\n name_dict['projectionName'] = parts[2].strip()\n name_dict['projectionType'] = gxf_dict['properties']['projection'].split(',', 1)[0].replace('\"', '')\n name_dict['unitName'] = gxf_dict['properties']['units'].split(',', 1)[0].replace('\"', '')\n name_dict['localDatumName'] = gxf_dict['properties']['local_datum'].split(',', 1)[0].replace('\"', '')\n\n # merge the dicts\n self._ipjDict = dict(list(name_dict.items()) + list(gxf_dict.items()))\n\n def to_gxf(self):\n \"\"\"\n Get GXF string list from ipj.\n Returns list of 5 GXF strings.\n\n .. versionadded:: 9.1\n \"\"\"\n\n s1 = gxapi.str_ref()\n s2 = gxapi.str_ref()\n s3 = gxapi.str_ref()\n s4 = gxapi.str_ref()\n s5 = gxapi.str_ref()\n self._ipj.get_gxf(s1, s2, s3, s4, s5)\n lst = [s1.value.replace('\"', ' ').strip(), s2.value, s3.value, s4.value, s5.value]\n return lst\n\n def to_json(self):\n \"\"\"\n Return a JSON formatted projection in the form:\n\n .. code::\n\n {\n \"baseName\": \"DHDN / Okarito 2000\",\n \"datumName\": \"DHDN\",\n \"localDatumName\": \"DHDN to WGS 84 (1)\",\n \"name\": \"DHDN / Okarito 2000 <25000,1000000,50,90,0,15>\",\n \"orientation\": \"<25000,1000000,50,90,0,15>\",\n \"projectionName\": \"Okarito 2000\",\n \"projectionType\": \"Transverse Mercator\",\n \"properties\": {\n \"datum\": \"DHDN,6377397.155,0.0816968312225275,0\",\n \"local_datum\": \"\\\"DHDN to WGS 84 (1)\\\",582,105,414,1.04,0.35,-3.08,8.29999999996112\",\n \"name\": \"DHDN / Okarito 2000 <25000,1000000,50,90,0,15>\",\n \"projection\": \"\\\"Transverse Mercator\\\",-43.11,170.260833333333,1,400000,800000\",\n \"units\": \"m,1\"\n },\n \"type\": \"Geosoft\",\n \"unitName\": \"m\"\n }\n\n .. versionadded:: 9.1\n \"\"\"\n return json.dumps(self._ipjDict)\n\n def dict(self):\n \"\"\"\n Return IPJ dictionary\n\n .. versionadded:: 9.1\n \"\"\"\n return self._ipjDict\n\n def name(self, what=None):\n \"\"\"\n Return requested name.\n\n :param what:\n | gxipj.NAME\n | gxipj.NAME_PCS\n | gxipj.NAME_PROJECTION\n | gxipj.NAME_METHOD\n | gxipj.NAME_DATUM\n | gxipj.NAME_ELLIPSOID\n | gxipj.NAME_LDATUM\n | gxipj.NAME_UNIT\n | gxipj.NAME_UNIT_FULL\n | gxipj.NAME_TYPE\n | gxipj.NAME_LLDATUM\n | gxipj.NAME_METHOD_PARMS\n | gxipj.NAME_METHOD_LABEL\n | gxipj.NAME_DATUM_PARMS\n | gxipj.NAME_LDATUM_PARMS\n | gxipj.NAME_GEOID\n | gxipj.NAME_LDATUMDESCRIPTION\n | gxipj.NAME_METHOD_PARMS_NATIVE\n | gxipj.NAME_ORIENTATION\n\n If 'what' is not specified, gxipj.NAME assumed, which returns the coordinate system display name.\n\n :return: The name requested\n\n .. versionadded:: 9.1\n \"\"\"\n\n if what is None:\n self._ipj.get_display_name(self._sr)\n else:\n self._ipj.get_name(what, self._sr)\n return self._sr.value\n\n @staticmethod\n def compare(ipj1, ipj2):\n \"\"\"\n :return: True if two projections are the same\n :param ipj1: GXipj\n :param ipj2: GXipj\n\n .. versionadded:: 9.1\n \"\"\"\n return ipj1._ipj.coordinate_systems_are_the_same_within_a_small_tolerance(ipj2._ipj)\n\n def units(self):\n \"\"\"\n :return: tuple (factor, abbreviation), where factor is multiplier to convert to metres\n\n .. versionadded:: 9.1\n \"\"\"\n self._ipj.get_units(self._fr, self._sr)\n return self._fr.value, self._sr.value\n\n\nclass GXpj:\n \"\"\"\n Class to reproject coordinates.\n\n :params ipj_from: GXipj from coordinate system\n :params ipj_to: GXipj to coordinate system\n\n .. deprecated: 9.2\n Replaced by :class:`gxpy.coordinate_system.GXpj`\n\n .. versionadded:: 9.1\n \"\"\"\n\n def __repr__(self):\n return \"{}({})\".format(self.__class__, self.__dict__)\n\n def __str__(self):\n return \"PJ from \\'{}\\' to \\'{}\\'\".format(str(self._ipj_from), str(self._ipj_to))\n\n _ipj_from = None\n _ipj_to = None\n _sr = gxapi.str_ref()\n\n def __init__(self, ipj_from, ipj_to):\n self._ipj_from = ipj_from\n self._ipj_to = ipj_to\n self._pj = gxapi.GXPJ.create_ipj(ipj_from._ipj, ipj_to._ipj)\n\n def convert(self, xyz):\n \"\"\"\n Project data in array in which first columns are x,y or x,y,z.\n\n Coordinates are reprojected in-place.\n\n :param xyz:\n | numpy array shape (,3+) for (x,y,z) conversion\n | numpy array shape (,2) for x,y conversion\n\n :example:\n Given an array shape (500,6), which represents 500 data records with 6 columns\n in which the first 3 columns are coordinates X, Y and Z.\n\n .. code::\n\n data = np.zeros((10,5), dtype='float') #then fill the array with some data\n\n pj.convert(data[:,2]) #transform x,y\n pj.convert(data[:,3]) #transform x,y and z\n pj.convert(data) #transform x,y and z (same as previous line)\n\n .. versionadded:: 9.1\n \"\"\"\n\n npoints = xyz.shape[0]\n if npoints == 0:\n return\n\n nd = xyz.shape[1]\n if nd < 2:\n raise IPJException(_t('Data must have minimum dimension 2 (x,y) or 3 for (x,y,z).'))\n\n vvx = gxapi.GXVV.create_ext(gxapi.GS_DOUBLE, npoints)\n vvy = gxapi.GXVV.create_ext(gxapi.GS_DOUBLE, npoints)\n vvx.set_data_np(0, xyz[:, 0])\n vvy.set_data_np(0, xyz[:, 1])\n\n if nd >= 3:\n vvz = gxapi.GXVV.create_ext(gxapi.GS_DOUBLE, npoints)\n vvz.set_data_np(0, xyz[:, 2])\n self._pj.convert_vv3(vvx, vvy, vvz)\n xyz[:, 2] = vvz.get_data_np(0, npoints, 'f8')\n else:\n self._pj.convert_vv(vvx, vvy)\n\n xyz[:, 0] = vvx.get_data_np(0, npoints, 'f8')\n xyz[:, 1] = vvy.get_data_np(0, npoints, 'f8')\n","sub_path":"geosoft/gxpy/ipj.py","file_name":"ipj.py","file_ext":"py","file_size_in_byte":21690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"438409632","text":"\"\"\" Module for computing time series metrics for multi scenario simulation.\"\"\"\n\nimport click\nimport datetime\nimport yaml\nfrom pathlib import Path\nimport multiprocessing\nfrom typing import Dict\n\nfrom emerge.metrics.time_series_metrics import system_metrics\nfrom emerge.metrics.time_series_metrics import observer\nfrom emerge.metrics.time_series_metrics import simulation_manager\nfrom emerge.metrics.time_series_metrics import node_voltage_stats\nfrom emerge.metrics.time_series_metrics import line_loading_stats\nfrom emerge.metrics.time_series_metrics import xfmr_loading_stats\n\n\ndef _get_observers(metrics: Dict):\n observers = {}\n\n class_mapper = {\n 'substation_power': system_metrics.TimeseriesTotalPower,\n 'total_pvpower': system_metrics.TimeseriesTotalPVPower,\n 'total_powerloss': system_metrics.TimeseriesTotalLoss,\n 'node_voltage_stats': node_voltage_stats.NodeVoltageStats,\n 'node_voltage_bins': node_voltage_stats.NodeVoltageBins,\n 'line_loading_stats': line_loading_stats.LineLoadingStats,\n 'line_loading_bins': line_loading_stats.LineLoadingBins,\n 'xfmr_loading_stats': xfmr_loading_stats.XfmrLoadingStats,\n 'xfmr_loading_bins': xfmr_loading_stats.XfmrLoadingBins,\n 'overloaded_lines': line_loading_stats.OverloadedLines,\n 'overloaded_transformers': xfmr_loading_stats.OverloadedTransformers,\n 'sardi_voltage': system_metrics.SARDI_voltage,\n 'sardi_line': system_metrics.SARDI_line,\n 'sardi_xfmr': system_metrics.SARDI_transformer,\n 'sardi_aggregated': system_metrics.SARDI_aggregated\n }\n\n for key, subdict in metrics.items():\n if key in class_mapper:\n if 'args' not in subdict:\n observers[key] = class_mapper[key]()\n else:\n observers[key] = class_mapper[key](*subdict['args'])\n return observers\n\ndef _run_timeseries_sim(\n master_dss_file_path: str,\n start_time: str, \n end_time: str, \n profile_start_time: str,\n resolution_min: float,\n export_path: str,\n metrics,\n pvshape = None,\n pvsystem_folder_path = None,\n time_group = None,\n scenario_folder = None\n):\n date_format = \"%Y-%m-%d %H:%M:%S\"\n manager = simulation_manager.OpenDSSSimulationManager(\n master_dss_file_path,\n datetime.datetime.strptime(start_time, date_format),\n datetime.datetime.strptime(profile_start_time, date_format),\n datetime.datetime.strptime(end_time, date_format),\n resolution_min,\n )\n manager.opendss_instance.set_max_iteration(200)\n subject = observer.MetricsSubject() \n\n if pvsystem_folder_path:\n pvsystem_file_path = pvsystem_folder_path / 'PVSystems.dss'\n manager.opendss_instance.execute_dss_command(f\"Redirect {pvsystem_file_path}\")\n manager.opendss_instance.execute_dss_command(f\"batchedit pvsystem..* yearly={pvshape}\")\n\n observers = _get_observers(metrics)\n for _, observer_ in observers.items():\n subject.attach(observer_)\n\n manager.simulate(subject)\n\n export_base_path = Path(export_path) \n if scenario_folder:\n if time_group:\n scenario_folder = f\"{scenario_folder}_{time_group}\"\n export_base_path = export_base_path / scenario_folder \n \n if pvsystem_folder_path:\n export_base_path = export_base_path / pvsystem_file_path.parent.name\n \n if not export_base_path.exists():\n export_base_path.mkdir(parents=True)\n \n manager.export_convergence(export_base_path / 'convergence_report.csv')\n observer.export_csv(list(observers.values()), export_base_path)\n\ndef _compute_custom_metrics(config, pvsystem_folder_path=None, \n scenario=None):\n \n if scenario:\n scenario_folder, master_file = scenario\n \n if config['multi_time']:\n for time_group, time_dict in config['multi_time'].items():\n _run_timeseries_sim(\n config[\"master\"] if not scenario else master_file,\n time_dict['start_time'],\n time_dict['end_time'],\n config[\"profile_start\"],\n config[\"resolution_min\"],\n config[\"export_path\"],\n config['metrics'],\n config['multi_scenario']['pv_profile_shape'],\n pvsystem_folder_path,\n time_group,\n None if not scenario else scenario_folder\n )\n else:\n _run_timeseries_sim(\n config[\"master\"] if not scenario else master_file,\n config['start_time'],\n config['end_time'],\n config[\"profile_start\"],\n config[\"resolution_min\"],\n config[\"export_path\"],\n config['metrics'],\n config['multi_scenario']['pv_profile_shape'],\n pvsystem_folder_path,\n None,\n None if not scenario else scenario_folder\n )\n \n\n@click.command()\n@click.option(\n \"-c\",\n \"--config-file\",\n help=\"Path to config yaml file.\",\n)\ndef compute_custom_metrics(\n config_file\n):\n \"\"\"Compute custom metrics after running time series powerflow.\"\"\"\n\n with open(config_file, \"r\") as fp:\n config = yaml.safe_load(fp)\n\n\n if config.get('multi_scenario', None):\n\n for folder_, master_file in config['multi_scenario']['scenario_folder'].items():\n scen_folder = Path(config['multi_scenario']['scenario_base_path']) / folder_\n if config['multi_scenario']['num_core'] > 1:\n all_paths = list(scen_folder.iterdir())\n with multiprocessing.Pool(config['multi_scenario']['num_core']) as p:\n p.starmap(_compute_custom_metrics, list(zip([config]*len(all_paths), all_paths, \n [[folder_,master_file]]*len(all_paths)) ))\n else:\n for path in scen_folder.iterdir():\n _compute_custom_metrics(config, path, [folder_, master_file])\n else:\n _compute_custom_metrics(config)\n\n \n\n ","sub_path":"emerge/cli/custom_metrics.py","file_name":"custom_metrics.py","file_ext":"py","file_size_in_byte":6178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"189617181","text":"import pandas as pd\nimport json\nimport unicodedata\nimport collections\nimport requests\n\n\njson_path = \"data/metadata.xlsx.json\"\n\nwith open(json_path) as f:\n df = json.load(f)\n\nmanifests = {}\n\nindex_map = {}\n\nfor i in range(len(df)):\n\n print(str(i+1)+\"/\"+str(len(df)))\n\n obj = df[i]\n\n id = obj[\"@id\"]\n index = int(id.split(\"#\")[1])\n\n curation_uri = obj[\"http://purl.org/dc/terms/relation\"][0][\"@id\"]\n\n r = requests.get(curation_uri)\n data = r.json()\n\n member = data[\"selections\"][0][\"members\"][0]\n\n # 不要な要素の削除\n\n member.pop(\"description\")\n\n metadata = member[\"metadata\"]\n\n indexes = []\n\n for j in range(len(metadata)):\n obj2 = metadata[j]\n if obj2[\"label\"] == \"タイトル\" or obj2[\"label\"] == \"帖数\":\n indexes.append(j)\n\n for j in range(len(indexes)):\n index3 = indexes[len(indexes) - j - 1]\n metadata.pop(index3)\n\n # ここまで\n\n member[\"label\"] = obj[\"http://purl.org/dc/terms/title\"][0][\"@value\"]\n member[\"related\"] = \"https://kunshujo.dl.itc.u-tokyo.ac.jp/iiif-curation-player/?curation=\"+curation_uri\n\n manifest = data[\"selections\"][0][\"within\"][\"@id\"]\n\n if manifest not in index_map:\n\n r = requests.get(manifest)\n mani_data = r.json()\n\n metadata = mani_data[\"metadata\"]\n\n for obj in metadata:\n if obj[\"label\"] == \"Sort\":\n index2 = int(obj[\"value\"])\n\n manifests[index2] = {\n \"uri\": manifest,\n \"label\": mani_data[\"label\"]\n }\n\n index_map[manifest] = {}\n\n index_map[manifest][index] = member\n\nselections = []\n\nrange = 1\n\nfor index2 in sorted(manifests):\n\n obj = manifests[index2]\n\n manifest = obj[\"uri\"]\n\n tmp = index_map[manifest]\n\n members = []\n\n for index in sorted(tmp):\n members.append(tmp[index])\n\n selections.append({\n \"@id\": \"https://kunshujo.dl.itc.u-tokyo.ac.jp/data/curation.json/range\"+str(range),\n \"@type\": \"sc:Range\",\n \"label\": \"Manual curation by IIIF Curation Viewer\",\n \"members\": members,\n \"within\": {\n \"@id\": manifest,\n \"label\": obj[\"label\"],\n \"@type\": \"sc:Manifest\"\n }\n })\n\n range += 1\n\nresult = {\n \"@context\": [\n \"http://iiif.io/api/presentation/2/context.json\",\n \"http://codh.rois.ac.jp/iiif/curation/1/context.json\"\n ],\n \"@id\": \"https://kunshujo.dl.itc.u-tokyo.ac.jp/data/curation.json\",\n \"@type\": \"cr:Curation\",\n \"label\": \"電子展示『捃拾帖』\",\n \"selections\": selections\n}\n\nwith open(\"../docs/data/curation.json\", 'w') as f:\n json.dump(result, f, ensure_ascii=False, indent=4,\n sort_keys=True, separators=(',', ': '))\n","sub_path":"src/92_create_curation.py","file_name":"92_create_curation.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"12886847","text":"numeros = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco', 'seis',\n 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',\n 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito',\n 'dezenove', 'vinte')\n\n\nfor i in range(0, len(numeros)):\n n = int(input('Escolha um número de 0 a 20: '))\n while n > 20 or n < 0:\n n = int(input('Tente Novamente e escolha um número de 0 a 20: '))\n print(f'{numeros[n]}')\n print('-'*10)\n","sub_path":"ProjetosPython/PraticandoPython/P61-NumeroPorExtenso.py","file_name":"P61-NumeroPorExtenso.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"440125781","text":"# https://atcoder.jp/contests/abc124/tasks/abc124_b\n\nn = int(input())\nh = list(map(int, input().split()))\nans = 1\nm = 0\n\nfor i in range(1, n, 1):\n m = max(m, h[i - 1])\n if (m <= h[i]):\n ans += 1\n\nprint(ans)\n","sub_path":"beginner_contests/124/B/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"437983398","text":"from git import Repo\nfrom os.path import isdir\nfrom os import environ\nfrom sys import stderr, stdout\nfrom pathlib import Path\nfrom .types import RegionReport\n\nimport csv\nimport pendulum\n\nREPO_TARGET = environ.get(\"REPO_TARGET\", \"./.stats_repo\")\n\n# The format (which is unfortunate) used by the csv files\nFILE_DATE_FORMAT = \"MM-DD-YYYY\"\n\ndef today():\n \"\"\"\n Return the current day in DD-MM-YYYY format.\n \"\"\"\n dt = pendulum.now()\n return (dt.year, dt.month, dt.day)\n\ndef clone_repo():\n \"\"\"\n Clone the covid-19 data repo.\n \"\"\"\n if not isdir(REPO_TARGET):\n stdout.write(f\"Cloning repo to {REPO_TARGET}\\n\")\n Repo.clone_from(\"https://github.com/CSSEGISandData/COVID-19.git\", REPO_TARGET)\n\ndef pull_repo():\n \"\"\"\n Pull the latest from the repo.\n \"\"\"\n clone_repo()\n repo = Repo(REPO_TARGET)\n stdout.write(f\"Pulling latest from origin\\n\")\n repo.remotes.origin.pull()\n\ndef case_reports_by_day(year, month, day):\n \"\"\"\n Given a timestamp, get an iterator over data from that day.\n If it does not exist, the iterator will yield zero values.\n \"\"\"\n\n timestamp = pendulum.datetime(year, month, day).format(FILE_DATE_FORMAT)\n reports_subpath = Path(\"csse_covid_19_data/csse_covid_19_daily_reports\")\n\n case_reports_path = Path(\".\") / Path(REPO_TARGET) / Path(reports_subpath) / Path(f\"{timestamp}.csv\")\n\n if case_reports_path.exists():\n with case_reports_path.open() as reportsfile:\n reports_reader = csv.reader(reportsfile, delimiter=\",\")\n # skip the headers\n next(reports_reader)\n for row in reports_reader:\n yield RegionReport(*row)\n\ndef current_case_reports():\n \"\"\"\n Get an iterator of all case reports for today. If they exist.\n Otherwise decrement day until we find one that does exist.\n \"\"\"\n return case_reports_by_day(*today())\n","sub_path":"fetchstats/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"14107732","text":"n = int(input())\r\nA = [[] for j in range(n)]\r\nm = int(input())\r\nfor i in range(m):\r\n x,y = map(int, input().split())\r\n A[x] +=[y]\r\n A[y] +=[x]\r\nB = []\r\n\r\ndef check(A, B, k):\r\n if k in B:\r\n return\r\n B.append(k)\r\n for element in A[k]:\r\n check(A, B, element)\r\ncheck(A, B, 0)\r\nif len(B) == n:\r\n print(\"YES\")\r\nelse:\r\n print(\"NO\")","sub_path":"D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"119176142","text":"from xml.sax.saxutils import escape, quoteattr\n\n__all__ = ['__author__', '__license__', 'Builder', 'Safe', 'Element']\n__author__ = ('Beat Bolli', 'me+python@drbeat.li', 'https://drbeat.li/py/')\n__license__ = \"GPL3+\"\n\n# prepare the keyword unmangling dictionary\nimport keyword\nkwunmangle = dict((k + '_', k) for k in keyword.kwlist)\ndel keyword\n\n\ndef nameprep(name):\n \"\"\"Undo keyword and colon mangling\"\"\"\n name = kwunmangle.get(name, name)\n return name.replace('__', ':')\n\n\nclass Builder:\n\n def __init__(self, version='1.0', encoding='utf-8', indent=' ', stream=None):\n self._document = ['']\n self._encoding = encoding\n self._indentation = 0\n self._indent = indent\n self.__write = stream.write if stream else self._document.append\n if version and encoding:\n self._write(f'')\n\n def __getattr__(self, name):\n return Element(name, self)\n\n def __getitem__(self, value):\n self._write(escape(value))\n\n def __str__(self):\n return ''.join(self._document)\n\n def __bytes__(self):\n return str(self).encode(self._encoding, 'xmlcharrefreplace')\n\n def _write(self, line, indent=0):\n if indent < 0:\n self._indentation += indent\n if self._indent is not None:\n line = self._indentation * self._indent + line + '\\n'\n self.__write(line)\n if indent > 0:\n self._indentation += indent\n\n\nclass Safe:\n\n def __init__(self, v):\n self.content = v.content if isinstance(v, Safe) else v\n\n def apply(self, fn):\n self.content = fn(self.content)\n return self\n\n\nclass Element:\n _empty = object()\n\n def __init__(self, name, builder):\n self._name = nameprep(name)\n self._builder = builder\n self._serialized_attrs = ''\n\n def __getattr__(self, name):\n return Element(name, self._builder)\n\n def __enter__(self):\n self._builder._write(f'<{self._name}{self._serialized_attrs}>', +1)\n return self\n\n def __exit__(self, typ, value, tb):\n if typ:\n return False # reraise exceptions\n self._builder._write(f'', -1)\n\n def __call__(self, _value=_empty, **attrs):\n self._serialized_attrs = ''.join(\n f' {nameprep(attr)}={quoteattr(value)}' for attr, value in attrs.items()\n )\n if _value is None:\n self._builder._write(f'<{self._name}{self._serialized_attrs}/>')\n elif _value is not self._empty:\n _value = _value.content if isinstance(_value, Safe) else escape(_value)\n self._builder._write(f'<{self._name}{self._serialized_attrs}>{_value}')\n return self\n\n def __getitem__(self, value):\n value = value.content if isinstance(value, Safe) else escape(value)\n self._builder._write(value)\n return self\n\n\nif __name__ == \"__main__\":\n import sys\n xml = Builder(stream=sys.stdout)\n with xml.feed(xmlns='http://www.w3.org/2005/Atom'):\n xml.title('Example Feed')\n # None is required for empty elements\n xml.link(None, href='http://example.org/')\n xml.updated('2003-12-13T18:30:02Z')\n with xml.author:\n xml.name('John Doe').email('jd@example.org')\n xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6')\n with xml.entry:\n xml.my__elem(\"Hello these are namespaces!\", xmlns__my='http://example.org/ns/', my__attr='what?')\n xml.quoting(\"< > & ' \\\"\", attr=\"< > & ' \\\"\")\n xml.quoting(Safe(\" & ' \\\"\"), attr=\"< > & ' \\\"\")\n xml.str(\"¡Thìs ïs å tést!\", attr='“—”')\n xml.title('Atom-Powered Robots Run Amok')\n xml.link(None, href='http://example.org/2003/12/13/atom03')\n xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a')\n xml.updated('2003-12-13T18:30:02Z')\n xml.summary('Some text.')\n with xml.content(type='xhtml').div(xmlns='http://www.w3.org/1999/xhtml'):\n xml.label('Some label', for_='some_field')[':'].input(None, type='text', value='')\n","sub_path":"xmlbuilder3.py","file_name":"xmlbuilder3.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"44507366","text":"from block import *\nfrom BeautifulSoup import BeautifulSoup \nfrom logging import ERROR, WARN, INFO, DEBUG\nimport urlparse\n\nclass bookmark_query(Block):\n def on_load(self, config):\n self.config = config\n self.add_port(\"list\", Port.QUERY, Port.UNNAMED, [])\n self.add_port(\"restore\", Port.QUERY, Port.UNNAMED, [\"url\", \"time\"])\n self.add_port(\"delete\", Port.QUERY, Port.UNNAMED, [\"url\", \"time\"])\n self.add_port(\"store_control\", Port.QUERY, Port.UNNAMED, [\"command\", \"args\"])\n self.add_port(\"meta_control\", Port.QUERY, Port.UNNAMED, [\"command\", \"args\"])\n \n def add_meta(self, log):\n mlog = Log()\n mlog.append_field(\"path\", log.log[\"internet_url\"])\n #we only have one fingerprint per url now, so create a one element list\n mlog.append_field(\"fingerprints\", [[f] for f in log.log[\"fingerprint\"]])\n self.push(\"meta_store\", mlog)\n\n def add_chunks(self, log):\n clog = Log()\n clog.append_field(\"url\", log.log[\"url\"])\n clog.append_field(\"fingerprint\", log.log[\"fingerprint\"])\n self.push(\"store\", clog)\n\n def recv_push(self, port, log):\n self.add_chunks(log)\n self.add_meta(log)\n \n def fetch_meta(self, url, time):\n mlog = Log()\n mlog.append_field(\"command\", [\"restore\"])\n mlog.append_field(\"args\", [[(url, time)]])\n retlog = self.query(\"meta_control\", mlog)\n asset_list = retlog.log[\"assets\"]\n self.log(INFO, \"got assets from meta_store: %r\" % asset_list)\n assert(len(asset_list)==1)\n return asset_list[0]\n \n def fetch_store(self, fp):\n slog = Log()\n slog.append_field(\"command\", [\"restore\"])\n slog.append_field(\"args\", [[fp]])\n retlog = self.query(\"store_control\", slog)\n store_urls = retlog.log[\"chunk\"]\n self.log(INFO, \"got urls from data_store: %r\" % store_urls)\n assert(len(store_urls)<=1)\n if len(store_urls) == 0:\n raise KeyError\n return store_urls[0]\n \n def rewrite_links(self, url, html, assets):\n soup = BeautifulSoup(html)\n img_links = [l.get('src') for l in soup.findAll('img')]\n css_links = [l.get('href') for l in soup.findAll('link') if l.has_key('rel') and l['rel'].lower() == 'stylesheet']\n #extract links with valid sources\n links = [l for l in (img_links + css_links) if l != None]\n local_links = {}\n for l in links:\n #convert relative links into absolute\n try:\n fp = assets[urlparse.urljoin(url, l) if l[:4] != 'http' else l]\n local_links[l] = self.fetch_store(fp)\n except KeyError:\n self.log(WARN, \"did not download url for link: %r\" % l)\n #we did not dowload that url\n local_links[l] = l\n \n img_tags = soup.findAll('img')\n for i in img_tags:\n i['src'] = local_links[i['src']]\n css_tags = [t for t in soup.findAll('link') if t.has_key('rel') and t['rel'].lower() == 'stylesheet']\n for c in css_tags:\n c['href'] = local_links[c['href']]\n\n return soup.prettify()\n \n def restore(self, url, time):\n try:\n asset_pairs = self.fetch_meta(url, time)\n assets = {}\n for aurl, fp in asset_pairs:\n assets[aurl] = fp\n local_url = assets[url]\n html = BlockUtils.fetch_file_at_url(self.fetch_store(local_url),\n self.ip_address)\n html = self.rewrite_links(url, html, assets)\n name = unicode('bookmark_restored')\n with open(name, 'w') as f:\n f.write(html)\n path = os.path.join(os.getcwd(), name)\n return BlockUtils.generate_url_for_path(path, self.ip_address)\n except KeyError:\n self.log(WARN, \"could not restore file: %r\" % url)\n return ''\n \n def delete(self, url, time):\n try:\n asset_pairs = self.fetch_meta(url, time)\n fps = [a[1] for a in asset_pairs]\n mlog = Log()\n mlog.append_field(\"command\", [\"delete\"])\n mlog.append_field(\"args\", [[(url, time)]])\n res = self.query(\"meta_control\", mlog).log[\"result\"][0]\n slog = Log()\n slog.append_field(\"command\", [\"delete\"])\n slog.append_field(\"args\", [fps])\n deleteres = self.query(\"store_control\", slog).log[\"result\"]\n for r in deleteres:\n res = res and r\n return res\n except Exception as e:\n self.log(WARN, \"could not delete %r (at %r) due to %r\" % (url, time, e))\n return False \n \n def list_bookmarks(self):\n mlog = Log()\n mlog.append_field(\"command\", [\"list\"])\n mlog.append_field(\"args\", [[]])\n retlog = self.query(\"meta_control\", mlog)\n return (retlog.log[\"path\"], retlog.log[\"time\"])\n \n def recv_query(self, port, log):\n retlog = Log()\n if port == \"list\":\n urls, times = self.list_bookmarks()\n retlog.append_field(\"url\", urls)\n retlog.append_field(\"time\", times)\n elif port == \"delete\":\n delete_res = [self.delete(u, t) for u, t in log.iter_fields(\"url\", \"time\")]\n retlog.append_field(\"result\", delete_res)\n elif port == \"restore\":\n restored_urls = [self.restore(u, t) for u, t in log.iter_fields(\"url\", \"time\")]\n retlog.append_field(\"url\", restored_urls)\n \n self.return_query_res(port, retlog)\n","sub_path":"blox/bookmark_query__1_0/b_bookmark_query.py","file_name":"b_bookmark_query.py","file_ext":"py","file_size_in_byte":5050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"353048151","text":"import sys\nimport numpy as np\n\ndef MatrixChainOrder(p, i, j): \n \n if i == j: \n return 0\n \n #_min = sys.maxsize \n _max = -(sys.maxsize)\n # place parenthesis at different places \n # between first and last matrix, \n # recursively calculate count of \n # multiplications for each parenthesis \n # placement and return the minimum count \n for k in range(i, j): \n \n count = (MatrixChainOrder(p, i, k) \n + MatrixChainOrder(p, k + 1, j) \n + p[i-1] * p[k] * p[j]) \n \n if count > _max: \n _max = count; \n \n \n # Return minimum count \n return _max; \n\ndef matrixChainOrder(p):\n n = len(p) - 1\n m = [[0 for x in range(0, n)] for y in range(0, n)]\n s = [[0 for x in range(0, n)] for y in range(0, n)]\n for i in range(n):\n m[i][i] = 0\n for l in range(2, n+1):\n for i in range(0, n - l + 1):\n j = i + l - 1\n if i < j: # skip the i > j cases since we must multiply in order\n # cost values\n c = [m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1] for k in range(i, j)]\n\n # get minimum index and value from costs\n (s[i][j], m[i][j]) = min(enumerate(c), key=lambda x: x[1])\n\n print (i, j, [x for x in enumerate(c)])\n\n s[i][j] = s[i][j] + i + 1\n print(\"M \")\n print(np.array(m, np.int32))\n print(\"S \")\n print(np.array(s, np.int32))\n printOptimalParens(s, 0, len(s) - 1)\n print()\n for i in range(n):\n for j in range(n):\n print(\"M[\" + str(i+1) + \",\" + str(j+1) + \"] = \" + str(m[i][j]))\n\ndef printOptimalParens(s, i, j):\n if i == j:\n print(\"A\" + str(i+1), end='')\n else:\n print(\"(\", end='')\n #print(\"DEBUG: \" + str(i) + \" \" + str(j))\n printOptimalParens(s, i, s[i][j] - 1)\n printOptimalParens(s, s[i][j], j)\n print(\")\", end='')\n\n#arr = [5,10,3,12,5,50,6]\narr = [10,2,5,20,5]\narr2 = np.array(arr)\nprint(MatrixChainOrder(arr, 1, len(arr)-1))\nmatrixChainOrder(arr)","sub_path":"pythonScripts/algo/matrixunop.py","file_name":"matrixunop.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"225397301","text":"# Part 2 of the Python Review lab.\ndef prime(x):\n\tfor i in range(2,x):\n\t\tif (x % i) == 0:\n\t\t\tprint(x,\"is not a prime number\")\n\t\t\treturn False\n\treturn True\n\n\n\ndef encode(x, y):\n\twhile not prime(x):\n\t\tx+=1\n\twhile not prime(y):\n\t\ty+=1\n\tif 1 < y < 250 and 500 < x < 1000 :\n\n\t\treturn(x*y)\n\telse:\n\t\tprint ('Invalid input: Outside range.')\n\t\treturn None\n\t\n\n\ndef decode(coded_message):\n\tfor x in range(501,1000):\n\t\tif prime (x):\n\t\t\ty = (coded_message / x )\n\t\t\tif (coded_message% x) == 0:\n\t\t\t\tif prime(y) and 1< y < 250:\n\t\t\t\t\treturn (x , y)\n\n\n\n","sub_path":"part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"23117858","text":"# -*- coding: UTF-8 -*-\n# 从widgetID_List.csv文件中获取widget列表,将widget返回的数据摘取,并存入文件中\n\nimport requests\nimport json\nimport logging\n\nhost = 'https://middlev2.datadeck.com/api/slack/v1/widgets/'\nfilenameWidget = 'widgetID_List1.csv'\npath = './middlev2/'\n\n\n# 从文件中获取widgetid的list\ndef getwidget(filenameWidget):\n with open(filenameWidget, \"rt\") as in_file:\n text = in_file.read()\n return text.strip().split('\\n') # 去掉字符串前后空格换行,并按照换行符区分返回list\n\n\n# 获取widget的数据\ndef getdata(host, uid, widgetid):\n\n header = {'token': 'bm90aWZpY2F0aW9uX3N1cGVyX3Rva2Vu',\n 'UserID': uid}\n url2 = host + widgetid\n para2 = {}\n r2 = requests.get(url2, params=para2, headers=header)\n # 响应的json数据转换为可被python识别的数据类型\n return r2.json()\n\n# 将获取的值,写入文件中\ndef writefile(json_r):\n list1 = []\n\n widgetid = json_r['data']['data']['widgetId']\n filename = widgetid +'.csv'\n\n dataList = json_r['data']['data']['data']\n\n # 将获取的值,添加到list\n for i in dataList:\n #list1.append(i['rows'])\n for j in i['rows']:\n list2 = []\n for k in j:\n if(type(k) == float):\n list2.append(int(k))\n else:\n list2.append(k)\n list1.append(list2)\n\n # 将list,写入文件中\n fl = open(path + filename, \"w+\")\n for i in list1:\n fl.write(str(i))\n fl.write('\\n')\n fl.close()\n\n\nif __name__ == '__main__':\n widgetlist = getwidget(filenameWidget)\n LOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\n logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n for i in widgetlist:\n logging.info('start')\n widgetUidList = i.split(',')\n logging.info('getdata start')\n json_r = getdata(host, widgetUidList[1], widgetUidList[0])\n logging.info('getdata end')\n logging.info('write start')\n writefile(json_r)\n logging.info('end')\n","sub_path":"test2/getdata_minddlev2.py","file_name":"getdata_minddlev2.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"572309981","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\nimport urllib\nimport re\n\n\nclass QSBK:\n def __init__(self):\n self.pageindex = 1\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}\n self.stories = []\n self.enable = False\n\n def getpage(self, pageindex):\n try:\n url = 'https://www.qiushibaike.com/hot/%s/%s' % ('page', pageindex)\n # print url\n request = urllib.Request(url, headers=self.headers)\n res = urllib.urlopen(request)\n res = res.read().decode('utf-8')\n return res\n except:\n print('链接失败错误')\n\n def getpageitems(self, pageindex):\n res = self.getpage(pageindex)\n if not res:\n print('页面加载失败')\n return\n pattern = re.compile(r'

(.*?)

.*?(.*?).*?class=\"number\">(.*?).*?class=\"number\">(.*?)', re.S)\n items = re.findall(pattern, res)\n # print items\n pagestories = []\n for item in items:\n pagestories.append([item[0], item[1], item[2], item[3]])\n return pagestories\n\n def loadpage(self):\n if self.enable == True:\n if len(self.stories) < 2:\n pagestories = self.getpageitems(self.pageindex)\n if pagestories:\n self.stories.append(pagestories)\n self.pageindex += 1\n\n def getonestory(self, pagestories, page):\n n = 0\n for story in pagestories:\n input = input('')\n n += 1\n self.loadpage()\n if input == 'q':\n self.enable = False\n return\n print('第%d页\\t第%d条发布:%s\\t%s' % (page, n, story[0], story[1]))\n print('这条阅读量是%s,评论是%s条' % (story[2], story[3]))\n\n def start(self):\n print('正在读取糗事百科,按回车查看新段子,q退出')\n self.enable = True\n self.loadpage()\n nowpage = 0\n while self.enable:\n if len(self.stories) > 0:\n pagestories = self.stories[0]\n nowpage += 1\n del self.stories[0]\n self.getonestory(pagestories, nowpage)\n\n\nspider = QSBK()\nspider.start()\n","sub_path":"Spider/qiushibaike/QSBK.py","file_name":"QSBK.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"531967839","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 21 13:56:35 2017\n\n@author: raymondmg\n\"\"\"\n\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'crawler.settings'\nimport django\ndjango.setup()\nfrom crawlerDataBase.models import Article\nimport requests\nimport re\nimport random\nfrom lxml import etree\nimport time\nimport jieba\nfrom jieba import analyse\nimport jieba.posseg as pseg\n\n\ndef creadstoplist(stopwordspath):\n stwlist = [line.strip()\n for line in open(stopwordspath, 'r', encoding='utf-8').readlines()]\n return stwlist\n\njieba.load_userdict(\"userdict.txt\") \nstwlist = creadstoplist('stopwords.txt')\n\ndef dealWithCutWord(data,filterOrNot,flag):\n words=pseg.cut(data.strip())\n\n \n strArticle=\"\"\n for w in words:\n #去停用词\n if w.word not in stwlist:\n if len(w.word) > 1:\n if filterOrNot:\n flagStrArray=flag.split(',')\n if w.flag in flagStrArray:\n strArticle+=w.word+\",\"+w.flag+\";\"\n else:\n strArticle+=w.word+\",\"+w.flag+\";\"\n return str(strArticle)\n\ndef updateArticleKeyWords():\n jieba.load_userdict(\"userdict.txt\") \n\n index=1\n allData=Article.objects.all()\n cutwordsres=[]\n for da in allData:\n articles=da.articleInfo\n if articles.strip()!='':\n cutword=dealWithCutWord(articles,False,\"ns\")\n cutwordsres.append(cutword)\n \n percent=index/allData.count()*100\n if percent>0.1:\n break\n printResult=\"%.2f\" % percent +'%'\n print(printResult)\n #print(cutword)\n index+=1\n \n df2Csv=pd.DataFrame({'result':cutwordsres})\n df2Csv.to_csv(\"cutword-result.csv\", index=False, encoding='utf-8') \n \n\n\nupdateArticleKeyWords()","sub_path":"crawler/cutword/cutWordDB.py","file_name":"cutWordDB.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"41209981","text":"from tqdm import tqdm\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom config import PARAMS as params\nfrom config import DEVICE as device\n\nfrom utils import get_dataloader\nfrom ss_rel_dcgan import Generator, Discriminator\n\n\n# Custom weight initialization\n# From https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.02)\n elif classname.find(\"BatchNorm\") != -1:\n nn.init.normal_(m.weight.data, 1.0, 0.02)\n nn.init.constant_(m.bias.data, 0)\n\n\nprint(device, \" used.\")\n\n# Configure dataloader\ndataloader = get_dataloader(params)\n\n# Plot the training images.\nsample_batch = next(iter(dataloader))\nplt.figure(figsize=(8, 8))\nplt.axis(\"off\")\nplt.title(\"Training Images\")\nplt.imshow(\n np.transpose(\n vutils.make_grid(\n sample_batch[0].to(device)[:64], padding=2, normalize=True,\n ).cpu(),\n (1, 2, 0),\n )\n)\n\nplt.show()\n\nreal_label = 1.0\nfake_label = 0.0\n\n# Initialize generator\ngen = Generator(params).to(device)\n# Apply custom weight initialization\ngen.apply(weights_init)\n\n# Initialize discriminator\ndisc = Discriminator(params).to(device)\n# Apply custom weight initialization\ndisc.apply(weights_init)\n\n# Binary Cross Entropy Loss\ncriterion = nn.BCEWithLogitsLoss().to(device)\n\n# Optimizers\ngen_opt = optim.Adam(\n gen.parameters(), lr=params[\"lr\"], betas=(params[\"beta1\"], params[\"beta2\"])\n)\ndisc_opt = optim.Adam(\n disc.parameters(), lr=params[\"lr\"], betas=(params[\"beta1\"], params[\"beta2\"])\n)\n\n# Tensorboard\nwriter = SummaryWriter(log_dir=\"./logs\")\n\n# Stores generated images as training progresses.\nimg_list = []\n\n# Fixed noise for visualization of generator progression\nfixed_visualization_noise = torch.randn(64, params[\"nz\"], 1, 1, device=device)\n\nbatches_trained = 0\nfor epoch in range(1, params[\"nepochs\"] + 1):\n print(f\"* Epoch {epoch}\")\n for i, data in enumerate(tqdm(dataloader), 0):\n # Get data and transfer to GPU/CPU\n real_imgs = data[0].to(device)\n # Get batch size (can be different than params for last batch)\n batch_size = real_imgs.size(0)\n\n #################\n # Train Discriminator\n #################\n\n disc.zero_grad()\n # Create labels for the real data. (label=1)\n real_labels = torch.full((batch_size * 4,), real_label, device=device).float()\n fake_labels = torch.full((batch_size * 4,), fake_label, device=device).float()\n\n # Rotate all of the real images by 0, 90, 180, and 270 degrees\n x = real_imgs\n x_90 = x.transpose(2, 3)\n x_180 = x.flip(2, 3)\n x_270 = x.transpose(2, 3).flip(2, 3)\n real_imgs = torch.cat((x, x_90, x_180, x_270), 0)\n\n # Sample random data from a unit normal distribution.\n noise = torch.randn(batch_size, params[\"nz\"], 1, 1, device=device)\n # Generate fake data (images).\n fake_imgs = gen(noise)\n\n # Rotate all of the fake images by 0, 90, 180, and 270 degrees\n x = fake_imgs\n x_90 = x.transpose(2, 3)\n x_180 = x.flip(2, 3)\n x_270 = x.transpose(2, 3).flip(2, 3)\n fake_imgs = torch.cat((x, x_90, x_180, x_270), 0)\n\n y_real_logits, y_real_rots_logits = disc(real_imgs)\n y_real_logits = y_real_logits.view(-1)\n y_real_rots_logits = y_real_rots_logits.view(batch_size * 4, -1)\n\n # Compute the one-hot rotational labels\n rot_labels = torch.zeros(4 * batch_size, device=device)\n for i in range(4 * batch_size):\n if i < batch_size:\n rot_labels[i] = 0\n elif i < 2 * batch_size:\n rot_labels[i] = 1\n elif i < 3 * batch_size:\n rot_labels[i] = 2\n else:\n rot_labels[i] = 3\n rot_labels = F.one_hot(rot_labels.to(torch.int64), 4).float()\n\n # Calculate the output of the discriminator of the fake data.\n # As no gradients w.r.t. the generator parameters are to be\n # calculated, detach() is used. Hence, only gradients w.r.t. the\n # discriminator parameters will be calculated.\n # This is done because the loss functions for the discriminator\n # and the generator are slightly different.\n y_fake_logits, y_fake_rots_logits = disc(fake_imgs.detach())\n y_fake_logits = y_fake_logits.view(-1)\n y_fake_rots_logits = y_fake_rots_logits.view(-1)\n\n # Net discriminator relativistic loss.\n disc_loss = (\n criterion(y_real_logits - torch.mean(y_fake_logits), real_labels)\n + criterion(y_fake_logits - torch.mean(y_real_logits), fake_labels)\n ) / 2\n\n # Compute gradient penalty and add this to the discriminator loss\n # alpha = torch.rand(real_imgs.size(0), 1, 1, 1, device=device)\n # alpha = alpha.expand_as(real_imgs)\n # interpolated = Variable(alpha * real_imgs + (1 - alpha) * fake_imgs, requires_grad=True, device=device)\n # interpolated_logits, _ = disc(interpolated)\n # interpolated_probs = nn.Sigmoid(interpolated_logits)\n # gradients = torch_grad(outputs=interpolated_probs, inputs=interpolated,\n # grad_outputs=torch.ones(interpolated_probs.size(), device=device),\n # create_graph=True, retain_graph=True)[0]\n # gradients = gradients.view(real_imgs.size(0), -1)\n\n # # TODO add these to tensorboard\n # gradients.norm(2, dim=1).sum().data\n\n # gradients_norm = torch.sqrt(torch.sum(gradients ** 2, dim=1) + 1e-12)\n # disc_loss += params[\"gp_weight\"] * ((gradients_norm - 1) ** 2).mean()\n\n # Loss term for rotations\n disc_loss += params[\"rot_weight_d\"] * torch.sum(\n F.binary_cross_entropy_with_logits(\n input=y_real_rots_logits, target=rot_labels\n )\n )\n\n # Backprop\n disc_loss.backward()\n # Update discriminator parameters.\n disc_opt.step()\n\n #################\n # Train generator\n #################\n\n # Make accumulated gradients of the generator zero.\n gen.zero_grad()\n\n y_real_logits, y_real_rots_logits = disc(\n real_imgs\n ) # necessary to avoid gradient problems\n y_real_logits = y_real_logits.view(-1)\n y_real_rots_logits = y_real_rots_logits.view(batch_size * 4, -1)\n y_fake_logits, y_fake_rots_logits = disc(fake_imgs)\n y_fake_logits = y_fake_logits.view(-1)\n y_fake_rots_logits = y_fake_rots_logits.view(batch_size * 4, -1)\n\n gen_loss = (\n criterion(y_real_logits - torch.mean(y_fake_logits), fake_labels)\n + criterion(y_fake_logits - torch.mean(y_real_logits), real_labels)\n ) / 2\n # Gradients for backpropagation are calculated.\n # Gradients w.r.t. both the generator and the discriminator\n # parameters are calculated, however, the generator's optimizer\n # will only update the parameters of the generator. The discriminator\n # gradients will be set to zero in the next iteration by netD.zero_grad()\n\n gen_loss += params[\"rot_weight_g\"] * torch.sum(\n F.binary_cross_entropy_with_logits(\n input=y_fake_rots_logits, target=rot_labels\n )\n )\n\n gen_loss.backward()\n gen_opt.step()\n\n # Logging\n if batches_trained % 100 == 0:\n writer.add_scalar(\"Generator Loss\", gen_loss.item(), batches_trained)\n writer.add_scalar(\"Discriminator Loss\", disc_loss.item(), batches_trained)\n writer.add_scalars(\n \"Loss\",\n {\"Generator\": gen_loss.item(), \"Discriminator\": disc_loss.item(),},\n batches_trained,\n )\n with torch.no_grad():\n fake_data = gen(fixed_visualization_noise).detach().cpu()\n grid = vutils.make_grid(fake_data, padding=2, normalize=True)\n writer.add_image(\"Outputs\", grid, batches_trained)\n\n batches_trained += 1\n\n # Save checkpoint\n if epoch % params[\"save_epoch\"] == 0:\n torch.save(\n {\n \"generator\": gen,\n \"discriminator\": disc,\n \"optimizerG\": gen_opt.state_dict(),\n \"optimizerD\": disc_opt,\n \"params\": params,\n },\n \"model/model_epoch_{}.pth\".format(epoch),\n )\n\n # Logging by epoch (save example output image)\n with torch.no_grad():\n fake_data = gen(fixed_visualization_noise).detach().cpu()\n grid = vutils.make_grid(fake_data, padding=2, normalize=True)\n img_list.append(grid)\n vutils.save_image(grid, f\"outputs/epoch_{epoch}.png\")\n\n# Save final model\ntorch.save(\n {\n \"generator\": gen,\n \"discriminator\": disc,\n \"optimizerG\": gen_opt.state_dict(),\n \"optimizerD\": disc_opt,\n \"params\": params,\n },\n \"model/model_final.pth\",\n)\n\n# Generate animation showing improvements of generator\nfig = plt.figure(figsize=(8, 8))\nplt.axis(\"off\")\nims = [[plt.imshow(np.transpose(i, (1, 2, 0)), animated=True)] for i in img_list]\nanim = animation.ArtistAnimation(fig, ims, interval=1000, repeat_delay=1000, blit=True)\nplt.show()\nanim.save(\"celeba.gif\", dpi=300, writer=\"imagemagick\")\n","sub_path":"ss_rel_dcgan/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"607465997","text":"import os\nimport sys\nimport socket\nimport ping\nimport wmi\nimport pyodbc\nimport pollerconfig\nfrom collections import defaultdict\n\n#test connection\n#uses python3-ping\n#https://github.com/corentone/python3-ping\n#uses WMI 1.4.9\n#https://pypi.org/project/WMI/\n\n\n\n\n\ndef machine_ping(host):\n delay = ping.do_one(host,2)\n if delay == None:\n for i in range(1,13):\n down_ping = ping.do_one(host, 10)\n if down_ping != None:\n break\n else:\n status = 0\n #else invoke alerting process\n else:\n status = 1\n return status\n \n\n'''\nhost.CSName.SerialNumber\nhost.Name.PercentProcessorTime\nhost.FreeMem.FreePhysicalMemory\nhost.TotalMem.Capacity\n\n\n\nWin32_OperatingSystem\n Caption = OS\n CSName = hostname\n FreePhysicalMemory = \"2539960\";\n Manufacturer\n SerialNumber\n Version\n\nWin32_Processor\n 'CPULoad':LoadPercentage\n\nWin32_PhysicalMemory\n 'TotalMem':Capacity\n\nWin32_LogicalDisk\n Caption.FreeSpace\n Caption.Size\n\n'''\n\ndef data_poll(host):\n payload = defaultdict(dict)\n wmi_connection = wmi.WMI(host, user=pollerconfig.wmi_user, password=pollerconfig.wmi_pass)\n\n for item in wmi_connection.Win32_OperatingSystem():\n #Operating System and Free Memory\n payload[host]['Hostname'] = item.CSName\n payload[host]['OS'] = item.Caption\n payload[host]['FreeMem'] = item.FreePhysicalMemory\n\n\n for item in wmi_connection.Win32_Processor():\n\n #CPU Load Percentage\n payload[host]['CPULoad'] = item.LoadPercentage\n \n\n for item in wmi_connection.Win32_PhysicalMemory():\n\n #Total RAM\n payload[host]['TotalMem'] = item.Capacity\n\n for item in wmi_connection.Win32_LogicalDisk():\n print(item)\n #Drive Free and Total Space\n if item.DriveType == 3:\n payload[host][item.Caption+'free'] = item.FreeSpace\n payload[host][item.Caption+'total'] = item.Size\n \n return payload\n \n\n#what can we do about services? WMI?\n\n\n#db stuff\ndef write_to_db(host, data):\n db_conn = pyodbc.connect(\n r'DRIVER={ODBC Driver 13 for SQL Server};'\n r'SERVER=localhost;'\n r'DATABASE=perfmondb;'\n r'UID=%s;PWD=%s;' % (pollerconfig.sql_user,pollerconfig.sql_pass))\n\n cursor = db_conn.cursor()\n #Get NodeID\n cursor.execute(\"SELECT NodeID FROM Nodes WHERE IPAddress LIKE '{}'\".format(host))\n\n for row in cursor:\n nodeid = row[0]\n query1 = \"INSERT INTO CPUStats (NodeID, CPULoad) VALUES ({},{})\".format(nodeid,data['CPULoad'])\n query2 = \"INSERT INTO MemStats (NodeID, FreeMem, Total) VALUES ({},{},{})\".format(nodeid,data['FreeMem'],data['TotalMem'])\n cursor.execute(query1)\n cursor.execute(query2)\n db_conn.commit()\n\n cursor.close()\n db_conn.close()\n\n\n\ndef main():\n host = pollerconfig.host\n payload = data_poll(host)\n #print(payload[host]['Hostname'])\n #write_to_db(host, payload[host])\n\nif __name__ == \"__main__\":\n main()","sub_path":"poller.py","file_name":"poller.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"220763705","text":"class Solution:\n def maxAreaOfIsland(self, grid):\n def dfs(x, y):\n if x < 0 or y < 0 or x == len(grid) or y == len(grid[0]) or grid[x][y] == 0: return 0\n grid[x][y] = 0\n return 1 + dfs(x - 1, y) + dfs(x, y - 1) + dfs(x + 1, y) + dfs(x, y + 1)\n\n ans = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n ans = max(ans, dfs(i, j))\n return ans\n","sub_path":"Python/max-area-of-island.py","file_name":"max-area-of-island.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"540408118","text":"def random_game_engine():\n \"\"\"This function runs a guess game engine where the user\n is expected guess the random number correctly\n by choosing a number between 1 and 1000.\"\"\"\n\n print('Welcome to random game engine...a place where you put your guessing abilities into great test. \\n')\n random_number = 1 + random.randrange(1000)\n reply = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))\n counter = 0\n while reply != random_number:\n random_number = 1 + random.randrange(1000)\n reply = int(input('Guess my number between 1 and 1000 with the fewest guesses:'))\n counter += 1\n if reply > random_number:\n print('Too high. Try again.')\n elif reply < random_number:\n print('Too low. Try again.')\n else:\n print('Congratulations. You guessed the number!')\n if counter < 10:\n print('Either you know the secret or you got lucky!')\n else:\n print('You should be able to do better!')\n user_reply = int(input('Would you like to continue this beautiful game? Enter 1 for yes, 2 for no'))\n if user_reply == 1:\n random_game_engine()\n else:\n print('Thank you for your time. see ya...')\n\n\nrandom_game_engine()","sub_path":"Chapter4 Exercises/random_game_engine_modified.py","file_name":"random_game_engine_modified.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"361942416","text":"# coding: utf-8\n__author__ = 'BinZHOU'\n__version__ = '20180509'\n\nimport os\nimport re\nfrom pprint import pprint\nimport time\nimport jieba\nimport jieba.analyse\nimport jieba.posseg as pseg\nfrom bz_xx import *\n\n# 加载外部词典\njieba.initialize()\njieba.load_userdict('user_dict.txt')\n\n\ndef merge_noun(a):\n idx1 = 0\n ll = []\n while idx1 < len(a):\n fg = False\n word = a[idx1].word\n flag = a[idx1].flag\n idx2 = idx1+1\n while idx2 < len(a):\n if a[idx1].flag in (\"an\",\"Ng\",\"n\",\"nr\",\"ns\",\"nt\",\"nz\",\"vn\") and a[idx2].flag in (\"an\",\"Ng\",\"n\",\"nr\",\"ns\",\"nt\",\"nz\",\"vn\"):\n# if a[idx1].flag[0] == a[idx2].flag[0] == 'n':\n word += a[idx2].word\n idx2 += 1\n fg = True\n else:\n break\n if fg:\n ll.append((word, 'n'))\n else:\n ll.append((word, flag))\n idx1 = idx2\n return ll\n\n\ndef tokenize2(b):\n ll2 = []\n for sen in b:\n word = sen[0]\n flag = sen[1]\n if len(word) == 1:\n ll2.append(word+' '+'S'+flag)\n else:\n ll2 += list(map(lambda x:x[0]+' '+x[1], zip([x for x in word], ['B'+flag]+['M'+flag]*(len(word)-2)+['E'+flag])))\n return ll2\ndef input_user_q(s):\n pseg_cut = pseg.lcut(s.strip().replace(' ',',').replace('\\n',''))\n merge_noun_result = merge_noun(pseg_cut)\n return tokenize2(merge_noun_result)\n\ndef ner_f(st,tagger):\n l = []\n s = ''\n for i in range(tagger.size()):\n if tagger.y2(i) == 'B-N' or tagger.y2(i) == 'M-N':\n s += tagger.x(i,0)\n elif tagger.y2(i) == 'E-N':\n s += tagger.x(i,0)\n l.append(s)\n s = ''\n return l\n\ndef ner_run(tagger, s):\n\ttagger.clear()\n\tl = input_user_q(s)\n\t[tagger.add(x) for x in l]\n\ttagger.parse()\n\n\treturn ner_f(s,tagger)\n\nif __name__ == '__main__':\n\n\t# 读取stop_words.txt 默认启用\n\tstop_w = True\n\tf = open('stop_words.txt','r')\n\tstop_words_list = [line.strip() for line in f.readlines()]\n\n\t# 测试字符串列表\n\tuser_file = open('user_file.txt','r')\n\ttest_list = [line.strip() for line in user_file.readlines()]\n\t# 加入正则使分词细化\n\tfor s in test_list:\n\t\tre_DATE_REG1 = re.compile(DATE_REG1)\n\t\tre_URL_REG = re.compile(URL_REG)\n\t\tre_PHONE_REG = re.compile(PHONE_REG)\n\t\tre_MAIL_REG = re.compile(MAIL_REG)\n\t\tre_IDCARD_REG = re.compile(IDCARD_REG)\n\t\tre_MONEY_REG1 = re.compile(MONEY_REG1)\n\t\tre_MONEY_REG2 = re.compile(MONEY_REG2)\n\t\tre_DATE_REG2 = re.compile(DATE_REG2)\n\t\tre_HYPER_REG = re.compile(HYPER_REG)\n\t\t[jieba.add_word(i,1,'date') for i in re_DATE_REG1.findall(s)]\n\t\t[jieba.add_word(i,1,'url') for i in re_URL_REG.findall(s)]\n\t\t[jieba.add_word(i,1,'phone') for i in re_PHONE_REG.findall(s)]\n\t\t[jieba.add_word(i,1,'mail') for i in re_MAIL_REG.findall(s)]\n\t\t[jieba.add_word(i,1,'idcard') for i in re_IDCARD_REG.findall(s)]\n\t\t[jieba.add_word(i,1,'money') for i in re_MONEY_REG1.findall(s)]\n\t\t[jieba.add_word(i,1,'money') for i in re_MONEY_REG2.findall(s)]\n\t\t[jieba.add_word(i,1,'date') for i in re_DATE_REG2.findall(s)]\n\t\t[jieba.add_word(i,1,'hyper') for i in re_HYPER_REG.findall(s)]\n\n\t# print('词性标注:\\t')\n\t# for s in test_list:\n\t# \tif stop_w:\n\t# \t\tprint([x for x in pseg.lcut(s) if x.word not in stop_words_list])\n\t# \telse:\n\t# \t\tprint(pseg.lcut(s))\n\n\t# print('\\n')\n\t# print('实体识别:\\t')\n\t# # 加载模型\n\t# tagger = CRFPP.Tagger(\"-m model_c2_m256_e0003 -v 3 -n2\")\n\t# for s in test_list:\n\t# \tprint(ner_run(tagger,s))\n\n\t# print('\\n')\n\t# print('动词提取:\\t')\n\t# for s in l:\n\t# \tif stop_w:\n\t# \t\tprint([x.word for x in pseg.lcut(s) if (x.word not in stop_words_list and x.flag == 'v')])\n\t# \telse:\n\t# \t\tprint([x.word for x in pseg.lcut(s) if x.flag == 'v'])\n # 加载模型\n\ttagger = CRFPP.Tagger(\"-m model_c2_m256_e0003 -v 3 -n2\")\n\tfor s in test_list:\n\t\tprint(ner_run(tagger,s) + [x.word for x in pseg.lcut(s) if (x.word not in stop_words_list and x.flag == 'v')])\n","sub_path":"自然语言处理/公共模块/NER/pos_ner_verb0509_list.py","file_name":"pos_ner_verb0509_list.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"344443210","text":"\nfrom __future__ import division\nimport numpy as np\nimport numpy.linalg\nimport math\nfrom IBP import new_K\nfrom IBP import full_X \n\nnp.random.seed(123)\n\ndef gibbs_sampler(X,init_alpha,init_sig_x,init_sig_a,mcmc):\n N = X.shape[0]\n chain_alpha = np.zeros(mcmc)\n chain_sigma_a = np.zeros(mcmc)\n chain_sigma_x = np.zeros(mcmc)\n chain_K = np.zeros(mcmc)\n chain_Z = list()\n #initial matrix Z\n Z = np.array(np.random.choice(2,N,p = [0.5,0.5])).reshape(N,1)\n\n chain_alpha[0] = alpha = init_alpha \n chain_sigma_a[0] = sigma_a = init_sig_a \n chain_sigma_x[0] = sigma_x = init_sig_x\n chain_K[0] = K = 1\n chain_Z.append(Z)\n P = np.zeros(2)\n \n Hn = 0\n for i in range(1,mcmc):\n #gibbs\n alpha = np.random.gamma(1+K,1/(1+Hn))\n print(i,K)\n Hn = 0\n for im in range(0,N): #loop over images\n Hn = Hn + 1/(im+1)\n #sample new Z_i\n for k in range(0,K):#loop over features\n zk_sum = np.sum(Z[:,k])\n if zk_sum == 0:\n lz = -10**5\n else:\n lz = np.log(zk_sum)-np.log(N)\n if zk_sum == N:\n lz0 = -10**5\n else:\n lz0 = np.log(N-zk_sum)-np.log(N)\n Z[im,k] = 1\n P[0] = full_X(Z,X,sigma_x,sigma_a)+lz\n Z[im,k] = 0\n P[1] = full_X(Z,X,sigma_x,sigma_a)+lz0\n\n P=np.exp(P - max(P))\n P[0] = P[0]/(P[0]+P[1])\n if np.random.uniform(0,1,1)(K+new_k):\n Ztemp=Z\n Ztemp[im,K:(K+new_k)]=1 \n else:\n Ztemp=np.zeros((Z.shape[0],K+new_k))\n Ztemp[0:Z.shape[0],0:Z.shape[1]]=Z\n Ztemp[im,K:(K+new_k)] = 1\n\n Z=Ztemp\n K = K + new_k\n\n #sample a new sigma_x and sigma_a with MH,invgamma(2,2) prior/invgamma(1,1) proposal\n #for mh in range(0,5):\n '''propose new sigma_x'''\n current_LH = full_X(Z,X,sigma_x,sigma_a)\n #sig_x_str = sigma_x + (np.random.rand(1)[0]-0.5)\n sig_x_str = 1/np.random.gamma(3,2)#propose a new sigma_x from invgamma(3,2)\n pos_str = full_X(Z,X,sig_x_str,sigma_a)-3*np.log(sig_x_str)-1/(2*sig_x_str)\n pos = current_LH-3*np.log(sigma_x)-1/(2*sigma_x)\n if((pos_str-pos)>0):\n sigma_x = sig_x_str\n else:\n move = np.random.rand(1)\n if(np.log(move[0]) < (pos_str-pos)):\n sigma_x = sig_x_str\n '''propose new sigma_a'''\n #sig_a_str = sigma_a + (np.random.rand(1)[0]-0.5)\n sig_a_str = 1/np.random.gamma(3,2)\n pos_str = full_X(Z,X,sigma_x,sig_a_str)-3*np.log(sig_a_str)-1/(2*sig_a_str)\n pos = current_LH-3*np.log(sigma_a)-1/(2*sigma_a)\n if((pos_str-pos) > 0):\n sigma_a = sig_a_str\n else:\n move = np.random.rand(1)\n if(np.log(move[0]) < (pos_str-pos)):\n sigma_a = sig_a_str\n\n #remove features that have only 1 object\n index = np.sum(Z,0)>1\n Z = Z[:,index]\n K = Z.shape[1]\n\n #store chain values \n chain_alpha[i] = alpha\n chain_sigma_a[i] = sigma_a\n chain_sigma_x[i] = sigma_x\n chain_K[i] = K\n chain_Z.append(Z)\n \n return(chain_alpha,chain_sigma_a,chain_sigma_x,chain_K,chain_Z)","sub_path":"IBP/gibbs.py","file_name":"gibbs.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"348233578","text":"import os\nimport re\nimport glob\nimport time\nfrom datetime import date\n\n_push = 1\n_pull = 2\n\n\nclass ServerInfo:\n def __init__(self, dmap):\n self.mandatory = ['host', 'user', 'password', 'type']\n self.optionals = ['port']\n self.host = ''\n self.password = ''\n self.user = ''\n self.type = ''\n self.port = None\n self.dmap = dmap.copy()\n self.setvals()\n\n def setvals(self):\n for key in self.mandatory:\n if key == 'host':\n self.host = self.dmap[key]\n elif key == 'password':\n self.password = self.dmap[key]\n elif key == 'user':\n self.user = self.dmap[key]\n elif key == 'type':\n self.set_type(self.dmap[key])\n\n for key in self.optionals:\n if key == 'port' and key in self.dmap:\n self.port = self.dmap[key]\n\n def set_type(self, type):\n print(type)\n if type.lower() != 'sftp' and type.lower() != 'ftp' and type.lower() != 'ftp_tls':\n raise Exception(\"TYPE MUST BE sftp, ftp, or ftp_tls\")\n self.type = type.lower()\n\n\nclass TransferFolderContent:\n def __init__(self, dmap, operation):\n self.operation = operation\n self.mandatory = ['source_folders', 'target_folder']\n self.optionals = ['file_type']\n self.source_folders = []\n self.target_folder = ''\n self.file_types = None\n self.source_files = []\n self.dmap = dmap.copy()\n self.setvals()\n self.transfers = []\n\n def get_transfers(self, file_list=None):\n # print(file_list)\n self.process_transfers(file_list=file_list)\n return self.transfers\n\n def process_transfers(self, file_list=None):\n # print(file_list)\n self.transfers = []\n # pull in files from ftp site\n if self.operation == _pull:\n self.source_files = []\n self.gather_files(file_list=file_list)\n for fi in self.source_files:\n filename = os.path.basename(fi)\n self.transfers.append((fi, os.path.join(self.target_folder, filename)))\n\n def setvals(self):\n for key in self.mandatory:\n if key == 'source_folders':\n self.set_source_folders(self.dmap[key])\n elif key == 'target_folder':\n self.target_folder = self.dmap[key]\n\n for key in self.optionals:\n if key == 'file_type':\n if key in self.dmap:\n self.set_file_types(self.dmap[key])\n if self.operation == _push:\n self.gather_files()\n # print(self.source_files)\n\n def set_file_types(self, type_str):\n if \",\" in type_str:\n self.file_types = type_str.split(',')\n else:\n self.file_types = [type_str]\n\n def set_source_folders(self, folder_str):\n if \",\" in folder_str:\n self.source_folders = folder_str.split(',')\n else:\n self.source_folders.append(folder_str)\n\n def gather_files(self, file_list=None):\n if self.operation == _push:\n # from our source folders lets grab all the files we need\n for folder in self.source_folders:\n for fi in os.listdir(folder):\n abs_fi = os.path.join(folder, fi)\n filename, file_extension = os.path.splitext(fi)\n file_extension = file_extension.replace('.', '') # need to strip out the '.'\n # print(file_extension)\n if os.path.isfile(abs_fi):\n if self.file_types is None:\n self.source_files.append(os.path.join(folder, fi))\n else:\n if file_extension in self.file_types:\n self.source_files.append(os.path.join(folder, fi))\n elif self.operation == _pull:\n for fi in file_list:\n # abs_fi = os.path.join(folder,fi)\n filename, file_extension = os.path.splitext(fi)\n file_extension = file_extension.replace('.', '') # need to strip out the '.'\n if self.file_types is None:\n self.source_files.append(fi)\n else:\n if file_extension in self.file_types:\n self.source_files.append(fi)\n\n\nclass TransferFiles:\n def __init__(self, dmap, operation):\n self.operation = operation\n self.mandatory = ['source_files', 'target_folder']\n self.optionals = ['source_dir', 'most_recent']\n self.source_files = []\n self.target_folder = ''\n self.source_dir = None\n self.dmap = dmap.copy()\n self.most_recent = False\n self.setvals()\n self.transfers = []\n\n def get_transfers(self, file_list=None):\n self.process_transfers(file_list=file_list)\n return self.transfers\n\n def process_transfers(self, file_list=None):\n self.transfers = []\n if self.most_recent == True:\n self.get_recent_files()\n\n for fi in self.source_files:\n if self.source_dir is not None:\n fi = os.path.join(self.source_dir, fi)\n filename = os.path.basename(fi)\n self.transfers.append((fi, os.path.join(self.target_folder, filename)))\n\n def get_recent_files(self):\n if self.operation == _pull:\n return False\n new_source_files = []\n for fi in self.source_files:\n if self.source_dir is not None:\n fi = os.path.join(self.source_dir, fi)\n dir = os.path.dirname(fi)\n filename = os.path.basename(fi)\n files = glob.glob(fi + '*')\n files.sort(key=os.path.getmtime)\n\n if len(files) > 0:\n new_source_files.append(files[-1])\n\n if len(new_source_files) > 0:\n del self.source_files[:]\n self.source_files.extend(new_source_files)\n\n return True\n\n def setvals(self):\n for key in self.mandatory:\n if key == 'source_files':\n self.set_source_files(self.dmap[key])\n elif key == 'target_folder':\n self.target_folder = self.dmap[key]\n\n for key in self.optionals:\n if key == 'source_dir' and key in self.dmap:\n self.source_dir = str(self.dmap[key]).replace('\\\\', '/')\n elif key == 'most_recent' and key in self.dmap:\n self.most_recent = self.set_most_recent(self.dmap[key])\n\n def set_most_recent(self, val):\n if val.lower() == 'true':\n return True\n return False\n\n def set_source_files(self, file_str):\n #print('hey')\n if \",\" in file_str:\n self.source_files = file_str.split(',')\n else:\n self.source_files.append(file_str)\n\n # for working with sftp need to convert to unix file path\n for idx in range(len(self.source_files)):\n self.source_files[idx] = str(self.source_files[idx]).replace('\\\\', '/')\n\n\nclass DateTransferFiles(TransferFiles):\n def __init__(self, dmap, operation):\n print(dmap['source_files'])\n super(DateTransferFiles, self).__init__(dmap, operation)\n\n #we will never be performing most recent against this type of search. disabled no matter what\n self.most_recent = False\n self.optionals = ['source_dir']\n\n def process_transfers(self, file_list=None):\n self.transfers = []\n\n for fi in self.source_files:\n if self.operation == _push: # ONLY DO IF WE ARE LOCALLY ON THE SYSTEM CHECKING.\n fi = self.format_date_file(fi)\n if self.source_dir is not None:\n fi = os.path.join(self.source_dir, fi)\n filename = os.path.basename(fi)\n self.transfers.append((fi, os.path.join(self.target_folder, filename)))\n\n def format_date_file(self,fi):\n today = date.today()\n new_fi = today.strftime(fi)\n return new_fi\n\n\"\"\"class PullFolderContent:\n def __init__(self,dmap):\n self.mandatory = ['source_dir','target_folder']\n self.optionals = []\n self.dmap = dmap.copy()\n self.source_dir = ''\n self.target_folder = ''\n self.source_folders = []\n self.source_files = []\n \n def setvals(self):\n for key in self.mandatory:\n if key == 'source_dir':\n self.source_dir = self.dmap[key]\n elif key == 'target_folder':\n self.target_folder = self.dmap[key]\n \n def gather_files(self):\n\"\"\"\n","sub_path":"sectiontypes/sectiontype.py","file_name":"sectiontype.py","file_ext":"py","file_size_in_byte":8595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"251741320","text":"from io import *\r\nimport os\r\n\r\nclass DataBase(object):\r\n def __init__(self, dir_name):\r\n self.dir_name = dir_name\r\n\r\n def get_count(self, file):\r\n db = open(os.path.join(self.dir_name, file))\r\n ans = 0\r\n base = []\r\n line = db.readline()\r\n while line != '==========\\n':\r\n base.append(line)\r\n if line.split('\\t')[0] == 'count_of_lines':\r\n ans = int(line.split('\\t')[1])\r\n line = db.readline()\r\n base.append(line)\r\n return ans, base, db\r\n \r\n def skip(self, file):\r\n db = open(os.path.join(self.dir_name, file))\r\n base = []\r\n line = db.readline()\r\n while line != '==========\\n':\r\n base.append(line)\r\n line = db.readline()\r\n base.append(line)\r\n return base, db\r\n\r\n def add(self, file, task_to_add):\r\n count_of_lines, base, db = self.get_count(file)\r\n count_of_lines += 1\r\n for i in range(len(base)):\r\n base[i] = list(base[i].split('\\t'))\r\n if base[i][0] == 'count_of_lines':\r\n base[i][1] = str(count_of_lines) + '\\n'\r\n base[i] = '\\t'.join(base[i])\r\n is_in_db = False\r\n task = db.readline().rstrip()\r\n #while task != '':\r\n #base.append(task + '\\n')\r\n #task = list(task.split('\\t'))\r\n #if len(task) >= 2 and task[1] == task_to_add:\r\n #is_in_db = True\r\n #task = db.readline().rstrip()\r\n db.close()\r\n db = open(os.path.join(self.dir_name, file), 'w')\r\n for task in base:\r\n db.write(task)\r\n if not is_in_db:\r\n db.write(unicode(count_of_lines) + '\\t' + unicode(task_to_add) + '\\n')\r\n db.close()\r\n\r\n def delete(self, file, pk):\r\n base, db = self.skip(file)\r\n task = db.readline().rstrip()\r\n while task != '':\r\n if int(task.split('\\t')[0]) == pk:\r\n base.append('')\r\n else:\r\n base.append(task + '\\n')\r\n task = db.readline().rstrip()\r\n db.close()\r\n db = open(os.path.join(self.dir_name, file), 'w')\r\n for i in range(len(base)):\r\n db.write(unicode(base[i]))\r\n db.close()\r\n\r\n def get(self, file, pk):\r\n base, db = self.skip(file)\r\n ans = []\r\n for task in db:\r\n if task.split('\\t')[0] == pk:\r\n ans.append(task.split('\\t')[1])\r\n if ans != []:\r\n return ans[0]\r\n else:\r\n return None\r\n\r\n def extract_all(self, file):\r\n base, db = self.skip(file)\r\n ans = [task.split('\\t')[1].rstrip() for task in db]\r\n db.close()\r\n return ans\r\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"499987433","text":"# -*- coding:utf-8 -*-\n__author__ = 'Tnew'\n\nimport pytest\nimport requests\n\n\nclass TestToken:\n #正向测试token:成功\n def test_get_token(self):\n \"\"\"\n 获取access_token\n https://work.weixin.qq.com/api/doc/90000/90135/91039\n :return:\n \"\"\"\n #第一种方式\n # #定义凭证\n # corpid = \"wwca233d5d5e521b32\"\n # corpsecret = \"d8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o\"\n # #去企业微信的接口文档里获取\n # url = f\"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}\"\n # r = requests.get(url)\n # print(r.json())\n\n #第二种方式\n # 定义凭证\n corpid = \"wwca233d5d5e521b32\"\n corpsecret = \"d8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o\"\n params = {\n \"corpid\":corpid,\n \"corpsecret\": corpsecret\n }\n # 去企业微信的接口文档里获取\n url = \"https://qyapi.weixin.qq.com/cgi-bin/gettoken\"\n r = requests.get(url,params=params)\n print(r.json())\n token = r.json()[\"access_token\"]\n print(token)\n assert r.status_code == 200\n assert r.json()['errmsg'] == 'ok'\n\n #异常无法获取token\n @pytest.mark.parametrize('corp_id, corp_secret, errmsg',[\n [\"wwca233d5d5e521b32\",'d8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o','ok'],\n [None,'d8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o','corpid missing'],\n [\"wwca233d5d5e521b32\",None,'corpsecret missing'],\n [\"wwca233d5d5e521b45\",'d8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o','invalid corpid'],\n [\"wwca233d5d5e521b32\",'e8ZdcI76eHMi2oL2qJRA_VcwBUjOQoG-YjvAJ4RJF_o','invalid credential'],\n [\"ww876064acebf0fa32\",\"A7LgEhs_Ty_dYXO9BcgY04PJBdawQ6JPzxNQJpv9Yxc\",'invalid corpid']\n ])\n def test_token(self,corp_id, corp_secret, errmsg):\n \"\"\"\n 正向验证:ok\n 异常逻辑的验证\n 1 不传企业ID\n 2 不传secret\n 3 错误的id\n 4 错误的secret\n 5 不匹配的id和secret\n :return:\n \"\"\"\n params = {\n \"corpid\": corp_id,\n \"corpsecret\": corp_secret\n }\n # 去企业微信的接口文档里获取\n url = \"https://qyapi.weixin.qq.com/cgi-bin/gettoken\"\n r = requests.get(url, params=params)\n print(r.json())\n print(r.json()['errmsg'])\n # token = r.json()[\"access_token\"]\n # print(token)\n print(r.status_code)\n assert r.status_code == 200\n assert errmsg in r.json()['errmsg']","sub_path":"lesson_free_requests/test_wework_accesstoken.py","file_name":"test_wework_accesstoken.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"473496437","text":"from pappyproxy import http\nfrom twisted.internet import defer\n\n\"\"\"\nSchema v4\n\nDescription:\nAdds additional metadata to the database for requests. Mainly it stores the host\nthat a request was sent to so that pappy doesn't have to guess from the host\nheader.\n\"\"\"\n\nupdate_queries = [\n \"\"\"\n ALTER TABLE requests ADD COLUMN host TEXT;\n \"\"\",\n]\n\n@defer.inlineCallbacks\ndef update(dbpool):\n for query in update_queries:\n yield dbpool.runQuery(query)\n\n # Update metadata for each request\n reqrows = yield dbpool.runQuery(\n \"\"\"\n SELECT id, full_request\n FROM requests;\n \"\"\",\n )\n\n # Create an object that will parse the host from the request\n for reqrow in reqrows:\n reqid = reqrow[0]\n fullreq = reqrow[1]\n r = http.Request(fullreq)\n host = r.host\n if r.host:\n yield dbpool.runQuery(\n \"\"\"\n UPDATE requests SET host=? WHERE id=?;\n \"\"\",\n (host, reqid)\n )\n\n yield dbpool.runQuery(\n \"\"\"\n UPDATE schema_meta SET version=4;\n \"\"\"\n )\n","sub_path":"pappyproxy/schema/schema_4.py","file_name":"schema_4.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"478759374","text":"\n# coding: utf-8\n\n# ## MOVIE AWARDS ANALYSIS\n# ### Q4_PART ONE\n# * Use ‘movies_awards’ data set.\n# * You are supposed to extract data from the awards column in this dataset and split it into several columns. An example is given below.\n# * The awards has details of wins, nominations in general and also wins and nominations in certain categories(e.g. Oscar, BAFTA etc.)\n# * You are supposed to create a win and nominated column (these 2 columns contain total number of wins and nominations) and other columns that extract the number of wins and nominations for each category of award.\n# * If a movie has 2 Oscar nominations and 4 Oscar won, the columns Oscar_Awards_Won should have value 4 and Oscar_Awards_Nominated should have value 2. You should also have a total won and nominated column which aggregates all the awards (won or nominated).\n# * Create two separate columns for each award category (won and nominated).\n# * Write your output to a csv file. (Sample output is given in next page)\n\n# In[1]:\n\nfrom pandas import Series, DataFrame\nimport pandas as pd\nimport csv\n\n\n# In[2]:\n\nmovies = pd.read_csv('Data/movies_awards.csv')\n\n\n# In[3]:\n\nmovies.head()\n\n\n# In[13]:\n\ndf1 = DataFrame(movies['Awards'])\n\n\n# In[15]:\n\ndf = df1.dropna()\n\n\n# In[20]:\n\ndf.head(10)\n\n\n# In[68]:\n\ndf.to_csv('simple.csv')\n\n\n# In[ ]:\n\nmovie.title.apply(lambda x : int(x[-5:-1]) if x[-5:-1].isdigit() else 1990 ).tail()\n\n\n# In[23]:\n\ndf.Awards.apply(lambda x : x[0]).value_counts()\n\n\n# In[67]:\n\ndf.Awards.apply(lambda x : x[0]).head()\n\n\n# In[ ]:\n\nsearchfor = ['og', 'at']\ns[s.str.contains('|'.join(searchfor))]\n\n\n# In[ ]:\n\nsearchfor = []\n\n\n# In[93]:\n\nawards_won= df.Awards.apply(lambda x : x[0] if x[0:5].find('win')!= -1 else 0 )\n\n\n# In[95]:\n\nawards_nominated= df.Awards.apply(lambda x : x[0] if x[0:5].find('nom')!= -1 else 0 )\n\n\n# In[ ]:\n\n\n\n\n# In[98]:\n\nN = df.Awards.apply(lambda x : x if x.startswith('N') else 0 )\n\n\n# In[129]:\n\n# N.head(10)\n\n\n# In[121]:\n\nN1 = df.Awards.apply(lambda x : x[0:16] if x.startswith('N') else 0)\n\n\n# In[124]:\n\n# N1\n\n\n# In[128]:\n\n# awards_won = df.Awards.apply(lambda x : x[0] if x[0:5].find('win')!= -1 else x )\n\n\n# In[127]:\n\n# df2.head()\n\n\n# In[126]:\n\n# Awards_Won.head()\n\n\n# In[125]:\n\n# df.Awards.apply(lambda x : (x[0:5]))\n\n\n# In[ ]:\n\ndf.Awards.apply(lambda x : int(x[-5:-1]) if x[-5:-1].isdigit() else 1990 ).tail()\n\n","sub_path":"Assignment3/Q4_Part1/Q4_PART+ONE.py","file_name":"Q4_PART+ONE.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"497985877","text":"\"\"\"\ncreated by: ishida\ndate: 2190417\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\nclass boolean_int():\n def __init__(self):\n print('start')\n\n def make_int_file(self, save_path, save_file_name, data_file):\n print(data_file)\n df = pd.read_csv(data_file)\n \"\"\"\n Ch1 = np.array(df['Ch1'])\n Ch2 = np.array(df['Ch2'])\n Ch3 = np.array(df['Ch3'])\n Ch4 = np.array(df['Ch4'])\n \"\"\"\n Ch1 = np.array(df['0'])\n Ch2 = np.array(df['1'])\n Ch3 = np.array(df['2'])\n Ch4 = np.array(df['3'])\n\n int_Ch1 = np.zeros(len(Ch1))\n int_Ch2 = np.zeros(len(Ch2))\n int_Ch3 = np.zeros(len(Ch3))\n int_Ch4 = np.zeros(len(Ch4))\n\n for i in range(0, len(Ch1)):\n int_Ch1[i] = int(Ch1[i])\n int_Ch2[i] = int(Ch2[i])\n int_Ch3[i] = int(Ch3[i])\n int_Ch4[i] = int(Ch4[i])\n\n df = pd.DataFrame({'Ch1': int_Ch1,\n 'Ch2': int_Ch2,\n 'Ch3': int_Ch3,\n 'Ch4': int_Ch4})\n\n df.to_csv(save_path + '/' + save_file_name + '.csv')\n\n def compare_array(self, data_file1, data_file2):\n print(data_file1)\n print(data_file2)\n df1 = pd.read_csv(data_file1)\n df2 = pd.read_csv(data_file2)\n\n df1_Ch1 = np.array(df1['Ch1'])\n df1_Ch2 = np.array(df1['Ch2'])\n df1_Ch3 = np.array(df1['Ch3'])\n df1_Ch4 = np.array(df1['Ch4'])\n\n df2_Ch1 = np.array(df2['Ch1'])\n df2_Ch2 = np.array(df2['Ch2'])\n df2_Ch3 = np.array(df2['Ch3'])\n df2_Ch4 = np.array(df2['Ch4'])\n\n print('Ch1 : ' + str((df1_Ch1 == df2_Ch1).all()))\n print('Ch2 : ' + str((df1_Ch2 == df2_Ch2).all()))\n print('Ch3 : ' + str((df1_Ch3 == df2_Ch3).all()))\n print('Ch4 : ' + str((df1_Ch4 == df2_Ch4).all()))\n\n\ndef main():\n save_path = 'C:/Users/ishida/Desktop'\n save_file_name = 'pulse_int' # .csv\n data_file = 'C:/Users/ishida/Desktop/pulse.csv'\n\n data_file1 = 'C:/Users/ishida/Desktop/Hahn_echo.csv'\n data_file2 = 'C:/Users/ishida/Desktop/pulse_int.csv'\n\n c = boolean_int()\n # c.make_int_file(save_path, save_file_name, data_file)\n c.compare_array(data_file1, data_file2)\n\n\nif __name__ == '__main__':\n main()","sub_path":"nagaoka_san/boolean_to_int.py","file_name":"boolean_to_int.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"424680272","text":"import subprocess\nimport platform\n\ndef getSubnet(ip):\n system = platform.system()\n if system == 'Windows':\n proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE)\n while True:\n line = proc.stdout.readline()\n if ip.encode() in line:\n break\n mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ',b'').decode()\n elif system == 'Linux':\n proc = subprocess.Popen('ifconfig', stdout=subprocess.PIPE)\n line = proc.stdout.read().split('\\n')[1]\n mask = line.split('Mask:')[1]\n else:\n raise Exception('os not compatible')\n return mask\n\n","sub_path":"getSubnetmask.py","file_name":"getSubnetmask.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"545931777","text":"import os\r\nos.chdir('C:\\python_exercise')\r\nknown_reducible={'':1,'i':1,'a':1}\r\n\r\ndef read_wordlist(filename='words.txt'):\r\n \"\"\"\r\n\"\"\"\r\n wordlist=dict()\r\n fin=open(filename)\r\n for a in fin:\r\n word=a.strip()\r\n wordlist[word]=1\r\n wordlist['']=1\r\n wordlist['a']=1\r\n wordlist['i']=1\r\n return wordlist\r\n\r\n\r\ndef word_children(word,word_dic):\r\n cdict=dict()\r\n mword=list(word)\r\n for i in range(len(mword)):\r\n temp=mword[:]\r\n del temp[i]\r\n newword=''.join(temp)\r\n if newword in word_dic:\r\n cdict[newword]=1\r\n return cdict\r\n\r\ndef is_reducible(word,word_dic):\r\n global known_reducible\r\n if word in known_reducible:\r\n return True\r\n a=word_children(word,word_dic)\r\n if len(a)==0:\r\n return False\r\n else:\r\n for cword in a:\r\n tempflag=is_reducible(cword,word_dic)\r\n if tempflag:\r\n known_reducible[word]=1\r\n return True\r\n return False\r\n\r\ndef find_all_red(word_dic):\r\n final_reducible=dict()\r\n for key in word_dic:\r\n if is_reducible(key,word_dic):\r\n final_reducible[key]=1\r\n return final_reducible\r\n\r\ndef red_sort(red_dict):\r\n b=list(red_dict)\r\n len_list=[]\r\n for word in b:\r\n len_list.append(len(word))\r\n dec_list=list(zip(len_list,b))\r\n dec_list.sort(reverse=True)\r\n return dec_list\r\n \r\ndef print_reduce_word(word,word_dict,all_red):\r\n print(word)\r\n a=word_children(word,word_dict)\r\n if len(a)!=0:\r\n for i in a:\r\n if i in all_red:\r\n print_reduce_word(i,word_dict,all_red)\r\n \r\n\r\nif __name__=='__main__':\r\n word_dict=read_wordlist()\r\n a=find_all_red(word_dict)\r\n b=red_sort(a)\r\n previous=b[0][0]\r\n \r\n for length,word in b:\r\n if length!=previous:\r\n break\r\n print(word)\r\n previous=length\r\n\r\n print_reduce_word('complecting',word_dict,a)\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"twelve_six.py","file_name":"twelve_six.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"259149934","text":"\"\"\"user ratings\n\nRevision ID: a218054e0936\nRevises: \nCreate Date: 2019-09-07 14:51:45.744269\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a218054e0936'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('movies',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('movieid', sa.Integer(), nullable=True),\n sa.Column('moviename', sa.String(length=64), nullable=True),\n sa.Column('genre', sa.String(length=256), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_movies_movieid'), 'movies', ['movieid'], unique=False)\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=120), nullable=True),\n sa.Column('password_hash', sa.String(length=15), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)\n op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)\n op.create_table('users',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('userid', sa.Integer(), nullable=True),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=120), nullable=True),\n sa.Column('password', sa.String(length=15), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=False)\n op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)\n op.create_index(op.f('ix_users_userid'), 'users', ['userid'], unique=False)\n op.create_table('interactions',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('userid', sa.Integer(), nullable=True),\n sa.Column('movieid', sa.String(length=120), nullable=True),\n sa.Column('rating', sa.Integer(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['movieid'], ['movies.movieid'], ),\n sa.ForeignKeyConstraint(['userid'], ['users.userid'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_interactions_id'), 'interactions', ['id'], unique=False)\n op.create_index(op.f('ix_interactions_timestamp'), 'interactions', ['timestamp'], unique=False)\n op.create_table('post',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('body', sa.String(length=140), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_post_timestamp'), table_name='post')\n op.drop_table('post')\n op.drop_index(op.f('ix_interactions_timestamp'), table_name='interactions')\n op.drop_index(op.f('ix_interactions_id'), table_name='interactions')\n op.drop_table('interactions')\n op.drop_index(op.f('ix_users_userid'), table_name='users')\n op.drop_index(op.f('ix_users_id'), table_name='users')\n op.drop_index(op.f('ix_users_email'), table_name='users')\n op.drop_table('users')\n op.drop_index(op.f('ix_user_username'), table_name='user')\n op.drop_index(op.f('ix_user_email'), table_name='user')\n op.drop_table('user')\n op.drop_index(op.f('ix_movies_movieid'), table_name='movies')\n op.drop_table('movies')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a218054e0936_user_ratings.py","file_name":"a218054e0936_user_ratings.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"108955619","text":"# | Copyright 2007-2016 Karlsruhe Institute of Technology\n# |\n# | Licensed under the Apache License, Version 2.0 (the \"License\");\n# | you may not use this file except in compliance with the License.\n# | You may obtain a copy of the License at\n# |\n# | http://www.apache.org/licenses/LICENSE-2.0\n# |\n# | Unless required by applicable law or agreed to in writing, software\n# | distributed under the License is distributed on an \"AS IS\" BASIS,\n# | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# | See the License for the specific language governing permissions and\n# | limitations under the License.\n\nimport os, sys, glob, stat, time, signal, fnmatch, logging, operator\nfrom grid_control.gc_exceptions import GCError, InstallationError, UserError\nfrom grid_control.utils.activity import Activity\nfrom grid_control.utils.data_structures import UniqueList\nfrom grid_control.utils.parsing import parseBool, parseType, strDict\nfrom grid_control.utils.process_base import LocalProcess\nfrom grid_control.utils.table import ColumnTable, ParseableTable, RowTable\nfrom grid_control.utils.thread_tools import TimeoutException, hang_protection\nfrom hpfwk import clear_current_exception\nfrom python_compat import exit_without_cleanup, get_user_input, identity, ifilter, imap, irange, lfilter, lmap, lru_cache, lzip, next, reduce, sorted, tarfile\n\ndef execWrapper(script, context = None):\n\tif context is None:\n\t\tcontext = dict()\n\texec(script, context) # pylint:disable=exec-used\n\treturn context\n\ndef QM(cond, a, b):\n\tif cond:\n\t\treturn a\n\treturn b\n\ndef swap(a, b):\n\treturn (b, a)\n\n################################################################\n# Path helper functions\n\ncleanPath = lambda x: os.path.normpath(os.path.expandvars(os.path.expanduser(x.strip())))\n\ndef getRootName(fn): # Return file name without extension\n\tbn = os.path.basename(str(fn)).lstrip('.')\n\treturn QM('.' in bn, str.join('', bn.split('.')[:-1]), bn)\n\ndef pathPKG(*args):\n\treturn cleanPath(os.path.join(os.environ['GC_PACKAGES_PATH'], *args))\n\ndef pathShare(*args, **kw):\n\treturn pathPKG(kw.get('pkg', 'grid_control'), 'share', *args)\n\ndef resolvePaths(path, searchPaths = None, mustExist = True, ErrorClass = GCError):\n\tpath = cleanPath(path) # replace $VAR, ~user, \\ separators\n\tresult = []\n\tif os.path.isabs(path):\n\t\tresult.extend(sorted(glob.glob(path))) # Resolve wildcards for existing files\n\t\tif not result:\n\t\t\tif mustExist:\n\t\t\t\traise ErrorClass('Could not find file \"%s\"' % path)\n\t\t\treturn [path] # Return non-existing, absolute path\n\telse: # search relative path in search directories\n\t\tsearchPaths = searchPaths or []\n\t\tfor spath in UniqueList(searchPaths):\n\t\t\tresult.extend(sorted(glob.glob(cleanPath(os.path.join(spath, path)))))\n\t\tif not result:\n\t\t\tif mustExist:\n\t\t\t\traise ErrorClass('Could not find file \"%s\" in \\n\\t%s' % (path, str.join('\\n\\t', searchPaths)))\n\t\t\treturn [path] # Return non-existing, relative path\n\treturn result\n\n\ndef resolvePath(path, searchPaths = None, mustExist = True, ErrorClass = GCError):\n\tresult = resolvePaths(path, searchPaths, mustExist, ErrorClass)\n\tif len(result) > 1:\n\t\traise ErrorClass('Path \"%s\" matches multiple files:\\n\\t%s' % (path, str.join('\\n\\t', result)))\n\treturn result[0]\n\n\ndef resolveInstallPath(path):\n\tresult = resolvePaths(path, UniqueList(os.environ['PATH'].split(os.pathsep)), True, InstallationError)\n\tresult_exe = lfilter(lambda fn: os.access(fn, os.X_OK), result) # filter executable files\n\tif not result_exe:\n\t\traise InstallationError('Files matching %s:\\n\\t%s\\nare not executable!' % (path, str.join('\\n\\t', result_exe)))\n\treturn result_exe[0]\n\n\ndef ensureDirExists(dn, name = 'directory', ExceptionClass = GCError):\n\tif not os.path.exists(dn):\n\t\ttry:\n\t\t\tos.makedirs(dn)\n\t\texcept Exception:\n\t\t\traise ExceptionClass('Problem creating %s \"%s\"' % (name, dn))\n\treturn dn\n\n\ndef freeSpace(dn, timeout = 5):\n\tdef freeSpace_int():\n\t\tif os.path.exists(dn):\n\t\t\ttry:\n\t\t\t\tstat_info = os.statvfs(dn)\n\t\t\t\treturn stat_info.f_bavail * stat_info.f_bsize / 1024**2\n\t\t\texcept Exception:\n\t\t\t\timport ctypes\n\t\t\t\tfree_bytes = ctypes.c_ulonglong(0)\n\t\t\t\tctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dn), None, None, ctypes.pointer(free_bytes))\n\t\t\t\treturn free_bytes.value / 1024**2\n\t\treturn -1\n\n\ttry:\n\t\treturn hang_protection(freeSpace_int, timeout)\n\texcept TimeoutException:\n\t\tsys.stderr.write(\n\t\t\t'Unable to get free disk space for directory %s after waiting for %d sec!\\n' % (dn, timeout) +\n\t\t\t'The file system is probably hanging or corrupted - try to check the free disk space manually. ' +\n\t\t\t'Refer to the documentation to disable checking the free disk space - at your own risk')\n\t\texit_without_cleanup(os.EX_OSERR)\n\n\n################################################################\n# Global state functions\n\ndef globalSetupProxy(fun, default, new = None):\n\tif new is not None:\n\t\tfun.setting = new\n\ttry:\n\t\treturn fun.setting\n\texcept Exception:\n\t\treturn default\n\n\ndef abort(new = None):\n\treturn globalSetupProxy(abort, False, new)\n\n\n################################################################\n# Dictionary tools\n\nclass Result(object): # Use with caution! Compared with tuples: +25% accessing, 8x slower instantiation\n\tdef __init__(self, **kwargs):\n\t\tself.__dict__ = kwargs\n\tdef __repr__(self):\n\t\treturn 'Result(%s)' % strDict(self.__dict__)\n\n\ndef mergeDicts(dicts):\n\ttmp = dict()\n\tfor x in dicts:\n\t\ttmp.update(x)\n\treturn tmp\n\n\ndef intersectDict(dictA, dictB):\n\tfor keyA in list(dictA.keys()):\n\t\tif (keyA in dictB) and (dictA[keyA] != dictB[keyA]):\n\t\t\tdictA.pop(keyA)\n\n\ndef replaceDict(result, allVars, varMapping = None):\n\tfor (virtual, real) in (varMapping or lzip(allVars.keys(), allVars.keys())):\n\t\tfor delim in ['@', '__']:\n\t\t\tresult = result.replace(delim + virtual + delim, str(allVars.get(real, '')))\n\treturn result\n\n\ndef filterDict(dictType, kF = lambda k: True, vF = lambda v: True):\n\tdef filterItems(k_v):\n\t\treturn kF(k_v[0]) and vF(k_v[1])\n\treturn dict(ifilter(filterItems, dictType.items()))\n\n\nclass PersistentDict(dict):\n\tdef __init__(self, filename, delimeter = '=', lowerCaseKey = True):\n\t\tdict.__init__(self)\n\t\tself.fmt = DictFormat(delimeter)\n\t\tself.filename = filename\n\t\tkeyParser = {None: QM(lowerCaseKey, lambda k: parseType(k.lower()), parseType)}\n\t\ttry:\n\t\t\tself.update(self.fmt.parse(open(filename), keyParser = keyParser))\n\t\texcept Exception:\n\t\t\tclear_current_exception()\n\t\tself.olddict = self.items()\n\n\tdef get(self, key, default = None, autoUpdate = True):\n\t\tvalue = dict.get(self, key, default)\n\t\tif autoUpdate:\n\t\t\tself.write({key: value})\n\t\treturn value\n\n\tdef write(self, newdict = None, update = True):\n\t\tif not update:\n\t\t\tself.clear()\n\t\tself.update(newdict or {})\n\t\tif dict(self.olddict) == dict(self.items()):\n\t\t\treturn\n\t\ttry:\n\t\t\tif self.filename:\n\t\t\t\tsafeWrite(open(self.filename, 'w'), self.fmt.format(self))\n\t\texcept Exception:\n\t\t\traise GCError('Could not write to file %s' % self.filename)\n\t\tself.olddict = self.items()\n\n\n################################################################\n# File IO helper\n\ndef safeWrite(fp, content):\n\tfp.writelines(content)\n\tfp.truncate()\n\tfp.close()\n\n\ndef renameFile(old, new):\n\tif os.path.exists(new):\n\t\tos.unlink(new)\n\tos.rename(old, new)\n\n\ndef removeFiles(args):\n\tfor item in args:\n\t\ttry:\n\t\t\tif os.path.isdir(item):\n\t\t\t\tos.rmdir(item)\n\t\t\telse:\n\t\t\t\tos.unlink(item)\n\t\texcept Exception:\n\t\t\tclear_current_exception()\n\n\n################################################################\n# String manipulation\n\ndef optSplit(opt, delim, empty = ''):\n\t\"\"\" Split option strings into fixed tuples\n\t>>> optSplit('abc : ghi # def', ['#', ':'])\n\t('abc', 'def', 'ghi')\n\t>>> optSplit('abc:def', '::')\n\t('abc', 'def', '')\n\t\"\"\"\n\tdef getDelimeterPart(oldResult, prefix):\n\t\ttry:\n\t\t\ttmp = oldResult[0].split(prefix)\n\t\t\tnew = tmp.pop(1)\n\t\t\ttry: # Find position of other delimeters in string\n\t\t\t\totherDelim = min(ifilter(lambda idx: idx >= 0, imap(new.find, delim)))\n\t\t\t\ttmp[0] += new[otherDelim:]\n\t\t\texcept Exception:\n\t\t\t\totherDelim = None\n\t\t\treturn [str.join(prefix, tmp)] + oldResult[1:] + [new[:otherDelim]]\n\t\texcept Exception:\n\t\t\treturn oldResult + ['']\n\tresult = imap(str.strip, reduce(getDelimeterPart, delim, [opt]))\n\treturn tuple(imap(lambda x: QM(x == '', empty, x), result))\n\n################################################################\n\nclass TwoSidedIterator(object):\n\tdef __init__(self, allInfo):\n\t\t(self.allInfo, self.left, self.right) = (allInfo, 0, 0)\n\tdef forward(self):\n\t\twhile self.left + self.right < len(self.allInfo):\n\t\t\tself.left += 1\n\t\t\tyield self.allInfo[self.left - 1]\n\tdef backward(self):\n\t\twhile self.left + self.right < len(self.allInfo):\n\t\t\tself.right += 1\n\t\t\tyield self.allInfo[len(self.allInfo) - self.right]\n\n\ndef accumulate(iterable, empty, doEmit, doAdd = lambda item, buffer: True, opAdd = operator.add):\n\tbuf = empty\n\tfor item in iterable:\n\t\tif doAdd(item, buf):\n\t\t\tbuf = opAdd(buf, item)\n\t\tif doEmit(item, buf):\n\t\t\tif buf != empty:\n\t\t\t\tyield buf\n\t\t\tbuf = empty\n\tif buf != empty:\n\t\tyield buf\n\n\ndef wrapList(value, length, delimLines = ',\\n', delimEntries = ', '):\n\tcounter = lambda item, buffer: len(item) + sum(imap(len, buffer)) + 2*len(buffer) > length\n\twrapped = accumulate(value, [], counter, opAdd = lambda x, y: x + [y])\n\treturn str.join(delimLines, imap(lambda x: str.join(delimEntries, x), wrapped))\n\n\ndef DiffLists(oldList, newList, keyFun, changedFkt, isSorted = False):\n\t(listAdded, listMissing, listChanged) = ([], [], [])\n\tif not isSorted:\n\t\t(newList, oldList) = (sorted(newList, key = keyFun), sorted(oldList, key = keyFun))\n\t(newIter, oldIter) = (iter(newList), iter(oldList))\n\t(new, old) = (next(newIter, None), next(oldIter, None))\n\twhile True:\n\t\tif (new is None) or (old is None):\n\t\t\tbreak\n\t\tkeyNew = keyFun(new)\n\t\tkeyOld = keyFun(old)\n\t\tif keyNew < keyOld: # new[npos] < old[opos]\n\t\t\tlistAdded.append(new)\n\t\t\tnew = next(newIter, None)\n\t\telif keyNew > keyOld: # new[npos] > old[opos]\n\t\t\tlistMissing.append(old)\n\t\t\told = next(oldIter, None)\n\t\telse: # new[npos] == old[opos] according to *active* comparison\n\t\t\tchangedFkt(listAdded, listMissing, listChanged, old, new)\n\t\t\t(new, old) = (next(newIter, None), next(oldIter, None))\n\twhile new is not None:\n\t\tlistAdded.append(new)\n\t\tnew = next(newIter, None)\n\twhile old is not None:\n\t\tlistMissing.append(old)\n\t\told = next(oldIter, None)\n\treturn (listAdded, listMissing, listChanged)\n\n\ndef splitBlackWhiteList(bwfilter):\n\tblacklist = lmap(lambda x: x[1:], ifilter(lambda x: x.startswith('-'), bwfilter or []))\n\twhitelist = lfilter(lambda x: not x.startswith('-'), bwfilter or [])\n\treturn (blacklist, whitelist)\n\n\nclass DictFormat(object):\n\t# escapeString = escape '\"', '$'\n\t# types = preserve type information\n\tdef __init__(self, delimeter = '=', escapeString = False):\n\t\tself.delimeter = delimeter\n\t\tself.escapeString = escapeString\n\n\t# Parse dictionary lists\n\tdef parse(self, lines, keyParser = None, valueParser = None):\n\t\tkeyParser = keyParser or {}\n\t\tvalueParser = valueParser or {}\n\t\tdefaultKeyParser = keyParser.get(None, lambda k: parseType(k.lower()))\n\t\tdefaultValueParser = valueParser.get(None, parseType)\n\t\tdata = {}\n\t\tdoAdd = False\n\t\tcurrentline = ''\n\t\ttry:\n\t\t\tlines = lines.splitlines()\n\t\texcept Exception:\n\t\t\tclear_current_exception()\n\t\tfor line in lines:\n\t\t\ttry:\n\t\t\t\tif not isinstance(line, str):\n\t\t\t\t\tline = line.decode('utf-8')\n\t\t\t\tif self.escapeString:\n\t\t\t\t\t# Switch accumulate on/off when odd number of quotes found\n\t\t\t\t\tif (line.count('\"') - line.count('\\\\\"')) % 2 == 1:\n\t\t\t\t\t\tdoAdd = not doAdd\n\t\t\t\t\tcurrentline += line\n\t\t\t\t\tif doAdd:\n\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tcurrentline = line\n\t\t\t\t# split at first occurence of delimeter and strip spaces around\n\t\t\t\tkey_value_list = lmap(str.strip, currentline.split(self.delimeter, 1))\n\t\t\t\tif len(key_value_list) == 2:\n\t\t\t\t\tkey, value = key_value_list\n\t\t\t\t\tcurrentline = ''\n\t\t\t\telse: # in case no delimeter was found\n\t\t\t\t\tcurrentline = ''\n\t\t\t\t\tcontinue\n\t\t\t\tif self.escapeString:\n\t\t\t\t\tvalue = value.strip('\"').replace('\\\\\"', '\"').replace('\\\\$', '$')\n\t\t\t\tkey = keyParser.get(key, defaultKeyParser)(key)\n\t\t\t\tdata[key] = valueParser.get(key, defaultValueParser)(value) # do .encode('utf-8') ?\n\t\t\texcept Exception:\n\t\t\t\traise GCError('Invalid dict format in %s' % repr(line))\n\t\tif doAdd:\n\t\t\traise GCError('Invalid dict format in %s' % repr(lines))\n\t\treturn data\n\n\t# Format dictionary list\n\tdef format(self, entries, printNone = False, fkt = lambda x_y_z: x_y_z, format = '%s%s%s\\n'):\n\t\tresult = []\n\t\tfor key in sorted(entries.keys()):\n\t\t\tvalue = entries[key]\n\t\t\tif value is None and not printNone:\n\t\t\t\tcontinue\n\t\t\tif self.escapeString and isinstance(value, str):\n\t\t\t\tvalue = '\"%s\"' % str(value).replace('\"', '\\\\\"').replace('$', '\\\\$')\n\t\t\t\tlines = value.splitlines()\n\t\t\t\tresult.append(format % fkt((key, self.delimeter, lines[0])))\n\t\t\t\tresult.extend(imap(lambda x: x + '\\n', lines[1:]))\n\t\t\telse:\n\t\t\t\tresult.append(format % fkt((key, self.delimeter, value)))\n\t\treturn result\n\n\ndef matchFileName(fn, patList):\n\tmatch = None\n\tfor p in patList:\n\t\tif fnmatch.fnmatch(fn, p.lstrip('-')):\n\t\t\tmatch = not p.startswith('-')\n\treturn match\n\n\ndef matchFiles(pathRoot, pattern, pathRel = ''):\n\t# Return (root, fn, state) - state: None == dir, True/False = (un)checked file, other = filehandle\n\tyield (pathRoot, pathRel, None)\n\tfor name in imap(lambda x: os.path.join(pathRel, x), os.listdir(os.path.join(pathRoot, pathRel))):\n\t\tmatch = matchFileName(name, pattern)\n\t\tpathAbs = os.path.join(pathRoot, name)\n\t\tif match is False:\n\t\t\tcontinue\n\t\telif os.path.islink(pathAbs): # Not excluded symlinks\n\t\t\tyield (pathAbs, name, True)\n\t\telif os.path.isdir(pathAbs): # Recurse into directories\n\t\t\tif match is True: # (backwards compat: add parent directory - not needed?)\n\t\t\t\tyield (pathAbs, name, True)\n\t\t\tfor result in matchFiles(pathRoot, QM(match is True, ['*'], pattern), name):\n\t\t\t\tyield result\n\t\telif match is True: # Add matches\n\t\t\tyield (pathAbs, name, True)\n\n\ndef genTarball(outFile, fileList):\n\ttar = tarfile.open(outFile, 'w:gz')\n\tactivity = Activity('Generating tarball')\n\tfor (pathAbs, pathRel, pathStatus) in fileList:\n\t\tif pathStatus is True: # Existing file\n\t\t\ttar.add(pathAbs, pathRel, recursive = False)\n\t\telif pathStatus is False: # Existing file\n\t\t\tif not os.path.exists(pathAbs):\n\t\t\t\traise UserError('File %s does not exist!' % pathRel)\n\t\t\ttar.add(pathAbs, pathRel, recursive = False)\n\t\telif pathStatus is None: # Directory\n\t\t\tactivity.update('Generating tarball: %s' % pathRel)\n\t\telse: # File handle\n\t\t\tinfo, handle = pathStatus.getTarInfo()\n\t\t\tinfo.mtime = time.time()\n\t\t\tinfo.mode = stat.S_IRUSR + stat.S_IWUSR + stat.S_IRGRP + stat.S_IROTH\n\t\t\tif info.name.endswith('.sh') or info.name.endswith('.py'):\n\t\t\t\tinfo.mode += stat.S_IXUSR + stat.S_IXGRP + stat.S_IXOTH\n\t\t\ttar.addfile(info, handle)\n\t\t\thandle.close()\n\tactivity.finish()\n\ttar.close()\n\n\ndef getVersion():\n\ttry:\n\t\tproc_ver = LocalProcess('svnversion', '-c', pathPKG())\n\t\tversion = proc_ver.get_output(timeout = 10).strip()\n\t\tif version != '':\n\t\t\tassert(lfilter(str.isdigit, version))\n\t\t\tproc_branch = LocalProcess('svn info', pathPKG())\n\t\t\tif 'stable' in proc_branch.get_output(timeout = 10):\n\t\t\t\treturn '%s - stable' % version\n\t\t\treturn '%s - testing' % version\n\texcept Exception:\n\t\tclear_current_exception()\n\treturn __import__('grid_control').__version__ + ' or later'\ngetVersion = lru_cache(getVersion)\n\n\ndef wait(timeout):\n\tactivity = Activity('Waiting', parent = 'root')\n\tfor remaining in irange(timeout, 0, -1):\n\t\tif abort():\n\t\t\treturn False\n\t\tif (remaining == timeout) or (remaining < 5) or (remaining % 5 == 0):\n\t\t\tactivity.update('Waiting for %d seconds' % remaining)\n\t\ttime.sleep(1)\n\tactivity.finish()\n\treturn True\n\n\ndef printTabular(head, data, fmtString = '', fmt = None):\n\tif printTabular.mode == 'parseable':\n\t\treturn ParseableTable(head, data, '|')\n\telif printTabular.mode == 'longlist':\n\t\treturn RowTable(head, data, fmt, printTabular.wraplen)\n\treturn ColumnTable(head, data, fmtString, fmt, printTabular.wraplen)\nprintTabular.wraplen = 100\nprintTabular.mode = 'default'\n\n\ndef getUserInput(text, default, choices, parser = identity):\n\twhile True:\n\t\thandler = signal.signal(signal.SIGINT, signal.SIG_DFL)\n\t\ttry:\n\t\t\tuserinput = get_user_input('%s %s: ' % (text, '[%s]' % default))\n\t\texcept Exception:\n\t\t\tsys.stdout.write('\\n') # continue on next line\n\t\t\traise\n\t\tsignal.signal(signal.SIGINT, handler)\n\t\tif userinput == '':\n\t\t\treturn parser(default)\n\t\tif parser(userinput) is not None:\n\t\t\treturn parser(userinput)\n\t\tvalid = str.join(', ', imap(lambda x: '\"%s\"' % x, choices[:-1]))\n\t\tlogging.getLogger('console').critical('Invalid input! Answer with %s or \"%s\"', valid, choices[-1])\n\n\ndef getUserBool(text, default):\n\treturn getUserInput(text, QM(default, 'yes', 'no'), ['yes', 'no'], parseBool)\n\n\ndef deprecated(text):\n\tsys.stderr.write('%s\\n[DEPRECATED] %s\\n' % (open(pathShare('fail.txt'), 'r').read(), text))\n\tif not getUserBool('Do you want to continue?', False):\n\t\tsys.exit(os.EX_TEMPFAIL)\n\n\ndef exitWithUsage(usage, msg = None, show_help = True):\n\tsys.stderr.write('Syntax: %s\\n%s' % (usage, QM(show_help, 'Use --help to get a list of options!\\n', '')))\n\tsys.stderr.write(QM(msg, '%s\\n' % msg, ''))\n\tsys.exit(os.EX_USAGE)\n\n\ndef ping_host(host):\n\tproc = LocalProcess('ping', '-Uqnc', 1, '-W', 1, host)\n\ttry:\n\t\ttmp = proc.get_output(timeout = 1).splitlines()\n\t\tassert(tmp[-1].endswith('ms'))\n\t\treturn float(tmp[-1].split('/')[-2]) / 1000.\n\texcept Exception:\n\t\treturn None\n\n\ndef display_selection(log, items_before, items_after, message, formatter):\n\tif len(items_before) != len(items_after):\n\t\tlog.log(logging.DEBUG, message, (len(items_before) - len(items_after)))\n\t\tfor item in items_before:\n\t\t\tif item in items_after:\n\t\t\t\tlog.log(logging.DEBUG1, ' * %s', formatter(item))\n\t\t\telse:\n\t\t\t\tlog.log(logging.DEBUG1, ' %s', formatter(item))\n\n\ndef filter_processors(processorList, id_fun = lambda proc: proc.__class__.__name__):\n\t(result, processorIDs) = ([], [])\n\tfor proc in processorList:\n\t\tif proc.enabled() and (id_fun(proc) not in processorIDs):\n\t\t\tresult.append(proc)\n\t\t\tprocessorIDs.append(id_fun(proc))\n\treturn result\n\n\ndef prune_processors(do_prune, processorList, log, message, formatter = None, id_fun = None):\n\tdef get_class_name(proc):\n\t\treturn proc.__class__.__name__\n\tselected = filter_processors(processorList, id_fun or get_class_name)\n\tdisplay_selection(log, processorList, selected, message, formatter or get_class_name)\n\treturn selected\n","sub_path":"packages/grid_control/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":18291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"417685291","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: 东风\n@file: babynames.py\n@time: 2019/10/10 11:49\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# 使用pandas.read_csv将其加载到DataFrame中\n# names1880 = pd.read_csv('D:/data/pydata_book2/datasets/babynames/yob1880.txt', names=['name', 'sex', 'births'])\n# print(names1880)\n\n# 按性别列出的出生总和作为当年的出生总数\n# print(names1880.groupby('sex').births.sum())\n\n# 将所有数据集中到一个DataFrame中,再添加一个年份字段(可使用pandas.concat)\nyears = range(1880, 2011)\npieces = []\ncolumns = ['name', 'sex', 'births']\nfor year in years:\n path = 'D:/data/pydata_book2/datasets/babynames/yob%d.txt' % year\n # print(path)\n frame = pd.read_csv(path, names=columns)\n frame['year'] = year\n pieces.append(frame)\n\n# 将所有内容粘接近一个DataFrame中\nnames = pd.concat(pieces, ignore_index=True)\n# print(names)\n\n# 现在可使用groupby或pivot_table开始聚合年份和性别数据\ntotal_births = names.pivot_table('births', index='year', columns='sex', aggfunc=sum)\n# print(total_births.tail())\n\n# 绘制图表\n# total_births.plot(title='Total births by sex and year')\n# plt.show()\n\n# 插入prop列,给出每个婴儿名字相对出生总数的比例\n# 首先按年份和性别对数据进行分组,然后将新列添加到每个组中\ndef add_prop(group):\n group['prop'] = group.births / group.births.sum()\n return group\nnames = names.groupby(['year', 'sex']).apply(add_prop)\n# print(names)\n\n# 进行完整性检查\n# print(names.groupby(['year', 'sex']).prop.sum())\n\n# 每个性别/年份组合的前1000名。\ndef get_top1000(group):\n return group.sort_values(by='births', ascending=False)[:1000]\ngrouped = names.groupby(['year', 'sex'])\ntop1000 = grouped.apply(get_top1000)\n# 删除组索引,不需要它\ntop1000.reset_index(inplace=True, drop=True)\n\n# DIY方式实现\n# pieces = []\n# for year, group in names.groupby(['year', 'sex']):\n# pieces.append(group.sort_values(by='births', ascending=False)[:1000])\n# top1000 = pd.concat(pieces, ignore_index=True)\n\n# print(top1000)\n\n# 分析名字趋势\n# 将Top1000的名字分成男孩和女孩\nboys = top1000[top1000.sex == 'M']\ngirls = top1000[top1000.sex == 'F']\n\n# 按年份和名字形成出生总数的数据透视表\n# total_births = top1000.pivot_table('births', index='year', columns='name', aggfunc=sum)\n# total_births.info()\n# 绘制少数名称的透视表\n# subset = total_births[['John', 'Harry', 'Mary', 'Marilyn']]\n# subset.plot(subplots=True, figsize=(12, 10), grid=False, title='Number of births per year')\n# plt.show()\n\n# 计算命名多样性的增加\n# 按照年份和性别进行聚合和绘图\n# table = top1000.pivot_table('prop', index='year', columns='sex', aggfunc=sum)\n# table.plot(title='Sum of table1000.prop by year and sex', yticks=np.linspace(0, 1.2, 13), xticks=range(1880, 2020, 10))\n# plt.show()\n\ndf = boys[boys.year == 2010]\n# print(df)\n\nprop_cumsum = df.sort_values(by='prop', ascending=False).prop.cumsum()\n# print(prop_cumsum[:10])\n\n# print(prop_cumsum.values.searchsorted(0.5))\n\ndf = boys[boys.year == 1990]\nin1990 = df.sort_values(by='prop', ascending=False).prop.cumsum()\n# print(in1990.values.searchsorted(0.5) + 1)\n\ndef get_quantile_count(group, q=0.5):\n group = group.sort_values(by='prop', ascending=False)\n return group.prop.cumsum().values.searchsorted(q) + 1\ndiversity = top1000.groupby(['year', 'sex']).apply(get_quantile_count)\ndiversity = diversity.unstack('sex')\n# print(diversity.head())\n\n# diversity.plot(title='Number of popular names is top 50%')\n# plt.show()\n\n# “最后一个字母”革命\n# 从name列提取最后一个字母\nget_last_letter = lambda x: x[-1]\nlast_tetters = names.name.map(get_last_letter)\nlast_tetters.name = 'last_letter'\ntable = names.pivot_table('births', index=last_tetters, columns=['sex', 'year'], aggfunc=sum)\nsubtable = table.reindex(columns=[1910, 1960, 2010], level='year')\n# print(subtable)\n# print(subtable.sum())\n\nletter_prop = subtable / subtable.sum()\n# print(letter_prop)\n\n# fig, axes = plt.subplots(2, 1, figsize=(10, 8))\n# letter_prop['M'].plot(kind='bar', rot=0, ax=axes[0], title='Male')\n# letter_prop['F'].plot(kind='bar', rot=0, ax=axes[1], title='Female', legend=False)\n# plt.show()\n\n# letter_prop = table / table.sum()\n# dny_ts = letter_prop.loc[['d', 'n', 'y'], 'M'].T\n# print(dny_ts.head())\n# dny_ts.plot()\n\n# 男孩名字变成女孩名字\nall_names = pd.Series(top1000.name.unique())\nlesley_like = all_names[all_names.str.lower().str.contains('lesl')]\n# print(lesley_like)\n\nfiltered = top1000[top1000.name.isin(lesley_like)]\nfiltered.groupby('name').births.sum()\n\ntable = filtered.pivot_table('births', index='year', columns='sex', aggfunc='sum')\ntable = table.div(table.sum(1), axis=0)\nprint(table.tail())\n\ntable.plot(style={'M': 'k-', 'F': 'k--'})\nplt.show()\n\n","sub_path":"python_data_analysis/14-数据分析案例/babynames.py","file_name":"babynames.py","file_ext":"py","file_size_in_byte":4881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"394689565","text":"import os #for change the color and the system pause\r\nimport string #for use the string\r\nimport random #for use the random function\r\n\r\nos.system(\"color 02\") #for change the color\r\nnums = [x for x in range(99999)] #num max that i find the hentai, i know that is not accurate\r\nrandom.shuffle(nums) #for have a random array\r\nhentai=str(nums[0]) #but i use the only one number of the array\r\nprint(\"The hentai that was choosen fo you is: \"+ hentai) #here there is a print of the hentai that was choseen for you\r\n\r\nurl = 'start https://nhentai.net/g/' + hentai +'/' #here the program fabbricate the url\r\nos.system(url) #and now the program open you you the nhentai page\r\n\r\nos.system(\"pause\") #system pause OwO\r\n","sub_path":"random_hentai.py","file_name":"random_hentai.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"328880505","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\n# 常用内建模块\n\n# datetime模块\n\n# 获取当前日期和时间\nfrom datetime import datetime\n\nnow = datetime.now()\nprint(now) # 2017-10-17 16:15:30.839127\n# 获取指定时间\ndt = datetime(year=2017, month=10, day=17, hour=16, minute=17)\nprint(dt) # 2017-10-17 16:17:00\n\n# 时间戳转换为datetime\nt = 1429417200.0\nprint(datetime.fromtimestamp(t)) # 2015-04-19 12:20:00 UTC时间\n\n# str转换为datetime\ncday = datetime.strptime('2017-10-17 16:20:20', '%Y-%m-%d %H:%M:%S')\nprint(cday) # 2017-10-17 16:20:20\n\n# datetime转换为str\nprint(now.strptime('%a,%b %d %H:%M')) # Tue,Oct 17 16:22\n\n\n# collections模块 集合类\n\n'''\nnamedtuple是一个函数,\n它用来创建一个自定义的tuple对象,\n并且规定了tuple元素的个数,\n并可以用属性而不是索引来引用tuple的某个元素\n'''\n# 用namedtuple写坐标函数\nfrom collections import namedtuple\n\nPoint = namedtuple('Point', ['x', 'y'])\np = Point(1, 2)\nprint(p.x, p.y) # 1,2\n\n'''\ndeque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈\n'''\nfrom collections import deque\n\nq = deque(['a', 'b', 'c'])\nq.append('x')\nq.appendleft('y')\nprint(q) # deque(['y', 'a', 'b', 'c', 'x'])\n\n'''\n使用dict时,如果引用的Key不存在,就会抛出KeyError。\n如果希望key不存在时,返回一个默认值,使用defaultdict\n'''\nfrom collections import defaultdict\n\ndd = defaultdict(lambda: '123')\ndd['key1'] = 'abc'\nprint(dd['key1'], dd['key2']) # abc 123\n\n'''\n使用dict时,Key是无序的。\n在对dict做迭代时,我们无法确定Key的顺序。\n如果要保持Key的顺序,可以用OrderedDict\n'''\nfrom collections import OrderedDict\n\nd = dict([('a', 1), ('b', 2), ('c', 3)])\nod = OrderedDict([('a', 1), ('b', 2), ('c', 3)])\n\n'''\nCounter是一个简单的计数器,例如,统计字符出现的个数\n'''\nfrom collections import Counter\n\ncount = Counter()\nfor i in 'hello':\n count[i] += 1\nprint(count) # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})\n","sub_path":"1/chapter04.py","file_name":"chapter04.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"518600816","text":"def main():\n neighbors = [[0, -1], [1, 0], [0, 1], [-1, 0]]\n data = read()\n locByLetter = {}\n locByPoint = {}\n graph = {}\n for y, row in enumerate(data):\n for x, letter in enumerate(row):\n if not letter in locByLetter:\n locByLetter[letter] = []\n locByLetter[letter].append([x, y])\n locByPoint[\"{}, {}\".format(x, y)] = letter\n sPoint = \"{}, {}\".format(locByLetter[\"S\"][0][0], locByLetter[\"S\"][0][1])\n graph[sPoint] = []\n for neighbor in neighbors:\n x, y = [x + y for x, y in zip(locByLetter[\"S\"][0], neighbor)]\n testPoint = \"{}, {}\".format(x, y)\n if testPoint in locByPoint and (locByPoint[testPoint] == \"a\" or locByPoint[testPoint] == \"b\"):\n graph[sPoint].append(testPoint)\n ePoint = \"{}, {}\".format(locByLetter[\"E\"][0][0], locByLetter[\"E\"][0][1])\n graph[ePoint] = []\n for neighbor in neighbors:\n x, y = [x + y for x, y in zip(locByLetter[\"E\"][0], neighbor)]\n testPoint = \"{}, {}\".format(x, y)\n if testPoint in locByPoint and (locByPoint[testPoint] == \"y\" or locByPoint[testPoint] == \"z\"):\n graph[ePoint].append(testPoint)\n for i in range(97, 123):\n char = chr(i)\n for idx in range(len(locByLetter[char])):\n point = \"{}, {}\".format(locByLetter[char][idx][0], locByLetter[char][idx][1])\n graph[point] = []\n for neighbor in neighbors:\n x, y = [x + y for x, y in zip(locByLetter[char][idx], neighbor)]\n testPoint = \"{}, {}\".format(x, y)\n testChar = \"E\" if i == 122 else chr(i+1)\n if testPoint in locByPoint and (locByPoint[testPoint] == char or locByPoint[testPoint] == testChar):\n graph[point].append(testPoint)\n elif testPoint in locByPoint and (i != 97 and i > ord(locByPoint[testPoint])):\n graph[point].append(testPoint)\n\n path = shortest_path(graph, sPoint, ePoint)\n print(len(path) - 1)\n\ndef shortest_path(graph, node1, node2):\n path_list = [[node1]]\n path_index = 0\n\n previous_nodes = {node1}\n if node1 == node2:\n return path_list[0]\n\n while path_index < len(path_list):\n current_path = path_list[path_index]\n last_node = current_path[-1]\n next_nodes = graph[last_node]\n\n if node2 in next_nodes:\n current_path.append(node2)\n return current_path\n\n for next_node in next_nodes:\n if not next_node in previous_nodes:\n new_path = current_path[:]\n new_path.append(next_node)\n path_list.append(new_path)\n\n previous_nodes.add(next_node)\n\n path_index += 1\n\n return []\n\ndef read():\n input = open(\"input.txt\", \"r\")\n return [[i for i in list(line)] for line in input.read().splitlines()]\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2022/12/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"627716127","text":"\nimport logging\nimport os\nimport subprocess as sp\nfrom multiprocessing import Process\n\nimport numpy as np\nfrom spatialnc import ipw\n\nfrom smrf.distribute import image_data\nfrom smrf.envphys import radiation\nfrom smrf.utils import utils\n\n\nclass solar(image_data.image_data):\n \"\"\"\n The :mod:`~smrf.distribute.solar.solar` class allows for variable specific\n distributions that go beyond the base class.\n\n Multiple steps are required to estimate solar radiation:\n\n 1. Terrain corrected clear sky radiation\n 2. Adjust solar radiation for vegetation effects\n 3. Calculate net radiation using the albedo\n\n The Image Processing Workbench (IPW) includes a utility ``stoporad`` to\n model terrain corrected clear sky radiation over the DEM. Within\n ``stoporad``, the radiation transfer model ``twostream`` simulates the\n clear sky radiation on a flat surface for a range of wavelengths through\n the atmosphere :cite:`Dozier:1980` :cite:`Dozier&Frew:1981`\n :cite:`Dubayah:1994`. Terrain correction using the DEM adjusts for terrain\n shading and splits the clear sky radiation into beam and diffuse radiation.\n\n The second step requires sites measuring solar radiation. The measured\n solar radiation is compared to the modeled clear sky radiation from\n ``twostream``. The cloud factor is then the measured incoming solar\n radiation divided by the modeled radiation. The cloud factor can be\n computed on an hourly timescale if the measurement locations are of high\n quality. For stations that are less reliable, we recommend calculating a\n daily cloud factor which divides the daily integrated measured radiation by\n the daily integrated modeled radiation. This helps to reduce the problems\n that may be encountered from instrument shading, instrument calibration, or\n a time shift in the data. The calculated cloud factor at each station can\n then be distrubted using any of the method available in\n :mod:`smrf.spatial`. Since the cloud factor is not explicitly controlled\n by elevation like other variables, the values may be distributed without\n detrending to elevation. The modeled clear sky radiation (both beam and\n diffuse) are adjusted for clouds using\n :mod:`smrf.envphys.radiation.cf_cloud`.\n\n The third step adjusts the cloud corrected solar radiation for vegetation\n affects, following the methods developed by Link and Marks (1999)\n :cite:`Link&Marks:1999`. The direct beam radiation is corrected by:\n\n .. math::\n R_b = S_b * exp( -\\\\mu h / cos \\\\theta )\n\n where :math:`S_b` is the above canopy direct radiation, :math:`\\\\mu` is\n the extinction coefficient (:math:`m^{-1}`), :math:`h` is the canopy height\n (:math:`m`), :math:`\\\\theta` is the solar zenith angle, and :math:`R_b` is\n the canopy adjusted direct radiation. Adjusting the diffuse radiation is\n performed by:\n\n .. math::\n R_d = \\\\tau * R_d\n\n where :math:`R_d` is the diffuse adjusted radiation, :math:`\\\\tau` is the\n optical transmissivity of the canopy, and :math:`R_d` is the above canopy\n diffuse radiation. Values for :math:`\\\\mu` and :math:`\\\\tau` can be found\n in Link and Marks (1999) :cite:`Link&Marks:1999`, measured at study sites\n in Saskatchewan and Manitoba.\n\n The final step for calculating the net solar radiation requires the surface\n albedo from :mod:`smrf.distribute.albedo`. The net radiation is the sum of\n the of beam and diffuse canopy adjusted radiation multipled by one minus\n the albedo.\n\n Args:\n config: full configuration dictionary contain at least the sections\n albedo, and solar\n stoporad_in: file path to the stoporad_in file created from\n :mod:`smrf.data.loadTopo.topo`\n tempDir: location of temp/working directory (default=None, which is the\n 'WORKDIR' environment variable)\n\n Attributes:\n config: configuration from solar section\n albedoConfig: configuration from [albedo] section\n config: configuration from [albedo] section\n\n stoporad_in: file path to the stoporad_in file created from\n :mod:`smrf.data.loadTopo.topo`\n clear_ir_beam: numpy array modeled clear sky infrared beam radiation\n clear_ir_diffuse: numpy array modeled clear sky infrared diffuse\n radiation\n clear_vis_beam: numpy array modeled clear sky visible beam radiation\n clear_vis_diffuse: numpy array modeled clear sky visible diffuse\n radiation\n cloud_factor: numpy array distributed cloud factor\n cloud_ir_beam: numpy array cloud adjusted infrared beam radiation\n cloud_ir_diffuse: numpy array cloud adjusted infrared diffuse radiation\n cloud_vis_beam: numpy array cloud adjusted visible beam radiation\n cloud_vis_diffuse: numpy array cloud adjusted visible diffuse radiation\n ir_file: temporary file from ``stoporad`` for infrared clear sky\n radiation\n metadata: metadata for the station data\n net_solar: numpy array for the calculated net solar radiation\n output_variables: Dictionary of the variables held within class\n :mod:`!smrf.distribute.solar.solar` that specifies the ``units``\n and ``long_name`` for creating the NetCDF output file.\n stations: stations to be used in alphabetical order\n stoporad_in: file path to the stoporad_in file created from\n :mod:`smrf.data.loadTopo.topo`\n tempDir: temporary directory for ``stoporad``, will default to the\n ``WORKDIR`` environment variable\n variable: solar\n veg_height: numpy array of vegetation heights from\n :mod:`smrf.data.loadTopo.topo`\n veg_ir_beam: numpy array vegetation adjusted infrared beam radiation\n veg_ir_diffuse: numpy array vegetation adjusted infrared diffuse\n radiation\n veg_k: numpy array of vegetation extinction coefficient from\n :mod:`smrf.data.loadTopo.topo`\n veg_tau: numpy array of vegetation optical transmissivity from\n :mod:`smrf.data.loadTopo.topo`\n veg_vis_beam: numpy array vegetation adjusted visible beam radiation\n veg_vis_diffuse: numpy array vegetation adjusted visible diffuse\n radiation\n vis_file: temporary file from ``stoporad`` for visible clear sky\n radiation\n\n \"\"\"\n\n variable = 'solar'\n\n # these are variables that can be output\n output_variables = {'clear_ir_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'clear_sky_infrared_beam',\n 'long_name': 'Clear sky infrared beam solar radiation'\n },\n 'clear_ir_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'clear_sky_infrared_diffuse',\n 'long_name': 'Clear sky infrared diffuse solar radiation'\n },\n 'clear_vis_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'clear_sky_visible_beam',\n 'long_name': 'Clear sky visible beam solar radiation'\n },\n 'clear_vis_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'clear_sky_visible_diffuse',\n 'long_name': 'Clear sky visible diffuse solar radiation'\n },\n 'cloud_ir_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'cloud_infrared_beam',\n 'long_name': 'Cloud corrected infrared beam solar radiation'\n },\n 'cloud_ir_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'cloud_infrared_diffuse',\n 'long_name': 'Cloud corrected infrared diffuse solar radiation'\n },\n 'cloud_vis_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'cloud_visible_beam',\n 'long_name': 'Cloud corrected visible beam solar radiation'\n },\n 'cloud_vis_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'cloud_visible_diffuse',\n 'long_name': 'Cloud corrected visible diffuse solar radiation'\n },\n 'net_solar': {\n 'units': 'watt/m2',\n 'standard_name': 'net_solar_radiation',\n 'long_name': 'Net solar radiation'\n },\n 'veg_ir_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'vegetation_infrared_beam',\n 'long_name': 'Vegetation corrected infrared beam solar radiation'\n },\n 'veg_ir_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'vegetation_infrared_diffuse',\n 'long_name': 'Vegetation corrected infrared diffuse solar radiation'\n },\n 'veg_vis_beam': {\n 'units': 'watt/m2',\n 'standard_name': 'vegetation_visible_beam',\n 'long_name': 'Vegetation corrected visible beam solar radiation'\n },\n 'veg_vis_diffuse': {\n 'units': 'watt/m2',\n 'standard_name': 'vegetation_visible_diffuse',\n 'long_name': 'Vegetation corrected visible diffuse solar radiation'\n }\n }\n\n # These are variables that are operate at the end only and do not need to\n # be written during main distribute loop\n post_process_variables = {}\n\n def __init__(self, config, stoporad_in, tempDir=None):\n\n # extend the base class\n image_data.image_data.__init__(self, self.variable)\n self._logger = logging.getLogger(__name__)\n\n self.config = config[\"solar\"]\n self.albedoConfig = config[\"albedo\"]\n\n self.stoporad_in = stoporad_in\n\n if (tempDir is None) | (tempDir == 'WORKDIR'):\n tempDir = os.environ['WORKDIR']\n self.tempDir = tempDir\n\n # stoporad file names\n self.ir_file = os.path.join(self.tempDir, 'clearsky_ir.ipw')\n self.vis_file = os.path.join(self.tempDir, 'clearsky_vis.ipw')\n\n self._logger.debug('Created distribute.solar')\n\n def initialize(self, topo, data):\n \"\"\"\n Initialize the distribution, soley calls\n :mod:`smrf.distribute.image_data.image_data._initialize`. Sets the\n following attributes:\n\n * :py:attr:`veg_height`\n * :py:attr:`veg_tau`\n * :py:attr:`veg_k`\n\n Args:\n topo: :mod:`smrf.data.loadTopo.topo` instance contain topographic\n data and infomation\n data: data Pandas dataframe containing the station data,\n from :mod:`smrf.data.loadData` or :mod:`smrf.data.loadGrid`\n\n \"\"\"\n\n self._logger.debug('Initializing distribute.solar')\n # Solar has no stations. Relies on Cloud factor\n self.stations = None\n self._initialize(topo, data.metadata)\n self.veg_height = topo.veg_height\n self.veg_tau = topo.veg_tau\n self.veg_k = topo.veg_k\n\n def distribute(self, t, cloud_factor, illum_ang, cosz, azimuth, min_storm_day,\n albedo_vis, albedo_ir):\n \"\"\"\n Distribute air temperature given a Panda's dataframe for a single time\n step. Calls :mod:`smrf.distribute.image_data.image_data._distribute`.\n\n If the sun is up, i.e. ``cosz > 0``, then the following steps are\n performed:\n\n 1. Model clear sky radiation\n 2. Cloud correct with :mod:`!smrf.distribute.solar.solar.cloud_correct`\n 3. vegetation correct with\n :mod:`!smrf.distribute.solar.solar.veg_correct`\n 4. Calculate net radiation with\n :mod:`!smrf.distribute.solar.solar.calc_net`\n\n If sun is down, then all calculated values will be set to ``None``,\n signaling the output functions to put zeros in their place.\n\n Args:\n cloud_factor: Numpy array of the domain for cloud factor\n cosz: cosine of the zenith angle for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n azimuth: azimuth to the sun for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n min_storm_day: decimal day of last storm for the entire basin, from\n :mod:`smrf.distribute.precip.ppt.last_storm_day_basin`\n albedo_vis: numpy array for visible albedo, from\n :mod:`smrf.distribute.albedo.albedo.albedo_vis`\n albedo_ir: numpy array for infrared albedo, from\n :mod:`smrf.distribute.albedo.albedo.albedo_ir`\n\n \"\"\"\n\n self._logger.debug('%s Distributing solar' % t)\n\n # Only calculate solar if the sun is up\n if cosz > 0:\n self.cloud_factor = cloud_factor.copy()\n\n wy_day, wyear, tz_min_west = self.radiation_dates(t)\n\n # --------------------------------------------\n # calculate clear sky radiation\n\n # Not all the clean but it will work for now\n val_beam, val_diffuse = self.calc_ir(min_storm_day, wy_day,\n tz_min_west, wyear, cosz,\n azimuth)\n setattr(self, 'clear_ir_beam', val_beam)\n setattr(self, 'clear_ir_diffuse', val_diffuse)\n self.ir_beam = val_beam.copy()\n self.ir_diffuse = val_diffuse.copy()\n\n val_beam, val_diffuse = self.calc_vis(min_storm_day, wy_day,\n tz_min_west, wyear, cosz,\n azimuth)\n setattr(self, 'clear_vis_beam', val_beam)\n setattr(self, 'clear_vis_diffuse', val_diffuse)\n self.vis_beam = val_beam.copy()\n self.vis_diffuse = val_diffuse.copy()\n\n # --------------------------------------------\n # correct clear sky for cloud\n if self.config['correct_cloud']:\n self.cloud_correct()\n # copy output for output variables\n self.cloud_vis_beam = self.vis_beam.copy()\n self.cloud_vis_diffuse = self.vis_diffuse.copy()\n self.cloud_ir_beam = self.ir_beam.copy()\n self.cloud_ir_diffuse = self.ir_diffuse.copy()\n\n # --------------------------------------------\n # correct cloud for veg\n if self.config['correct_veg']:\n self.veg_correct(illum_ang)\n self.veg_vis_beam = self.vis_beam.copy()\n self.veg_vis_diffuse = self.vis_diffuse.copy()\n self.veg_ir_beam = self.ir_beam.copy()\n self.veg_ir_diffuse = self.ir_diffuse.copy()\n\n # --------------------------------------------\n # calculate net radiation\n self.calc_net(albedo_vis, albedo_ir)\n\n else:\n\n self._logger.debug('Sun is down, see you in the morning!')\n\n # clear sky\n# z = np.zeros()\n\n self.clear_vis_beam = None\n self.clear_vis_diffuse = None\n self.clear_ir_beam = None\n self.clear_ir_diffuse = None\n\n # cloud\n self.cloud_vis_beam = None\n self.cloud_vis_diffuse = None\n self.cloud_ir_beam = None\n self.cloud_ir_diffuse = None\n\n # canopy\n self.veg_vis_beam = None\n self.veg_vis_diffuse = None\n self.veg_ir_beam = None\n self.veg_ir_diffuse = None\n\n # net\n self.net_solar = None\n\n def distribute_thread(self, queue, data):\n \"\"\"\n Distribute the data using threading and queue. All data is provided and\n ``distribute_thread`` will go through each time step following the\n methods outlined in :mod:`smrf.distribute.solar.solar.distribute`. The\n data queues puts the distributed data into:\n\n * :py:attr:`net_solar`\n\n Args:\n queue: queue dictionary for all variables\n data: pandas dataframe for all data, indexed by date time\n \"\"\"\n self._logger.info(\"Distributing {}\".format(self.variable))\n for t in data.index:\n\n # check if sun is up or not\n cosz = queue['cosz'].get(t)\n self.cloud_factor = queue['cloud_factor'].get(t)\n\n if cosz > 0:\n\n # get the clear sky, set class attributes\n setattr(self, 'clear_vis_beam',\n queue['clear_vis_beam'].get(t))\n setattr(self, 'clear_vis_diffuse',\n queue['clear_vis_diffuse'].get(t))\n setattr(self, 'clear_ir_beam',\n queue['clear_ir_beam'].get(t))\n setattr(self, 'clear_ir_diffuse',\n queue['clear_ir_diffuse'].get(t))\n\n self.ir_beam = self.clear_ir_beam.copy()\n self.ir_diffuse = self.clear_ir_diffuse.copy()\n self.vis_beam = self.clear_vis_beam.copy()\n self.vis_diffuse = self.clear_vis_diffuse.copy()\n\n # Correct clear sky for cloud effects\n if self.config['correct_cloud'] == True:\n self.cloud_correct()\n\n # Copy output for output variables\n self.cloud_vis_beam = self.vis_beam.copy()\n self.cloud_vis_diffuse = self.vis_diffuse.copy()\n self.cloud_ir_beam = self.ir_beam.copy()\n self.cloud_ir_diffuse = self.ir_diffuse.copy()\n\n\n # correct for vegetation effects\n illum_ang = queue['illum_ang'].get(t)\n if self.config['correct_veg'] == True:\n self.veg_correct(illum_ang)\n\n # copy output for output variables\n self.veg_vis_beam = self.vis_beam.copy()\n self.veg_vis_diffuse = self.vis_diffuse.copy()\n self.veg_ir_beam = self.ir_beam.copy()\n self.veg_ir_diffuse = self.ir_diffuse.copy()\n\n # Get the albedo from the queue\n self._logger.debug(\"Getting alebdo_vis\")\n albedo_vis = queue['albedo_vis'].get(t)\n self._logger.debug(\"Getting alebdo_ir\")\n albedo_ir = queue['albedo_ir'].get(t)\n\n # calculate net radiation\n self.calc_net(albedo_vis, albedo_ir)\n\n else:\n self.net_solar = None\n\n if self.config['correct_veg'] == True:\n self.veg_vis_beam = None\n self.veg_vis_diffuse = None\n self.veg_ir_beam = None\n self.veg_ir_diffuse = None\n\n if self.config['correct_cloud'] == True:\n self.cloud_vis_beam = None\n self.cloud_vis_diffuse = None\n self.cloud_ir_beam = None\n self.cloud_ir_diffuse = None\n\n # Add the veg correct variables to the queue if requested\n if self.config['correct_veg'] == True:\n queue['veg_vis_beam'].put([t, self.veg_vis_beam])\n queue['veg_vis_diffuse'].put([t, self.veg_vis_diffuse])\n queue['veg_ir_beam'].put([t, self.veg_ir_beam])\n queue['veg_ir_diffuse'].put([t, self.veg_ir_diffuse])\n\n # Add the cloud corrected variables to the queue if requested\n if self.config['correct_cloud'] == True:\n queue['cloud_vis_beam'].put([t, self.cloud_vis_beam])\n queue['cloud_vis_diffuse'].put([t, self.cloud_vis_diffuse])\n queue['cloud_ir_beam'].put([t, self.cloud_ir_beam])\n queue['cloud_ir_diffuse'].put([t, self.cloud_ir_diffuse])\n\n queue['net_solar'].put([t, self.net_solar])\n\n def distribute_thread_clear(self, queue, data, calc_type):\n \"\"\"\n Distribute the data using threading and queue. All data is provided and\n ``distribute_thread`` will go through each time step and model clear sky\n radiation with ``stoporad``. The data queues puts the distributed data into:\n\n * :py:attr:`clear_vis_beam`\n * :py:attr:`clear_vis_diffuse`\n * :py:attr:`clear_ir_beam`\n * :py:attr:`clear_ir_diffuse`\n\n \"\"\"\n # the variable names\n beam = '%s_beam' % calc_type\n diffuse = '%s_diffuse' % calc_type\n\n for t in data.index:\n cosz = queue['cosz'].get(t)\n\n # check if sun is up or not\n if cosz > 0:\n\n # get the rest of the information\n azimuth = queue['azimuth'].get(t)\n min_storm_day = queue['last_storm_day_basin'].get(t)\n\n wy_day, wyear, tz_min_west = self.radiation_dates(t)\n\n if calc_type == 'clear_ir':\n val_beam, val_diffuse = self.calc_ir(min_storm_day, wy_day,\n tz_min_west, wyear, cosz,\n azimuth)\n elif calc_type == 'clear_vis':\n val_beam, val_diffuse = self.calc_vis(min_storm_day, wy_day,\n tz_min_west, wyear, cosz,\n azimuth)\n else:\n raise Exception('''Could not determine type of clear sky\n radiation to calculate''')\n\n else:\n val_beam = None\n val_diffuse = None\n\n # put into the queue\n queue[beam].put([t, val_beam])\n queue[diffuse].put([t, val_diffuse])\n\n def cloud_correct(self):\n \"\"\"\n Correct the modeled clear sky radiation for cloud cover using\n :mod:`smrf.envphys.radiation.cf_cloud`. Sets :py:attr:`cloud_vis_beam`\n and :py:attr:`cloud_vis_diffuse`.\n \"\"\"\n\n self._logger.debug('Correcting clear sky radiation for clouds')\n self.vis_beam, self.vis_diffuse = radiation.cf_cloud(self.vis_beam,\n self.vis_diffuse,\n self.cloud_factor)\n\n self.ir_beam, self.ir_diffuse = radiation.cf_cloud(self.ir_beam,\n self.ir_diffuse,\n self.cloud_factor)\n\n def veg_correct(self, illum_ang):\n \"\"\"\n Correct the cloud adjusted radiation for vegetation using\n :mod:`smrf.envphys.radiation.veg_beam` and\n :mod:`smrf.envphys.radiation.veg_diffuse`. Sets\n :py:attr:`veg_vis_beam`, :py:attr:`veg_vis_diffuse`,\n :py:attr:`veg_ir_beam`, and :py:attr:`veg_ir_diffuse`.\n\n Args:\n illum_ang: numpy array of the illumination angle over the DEM, from\n :mod:`smrf.envphys.radiation.sunang`\n\n \"\"\"\n\n self._logger.debug('Correcting radiation for vegetation')\n\n # calculate for visible\n # correct beam\n self.vis_beam = radiation.veg_beam(self.vis_beam,\n self.veg_height,\n illum_ang,\n self.veg_k)\n\n # correct diffuse\n self.vis_diffuse = radiation.veg_diffuse(self.vis_diffuse,\n self.veg_tau)\n\n # calculate for ir #\n # correct beam\n self.ir_beam = radiation.veg_beam(self.ir_beam,\n self.veg_height,\n illum_ang,\n self.veg_k)\n\n # correct diffuse\n self.ir_diffuse = radiation.veg_diffuse(self.ir_diffuse,\n self.veg_tau)\n\n def calc_net(self, albedo_vis, albedo_ir):\n \"\"\"\n Calculate the net radiation using the vegetation adjusted radiation.\n Sets :py:attr:`net_solar`.\n\n Args:\n albedo_vis: numpy array for visible albedo, from\n :mod:`smrf.distribute.albedo.albedo.albedo_vis`\n albedo_ir: numpy array for infrared albedo, from\n :mod:`smrf.distribute.albedo.albedo.albedo_ir`\n \"\"\"\n\n self._logger.debug('Calculating net radiation')\n\n # calculate net visible\n vv_n = (self.vis_beam + self.vis_diffuse) * (1 - albedo_vis)\n vv_n = utils.set_min_max(vv_n, self.min, self.max)\n\n # calculate net ir\n vir_n = (self.ir_beam + self.ir_diffuse) * (1 - albedo_ir)\n vir_n = utils.set_min_max(vir_n, self.min, self.max)\n\n # calculate total net\n self.net_solar = vv_n + vir_n\n self.net_solar = utils.set_min_max(self.net_solar, self.min, self.max)\n\n def calc_ir(self, min_storm_day, wy_day, tz_min_west, wyear, cosz, azimuth):\n \"\"\"\n Run ``stoporad`` for the infrared bands\n\n Args:\n min_storm_day: decimal day of last storm for the entire basin, from\n :mod:`smrf.distribute.precip.ppt.last_storm_day_basin`\n wy_day: day of water year, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n tz_min_west: time zone in minutes west from UTC, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n wyear: water year, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n cosz: cosine of the zenith angle for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n azimuth: azimuth to the sun for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n \"\"\"\n self._logger.debug('Calculating clear sky radiation, ir')\n\n ir_cmd = 'stoporad -z %i -t %s -w %s -g %s -x 0.7,2.8 -s %s'\\\n ' -d %s -f %i -y %i -A %f,%f -a %i -m %i -c %i -D %s > %s' \\\n % (self.config['clear_opt_depth'],\n str(self.config['clear_tau']),\n str(self.config['clear_omega']),\n str(self.config['clear_gamma']),\n str(min_storm_day),\n str(wy_day),\n tz_min_west, wyear,\n cosz, azimuth,\n self.albedoConfig['grain_size'],\n self.albedoConfig['max_grain'],\n self.albedoConfig['dirt'],\n self.stoporad_in,\n self.ir_file)\n\n #self._logger.debug(ir_cmd)\n\n irp = sp.Popen(ir_cmd,\n shell=True,\n env={\"PATH\": os.environ['PATH'],\n \"WORKDIR\": os.environ['WORKDIR']})\n\n stdoutdata, stderrdata = irp.communicate()\n\n if irp.returncode != 0:\n raise Exception('Clear sky for IR failed')\n\n ir = ipw.IPW(self.ir_file)\n clear_ir_beam = ir.bands[0].data\n clear_ir_diffuse = ir.bands[1].data\n\n return clear_ir_beam, clear_ir_diffuse\n\n def calc_vis(self, min_storm_day, wy_day, tz_min_west, wyear, cosz, azimuth):\n \"\"\"\n Run ``stoporad`` for the visible bands\n\n Args:\n min_storm_day: decimal day of last storm for the entire basin, from\n :mod:`smrf.distribute.precip.ppt.last_storm_day_basin`\n wy_day: day of water year, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n tz_min_west: time zone in minutes west from UTC, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n wyear: water year, from\n :mod:`~smrf.distirbute.solar.solar.radiation_dates`\n cosz: cosine of the zenith angle for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n azimuth: azimuth to the sun for the basin, from\n :mod:`smrf.envphys.radiation.sunang`\n \"\"\"\n self._logger.debug('Calculating clear sky radiation, visible')\n\n vis_cmd = 'stoporad -z %i -t %s -w %s -g %s -x 0.28,0.7 -s %s'\\\n ' -d %s -f %i -y %i -A %f,%f -a %i -m %i -c %i -D %s > %s' \\\n % (self.config['clear_opt_depth'],\n str(self.config['clear_tau']),\n str(self.config['clear_omega']),\n str(self.config['clear_gamma']),\n str(min_storm_day),\n str(wy_day),\n tz_min_west,\n wyear,\n cosz,\n azimuth,\n self.albedoConfig['grain_size'],\n self.albedoConfig['max_grain'],\n self.albedoConfig['dirt'],\n self.stoporad_in,\n self.vis_file)\n# self._logger.debug(vis_cmd)\n\n visp = sp.Popen(vis_cmd,\n shell=True,\n env={\"PATH\": os.environ['PATH'],\n \"WORKDIR\": os.environ['WORKDIR']})\n\n stdoutdata, stderrdata = visp.communicate()\n\n if visp.returncode != 0:\n raise Exception('Clear sky for visible failed')\n\n # load clear sky files back in\n vis = ipw.IPW(self.vis_file)\n clear_vis_beam = vis.bands[0].data\n clear_vis_diffuse = vis.bands[1].data\n\n return clear_vis_beam, clear_vis_diffuse\n\n def radiation_dates(self, date_time):\n \"\"\"\n Calculate some times based on the date for ``stoporad``\n\n Args:\n date_time: date time object\n\n Returns:\n (tuple): tuple containing:\n\n * **wy_day** - day of water year from October 1\n * **wyear** - water year\n * **tz_min_west** - minutes west of UTC for timezone\n \"\"\"\n\n # get the current day of water year\n wy_day, wyear = utils.water_day(date_time)\n\n # determine the minutes west of timezone\n tz_min_west = np.abs(date_time.utcoffset().total_seconds()/60)\n\n return wy_day, wyear, tz_min_west\n","sub_path":"smrf/distribute/solar.py","file_name":"solar.py","file_ext":"py","file_size_in_byte":31282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"411034905","text":"'''\nBy considering the terms in the Fibonacci sequence whose values\ndo not exceed four million, find the sum of the even-valued terms.\n'''\nn1 = 1\nn2 = 2\nsum = 0\nwhile n1 < 4000000:\n\tif n1 % 2 == 0:\n\t\tsum += n1\n\tn2 += n1\n\tn1 = n2-n1\nprint(sum)\n","sub_path":"p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"174603577","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n# opcodes for branch table\nADD = 0b10100000\nHLT = 0b00000001\nPRN = 0b01000111\nLDI = 0b10000010\nMUL = 0b10100010\nPOP = 0b01000110\nPUSH = 0b01000101\nCALL = 0b01010000\nRET = 0b00010001\nCMP = 0b10100111\nJNE = 0b01010110\nJEQ = 0b01010101\nJMP = 0b01010100\n\n# reserve register for stack pointer\nSP = 7\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.pc = 0\n self.reg = [0] * 8\n self.ram = [0] * 256\n self.fl = 0\n self.branch_table = {\n ADD: self.add,\n HLT: self.halt,\n LDI: self.ldi,\n PRN: self.prn,\n MUL: self.multiply,\n POP: self.pop,\n PUSH: self.push,\n CALL: self.call,\n RET: self.ret,\n CMP: self.cmp,\n JNE: self.jne,\n JEQ: self.jeq,\n JMP: self.jmp\n }\n def add(self, op_a, op_b):\n self.reg[op_a] += self.reg[op_b]\n self.pc += 3\n\n def cmp(self, op_a, op_b):\n if self.reg[op_a] == self.reg[op_b]:\n self.fl = \"E\"\n elif self.reg[op_a] < self.reg[op_b]:\n self.fl = \"LT\"\n elif self.reg[op_a] > self.reg[op_b]:\n self.fl = \"GT\"\n self.pc += 3\n\n def jeq(self, op_a, op_b):\n if self.fl == \"E\":\n self.pc = self.reg[op_a]\n else:\n self.pc += 2\n \n def jmp(self, op_a, op_b):\n self.pc = self.reg[op_a]\n\n def jne(self, op_a, op_b):\n if self.fl != \"E\":\n self.pc = self.reg[op_a]\n else:\n self.pc += 2\n \n def call(self, op_a, op_b):\n self.reg[SP] -= 1\n self.ram_write(self.pc + 2, self.reg[SP])\n self.pc = self.reg[op_a]\n \n def ret(self, op_a, op_b):\n self.pc = self.ram[self.reg[SP]]\n self.reg[SP] += 1 \n\n def halt(self, op_a, op_b):\n sys.exit(0)\n\n def ldi(self, op_a, op_b):\n self.reg[op_a] = op_b\n self.pc += 3\n\n def prn(self, op_a, op_b):\n print(self.reg[op_a])\n self.pc += 2\n\n def multiply(self, op_a, op_b):\n self.reg[op_a] *= self.reg[op_b]\n self.pc += 3\n\n def push(self, op_a, op_b):\n self.reg[SP] -= 1\n self.ram_write(self.reg[op_a], self.reg[SP])\n self.pc += 2\n\n def pop(self, op_a, op_b):\n value = self.ram_read(self.reg[SP])\n self.reg[op_a] = value\n self.reg[SP] += 1\n self.pc += 2\n \n def ram_read(self, mar):\n mdr = self.ram[mar]\n return mdr\n\n def ram_write(self, mdr, mar):\n self.ram[mar] = mdr\n \n def load(self, program):\n \"\"\"Load a program into memory.\"\"\"\n instructions = []\n with open(program) as f:\n for line in f:\n line = line.strip().split(\"#\")\n try:\n num = int(line[0], 2)\n except ValueError:\n continue\n instructions.append(num)\n \n address = 0\n\n for instruction in instructions:\n self.ram[address] = instruction\n address += 1\n\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n #elif op == \"SUB\": etc\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n #self.fl,\n #self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n while True:\n self.trace()\n op_code = self.ram[self.pc]\n operand_a , operand_b = self.ram[self.pc + 1], self.ram[self.pc + 2]\n if op_code in self.branch_table:\n self.branch_table[op_code](operand_a, operand_b)\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"73"} +{"seq_id":"426860834","text":"'''\nsudo apt-get install python-tk\nsudo apt-get install python-imaging\nsudo apt-get install python-imaging-tk\npip install Pillow\n'''\n\nfrom Tkinter import *\nfrom tkFileDialog import askopenfilename\nfrom PIL import Image, ImageTk\nimport sys, os\n\nif __name__ == \"__main__\":\n counter = 0\n\n root = Tk()\n\n corners_file = file('corners.txt', 'w')\n corners_string = ''\n\n #fn = '/home/vctr/Dropbox/_UNSW/Robocup/vctr_field_transform/testphotosat1340.JPG'\n # fn = '/Users/Martin/Github/RSA-Major-Project-2016/field_image_colour_cal_2.JPG'\n fn = os.getcwd() + '/calibrationphoto.jpg'\n # fn = './' + sys.argv[1]\n size = Image.open(fn).size\n\n #setting up a tkinter canvas with scrollbars\n frame = Frame(root, bd=2, relief=SUNKEN)\n frame.grid_rowconfigure(0, weight=1)\n frame.grid_columnconfigure(0, weight=1)\n xscroll = Scrollbar(frame, orient=HORIZONTAL)\n xscroll.grid(row=1, column=0, sticky=E+W)\n yscroll = Scrollbar(frame)\n yscroll.grid(row=0, column=1, sticky=N+S)\n canvas = Canvas(frame, width=size[0], height=size[1], bd=0, xscrollcommand=xscroll.set, yscrollcommand=yscroll.set)\n canvas.grid(row=0, column=0, sticky=N+S+E+W)\n xscroll.config(command=canvas.xview)\n yscroll.config(command=canvas.yview)\n frame.pack(fill=BOTH,expand=1)\n\n #adding the image\n #File = askopenfilename(parent=root, initialdir=\"C:/\",title='Choose an image.')\n img = ImageTk.PhotoImage(Image.open(fn))\n canvas.create_image(0,0,image=img,anchor=\"nw\")\n canvas.config(scrollregion=canvas.bbox(ALL))\n\n #function to be called when mouse is clicked\n def printcoords(event):\n #outputting x and y coords to console\n global counter\n global corners_string\n\n corners_string += str(event.x) + ',' + str(event.y) + '|'\n counter += 1\n if counter == 4:\n corners_file.write(corners_string[:-1])\n root.destroy()\n\n #mouseclick event\n canvas.bind(\"