/', views.delete_story, name='delete_story'),\r\n\r\n]\r\n","sub_path":"basic_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"597885321","text":"# -*- mode: python ; coding: utf-8 -*-\nimport os\nimport platform\n\nOS = platform.system()\n\nblock_cipher = None\n\nbinaries = [(os.path.join('tools', str.lower(OS), '*'), '.')]\n\na = Analysis(['KodularStarter.py', 'utils.py'],\n pathex=['.'],\n binaries=binaries,\n datas=[],\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\n\npyz = PYZ(a.pure,\n a.zipped_data,\n cipher=block_cipher)\n\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name='KodularStarter',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n runtime_tmpdir=None,\n console=True,\n icon='icon.ico')\n\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n strip=False,\n upx=False,\n name='KodularStarter')\n\nif OS == 'Darwin':\n info_plist = {\n 'NSHighResolutionCapable': 'True',\n 'NSPrincipalClass': 'NSApplication',\n 'CFBundleName': 'KodularStarter',\n 'CFBundleDisplayName': 'Kodular Starter',\n 'CFBundleIdentifier': 'io.kodular.starter',\n 'CFBundleVersion': '1',\n 'CFBundleShortVersionString': '1',\n 'LSMinimumSystemVersion': '10.12',\n }\n app = BUNDLE(coll,\n name='KodularStarter.app',\n icon='icon.icns',\n bundle_identifier=None,\n info_plist=info_plist\n )","sub_path":"KodularStarter.spec","file_name":"KodularStarter.spec","file_ext":"spec","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"297600523","text":"#!/usr/bin/env_python\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport pylab\n\ndata = pd.read_csv('OneDimHighPayoff.txt', sep=\"\\t\", header = None)\n\nfig=plt.figure()\nax=fig.gca(projection='3d')\n\nax.set_ylabel('Time (Years)')\nax.set_xlabel('Stock Price ($)')\nax.set_zlabel('Option Value ($)')\nplt.title('Evolution of High Estimator Put Option Values')\n\nx=data['X.1']\nz=data['X.2']\ny=data['X.3']\n\n\nax.scatter(y,x,z,c=z)\n\n#pylab.xlim([0,200])\n#ax.plot_wireframe(x,y,z)\n#fig.colorbar(surf,shrink=0.5, aspect=5)\n\n#NOTE THIS CHANGES THE POSITION OF Z AXIS\ntmp_planes = ax.zaxis._PLANES \nax.zaxis._PLANES = ( tmp_planes[2], tmp_planes[3], \n tmp_planes[0], tmp_planes[1], \n tmp_planes[4], tmp_planes[5])\nview_1 = (25, -135)\nview_2 = (25, -45)\ninit_view = view_2\nax.view_init(elev=20, azim=320)\npylab.xlim([0,200])\nplt.savefig('OptValEvolPut1.png')\n\n#ax.plot(x,y,z)\n\n\n","sub_path":"cuda_dir/CUDA_Implementation_of_the_Stochastic_Mesh_Method/Thesis_CodeA/OneDimPayoff.py","file_name":"OneDimPayoff.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"565136266","text":"from django.contrib import admin\nfrom wagtail.contrib.modeladmin.options import(\n\n ModelAdmin,\n modeladmin_register,\n ModelAdminGroup,\n)\nfrom .models import Reviews,OfferRequests,ContactRequest,WorkspaceRequest\n\nclass ReviewsAdmin(ModelAdmin):\n model=Reviews\n menu_label='Review'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"company\",\"comment\")\n search_fields=(\"name\",\"company\",\"comment\")\nclass OfferRequestsAdmin(ModelAdmin):\n model=OfferRequests\n menu_label='Offer Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"services\",\"name\",\"message\")\n search_fields=(\"services\",\"name\")\nclass ContactRequestsAdmin(ModelAdmin):\n model=ContactRequest\n menu_label='Contact Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"message\")\n search_fields=(\"name\")\nclass WorkspaceRequestsAdmin(ModelAdmin):\n model=WorkspaceRequest\n menu_label='Workspace Requests'\n menu_icon=\"placeholder\"\n menu_order=1\n add_to_settings_menu=False\n exclude_from_explorer=False\n list_display=(\"name\",\"date\",\"paymentStatus\")\n search_fields=(\"name\",\"date\")\n\nmodeladmin_register(ReviewsAdmin)\nmodeladmin_register(WorkspaceRequestsAdmin)\nmodeladmin_register(OfferRequestsAdmin)\nmodeladmin_register(ContactRequestsAdmin)","sub_path":"appforms/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"537020767","text":"# vim: set ts=8 sw=4 sts=4 et ai:\nfrom functools import update_wrapper\n\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponseRedirect\nfrom django.utils.http import urlquote\n\n\nclass _CheckAuthenticatableContactLogin(object):\n '''\n Copied from the _CheckLogin from django.contrib.auth.decorators and\n customized to fit exactly one need.\n '''\n def __init__(self, view_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):\n if not login_url:\n from django.conf import settings\n login_url = settings.LOGIN_URL\n self.view_func = view_func\n self.login_url = login_url\n self.redirect_field_name = redirect_field_name\n\n # We can't blindly apply update_wrapper because it updates __dict__ and\n # if the view function is already a _CheckLogin object then\n # self.test_func and friends will get stomped. However, we also can't\n # *not* update the wrapper's dict because then view function attributes\n # don't get updated into the wrapper. So we need to split the\n # difference: don't let update_wrapper update __dict__, but then update\n # the (parts of) __dict__ that we care about ourselves.\n update_wrapper(self, view_func, updated=())\n for k in view_func.__dict__:\n if k not in self.__dict__:\n self.__dict__[k] = view_func.__dict__[k]\n\n def __get__(self, obj, cls=None):\n view_func = self.view_func.__get__(obj, cls)\n return _CheckAuthenticatableContactLogin(view_func, self.login_url, self.redirect_field_name)\n\n def __call__(self, request, *args, **kwargs):\n if not request.user.is_authenticated():\n path = urlquote(request.get_full_path())\n tup = self.login_url, self.redirect_field_name, path\n return HttpResponseRedirect('%s?%s=%s' % tup)\n\n if hasattr(request, 'active_relation'):\n relation = request.active_relation\n else:\n try:\n contact = request.user.authenticatablecontact\n except ObjectDoesNotExist:\n relation = None\n else:\n relation = contact.relation\n\n assert relation, 'User %s has no profile / no relation!' % (request.user,)\n return self.view_func(relation, request.user, request, *args, **kwargs)\n\n\ndef login_with_company_profile_required(func):\n '''\n Decorator for views that checks that the user is logged in and checks that\n the user has a valid profile and, which that checked, adds the company and\n user to the view function as first and second parameters, before the request\n object.\n '''\n return _CheckAuthenticatableContactLogin(func)\n","sub_path":"osso/relation/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"132350245","text":"import csv\nimport Divergence\nimport statistics\nimport random\nimport scipy.stats as stats\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport math\nimport sys\n\n\nreader = csv.reader(open(\"Correct/92.csv\", 'r'))\ndata = list(int(row[2]) for row in reader)\nreader = csv.reader(open(\"Centralized/92.csv\", 'r'))\ndata_cen = list(int(row[2]) for row in reader)\nstep = 1403\n\ndropped, dist = Divergence.histogram(data, step)\ndropped, dist_cen = Divergence.histogram(data_cen, step)\n\nfigure = plt.figure(figsize=(1500/300, 900/300), dpi=300)\nacc = 0\nx = []\necdf = []\nfor i in range(60):\n if i in dist:\n acc += dist[i]\n x += [i, i+1]\n ecdf += [acc, acc]\nplt.plot(x, ecdf, 'k', label=\"Correct\")\n\nacc = 0\nx = []\necdf = []\nfor i in range(60):\n if i in dist_cen:\n acc += dist_cen[i]\n x += [i, i+1]\n ecdf += [acc, acc]\nplt.plot(x, ecdf, 'r', label=\"Cheated\")\nplt.legend()\nplt.grid()\nfigure.savefig(\"ECDF.png\")","sub_path":"OldStory/Synthetic/tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"282598383","text":"from deep_space_trader.transaction_dialogs import Buy, Sell, PlayerToWarehouse, WarehouseToPlayer\nfrom deep_space_trader import constants as const\nfrom deep_space_trader.utils import errorDialog\n\nfrom PyQt5 import QtWidgets, QtCore, QtGui\n\n\nclass ItemBrowser(QtWidgets.QWidget):\n def __init__(self, parent):\n super(ItemBrowser, self).__init__(parent)\n\n self.parent = parent\n self.mainLayout = QtWidgets.QVBoxLayout(self)\n self.buttonLayout = QtWidgets.QHBoxLayout()\n\n self.table = QtWidgets.QTableWidget()\n self.table.verticalHeader().setVisible(False)\n self.table.setSelectionBehavior(QtWidgets.QTableView.SelectRows)\n self.table.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)\n self.table.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)\n\n self.setupHeader()\n self.populateTable()\n self.mainLayout.addLayout(self.buttonLayout)\n self.mainLayout.addWidget(self.table)\n\n self.table.resizeColumnsToContents()\n self.update()\n\n def setupHeader(self):\n self.table.setColumnCount(2)\n self.table.setHorizontalHeaderLabels(['Item type', 'Quantity'])\n header = self.table.horizontalHeader()\n header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)\n\n def update(self):\n self.populateTable()\n super(ItemBrowser, self).update()\n\n def add_button(self, text, on_click):\n b = QtWidgets.QPushButton(text)\n b.clicked.connect(on_click)\n self.buttonLayout.addWidget(b)\n\n def addRow(self, itemname):\n raise NotImplementedError()\n\n def populateTable(self):\n raise NotImplementedError()\n\n\nclass PlayerItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(PlayerItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Sell item\", self.sellButtonClicked)\n self.add_button(\"Add to warehouse\", self.warehouseButtonClicked)\n\n def sellButtonClicked(self):\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item to sell first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n if itemname not in self.parent.state.current_planet.items.items:\n errorDialog(self, message=\"%s is not currently in demand on %s\"\n % (itemname, self.parent.state.current_planet.full_name))\n return\n\n dialog = Sell(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def warehouseButtonClicked(self):\n if self.parent.state.warehouse_puts == const.WAREHOUSE_PUTS_PER_DAY:\n errorDialog(self, \"Warehouse\", message=\"You cannot put anything else \"\n \"in the warehouse until tomorrow\")\n return\n\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n dialog = PlayerToWarehouse(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.items\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.items.items:\n self.addRow(name)\n\n\nclass PlanetItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(PlanetItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Buy item\", self.buyButtonClicked)\n\n def setupHeader(self):\n self.table.setColumnCount(3)\n self.table.setHorizontalHeaderLabels(['Item type', 'Quantity', 'Value'])\n header = self.table.horizontalHeader()\n header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)\n header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)\n\n def buyButtonClicked(self):\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, \"No item selected\",\n message=\"Please select an item to buy first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n if self.parent.state.current_planet.items.items[itemname].quantity == 0:\n errorDialog(self, \"None available\",\n message=\"%s has no %s left to sell\" %\n (self.parent.state.current_planet.full_name, itemname))\n return\n\n dialog = Buy(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.current_planet.items\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n item3 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].value))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n item3.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n self.table.setItem(nextFreeRow, 2, item3)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.current_planet.items.items:\n self.addRow(name)\n\n\nclass WarehouseItemBrowser(ItemBrowser):\n def __init__(self, *args, **kwargs):\n super(WarehouseItemBrowser, self).__init__(*args, **kwargs)\n\n self.add_button(\"Retrieve from warehouse\", self.removeButtonClicked)\n\n def removeButtonClicked(self):\n if self.parent.state.warehouse_gets == const.WAREHOUSE_GETS_PER_DAY:\n errorDialog(self, \"Warehouse\", message=\"You cannot take anything else \"\n \"from the warehouse until tomorrow\")\n return\n\n selectedRow = self.table.currentRow()\n if selectedRow < 0:\n errorDialog(self, message=\"Please select an item first!\")\n return\n\n itemname = self.table.item(selectedRow, 0).text()\n dialog = WarehouseToPlayer(self.parent, itemname)\n dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n dialog.exec_()\n\n\n def addRow(self, itemname):\n nextFreeRow = self.table.rowCount()\n self.table.insertRow(nextFreeRow)\n collection = self.parent.state.warehouse\n\n item1 = QtWidgets.QTableWidgetItem(itemname)\n item2 = QtWidgets.QTableWidgetItem(str(collection.items[itemname].quantity))\n\n item2.setTextAlignment(QtCore.Qt.AlignHCenter)\n\n self.table.setItem(nextFreeRow, 0, item1)\n self.table.setItem(nextFreeRow, 1, item2)\n\n def populateTable(self):\n self.table.setRowCount(0)\n for name in self.parent.state.warehouse.items:\n self.addRow(name)\n","sub_path":"deep_space_trader/item_browsers.py","file_name":"item_browsers.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"122762023","text":"# Import required modules\nimport cv2 as cv\nimport math\nimport argparse\nimport os \nimport time\nimport datetime\n#agiunto il deltatime : guestdatalogger\nfrom datetime import timedelta\nimport tkinter as tk\nfrom tkinter import *\nfrom PIL import Image, ImageTk\n#aggiunto l'importazione del json : guestdatalogger\nimport json\n#aggiunto l'importazione del request : guestdatalogger\nimport requests\nimport threading as thread\nfrom multiprocessing import *\nimport StartWindow\nimport CameraWindow\nimport sys\n\n#il metodo get() della classe Queue, di default ha un parametro block settato a true che blocca il flusso del programma fino a quando la coda si riempie.\n\nclass SenderData (thread.Thread):\n def __init__(self, q, api_key, ex):\n thread.Thread.__init__(self)\n self._stopevent = thread.Event()\n self.q = q\n self.api_key = api_key\n self.ex = ex\n \n def run(self):\n condizione = self.checkEx()\n while condizione:\n self.send_data()\n condizione = self.checkEx()\n print(\"Fuori dal run\")\n #sys.exit()\n return\n \n def join (self, timeout = None):\n self._stopevent.set()\n\n def checkEx(self):\n if(self.ex.get(False)['exit']):\n print(\"exit now\")\n return False\n else:\n print(\"FALSE exit\")\n self.ex.put({'exit': False})\n return True\n \n #Permette l'aggiunta di dati al database\n #@param date Data corrente nel formato mm-dd-YY\n #@param hours Ora attuale.\n #@param minutes Minuti attuali.\n #@param secs Secondi attuali.\n def dataToJSON(self):\n try:\n v = self.q.get(True, 3)\n myJson = {\n \"data\":v[\"time\"],\n \"num_persone\": v[\"count\"],\n \"api_key\":self.api_key\n }\n return myJson\n except:\n print(\"dataToJSON: exception\")\n\n #----------------------------------------------------------------------------- \n\n #----------------------------------------------------------------------------- \n\n #bisogna fare il controllo se la chiave inserita sia veritiera\n\n #verifica se i dati utente inseriti sono validi, per farlo utilizza un try & catch\n # che verifica se l'host o l'utente inserito esistano.\n #@param host Host da testare.\n #@param user User da testare.\n #@param password Password dell'utente da testare.\n\n def send_data(self):\n url = 'http://localhost:8080/GuestDataLogger/scripts/insertStat.php'\n #url = 'http://127.0.0.1'\n req = requests.post(url, json= self.dataToJSON())\n print(req.text)\n\n#----------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n ex = Queue()\n ex.put({'exit':False})\n q = Queue()\n mw = StartWindow.StartWindow(q)\n api_key = q.get()[\"api_key\"]\n sd = SenderData(q, api_key, ex)\n sd.start()\n cw = CameraWindow.CameraWindow(q, ex)\n while sd.is_alive():\n time.sleep(0.5)\n print(\"Thread morta\")\n # NOTA: IDLE cattura tutte le eccezioni, compresa la SystemExit.\n # Provare senza IDLE.\n sys.exit(\"sys.exit()\")\n #exit()","sub_path":"src/GDL/src/old_version/TestFaceRec.py","file_name":"TestFaceRec.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"620583415","text":"def add_matrix():\n if r1==r2 and c1==c2:\n print(\"Addition Matrix of Given matrices is:\")\n for i in range(r1):\n for j in range(c1):\n print(m1[i][j]+m2[i][j], end=\" \")\n print()\n else:\n print(\"Error! Can't Add them!!\")\n\nr1=int(input(\"Enter no of rows in the matrix 1: \"))\nc1=int(input(\"Enter no of columns in the matrix 1: \"))\nm1=[[int(input(\"Enter element: \")) for j in range(c1)] for i in range(r1)]\nfor i in range(r1):\n for j in range(c1):\n print(m1[i][j], end=\" \")\n print()\n\n \nr2=int(input(\"\\nEnter no of rows in the matrix 2: \"))\nc2=int(input(\"Enter no of columns in the matrix 2: \"))\nm2=[[int(input(\"Enter element: \")) for j in range(c2)] for i in range(r2)]\n\nfor i in range(r2):\n for j in range(c2):\n print(m2[i][j], end=\" \")\n print()\nadd_matrix()\n","sub_path":"Python_Programs/addition_of_matrices.py","file_name":"addition_of_matrices.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"129714723","text":"# -*- coding: utf-8 -*-\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom datetime import datetime\nfrom logging import getLogger\nfrom typing import Dict\nfrom typing import Generator\nfrom typing import Iterator\nfrom typing import List\n\nfrom moneybot.market.history import MarketHistory\nfrom moneybot.market.state import MarketState\nfrom moneybot.strategy import ProposedTrade\n\n\nlogger = getLogger(__name__)\n\n\nclass MarketAdapter(metaclass=ABCMeta):\n\n def __init__(\n self,\n history: MarketHistory,\n initial_balances: Dict[str, float],\n fiat: str,\n ) -> None:\n self.market_history = history\n self.balances = initial_balances\n self.fiat = fiat\n\n @abstractmethod\n def get_balances(self):\n raise NotImplementedError\n\n @abstractmethod\n def execute(\n self,\n proposed_trades: Iterator[ProposedTrade],\n market_state: MarketState,\n ):\n raise NotImplementedError\n\n def get_market_state(self, time: datetime) -> MarketState:\n # Get the latest chart data from the market\n charts = self.market_history.latest(time)\n balances = self.get_balances()\n # We wrap these data in a MarketState,\n # which provides some convenience methods.\n market_state = MarketState(charts, balances, time, self.fiat)\n return market_state\n\n def filter_legal(\n self,\n proposed_trades: List[ProposedTrade],\n market_state: MarketState,\n ) -> Generator[ProposedTrade, None, None]:\n '''\n Takes a list of ProposedTrade objects.\n Checks that each is a legal trade by the rules of our market.\n '''\n for proposed in proposed_trades:\n if self.is_legal(proposed, market_state):\n yield proposed\n\n def is_legal(\n self,\n proposed: ProposedTrade,\n market_state: MarketState,\n ) -> bool:\n # TODO This is pretty Poloniex specific, so we might move it\n # to a PoloniexMarketAdapter if we ever add more exchanges.\n\n # Check that proposed bid has a price:\n if not proposed.price:\n logger.warning(\n f'Filtering out proposed trade (has no price): {proposed}.'\n )\n return False\n\n # Check that we have enough to sell\n held_amount = market_state.balances[proposed.from_coin]\n if proposed.bid_amount > held_amount:\n logger.warning(\n \"Filtering out proposed trade (can't sell more than is held): \"\n f\"{proposed}. Holding {held_amount} {proposed.from_coin}.\"\n )\n return False\n\n # Check that we are trading a positive amount for a positive amount\n if proposed.bid_amount < 0 or proposed.ask_amount < 0:\n logger.warning(\n 'Filtering out proposed trade (bid or ask amount < 0): '\n f'{proposed}.'\n )\n return False\n\n # Check that the proposed trade exceeds minimum fiat trade amount.\n if (\n (proposed.from_coin == proposed.fiat and proposed.bid_amount < 0.0001) or\n (proposed.to_coin == proposed.fiat and proposed.ask_amount < 0.0001)\n ):\n logger.warning(\n 'Filtering out proposed trade (transaction too small): '\n f'{proposed}.'\n )\n return False\n\n # Check that the trade is on a market that exists.\n if proposed.market_name not in market_state.chart_data.keys():\n logger.warning(\n f'Filtering out proposed trade (unknown market): {proposed}.'\n )\n return False\n\n return True\n","sub_path":"moneybot/market/adapters/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"15504167","text":"###\n# Copyright 2015-2021, Institute for Systems Biology\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\nfrom builtins import str\nimport time\nimport json\nfrom json.decoder import JSONDecodeError\nimport logging\nimport sys\nimport datetime\nimport re\nimport copy\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.cache import never_cache\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.utils.html import escape\n\nfrom google_helpers.stackdriver import StackDriverLogger\nfrom cohorts.models import Cohort, Cohort_Perms\nfrom idc_collections.models import Program, DataSource, Collection, ImagingDataCommonsVersion, Attribute, Attribute_Tooltips, DataSetType\nfrom idc_collections.collex_metadata_utils import build_explorer_context, get_collex_metadata, create_file_manifest\nfrom allauth.socialaccount.models import SocialAccount\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import HttpResponse, JsonResponse\nfrom django.contrib.auth.signals import user_login_failed\nfrom django.dispatch import receiver\nfrom idc.models import User_Data\n\n\ndebug = settings.DEBUG\nlogger = logging.getLogger('main_logger')\n\nBQ_ATTEMPT_MAX = 10\nWEBAPP_LOGIN_LOG_NAME = settings.WEBAPP_LOGIN_LOG_NAME\n\n\n# The site's homepage\n@never_cache\ndef landing_page(request):\n collex = Collection.objects.filter(active=True, subject_count__gt=6,\n collection_type=Collection.ORIGINAL_COLLEX, species='Human',\n access=\"Public\").values()\n idc_info = ImagingDataCommonsVersion.objects.get(active=True)\n\n sapien_counts = {}\n\n changes = {\n 'Head': 'Head and Neck',\n 'Head-Neck': 'Head and Neck',\n 'Head-and-Neck': 'Head and Neck',\n 'Colon': 'Colorectal',\n 'Rectum': 'Colorectal',\n \"Marrow, Blood\": \"Blood\",\n \"Testicles\": \"Testis\",\n \"Adrenal Glands\": \"Adrenal Gland\",\n \"Adrenal\": \"Adrenal Gland\"\n }\n\n skip = [\n 'Extremities',\n 'Abdomen, Mediastinum',\n 'Abdomen, Pelvis',\n 'Abdomen',\n 'Ear',\n 'Pelvis, Prostate, Anus',\n \"Intraocular\",\n \"Mesothelium\",\n \"Chest-Abdomen-Pelvis, Leg, TSpine\",\n \"Abdomen, Arm, Bladder, Chest, Head-Neck, Kidney, Leg, Retroperitoneum, Stomach, Uterus\"\n ]\n\n for collection in collex:\n loc = collection['location']\n if re.search(r'[Pp]hantom',loc) or re.search('[Vv]arious',loc) or loc in skip:\n continue\n if collection['location'] in changes:\n loc = changes[collection['location']]\n if loc not in sapien_counts:\n sapien_counts[loc] = 0\n sapien_counts[loc] += collection['subject_count']\n\n ex_tooltips = {\n '1.3.6.1.4.1.14519.5.2.1.6279.6001.224985459390356936417021464571': 'Patient ID: LIDC-IDRI-0834
Modality: CT
',\n '1.3.6.1.4.1.14519.5.2.1.1706.4001.149500105036523046215258942545': 'Patient ID: TCGA-02-0006
Modality: MR
',\n '1.3.6.1.4.1.14519.5.2.1.2744.7002.950936925946327395356711739684': 'Patient ID: QIN-HEADNECK-01-0228
Modality: PET
'\n }\n\n return render(request, 'idc/landing.html', {\n 'request': request,\n 'case_counts': [{'site': x, 'cases': sapien_counts[x], 'fileCount': 0} for x in sapien_counts.keys()],\n 'example_tooltips': ex_tooltips,\n 'idc_info': idc_info\n })\n\n\n# Displays the privacy policy\ndef privacy_policy(request):\n return render(request, 'idc/privacy.html', {'request': request, })\n\n\n# Displays the page of collaborators\ndef collaborators(request):\n return render(request, 'idc/collaborators.html', {'request': request, })\n\n\n# News page (loads from Discourse)\ndef news_page(request):\n return render(request, 'idc/news.html')\n\n\n# User details page\n@login_required\ndef user_detail(request, user_id):\n if debug: logger.debug('Called ' + sys._getframe().f_code.co_name)\n\n if int(request.user.id) == int(user_id):\n\n user = User.objects.get(id=user_id)\n try:\n social_account = SocialAccount.objects.get(user_id=user_id, provider='google')\n except Exception as e:\n # This is a local account\n social_account = None\n user_details = {\n 'date_joined': user.date_joined,\n 'email': user.email,\n 'id': user.id,\n 'last_login': user.last_login\n }\n\n if social_account:\n user_details['extra_data'] = social_account.extra_data if social_account else None\n user_details['first_name'] = user.first_name\n user_details['last_name'] = user.last_name\n else:\n user_details['username'] = user.username\n\n return render(request, 'idc/user_detail.html',\n {'request': request,\n 'user': user,\n 'user_details': user_details,\n 'unconnected_local_account': bool(social_account is None),\n 'social_account': bool(social_account is not None)\n })\n else:\n return render(request, '403.html')\n\n\n# Callback method for logs of failed logins\n@receiver(user_login_failed)\ndef user_login_failed_callback(sender, credentials, **kwargs):\n try:\n # Write log entry\n st_logger = StackDriverLogger.build_from_django_settings()\n log_name = WEBAPP_LOGIN_LOG_NAME\n st_logger.write_text_log_entry(\n log_name,\n '[WEBAPP LOGIN] Login FAILED for: {credentials}'.format(credentials=credentials)\n )\n\n except Exception as e:\n logger.exception(e)\n\n\n# Extended login view so we can track user logins, redirects to data exploration page\ndef extended_login_view(request):\n try:\n # Write log entry\n st_logger = StackDriverLogger.build_from_django_settings()\n log_name = WEBAPP_LOGIN_LOG_NAME\n user = User.objects.get(id=request.user.id)\n st_logger.write_text_log_entry(\n log_name,\n \"[WEBAPP LOGIN] User {} logged in to the web application at {}\".format(user.email,\n datetime.datetime.utcnow())\n )\n\n except Exception as e:\n logger.exception(e)\n\n return redirect(reverse('explore_data'))\n\n\n# Health check callback\n#\n# Because the match for vm_ is always done regardless of its presence in the URL\n# we must always provide an argument slot for it\ndef health_check(request, match):\n return HttpResponse('')\n\n\n# Quota page for the viewer\ndef quota_page(request):\n return render(request, 'idc/quota.html', {'request': request, 'quota': settings.IMG_QUOTA})\n\n\n@login_required\ndef save_ui_hist(request):\n status = 200\n try:\n req = request.POST or request.GET\n hist = req['his']\n try:\n user_data = User_Data.objects.get(user_id=request.user.id)\n user_data.history = hist\n user_data.save()\n\n except ObjectDoesNotExist:\n user_data_dict = {'user_id': request.user.id, \"history\": hist}\n User_Data.objects.update_or_create(**user_data_dict)\n except Exception as e:\n logger.error(\"[ERROR] While trying to save the user's UI preferences:\")\n logger.exception(e)\n status = 500\n\n return JsonResponse({}, status=status)\n\n\n# Method for obtaining the records displayed in the tables on the right-hand side of the explore data page\n@login_required\ndef populate_tables(request):\n response = {}\n status = 200\n tableRes = []\n try:\n req = request.GET if request.GET else request.POST\n path_arr = [nstr for nstr in request.path.split('/') if nstr]\n table_type = path_arr[len(path_arr)-1]\n fields = None\n collapse_on = None\n filters = json.loads(req.get('filters', '{}'))\n offset = int(req.get('offset', '0'))\n limit = int(req.get('limit', '500'))\n if limit > settings.MAX_SOLR_RECORD_REQUEST:\n logger.warning(\"[WARNING] Attempt to request more than MAX_SOLR_RECORD_REQUEST! ({})\".format(limit))\n limit = settings.MAX_SOLR_RECORD_REQUEST\n sort = req.get('sort', 'PatientID')\n sortdir = req.get('sortdir', 'asc')\n checkIds = json.loads(req.get('checkids', '[]'))\n #table_data = get_table_data(filters, table_type)\n diffA = []\n\n sources = ImagingDataCommonsVersion.objects.get(active=True).get_data_sources(\n active=True, source_type=DataSource.SOLR,\n aggregate_level=\"SeriesInstanceUID\" if table_type == 'series' else \"StudyInstanceUID\"\n )\n\n sortByField = True\n #idsReq=[]\n custom_facets = None\n custom_facets_order = None\n if table_type == 'cases':\n custom_facets = {\"per_id\": {\"type\": \"terms\", \"field\": \"PatientID\", \"limit\": limit,\n \"facet\": {\"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"}}\n }\n tableIndex = 'PatientID'\n fields = ['collection_id', 'PatientID','access']\n facetfields=['unique_study', 'unique_series']\n\n if sort == 'collection_id':\n sortByField = True\n sort_arg = 'collection_id '+sortdir\n\n elif sort == 'PatientID':\n sort_arg = 'PatientID ' + sortdir\n\n elif sort == 'StudyInstanceUID':\n sortByField = False\n sort_arg = 'unique_study ' + sortdir\n custom_facets_order = {\n \"tot\": \"unique(PatientID)\",\n \"per_id\": {\n \"type\": \"terms\",\n \"field\": \"PatientID\",\n \"sort\": sort_arg,\n \"offset\": offset,\n \"limit\": limit,\n \"facet\": {\n \"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"\n }\n }\n }\n elif sort == 'SeriesInstanceUID':\n sortByField=False\n sort_arg = 'unique_series '+sortdir\n custom_facets_order = {\n \"tot\": \"unique(PatientID)\",\n \"per_id\": {\n \"type\": \"terms\", \"field\": \"PatientID\", \"sort\": sort_arg, \"offset\": offset, \"limit\": limit,\n \"facet\": {\n \"unique_study\": \"unique(StudyInstanceUID)\",\n \"unique_series\": \"unique(SeriesInstanceUID)\"\n }\n }\n }\n\n if table_type == 'studies':\n custom_facets = {\"per_id\": {\"type\": \"terms\", \"field\": \"StudyInstanceUID\", \"limit\": limit,\n \"facet\": {\"unique_series\": \"unique(SeriesInstanceUID)\"}}\n }\n tableIndex = 'StudyInstanceUID'\n fields = ['collection_id','PatientID','StudyInstanceUID','StudyDescription','Modality','StudyDate','access']\n facetfields = ['unique_series']\n sort_arg = 'PatientID asc, StudyDate asc'\n\n if sort in ['PatientID','StudyInstanceUID', 'StudyDescription', 'StudyDate']:\n sortByField = True\n sort_arg = \"{} {}\".format(sort, sortdir)\n if sort == 'PatientID':\n sort_arg = sort_arg+', StudyDate asc'\n #elif sort == 'StudyInstanceUID':\n # sort_arg = sort_arg + 'StudyDate asc'\n elif sort == 'SeriesInstanceUID':\n sortByField = False\n sort_arg = 'unique_series '+sortdir\n\n custom_facets_order = {\"tot\": \"unique(SeriesInstanceUID)\",\n \"per_id\": {\"type\": \"terms\", \"field\": \"StudyInstanceUID\",\n \"sort\": sort_arg,\"offset\": offset, \"limit\": limit,\n \"facet\": {\"unique_series\": \"unique(SeriesInstanceUID)\"}\n }\n }\n\n if table_type == 'series':\n custom_facets = {}\n tableIndex = 'SeriesInstanceUID'\n fields = ['collection_id', 'SeriesInstanceUID', 'StudyInstanceUID', 'SeriesDescription', 'SeriesNumber',\n 'BodyPartExamined', 'Modality', 'access', 'crdc_series_uuid','gcs_bucket','aws_bucket']\n facetfields = []\n sortByField = True\n\n sort_arg = 'StudyInstanceUID asc, SeriesNumber asc' if not sort else \"{} {}, SeriesNumber asc\".format(\n sort, sortdir\n )\n\n if sort == 'SeriesDescription':\n custom_facets_order = {}\n\n order = {}\n curInd = 0\n idsFilt = []\n\n # check that any selected ids are still valid after the filter is updated. ids that are not longer valid are\n # then deselected on the front end\n if len(checkIds)>0:\n selFilters=copy.deepcopy(filters)\n selFilters[tableIndex] = checkIds\n newCheckIds = get_collex_metadata(\n selFilters, [tableIndex], record_limit=len(checkIds)+1,sources=sources, records_only=True,\n collapse_on=tableIndex, counts_only=False, filtered_needed=False, sort=tableIndex+' asc'\n )\n\n nset = set([x[tableIndex] for x in newCheckIds['docs']])\n diffA = [x for x in checkIds if x not in nset]\n\n if sortByField:\n idsReq = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, offset=offset, records_only=True,\n collapse_on=tableIndex, counts_only=False, filtered_needed=False, sort=sort_arg\n )\n\n cnt = idsReq['total']\n for rec in idsReq['docs']:\n id = rec[tableIndex]\n idsFilt.append(id)\n order[id] = curInd\n newRow = {}\n for field in fields:\n if field in rec:\n newRow[field] = rec[field]\n else:\n newRow[field] = ''\n tableRes.append(newRow)\n curInd = curInd + 1\n filters[tableIndex]=idsFilt\n if not table_type == 'series':\n cntRecs = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, collapse_on=tableIndex, counts_only=True,\n records_only=False, filtered_needed=False, custom_facets=custom_facets, raw_format=True\n )\n\n for rec in cntRecs['facets']['per_id']['buckets']:\n id = rec['val']\n tableRow = tableRes[order[id]]\n for facet in facetfields:\n if facet in rec:\n tableRow[facet] = rec[facet]\n else:\n tableRow[facet] = 0\n else:\n idsReq = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, offset=offset, records_only=False,\n collapse_on=tableIndex, counts_only=True, filtered_needed=False, custom_facets=custom_facets_order,\n raw_format=True\n )\n cnt = idsReq['facets']['tot']\n for rec in idsReq['facets']['per_id']['buckets']:\n id = rec['val']\n idsFilt.append(id)\n order[id] = curInd\n newRow = {tableIndex: id}\n for facet in facetfields:\n if facet in rec:\n newRow[facet]=rec[facet]\n else:\n newRow[facet] = 0\n tableRes.append(newRow)\n curInd = curInd + 1\n filters[tableIndex] = idsFilt\n fieldRecs = get_collex_metadata(\n filters, fields, record_limit=limit, sources=sources, records_only=True, collapse_on=tableIndex,\n counts_only=False, filtered_needed=False\n )\n for rec in fieldRecs['docs']:\n id = rec[tableIndex]\n tableRow = tableRes[order[id]]\n for field in fields:\n if not field == tableIndex:\n if field in rec:\n tableRow[field] = rec[field]\n else:\n tableRow[field] = ''\n\n response[\"res\"] = tableRes\n response[\"cnt\"] = cnt\n response[\"diff\"] = diffA\n\n except Exception as e:\n logger.error(\"[ERROR] While attempting to populate the table:\")\n logger.exception(e)\n messages.error(\n request,\n \"Encountered an error when attempting to populate the page - please contact the administrator.\"\n )\n status = 400\n\n return JsonResponse(response, status=status)\n\n\n# Data exploration and cohort creation page\n@login_required\ndef explore_data_page(request, filter_path=False, path_filters=None):\n context = {'request': request}\n is_json = False\n wcohort = False\n status = 200\n\n try:\n req = request.GET or request.POST\n is_dicofdic = (req.get('is_dicofdic', \"False\").lower() == \"true\")\n source = req.get('data_source_type', DataSource.SOLR)\n versions = json.loads(req.get('versions', '[]'))\n filters = json.loads(req.get('filters', '{}'))\n disk_size = (req.get('disk_size', 'False').lower() == \"true\")\n\n fields = json.loads(req.get('fields', '[]'))\n order_docs = json.loads(req.get('order_docs', '[]'))\n counts_only = (req.get('counts_only', \"False\").lower() == \"true\")\n with_related = (req.get('with_clinical', \"True\").lower() == \"true\")\n with_derived = (req.get('with_derived', \"True\").lower() == \"true\")\n collapse_on = req.get('collapse_on', 'SeriesInstanceUID')\n if len(Attribute.objects.filter(name=collapse_on)) <= 0:\n logger.error(\"[ERROR] Attempt to collapse on an invalid field: {}\".format(collapse_on))\n collapse_on='SeriesInstanceUID'\n is_json = (req.get('is_json', \"False\").lower() == \"true\")\n uniques = json.loads(req.get('uniques', '[]'))\n totals = json.loads(req.get('totals', '[]'))\n\n cohort_id = int(req.get('cohort_id', '-1'))\n\n cohort_filters = {}\n if cohort_id > 0:\n cohort = Cohort.objects.get(id=cohort_id, active=True)\n cohort.perm = cohort.get_perm(request)\n if cohort.perm:\n wcohort = True\n cohort_filters_dict = cohort.get_filters_as_dict()\n cohort_filters_list = cohort_filters_dict[0]['filters']\n for cohort in cohort_filters_list:\n cohort_filters[cohort['name']] = cohort['values']\n if filter_path and is_json:\n filters = path_filters\n\n if wcohort and is_json:\n filters = cohort_filters\n\n versions = ImagingDataCommonsVersion.objects.filter(\n version_number__in=versions\n ).get_data_versions(active=True) if len(versions) else ImagingDataCommonsVersion.objects.filter(\n active=True\n ).get_data_versions(active=True)\n\n context = build_explorer_context(\n is_dicofdic, source, versions, filters, fields, order_docs, counts_only, with_related, with_derived,\n collapse_on, is_json, uniques=uniques, totals=totals, disk_size=disk_size\n )\n\n if not is_json:\n # These are filters to be loaded *after* a page render\n if wcohort:\n context['filters_for_load'] = cohort_filters_dict\n elif filter_path:\n context['filters_for_load'] = path_filters\n else:\n filters_for_load = req.get('filters_for_load', None)\n if filters_for_load:\n blacklist = re.compile(settings.BLACKLIST_RE, re.UNICODE)\n if blacklist.search(filters_for_load):\n logger.warning(\"[WARNING] Saw bad filters in filters_for_load:\")\n logger.warning(filters_for_load)\n filters_for_load = {}\n messages.error(\n request,\n \"There was a problem with some of your filters - please ensure they're properly formatted.\"\n )\n status = 400\n else:\n filters_for_load = json.loads(filters_for_load)\n else:\n filters_for_load = None\n context['filters_for_load'] = filters_for_load\n context['hist'] = ''\n try:\n user_data = User_Data.objects.get(user_id=request.user.id)\n context['history'] = json.loads(user_data.history)\n except ObjectDoesNotExist:\n pass\n\n except JSONDecodeError as e:\n logger.error(\"[ERROR] While attempting to load the search page:\")\n logger.error(\"Invalid JSON format received.\")\n logger.exception(e)\n messages.error(\n request,\n \"The filters supplied contained invalid JSON.\"\n )\n status = 400\n except Exception as e:\n logger.error(\"[ERROR] While attempting to load the search page:\")\n logger.exception(e)\n messages.error(\n request,\n \"Encountered an error when attempting to load the page - please contact the administrator.\"\n )\n status = 500\n\n if is_json:\n # In the case of is_json=True, the 'context' is simply attr_by_source\n return JsonResponse(context, status=status)\n\n return render(request, 'idc/explore.html', context)\n\n\ndef explorer_manifest(request):\n req = request.GET or request.POST\n if req.get('manifest-type', 'file-manifest') == 'bq-manifest' :\n messages.error(request, \"BigQuery export requires a cohort! Please save your filters as a cohort.\")\n return JsonResponse({'msg': 'BigQuery export requires a cohort.'}, status=400)\n return create_file_manifest(request)\n\n\n# Given a set of filters in a GET request, parse the filter set out into a filter set recognized\n# by the explore_data_page method and forward it on to that view, returning its response.\ndef parse_explore_filters(request):\n try:\n if not request.GET:\n raise Exception(\"This call only supports GET!\")\n raw_filters = {x: request.GET.getlist(x) for x in request.GET.keys()}\n filters = {}\n filter_ops = {}\n for x in raw_filters:\n if re.search('_op', x):\n filter_ops[x[:x.rfind('_')]] = raw_filters[x][0]\n else:\n filters[x] = raw_filters[x]\n # determine if any of the filters are misnamed\n filter_name_map = {(x[:x.rfind('_')] if re.search('_[gl]te?|_e?btwe?', x) else x): x for x in filters.keys()}\n attr_names = filter_name_map.keys()\n attrs = Attribute.objects.filter(name__in=attr_names)\n attr_map = {x.name: {\"id\": x.id, \"filter\": filter_name_map[x.name]} for x in attrs}\n not_found = [x for x in attr_names if x not in attr_map.keys()]\n blacklist = re.compile(settings.BLACKLIST_RE, re.UNICODE)\n if blacklist.search(str(filters)):\n logger.warning(\"[WARNING] Saw bad filters in filters_for_load:\")\n logger.warning(filters)\n messages.error(\n request,\n \"There was a problem with some of your filters - please ensure they're properly formatted.\"\n )\n else:\n if len(not_found) > 0:\n not_rec = \"{}\".format(\"; \".join(not_found))\n logger.warning(\"[WARNING] Saw invalid filters while parsing explore/filters call:\")\n logger.warning(not_rec)\n messages.warning(request, \"The following attribute names are not recognized: {}\".format(escape(not_rec)))\n else:\n if len(attrs) > 0:\n filters = [{\n \"id\": attr_map[x]['id'],\n \"values\": filters[attr_map[x]['filter']],\n \"op\": filter_ops.get(x, 'OR')\n } for x in attr_map]\n return explore_data_page(request, filter_path=True, path_filters=[{\"filters\": filters}])\n\n except Exception as e:\n logger.error(\"[ERROR] While parsing filters for the explorer page:\")\n logger.exception(e)\n\n return redirect(reverse('explore_data'))\n\n\n# Callback for recording the user's agreement to the warning popup\ndef warn_page(request):\n request.session['seenWarning'] = True;\n return JsonResponse({'warning_status': 'SEEN'}, status=200)\n\n\n# About page\ndef about_page(request):\n return render(request, 'idc/about.html', {'request': request})\n\n\n# User dashboard, where saved cohorts (and, in the future, uploaded/indexed data) are listed\n@login_required\ndef dashboard_page(request):\n context = {'request': request}\n\n try:\n # Cohort List\n cohort_perms = list(set(Cohort_Perms.objects.filter(user=request.user).values_list('cohort', flat=True)))\n # TODO: Add in 'date created' and sort on that\n context['cohorts'] = Cohort.objects.filter(id__in=cohort_perms, active=True).order_by('-name')\n\n except Exception as e:\n logger.error(\"[ERROR] While attempting to load the dashboard:\")\n logger.exception(e)\n\n return render(request, 'idc/dashboard.html', context)\n","sub_path":"idc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":26547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"128202785","text":"class Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n colDict = [defaultdict(int) for _ in range(9)]\n rowDict = [defaultdict(int) for _ in range(9)]\n boxDict = [defaultdict(int) for _ in range(9)]\n for i in range(9):\n for j in range(9):\n if board[i][j] != '.':\n x = int(board[i][j])\n boxIdx = self.getBoxIdx(i, j)\n rowDict[i][x] = 1\n colDict[j][x] = 1\n boxDict[boxIdx][x] = 1\n def fill(row, col, colDict, rowDict, boxDict):\n nextRow =row + (col + 1)//9\n nextCol = (col + 1)%9\n if row == 9: return True\n boxIdx = self.getBoxIdx(row, col)\n nextBoxIdx = self.getBoxIdx(nextRow, nextCol)\n #print(row, col)\n if board[row][col] != '.':\n return fill(nextRow, nextCol, colDict, rowDict, boxDict)\n for i in range(1, 10):\n if colDict[col][i] + rowDict[row][i] + boxDict[boxIdx][i] == 0:\n board[row][col] = str(i)\n colDict[col][i] = 1\n rowDict[row][i] = 1\n boxDict[boxIdx][i] = 1\n if fill(nextRow, nextCol, colDict, rowDict, boxDict): \n return True\n colDict[col][i] = 0\n rowDict[row][i] = 0\n boxDict[boxIdx][i] = 0\n board[row][col] = '.'\n return False\n fill(0, 0, colDict, rowDict, boxDict)\n return board\n \n def getBoxIdx(self, row, col):\n return 3*(row//3) + col//3\n ","sub_path":"37. Sudoku Solver.py","file_name":"37. Sudoku Solver.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"638321299","text":"class treeNode:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None \n\nclass BinaryTree:\n def __init__(self, cmpFnc):\n self.top = treeNode(None)\n self.cmpFnc = cmpFnc\n\n def recursiveFind(self, key, node):\n if (self.cmpFnc(key,node.value) == 0):\n return True\n elif (self.cmpFnc(key,node.value) < 0):\n if (node.left is None):\n return False\n else:\n return self.recursiveFind(key,node.left)\n elif (self.cmpFnc(key,node.value) > 0):\n if (node.right is None):\n return False\n else:\n return self.recursiveFind(key,node.right)\n else:\n print(\"oh no\")\n return False\n\n def find(self, key):\n return self.recursiveFind(key, self.top) \n\n def recursiveInsert(self, key, node):\n if (self.cmpFnc(key,node.value) == 0):\n #do nothing, it is already there\n waste = 0\n elif (self.cmpFnc(key,node.value) < 0):\n if (node.left is None):\n newNode = treeNode(key)\n node.left = newNode\n else:\n self.recursiveInsert(key, node.left)\n elif (self.cmpFnc(key,node.value) > 0):\n if (node.right is None):\n newNode = treeNode(key)\n node.right = newNode\n else:\n self.recursiveInsert(key, node.right)\n else:\n print(\"how??\")\n return False\n\n def insert(self, key):\n if self.top.value == None:\n self.top.value = key\n print(\"insert top\")\n else:\n self.recursiveInsert(key, self.top)\n print(\"insert value\")\n\n def inOrderTraversal(self, node, rvList):\n if (node.left is not None) :\n self.inOrderTraversal(node.left, rvList)\n rvList.append(node.value)\n if (node.left is not None) :\n self.inOrderTraversal(node.right, rvList)\n\n def traverse(self):\n newList = []\n self.inOrderTraversal(self.top, newList)\n return newList\n\n \n \n\n\n","sub_path":"Semester4_Spring2015/ProgrammingLanguagesAndSystems/hw9/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"542686281","text":"import os\n\n# map is a list of lists [[],[],[],[]], where each another list is next row in print\n# position on map is accesed by map[y][x]\n\ndef print_bcg(bcg):\n for each in bcg:\n print(\"\".join(each))\n\ndef controls(y, x, control, bcg):\n if control == \"w\":\n (y, x) = move_up(y, x, bcg)\n elif control == \"s\":\n (y, x) = move_down(y, x, bcg)\n elif control == \"a\":\n (y, x) = move_left(y, x, bcg)\n elif control == \"d\":\n (y, x) = move_right(y, x, bcg)\n return (y, x)\n\n\ndef move_up(y, x, bcg):\n if bcg[y-1][x] != \"X\":\n bcg[y][x] = ' '\n bcg[y-1][x] = '@'\n return (y-1, x)\n else:\n return (y, x)\n\ndef move_down(y, x, bcg):\n if bcg[y+1][x] != \"X\":\n bcg[y][x] = ' '\n bcg[y+1][x] = '@'\n return (y+1, x)\n else:\n return (y, x)\n\ndef move_left(y, x, bcg):\n if bcg[y][x-1] != \"X\":\n bcg[y][x] = ' '\n bcg[y][x-1] = '@'\n return (y, x-1)\n else:\n return (y, x)\n\ndef move_right(y, x, bcg):\n if bcg[y][x+1] != \"X\":\n bcg[y][x] = ' '\n bcg[y][x+1] = '@'\n return (y, x+1)\n else:\n return (y, x)\n\n\nbcg = []\ntemp_list = []\nfor i in range(0,50):\n temp_list.append('X')\nbcg.append(temp_list)\nfor i in range(0, 48):\n temp_list = ['X']\n for i in range(1,49):\n temp_list.append(' ')\n temp_list.append('X')\n bcg.append(temp_list)\n temp_list = []\nfor i in range(0,50):\n temp_list.append('X')\nbcg.append(temp_list)\n\nprint_bcg(bcg)\ny = 5\nx = 5\nbcg[5][5] = '@'\nprint_bcg(bcg)\n\ncontrol = None\nwhile control != \"exit\":\n control = input()\n (y, x) = controls(y, x, control, bcg)\n os.system(\"clear\")\n print_bcg(bcg)\n","sub_path":"try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"155158050","text":"import math\nfrom collections import OrderedDict\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.response import Response\n\n#Provide a maximum limit for http GET \":8000/drones/limit=8&offset=0\"\nclass LimitOffsetPaginationWithUpperBound(LimitOffsetPagination):\n #Set the maximum limit value to 20 for ?limit=100 we still return max of 20 instances\n max_limit = 20\n #default_limit is how many instances you want to return if the user does not\n #use a query param ?limit=N to indicate\n default_limit=10\n def get_paginated_response(self, data):\n return Response(OrderedDict([\n ('count', self.count),\n ('next', self.get_next_link()),\n ('previous', self.get_previous_link()),\n ('total_page_count',\n math.ceil(\n self.count / self.limit\n )\n ),\n ('limit', self.limit),\n ('offset', self.offset),\n ('results', data),\n ]))\n","sub_path":"backend/drones/custompagination.py","file_name":"custompagination.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"634128337","text":"def setup():\n size(600, 600)\n \ndef draw():\n background(255)\n translate(50, 450)\n sierprinski(400, 8)\n \ndef sierprinski(sz, level):\n if level == 0:\n fill(0)\n triangle(0, 0, sz, 0, sz / 2.0, -sz*sqrt(3)/2.0)\n else:\n for i in range(3):\n sierprinski(sz / 2.0, level-1)\n translate(sz/2.0, -sz*sqrt(3)/2.0)\n rotate(radians(120))\n","sub_path":"sierpinski/sierpinski.pyde","file_name":"sierpinski.pyde","file_ext":"pyde","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"21389725","text":"from chair.models import Order, Customer\nimport datetime\n\ndef custom_validate(order, customer):\n try:\n custom_error_list = []\n\n if customer.firstname and customer.lastname and len(customer.firstname + customer.lastname) > 30:\n custom_error_list.append(f'Name Error - customer name has > 30 characters')\n\n if customer.phone and (customer.phone.replace(\"+\", \"\").lstrip().startswith(\"0\") or customer.phone.replace(\"+\", \"\").lstrip().startswith(\"1\")):\n # Remove +'s strip the string after then check the leading digit\n # custom_error_list.append(f'Telephone Error - starts with \"{customer.phone[0]}\"')\n # Remove all +'s, -'s and white spaces then take everything but the first \n pn = customer.phone.replace(\"+\", \"\").lstrip()[1:].replace(\" \", \"\").replace(\"-\", \"\") + \"1\"\n # Just remove the digit and add \"1\" to the back of the customer's phone number to let it pass Newegg validation\n #'123-456-7890'\n #'234-567-8901'\n customer.phone = \"-\".join([pn[:3], pn[3:6], pn[6:]])\n\n if customer.street and (\"po box\" in customer.street.lower() or \"p.o. box\" in customer.street.lower()):\n custom_error_list.append(\"Address error - contains P.O. Box\")\n\n if customer.street and not any(char.isdigit() for char in customer.street):\n # Address string has no digits\n custom_error_list.append(\"Address error - has no numeric component\")\n\n if customer.street and len(customer.street) > 40:\n custom_error_list.append(\"Address error - has more than 40 characters\")\n\n other_occurances_this_customer = Customer.objects.filter(firstname__iexact=customer.firstname, lastname__iexact=customer.lastname).exclude(id=customer.id).values_list('id', flat=True)\n # No repeat customer handling - each customer has a different id - exclude the one of the current order to find his other orders\n if other_occurances_this_customer: \n # A customer with this firstname + lastname exists\n five_days_ago = datetime.datetime.utcnow() - datetime.timedelta(days=5)\n orders = Order.objects.filter(customer_id_id__in=other_occurances_this_customer, part_number=order.part_number).exclude(received__gt=five_days_ago).values_list('order_id', flat=True)\n # Find this customers other orders using the list of ids filter for this part only and remove orders older than 5 days ago\n if orders:\n # Repeated order\n custom_error_list.append(f'Order error - this customer has ordered this SKU in {\", \".join(orders)} within range of 5 days')\n\n if custom_error_list: \n s = \" \\n \"\n order.custom_error = s.join(custom_error_list)\n order.save()\n except AttributeError:\n print(f'Could not validate order {order.order_id} from customer {customer.id}, missing parameters')","sub_path":"chair/order_processing/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"330962633","text":"\"\"\"List of config validators.\"\"\"\n\nimport warnings\nfrom collections.abc import Iterable\nfrom functools import lru_cache\nfrom pathlib import Path\n\n\nclass ValidationError(ValueError):\n \"\"\"Custom validation error.\"\"\"\n\n\n# The code for this function was taken from matplotlib (v3.3) and modified\n# to fit the needs of eWaterCycle. Matplotlib is licenced under the terms of\n# the the 'Python Software Foundation License'\n# (https://www.python.org/psf/license)\ndef _make_type_validator(cls, *, allow_none=False):\n \"\"\"Construct a type validator for `cls`.\n\n Return a validator that converts inputs to *cls* or raises (and\n possibly allows ``None`` as well).\n \"\"\"\n def validator(inp):\n looks_like_none = isinstance(inp, str) and (inp.lower() == \"none\")\n if (allow_none and (inp is None or looks_like_none)):\n return None\n try:\n return cls(inp)\n except ValueError as err:\n if isinstance(cls, type):\n raise ValidationError(\n f'Could not convert {repr(inp)} to {cls.__name__}'\n ) from err\n raise\n\n validator.__name__ = f\"validate_{cls.__name__}\"\n if allow_none:\n validator.__name__ += \"_or_None\"\n validator.__qualname__ = (validator.__qualname__.rsplit(\".\", 1)[0] + \".\" +\n validator.__name__)\n return validator\n\n\n# The code for this function was taken from matplotlib (v3.3) and modified\n# to fit the needs of eWaterCycle. Matplotlib is licenced under the terms of\n# the the 'Python Software Foundation License'\n# (https://www.python.org/psf/license)\n@lru_cache()\ndef _listify_validator(scalar_validator,\n allow_stringlist=False,\n *,\n n_items=None,\n docstring=None):\n \"\"\"Apply the validator to a list.\"\"\"\n def func(inp):\n if isinstance(inp, str):\n try:\n inp = [\n scalar_validator(val.strip()) for val in inp.split(',')\n if val.strip()\n ]\n except Exception:\n if allow_stringlist:\n # Sometimes, a list of colors might be a single string\n # of single-letter colornames. So give that a shot.\n inp = [\n scalar_validator(val.strip()) for val in inp\n if val.strip()\n ]\n else:\n raise\n # Allow any ordered sequence type -- generators, np.ndarray, pd.Series\n # -- but not sets, whose iteration order is non-deterministic.\n elif isinstance(inp,\n Iterable) and not isinstance(inp, (set, frozenset)):\n # The condition on this list comprehension will preserve the\n # behavior of filtering out any empty strings (behavior was\n # from the original validate_stringlist()), while allowing\n # any non-string/text scalar values such as numbers and arrays.\n inp = [\n scalar_validator(val) for val in inp\n if not isinstance(val, str) or val\n ]\n else:\n raise ValidationError(\n f\"Expected str or other non-set iterable, but got {inp}\")\n if n_items is not None and len(inp) != n_items:\n raise ValidationError(f\"Expected {n_items} values, \"\n f\"but there are {len(inp)} values in {inp}\")\n return inp\n\n try:\n func.__name__ = \"{}list\".format(scalar_validator.__name__)\n except AttributeError: # class instance.\n func.__name__ = \"{}List\".format(type(scalar_validator).__name__)\n func.__qualname__ = func.__qualname__.rsplit(\".\",\n 1)[0] + \".\" + func.__name__\n if docstring is not None:\n docstring = scalar_validator.__doc__\n func.__doc__ = docstring\n return func\n\n\ndef validate_path(value, allow_none=False):\n \"\"\"Return a `Path` object.\"\"\"\n if (value is None) and allow_none:\n return value\n try:\n path = Path(value).expanduser().absolute()\n except TypeError as err:\n raise ValidationError(f\"Expected a path, but got {value}\") from err\n else:\n return path\n\n\nvalidate_string = _make_type_validator(str)\nvalidate_string_or_none = _make_type_validator(str, allow_none=True)\nvalidate_stringlist = _listify_validator(validate_string,\n docstring='Return a list of strings.')\nvalidate_int = _make_type_validator(int)\nvalidate_int_or_none = _make_type_validator(int, allow_none=True)\nvalidate_float = _make_type_validator(float)\nvalidate_floatlist = _listify_validator(validate_float,\n docstring='Return a list of floats.')\n\nvalidate_path_or_none = _make_type_validator(validate_path, allow_none=True)\n\nvalidate_pathlist = _listify_validator(validate_path,\n docstring='Return a list of paths.')\n\n_validators = {\n 'esmvaltool_config': validate_path_or_none,\n 'grdc_location': validate_path_or_none,\n 'container_engine': validate_string_or_none,\n 'singularity_dir': validate_path_or_none,\n 'output_dir': validate_path_or_none,\n 'ewatercycle_config': validate_path_or_none,\n # wflow specific\n 'wflow.singularity_image': validate_string_or_none,\n 'wflow.docker_image': validate_string_or_none,\n # marrmot specific\n 'marrmot.singularity_image': validate_string_or_none,\n 'marrmot.docker_image': validate_string_or_none,\n # lisflood specific\n 'lisflood.singularity_image': validate_string_or_none,\n 'lisflood.docker_image': validate_string_or_none,\n # pcrglobwb specific\n 'pcrglobwb.singularity_image': validate_string_or_none,\n 'pcrglobwb.docker_image': validate_string_or_none,\n}\n","sub_path":"ewatercycle/config/_validators.py","file_name":"_validators.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"456200364","text":"import uuid\n\nimport pytest\nimport time\n\nfrom labelbox.schema.labeling_frontend import LabelingFrontend\nfrom labelbox.schema.annotation_import import MALPredictionImport\n\n\n@pytest.fixture\ndef ontology():\n bbox_tool = {\n 'required':\n False,\n 'name':\n 'bbox',\n 'tool':\n 'rectangle',\n 'color':\n '#a23030',\n 'classifications': [{\n 'required': False,\n 'instructions': 'nested',\n 'name': 'nested',\n 'type': 'radio',\n 'options': [{\n 'label': 'radio_option_1',\n 'value': 'radio_value_1'\n }]\n }]\n }\n polygon_tool = {\n 'required': False,\n 'name': 'polygon',\n 'tool': 'polygon',\n 'color': '#FF34FF',\n 'classifications': []\n }\n polyline_tool = {\n 'required': False,\n 'name': 'polyline',\n 'tool': 'line',\n 'color': '#FF4A46',\n 'classifications': []\n }\n point_tool = {\n 'required': False,\n 'name': 'point--',\n 'tool': 'point',\n 'color': '#008941',\n 'classifications': []\n }\n entity_tool = {\n 'required': False,\n 'name': 'entity--',\n 'tool': 'named-entity',\n 'color': '#006FA6',\n 'classifications': []\n }\n segmentation_tool = {\n 'required': False,\n 'name': 'segmentation--',\n 'tool': 'superpixel',\n 'color': '#A30059',\n 'classifications': []\n }\n checklist = {\n 'required':\n False,\n 'instructions':\n 'checklist',\n 'name':\n 'checklist',\n 'type':\n 'checklist',\n 'options': [{\n 'label': 'option1',\n 'value': 'option1'\n }, {\n 'label': 'option2',\n 'value': 'option2'\n }, {\n 'label': 'optionN',\n 'value': 'optionn'\n }]\n }\n free_form_text = {\n 'required': False,\n 'instructions': 'text',\n 'name': 'text',\n 'type': 'text',\n 'options': []\n }\n\n tools = [\n bbox_tool, polygon_tool, polyline_tool, point_tool, entity_tool,\n segmentation_tool\n ]\n classifications = [checklist, free_form_text]\n return {\"tools\": tools, \"classifications\": classifications}\n\n\n@pytest.fixture\ndef configured_project(client, ontology, rand_gen, image_url):\n project = client.create_project(name=rand_gen(str))\n dataset = client.create_dataset(name=rand_gen(str))\n editor = list(\n client.get_labeling_frontends(\n where=LabelingFrontend.name == \"editor\"))[0]\n project.setup(editor, ontology)\n data_row_ids = []\n for _ in range(len(ontology['tools']) + len(ontology['classifications'])):\n data_row_ids.append(dataset.create_data_row(row_data=image_url).uid)\n project.datasets.connect(dataset)\n project.data_row_ids = data_row_ids\n yield project\n project.delete()\n dataset.delete()\n\n\n@pytest.fixture\ndef prediction_id_mapping(configured_project):\n #Maps tool types to feature schema ids\n ontology = configured_project.ontology().normalized\n result = {}\n\n for idx, tool in enumerate(ontology['tools'] + ontology['classifications']):\n if 'tool' in tool:\n tool_type = tool['tool']\n else:\n tool_type = tool['type']\n result[tool_type] = {\n \"uuid\": str(uuid.uuid4()),\n \"schemaId\": tool['featureSchemaId'],\n \"dataRow\": {\n \"id\": configured_project.data_row_ids[idx],\n },\n 'tool': tool\n }\n return result\n\n\n@pytest.fixture\ndef polygon_inference(prediction_id_mapping):\n polygon = prediction_id_mapping['polygon'].copy()\n polygon.update({\n \"polygon\": [{\n \"x\": 147.692,\n \"y\": 118.154\n }, {\n \"x\": 142.769,\n \"y\": 404.923\n }, {\n \"x\": 57.846,\n \"y\": 318.769\n }, {\n \"x\": 28.308,\n \"y\": 169.846\n }]\n })\n del polygon['tool']\n return polygon\n\n\n@pytest.fixture\ndef rectangle_inference(prediction_id_mapping):\n rectangle = prediction_id_mapping['rectangle'].copy()\n rectangle.update({\n \"bbox\": {\n \"top\": 48,\n \"left\": 58,\n \"height\": 865,\n \"width\": 1512\n },\n 'classifications': [{\n \"schemaId\":\n rectangle['tool']['classifications'][0]['featureSchemaId'],\n \"answer\": {\n \"schemaId\":\n rectangle['tool']['classifications'][0]['options'][0]\n ['featureSchemaId']\n }\n }]\n })\n del rectangle['tool']\n return rectangle\n\n\n@pytest.fixture\ndef line_inference(prediction_id_mapping):\n line = prediction_id_mapping['line'].copy()\n line.update(\n {\"line\": [{\n \"x\": 147.692,\n \"y\": 118.154\n }, {\n \"x\": 150.692,\n \"y\": 160.154\n }]})\n del line['tool']\n return line\n\n\n@pytest.fixture\ndef point_inference(prediction_id_mapping):\n point = prediction_id_mapping['point'].copy()\n point.update({\"point\": {\"x\": 147.692, \"y\": 118.154}})\n del point['tool']\n return point\n\n\n@pytest.fixture\ndef entity_inference(prediction_id_mapping):\n entity = prediction_id_mapping['named-entity'].copy()\n entity.update({\"location\": {\"start\": 67, \"end\": 128}})\n del entity['tool']\n return entity\n\n\n@pytest.fixture\ndef segmentation_inference(prediction_id_mapping):\n segmentation = prediction_id_mapping['superpixel'].copy()\n segmentation.update(\n {'mask': {\n 'instanceURI': \"sampleuri\",\n 'colorRGB': [0, 0, 0]\n }})\n del segmentation['tool']\n return segmentation\n\n\n@pytest.fixture\ndef checklist_inference(prediction_id_mapping):\n checklist = prediction_id_mapping['checklist'].copy()\n checklist.update({\n 'answers': [{\n 'schemaId': checklist['tool']['options'][0]['featureSchemaId']\n }]\n })\n del checklist['tool']\n return checklist\n\n\n@pytest.fixture\ndef text_inference(prediction_id_mapping):\n text = prediction_id_mapping['text'].copy()\n text.update({'answer': \"free form text...\"})\n del text['tool']\n return text\n\n\n@pytest.fixture\ndef video_checklist_inference(prediction_id_mapping):\n checklist = prediction_id_mapping['checklist'].copy()\n checklist.update({\n 'answers': [{\n 'schemaId': checklist['tool']['options'][0]['featureSchemaId']\n }]\n })\n\n checklist.update(\n {\"frames\": [{\n \"start\": 7,\n \"end\": 13,\n }, {\n \"start\": 18,\n \"end\": 19,\n }]})\n del checklist['tool']\n return checklist\n\n\n@pytest.fixture\ndef model_run_predictions(polygon_inference, rectangle_inference,\n line_inference):\n # Not supporting mask since there isn't a signed url representing a seg mask to upload\n return [polygon_inference, rectangle_inference, line_inference]\n\n\n@pytest.fixture\ndef object_predictions(polygon_inference, rectangle_inference, line_inference,\n entity_inference, segmentation_inference):\n return [\n polygon_inference, rectangle_inference, line_inference,\n entity_inference, segmentation_inference\n ]\n\n\n@pytest.fixture\ndef classification_predictions(checklist_inference, text_inference):\n return [checklist_inference, text_inference]\n\n\n@pytest.fixture\ndef predictions(object_predictions, classification_predictions):\n return object_predictions + classification_predictions\n\n\n@pytest.fixture\ndef model(client, rand_gen, configured_project):\n ontology = configured_project.ontology()\n data = {\"name\": rand_gen(str), \"ontology_id\": ontology.uid}\n model = client.create_model(data[\"name\"], data[\"ontology_id\"])\n yield model\n try:\n model.delete()\n except:\n # Already was deleted by the test\n pass\n\n\n@pytest.fixture\ndef model_run(rand_gen, model):\n name = rand_gen(str)\n model_run = model.create_model_run(name)\n yield model_run\n try:\n model_run.delete()\n except:\n # Already was deleted by the test\n pass\n\n\n@pytest.fixture\ndef model_run_annotation_groups(client, configured_project,\n annotation_submit_fn, model_run_predictions,\n model_run):\n configured_project.enable_model_assisted_labeling()\n\n upload_task = MALPredictionImport.create_from_objects(\n client, configured_project.uid, f'mal-import-{uuid.uuid4()}',\n model_run_predictions)\n upload_task.wait_until_done()\n label_ids = []\n for data_row_id in {x['dataRow']['id'] for x in model_run_predictions}:\n label_ids.append(\n annotation_submit_fn(configured_project.uid, data_row_id))\n model_run.upsert_labels(label_ids)\n time.sleep(3)\n yield model_run\n # TODO: Delete resources when that is possible ..\n","sub_path":"tests/integration/mal_and_mea/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"436142314","text":"import asyncio\nimport aiohttp\nimport http.cookiejar\nfrom lxml import etree, html\nimport re\nfrom DataPersistor import persist\nfrom bs4 import BeautifulSoup\nimport json\n\n\nclass scraper:\n def __init__(self):\n self.jar = http.cookiejar.CookieJar()\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'}\n self.baseURL = \"http://www.quamnet.com/\"\n self.news_list_basesURL = self.baseURL + \"newslist.action?listSectionCode=NEW_HOT&p=\"\n self.news_article_baseURL = self.baseURL + \"newscontent.action?articleId=\"\n self.public_news_title_list = []\n self.url_not_parsed = []\n self.loop = asyncio.get_event_loop()\n self.success_count = 0\n self.parse_title_count = 0\n self.page_fetched = []\n self.end_id = 0\n self.start_id = 0\n self.total_url_num = 0\n\n async def fetch_page(self, session, url):\n async with session.get(url, timeout=120) as response:\n # if the html sources is successfully load\n assert response.status == 200\n # return await response.read()\n return await response.text()\n\n # added the try catch mechanism back since the article crawling part is a little bit unstable\n async def issue_call(self, loop, session, sem, parser, url):\n async with sem:\n try:\n html = await self.fetch_page(session, url)\n self.page_fetched.append(url)\n print(\"\\npage %s download is done\\n\" % (url))\n collection = await parser(html, url)\n print(\"\\nParsing task %s is done\\n\" % (url))\n self.public_news_title_list.extend(collection) if type(\n collection) == list else self.public_news_title_list.append(collection)\n # self.public_news_title_list.extend(l)\n return collection\n except Exception as e:\n print(\"\\ncaught exception: [%s] in downloading page: [%s]\\n\" % (e, url))\n self.url_not_parsed.append(url)\n\n async def getNewsList(self, min, max):\n print(\"getNewsList\")\n\n current_page = max\n # each page currently display 30 news\n tasks = []\n # filling all the url that need to download to the tasks list\n # 300 concurrent request at a time; introdcuing the Semaphore mechanism\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n while current_page >= min:\n fullURL = self.news_list_basesURL + str(current_page)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_title, fullURL))\n tasks.append(task)\n current_page -= 1\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def parse_title(self, html_string, url):\n l = []\n tree = html.fromstring(str(html_string))\n title = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/a[@class=\"content_lt_blue_link\"]')\n url = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/a/@href')\n time = tree.xpath('//td[1]/table[4]/tr/td[@valign=\"top\"]/font[@class=\"q_datetime_grey\"]')\n\n for x in range(0, len(title)):\n news_dict = {\"article_id\": re.search(\"(?<==)(\\d+)\", str(url[x])).group(1), 'category': \"滾動新聞\",\n 'title': title[x].text, 'url': self.baseURL + url[x], 'time': time[x].text}\n l.append(news_dict)\n print(news_dict)\n self.parse_title_count += 1\n return l\n\n async def getNewsArticle(self, start_id, end_id):\n tasks = []\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n for id in range(start_id, end_id):\n fullURL = self.news_article_baseURL + str(id)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_news_article, fullURL))\n tasks.append(task)\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def getNewsArticle(self, l):\n tasks = []\n sem = asyncio.Semaphore(300)\n async with aiohttp.ClientSession() as session:\n for id in l:\n fullURL = self.news_article_baseURL + str(id)\n task = asyncio.ensure_future(self.issue_call(self.loop, session, sem, self.parse_news_article, fullURL))\n tasks.append(task)\n responses = await asyncio.gather(*tasks)\n return responses\n\n async def parse_news_article(self, html_string, url):\n l = []\n # create xpath object\n tree = html.fromstring(html_string)\n\n title = tree.xpath('//table/tr/td/font[@class=\"headline\"]/text()')\n source = tree.xpath('//table[3]/tr/td/font[3]/text()')\n date = tree.xpath('//table[3]/tr/td/font[2]/text()')\n\n soup = BeautifulSoup(html_string, 'html.parser')\n # removed the undesired tag from the soup first\n unwanted = [x.extract() for x in soup.findAll(\"span\", attrs={\"class\": \"content\"})]\n # print(unwanted)\n content = soup.find(\"font\", attrs={\"id\": \"article_content\"}).findAll(text=True)\n news_article_dict = {\"title\": title, \"date\": date, \"url\": url, \"source\": source, \"content\": content}\n\n for key, value in news_article_dict.items():\n # do something with value\n newvalue = \"\".join(map(str, value)).strip().replace(\"\\n\", \"\").replace(\"\\xa0\", \"\")\n news_article_dict[key] = newvalue\n\n l.append(news_article_dict)\n return l\n\n # The main loop -> run method\n def news_list_run(self, min, max):\n self.start_id = min\n self.end_id = max\n self.total_url_num = max - min\n future = asyncio.ensure_future(self.getNewsList(min, max))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_title\")\n persist().save_to_json(self.create_report, \"log/\", \"report\")\n return future\n\n # The main loop -> run method\n def news_article_run(self, min, max):\n self.start_id = min\n self.end_id = max\n self.total_url_num = max - min\n\n future = asyncio.ensure_future(self.getNewsArticle(min, max))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_articles\")\n persist().save_to_json(self.create_report, \"log/\", \"report\")\n return future\n\n # The main loop -> run method\n def news_article_run(self, l):\n self.start_id = l[0]\n self.end_id = l[-1]\n self.total_url_num = len(l) + 1\n\n future = asyncio.ensure_future(self.getNewsArticle(l))\n self.loop.run_until_complete(future)\n self.loop.close()\n # Last block of the logic, serialize the output with text file\n persist().save_to_json(self.public_news_title_list, \"document/\", \"news_articles\")\n persist().save_to_json(self.create_report(), \"log/\", \"report\")\n return future\n\n def create_report(self):\n report_dict = {\n \"start_id\": self.start_id,\n \"end_id\": self.end_id,\n \"total_url_to_parse\": self.total_url_num,\n \"url_failed\": self.url_not_parsed,\n \"page_failed\": len(self.url_not_parsed),\n \"success_rate\": (self.total_url_num - len(self.url_not_parsed)) / self.total_url_num,\n }\n\n return dict(report_dict)\n","sub_path":"QuamnetNewsScrapper.py","file_name":"QuamnetNewsScrapper.py","file_ext":"py","file_size_in_byte":7847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"81738837","text":"from django.db import models\n\nfrom stream_field import blocks\nfrom stream_field.blocks import admin_block\nfrom stream_field.fields import StreamField\n\n\nclass ChooseableModel(models.Model):\n text = models.TextField()\n\n\nclass StreamFieldModel(models.Model):\n\n body = StreamField([\n ('chooser', admin_block.ForeignKeyChooserBlock(ChooseableModel)),\n ('text', blocks.CharBlock()),\n ('List', blocks.ListBlock(blocks.URLBlock())),\n ('DateTime', blocks.DateTimeBlock()),\n ('Person', blocks.StructBlock([\n ('first_name', blocks.CharBlock()),\n ('last_name', blocks.CharBlock()),\n ('date_of_birth', blocks.DateBlock()),\n ('bio', blocks.TextBlock()),\n ])),\n ])\n","sub_path":"example/exampleapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"183918464","text":"\"Implements various metrics to measure training accuracy\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom sklearn.isotonic import IsotonicRegression\n\n\ndef isotonic(input_data, quantile_list):\n quantile_list = np.array(quantile_list).reshape(-1)\n batch_size = input_data.shape[0]\n new_output_data = []\n for i in range(batch_size):\n new_output_data.append(IsotonicRegression().fit_transform(quantile_list, input_data[i]))\n return np.stack(new_output_data, 0)\n\n\nclass HuberPinballLoss(nn.Module):\n __name__ = 'huber_pinball_loss'\n\n def __init__(self, quantile_levels, alpha=0.01):\n super(HuberPinballLoss, self).__init__()\n self.quantile_levels = torch.Tensor(quantile_levels).contiguous().reshape(1, -1)\n self.alpha = alpha\n\n def forward(self, predict_data, target_data):\n target_data = target_data.contiguous().reshape(-1, 1)\n batch_size = target_data.size()[0]\n predict_data = predict_data.contiguous().reshape(batch_size, -1)\n\n error_data = target_data - predict_data\n loss_data = torch.where(torch.abs(error_data) < self.alpha,\n 0.5 * error_data * error_data,\n self.alpha * (torch.abs(error_data) - 0.5 * self.alpha))\n loss_data = loss_data / self.alpha\n\n scale = torch.where(error_data >= 0,\n torch.ones_like(error_data) * self.quantile_levels,\n torch.ones_like(error_data) * (1 - self.quantile_levels))\n loss_data *= scale\n return loss_data.mean()\n\n\nclass PinballLoss(nn.Module):\n __name__ = 'pinball_loss'\n\n def __init__(self, quantile_levels):\n super(PinballLoss, self).__init__()\n if quantile_levels is None:\n self.quantile_levels = None\n else:\n self.quantile_levels = torch.Tensor(quantile_levels).contiguous().reshape(1, -1)\n\n def forward(self, predict_data, target_data):\n # compute error (batch_size x num_quantiles)\n target_data = target_data.contiguous().reshape(-1, 1)\n error_data = target_data - predict_data\n\n # compute pinball loss\n loss_data = torch.max(self.quantile_levels * error_data, (self.quantile_levels - 1) * error_data)\n\n # mean over samples (num_quantiles)\n return loss_data.mean()\n","sub_path":"tabular/src/autogluon/tabular/models/fastainn/quantile_helpers.py","file_name":"quantile_helpers.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"87088707","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('/', views.detail, name = \"detail\"),\n path('create', views.create, name = \"create\"),\n path('new/', views.new, name = \"new\"),\n path('newblog/', views.blogpost, name = \"newblog\"),\n path('blog/', views.blog, name = \"blog\"),\n path('plus/', views.plus, name = \"plus\"),\n path('search/', views.search, name = \"search\"),\n]","sub_path":"firstblog/blog1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"574776427","text":"from t2v_common import *\nimport requests,random\nfrom bs4 import BeautifulSoup\n\nDATE_RANGE_STR = '20180101_31' #'20171219_31' #'20180401_17' #'20180301_31' #'20180201_28' #\n\nDATA_DIR = '../twtrstyle' #'/Volumes/JYPENG-HD3/trendmicro/twtrstyle' #\nTWEETS_FILENAME = \"%s/tweets/tweets_%%s.gz\" % DATA_DIR\nUSERMAP_FILENAME = \"%s/usermap/usermap_%%s.gz\" % DATA_DIR\nUSERFILT_FILENAME = \"%s/userfilt/userfilt_%%s.gz\" % DATA_DIR\n\ndt_range = date_range_from_str(DATE_RANGE_STR,'d')\n\n#-----------------------------#\n#-- Collect Experiment Data --#\n#-----------------------------#\nstats = pd.DataFrame(columns=('orig_tweets','orig_users','filt_tweets','filt_users'))\ncounts = None\nfor dt in dt_range.strftime('%Y%m%d'):\n print(dt)\n #\n counts_dt = None\n for datehour in date_range_from_str(dt,'H').strftime('%Y%m%d%H'):\n t = read_prep(TWEETS_FILENAME % datehour,usecols=['id','created_at','text','truncated','has_media','user_id','interaction_24hr'])\n # u = read_prep(USERMAP_FILENAME % datehour)\n #\n # t['screen_name'] = u.loc[t.user_id,'screen_name'].values\n #\n c = t.groupby('user_id').interaction_24hr.agg(['count','sum']).rename(columns={'count':'N','sum':'c'})\n counts_dt = c if counts_dt is None else counts_dt.add(c,fill_value=0)\n #\n counts_dt['nc'] = counts_dt.c/counts_dt.N\n #\n mask = (counts_dt.N<=10) & (counts_dt.nc>=30)\n stats.loc[dt,'orig_tweets'] = counts_dt.N.sum()\n stats.loc[dt,'orig_users'] = len(counts_dt)\n stats.loc[dt,'filt_tweets'] = counts_dt[mask].N.sum()\n stats.loc[dt,'filt_users'] = len(counts_dt[mask])\n print(\" Original:\\n\\t%(orig_tweets)d Tweets\\n\\t%(orig_users)d Users\\n Filtered:\\n\\t%(filt_tweets)d Tweets\\n\\t%(filt_users)d Users\" % \n stats.loc[dt])\n #\n counts = counts_dt[['N','c']] if counts is None else counts.add(counts_dt[['N','c']],fill_value=0)\n\ncounts['nc'] = counts.c/counts.N\nmask = (counts.N<=10*len(dt_range)) & (counts.nc>100)\nstats.loc[DATE_RANGE_STR,'orig_tweets'] = counts.N.sum()\nstats.loc[DATE_RANGE_STR,'orig_users'] = len(counts)\nstats.loc[DATE_RANGE_STR,'filt_tweets'] = counts[mask].N.sum()\nstats.loc[DATE_RANGE_STR,'filt_users'] = len(counts[mask])\ncounts[['N','c']].astype(int).to_csv(USERFILT_FILENAME % DATE_RANGE_STR,compression='gzip')\n","sub_path":"t2v_expt_user.py","file_name":"t2v_expt_user.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"494125593","text":"# Libraries Import\nimport os\nimport pickle\nfrom datetime import datetime\nimport argparse\nimport matplotlib.pyplot as plt\nimport autograd.numpy as np\nimport sys\nimport shutil\nimport math\nimport random\nimport pickle\n\nimport data\nimport model\nfrom scipy.linalg import subspace_angles\nimport math\n\nfrom tqdm import tqdm\n\nimport torch\nfrom pyfiglet import Figlet\n\n\nos.system('clear')\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nprint(\"===============================================================================================\")\nf = Figlet(font='thin')\nprint(f.renderText('Invariance Baseline'))\nprint(\":::: Code by Adepu Ravi Shankar & Rahul-Vigneswaran K 2019 ::::\")\nprint(\"===============================================================================================\\n\")\n\n\n# Initialize Variables\n\nprev_hess = 0\nprev_eigval = 0\nprev_eigvec = 0\ninitial_model = []\n\nparser = argparse.ArgumentParser()\n # Hessian\nparser.add_argument('--top', type=int, default= 100,\n help='Dimension of the top eigenspace')\nparser.add_argument('--suffix', type=str, default='new',\n help='suffix to save npy array')\nparser.add_argument('--freq', type=int, default='1',\n help='freq of Hess calculation')\n\n\n# Data Generation\nparser.add_argument('--data-type', type=str, choices=['blob', 'circle', 'moon'], default='blob',\n help='Type of random data generation pattern.')\nparser.add_argument('--num-samples', type=int, default=1000,\n help='Number of training samples')\nparser.add_argument('--input-dim', type=int, default=5,\n help='Dimension of the input space')\nparser.add_argument('--num-classes', type=int, default=2,\n help='Number of classes in generated data. '\n 'Taken into account only by classifiers and data generators that support multi-class')\nparser.add_argument('--cov-factor', type=float, default=1.,\n help='Multiplier for the covariance of the data')\nparser.add_argument('--data-seed', type=int, default=None,\n help='Seed for random number generation of data generators')\n\n# Model\nparser.add_argument('--classifier', type=str, choices=['logreg', 'fullconn'], default='fullconn',\n help='Type of classifier. Logistic Regression, Fully-Connected NN.')\nparser.add_argument('--layer-sizes', nargs='*', type=int, default=[10, 5],\n help='Number of units in hidden layers. '\n 'First layer will have --input-dim units. Last layer will have --num-classes units.')\n\n# Training\nparser.add_argument('--batch-size', type=int, default=0,\n help='Number of samples in a training batch. '\n '0 means whole dataset')\nparser.add_argument('--learning-rate', type=float, default=0.01,\n help='Learning rate')\nparser.add_argument('--stopping-grad-norm', type=float, default=1e-4,\n help='Stop training if grad_norm becomes smaller than this threshold')\nparser.add_argument('--max-iterations', type=int, default=100,\n help='Cancel training after maximum number of iteration steps')\n\n# Results\nparser.add_argument('--hessian-calc-period', type=int, default=1,\n help='Calculate hessian at every N iteration. '\n '0 means do not calculate at intermediate iterations.')\nparser.add_argument('--results-folder', type=str, default='/home/ravi/eclipse-workspace/saguant/hessian-for-basicDL/hessianexps/results',\n help='Folder in which to put all results folders')\nparser.add_argument('--experiment-folder', type=str, default='defaults',\n help='Folder in which to write results files')\n\n# Hessian analysis\nparser.add_argument('--top-evals', type=int, default=100,\n help='Find top k evals')\nparser.add_argument('--bottom-evals', type=int, default=0,\n help='Find bottom k evals')\n\nargs = parser.parse_args()\n#args.layer_sizes = np.array(args.layer_sizes)\n\ndef yes_or_no() :\n while True:\n yes = {'yes','y', 'ye', ''}\n no = {'no','n'}\n\n choice = raw_input(\"Do you want me to delete the directory? (y/n) \\n\\n\").lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"\\nPlease respond with 'yes' or 'no' \\n\\n\")\n\ndef yes_or_no_image():\n while True:\n yes = {'yes', 'y', 'ye', ''}\n no = {'no', 'n'}\n\n choice = raw_input(\n \"Do you want to see the plot? (y/n) \\n\\n\").lower()\n if choice in yes:\n return True\n elif choice in no:\n return False\n else:\n sys.stdout.write(\"\\nPlease respond with 'yes' or 'no' \\n\\n\")\n\n\nargs.results_folder = os.getcwd() + '/' +'results/' + 'baseline/' +'B_size-'+str(args.batch_size)+'-Arch-'+str(args.input_dim)+str(args.layer_sizes)+'-iters-'+str(args.max_iterations)+'-data-'+str(args.data_type)+'-hess_freq-'+str(args.hessian_calc_period)+'-top-'+str(args.top)+'--freq-'+str(args.freq)+'--iter-'+str(args.max_iterations)\nif not os.path.exists(args.results_folder):\n os.mkdir(args.results_folder)\nelse: \n print(\"\\nDirectory already exists !!\\n\")\n a1 = yes_or_no()\n if a1 == True :\n shutil.rmtree(args.results_folder, ignore_errors=True) # Prompt to delete directory if it already exists\n print(\"====> Directory Deleted\")\n os.mkdir(args.results_folder)\n print(\"====> Directory recreated\\n\")\n print(\"===============================================================================================\\n\")\n\n\n else:\n print (\"Directory Already exists and was not opted for deletion.\\n\\n\")\n sys.exit()\n \nif args.classifier == 'logreg' and args.data_type == 'blob' and args.num_classes != 2:\n raise Exception('LogReg for more than 2 classes is not implemented yet.')\n\n\ndef main():\n inputs_train, targets_train, inputs_test, targets_test = data.generate_data(args)\n results = {\n 'inputs_train': inputs_train,\n 'targets_train': targets_train,\n 'inputs_test': inputs_test,\n 'targets_test': targets_test\n }\n \n mdl = model.create_model(args, inputs_train, targets_train) # Actual Model that is being observed\n mdl_test = model.create_model(args, inputs_train, targets_train) # Dummy Model for calculating gradient\n train_model(args, mdl, mdl_test, results)\n\n\ndef train_model(args, mdl, mdl_test, results):\n coeff = []\n ang_sb=[]\n ang_np=[]\n p_angles = []\n all_w=[]\n results['args'] = args\n loss=[]\n\n init_loss = mdl.loss(mdl.params_flat)\n init_grad_norm = np.linalg.norm(mdl.gradient(mdl.params_flat))\n print(\"\\n===============================================================================================\\n\")\n\n print('Initial loss: {}, norm grad: {}\\n'.format(init_loss, init_grad_norm))\n results['init_full_loss'] = init_loss\n results['init_full_grad_norm'] = init_grad_norm\n\n results['history1'] = []\n results['history1_columns'] = ['iter_no', 'batch_loss', 'batch_grad_norm', 'batch_param_norm']\n results['history2'] = []\n results['history2_columns'] = ['full_hessian', 'full_hessian_evals']\n\n for iter_no in tqdm(range(args.max_iterations), desc=\"Training Progress\", dynamic_ncols=True):\n inputs, targets = get_batch_samples(iter_no, args, mdl)\n batch_loss = mdl.loss(mdl.params_flat, inputs, targets)\n batch_grad = mdl.gradient(mdl.params_flat, inputs, targets)\n batch_grad_norm = np.linalg.norm(batch_grad)\n batch_param_norm = np.linalg.norm(mdl.params_flat)\n\n if iter_no % args.freq == 0:\n\n # calculating hessian\n hess = mdl.hessian(mdl.params_flat) # Calculating Hessian\n hess = torch.tensor(hess).float() # Converting the Hessian to Tensor\n eigenvalues, eigenvec = torch.symeig(hess,eigenvectors=True) # Extracting the eigenvalues and Eigen Vectors from the Calculated Hessian\n \n if iter_no == 0:\n prev_hess = hess\n prev_eigval = eigenvalues\n prev_eigvec = eigenvec\n \n top = args.top # This decides how many top eigenvectors are considered\n dom = eigenvec[:,-top:] # |The reason for negative top :: torch.symeig outputs eigen vectors in the increasing order and as a result |\n # | the top (maximum) eigenvectors will be atlast. |\n dom = dom.float()\n alpha=torch.rand(top) # A random vector which is of the dim of variable \"top\" is being initialized\n\n # Finding the top vector\n vec=(alpha*dom.float()).sum(1) # Representing alpha onto dominant eigen vector\n vec=vec/torch.sqrt((vec*vec).sum()) # Normalization of top vector\n# vec = vec*5\n\n # Finding gradient at top vec using Dummy network.\n mdl_test.params_flat = np.array(vec)\n \n \n batch_grad_mdl_test = mdl_test.gradient(mdl_test.params_flat, inputs, targets)\n mdl_test.params_flat -= batch_grad_mdl_test * args.learning_rate\n\n # Find coeff and append. But why do we need to find the coeffs ? \n c = torch.mv(hess.transpose(0,1), torch.tensor(mdl_test.params_flat).float())\n if np.size(coeff) == 0:\n coeff = c.detach().cpu().numpy()\n coeff = np.expand_dims(coeff, axis=0)\n else:\n coeff = np.concatenate((coeff,np.expand_dims(c.detach().cpu().numpy(),axis=0)),0) \n\n#\tStatistics of subspaces, (1) Angle between top subpaces\n eigenvalues_prev, eigenvec_prev = torch.symeig(prev_hess, eigenvectors = True)\n dom_prev = eigenvec_prev[:,-top:] # Is it not the same as the variable \"dom\" that was calculated earlier ?\n # calculation 1 norm, which is nothing but angle between subspaces\n ang=np.linalg.norm(torch.mm(dom_prev, dom.transpose(0,1)).numpy(),1)\n ang_sb.append(ang)\n ang = np.rad2deg(subspace_angles(dom_prev, dom))\n ang_np.append(ang)\n# Calculating principal angles\n u,s,v =torch.svd(torch.mm(dom.transpose(0, 1), dom_prev))\n # Output in radians\n s = torch.acos(torch.clamp(s,min=-1,max=1))\n s = s*180/math.pi\n# Attach 's' to p_angles\n if np.size(p_angles) == 0:\n p_angles = s.detach().cpu().numpy()\n p_angles = np.expand_dims(p_angles, axis=0)\n else:\n p_angles = np.concatenate((p_angles,np.expand_dims(s.detach().cpu().numpy(),axis=0)),0) \n prev_hess = hess\n prev_eigval = eigenvalues\n prev_eigvec = eigenvec\n\n# saving weights in all iterations\n if batch_grad_norm <= args.stopping_grad_norm:\n break\n mdl.params_flat -= batch_grad * args.learning_rate\n #print(mdl.params_flat)\n all_w.append(np.power(math.e,mdl.params_flat))\n # print('{:06d} {} loss: {:.8f}, norm grad: {:.8f}'.format(iter_no, datetime.now(), batch_loss, batch_grad_norm))\n loss.append(batch_loss)\n final_loss = mdl.loss(mdl.params_flat)\n final_grad_norm = np.linalg.norm(mdl.gradient(mdl.params_flat))\n print('\\nFinal loss: {}, norm grad: {}'.format(final_loss, final_grad_norm))\n args.suffix=args.results_folder+'/coeff.npy'\n np.save(args.suffix,coeff)\n args.suffix=args.results_folder+'/ang_sb.npy'\n np.save(args.suffix,ang_sb)\n args.suffix=args.results_folder+'/ang_np.npy'\n np.save(args.suffix,ang_np) \n args.suffix=args.results_folder+'/p_angles.npy'\n np.save(args.suffix,p_angles) \n args.suffix=args.results_folder+'/all_weights.npy'\n np.save(args.suffix,np.array(all_w))\n \n \n\n# Saving png plots\n coeff = torch.tensor(coeff)\n for i in range(coeff.shape[0]):\n a=torch.zeros(coeff[i].shape[0]).long()\n b=torch.arange(0, coeff[i].shape[0])\n c=torch.where(((coeff[i] > -0.1) & (coeff[i] < 0.1)),b,a)\n z = torch.zeros(coeff[i].shape[0]).fill_(0)\n z[torch.nonzero(c)] = coeff[i][torch.nonzero(c)]\n z = np.array(z)\n plt.plot(z)\n plt.xlabel('Dimension', fontsize=14)\n plt.ylabel('Coefficient', fontsize=14)\n pnpy = args.results_folder+'/plot1'\n plt.savefig(pnpy, format='png', pad_inches=5)\n\n\n return args.results_folder\n\n\ndef get_batch_samples(iter_no, args, mdl):\n \"\"\"Return inputs and outputs belonging to batch given iteration number.\"\"\"\n if args.batch_size == 0:\n return None, None\n\n num_batches = int(np.ceil(len(mdl.inputs) / args.batch_size))\n mod_iter_no = iter_no % num_batches\n start = mod_iter_no * args.batch_size\n end = (mod_iter_no + 1) * args.batch_size\n inputs = mdl.inputs[start:end]\n targets = mdl.targets[start:end]\n return inputs, targets\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n args.results_folder = main()\n print(\"\\n\\n The code has been successfully executed!!\\n\\n\")\n #a11 = yes_or_no_image()\n #if a11 == True :\n # pnpy = str(args.results_folder) + '/plot1' + '.png'\n # import cv2 \n # img = cv2.imread(pnpy) \n # cv2.imshow('Plot', img) \n # cv2.waitKey(0) \n # cv2.destroyAllWindows() \n # print(\"\\n\\n Tata!!\\n\\n\")\n #else:\n # print(\"\\n\\n Tata!!\\n\\n\")\n # \n print(\"\\n===============================================================================================\\n\")\n","sub_path":"baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":13835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"250612570","text":"\"\"\"\nLandon Buell\nNeural-Network-Projects-with-Python\nChapter 01 - Creating Neural Networks with Keras\n6 June 2021\n\"\"\"\n\n #### IMPORTS ####\n\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import SGD\n\n #### MAIN EXECUTABLE ####\n\nif __name__ == \"__main__\":\n\n # Create and model, and add a few layers\n model = Sequential(name=\"my_model\")\n model.add(Dense(units=4,activation='sigmoid',input_dim=3)) # layer 1\n model.add(Dense(units=1,activation='sigmoid')) # output layer\n\n # Get a summary of the model\n print(model.summary())\n print(\"\")\n \n # Compile w/ Optimizer & \n sgd = SGD(learning_rate=1)\n model.compile(optimizer=sgd,loss='mean_squared_error')\n\n # Genrate a Data Set\n np.random.seed(9)\n X = np.array([[0,0,1],\n [0,1,1],\n [1,0,1],\n [1,1,1]])\n Y = np.array([[0],[1],[1],[0]])\n\n # Train for 1500 iterations\n model.fit(X,Y,epochs=1500,verbose=1)\n\n # Get predictions\n print(model.predict(X))\n print(\"\")\n\n","sub_path":"Chapter01/KerasIntro.py","file_name":"KerasIntro.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"180463813","text":"\"\"\"\ncreated by nzh\nDate: 2018/9/21 上午11:00\n\"\"\"\n\n# 创建数组\n# 1. []\nlist1 = []\n\n# 2. list(iteralbe)\n# 给list函数传入一个可迭代变量,iterable可以是str,list,dict,set, tuple\n# 如果传入dict,那么dict的所有key会被提取到数组中\nlist2 = list(set((1, 2, 3)))\nlist2 = list({'a': 1, 'b': 2}) # output: ['a', 'b']\nlist2 = list('abc')\nlist2 = list((1,2,3))\n\n# 3. 列表生成式\nlist3 = [i for i in 'abc']\n# 列表生成式还可以加入筛选条件,比如过滤掉了'a'和'c'\nlist3 = [i for i in 'abc' if i not in ['a', 'c']]\n\n\n# 创建二维数组\nlist4 = ['a'] * 3 # output: ['a', 'a', 'a']\nlist4 = [{'a': 1, 'b': 2}] * 3 # output: [{'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {'a': 1, 'b': 2}]\nlist4 = [[]] * 3 # output: [[], [], []]\n# 由于内部的[]会被浅赋值,所以当修改其中一个元素时,其他[]也会被修改。\nlist4[0].append(3) # output: [[3], [3], [3]]\n# 可以使用列表生成式\n# for循环表示迭代的次数,[]表示生成的结果\nlist4 = [[] for i in range(3)]\nlist4[0].append(1)\nlist4[1].append([1,3])\n\nlist4 = [[0] * 3 for i in range(4)] #output: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]\nlist4[1].remove(0)\n\n\n###################################################\n# 查看python列表的内置函数\nbuilt_in_function_list = dir(list)\nprint(built_in_function_list)\n\n\n# 1. append,在list的末尾添加一个元素\n# append函数的返回值是None,函数会直接改变list的值\nlist5 = [1, 2, 3]\nappended_list = list5.append(4)\n# print(list5) # output: [1, 2, 3, 4]\n# print(appended_list) # output: None\n\n\n# 2. clear,清空list\n# clear函数的返回值���None\nclear_list = list5.clear()\n# print(list5) # output: []\n# print(clear_list) # output: None\n\n\n# 3. copy,对list进行浅复制\nlist6 = [{'a': 2}, 3, '4', 5.1234, [7, 7, 8]]\nshadow_copy = list6.copy()\n# print(list6) # output: [{'a': 2}, 3, '4', 5.1234, [7, 7, 8]]\nshadow_copy.append(9)\nshadow_copy[0] = 1\n# print(shadow_copy) # output: [1, 3, '4', 5.1234, [7, 7, 8], 9]\nshadow_copy[4].append(10)\n# print(shadow_copy) # output: [1, 3, '4', 5.1234, [7, 7, 8, 10], 9]\n\n\n# count,计算list中某个元素出现的次数\n# 传入一个值,返回list中这个值的个数\nlist7 = [[1] * 3, [2] * 2, [1], [1], [1] * 3]\n# print(list7) # output: [[1, 1, 1], [2, 2], [1], [1], [1, 1, 1]]\n# print(list7[0].count(1)) # output: 3\n\n\n# extend(iterable),扩展列表\n# extend接受一个可迭代对象,并将可迭代对象的每一个元素依次添加到list中\n# 如果iterable是dict,那么会依次添加dict的key到list中\nlist8 = [1, 2, 3, 4]\nlist8.append('abc')\n# print(list8) # output: [1, 2, 3, 4, 'abc']\nlist8.extend(['def'])\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def']\nlist8.extend('ipo')\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def', 'i', 'p', 'o']\nlist8.extend({'name': 'nzh', 'age': 18})\n# print(list8) # output: [1, 2, 3, 4, 'abc', 'def', 'i', 'p', 'o', 'name', 'age']\n\n\n# index(element, start, stop),返回element在list中的索引\nlist9 = [1, 2, 3, 4]\nindex = list9.index(4)\n# index函数还有其他参数start和end,用来指定索引的搜索范围\n# 包括start索引,但是不包括end索引,区间是左闭右开\n# 如果没有找到element,就会引发ValueError异常,提示:element is not in list\nlist10 = [1, 2, 3, 5, 4, 3, 2, 4, 1]\nindex = list10.index(1, 7, len(list10))\n# print(len(list10))\n# print(index) # output: 8\n\n\n# insert,在指定索引的地方添加元素,返回插入element之后的list\nlist11 = [1, 2, 3, 4, 5, 6, 7]\nlist11.insert(3, 100)\n# print(list11) # output: [1, 2, 3, 100, 4, 5, 6, 7]\n\n\n# pop(index),弹出指定索引处的元素\n# 从list11中弹出最后一个元素\nlist11.pop(-1)\n# print(list11) # output: [1, 2, 3, 100, 4, 5, 6]\n\n\n# remove(value), 删除指定的元素\n# 函数返回None\nlist11.remove(1)\n# print(list11) # output: [2, 3, 100, 4, 5, 6]\n# 当列表中有多个重复元素value时,删除第一个value\nlist12 = [1, 2, 1, 1]\nlist12.remove(1)\n# print(list12) # output: [2, 1, 1]\n# 当删除一个不存在的value时,抛出ValueError异常,提示x not in list\n# list12.remove(4) # raise Exception: ValueError\n\n\n# reverse(),颠倒list中的元素\n# 改变原始list,返回None\nlist13 = [1, 2, 3, 4]\nlist13.reverse()\n\n# 其他逆转list的方法\n# 比如内置的reversed(list)函数,会return一个list_reverseiterator类型的对象\n# 可以使用for或者列表生成式,再或者list()来生成一个新的list\n# print([i for i in reversed(list13)]) # output: [1, 2, 3, 4]\n# print(reversed(list13)) # output: \n# print(list(reversed(list13))) # output: [1, 2, 3, 4]\n\n# 除了上述操作,使用list的切片属性也能完成list反转\n# print(list13[::-1]) # output: [1, 2, 3, 4]\n\n\n# sort(),对list按照升序排序\nlist14 = [1, 3, 2, 1, 5, 4]\nlist14.sort()\n# print(list14) # output: [1, 1, 2, 3, 4, 5]\n# 降序排序\nlist14.sort(reverse=True)\n# print(list14) # output: [5, 4, 3, 2, 1, 1]","sub_path":"list_prictise/basic_use.py","file_name":"basic_use.py","file_ext":"py","file_size_in_byte":5124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"255033218","text":"# Write a function that accepts two positive integers as parameters. The first integer is the number of heads and the\n# second integer is the number of legs of all the creatures in a farm which consists of chickens and dogs.\n# Your function should calculate and return the number of chickens and number of dogs in the farm in a list as specified\n# below. If it is impossible to determine the correct number of chickens and dogs with the given information\n# then your function should return None.\n# your function should return a list that contains two numbers in this order [number_of_chickens, number_of_dogs]\ndef farm (heads, legs):\n #Check if it is at least 2 legs per heads\n if heads >= legs/ 2:\n return None\n elif legs % 2 != 0:\n return None\n\n chicken = 0\n dog = 0\n dogDiff = 0\n\n twoLegs = legs / 2\n if twoLegs > heads:\n dogDiff = twoLegs - heads\n dog = dogDiff\n chicken = (legs - (dogDiff * 4))/2\n\n return [dog, chicken]\n\nprint(farm(5, 12))","sub_path":"CSE1309x/chickenDogs.py","file_name":"chickenDogs.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"211466123","text":"# DFS\n# 20200811\n\ndef dfs(v): # v : 각 노��\n global curr_time\n mark[v] = 'visited'\n print(v, end=' ')\n\n pre[v] = curr_time\n curr_time += 1\n\n for i in edge:\n if v in i:\n if i[0] == v:\n if mark[i[1]]=='unvisited':\n parent[i[1]] = v\n #print(i[1])\n dfs(i[1])\n else:\n if mark[i[0]]=='unvisited':\n parent[i[0]] = v\n #print(i[0])\n dfs(i[0])\n post[v] = curr_time\n curr_time += 1\n\n \n\ndef dfsAll(G): # G = [1,2,3,4]\n for node in G:\n if mark[node] == 'unvisited':\n dfs(node)\n\n print()\n print(pre)\n print(post)\n\n \n\n\n\nN,M,V = input().split()\nN,M,V = int(N),int(M),int(V)\nedge = []\nnode = [i for i in range(1,N+1)] # node = [1,2,3,4]\nparent = [0]*(N+1) # parend = [0,0,0,0,0] \nmark = ['unvisited']*(N+1) # mark = ['unvisited','unvisited','unvisited'...]\nfor _ in range(M):\n edge.append(tuple(map(int,input().split())))\n\nedge.sort()\n\npre = [0]*(N+1)\npost = [0]*(N+1)\nglobal curr_time\ncurr_time = 1\n\ndfsAll(node)\n","sub_path":"DFS_goorm.py","file_name":"DFS_goorm.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"131466898","text":"import os\n\nif __name__ == \"__main__\":\n path_to_settings = os.path.join(os.path.expanduser(\"~\"), \"Documents\\Paradox Interactive\\Stellaris\\settings.txt\")\n while not os.path.exists(path_to_settings):\n print(\"Please print path to the Documents folder: \", end='')\n path_to_settings = os.path.join(input(), \"Paradox Interactive\\Stellaris\\settings.txt\")\n\n mod_list = []\n with open(path_to_settings, 'r') as file:\n mod_lines = False\n for line in file:\n if line == \"last_mods={\\n\":\n mod_lines = True\n continue\n if line == \"}\\n\" and mod_lines: # the closing bracket\n break\n if mod_lines:\n mod_list.append(line.split('_')[-1].split('.')[0])\n file.close()\n\n with open(\"master_mod_list.txt\", 'w') as file:\n for mod in mod_list:\n file.write(\"{}\\n\".format(mod))\n file.close()","sub_path":"PycharmProjects/Stellaris/StellarisModSynchronaizerMaster.py","file_name":"StellarisModSynchronaizerMaster.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"123669356","text":"import requests\nfrom flask import render_template, Blueprint, current_app, request\n\nfrom sqlalchemy import func\n\nfrom labmanager.db import db\nfrom labmanager.models import UseLog\n\nstats_blueprint = Blueprint('stats', __name__)\n\n@stats_blueprint.before_request\ndef check_auth():\n key = request.args.get(\"key\")\n if not key:\n return \"key missing\"\n\n if key != current_app.config.get(\"EASYADMIN_KEY\"):\n return \"Invalid key\"\n return\n\n@stats_blueprint.route(\"/\")\ndef simple():\n by_day = sorted(db.session.query(func.count(\"*\"), UseLog.date).group_by(UseLog.date).all(), lambda x, y: cmp(x[1], y[1]))\n return render_template(\"stats/index.html\", by_day = by_day)\n\n@stats_blueprint.route(\"/monthly\")\ndef monthly():\n try:\n failure_data = requests.get(\"http://composer.golabz.eu/translator/stats/status.json\").json()\n except:\n failure_data = {\n 'failing': [],\n 'flash': [],\n 'ssl': [],\n }\n\n lab_contents = requests.get('http://www.golabz.eu/rest/labs/retrieve.json').json()\n lab_per_url = {\n # url: lab_data\n }\n for lab in lab_contents:\n for lab_app in lab['lab_apps']:\n lab_per_url[lab_app['app_url']] = lab\n\n month_results = [\n # {\n # 'year': year,\n # 'month': month,\n # 'count': count,\n # }\n ]\n monthly_summary = {\n # (year, month): count\n }\n for count, year, month in db.session.query(func.count(\"id\"), UseLog.year, UseLog.month).group_by(UseLog.year, UseLog.month).all():\n month_results.append({\n 'year': year,\n 'month': month,\n 'count': count\n })\n monthly_summary[year, month] = count\n month_results.sort(lambda x, y: cmp(x['year'], y['year']) or cmp(x['month'], y['month']), reverse=True)\n\n temporal_month_url = {\n # (year, month): [ { 'count': count, 'url': url ]\n }\n for count, year, month, url in db.session.query(func.count(\"id\"), UseLog.year, UseLog.month, UseLog.url).group_by(UseLog.year, UseLog.month, UseLog.url).all():\n if (year, month) not in temporal_month_url:\n temporal_month_url[year, month] = []\n\n temporal_month_url[year, month].append({\n 'count': count,\n 'url': url,\n 'data': lab_per_url.get(url, {})\n })\n temporal_month_url[year, month].sort(lambda x, y: cmp(x['count'], y['count']), reverse=True)\n\n month_url_results = [\n # {\n # 'year': year,\n # 'month': month,\n # 'urls': [\n # { # sorted > to min\n # 'count': count,\n # 'url': url\n # }\n # ]\n # }\n ]\n for (year, month), results in temporal_month_url.items():\n month_url_results.append({\n 'year': year,\n 'month': month,\n 'count': monthly_summary[year, month],\n 'urls': results,\n })\n\n month_url_results.sort(lambda x, y: cmp(x['year'], y['year']) or cmp(x['month'], y['month']), reverse=True)\n return render_template(\"stats/monthly.html\", month_results=month_results, month_url_results=month_url_results, failure_data=failure_data)\n\n\n","sub_path":"labmanager/views/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"377867446","text":"import streamlit as st\nimport numpy as np\nimport pandas as pd\npd.set_option('display.max_rows', None)\nimport pandas_datareader as dr\nfrom datetime import datetime\nfrom datetime import timedelta\nimport math\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM, GRU\nfrom keras.preprocessing.sequence import TimeseriesGenerator\nfrom keras import callbacks\n\n\ndef app():\n\n st.write(\"\"\"\n # Prediction\n Enter a stock, date range, and training parameters to train a prediction model to generate prediction curves on that stock.\n \"\"\")\n\n #Create a sidebar header\n st.sidebar.header('Training Parameters:')\n\n def get_input():\n with open('./stock symbols.csv', 'r', encoding='utf-8-sig') as stock_file:\n stock_list = pd.read_csv(stock_file)\n symbols = stock_list.iloc[:, 0]\n selected = st.selectbox(label=\"\", options=symbols)\n index = stock_list[stock_list['Symbol'] == selected].index.values\n stock_symbol = stock_list['Symbol'][index].to_string(index=False)\n company_name = stock_list['Name'][index].to_string(index=False)\n start_date = st.sidebar.date_input(\"Starting Date:\", value=(datetime.today() - timedelta(days=365*3)), min_value=datetime(1817, 3, 8), max_value=datetime.today())\n end_date = st.sidebar.date_input(\"Ending Date:\", min_value=datetime(1817, 3, 8), max_value=datetime.today())\n epochs = st.sidebar.text_input(\"Enter Number of Epochs:\", 100)\n lag = st.sidebar.text_input(\"Enter Time Series Lag:\", 30)\n steps = st.sidebar.text_input(\"Enter Training Steps:\", 100)\n days = st.sidebar.text_input(\"Enter Prediction Length in Days:\", 30)\n pullback = st.sidebar.text_input(\"Pullback (Used for experiments):\", 0)\n return start_date, end_date, stock_symbol.strip(), company_name, int(epochs), int(lag), int(steps), int(days), int(pullback)\n\n global RMSE\n start_date, end_date, stock_symbol, company_name, epochs, lag, steps, days, pullback = get_input()\n\n ###Load and shape data\n df = dr.DataReader(stock_symbol, data_source='yahoo', start=start_date, end=end_date)\n prices = df.reset_index()['Adj Close']\n scaler = MinMaxScaler(feature_range=(0,1))\n prices = scaler.fit_transform(np.array(prices).reshape(-1,1))\n\n ###Split data into training and testing sets\n training_size = int(len(prices)*.65)\n training_data = prices[0:training_size, :]\n test_data = prices[training_size:len(prices), :]\n\n\n ###function to create time series datasets\n def create_timeseries(data, lag):\n t_series = TimeseriesGenerator(data, data, length=lag, batch_size=len(data))\n for i in range(len(t_series)):\n x, y = t_series[i]\n return np.array(x), np.array(y)\n\n ###generate time series for training and test sets\n x_train, y_train = create_timeseries(training_data, lag)\n x_test, y_test = create_timeseries(test_data, lag)\n\n ###reshape data for LSTM which requires 3D data\n x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\n x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], 1)\n\n ###create stacked LSTM model\n model = Sequential()\n model.add(LSTM(50, return_sequences=True, input_shape=(100,1)))\n model.add(LSTM(50, return_sequences=True))\n model.add(LSTM(50))\n model.add(Dense(1))\n model.compile(loss='mean_squared_error', optimizer='adam')\n\n if st.button(\"Train Model\"):\n bar = st.progress(0)\n class Callback(callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n bar.progress(((epoch+1)/epochs))\n\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=epochs, batch_size=64, verbose=1, callbacks=[Callback()])\n\n ###run trained model on train and test data, get RMSE, undo scaling\n train_predict = model.predict(x_train)\n test_predict = model.predict(x_test)\n math.sqrt(mean_squared_error(y_train, train_predict))\n RMSE = math.sqrt(mean_squared_error(y_test, test_predict))\n train_predict = scaler.inverse_transform((train_predict))\n test_predict = scaler.inverse_transform((test_predict))\n\n\n ###Reformat data to be plotted\n prices = scaler.inverse_transform(prices)\n prices = np.array(prices).reshape(len(prices))\n train_predict = np.array(train_predict).reshape(len(train_predict))\n test_predict = np.array(test_predict).reshape(len(test_predict))\n\n\n ###Load data into single dataframe and plot\n global data_df\n data_df = pd.DataFrame(columns=['Prices', 'Training Predictions', 'Testing Predictions'])\n data_df['Prices'] = prices\n data_df['Training Predictions'][(lag - 5):len(train_predict) + (lag - 5)] = train_predict\n data_df['Testing Predictions'][len(train_predict) + ((lag*2)-5):len(test_predict) + len(train_predict) + ((lag*2)-5)] = test_predict\n\n st.header(company_name + \" Training Results from \" + str(start_date) + \" to \" + str(end_date) + \"\\n\")\n st.line_chart(data_df)\n st.text(\"Epochs used: \" + str(epochs))\n st.text(\"Steps: \" + str(steps))\n st.text(\"Training RMSE: \" + str(RMSE))\n\n if st.button(\"Run Predictions\"):\n ###Use all data to train for predictions\n data = prices[:]\n\n\n ###function to create time series datasets\n def create_timeseries(data, lag):\n t_series = TimeseriesGenerator(data, data, length=lag, batch_size=len(data))\n for i in range(len(t_series)):\n x, y = t_series[i]\n return np.array(x), np.array(y)\n\n ###generate time series for training and test sets\n x_train, y_train = create_timeseries(data, lag)\n\n ###reshape data for LSTM which requires 3D data\n x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], 1)\n\n ###create stacked LSTM model\n model = Sequential()\n model.add(LSTM(50, return_sequences=True, input_shape=(100, 1)))\n model.add(LSTM(50, return_sequences=True))\n model.add(LSTM(50))\n model.add(Dense(1))\n model.compile(loss='mean_squared_error', optimizer='adam')\n\n bar = st.progress(0)\n\n class Callback(callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n bar.progress(((epoch + 1) / epochs))\n\n model.fit(x_train, y_train, epochs=epochs, batch_size=64, verbose=1,\n callbacks=[Callback()])\n\n\n ###Forecasting function takes number of steps (or lag days) to use to make prediction, and number of days to forecast out.\n def forecast(data, steps, days):\n n_steps = steps\n x_input = data[-steps:].reshape(1,-1)\n temp_input = list(x_input)\n temp_input=temp_input[0].tolist()\n lst_output = []\n i = 0\n while (i < days):\n\n if (len(temp_input) > n_steps):\n x_input = np.array(temp_input[1:])\n x_input = x_input.reshape(1, -1)\n x_input = x_input.reshape((1, n_steps, 1))\n yhat = model.predict(x_input, verbose=0)\n temp_input.extend(yhat[0].tolist())\n temp_input = temp_input[1:]\n lst_output.extend(yhat.tolist())\n i = i + 1\n else:\n x_input = x_input.reshape((1, n_steps, 1))\n yhat = model.predict(x_input, verbose=0)\n temp_input.extend(yhat[0].tolist())\n lst_output.extend(yhat.tolist())\n i = i + 1\n\n return lst_output\n lst_output = forecast(data[0:len(data)-pullback], steps, days)\n if(pullback != 0):\n prediction_RMSE = math.sqrt(mean_squared_error(data[len(data)-pullback:], lst_output))\n\n ###Convert data to dataframes and chart zoomed in view\n prices_df = pd.DataFrame(columns= ['Actual', 'Predictions'])\n prices_df['Actual'] = data_df['Prices']\n lst_output = scaler.inverse_transform(lst_output)\n lst_output = np.array(lst_output).reshape(len(lst_output))\n lst_output_df = pd.DataFrame(columns=['Actual','Predictions'])\n lst_output_df['Predictions'] = lst_output\n chart_df = pd.DataFrame(columns=['Actual', 'Predictions'])\n if(pullback == 0):\n chart_df = pd.concat([prices_df[['Actual', 'Predictions']], lst_output_df[['Actual', 'Predictions']]], ignore_index=True)\n else:\n chart_df['Actual'] = prices_df['Actual']\n chart_df['Predictions'] = np.nan\n chart_df['Predictions'][-pullback:] = lst_output_df['Predictions']\n\n st.header(company_name + \" Prediction (Zoomed In)\" + \" from \" + str(start_date) + \" to \" + str(end_date) + \" for \" + str(days) + \" days\\n\")\n st.line_chart(chart_df[-(steps+days):])\n\n ###Chart zoomed out view\n st.header(company_name + \" Prediction (Zoomed Out)\" + \" from \" + str(start_date) + \" to \" + str(end_date) + \" for \" + str(days) + \" days\\n\")\n st.line_chart(chart_df)\n st.text(\"Epochs: \" + str(epochs))\n st.text(\"Steps: \" + str(steps))\n if(pullback != 0):\n st.text(\"Prediction RMSE: \" + str(prediction_RMSE))\n\n\n\n\n\n\n\n\n\n","sub_path":"Prediction.py","file_name":"Prediction.py","file_ext":"py","file_size_in_byte":9428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"557684390","text":"# archives GIS job data into a .csv\n\nimport csv\nfrom time import strftime\nimport os\n\n\ndef jobs(c):\n try:\n c.execute('SELECT jobkey, jobtitle, lat, lng, city, state, formattedLocation, country from jobs_tbl;')\n\n locations = c.fetchall()\n\n locations_outfile = os.path.join('archived_data', 'jobs', strftime('%y%m%d_%H%M') + '.tsv')\n\n with open(locations_outfile, 'w') as csvfile:\n fieldnames = ['jobkey','jobtitle','lat', 'lng', 'city', 'state', 'location', 'country']\n writer = csv.DictWriter(csvfile, delimiter='\\t', fieldnames=fieldnames)\n writer.writeheader()\n for l in locations:\n writer.writerow({'jobkey': l[0], 'jobtitle': l[1], 'lat': l[2], 'lng': l[3], 'city': l[4], 'state':l[5], 'location': l[6], 'country':l[7]})\n\n except Exception as e:\n print('Archiving Job Locations Error', e)\n\n\ndef employers(c):\n try:\n c.execute('SELECT employer, sum_current, sum_avg from employers_tbl;')\n\n locations = c.fetchall()\n\n locations_outfile = os.path.join('archived_data', 'employers', 'locations_' + strftime('%y%m%d') + '.csv')\n\n print(locations_outfile)\n\n with open(locations_outfile, 'w') as csvfile:\n fieldnames = ['employer', 'sum_current', 'sum_avg']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for l in locations:\n writer.writerow({'lat': round(l[0],5), 'lng': round(l[1],5), 'location': l[2]})\n\n except Exception as e:\n print('Archiving Job Locations Error', e)\n","sub_path":"src/archive_data.py","file_name":"archive_data.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"546202990","text":"import scrapy\nfrom mpicture.items import MpictureItem\nimport requests\nclass SexypicSpider(scrapy.Spider):\n name = 'sexypic'\n # allowed_domains = ['b9102.com']\n start_urls = ['https://www.b9102.com/photo/photo_list.html?photo_type=23&page_index=1']\n\n\n\n def parse(self, response):\n\n # headers={\n # \":authority\": \"imagetupian.nypd520.com\",\n # \":method\": \"GET\",\n # # \":path\": /uploads/laoying/2020/2/2020226/80.jpg?max-age=3600\n # \":scheme\": \"https\",\n # \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n # \"accept-encoding\": \"gzip, deflate, br\",\n # \"accept-language\": \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\",\n # \"cache-control\": \"max-age=0\",\n # \"if-modified-since\": \"Wed, 26 Feb 2020 00:47:31 GMT\",\n # \"if-none-match\": 'W/\"5e55c023-48422\"',\n # \"sec-fetch-dest\": \"document\",\n # \"sec-fetch-mode\": \"navigate\",\n # \"sec-fetch-site\": \"none\",\n # \"sec-fetch-user\": \"?1\",\n # \"upgrade-insecure-requests\": \"1\",\n # \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.61\",\n # }\n\n current_item_list=response.xpath('//div[@class=\"box movie_list\"]/ul/li/a/@href').getall()\n for url in current_item_list:\n # headers[':path']=url+'?max-age=3600'\n yield scrapy.Request(url=response.urljoin(url),callback=self.dealwith_item)\n \n \n next_page_tmp=response.xpath('//div[@class=\"pagination\"]/a/@href').getall()\n next_page_url=next_page_tmp[-2]\n yield scrapy.Request(url=response.urljoin(next_page_url),callback=self.parse)\n\n def dealwith_item(self,response):\n catgery=response.xpath('//div[@class=\"post_title\"]/h1/text()').get()\n image_urls=response.xpath('//div[@class=\"post_content\"]/a/img/@src').getall()\n # for i in image_urls:\n # resp=requests.get(i)\n # if resp.status_code==200:\n # with open(image_urls.split('/')[-1],\"wb+\") as f:\n # f.write(resp.text)\n item=MpictureItem(catgery=catgery,image_urls=image_urls)\n # item=MpictureItem()\n # item['image_urls']=image_urls\n # item['catgery']=catgery\n print(\"_\"*50)\n print(item)\n yield item \n\n\n","sub_path":"mpicture/mpicture/spiders/sexypic.py","file_name":"sexypic.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"269548388","text":"from douglas.tests import PluginTest\nfrom douglas.plugins import yeararchives\n\n\nclass Test_yeararchives(PluginTest):\n def setUp(self):\n PluginTest.setUp(self, yeararchives)\n\n def tearDown(self):\n PluginTest.tearDown(self)\n\n def test_parse_path_info(self):\n for testin, testout in [\n (\"\", None),\n (\"/\", None),\n (\"/2003\", (\"2003\", None)),\n (\"/2003/\", (\"2003\", None)),\n (\"/2003/index\", (\"2003\", None)),\n (\"/2003/index.theme\", (\"2003\", \"theme\")),\n ]:\n \n self.assertEquals(yeararchives.parse_path_info(testin),\n testout)\n","sub_path":"douglas/tests/test_yeararchives.py","file_name":"test_yeararchives.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"196266420","text":"import numpy as np\n\n\nclass MatrixFactorizationModel:\n \"\"\"\n Basic Matrix Factorization Model\n \"\"\"\n\n def __init__(self, x_train, y_train, x_test, y_test, num_users, num_movies, k, alpha, beta, epochs, shuffle=False, verbose=False):\n \"\"\"\n\n :param x_train (ndarray) : 훈련 데이터 (userId, movieId)\n :param y_train (ndarray) : 훈련 데이터 라벨 (rating)\n :param x_test (ndarray) : 테스트 데이터 (userId, movieId)\n :param y_test (ndarray) : 테스트 데이터 라벨 (rating)\n :param num_users (int) : 전체 user 수\n :param num_movies (int) : 전체 movie 수\n :param k (int) : latent feature 크기\n :param alpha (float) : learning rate\n :param beta (float) : lambda, regularization parameter\n :param epochs (int) : training epochs\n :param shuffle (bool) : 훈련 데이터 shuffle\n :param verbose (bool) : print status\n \"\"\"\n\n self.train_size = x_train.shape[0]\n self.x_train = x_train\n self.y_train = y_train\n self.test_size = x_test.shape[0]\n self.x_test = x_test\n self.y_test = y_test\n self.num_users = num_users\n self.num_movies = num_movies\n self.k = k\n self.alpha = alpha\n self.beta = beta\n self.epochs = epochs\n self.shuffle = shuffle\n self.verbose = verbose\n\n # latent feature 초기화\n self.P = np.random.normal(size=(self.num_users+1, self.k)) # user latent feature\n self.Q = np.random.normal(size=(self.num_movies+1, self.k)) # movie latent feature\n\n # bias 초기화\n self.b_u = np.zeros(self.num_users) # user bias\n self.b_i = np.zeros(self.num_movies) # movie bias\n self.b = np.mean(self.y_train) # global bias, Mu, overall average rating\n\n def train(self):\n \"\"\"\n Matrix Factorization Model 학습, optimizer로 SGD를 이용하여 가중치 갱신\n :return: training_process (학습 진행 상황, epoch 별 rmse 값)\n \"\"\"\n training_process = []\n for epoch in range(self.epochs):\n cnt = 0\n if self.shuffle is True:\n idx = np.arange(self.x_train.shape[0])\n np.random.shuffle(idx)\n for (i, j), r in zip(self.x_train[idx], self.y_train[idx]):\n self.sgd(i, j, r)\n cnt += 1\n if self.verbose is True and cnt % 500000 == 0:\n s = \".\" * (cnt // 500000)\n print(\"\\rtraining\", s, end='')\n else:\n for (i, j), r in zip(self.x_train, self.y_train):\n self.sgd(i, j, r)\n cnt += 1\n if self.verbose is True and cnt % 500000 == 0:\n s = \".\" * (cnt // 500000)\n print(\"\\rtraining\", s, end='')\n\n rmse = self.rmse()\n _, test_error = self.test()\n training_process.append([epoch+1, rmse, test_error])\n\n if self.verbose is True:\n print(\" Epoch: %d, rmse = %.4f, test_error(rmse) = %.4f\" % (epoch + 1, rmse, test_error))\n\n return training_process\n\n def test(self):\n \"\"\"\n\n :param x_test (ndarray) : test data (userId, movieId)\n :param y_test (ndarray) : test data label(ratings)\n :return: preds, rmse (테스트 데이터에 대한 에측 값, rmse 값)\n \"\"\"\n preds = [] # test data에 대한 예측 값 리스트\n error = 0\n for (i, j), r in zip(self.x_test, self.y_test): # i: userId, j: movieId, r: 실제 rating 값\n pred = self.get_pred(i, j)\n preds.append(str(round(pred, 4)))\n error += pow(r - pred, 2)\n\n return preds, np.sqrt(error / self.test_size)\n\n def rmse(self):\n \"\"\"\n train data에 대한 rmse 값 계산\n :return: rooted mean square error 값\n \"\"\"\n error = 0\n for (i, j), r in zip(self.x_train, self.y_train): # i: userId, j: movieId, r: 실제 rating 값\n pred = self.get_pred(i, j)\n error += pow(r - pred, 2)\n return np.sqrt(error / self.train_size)\n\n def sgd(self, i, j, r):\n \"\"\"\n Stochastic Gradient Descent 수행\n\n :param i (int) : userId\n :param j (int) : movieId\n :param r (float) : 실제 rating 값\n \"\"\"\n pred = self.get_pred(i, j)\n error = r - pred\n\n # latent feature 갱신\n self.P[i, :] += self.alpha * (error * self.Q[j, :] - self.beta * self.P[i, :])\n self.Q[j, :] += self.alpha * (error * self.P[i, :] - self.beta * self.Q[j, :])\n\n # bias 갱신\n self.b_u[i] += self.alpha * (error - self.beta * self.b_u[i])\n self.b_i[j] += self.alpha * (error - self.beta * self.b_i[j])\n\n def get_pred(self, i, j):\n \"\"\"\n\n :param i (int) : userId\n :param j (int) : movieId\n :return: user i, movie j에 대해 모델이 예측한 rating 값\n \"\"\"\n pred = self.b + self.b_u[i] + self.b_i[j] + self.P[i, :].dot(self.Q[j, :].T)\n return pred\n\n def get_pred_matrix(self):\n \"\"\"\n\n :return: 모든 user x movie 조합에 대하여 예측한 matrix\n \"\"\"\n return self.b + self.b_u[:, np.newaxis] + self.b_i[np.newaxis:, ] + self.P.dot(self.Q.T)\n","sub_path":"Dataset2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"193694780","text":"import os\nimport sys\nimport uuid\n\nfrom ._uwsgi import uwsgi\n\n\nclass WebSocketClient(object):\n '''\n Default WebSocket client has a blocking recieve method, but still exports\n rest of uWSGI API.\n '''\n def __init__(self, environ, fd, timeout=5):\n self.environ = environ\n self.fd = fd\n self.timeout = timeout\n self.id = str(uuid.uuid1())\n self.connected = True\n self.ctx = uwsgi.request_context()\n\n def receive(self):\n return self.recv()\n\n def recv(self):\n try:\n return uwsgi.websocket_recv(request_context=self.ctx)\n except IOError:\n return None\n\n def recv_nb(self):\n return uwsgi.websocket_recv_nb(request_context=self.ctx)\n\n def send(self, msg, binary=False):\n if binary:\n return self.send_binary(msg)\n return uwsgi.websocket_send(msg, request_context=self.ctx)\n\n def send_binary(self, msg):\n return uwsgi.websocket_send_binary(msg, request_context=self.ctx)\n\n def send_from_sharedarea(self, id, pos):\n return uwsgi.websocket_send_from_sharedarea(id, pos)\n\n def send_binary_from_sharedarea(self, id, pos):\n return uwsgi.websocket_send_binary_from_sharedarea(id, pos)\n\n def close(self):\n self.connected = False\n\n\nclass WebSocketMiddleware(object):\n '''\n WebSocket Middleware that handles handshake and passes route a WebSocketClient.\n '''\n client = WebSocketClient\n\n def __init__(self, wsgi_app, websocket):\n self.wsgi_app = wsgi_app\n self.websocket = websocket\n\n def __call__(self, environ, start_response):\n handler = self.websocket.routes.get(environ['PATH_INFO'])\n\n if not handler or 'HTTP_SEC_WEBSOCKET_KEY' not in environ:\n return self.wsgi_app(environ, start_response)\n\n uwsgi.websocket_handshake(environ['HTTP_SEC_WEBSOCKET_KEY'], environ.get('HTTP_ORIGIN', ''))\n handler(self.client(environ, uwsgi.connection_fd(), self.websocket.timeout))\n return ''\n\n\nclass WebSocket(object):\n '''\n Flask extension which makes it easy to integrate uWSGI-powered WebSockets\n into your applications.\n '''\n middleware = WebSocketMiddleware\n\n def __init__(self, app=None, timeout=5):\n if app:\n self.init_app(app)\n self.timeout = timeout\n self.routes = {}\n\n def run(self, app=None, debug=False, host='localhost', port=5000, **kwargs):\n if not app:\n app = self.app.name + ':app'\n\n # kwargs are treated as uwsgi arguments\n if kwargs.get('master') is None:\n kwargs['master'] = True\n\n # boolean should be treated as empty value\n for k,v in kwargs.items():\n if v is True:\n kwargs[k] = ''\n\n # constructing uwsgi arguments\n uwsgi_args = ' '.join(['--{0} {1}'.format(k,v) for k,v in kwargs.items()])\n\n uwsgi_executable = \"{0}/uwsgi\".format(os.path.dirname(sys.executable))\n args = '{0} --http {1}:{2} --http-websockets {3} --wsgi {4}'.format(uwsgi_executable, host, port, uwsgi_args, app)\n\n # set enviromental variable to trigger adding debug middleware\n if self.app.debug or debug:\n args = 'FLASK_UWSGI_DEBUG=true {0} --python-autoreload 1'.format(args)\n\n # run uwsgi with our args\n print('Running: {0}'.format(args))\n sys.exit(os.system(args))\n\n def init_app(self, app):\n self.app = app\n\n if os.environ.get('FLASK_UWSGI_DEBUG'):\n from werkzeug.debug import DebuggedApplication\n app.wsgi_app = DebuggedApplication(app.wsgi_app, True)\n app.debug = True\n\n app.wsgi_app = self.middleware(app.wsgi_app, self)\n app.run = lambda **kwargs: self.run(**kwargs)\n\n def route(self, rule):\n def decorator(f):\n self.routes[rule] = f\n return f\n return decorator\n","sub_path":"flask_uwsgi_websocket/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"498382136","text":"import sys\n# 创建字符串、列表或元组对象\nlist = ['苹果','香蕉','橘子','桃子']\n# 创建迭代对象\niter_list = iter(list)\n# 迭代一次\n# print(next(iter_list))\n\n# 遍历\nflag = True\nwhile flag:\n try:\n print(next(iter_list))\n except StopIteration:\n print('end...')\n flag = False\n\n# 迭代器对象可以使用for 语句进行遍历\nstr = 'string'\niter_str = iter(str)\nfor s in iter_str:\n print(s, end=\" \")\n","sub_path":"迭代器和操作文件/Iterator.py","file_name":"Iterator.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"217736211","text":"coin1 = float(input(\"Coin 1: \"))\ncoin2 = float(input(\"Coin 2: \"))\ncoin3 = float(input(\"Coin 3: \"))\ncoin4 = float(input(\"Coin 4: \"))\ncost = float(input(\"Cost: \"))\npaid = float(input(\"Paid: \"))\nsort = []\nsort.append(coin1)\nsort.append(coin2)\nsort.append(coin3)\nsort.append(coin4)\nlist.sort(sort)\ntruepaid = paid\ntruecost = cost - truepaid\n\nwhile truepaid > truecost:\n if sort[0] <= truecost:\n while sort[0] <= truecost:\n truepaid += sort[0]\n if sort[1] <= truecost:\n while sort[1] <= truecost:\n truepaid += sort[1]\n if sort[2] <= truecost:\n while sort[2] <= truecost:\n truepaid += sort[2]\n if sort[3] <= truecost:\n while sort[3] <= truecost:\n truepaid += sort[3]\nprint (truepaid)\n","sub_path":"2011/6A.py","file_name":"6A.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"11399066","text":"# Project Euler Problem 039\n\n\n#-------------------------------------------------------------------------------------#\n# If p is the perimeter of a right angle triangle with integral length sides, \n# {a,b,c}, there are exactly three solutions for p = 120.\n#\n# {20,48,52}, {24,45,51}, {30,40,50}\n#\n# For which value of p ≤ 1000, is the number of solutions maximised?\n#-------------------------------------------------------------------------------------#\n\n\nPERIMETER = 1000\nMIN_PERIM = 12\n\n\ndef main():\n max_sols = 0\n p = PERIMETER\n max_count = 0\n\n # Honestly just brute force it, it's quick enough to not be too much of a burden\n while p >= MIN_PERIM:\n count = 0\n for a in range(1, p - 1):\n if p % a == 0:\n b = 1\n while (a + b) <= p:\n if (a ** 2 + b ** 2) == (p - (a + b)) ** 2:\n count += 1\n b += 1\n\n if count > max_count:\n max_count = count \n max_sols = p\n\n p -= 1\n\n print(max_sols)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/Problem039.py","file_name":"Problem039.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"443975322","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 13 12:05:38 2015\n\n@author: jlade\n\"\"\"\nnode_list = []\n\nclass Node():\n def __init__(self):\n self.connected_to = []\n global node_list\n node_list.append(self)\n\n def connect_to(self,node):\n if node == self:\n return 0\n elif node in self.connected_to:\n return 1\n else:\n self.connected_to.append(node)\n node.connect_to(self)\n \n def connect_to_multiple(self, nodes):\n for node in nodes:\n self.connect_to(node)\n\n\n","sub_path":"Objects_Vortrag/Listings/my_class2.py","file_name":"my_class2.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"44007262","text":"def ozgunliste(a):\r\n\r\n liste = []\r\n for i in a:\r\n if i not in liste:\r\n liste.append(i)\r\n\r\n return liste\r\n\r\nonerilen_liste = [1,2,5,7,6,6,9,45,54,25,12,35,1,7,25,'a','a','b',[3,4],[4,3]]\r\n\r\nprint(ozgunliste(onerilen_liste)) \r\n","sub_path":"11.ödev-özgün liste.py","file_name":"11.ödev-özgün liste.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"43451817","text":"\"\"\"Demonstrate the creation of a simple wxPython application.\"\"\"\n\nimport wx\n\n\nclass MainFrame(wx.Frame):\n \"\"\"Create and show the frame for the application.\"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Initialise the MainFrame class.\"\"\"\n super(MainFrame, self).__init__(*args, **kwargs)\n panel = MainPanel(self)\n sizer = wx.BoxSizer(orient=wx.VERTICAL)\n sizer.Add(panel)\n self.SetSizerAndFit(sizer)\n self.Show()\n\n\nclass MainPanel(wx.Panel):\n \"\"\"Create a panel to hold application widgets.\"\"\"\n def __init__(self, parent, *args, **kwargs):\n \"\"\"Initialise the MainPanel class.\"\"\"\n super(MainPanel, self).__init__(parent, *args, **kwargs)\n lbl_name = wx.StaticText(parent=self, label=\"Name:\")\n txt_name = wx.TextCtrl(parent=self, size=(150, -1))\n cmd_quit = wx.Button(parent=self, id=wx.ID_CANCEL)\n cmd_quit.Bind(wx.EVT_BUTTON, self.on_cmd_quit_click)\n sizer = wx.BoxSizer(orient=wx.VERTICAL)\n sizer.Add(lbl_name, flag=wx.ALL, border=10)\n sizer.Add(txt_name, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)\n sizer.Add(cmd_quit, flag=wx.LEFT|wx.RIGHT|wx.BOTTOM, border=10)\n self.SetSizer(sizer)\n\n def on_cmd_quit_click(self, event):\n \"\"\"Tear down processes and quit the application.\"\"\"\n del event\n quit()\n\nif __name__ == \"__main__\":\n \"\"\"Implement the wxPython loop.\"\"\"\n SCREEN_APP = wx.App()\n MAIN_FRAME = MainFrame(parent=None, title=\"Frame with widgets\")\n SCREEN_APP.MainLoop()\n","sub_path":"wx_python/snippets/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"485099929","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext\nfrom pinax.notifications.backends.base import BaseBackend\n\nfrom tools.iam_client import get_profile\n\n\nclass EmailBackend(BaseBackend):\n spam_sensitivity = 2\n\n def can_send(self, user, notice_type, scoping):\n can_send = super(EmailBackend, self).can_send(user, notice_type, scoping)\n if can_send and user.email:\n return True\n return False\n\n def deliver(self, recipient, sender, notice_type, extra_context):\n context = self.default_context()\n context.update({\n \"recipient\": recipient,\n \"sender\": sender,\n \"notice\": ugettext(notice_type.display),\n \"cloudEyeUrl\": settings.CLOUD_EYE_URL,\n })\n context.update(extra_context)\n\n # 将消息体中的回车换行符替换为html格式\n extra_context['pm_message'].body = str(extra_context['pm_message'].body.encode(\"utf-8\")).replace('\\r\\n', '
') \\\n .replace('\\n', '
').replace('\\\\r\\\\n', '
').replace('\\\\n', '
')\n\n subject = \"\".join(render_to_string(\"email/email_subject.txt\", {\n \"subject\": extra_context[\"pm_message\"].subject\n }).splitlines())\n body = render_to_string(\"email/email_body.html\", {\n \"extra_content\": extra_context,\n \"recipient\": recipient,\n })\n\n mail_sender_name = extra_context['pm_message'].sender.username\n mail_sender_profile = get_profile(mail_sender_name)\n if mail_sender_profile and mail_sender_profile[0].get(\"name\"):\n mail_from = mail_sender_profile[0].get(\"name\") + '<' + settings.DEFAULT_FROM_EMAIL + '>'\n else:\n mail_from = mail_sender_name + '<' + settings.DEFAULT_FROM_EMAIL + '>'\n # 屏蔽邮件发送功能\n send_mail(subject, body, mail_from, [recipient.email], html_message=body)\n","sub_path":"WiseEye/cmdb_back/frame/backends/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"648216406","text":"import h5py\nimport numpy as np\nfrom pathlib import Path\nimport torch\nfrom torch.utils import data\nfrom torch.utils.data.dataloader import default_collate\n\n\nclass HDF5Dataset(data.Dataset):\n \"\"\"Represents an abstract HDF5 dataset.\n \n Parameters:\n file_path: Path to the HDF5 file.\n dataset_names: List of dataset names to gather. \n Objects will be returned in this order.\n \"\"\"\n def __init__(self, file_path, partition):\n super().__init__()\n self.file_path = file_path\n self.partition = partition\n self.meta_dset = partition + '_metadata'\n # s3 is too risky and slow here\n self.h5f = h5py.File(file_path, 'r')\n\n def __len__(self):\n return self.h5f[self.partition].shape[0]\n \n def __getitem__(self, index):\n data = self.h5f[self.partition][index]\n #if self.meta_dset in self.h5f.keys():\n # metadata = self.h5f[self.meta_dset][index]\n #else:\n metadata = None\n return data, metadata\n \n\ndef id_collate(batch):\n new_batch = []\n ids = []\n for _batch in batch:\n new_batch.append(_batch[0])\n ids.append(_batch[1])\n return default_collate(new_batch), np.array(ids)\n \n\ndef get_n_params(model):\n trainable = filter(lambda x: x.requires_grad, model.parameters())\n n_params = sum([np.prod(p.size()) for p in trainable])\n return n_params\n\n\ndef get_gradient_norm(model):\n total_norm = 0\n for p in model.parameters():\n param_norm = p.grad.data.norm(2)\n total_norm += param_norm.item() ** 2\n return total_norm ** (0.5)\n\n\ndef get_quantiles(x):\n rank = np.searchsorted(sorted(x), x)\n quantile = rank / len(rank)\n return quantile\n\ndef match_ids(IDs, match_IDs, require_in_match=True):\n \"\"\" Match input IDs to another array of IDs (usually in a table)\n Return the rows aligned with input IDs\n Parameters\n ----------\n IDs : ndarray\n match_IDs : ndarray\n require_in_match : bool, optional\n Require that each of the input IDs occurs within the match_IDs\n Returns\n -------\n rows : ndarray\n Rows in match_IDs that match to IDs, aligned\n -1 if there is no match\n \"\"\"\n rows = -1 * np.ones_like(IDs).astype(int)\n # Find which IDs are in match_IDs\n in_match = np.in1d(IDs, match_IDs)\n if require_in_match:\n if np.sum(~in_match) > 0:\n raise IOError(\"qcat.match_ids: One or more input IDs not in match_IDs\")\n rows[~in_match] = -1\n #\n IDs_inmatch = IDs[in_match]\n # Find indices of input IDs in meta table -- first instance in meta only!\n xsorted = np.argsort(match_IDs)\n ypos = np.searchsorted(match_IDs, IDs_inmatch, sorter=xsorted)\n indices = xsorted[ypos]\n rows[in_match] = indices\n return rows","sub_path":"ulmo/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"216205380","text":"from tkinter import *\nimport tkinter.font\n\nimport sys\nimport os\n\nfrom rosie import RosieGUI\nfrom rosie.testing import TestAgent\nfrom mobilesim.rosie import MobileSimAgent\n\ndef launch_gui(rosie_config):\n root = Tk()\n eval_agent = MobileSimAgent(rosie_config)\n eval_agent.messages.append(\"!CMD cli pc -f\")\n eval_gui = RosieGUI(eval_agent, master=root)\n eval_gui.run()\n\ndef run_test(rosie_config):\n eval_agent = TestAgent(config_filename=rosie_config, write_to_stdout=True, source_output=\"summary\",\n task_test_output_filename='output/test-output.txt', watch_level=0)\n eval_agent.run_test('correct-output.txt')\n\n# Lookup $ROSIE_HOME\nrosie_home = \"\"\nif \"ROSIE_HOME\" in os.environ:\n rosie_home = os.environ[\"ROSIE_HOME\"]\nelse:\n print(\"ERROR: Requires ROSIE_HOME environment variable set\")\n sys.exit(0)\n\nrosie_config = \"agent/rosie.fill.config\"\n\nif \"--test\" in sys.argv:\n run_test(rosie_config)\nelse:\n launch_gui(rosie_config)\n\n","sub_path":"python/rosie/evaluation/modifiers/fill/run_rosie.py","file_name":"run_rosie.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"255085094","text":"import os\nimport sys\n\ntry:\n\tBOOL = os.path.exists(\"/home/test/flag.txt\")\n\tif BOOL == True:\n\t\tprint(\"What rights do you have with document 'flag.txt'?\")\n\telse:\n\t\tf = open(\"/root/flag.txt\",'r')\n\t\ta = f.read()\n\t\tprint(a)\n\t\tprint('you are brave')\nexcept:\n\tprint(\"you have make some mistake\")\n","sub_path":"Docker190924/ee.py","file_name":"ee.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"363669634","text":"#! /usr/bin/python\n\nfrom stick_figure import *\n\ndef collision_detect(x1,y1,w1,h1,x2,y2,w2,h2,debug,screen):\n\t\n\tif x2+w2>=x1>=x2 and y2+h2>=y1>=y2:\n\t\treturn True\n\telif x2+w2>=x1+w1>=x2 and y2+h2>=y1>=y2:\n\t\treturn True\n\telif x2+w2>=x1>=x2 and y2+h2>=y1+h1>=y2:\n\t\treturn True\n\telif x2+w2>=x1+w1>=x2 and y2+h2>=y1+h1>=y2:\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\tif debug == 0:\n\t\tpass\n\telif debug == 1:\n\t\tdraw_blocker(screen,red,[x1,y1,h1,w1])\n\t\tdraw_blocker(screen,red,[x2,y2,h2,w2])\n\n\n\n\n\nclass Player(object):\n\tdef __init__(self, screen, pos, size):\n\t\t# Instantiate with the position of player object\n\t\tself.x = pos[0]\n\t\tself.y = pos[1]\n\t\tself.screen = screen\n\t\tself.size = size\n\t\t\n\n\tdef move(self, x_move, y_move):\n\t\t# Move the player object\n\t\tself.x = self.x + x_move\n\t\tself.y = self.y + y_move\n\t\treturn (self.x, self.y)\n\n\tdef render(self):\n\t\tdraw_ball(self.screen, self.x, self.y)\n\n\nclass Projectile(object):\n\tdef __init__(self, screen, pos):\n\t\tself.x = pos[0]\n\t\tself.y = pos[1]\n\t\tself.screen = screen\n\n\tdef move(self, speed):\n\t\tself.x = self.x - speed\n\n\n\tdef render(self):\n\t\tdraw_bullet(self.screen, self.x, self.y)\n\n\n\n\n\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"138388976","text":"import os\nfrom setuptools import setup\n \nREADME = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\n \n# Allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n \nsetup(\n name = 'django-rest-framework-proxy-gateway',\n version = '1.0.0',\n packages = ['rest_framework_proxy_gateway', 'tests'],\n include_package_data = True,\n license = 'BSD License',\n description = 'Extends django-rest-framework-proxy to limit the http verbs.',\n long_description = README,\n install_requires=[\n 'django-rest-framework-proxy>=1.6.0,<1.7.0',\n ],\n test_suite='tests',\n url = 'http://www.example.com/',\n author = 'Gordon Collins',\n author_email = 'gordon.collins@excella.com',\n classifiers =[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'\n ]\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"171135533","text":"import os\nimport numpy as np\nimport pandas as pd\nimport sys\nimport pdb\nimport glob\nfrom collections import defaultdict\nfrom tensorboard.backend.event_processing.event_accumulator import EventAccumulator\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\n\ntestcases = {\n'loss curve of vgg16 on K80': 'K80_vgg16_64', \n'loss curve of vgg16 on P100': 'P100_vgg16_64',\n'loss curve of vgg16 on V100': 'V100_vgg16_64'\n}\n\nbase_dir = '/scratch/li.baol/tsrbrd_log/pwr_meas/round1/'\n\nfig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(5,5))\nfig.suptitle(\"loss curve during training\")\n\nfor key, value in testcases.items():\n log_dir = base_dir + value + '_*/'\n \n dirs = glob.glob(log_dir)\n dirs.sort()\n time_all = [] # time for all 10 reps\n loss_all = []\n \n for tc in dirs:\n model = tc.split('/')[5+1]\n iterator = EventAccumulator(tc).Reload()\n tag = 'loss'#iterator.Tags()['scalars'][3] # this is tag for loss\n \n loss = [item.value for item in iterator.Scalars(tag)]\n pdb.set_trace()\n wall_time = [t.wall_time for t in iterator.Scalars(tag)]\n relative_time = [(time - wall_time[0])/3600 for time in wall_time]\n \n time_all.append(relative_time)\n loss_all.append(loss)\n \n time_avg = [0] * len(time_all[0])\n loss_avg = [0] * len(time_all[0])\n \n for j in range(len(time_all)): # 10\n time_avg = np.add(time_all[j], time_avg)\n loss_avg = np.add(loss_all[j], loss_avg) \n \n time_avg = time_avg / len(time_all)\n loss_avg = loss_avg / len(time_all) * 100\n \n# clr = 'tab:orange' if 'vgg16' in value else 'tab:blue'\n# mkr = 'o' if 'K80' in value else '^'\n axs.plot(#time_avg, \n loss_avg, label = key)#, color = clr, marker = mkr)\n\naxs.set_xlabel('epoch') #'training time (h)')\naxs.set_ylabel('model loss')\n\naxs.legend(loc='center right')#, bbox_to_anchor=(1, 0.5))\n#axs.get_xaxis().set_minor_locator(MultipleLocator(0.5))\n#axs.get_yaxis().set_minor_locator(MultipleLocator(5))\naxs.grid(which='both', axis='both', linestyle=':', color='black')\n\n#plt.show()\nplt.savefig('vgg16.png')\n\n#pdb.set_trace()\n#df = pd.DataFrame(time_all, columns=[\"time(h)\"])\n#df.to_csv(result_base_dir + 'csv/' + testcase + '.csv', index=False)\n#\n#fig, axs = plt.subplots(1, 1, gridspec_kw={'hspace': 0, 'wspace': 0}, figsize=(12,5))\n#fig.suptitle(testcase + \" GPU time (h) to train 50 epochs\")\n# \n#x = np.arange(len(time_all))\n#axs.bar(x, time_all)\n#axs.set_xlabel('test rep (10 reps in total)')\n#axs.set_ylabel('time (h)')\n##axs.set_yticks(minor=True)\n#axs.get_yaxis().set_minor_locator(MultipleLocator(5))\n#\n#axs.grid(which='both', axis='y', linestyle=':', color='black')\n#time = int(sum(time_all) / len(time_all))\n#plt.savefig(result_base_dir + \"png/\" + testcase + '_time' + str(time) + \".png\")\n","sub_path":"examples/pwr_run/motivation/motivation2/motivation2.py","file_name":"motivation2.py","file_ext":"py","file_size_in_byte":2895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"147453198","text":"import boto3\nfrom botocore.client import Config\n\ns3 = boto3.resource('s3',config=Config(signature_version='s3v4'))\nbucket_name = 'sc-clipboard'\nkey_name = '08may2017_sc_mds_saral_exambasesumm_v3_1494318395.csv'\n\ndef file_stream():\n data_to_prepend = ''\n fileobj = s3.Object(bucket_name, key).get()['Body']\n for idx in range(5):\n chunk = fileobj.read(1)\n if idx == 1:\n yield headers + chunk\n else:\n yield chunk # Store the new object with .temp appended to the name\n \n \ntemp_key = key_name + \".temp\"\n# we have to keep track of all of our parts\npart_info_dict = {'Parts': []}\n# start the multipart_upload process\nmulti_part_upload = s3.create_multipart_upload(Bucket=bucket_name, Key=temp_key)\ncounter = 0\n# Part Indexes are required to start at 1\nfor part_index, line in enumerate(file_stream(), start=1):\n if counter == 5:\n break\n counter += 1\n # store the return value from s3.upload_part for later\n part = s3.upload_part(\n Bucket=bucket_name,\n Key=temp_key,\n # PartNumber's need to be in order and unique\n PartNumber=part_index,\n # This 'UploadId' is part of the dict returned in multi_part_upload\n UploadId=multi_part_upload['UploadId'],\n # The chunk of the file we're streaming.\n Body=line,\n )\n\n # PartNumber and ETag are needed\n part_info_dict['Parts'].append({\n 'PartNumber': part_index,\n # You can get this from the return of the uploaded part that we stored earlier\n 'ETag': part['ETag']\n })\n\n # This what AWS needs to finish the multipart upload process\n completed_ctx = {\n 'Bucket': bucket_name,\n 'Key': temp_key,\n 'UploadId': multi_part_upload['UploadId'],\n 'MultipartUpload': part_info_dict\n }\n\n# Complete the upload. This triggers Amazon S3 to rebuild the file for you.\n# No need to manually unzip all of the parts ourselves!\ns3.complete_multipart_upload(**completed_ctx)\n","sub_path":"s3_read.py","file_name":"s3_read.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"174234530","text":"import datetime\nimport unittest\n\nfrom baseplate.message_queue import MessageQueue, TimedOutError\nimport webtest\n\nfrom events import collector\n\n\nclass CollectorFunctionalTests(unittest.TestCase):\n def setUp(self):\n # we create the queues before the actual code can so that we can\n # override the max sizes to use these numbers which are safe to use\n # without extra privileges on linux\n self.events_queue = MessageQueue(name=\"/events\",\n max_messages=10, max_message_size=8192)\n self.errors_queue = MessageQueue(name=\"/errors\",\n max_messages=10, max_message_size=8192)\n\n class MockDatetime(datetime.datetime):\n @classmethod\n def utcnow(cls):\n return datetime.datetime(2015, 11, 17, 12, 34, 56)\n datetime.datetime = MockDatetime\n\n app = collector.make_app(global_config={}, **{\n \"key.TestKey1\": \"dGVzdA==\",\n \"msgq.events\": \"0xcafe\",\n \"msgq.errors\": \"0xdecaf\",\n \"allowed_origins\": \"example.com\",\n \"metrics.namespace\": \"eventcollector\",\n \"metrics.endpoint\": \"\",\n })\n self.test_app = webtest.TestApp(app)\n\n def tearDown(self):\n self.events_queue.queue.unlink()\n self.events_queue.queue.close()\n self.errors_queue.queue.unlink()\n self.errors_queue.queue.close()\n\n def test_batch(self):\n self.test_app.post(\"/v1\",\n '[{\"event1\": \"value\"}, {\"event2\": \"value\"}]',\n headers={\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"TestApp/1.0\",\n \"Date\": \"Wed, 25 Nov 2015 06:25:24 GMT\",\n \"X-Signature\": \"key=TestKey1, mac=d7aab40b9db8ae0e0b40d98e9c50b2cfc80ca06127b42fbbbdf146752b47a5ed\",\n },\n extra_environ={\n \"REMOTE_ADDR\": \"1.2.3.4\",\n },\n )\n\n event1 = self.events_queue.get(timeout=0)\n self.assertEqual(event1, '{\"ip\": \"1.2.3.4\", \"event\": {\"event1\": \"value\"}, \"time\": \"2015-11-17T12:34:56\"}')\n event2 = self.events_queue.get(timeout=0)\n self.assertEqual(event2, '{\"ip\": \"1.2.3.4\", \"event\": {\"event2\": \"value\"}, \"time\": \"2015-11-17T12:34:56\"}')\n\n with self.assertRaises(TimedOutError):\n self.errors_queue.get(timeout=0)\n\n def test_cors(self):\n response = self.test_app.options(\"/v1\", headers={\n \"Origin\": \"http://example.com\",\n \"Access-Control-Request-Method\": \"POST\",\n \"Access-Control-Request-Headers\": \"X-Signature\",\n })\n\n self.assertEqual(response.status_code, 204)\n","sub_path":"tests/functional_tests.py","file_name":"functional_tests.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"617102653","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport commands\nimport os\nimport threading\nimport time\nimport uuid\nimport json\nfrom Queue import Queue\nfrom bondVideo import utils\nfrom bondVideo import course_info\nimport logging.config\nfrom bondVideo.model import CourseVideo, camera_param\nfrom bondVideo.utils import t2s, getPath, getNow\nimport sys\nimport thread\nimport globalValues\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\nlogging.config.fileConfig(getPath(\"logger.conf\"))\nlogger = logging.getLogger(\"bondVideo\")\ncameraQueue = Queue()\nclass Consumer_even(threading.Thread):\n\n def __init__(self, t_name, queue):\n threading.Thread.__init__(self, name=t_name)\n self.data = queue\n\n def run(self):\n logger.info('job {0} start'.format('Consumer'))\n logger.info('开始处理等待开课的队列,大小:{0}'.format(self.data.qsize()))\n while True:\n if self.data.qsize() > 0:\n cameraQueue.put(self.data.get())\n else:break\n processJob(self,cameraQueue)\n\n '''\n 调用摄像头\n '''\ndef processJob(self,dataQueue):\n nowTime =time.strftime(\"%H:%M\")\n while True:\n if dataQueue.qsize() > 0:\n data = dataQueue.get()\n if data.startTime <= nowTime:\n logger.info(\"{0}-{1} 开始启动摄像头\".format(data.courseNo,data.classIdx))\n thread.start_new_thread(callCamera,(data,))\n else:\n logger.info(\"{0}-{1}-时间未到重新插入等待队列,开课时间 {2} 当前时间 {3} \"\n .format(data.courseNo,data.classIdx,\n data.startTime,nowTime))\n self.data.put(data)\n else:break\n logger.info(\"处理等待开课的队列任务结束\")\n\n\n\ndef callCamera(data):\n try:\n dicKey = data.courseNo+\"_\"+str(data.classIdx)\n if globalValues.GLOBAL_DIC_CAPTURE.has_key(dicKey):\n logger.info(\"{0}已经在 {1} 开始抓取,返回退出\".format(dicKey,\n globalValues.GLOBAL_DIC_CAPTURE[dicKey]))\n return\n globalValues.GLOBAL_DIC_CAPTURE[dicKey]= time.strftime(\"%Y-%m-%d %X\", time.localtime( time.time() ) )\n logger.info(\"{0}插入到已经开始抓取视屏的列表.当前已经执行抓取任务{1}条\"\n .format(dicKey ,len(globalValues.GLOBAL_DIC_CAPTURE)))\n duration = t2s(str(data.endTime)) - \\\n t2s(str(data.startTime))\n fileName = data.courseNo + \"_\" + \\\n str(data.classIdx) + \".data\"\n captureDir = utils.getConfig(\"sys\", \"captureDir\")\n downloadDir = utils.getConfig(\"sys\", \"downloadDir\")\n school_id = int(utils.getConfig(\"sys\", \"school_id\")),\n course_video = CourseVideo(\n id=str(uuid.uuid1()),\n cno=data.courseNo,\n class_time=data.classIdx,\n file_path=downloadDir + os.sep + fileName,\n school_id=school_id,\n video_unique='',\n video_status=0,\n video_id=0,\n video_file_size=0,\n video_add_time='1970-01-01 00:00:00',\n video_complete_time='1970-01-01 00:00:00',\n video_duration=duration,\n video_img='',\n upload_times=0,\n create_time=getNow(),\n update_time=getNow(),\n capture_status=1,\n post_status=0)\n\n #读取摄像头配置信息\n videoCamera = course_info.getCameraConf(school_id ,data.classRoom);\n\n if videoCamera==None:\n errmsg=\"{0}-{1}@[{2}]不存在对应关系\".format(school_id, dicKey, data.classRoom)\n logger.error(errmsg);\n #utils.sendMailNotifier(\"edu_room\", \"edu_room\", errmsg)\n #utils.sendSMSNotifier(\"edu_room\", \"[vod]\"+errmsg)\n return\n # 组织抓取参数\n jsonData = camera_param(\n fileName,\n downloadDir,\n captureDir,\n videoCamera.user,\n videoCamera.pwd,\n \"rapidjson\",\n duration,\n videoCamera.ip,\n videoCamera.port,\n videoCamera.channel\n )\n param = json.dumps(jsonData,separators=( ',',':'),default=lambda o: o.__dict__,sort_keys=False)\n param = param.replace('\"', '\\\\\"').replace(',', '\\\\,') # 抓视屏的脚本需要对JSON格式中的冒号 双引号 : \" 转义 不能有空格\n param = param+ \" \" + dicKey +\" > camera.log 2>&1 &\";\n cmd = utils.getConfig(\"sys\", \"capture_command\") + \" \" + param\n logger.info(cmd)\n course_info.addCourseVideo(course_video)\n os.system(cmd)\n logger.info(\"{0}调用抓取视屏完成\".format(dicKey))\n except Exception as e:\n logger.exception(\"{0}调用摄像头异常 :{1}\".format(dicKey,e))\n finally:\n logger.info(\"{0}调用摄像头程序完成!\".format(dicKey))\n\n\n\n","sub_path":"bondVideo/consumer_camera.py","file_name":"consumer_camera.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"344764601","text":"from numpy import *\nimport random as rd\nimport time\n\nuse_vision_walls = True\nuse_odorat_candies = True\nuse_odorat_snakes = True\n\nvision_walls_max = 2\nodorat_candies_max = 8\nodorat_snakes_max = 4\n\nepsilon = 0.01\ntau = 0.1\nalpha = 0.2\ngamma = 0.9\nreward_dead = -10\nreward_candy = 1\n\nuse_epsilon_greedy = True # Softmax otherwise\nuse_sarsa = True # Q-Learning otherwise\n\nMOVES = [\n (1, 0),\n (0, -1),\n (-1, 0),\n (0, 1)\n]\n\nsensors = [vision_walls_max for _ in range(4)] * use_vision_walls + [odorat_candies_max for _ in range(4)] * use_odorat_candies + [odorat_snakes_max for _ in range(4)] * use_odorat_snakes\nn_sensors = len(sensors)\nn_actions = 4\nactions = range(n_actions)\nn_states = (vision_walls_max ** (4 * use_vision_walls)) * (odorat_candies_max ** (4 * use_odorat_candies)) * (odorat_snakes_max ** (4 * use_odorat_snakes))\ndelimiter = \",\"\n\nclass IA():\n\n def __init__(self, agent_id, save = None):\n\n self.id = agent_id\n\n self.prev_s = None\n self.prev_a = None\n\n if save is None:\n self.q = zeros((n_states, n_actions))\n else:\n self.q = save\n\n def load(self, fichier):\n self.q = loadtxt(fichier, delimiter = delimiter)\n self.prev_s = None\n self.prev_a = None\n\n def save(self, fichier):\n savetxt(fichier, self.q, delimiter = delimiter)\n\n def numberize_state(self, s):\n r = 0\n m = 1\n for i in range(n_sensors):\n x = s[i]\n r += (x - 1) * m\n m *= sensors[i]\n if (x <= 0 or x > sensors[i]):\n print(i, x)\n time.sleep(100)\n raise Exception(\"Error: Bad sensor value\")\n return r\n\n def distance_to_candy(self, x, y, M):\n d = odorat_candies_max - 1\n for (a, b) in M.candies:\n d = min(d, abs(x - a) + abs(y - b))\n return d + 1\n\n def distance_to_snake(self, x, y, M):\n d = odorat_snakes_max - 1\n for agent in M.agents:\n if agent.id != self.id:\n for (a, b) in agent.pos:\n d = min(d, abs(x - a) + abs(y - b))\n return d + 1\n\n def convert_input(self, M):\n\n head = M.agents[self.id].getHead()\n x = head[0]\n y = head[1]\n values = []\n\n if use_vision_walls:\n vision_walls = []\n # Walls\n for i in range(len(MOVES)):\n (xx, yy) = MOVES[i]\n dist_wall = vision_walls_max\n if xx == 1:\n dist_wall = M.gridsize - x\n elif xx == -1:\n dist_wall = x + 1\n elif yy == 1:\n dist_wall = M.gridsize - y\n elif yy == -1:\n dist_wall = y + 1\n else:\n print(\"ERROR: shouldn't happen\")\n vision_walls.append(min(dist_wall, vision_walls_max))\n values += vision_walls\n\n if use_odorat_candies:\n odorat_candies = []\n odorat_candies.append(self.distance_to_candy(x + 1, y, M))\n odorat_candies.append(self.distance_to_candy(x, y - 1, M))\n odorat_candies.append(self.distance_to_candy(x - 1, y, M))\n odorat_candies.append(self.distance_to_candy(x, y + 1, M))\n values += odorat_candies\n\n if use_odorat_snakes:\n odorat_snakes = []\n odorat_snakes.append(self.distance_to_snake(x + 1, y, M))\n odorat_snakes.append(self.distance_to_snake(x, y - 1, M))\n odorat_snakes.append(self.distance_to_snake(x - 1, y, M))\n odorat_snakes.append(self.distance_to_snake(x, y + 1, M))\n values += odorat_snakes\n\n return values\n\n def proba_softmax(self, l):\n p = [exp(q_value / tau) for q_value in l]\n s = sum(p)\n return [x/s for x in p]\n\n def choose_action(self, s):\n l = self.q[s]\n if use_epsilon_greedy:\n if rd.random() < epsilon:\n return rd.choice(actions)\n return argmax(l)\n else:\n p = self.proba_softmax(l)\n somme = p[0]\n r = rd.random()\n i = 0\n while r > somme:\n i +=1\n somme += p[i]\n return i\n\n def print_choix(self, s):\n spaces = \" \" * 4\n l = [\"%.2f\" % x for x in self.q[s]]\n print(\"\")\n print(\"Espace de choix\")\n print(spaces + l[1])\n print(l[2] + spaces + l[0])\n print(spaces + l[3])\n print(\"\")\n\n def candy_found(self, M):\n return M.agents[self.id].has_eaten\n\n def act(self, M):\n reward = reward_candy * self.candy_found(M)\n s = self.numberize_state(self.convert_input(M))\n a = self.choose_action(s)\n if not (self.prev_s is None):\n if use_sarsa:\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * (reward + gamma * self.q[s][a])\n else:\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * (reward + gamma * max(self.q[s]))\n self.prev_a = a\n self.prev_s = s\n return a\n\n def dead(self):\n self.q[self.prev_s][self.prev_a] = (1 - alpha) * self.q[self.prev_s][self.prev_a] + alpha * reward_dead\n","sub_path":"IA/IA_rl.py","file_name":"IA_rl.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"415402548","text":"from mcpi.minecraft import Minecraft\r\nmc = Minecraft.create()\r\n\r\nimport random,time\r\n\r\n\r\nwhile True:\r\n x,y,z = mc.player.getTilePos()\r\n x = x+1\r\n for j in range(10):\r\n color = random.randrange(0,16)\r\n z = z+1\r\n mc.setBlock(x,y-1,z,35,color)\r\n time.sleep(20)\r\n ","sub_path":"untitled11.py","file_name":"untitled11.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"352852326","text":"# ======================================================================================================================\n# 将fasta文件进行分词,修改fastafilepath(源文件)和wordfilepath(目标文件存储路径)的路径即可\n# ======================================================================================================================\n# kmer切分\n# b = [document[i:i + 3] for i in range(len(document)) if i < len(document) - 2]\n# b = re.findall(r'.{3}', string)\n\nimport re\nimport time\n\nstart_time=time.time()\nfastafilepath = \"..\\\\data\\\\4mc\\\\4mc.txt\"\nwordfilepath = \"..\\\\data\\\\4mc\\\\4mcword.txt\"\n\nf = open(fastafilepath)\nf1 = open(wordfilepath, \"w\")\n\ndocuments = f.readlines()\nstring=\"\"\nflag=0\nfor document in documents:\n if document.startswith(\">\") and flag == 0:\n flag = 1\n continue\n elif document.startswith(\">\") and flag == 1:\n b = [string[i:i + 3] for i in range(len(string)) if i < len(string) - 2]\n word = \" \".join(b)\n f1.write(word)\n f1.write(\"\\n\")\n string = \"\"\n else:\n string += document\n string = string.strip()\nb = [string[i:i + 3] for i in range(len(string)) if i < len(string) - 2]\nword = \" \".join(b)\nf1.write(word)\nf1.write(\"\\n\")\n\nprint(\"训练结果已保存到{}该目录下!\\n\".format(wordfilepath))\n\nend_time = time.time()\nprint(\"耗时:{}s\\n\".format(end_time - start_time))\nf1.close()\nf.close()\n\n","sub_path":"LSTM/word2vec/Fasta2Segment.py","file_name":"Fasta2Segment.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"469228449","text":"import pygame,sys, random, time\r\nfrom pygame.locals import *\r\n#Set up pygame\r\npygame.init()\r\n\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\n\r\nMovespeed = 5\r\ndirection= 'right'\r\n#Set up the window\r\nwindowSurface=pygame.display.set_mode((400,400))\r\npygame.display.set_caption(\"Animation xD\")\r\nwindowSurface.fill(WHITE)\r\n#Set up and display the rectangular(Square) block\r\nblock=pygame.Rect(0,0,20,20)\r\npygame.draw.rect(windowSurface,BLACK,block)\r\npygame.display.update()\r\n#Run the game Loop\r\nwhile True:\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n #Draw the black background onto the surface\r\n windowSurface.fill(WHITE)\r\n\r\n\r\n if direction == 'right':\r\n block.right=block.right + Movespeed\r\n\r\n\r\n #Draw the player onto the surface\r\n pygame.draw.rect(windowSurface,BLACK,block)\r\n\r\n #Render the windowSurface object\r\n pygame.display.update()\r\n time.sleep(0.02)\r\n\r\n\r\n","sub_path":"2016/Animation.py","file_name":"Animation.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"329369496","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom keras.models import load_model\nfrom collections import deque\nimport time\nimport shap\n\n\nclass Model_module:\n def __init__(self):\n self.shap_result_postive = {'Normal':deque(maxlen=1), 'Ab21_01':deque(maxlen=1), 'Ab21_02':deque(maxlen=1), 'Ab20_04':deque(maxlen=1), 'Ab15_07':deque(maxlen=1), 'Ab15_08':deque(maxlen=1), 'Ab63_04':deque(maxlen=1), 'Ab63_02':deque(maxlen=1), 'Ab21_12':deque(maxlen=1), 'Ab19_02':deque(maxlen=1), 'Ab21_11':deque(maxlen=1), 'Ab23_03':deque(maxlen=1), 'Ab60_02':deque(maxlen=1), 'Ab59_02':deque(maxlen=1), 'Ab23_01':deque(maxlen=1), 'Ab23_06':deque(maxlen=1)}\n self.shap_result_negative = {'Normal':deque(maxlen=1), 'Ab21_01':deque(maxlen=1), 'Ab21_02':deque(maxlen=1), 'Ab20_04':deque(maxlen=1), 'Ab15_07':deque(maxlen=1), 'Ab15_08':deque(maxlen=1), 'Ab63_04':deque(maxlen=1), 'Ab63_02':deque(maxlen=1), 'Ab21_12':deque(maxlen=1), 'Ab19_02':deque(maxlen=1), 'Ab21_11':deque(maxlen=1), 'Ab23_03':deque(maxlen=1), 'Ab60_02':deque(maxlen=1), 'Ab59_02':deque(maxlen=1), 'Ab23_01':deque(maxlen=1), 'Ab23_06':deque(maxlen=1)}\n self.selected_para = pd.read_csv('./DataBase/Final_parameter_200825.csv')\n\n\n def flatten(self, X):\n '''\n Flatten a 3D array.\n\n Input\n X A 3D array for lstm, where the array is sample x timesteps x features.\n\n Output\n flattened_X A 2D array, sample x features.\n '''\n flattened_X = np.empty((X.shape[0], X.shape[2])) # sample x features array.\n for i in range(X.shape[0]):\n flattened_X[i] = X[i, (X.shape[1] - 1), :]\n return (flattened_X)\n\n\n def load_model(self):\n # Model Code + Weight (나중에..)\n # Compile False Option -> Very fast model load\n self.train_untrain_lstm_autoencoder = load_model('model/Train_Untrain_epoch27_[0.00225299]_acc_[0.9724685967462512].h5', compile=False)\n self.multiple_xgbclassification = pickle.load(open('model/Lightgbm_max_depth_feature_137_200825.h5', 'rb')) # multiclassova\n self.explainer = pickle.load(open('model/explainer.pkl', 'rb')) # pickle로 저장하여 로드하면 더 빠름.\n self.normal_abnormal_lstm_autoencoder = load_model('model/node32_Nor_Ab_epoch157_[0.00022733]_acc_[0.9758567350470185].h5', compile=False)\n self.ab_21_01_lstmautoencoder = load_model('model/ab21-01_epoch74_[0.00712891]_acc_[0.9653829136428816].h5', compile=False)\n self.ab_21_02_lstmautoencoder = load_model('model/ab21-02_epoch200_[0.01140293]_acc_[0.8144184191122964]_rev1.h5', compile=False)\n self.ab_20_04_lstmautoencoder = load_model('model/ab20-04_epoch62_[0.00121183]_acc_[0.9278062539244847].h5', compile=False)\n self.ab_15_07_lstmautoencoder = load_model('model/ab15-07_epoch100_[0.00048918]_acc_[0.9711231231353337].h5', compile=False)\n self.ab_15_08_lstmautoencoder = load_model('model/ab15-08_epoch97_[0.00454363]_acc_[0.9602876916386659].h5', compile=False)\n self.ab_63_04_lstmautoencoder = load_model('model/ab63-04_epoch92_[0.00015933]_acc_[0.9953701129330438].h5', compile=False)\n self.ab_63_02_lstmautoencoder = load_model('model/ab63-02_epoch100_[0.00376744]_acc_[0.8948400650463064].h5', compile=False)\n self.ab_21_12_lstmautoencoder = load_model('model/ab21-12_epoch40_[0.00236955]_acc_[0.9473147939642043].h5', compile=False)\n self.ab_19_02_lstmautoencoder = load_model('model/ab19-02_epoch200_[0.00610265]_acc_[0.8852787664918006]_rev1.h5', compile=False)\n self.ab_21_11_lstmautoencoder = load_model('model/ab21-11_epoch98_[0.00265125]_acc_[0.9907740136695732].h5', compile=False)\n self.ab_60_02_lstmautoencoder = load_model('model/ab60-02_epoch100_[0.00370811]_acc_[0.989989808320697].h5', compile=False)\n self.ab_23_03_lstmautoencoder = load_model('model/ab23-03_epoch91_[0.00017211]_acc_[0.9931771647209489].h5', compile=False)\n self.ab_59_02_lstmautoencoder = load_model('model/ab59-02_epoch98_[0.00424398]_acc_[0.9923899523150299].h5', compile=False)\n self.ab_23_01_lstmautoencoder = load_model('model/ab23-01_epoch93_[0.00314694]_acc_[0.9407692298522362].h5', compile=False)\n self.ab_23_06_lstmautoencoder = load_model('model/ab23-06_epoch96_[0.00584512]_acc_[0.8694280893287306].h5', compile=False)\n return\n\n\n def train_untrain_classifier(self, data):\n # LSTM_AutoEncoder를 활용한 Train / Untrain 분류\n train_untrain_prediction = self.train_untrain_lstm_autoencoder.predict(data) # 예측\n train_untrain_error = np.mean(np.power(self.flatten(data) - self.flatten(train_untrain_prediction), 2), axis=1)\n if train_untrain_error[0] <= 0.00225299:\n train_untrain_result = 0 # trained condition\n else:\n train_untrain_result = 1 # untrained condition\n return train_untrain_result\n\n def abnormal_procedure_classifier_0(self, data):\n self.abnormal_procedure_prediction = self.multiple_xgbclassification.predict(data) # Softmax 예측 값 출력\n self.diagnosed_scenario = np.argmax(self.abnormal_procedure_prediction, axis=1)[0]\n self.shap_value = self.explainer.shap_values(data) # Shap_value 출력\n return self.abnormal_procedure_prediction, self.diagnosed_scenario\n\n def abnormal_procedure_classifier_1(self):\n diagnosis_convert_text = {0: 'Normal', 1: 'Ab21_01', 2: 'Ab21_02', 3: 'Ab20_04', 4: 'Ab15_07', 5: 'Ab15_08',\n 6: 'Ab63_04', 7: 'Ab63_02', 8: 'Ab21_12',9: 'Ab19_02', 10: 'Ab21_11', 11: 'Ab23_03',\n 12: 'Ab60_02', 13: 'Ab59_02', 14: 'Ab23_01', 15: 'Ab23_06'}\n sort_shap_values_positive = pd.DataFrame(self.shap_value[np.argmax(self.abnormal_procedure_prediction, axis=1)[0]], columns=self.selected_para['0'].tolist()).sort_values(by=0, ascending=False, axis=1)\n drop_shap_values_positive = sort_shap_values_positive[sort_shap_values_positive.iloc[:]>0].dropna(axis=1).T\n reset_shap_values_positive = drop_shap_values_positive.reset_index()\n column_positive = reset_shap_values_positive['index']\n var_positive = [self.selected_para['0'][self.selected_para['0'] == col_].index for col_ in column_positive]\n val_col_positive = [self.selected_para['1'][var_].iloc[0] for var_ in var_positive]\n proba_positive = [(reset_shap_values_positive[0][val_num]/sum(reset_shap_values_positive[0]))*100 for val_num in range(len(reset_shap_values_positive))]\n val_system_positive = [self.selected_para['2'][var_].iloc[0] for var_ in var_positive]\n reset_shap_values_positive['describe'] = val_col_positive\n reset_shap_values_positive['probability'] = proba_positive\n reset_shap_values_positive['system'] = val_system_positive\n self.shap_result_postive[diagnosis_convert_text[np.argmax(self.abnormal_procedure_prediction, axis=1)[0]]].append(reset_shap_values_positive)\n return self.shap_result_postive\n\n def abnormal_procedure_classifier_2(self, scenario):\n int_convert_text = {0:'Normal', 1:'Ab21_01', 2:'Ab21_02', 3:'Ab20_04', 4:'Ab15_07', 5:'Ab15_08',\n 6:'Ab63_04', 7:'Ab63_02', 8:'Ab21_12', 9:'Ab19_02', 10:'Ab21_11', 11:'Ab23_03',\n 12:'Ab60_02', 13:'Ab59_02', 14:'Ab23_01', 15:'Ab23_06'}\n\n sort_shap_values_negative = pd.DataFrame(self.shap_value[scenario], columns=self.selected_para['0'].tolist()).sort_values(by=0, ascending=True, axis=1)\n drop_shap_values_negative = sort_shap_values_negative[sort_shap_values_negative.iloc[:]<0].dropna(axis=1).T\n reset_shap_values_negative = drop_shap_values_negative.reset_index()\n column_negative = reset_shap_values_negative['index']\n val_negative = [self.selected_para['0'][self.selected_para['0'] == col_].index for col_ in column_negative]\n val_col_negative = [self.selected_para['1'][var_].iloc[0] for var_ in val_negative]\n proba_negative = [(reset_shap_values_negative[0][val_num]/sum(reset_shap_values_negative[0]))*100 for val_num in range(len(reset_shap_values_negative))]\n val_system_negative = [self.selected_para['2'][var_].iloc[0] for var_ in val_negative]\n reset_shap_values_negative['describe'] = val_col_negative\n reset_shap_values_negative['probability'] = proba_negative\n reset_shap_values_negative['system'] = val_system_negative\n self.shap_result_negative[int_convert_text[scenario]].append(reset_shap_values_negative)\n return self.shap_result_negative\n\n def abnormal_procedure_verification(self, data): # 만약 abnormal 예측이 실패한다면??\n global verif_prediction, verif_threshold\n if self.diagnosed_scenario == 0:\n verif_prediction = self.normal_abnormal_lstm_autoencoder.predict(data)\n verif_threshold = 0.00022733\n elif self.diagnosed_scenario == 1:\n verif_prediction = self.ab_21_01_lstmautoencoder.predict(data)\n verif_threshold = 0.00712891\n elif self.diagnosed_scenario == 2:\n verif_prediction = self.ab_21_02_lstmautoencoder.predict(data)\n verif_threshold = 0.01140293\n elif self.diagnosed_scenario == 3:\n verif_prediction = self.ab_20_04_lstmautoencoder.predict(data)\n verif_threshold = 0.00121183\n elif self.diagnosed_scenario == 4:\n verif_prediction = self.ab_15_07_lstmautoencoder.predict(data)\n verif_threshold = 0.00048918\n elif self.diagnosed_scenario == 5:\n verif_prediction = self.ab_15_08_lstmautoencoder.predict(data)\n verif_threshold = 0.00454363\n elif self.diagnosed_scenario == 6:\n verif_prediction = self.ab_63_04_lstmautoencoder.predict(data)\n verif_threshold = 0.00015933\n elif self.diagnosed_scenario == 7:\n verif_prediction = self.ab_63_02_lstmautoencoder.predict(data)\n verif_threshold =0.00376744\n elif self.diagnosed_scenario == 8:\n verif_prediction = self.ab_21_12_lstmautoencoder.predict(data)\n verif_threshold = 0.00236955\n elif self.diagnosed_scenario == 9:\n verif_prediction = self.ab_19_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00610265\n elif self.diagnosed_scenario == 10:\n verif_prediction = self.ab_21_11_lstmautoencoder.predict(data)\n verif_threshold = 0.00265125\n elif self.diagnosed_scenario == 11:\n verif_prediction = self.ab_23_03_lstmautoencoder.predict(data)\n verif_threshold = 0.00017211\n elif self.diagnosed_scenario == 12:\n verif_prediction = self.ab_60_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00370811\n elif self.diagnosed_scenario == 13:\n verif_prediction = self.ab_59_02_lstmautoencoder.predict(data)\n verif_threshold = 0.00424398\n elif self.diagnosed_scenario == 14:\n verif_prediction = self.ab_23_01_lstmautoencoder.predict(data)\n verif_threshold = 0.00314694\n elif self.diagnosed_scenario == 15:\n verif_prediction = self.ab_23_06_lstmautoencoder.predict(data)\n verif_threshold = 0.00584512\n abnormal_verif_error = np.mean(np.power(self.flatten(data) - self.flatten(verif_prediction), 2), axis=1)\n if abnormal_verif_error <= verif_threshold: # diagnosis success\n verif_result = 0\n else: # diagnosis failure\n verif_result = 1\n return verif_result\n\n\n\n","sub_path":"version 6/model_module_thread_210210.py","file_name":"model_module_thread_210210.py","file_ext":"py","file_size_in_byte":11581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"560019833","text":"if __name__ == '__main__':\n\n students = []\n\n for _ in range(int(input())):\n name = input()\n score = float(input())\n\n # create the list\n students.append([name, score])\n\n # sort list by grade first (highest first) and name second\n students = sorted(students, key=lambda x: (x[1], x[0]))\n\n # edge case where only one student or all students got the same grade\n if len(students) == 1 or students[0][1] == students[-1][1]:\n print(\"Error: Only one grade\")\n\n # find second highest grade\n for i in range(1, len(students)):\n if students[i][1] > students[0][1]:\n # print all students with this grade\n j = i\n while students[i][1] == students[j][1]:\n print(students[j][0])\n j += 1\n break\n","sub_path":"Python/BasicDataTypes/NestedList.py","file_name":"NestedList.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"404727873","text":"import os\nimport threading\nfrom multiprocessing.pool import Pool\nfrom time import sleep, time\n\nimport sys\n\nimport logging\n\nimport fcntl\n\nfrom confmom.ConfMom import ConfMom, SelectEnv, MODE_ZK, MODE_FILE\n\nstdout_handler = logging.StreamHandler(sys.stdout)\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S', # filename='/var/log/sea_spider/logging.log',\n # filemode='a',\n handlers=[stdout_handler])\n\ndef get_config():\n conf = ConfMom(\"127.0.0.1:2181\",\"beehive_web\",\"master\")\n c = conf.get_config()\n print(c)\n\ndef test_client_get_config():\n \"\"\"\n 测试客户端拉取数据的例子\n :return:\n \"\"\"\n def get_change(data):\n print(\"变化了{}\".format(data))\n conf = ConfMom(\"127.0.0.1:2181\", \"beehive_web\", SelectEnv.Env(\"master\"),(\"conf_server\",\"123456\"), callbackOnChange=get_change)\n c = conf.get_config()\n print(c)\n\n\n conf.push_config({\"push_data\":\"123456\"})\n print(\"推送配置\")\n\n t = threading.Thread(target=lambda: sleep(100))\n t.start()\n t.join()\ndef test_client_select_env():\n print(SelectEnv.FileEnv(\"./env\"))\n print(SelectEnv.GitEnv(\"./\"))\n\ndef test_conf_mom_in_muti_process():\n def get_change(data):\n pass\n # print(\"变化了{}\".format(data))\n conf = ConfMom( \"beehive_web\", SelectEnv.Env(\"dev\"),\n mode=MODE_ZK ,\n zk_host=\"192.168.81.60:2181\",\n acl=(\"read\", \"123\"),\n callbackOnChange=get_change, use_file_on_fork=\"./ignore.config.json\"\n )\n\n d = conf.get_config()\n print(\"1--\"+str(d))\n sleep(1)\n if 0 == os.fork():\n d = conf.get_config()\n print(\"2--\"+str(d))\n sleep(1)\n if 0== os.fork():\n d = conf.get_config()\n print(\"3--\"+str(d))\n sleep(1)\n if 0 == os.fork():\n d = conf.get_config()\n print(\"4--\" + str(d))\n sleep(100000)\n else:\n sleep(100000)\n else:\n sleep(100000)\n else:\n sleep(100000)\n\n\ndef test_conf_mom_more_p():\n def get_change(data):\n pass\n\n conf = ConfMom(\"beehive_web\", SelectEnv.Env(\"dev\"), mode=MODE_ZK, zk_host=\"192.168.81.60:2181\", acl=(\"read\", \"123\"),\n callbackOnChange=get_change, use_file_on_fork=\"./ignore.config.json\")\n d = conf.get_config()\n print(\"master {}\".format(d))\n # def par(x):\n # d = conf.get_config()\n # print(\"{}.{} = {}\".format(x, os.getpid(),d))\n # sleep(100)\n # return os.getpid()\n # worker = Pool(processes=100)\n # result = worker.map(par,range(100))\n # print(result)\n\n a = 200\n while a:\n if os.fork() == 0:\n d = conf.get_config()\n print(\"{} = {}\".format(a,d))\n sleep(100)\n break\n a-=1\n sleep(1000)\n\ndef test_conf_file_multi_process():\n def get_change(data):\n pass\n\n def config():\n if 0 == os.fork():\n print(\"儿子备锁住文件\")\n\n file = open(\"./ignore.config.json\", \"w\")\n print(file)\n fcntl.lockf(file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n print(\"儿子锁住文件\")\n sleep(100)\n else:\n print(\"爸爸准备锁住文件\")\n file = open(\"./ignore.config.json\",\"w\")\n fcntl.lockf(file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n print(\"爸爸锁住文件\")\n sleep(100)\n threading.Thread(target=config).start()\n sleep(1000)\n\ntest_conf_mom_more_p()","sub_path":"confmom/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"167808437","text":"import socket,ssl,select\nclass RequestMethod:\n UNSET=0\n GET=1\n POST=2\n PUT=3\n OPTIONS=4\n HEAD=5\n DELETE=6\n TRACE=7\n CONNECT=8\n def toString(reqMeth):\n if reqMeth==0:return \"UNSET\";\n elif reqMeth==1:return \"GET\";\n elif reqMeth==2:return \"POST\";\n elif reqMeth==3:return \"PUT\";\n elif reqMeth==4:return \"OPTIONS\";\n elif reqMeth==5:return \"HEAD\";\n elif reqMeth==6:return \"DELETE\";\n elif reqMeth==7:return \"TRACE\";\n elif reqMeth==8:return \"CONNECT\";\n def parseMethod(s):\n if s==\"GET\":return RequestMethod.GET;\n elif s==\"POST\":return RequestMethod.POST;\n elif s==\"PUT\":return RequestMethod.PUT;\n elif s==\"OPTIONS\":return RequestMethod.OPTIONS;\n elif s==\"HEAD\":return RequestMethod.HEAD;\n elif s==\"DELETE\":return RequestMethod.DELETE;\n elif s==\"TRACE\":return RequestMethod.TRACE;\n elif s==\"CONNECT\":return RequestMethod.CONNECT;\n else:return RequestMethod.UNSET\ndef StripLeadingChar(s,c):\n while True:\n if(len(s)>0):\n if(s[0]==c):s=s[1:len(s)]\n else:break\n else:break\n return s\nclass RequestHeader:\n def __init__(self):\n self.requestMethod=RequestMethod.GET;self.requestData=\"/\";self.headers={};self.httpVersion=\"1.1\"\n def LoadString(self,headerData):\n self.requestMethod=RequestMethod.UNSET\n headerSplit=headerData.split(\"\\r\\n\")\n if(len(headerSplit)>0):\n firstSplit=headerSplit[0].split(\" \")\n self.requestMethod=RequestMethod.parseMethod(firstSplit[0])\n if(len(firstSplit)>2):\n self.requestData=firstSplit[1]\n for s in firstSplit:\n if \"HTTP\" in s:httpSplit=s.split(\"/\");self.httpVersion=httpSplit[1];break\n for i in range(1,headerLength):\n dataSplit=headerSplit[i].split(\":\");self.headers[dataSplit[0]]=StripLeadingChar(dataSplit[1],' ')\n return self\n def setRequestMethod(self,requestMethod):self.requestMethod=requestMethod;return self;\n def getRequestMethod(self):return self.requestMethod\n def setHTTPVersion(self,httpVersion):self.httpVersion=httpVersion;return self;\n def getHTTPVersion(self):return self.httpVersion;\n def setRequestData(self,requestData):self.requestData=requestData;return self;\n def getRequestData(self):return self.requestData;\n def putHeader(self,key,value):self.headers[key]=value;return self;\n def removeHeader(self,key):del self.headers[key];return self;\n def hasHeader(self,key):return key in self.headers\n def toString(self):\n reqData=\"/\"\n if(len(self.requestData)>0):reqData=self.requestData\n s=RequestMethod.toString(self.requestMethod)+\" \"+reqData+\" HTTP/\"+self.httpVersion\n for k,v in self.headers.items():\n s+=\"\\r\\n\"+str(k)+\": \"+str(v)\n return s\ndef IsInteger(s):\n try:int(s);return True;\n except ValueError as ve:return False;\nclass ResponseHeader:\n def __init__(self):self.responseCode=200;self.httpVersion=\"1.1\";self.headers={}\n def LoadString(self,s):\n headerSplit=s.split(\"\\r\\n\")\n if len(headerSplit)>0:\n firstSplit = headerSplit[0].split(\" \")\n for st in firstSplit:\n if \"HTTP\" in st:self.httpVersion=st.split(\"/\")[1]\n elif IsInteger(st):self.responseCode=int(st)\n for i in range(1,len(headerSplit)):\n dataSplit=headerSplit[i].split(\":\")\n self.headers[dataSplit[0]]=StripLeadingChar(dataSplit[1],' ')\n return self\n def setResponseCode(self,code):self.responseCode=code;return self;\n def getResponseCode(self):return self.responseCode;\n def setHTTPVersion(self,httpVersion):self.httpVersion=httpVersion;return self;\n def getHTTPVersion(self):return self.httpVersion;\n def putHeader(self,key,value):self.headers[key]=value;return self;\n def removeHeader(self,key):del self.headers[key];return self;\n def hasHeader(self,key):return key in self.headers;\n def toString(self):\n s=\"HTTP/\"+self.httpVersion+\" \"+str(self.responseCode)\n for k,v in self.headers.items():\n s+=\"\\r\\n\"+str(k)+\": \"+str(v)\n return s\ndef Dechunkify(body):\n actualBody=\"\"\n hexAmount=\"\"\n hexTime=0\n bodyLength=len(body)\n for i in range(len(body)):\n if(i==hexTime):\n hexAmount=\"\"\n if(i>=hexTime):\n if(body[i]=='\\r' and body[i+1]=='\\n'):\n hexTime=i+3+int(hexAmount,16)\n else:\n hexAmount+=body[i]\n else:\n actualBody+=body[i]\n return actualBody\n#Appears to be some crappy bot\nsock=socket.socket()\ncfduid=\"\"\nscraptf_session=\"\"\nscr_session=\"\"\nuser_agent=\"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36\"\nlanguage_settings=\"en-GB,en;q=0.8,en-US;q=0.6,ru;q=0.4\"\ndef GetRaffleInfo(raffleID):\n sock=socket.socket()\n sock.connect((\"scrap.tf\",443))\n sslsock=ssl.wrap_socket(sock)\n req=RequestHeader().setRequestMethod(RequestMethod.GET).setRequestData(\"/raffles/\"+raffleID).putHeader(\"Host\",\"scrap.tf\").putHeader(\"dnt\",1).putHeader(\"upgrade-insecure-requests\",1)\n req.putHeader(\"accept\",\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\").putHeader(\"accept-language\",language_settings).putHeader(\"user-agent\",user_agent)\n req.putHeader(\"cache-control\",\"max-age=0\").putHeader(\"cookie\",\"__cfduid=\"+cfduid+\"; scraptf_session=\"+scraptf_session+\"; scr_session=\"+scr_session)\n sslsock.write((req.toString()+\"\\r\\n\\r\\n\").encode())\n sslsock.settimeout(1)\n entireResponse=\"\"\n while True:\n try:entireResponse+=sslsock.read().decode()\n except Exception as e:break\n splet=entireResponse.split(\"\\r\\n\\r\\n\")\n respHed=ResponseHeader().LoadString(splet[0])\n dataTime=None\n specialThing=None\n if(respHed.hasHeader(\"Transfer-Encoding\")):\n body=Dechunkify(splet[1])\n if(\"onclick=\\\"ScrapTF.Raffles.EnterRaffle(\" in body):\n ind=body.index(\"onclick=\\\"ScrapTF.Raffles.EnterRaffle(\")\n i=ind+37\n length=len(body)\n raffleData=\"\"\n while i 1:\n loss = loss / grad_accum_steps\n\n if config.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n\n # step the optimizer every grad_accum_steps\n if (step + 1) % grad_accum_steps == 0:\n update_learning_rate(optimizer, global_step, lr_schedule, config)\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n losses.append(loss.item() * grad_accum_steps)\n batch_iter.set_postfix(loss=np.mean(losses))\n\n if val_dl is not None:\n res = eval_model(model, val_dl, config)\n test_loss, test_accy = res['loss'], res['accy']\n msg = \"Epoch %d, Train loss: %0.04f, Val loss: %0.04f, Val accy: %0.02f%%\"\n msg = msg%(epoch+1, np.mean(losses), test_loss, test_accy)\n if 'f1' in res:\n msg += \", f1: %0.02f\"%(100 * res['f1'])\n log(msg)\n else:\n msg = \"Epoch %d, Train loss : %0.04f\"%(epoch+1, np.mean(losses))\n log(msg, console=False)\n\n return model\n\n\ndef eval_model(model, dataloader, config, desc=\"Validating\"):\n \"\"\"\n Evaluate model on validation data.\n\n Parameters\n ----------\n model : BertPlusMLP\n Bert model plus mlp head\n dataloader : Dataloader\n validation dataloader\n config : FinetuneConfig\n Parameters for finetuning BERT\n desc : string\n text label for progress bar\n \n Returns\n -------\n loss : float\n Loss calculated on eval data\n accy : float\n Classification accuracy for classifiers.\n Pearson coorelation for regressors.\n \"\"\"\n device = config.device\n model_type = config.model_type\n ignore_label = config.ignore_label_id\n\n regression_stats = OnlinePearson()\n stats = OnlineF1(ignore_label=ignore_label)\n\n model.to(device)\n model.eval()\n loss = accy = 0.\n total_evals = 0\n res = {}\n\n sys.stdout.flush()\n batch_iter = pbar(dataloader, desc=desc, leave=True)\n\n for eval_steps, batch in enumerate(batch_iter):\n batch = tuple(t.to(device) for t in batch)\n _, _, _, y = batch\n with torch.no_grad():\n tmp_eval_loss, output = model(*batch)\n loss += tmp_eval_loss.mean().item()\n\n if model_type == \"text_classifier\":\n _, y_pred = torch.max(output, 1)\n accy += torch.sum(y_pred == y)\n\n elif model_type == \"text_regressor\":\n y_pred = output\n\n # add to online stats calculator\n for xi, yi in zip(y.detach().cpu().numpy(),\n y_pred.detach().cpu().numpy()):\n regression_stats.add(xi, yi)\n\n elif model_type == \"token_classifier\":\n\n output = output.view(-1, output.shape[-1])\n y_true = y.view(-1)\n valid_tokens = y_true != -1\n\n _, y_pred = torch.max(output, 1)\n\n accy += torch.sum(y_pred[valid_tokens] == y_true[valid_tokens])\n total_evals += torch.sum(valid_tokens).item()\n\n y_true = y_true[valid_tokens].detach().cpu().numpy()\n y_pred = y_pred[valid_tokens].detach().cpu().numpy()\n\n # add to online stats calculator\n stats.add(y_true=y_true, y_pred=y_pred)\n\n loss = loss/(eval_steps+1)\n\n if model_type == \"text_classifier\":\n accy = 100 * (accy.item() / len(dataloader.dataset))\n elif model_type == \"text_regressor\":\n accy = 100 * regression_stats.pearson\n elif model_type == \"token_classifier\":\n accy = 100 * (accy.item() / total_evals)\n res['f1'] = stats.f1\n res['precision'] = stats.precision\n res['recall'] = stats.recall\n\n res['loss'] = loss\n res['accy'] = accy\n return res\n","sub_path":"bert-sklearn/bert_sklearn/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"143068815","text":"import os\nimport copy\nimport time\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom message_utils import parse_message\nimport datetime\n\n# util and commands \n\ndef calc_paramater(act_min, act_max, max_val):\n if act_max == 0.0 and act_min == 0.0:\n return 0, (0.5,0.5)\n reward_sum = act_max + act_min\n reward_rate = (act_min / reward_sum, act_max / reward_sum)\n value = max_val * reward_rate[1]\n return value, reward_rate\n\ndef command_turn(inference_result):\n direction, reward_rate = calc_paramater(inference_result[0], inference_result[1],180)\n command = '(turn {})'.format(direction - 90)\n # print(inference_result, reward_rate)\n return command, reward_rate\n\ndef command_dash(inference_result):\n power, reward_rate_a = calc_paramater(inference_result[0], inference_result[1], 100)\n direction, reward_rate_b = calc_paramater(inference_result[2], inference_result[3], 180)\n command = '(dash {} {})'.format(power, direction - 90)\n return command, (reward_rate_a[0] / 2.0, reward_rate_a[1] / 2.0, reward_rate_b[0] / 2.0, reward_rate_b[1] / 2.0)\n\ndef command_kick(inference_result):\n power, reward_rate_a = calc_paramater(inference_result[0], inference_result[1], 100)\n direction, reward_rate_b = calc_paramater(inference_result[2], inference_result[3], 180)\n command = '(kick {} {})'.format(power, direction - 90)\n return command, (reward_rate_a[0] / 2.0, reward_rate_a[1] / 2.0, reward_rate_b[0] / 2.0, reward_rate_b[1] / 2.0)\n\ndef command_change_view_wide(inference_result):\n return '(change_view wide)', (1,)\n\ndef command_change_view_normal(inference_result):\n return '(change_view normal)', (1,)\n\ndef command_change_view_narrow(inference_result):\n return '(change_view narrow)', (1,)\n\ndef random_commands():\n vals = [\n (0, [0.2, 0.8]),\n (0, [0.3, 0.7]),\n (0, [0.4, 0.6]),\n (1, [0.2, 0.8, 0.8, 0.2]),\n ]\n return vals[random.randrange(len(vals))]\n\ndef find_command_and_rate(command:str) -> int:\n print(command)\n parsed_command = parse_message(command)[0]\n command_index = ['turn', 'dash', 'kick', 'change_view'].index(parsed_command[0])\n if parsed_command[0] == 'turn':\n command_index = 0\n dir_a = float(parsed_command[1]) + 180.0\n dir_b = 360.0 - dir_a\n return command_index, [dir_b, dir_a]\n elif parsed_command[0] == 'dash' or parsed_command[0] == 'kick':\n command_index = 1 if parsed_command[0] == 'dash' else 2\n power_a = float(parsed_command[1])\n power_b = 100.0 - power_a\n dir_a = float(parsed_command[2]) + 180.0\n dir_b = 360.0 - dir_a\n return command_index, [power_b, power_a, dir_b, dir_a]\n elif parsed_command[0] == 'change_view':\n return 2 + ['wide', 'normal', 'narrow'].index(parsed_command[1])\n\n\n\ncommand_arg_counts = np.array([2,4,4,1,1,1])\ncommands = [\n command_turn,\n command_dash,\n command_kick,\n command_change_view_wide,\n command_change_view_normal,\n command_change_view_narrow\n]\n\n# turn(dir) dash(power, direction), kick(power, direction) change_view_wide() change_view_normal() change_view_narrow()\n# 入力値がある場合、入力値*2のActが存在していることになる\n\n# 環境\nMONITOR = False\nHIDDEN_SIZE = 300\nMEMORY_SIZE = 3000\nBATCH_SIZE = 20\nTRAIN_INTERVAL = 10\nGAMMA = 0.97\nacts_num = 13\nobs_num = 294 * 2 + acts_num * 3\n\nclass NN(nn.Module):\n def __init__(self):\n super(NN, self).__init__()\n self.fc1 = nn.Linear(obs_num, HIDDEN_SIZE)\n self.fc2 = nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE)\n self.fc3 = nn.Linear(HIDDEN_SIZE, HIDDEN_SIZE)\n self.fc4 = nn.Linear(HIDDEN_SIZE+obs_num, acts_num)\n self.dropout1 = nn.Dropout(0.3)\n self.dropout2 = nn.Dropout(0.5)\n \n def __call__(self, x):\n h = F.relu(self.fc1(x))\n h = F.relu(self.fc2(h))\n h = self.dropout1(h)\n h = F.relu(self.fc3(h))\n h = self.dropout2(h)\n y = F.relu(self.fc4(torch.cat([h, x], -1)))\n return y\n\nclass Estimater():\n def __init__(self, player_number, player_side, save_path='robo.pt', batch_size=BATCH_SIZE):\n self.player_number = player_number\n self.player_side = player_side\n self.save_path = save_path\n \n self.batch_size = batch_size\n self.commands = commands\n self.command_arg_counts = command_arg_counts\n\n self.q_func = NN()\n self.q_func_old = copy.deepcopy(self.q_func)\n if os.path.exists(self.save_path):\n self.load()\n self.optimizer = optim.RMSprop(self.q_func.parameters(), lr=0.00015, alpha=0.95, eps=0.01)\n\n self.saved = False\n self.episode = [] # [[state, act, reward_rate, reward, next_state]]\n self.total_reward = 0\n self.call_count = 0\n \n def __call__(self, state, state_reward=0, suggest_command=None):\n input_state = np.array(state, dtype='float32')\n command, act_command ,reward_rate, inference_result = self.predict(input_state, suggest_command)\n\n # input datas to self.episode for training\n self.total_reward += state_reward\n self.call_count += 1\n self.episode.append([input_state, act_command, reward_rate, None, None])\n if len(self.episode) > 0:\n self.episode[-1][3:] = [state_reward, input_state]\n\n if len(self.episode) > MEMORY_SIZE:\n self.episode.pop()\n if self.call_count % TRAIN_INTERVAL == 0:\n self.train()\n\n if self.call_count % 500 == 0 and not self.saved:\n self.save()\n return command, inference_result\n \n def set_episode(self, episode):\n self.episode = episode\n \n def predict(self, state, suggest_command=None):\n result = self.q_func(Variable(torch.from_numpy(state))).data.numpy()\n command, best_act, reward_rate = self.parse_result_to_command(result, suggest_command)\n return command, best_act, reward_rate, result\n \n def parse_result_to_command(self, result, suggest_command=None):\n best_act, splited_result = self.inference_split(result, suggest_command)\n command, reward_rate = self.commands[best_act](splited_result[best_act])\n \n return command, best_act, reward_rate\n\n def inference_split(self, result, suggest_command=None):\n acts_results = []\n act_rewards = []\n start_index = 0\n for i in self.command_arg_counts:\n acts_results.append(result[start_index:start_index+i])\n act_rewards.append(np.sum(result[start_index:start_index+i]))\n start_index += i\n \n if suggest_command != None:\n best_act, act_reward = find_command_and_rate(suggest_command)\n acts_results[best_act] = np.array(act_reward)\n elif random.randint(0, 5) == 0:\n best_act, tmp = random_commands()\n acts_results[best_act] = tmp\n else:\n best_act = np.argmax(act_rewards)\n\n return best_act, acts_results\n\n def train(self):\n episode = np.array(self.episode)\n if len(episode) < self.batch_size:\n return None\n \n np.random.shuffle(episode)\n for i in range(len(episode))[::self.batch_size]:\n batch = episode[i:i+self.batch_size]\n if len(batch) < self.batch_size:\n continue\n states = np.array(batch[:,0].tolist(), dtype='float32')\n best_acts = batch[:,1]\n reward_rates = batch[:,2]\n rewards = batch[:,3]\n next_states = np.array(batch[:,4].tolist(), dtype='float32')\n inferences_a = self.q_func(Variable(torch.from_numpy(states)))\n inferences_b = self.q_func_old(Variable(torch.from_numpy(next_states))).data.numpy()\n target = copy.deepcopy(inferences_a.data.numpy())\n for l in range(self.batch_size):\n update_start = np.sum(self.command_arg_counts[:best_acts[l]])\n update_end = update_start + self.command_arg_counts[best_acts[l]]\n best_act, splited_inference = self.inference_split(inferences_b[l])\n tmp = np.sum(splited_inference[best_act])\n updates = np.array(reward_rates[l]) * (rewards[l] + (GAMMA * tmp))\n target[l,update_start:update_end] = updates\n # if l == 0:\n # print(['turn', 'dash', 'kick', 'wide', 'normal', 'narrow'][best_acts[l]], rewards[l], updates)\n self.optimizer.zero_grad()\n loss = nn.MSELoss()(inferences_a, Variable(torch.from_numpy(target)))\n loss.backward()\n self.optimizer.step()\n \n self.q_func_old = copy.deepcopy(self.q_func)\n \n def end(self, win=True):\n reward = 2000 if win else -500\n self.episode[-1][3] = reward\n self.episode[-1][4] = np.zeros(obs_num)\n timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')\n np.save('dataset_{}.npy'.format(timestamp), np.array(self.episode))\n self.train()\n\n self.episode = []\n self.total_reward = 0\n self.call_count = 0\n \n def save(self):\n torch.save(self.q_func.state_dict(), self.save_path)\n \n def load(self):\n self.q_func.load_state_dict(torch.load(self.save_path))\n self.q_func_old = copy.deepcopy(self.q_func)\n","sub_path":"dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":9470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"457112804","text":"import random\n\nguessesTaken = 0\nguess = 0 \n\nprint('Hello! What is your name? ')\nplayerName = input()\n\nsecretNumber = random.randint(1,20)\n\nprint(f'Well, {playerName}, I am thinking of a number between 1 and 20.') \n\nfor guessesTaken in range(6):\n\n print('Take a guess')\n guess = int(input())\n \n if guess < secretNumber:\n print('Your guess is to low')\n if guess > secretNumber:\n print('Your guess is to high')\n if guess == secretNumber:\n break\n\nif guess == secretNumber:\n print(f'Good job, {playerName}! Your guessed'\n f'the secret number in {guessesTaken + 1} guesses')\nelse:\n print(f'Nope. The number i was thinking of was {secretNumber}.')\n","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"599808062","text":"import os\r\nimport json\r\nimport sys\r\nimport time\r\nimport subprocess\r\ndir_path = os.path.dirname(os.path.realpath(__file__))\r\nproject_path = dir_path[0:dir_path.find(\"/targets\")]\r\nsys.path.append(project_path + \"/core/abstract_target\")\r\nfrom abstract_target import AbstractTarget\r\n\r\n\r\nclass TargetImpl(AbstractTarget):\r\n\r\n def __init__(self, target_cfg):\r\n super().__init__(target_cfg)\r\n self.speed_list = [\"n/a\"]\r\n\r\n # creates config file for p4 device\r\n def stamper_specific_config(self, cfg):\r\n f = open(self.realPath + \"/data/commands1_middlebox1.txt\", \"w+\")\r\n # delete old entries\r\n f.write(\"table_clear ingress.t_add_timestamp_header\" + \"\\n\")\r\n f.write(\"table_clear ingress.multicast\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l1_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l2_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_l3_forwarding\" + \"\\n\")\r\n f.write(\"table_clear ingress.timestamp2\" + \"\\n\")\r\n f.write(\"table_clear egress.broadcast_mac\" + \"\\n\")\r\n f.write(\"table_clear ingress.t_add_timestamp_header_udp\" + \"\\n\")\r\n f.write(\"table_clear ingress.timestamp2_udp\" + \"\\n\")\r\n # delete old multicast groups (up to 10 groups)\r\n for group in range(1, 11):\r\n for node in range(0, 10):\r\n f.write(\"mc_node_dissociate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n for node in range(0, 10):\r\n f.write(\"mc_node_destroy \" + str(node) + \"\\n\")\r\n for group in range(1, 11):\r\n f.write(\"mc_mgrp_destroy \" + str(group) + \"\\n\")\r\n\r\n node = 0\r\n # multicast grp for loadgen servers:\r\n f.write(\"mc_mgrp_create 1\" + \"\\n\")\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"mc_node_create \" + str(node) + \" \" + server[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate 1 \" + str(node) + \"\\n\")\r\n node = node + 1\r\n\r\n # multicast grp for loadgen clients:\r\n f.write(\"mc_mgrp_create 2\" + \"\\n\")\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"mc_node_create \" + str(node) + \" \" + client[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate 2 \" + str(node) + \"\\n\")\r\n node = node + 1\r\n\r\n # multicast groups for external host, because of bmv2 the original receiver needs to be included\r\n group = 3\r\n for host in cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]:\r\n host[\"mcast_grp\"] = str(group)\r\n f.write(\"mc_mgrp_create \" + str(group) + \"\\n\")\r\n f.write(\"mc_node_create \" + str(node) + \" \" + cfg[\"ext_host\"] + \"\\n\")\r\n f.write(\"mc_node_associate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n node = node + 1\r\n f.write(\"mc_node_create \" + str(node) + \" \" + host[\"p4_port\"] + \"\\n\")\r\n f.write(\"mc_node_associate \" + str(group) + \" \" + str(node) + \"\\n\")\r\n node = node + 1\r\n group = group + 1\r\n\r\n if cfg['forwarding_mode'] == \"1\":\r\n server = cfg[\"loadgen_servers\"][0]\r\n client = cfg[\"loadgen_clients\"][0]\r\n f.write(\r\n \"table_add ingress.t_l1_forwarding ingress.send \" + cfg[\"dut1\"] + \" => \" + server[\r\n \"p4_port\"] + \"\\n\")\r\n f.write(\r\n \"table_add ingress.t_l1_forwarding ingress.send \" + cfg[\"dut2\"] + \" => \" + client[\r\n \"p4_port\"] + \"\\n\")\r\n else:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"dut1\"] + \" =>\\n\")\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"dut2\"] + \" =>\\n\")\r\n\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.no_op \" + cfg[\"ext_host\"] + \" =>\\n\")\r\n\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.send \" + server[\"p4_port\"] + \" => \" + cfg[\"dut1\"] + \"\\n\")\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l1_forwarding ingress.send \" + client[\"p4_port\"] + \" => \" + cfg[\"dut2\"] + \"\\n\")\r\n\r\n if int(cfg['forwarding_mode']) >= 2:\r\n # MC l2 group\r\n print(\"create table entries for l2 forwarding\")\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send_to_mc_grp \" + cfg[\"dut1\"] + \" 0xffffffffffff => 1\\n\")\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send_to_mc_grp \" + cfg[\"dut2\"] + \" 0xffffffffffff => 2\\n\")\r\n\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send \" + cfg[\"dut1\"] + \" 0x\" +\r\n server['loadgen_mac'].replace(\":\", \"\") + \" => \" + server[\"p4_port\"] + \"\\n\")\r\n\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l2_forwarding ingress.send \" + cfg[\"dut2\"] + \" 0x\" +\r\n client['loadgen_mac'].replace(\":\", \"\") + \" => \" + client[\"p4_port\"] + \"\\n\")\r\n\r\n if cfg['forwarding_mode'] == \"3\":\r\n print(\"create table entries for l3 forwarding\")\r\n # IPv4 forwarding\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.t_l3_forwarding ingress.send \" + cfg[\"dut1\"] + \" \" + server[\"loadgen_ip\"] + \" => \" + server[\"p4_port\"] + \"\\n\")\r\n\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.t_l3_forwarding ingress.send \" + cfg[\"dut2\"] + \" \" + client[\"loadgen_ip\"] + \" => \" + client[\"p4_port\"] + \"\\n\")\r\n\r\n f.write(\"table_add egress.broadcast_mac egress.change_mac \" + cfg[\"ext_host\"] + \" => 0xffffffffffff\" + \"\\n\")\r\n\r\n if cfg[\"stamp_tcp\"] == \"checked\":\r\n offsets_start = [\"0x5\", \"0x8\"]\r\n offsets_end = [\"0x9\", \"0xc\"]\r\n for i in range(0, 2):\r\n if cfg[\"dut_1_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header ingress.add_timestamp_header \" + offsets_start[i] + \" \" + cfg[\"dut2\"] + \" => \" + offsets_end[i] + \" 0\\n\")\r\n f.write(\"table_add ingress.timestamp2 ingress.add_timestamp2 \" + offsets_end[i] + \" 0x0f10 \" + cfg[\"dut1\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 0\\n\") # multicast -1 because it begins at 0\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header ingress.add_timestamp_header \" + offsets_start[i] + \" \" + cfg[\"dut1\"] + \" => \" + offsets_end[i] + \" 1\\n\")\r\n f.write(\"table_add ingress.timestamp2 ingress.add_timestamp2 \" + offsets_end[i] + \" 0x0f10 \" + cfg[\"dut2\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 1\\n\")\r\n\r\n if cfg[\"dut_1_duplicate\"] == \"checked\" and cfg[\"ext_host\"] != \"\":\r\n for server in cfg[\"loadgen_servers\"]:\r\n f.write(\"table_add ingress.multicast ingress.send_to_mc_grp \" + cfg[\"dut1\"] + \" \" + server[\"p4_port\"] + \" => \" + server[\"mcast_grp\"] + \"\\n\")\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\" and cfg[\"ext_host\"] != \"\":\r\n for client in cfg[\"loadgen_clients\"]:\r\n f.write(\"table_add ingress.multicast ingress.send_to_mc_grp \" + cfg[\"dut2\"] + \" \" + client[\"p4_port\"] + \" => \" + client[\"mcast_grp\"] + \"\\n\")\r\n\r\n ### UDP\r\n if cfg[\"stamp_udp\"] == \"checked\":\r\n if cfg[\"dut_1_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header_udp ingress.add_timestamp_header_udp \" + cfg[\"dut2\"] + \" => \" + \" 0\\n\")\r\n f.write(\"table_add ingress.timestamp2_udp ingress.add_timestamp2 0x0f10 \" + cfg[\"dut1\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 0\\n\") # multicast -1 because it begins at 0\r\n\r\n if cfg[\"dut_2_duplicate\"] == \"checked\":\r\n f.write(\"table_add ingress.t_add_timestamp_header_udp ingress.add_timestamp_header_udp \" + cfg[\"dut1\"] + \" => \" + \" 1\\n\")\r\n f.write(\"table_add ingress.timestamp2_udp ingress.add_timestamp2 0x0f10 \" + cfg[\"dut2\"] + \" => \" + hex(int(cfg[\"multicast\"]) - 1) + \" 1\\n\") # multicast -1 because it begins at 0\r\n\r\n f.close()\r\n\r\n\r\n # returns a dict[\"real_ports\"] and [\"logical_ports\"]\r\n def port_lists(self):\r\n temp = {\"real_ports\": [], \"logical_ports\": []}\r\n for i in range(0, 100):\r\n temp[\"real_ports\"].append(str(i))\r\n temp[\"logical_ports\"].append(str(i)) # = p4 ports\r\n return temp\r\n\r\n # deploy config file (table entries) again to p4 device (in case of changes)\r\n def deploy(self, cfg):\r\n self.stamper_specific_config()\r\n lag = \"SimplePreLAG\"\r\n cli = cfg[\"bmv2_dir\"] + \"/tools/runtime_CLI.py\"\r\n json_path = self.realPath + \"/data/\" + cfg[\"program\"] + \".json\"\r\n cmd = [cli, \"--pre\", lag, \"--json\", json_path, \"--thrift-port\", str(22223)]\r\n with open(self.realPath + \"/data/commands1_middlebox1.txt\", \"r\") as f:\r\n try:\r\n output = subprocess.check_output(cmd, stdin=f)\r\n except subprocess.CalledProcessError as e:\r\n print (e)\r\n\r\n # if not overwritten = everything is zero\r\n def read_p4_device(self, cfg):\r\n def error_cfg():\r\n for key in [\"total_deltas\", \"delta_counter\", \"min_delta\", \"max_delta\"]:\r\n cfg[key] = -1\r\n for key in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n for direction in [\"ingress\", \"egress\"]:\r\n cfg[key + \"_num_\" + direction + \"_packets\"] = cfg[key + \"_num_\" + direction + \"_bytes\"] = -1\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n for direction in [\"ingress\", \"egress\"]:\r\n host[\"num_\" + direction + \"_packets\"] = host[\"num_\" + direction + \"_bytes\"] = -1\r\n cfg[\"dut2_num_egress_stamped_packets\"] = cfg[\"dut2_num_egress_stamped_bytes\"] = cfg[\"dut1_num_ingress_stamped_packets\"] = cfg[\"dut1_num_ingress_stamped_bytes\"] = cfg[\"dut1_num_egress_stamped_packets\"] = cfg[\"dut1_num_egress_stamped_bytes\"] = cfg[\"dut2_num_ingress_stamped_packets\"] = cfg[\"dut2_num_ingress_stamped_bytes\"] = 0\r\n\r\n # generating the input for the bmv2 cli\r\n in_c = \"counter_read ingress.ingress_counter \"\r\n in_stamped_c = \"counter_read ingress.ingress_stamped_counter \"\r\n out_c = \"counter_read egress.egress_counter \"\r\n out_stamped_c = \"counter_read egress.egress_stamped_counter \"\r\n cli_input = \"register_read ingress.time_average 0\\nregister_read ingress.time_average 1\\nregister_read ingress.time_delta_min_max 0\\nregister_read ingress.time_delta_min_max 1\\n\"\r\n for host in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n cli_input = cli_input + in_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + out_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + in_stamped_c + cfg[host] + \"\\n\"\r\n cli_input = cli_input + out_stamped_c + cfg[host] + \"\\n\"\r\n\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n cli_input = cli_input + in_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + out_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + in_stamped_c + host[\"p4_port\"] + \"\\n\"\r\n cli_input = cli_input + out_stamped_c + host[\"p4_port\"] + \"\\n\"\r\n\r\n\r\n try:\r\n cmd = [cfg[\"bmv2_dir\"] + \"/targets/simple_switch/sswitch_CLI.py\", \"--thrift-port\", \"22223\"]\r\n output = subprocess.run(cmd, stdout=subprocess.PIPE, input=cli_input.encode()).stdout.decode('UTF-8')\r\n lines = output.split(\"\\n\")\r\n for line in lines:\r\n print(line)\r\n\r\n if len(lines) > 10: # make sure there is no error, if it's not greater than 10 lines; else bmv2 not running\r\n # parsing output of bmv2 CLI\r\n start = 0\r\n for line in lines:\r\n start = start + 1\r\n if line.find(\"Control utility for runtime P4 table manipulation\") > -1:\r\n break\r\n\r\n cfg[\"total_deltas\"] = int(lines[start][lines[start].find(\"[0]=\")+5:])*1000 # because bmv2 is in microseconds but nanoseconds are expected\r\n cfg[\"delta_counter\"] = int(lines[start+1][lines[start+1].find(\"[1]=\") + 5:])\r\n cfg[\"min_delta\"] = int(lines[start+2][lines[start+2].find(\"[0]=\") + 5:])*1000\r\n cfg[\"max_delta\"] = int(lines[start+3][lines[start+3].find(\"[1]=\") + 5:])*1000\r\n counter = start+4\r\n for key in [\"dut1\", \"dut2\", \"ext_host\"]:\r\n for direction in [\"ingress\", \"egress\", \"ingress_stamped\", \"egress_stamped\"]:\r\n cfg[key+\"_num_\"+direction+\"_packets\"] = int(lines[counter][lines[counter].find(\"packets=\")+8:lines[counter].find(\",\")])\r\n cfg[key+\"_num_\"+direction+\"_bytes\"] = int(lines[counter][lines[counter].find(\"bytes=\")+6:-1])\r\n counter = counter + 1\r\n for host in (cfg[\"loadgen_servers\"] + cfg[\"loadgen_clients\"]):\r\n for direction in [\"ingress\", \"egress\", \"ingress_stamped\", \"egress_stamped\"]:\r\n host[\"num_\"+direction+\"_packets\"] = int(lines[counter][lines[counter].find(\"packets=\")+8:lines[counter].find(\",\")])\r\n host[\"num_\"+direction+\"_bytes\"] = int(lines[counter][lines[counter].find(\"bytes=\")+6:-1])\r\n counter = counter + 1\r\n\r\n else: # if an error occurs set everything to -1\r\n print(\"Error in BMV2 read_p4_device. Sure the mininet/bmv2 instance is running?\")\r\n error_cfg()\r\n\r\n except subprocess.CalledProcessError as e:\r\n print(\"Error in BMV2 read_p4_device\")\r\n print (e)\r\n error_cfg()\r\n\r\n return cfg\r\n\r\n def get_pid(self):\r\n lines = subprocess.run([self.realPath + \"/scripts/mn_status.sh\"], stdout=subprocess.PIPE).stdout.decode(\"utf-8\").split(\"\\n\")\r\n try:\r\n if int(lines[0]) > 0:\r\n pid = int(lines[0])\r\n else:\r\n pid = 0\r\n except:\r\n pid = 0\r\n return pid\r\n\r\n def p4_dev_status(self, cfg):\r\n pid = self.get_pid()\r\n print(pid)\r\n if pid > 0:\r\n dev_status = \"Yes! PID: \" + str(pid)\r\n running = True\r\n try:\r\n with open(self.realPath + \"/data/mn.log\", \"r\") as log:\r\n lines_pm = [\"There is no need to deploy the current config explicitly.\",\r\n \"The settings were applied at the start of mininet.\",\r\n \"Mininet link and port configuration: \"]\r\n for line in log.readlines():\r\n lines_pm.append(line)\r\n except:\r\n lines_pm = [\"Error while reading mininet output\"]\r\n else:\r\n dev_status = \"not running\"\r\n running = False\r\n lines_pm = [\"No portmanager available\",\r\n \"Are you sure you selected a target before?\"]\r\n\r\n return lines_pm, running, dev_status\r\n\r\n\r\n # starts specific p4 software on device\r\n def start_p4_dev_software(self, cfg):\r\n subprocess.run([self.realPath + \"/scripts/start_mininet.sh\", self.realPath + \"/scripts/netgen.py\", cfg[\"bmv2_dir\"]])\r\n\r\n def stop_p4_dev_software(self, cfg):\r\n pid = self.get_pid()\r\n if pid > 0:\r\n subprocess.run([self.realPath + \"/scripts/stop_mininet.sh\"])\r\n\r\n # reset registers of p4 device\r\n def reset_p4_registers(self, cfg):\r\n cli_input = \"register_reset ingress.time_average\\nregister_reset ingress.time_delta_min_max\\n\"\r\n cli_input += \"counter_reset egress.egress_counter\\ncounter_reset ingress.ingress_counter\"\r\n cli_input += \"counter_reset egress.egress_stamped_counter\\ncounter_reset ingress.ingress_stamped_counter\\n\"\r\n cmd = [cfg[\"bmv2_dir\"] + \"/targets/simple_switch/sswitch_CLI.py\", \"--thrift-port\", \"22223\"]\r\n\r\n output = subprocess.run(cmd, stdout=subprocess.PIPE, input=cli_input.encode()).stdout.decode('UTF-8')\r\n\r\n def check_if_p4_compiled(self, cfg):\r\n return True if self.get_pid() > 0 else False, \"If BMV2 is running, the selected program \" + str(cfg[\"program\"]) + \" is compiled.\"","sub_path":"targets/bmv2/bmv2_middlebox_v8.py","file_name":"bmv2_middlebox_v8.py","file_ext":"py","file_size_in_byte":16279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"33439102","text":"\nimport os\nimport inspect\nimport nodechecker.notification.notification\nimport nodechecker.notification.snmp\nimport nodechecker.config\nimport nodechecker.node\n\nnode = None\nconf = None\nsender = None\n\n\ndef setup():\n global node, conf, sender\n node = nodechecker.node.Node(hostname='test1', port=10, cloud_zone='cloudzone1', ip_address_public='1.2.3.4',\n instance_id=1, cluster_id=1, machine_id=1)\n test_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n p1_dir = os.path.abspath(os.path.join(test_dir, os.pardir))\n p2_dir = os.path.abspath(os.path.join(p1_dir, os.pardir))\n conf = nodechecker.config.Config(os.path.join(p2_dir, 'conf', 'nodechecker', 'etc', 'nodechecker.conf'))\n #conf = nodechecker.config.Config(os.path.join(test_dir, 'nodechecker.conf'))\n sender = nodechecker.notification.snmp.TrapSender(conf, node)\n\n\ndef test_send():\n global node, conf, sender\n ntf_1 = nodechecker.notification.notification.Notification(category='fatal', severity='error')\n ntf_2 = nodechecker.notification.notification.Notification(category='dead', severity='warn')\n\n notifications = [ntf_1, ntf_2]\n error = 0\n try:\n sender.send(notifications)\n except Exception:\n error = 1\n assert error == 0\n\n\ndef test_truncate():\n global node, conf, sender\n word_1 = ''\n word_2 = '123456789'\n word_3 = 3\n\n assert sender.truncate(word_1, 0) == ''\n assert sender.truncate(word_1, 1) == ''\n assert sender.truncate(word_2, 0) == ''\n assert sender.truncate(word_2, 1) == '1'\n assert sender.truncate(word_2, 9) == '123456789'\n assert sender.truncate(word_2, 10) == '123456789'\n\n # should throw TypeError exception\n thrown = False\n try:\n sender.truncate(word_3, 0) == ''\n except TypeError:\n thrown = True\n assert thrown is True\n","sub_path":"nodechecker/nodechecker/lib/python/test/snmp_tests/unit_tests/test_snmp.py","file_name":"test_snmp.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"314735748","text":"import dataclasses\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional\n\nimport log\nfrom classproperties import classproperty\n\nfrom . import hooks\nfrom .converters import Converter, map_type\nfrom .managers import InstanceManager, ModelManager\n\n\n@dataclass\nclass ModelMeta:\n datafile_attrs: Optional[Dict[str, Converter]] = None\n datafile_pattern: Optional[str] = None\n\n datafile_manual: bool = False\n datafile_defaults: bool = False\n\n\nclass Model:\n\n Meta: ModelMeta = ModelMeta()\n\n def __post_init__(self):\n with hooks.disabled():\n log.debug(f'Initializing {self.__class__} object')\n\n self.datafile = build_datafile(self)\n\n path = self.datafile.path\n exists = self.datafile.exists\n\n if path:\n log.debug(f'Datafile path: {path}')\n log.debug(f'Datafile exists: {exists}')\n\n if exists:\n self.datafile.load(first_load=True)\n elif path:\n self.datafile.save()\n\n hooks.apply(self, self.datafile, build_datafile)\n\n log.debug(f'Initialized {self.__class__} object')\n\n @classproperty\n def datafiles(cls) -> ModelManager: # pylint: disable=no-self-argument\n return ModelManager(cls)\n\n\ndef build_datafile(obj, root=None) -> InstanceManager:\n try:\n return object.__getattribute__(obj, 'datafile')\n except AttributeError:\n log.debug(f\"Building 'datafile' for {obj.__class__} object\")\n\n m = getattr(obj, 'Meta', None)\n pattern = getattr(m, 'datafile_pattern', None)\n attrs = getattr(m, 'datafile_attrs', None)\n manual = getattr(m, 'datafile_manual', False)\n defaults = getattr(m, 'datafile_defaults', False)\n\n if attrs is None and dataclasses.is_dataclass(obj):\n attrs = {}\n log.debug(f'Mapping attributes for {obj.__class__} object')\n for field in dataclasses.fields(obj):\n self_name = f'self.{field.name}'\n if pattern is None or self_name not in pattern:\n attrs[field.name] = map_type(field.type)\n\n return InstanceManager(\n obj, attrs=attrs, pattern=pattern, manual=manual, defaults=defaults, root=root\n )\n\n\ndef create_model(cls, *, attrs=None, pattern=None, manual=None, defaults=None):\n \"\"\"Patch datafile attributes on to an existing dataclass.\"\"\"\n log.debug(f'Converting {cls} to a datafile model')\n\n if not dataclasses.is_dataclass(cls):\n raise ValueError(f'{cls} must be a dataclass')\n\n # Patch Meta\n\n m = getattr(cls, 'Meta', ModelMeta())\n\n if attrs is not None:\n m.datafile_attrs = attrs\n if pattern is not None:\n m.datafile_pattern = pattern\n\n if not hasattr(cls, 'Meta') and manual is not None:\n m.datafile_manual = manual\n if not hasattr(cls, 'Meta') and defaults is not None:\n m.datafile_defaults = defaults\n\n cls.Meta = m\n\n # Patch __init__\n\n init = cls.__init__\n\n def modified_init(self, *args, **kwargs):\n with hooks.disabled():\n init(self, *args, **kwargs)\n Model.__post_init__(self)\n\n cls.__init__ = modified_init\n cls.__init__.__doc__ = init.__doc__\n\n return cls\n","sub_path":"datafiles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"555244154","text":"for i in range(int(input())):\n a, b = map(int, input().split())\n for j in range(1, a+b+1, 2):\n a = a - j\n if a < 0:\n print(\"Bob\")\n break\n b = b - (j+1)\n if b < 0:\n print(\"Limak\")\n break","sub_path":"CodeChef/bear_candies.py","file_name":"bear_candies.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"84745171","text":"#configuration du support#\n\nfrom tkinter import* \nfrom random import*\nfenetre = Tk()\nfenetre.title('Jeu de compatibilite')\nfenetre.configure(width=400,height=200,bg='#FFCCCC')\n\nL_prenom_1=Label(fenetre,text=\"Entrez le nom 1:\",fg='#CC0033',width=20)\nL_prenom_2=Label(fenetre,text=\"Entrez le nom 2:\",fg='#CC0033',width=20)\nPrenom_1=StringVar()\nPrenom_2=StringVar()\nE_prenom_1=Entry(fenetre,width=20)\nE_prenom_2=Entry(fenetre,width=20)\nB1=Button(fenetre,text=\"Valider\",width=20,command=recuperation)\n\nL_prenom_1.place(x=50, y=10)\nL_prenom_2.place(x=50, y=50)\nB1.place(x=125, y=150)\nE_prenom_1.place(x=200, y=10)\nE_prenom_2.place(x=200, y=50)\n\n#Configuraton deuxième fenêtre#\n\ndef recuperation():\n P_1 = E_prenom_1.get()\n P_2 = E_prenom_2.get()\n L_prenom_1.place_forget()\n L_prenom_2.place_forget()\n E_prenom_1.place_forget()\n E_prenom_2.place_forget()\n B1.place_forget()\n L_astro_1= Label(text=\"Entrez le signe astrologique de nom 1:\")\n L_astro_2= Label(text=\"Entrez le signe astrologique de nom 2:\")\n L_astro_1.place(x=40,y=0)\n L_astro_2.place(x=40,y=50)\n E_astro_1=Entry(fenetre,width=20)\n E_astro_2=Entry(fenetre,width=20)\n B2= Button(fenetre,text=\"Valider\",width=20,command=alea)\n B2.place(x=55,y=80)\n\n#configuration de la fenêtre de résultat#\n\ndef alea():\n nb=randint(1,100)\n L5= Label(fenetre,text=\"Calcul du pourcentage en cours...\",fg='black')\n L5.configure(text=\"Le pourcentage de compatibilite est de\"+ str(nb)+'%')\n L5.place(x=100,y=50)\n B3= Button(fenetre,text=\"Quitter\",width=10,command=fenetre.destroy)\n B3.place(x=150,y=100)\n\n\n\n#main window\nfenetre.mainloop()","sub_path":"Projet_brouillon.py","file_name":"Projet_brouillon.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"346437654","text":"import sys\n\nftable = open(sys.argv[1], 'r')\ntext = ftable.read().split(\"\\n\")\n\nclust = []\nfor line in text:\n#\tprint(line)\n\tfields = line.split()\n\tif len(fields) != 4:\n\t\tcontinue\n\tfound = False\n\tfor i in range(0, len(clust)):\n\t\tif fields[0] in clust[i]:\n\t\t\tif (not (fields[1] in clust[i]) and float(fields[3])>0.85):\n\t\t\t\tclust[i].append(fields[1])\n\t\t\tfound = True\n\t\t\tbreak\n\tif not found:\n\t\tclust.append([])\n\t\tclust[len(clust)-1].append(fields[0])\n\t\tif float(fields[3])>0.85:\n\t\t\tclust[len(clust)].append(fields[1])\n#\tprint(clust)\n\n#print(clust)\n#print(len(clust), sum([len(i) for i in clust]))\n\ncfile = open(sys.argv[2], 'r')\ntext = cfile.read().split(\"\\n\")\n\ncl2cl = {}\nfor line in text:\n\tfields = line.split()\n\tif len(fields) > 0:\n\t\tif fields[0] == \"group:\":\n\t\t\tng = int(fields[1])\n\t\telse:\n\t\t\tfor i in range(0, len(clust)):\n\t\t\t\tif fields[0] in clust[i]:\n\t\t\t\t\tcl2cl[i] = ng\n#print(cl2cl) \n\nfor i in range(1, ng+1):\n\tprint(\"Family #{0}\".format(i))\n\tno = 0\n\tfor j in cl2cl.keys():\n\t\tif cl2cl[j] == i:\n\t\t\tno += 1\n\t\t\tprint(\"\\tObject #{0}\".format(no))\n\t\t\tfor k in clust[j]:\n\t\t\t\tprint(\"\\t\\t{0}\".format(k))\n","sub_path":"old/clust.py","file_name":"clust.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"290995233","text":"#coding=utf-8\n#-------------------------------------------------------------------------------------------\n#作者:吴俊威 日期:2018年10月\n#内容:即有宝脚本生成与运行\n#--------------------------------------------------------------------------------------------\n# import time\nfrom run_main import *\nfrom jy_case.jyb_temp import *\nfrom appium import webdriver\n# import time\nfrom mobiletest.appcomm import *\nfrom common.fun_t import *\nfrom common.mysql_pub import *\nfrom common.mysql_pubtwo import *\nfrom common.oracle_pub import *\nfrom common.logger import Log\ncpath = PATH(\"..\\config\\yaml\\jyb\\jybcase1.yaml\")\n\ndef app_run_test(getid,uname,marknum):\n Log().info(\"即有宝提单开始执行\")\n # OracleUtil(dbname).oracle_sql(\"update dafy_sales.registers set status='n' where reg_number=1647 and reg_val_code=1805\") #关闭协议支付\n # OracleUtil(dbname).oracle_sql(\"update dafy_sales.sys_parameters set para_value=0 where para_id='LIVE_BODY_CHECK_SWITCH'\") #关闭活体检测\n try:\n markval=str(uname)+\"_\"+str(getid)+\"_\"+str(marknum)\n con_name,con_num,pc_type,pc_ip = getrun_db(getid)\n delpath=PATH(\"../case\")\n filename = 'test_'+str(uname)+\"_\"+str(getid)\n del_files(delpath,filename)\n time.sleep(2)\n for j in range(con_num):\n try:\n getparam,paramcount = param_db(uname)\n print(\"统计行:%s\"%paramcount)\n count_sys = 0\n for i in range(paramcount):\n try:\n filep = PATH(\"../case/test_\")+str(uname)+\"_\"+str(getid)+\"_\"+str(i)+\".py\"\n if getparam[i]['paraml'] == \"a\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n print(\"生成a合同case\")\n if getparam[i]['paraml'] == \"y\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试a合同\")\n print(\"生成y合同case\")\n if getparam[i]['paraml'] == \"s\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成s合同case\")\n if getparam[i]['paraml'] == \"pr\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试r合同\")\n remove_lines(filep,filep,\"流程测试s合同\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成pr合同case\")\n if getparam[i]['paraml'] == \"r\":\n remove_lines(PATH(\"../jy_case/jyb_temp.py\"),filep,\"#默认误删\")\n remove_lines(filep,filep,\"流程测试s合同\")\n remove_lines(filep,filep,\"流程测试a合同\")\n remove_lines(filep,filep,\"流程测试y合同\")\n print(\"生成r合同case\")\n with open(filep,'r',encoding='UTF-8') as ui:\n data = ui.readlines()\n for inx,line in enumerate(data):\n if inx == 14:\n val = str(\"newcon_name=\")+\"\\\"\"+str(\"默认空箺\")+\"\\\"\"+\"\\n\"+str(\"con_name=\")+\"\\\"\"+str(con_name)+\"\\\"\"+\"\\n\"+str(\"cpath=\")+\"PATH(\\\"..\\config\\yaml\\jyb\\jybcase1.yaml\\\")\"+\"\\n\"+str(\"pc_type=\")+\"\\\"\"+str(pc_type)+\"\\\"\"+\"\\n\"\\\n +str(\"pc_ip=\")+\"\\\"\"+str(pc_ip)+\"\\\"\"+\"\\n\"+str(\"getparam=\")+str(getparam[i])+\"\\n\"+str(\"uname=\")+\"\\\"\"+str(uname)+\"\\\"\"+\"\\n\"+str(\"markval=\")+\"\\\"\"+str(markval)+\"\\\"\"+\"\\n\"+str(\"class jyb_order_\")+str(uname)+\"_\"+str(getid)+\"_\"+str(i+1)+str(\"(unittest.TestCase):\")+\"\\n\"\n data[inx] = val\n else:\n data[inx] = line\n with open(filep,'w',encoding='UTF-8') as oi:\n oi.writelines(data)\n except Exception as e:\n print(e)\n count_sys = count_sys+i+1\n print(count_sys)\n except Exception as e:\n print(e)\n time.sleep(2)\n ruleval=\"test_\"+str(uname)+\"_\"+str(getid)+\"_*.py\"\n all_case = add_case(caseName=\"case\", rule=ruleval)\n run_casenew(all_case,\"result_wei.html\")\n report_path = os.path.join(cur_path, \"report\")\n print(report_path)\n report_file = get_reportfile(report_path,'result_wei.html')\n shutil.copyfile(report_file,os.path.join(cur_path, \"mobiletest/templates/result_wei.html\"))\n if count_sys > 0:\n run_sat = \"ok\"\n else:\n run_sat = \"fail\"\n except Exception as e:\n print(e)\n run_sat = \"fail\"\n return run_sat,markval\n","sub_path":"jy_case/jytest.py","file_name":"jytest.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"227001615","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author: Marc\n# @Date: 2015-03-02 21:23:23\n# @Last Modified by: Marc\n# @Last Modified time: 2015-03-04 21:16:28\n\nWTF_CSRF_ENABLED \t\t= True\nSECRET_KEY \t\t\t\t= 'qjefncjaiarto85730ij#'\n\n# Sijax\nSIJAX_STATIC_PATH \t\t= 'static/js/sijax/'\nSIJAX_JSON_URI\t\t\t= '/static/js/sijax/json2.js'\n\n# Pagination\nPER_PAGE \t\t\t\t= 10\nCSS_FRAMEWORK \t\t\t= 'bootstrap3'\nLINK_SIZE \t\t\t\t= 'sm'\n# decide whether or not a single page returns pagination\nSHOW_SINGLE_PAGE = False","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"104282527","text":"from keras import layers, models, optimizers\nfrom keras import backend as K\nimport numpy as np\n\nclass Actor:\n '''\n Actor (Policy) Model.\n \n Model: policy function mu(s | theta^{mu}).\n inputs: states values\n outputs: predicted actions.values\n Optimization: gradient descent\n '''\n\n def __init__(self, state_size, action_size, action_low, action_high, learning_rate):\n \"\"\"Initialize parameters and build model.\n \n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n action_low (array): Min value of each action dimension\n action_high (array): Max value of each action dimension\n learning_rate \n \"\"\"\n\n self.state_size = state_size\n self.action_size = action_size\n self.action_low = action_low\n self.action_high = action_high\n self.action_range = self.action_high - self.action_low\n self.learning_rate = learning_rate\n # model\n self.model = None\n # function for policy update\n self.train_fn = None\n # create model\n self.build_model()\n\n def build_model(self):\n '''Build an actor (policy) network.'''\n\n ########################### Network ###########################\n # input layer (states)\n states = layers.Input(shape=(self.state_size,), name='states')\n\n # hidden1\n h1 = layers.Dense(units=4, activation=None, use_bias=False)(states)\n h1 = layers.BatchNormalization()(h1)\n h1 = layers.Activation('relu')(h1)\n h1 = layers.Dropout(0.5)(h1)\n \n # hidden2\n h2 = layers.Dense(units=16, activation=None, use_bias=False)(h1)\n h2 = layers.BatchNormalization()(h2)\n h2 = layers.Activation('relu')(h2)\n h2 = layers.Dropout(0.5)(h2)\n '''\n # hidden3\n h3 = layers.Dense(units=32, activation=None, use_bias=False)(h2)\n h3 = layers.BatchNormalization()(h3)\n h3 = layers.Activation('relu')(h3)\n h3 = layers.Dropout(0.5)(h3)\n '''\n # output layer with sigmoid activation; output range -> [0,1]\n raw_actions = layers.Dense(units=self.action_size, activation='sigmoid',\n name='raw_actions')(h2)\n\n # Scale [0, 1] output for each action dimension to proper range\n actions = layers.Lambda(lambda x: (x * self.action_range) + self.action_low,\n name='actions')(raw_actions)\n\n # Create Keras model\n self.model = models.Model(inputs=states, outputs=actions)\n\n ##################### Loss & Optimization ######################\n \n # Define loss function using action value (Q value) gradients\n action_gradients = layers.Input(shape=(self.action_size,))\n loss = K.mean(-action_gradients * actions)\n\n # Define optimizer and training function\n optimizer = optimizers.Adam(lr=self.learning_rate)\n updates_op = optimizer.get_updates(params=self.model.trainable_weights, loss=loss)\n self.train_fn = K.function(\n inputs=[self.model.input, action_gradients, K.learning_phase()],\n outputs=[],\n updates=updates_op)\n\nclass Critic:\n '''\n Critic (Value) Model.\n \n Model: q_hat(s,a,w).\n inputs: states and action values\n output: predicted Q-values of the inputs\n Optimization:\n target: better estimated reward of the greedy-policy\n R_t+1 + gamma * Q(s_t+1, policy(s_t+1))\n loss: estimated reward\n mean squared error of \"(target) - (predicted Q-values of the inputs)\"\n '''\n\n def __init__(self, state_size, action_size, learning_rate):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n learning_rate:\n \"\"\"\n self.state_size = state_size\n self.action_size = action_size\n self.learning_rate = learning_rate\n # model\n self.model = None\n # action gradient for policy update\n self.get_action_gradients = None\n # create model\n self.build_model()\n\n def build_model(self):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n \n ########################### Network ###########################\n # input layers\n states = layers.Input(shape=(self.state_size,), name='states')\n actions = layers.Input(shape=(self.action_size,), name='actions')\n\n # hidden layer for state pathway\n h1_states = layers.Dense(units=64, activation=None, use_bias=False)(states)\n h1_states = layers.BatchNormalization()(h1_states)\n h1_states = layers.Activation('relu')(h1_states)\n h1_states = layers.Dropout(0.5)(h1_states)\n \n h2_states = layers.Dense(units=128, activation=None, use_bias=False)(h1_states)\n h2_states = layers.BatchNormalization()(h2_states)\n h2_states = layers.Activation('relu')(h2_states)\n h2_states = layers.Dropout(0.5)(h2_states)\n '''\n h3_states = layers.Dense(units=32, activation=None, use_bias=False)(h2_states)\n h3_states = layers.BatchNormalization()(h3_states)\n h3_states = layers.Activation('relu')(h3_states)\n h3_states = layers.Dropout(0.5)(h3_states)\n '''\n # Add hidden layer(s) for action pathway\n h1_actions = layers.Dense(units=64, activation=None, use_bias=False)(actions)\n h1_actions = layers.BatchNormalization()(h1_actions)\n h1_actions = layers.Activation('relu')(h1_actions)\n h1_states = layers.Dropout(0.5)(h1_states)\n \n h2_actions = layers.Dense(units=128, activation=None, use_bias=False)(h1_actions)\n h2_actions = layers.BatchNormalization()(h2_actions)\n h2_actions = layers.Activation('relu')(h2_actions)\n h2_states = layers.Dropout(0.5)(h2_states)\n '''\n h3_actions = layers.Dense(units=32, activation=None, use_bias=False)(h2_actions)\n h3_actions = layers.BatchNormalization()(h3_actions)\n h3_actions = layers.Activation('relu')(h3_actions)\n h3_states = layers.Dropout(0.5)(h3_states)\n '''\n # Combine state and action pathways\n add_net = layers.Add()([h2_states, h2_actions])\n add_net = layers.Activation('relu')(add_net)\n\n # Add final output layer to prduce action values (Q values)\n Q_values = layers.Dense(units=1, name='q_values')(add_net)\n\n # Create Keras model\n self.model = models.Model(inputs=[states, actions], outputs=Q_values)\n \n ###################### Loss & Optimization ######################\n \n # Define optimizer and compile model for training with built-in loss function\n optimizer = optimizers.Adam(lr=self.learning_rate)\n self.model.compile(optimizer=optimizer, loss='mse')\n\n ########## gradient caluculation for the actor network ##########\n \n # Compute action gradients (derivative of Q values w.r.t. to actions)\n action_gradients = K.gradients(Q_values, actions)\n\n # Define an additional function to fetch action gradients (to be used by actor model)\n self.get_action_gradients = K.function(\n inputs=[*self.model.input, K.learning_phase()],\n outputs=action_gradients)","sub_path":"agents/actor_critic.py","file_name":"actor_critic.py","file_ext":"py","file_size_in_byte":7517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"360530156","text":"length = 81 + 1\ninformation = \"@RELATION hog\\n\\n\"\nfor i in range(1,length):\n information += \"@ATTRIBUTE a\" + str(i) + \" REAL\\n\"\ninformation += \"@ATTRIBUTE class {1,2,3,4,5}\\n\\n\"\ninformation += \"@DATA\\n\"\n\nlabels = open(\"/home/emre/Desktop/labels.txt\", \"r\")\nread = \"/home/emre/Desktop/Feature Vectors/HOG/SCUT-FBP-\"\nresult = \"/home/emre/Desktop/Project/arff files/hog.arff\"\n\nfile = open(result, \"w+\")\nfile.write(information)\n\nfor i in range(1, 501):\n\n foo = open(read + str(i) + \".txt\", \"r\")\n for j in range(length-1):\n token = foo.readline()\n float_number = float(token)\n file.write(str(float_number) + \", \")\n foo.close()\n\n label = int(labels.readline())\n file.write(str(label) + \"\\n\")\n\nfile.close()\nlabels.close()","sub_path":"arffGenerator/HogGenerator.py","file_name":"HogGenerator.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"494573419","text":"\"\"\"ImportManager\n\nManages imported modules and protects against concurrent imports.\n\nKeeps lists of all imported Python modules and templates as well as other\nconfig files used by Webware for Python. Modules which are not directly\nimported can be monitored using hupper. This can be used to detect changes in\nsource files, templates or config files in order to reload them automatically.\n\"\"\"\n\n\nimport sys\nimport warnings\n\nfrom os.path import getmtime, isfile, join\nfrom importlib.util import module_from_spec, spec_from_file_location\nfrom importlib.machinery import (\n ModuleSpec, SourceFileLoader, SourcelessFileLoader)\n\n\nclass ImportManager:\n \"\"\"The import manager.\n\n Keeps track of the Python modules and other system files that have been\n imported and are used by Webware.\n \"\"\"\n\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n \"\"\"Create ImportManager as a singleton.\"\"\"\n if not cls._instance:\n cls._instance = super().__new__(cls, *args, **kwargs)\n return cls._instance\n\n def __init__(self):\n \"\"\"Initialize import manager.\"\"\"\n self._fileList = {}\n self._moduleFiles = {}\n self._notifyHook = None\n self._reloader = self.getReloader()\n\n def getReloader(self):\n \"\"\"Get the current reloader if the application is monitored.\"\"\"\n reloader = None\n with warnings.catch_warnings():\n # ignore deprecation warnings from hupper\n warnings.filterwarnings('ignore', category=DeprecationWarning)\n try:\n import hupper\n except ImportError:\n pass\n else:\n if hupper.is_active():\n try:\n reloader = hupper.get_reloader()\n except RuntimeError:\n pass\n if reloader:\n print('Application is monitored for reloading.')\n print()\n return reloader\n\n def moduleFromSpec(self, spec):\n \"\"\"Load the module with the given module spec.\"\"\"\n if not spec or not isinstance(spec, ModuleSpec):\n raise TypeError(f'Invalid spec: {spec!r}')\n try:\n module = module_from_spec(spec)\n except Exception:\n # Also record file paths which weren't successfully loaded, which\n # may happen due to a syntax error in a servlet, because we also\n # want to know when such a file is modified:\n if spec.origin:\n self.recordFile(spec.origin)\n raise\n self.recordModule(module)\n spec.loader.exec_module(module)\n return module\n\n def findSpec(self, name, path, fullModuleName=None):\n \"\"\"Find the module spec for the given name at the given path.\"\"\"\n if not name or not isinstance(name, str):\n raise TypeError(f'Invalid name: {name!r}')\n if not path or not isinstance(path, str):\n raise TypeError(f'Invalid path: {path!r}')\n\n # find package\n packageDirectory = join(path, name)\n packageFileName = '__init__.py'\n filePath = join(packageDirectory, packageFileName)\n if isfile(filePath):\n return spec_from_file_location(name, filePath)\n\n # find package as byte code without source\n filePath += 'c'\n if isfile(filePath):\n return spec_from_file_location(name, filePath)\n\n # find module\n fileName = f'{name}.py'\n filePath = join(path, fileName)\n if isfile(filePath):\n if fullModuleName:\n name = fullModuleName\n loader = SourceFileLoader(name, filePath)\n return spec_from_file_location(name, filePath, loader=loader)\n\n # find module as optimized byte code without source\n filePath += 'c'\n if isfile(filePath):\n loader = SourcelessFileLoader(name, filePath)\n return spec_from_file_location(name, filePath, loader=loader)\n\n raise ImportError(f'No module named {name!r}')\n\n def fileList(self, update=True):\n \"\"\"Return the list of tracked files.\"\"\"\n if update:\n # Update list of files of imported modules\n moduleNames = [modname for modname in sys.modules\n if modname not in self._moduleFiles]\n if moduleNames:\n self.recordModules(moduleNames)\n return self._fileList\n\n def notifyOfNewFiles(self, hook):\n \"\"\"Register notification hook.\n\n Called by someone else to register that they'd like to know\n when a new file is imported.\n \"\"\"\n self._notifyHook = hook\n\n def watchFile(self, path, moduleName=None, getmtime=getmtime):\n \"\"\"Add more files to watch without importing them.\"\"\"\n mtime = getmtime(path)\n self._fileList[path] = mtime\n if moduleName:\n self._moduleFiles[moduleName] = path\n # send notification that this file was imported\n if self._notifyHook:\n self._notifyHook(path, mtime)\n # let reloader know that this was imported\n if self._reloader:\n self._reloader.watch_files([path])\n\n def recordModule(self, module, isfile=isfile):\n \"\"\"Record a module.\"\"\"\n moduleName = getattr(module, '__name__', None)\n if not moduleName or moduleName not in sys.modules:\n return\n fileList = self._fileList\n # __orig_file__ is used for PSP and Cheetah templates; we want\n # to record the source filenames, not the auto-generated modules:\n f = getattr(module, '__orig_file__', None)\n if f and f not in fileList:\n try:\n if isfile(f):\n self.watchFile(f, moduleName)\n except OSError:\n pass\n else:\n f = getattr(module, '__file__', None)\n if f and f not in fileList:\n # record the .py file corresponding to each .pyc\n if f[-4:].lower() == '.pyc':\n f = f[:-1]\n try:\n if isfile(f):\n self.watchFile(f, moduleName)\n else:\n self.watchFile(join(f, '__init__.py'))\n except OSError:\n pass\n\n def recordModules(self, moduleNames=None):\n \"\"\"Record a list of modules (or all modules).\"\"\"\n if moduleNames is None:\n moduleNames = sys.modules\n for modname in moduleNames:\n mod = sys.modules[modname]\n self.recordModule(mod)\n\n def recordFile(self, filename, isfile=isfile):\n \"\"\"Record a file.\"\"\"\n if isfile(filename):\n self.watchFile(filename)\n\n def fileUpdated(self, filename, update=True, getmtime=getmtime):\n \"\"\"Check whether file has been updated.\"\"\"\n fileList = self.fileList(update)\n try:\n oldTime = fileList[filename]\n except KeyError:\n return True\n try:\n newTime = getmtime(filename)\n except OSError:\n return True\n if oldTime >= newTime:\n return False\n fileList[filename] = newTime\n # Note that the file list could be changed while running this\n # method in a monitor thread, so we don't use iteritems() here:\n for moduleName, moduleFile in self._moduleFiles.items():\n if moduleFile == filename:\n module = sys.modules.get(moduleName)\n return not module or not getattr(\n module, '__donotreload__', False)\n return True # it's not a module, we must reload\n\n def updatedFile(self, update=True, getmtime=getmtime):\n \"\"\"Check whether one of the files has been updated.\"\"\"\n fileList = self.fileList(update)\n for filename, oldTime in list(fileList.items()):\n try:\n newTime = getmtime(filename)\n except OSError:\n return filename\n if oldTime >= newTime:\n continue\n fileList[filename] = newTime\n for moduleName, moduleFile in self._moduleFiles.items():\n if moduleFile == filename:\n module = sys.modules.get(moduleName)\n if module and getattr(module, '__donotreload__', False):\n break\n return filename # it's a module that needs to be reloaded\n else:\n return filename # it's not a module, we must reload\n\n def delModules(self, includePythonModules=False, excludePrefixes=None):\n \"\"\"Delete imported modules.\n\n Deletes all the modules that have been imported unless they are part\n of Webware. This can be used to support auto reloading.\n \"\"\"\n moduleFiles = self._moduleFiles\n fileList = self._fileList\n for modname in moduleFiles:\n if modname == __name__:\n continue\n filename = self._moduleFiles[modname]\n if not includePythonModules:\n if not filename or filename.startswith(sys.prefix):\n continue\n for prefix in excludePrefixes or []:\n if modname.startswith(prefix):\n break\n else:\n try:\n del sys.modules[modname]\n except KeyError:\n pass\n try:\n del moduleFiles[modname]\n except KeyError:\n pass\n try:\n del fileList[filename]\n except KeyError:\n pass\n","sub_path":"webware/ImportManager.py","file_name":"ImportManager.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"326723846","text":"\r\n# execfile('product_discovery_functions.py'); \r\n\r\n\r\n\"\"\"\r\ndependency: execfile('feed_generation_functions.py');\r\n\"\"\"\r\n\r\n\r\ndef find_prod_names(cached_data1, score_maps1, para, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\tprod_names=para['prod_names']; \r\n\ti=para['i'];\r\n\treturn [{'name':name,} for name in set(prod_names[i]) ]; \r\n\r\ndef find_is_concept_names(cached_data1, score_maps1, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\tuse global function check_product_name()\r\n\t\"\"\"\r\n\tif not para or not para['concepts']:\r\n\t\tif not para: para=defaultdict(list); \r\n\t\tpara['concepts']=['is_concept', 'noun_concept']; # 'noun_title'\r\n\tif 'score_maps' in para.keys(): \r\n\t\tscore_maps1=para['score_maps'];\r\n\tfilters_map=[];\r\n\tfor concept_fn in para['concepts']:\r\n\t\tfilters_map.append(\t{'name':'is_product', 'type':'rel', 'fn':concept_fn,\r\n\t\t\t\t\t'keywords1':score_maps1['is_obj_names1'], \r\n\t\t\t\t\t'keywords2':score_maps1['is_obj_names2'], \r\n\t\t\t\t\t} );\r\n\t#print(filters_map);\r\n\t#\r\n\t#sb=subject_builder();\r\n\t#sb.subjectize_relations(cached_data1['relations']);\r\n\t#print_list(cached_data1['relations'], ['class', 'sbj','verb','adj','obj']);\r\n\tsf=subject_filter();\r\n\tsf.filters_map=filters_map;\r\n\tsf.relations=cached_data1['relations']; \r\n\tsf.blog_pos=cached_data1['blog_pos'];\r\n\trel=sf.search_objects('is_product', to_print=0);\r\n\t#print(sf.var);\r\n\tif to_print: print_list([t for t in sf.var['is_product'] ], ['sbj','verb','adj','obj','class']); \r\n\t#\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in sf.var['is_product']:\r\n\t\t#print(rel);\r\n\t\tif not rel['sbj']: continue; \r\n\t\tname=T(rel['sbj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry: \r\n\t\t\tif not check_product_name(name, to_print=to_print): continue;\r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\ndef find_howto_names(cached_data1, score_maps1=None, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\trb=relationship_builder(None);\r\n\tfor pos in cached_data1['blog_pos']: replace_howto_tags(pos); \r\n\trb.set_pos(cached_data1['blog_pos']);\r\n\trules=rb.get_howto_rules();\r\n\trb.parse_np_relations(rules, to_print=0);\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in rb.np_relations:\r\n\t\tif rel['np_sbj']: rel['sbj']=rel['np_sbj'][0];\r\n\t\tif rel['np_obj']: rel['obj']=rel['np_obj'][0];\r\n\t\tif rel['np_verb']: rel['verb']=rel['np_verb'][0];\r\n\t\t#\r\n\t\tif not rel['obj'] or not rel['verb']: continue; \r\n\t\tname=T(rel['verb']+rel['obj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry: \r\n\t\t\tif not check_product_name(name, to_print=to_print): continue; \r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\ndef find_rule_topics(cached_data1, score_maps1=None, para=None, to_print=True):\r\n\t\"\"\"\r\n\t\tcompute_fun() function for compute_blog_data_concept_names()\r\n\t\"\"\"\r\n\trules=[]; \r\n\trb=relationship_builder(None);\r\n\trb.set_pos(cached_data1['blog_pos']);\r\n\tif para and para['rules']: \r\n\t\trules=para['rules']\r\n\telse:\r\n\t\trules=rb.get_baby_rules();\r\n\trb.parse_np_relations(rules, to_print=0);\r\n\tprods=[];\r\n\tnames=[];\r\n\tfor rel in rb.np_relations:\r\n\t\tif rel['np_sbj']: rel['sbj']=rel['np_sbj'][0];\r\n\t\tif rel['np_obj']: rel['obj']=rel['np_obj'][0];\r\n\t\tif rel['np_verb']: rel['verb']=rel['np_verb'][0];\r\n\t\t#\r\n\t\tname=T(rel['sbj']);\r\n\t\tif not name or name in names: continue;\r\n\t\tnames.append(name);\r\n\t\ttry:\r\n\t\t\tif not check_product_name(name, to_print=to_print): continue; \r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods.append({'name':name, 'rel':rel});\r\n\t\t#\r\n\treturn prods;\r\n\r\n\r\ndef compute_blog_data_concept_names(blog_data, type_id, subtype_id, score_maps1, compute_fun, para=None, to_recompute=False, to_print=True, to_compute_context=True, to_save=True): \r\n\tproduct_names=[ [] for i in range(0, len(blog_data)) ]; \r\n\tif type_id==None: type_id='default';\r\n\tfor i in range(len(blog_data)): \r\n\t\tif to_print:\r\n\t\t\tif 'title' in blog_data[i].keys():\r\n\t\t\t\tprint('concept_names (%s - %s): post %d/%d: %s'%(type_id, subtype_id, i, len(blog_data), escape_html(blog_data[i]['title']))); \r\n\t\t\telif 'name' in blog_data[i].keys():\r\n\t\t\t\tprint('concept_names (%s - %s): post %d/%d: %s'%(type_id, subtype_id, i, len(blog_data), escape_html(blog_data[i]['name']))); \t\t\t\r\n\t\tpost=[];\r\n\t\tif isinstance(blog_data[i], dict) and 'data_t' in blog_data[i].keys(): \r\n\t\t\tpost=[blog_data[i]];\r\n\t\telse:\r\n\t\t\tpost=query_post_data(blog_data[i], category=workspace, solr_server=SOLR_SERVER);\r\n\t\tif not post: continue;\r\n\t\tif 'data_t' not in post[0].keys(): continue; \r\n\t\tcached_data1=decode_post_data(post[0]['data_t']);\r\n\t\tif not cached_data1: continue;\r\n\t\t#\r\n\t\trs=[];\r\n\t\ttry:\r\n\t\t\trs,s=solr_query_var({'category':workspace+'__concept_prods', 'type_id_s':type_id, 'subtype_id_s':subtype_id, 'post_id_s':cached_data1['id'] }, page=-1 );\r\n\t\t\t#rs,s=solr_query_var({'category':workspace+'__concept_prods', 'type_id_s':'default', 'post_id_s':blog_data[0]['id'] }, page=-1 )\r\n\t\texcept: \r\n\t\t\tpass; \r\n\t\t#\r\n\t\tprods=[];\r\n\t\tif rs and not to_recompute: \r\n\t\t\tif 'prods_t' in rs[0].keys(): \r\n\t\t\t\tprods=decode_post_data(rs[0]['prods_t']);\r\n\t\telse:\r\n\t\t\tif para: para['i']=i;\r\n\t\t\tprods=compute_fun(cached_data1, score_maps1, para=para, to_print=to_print);\r\n\t\t\tfor prod in prods: \r\n\t\t\t\tprod['type_id']=type_id;\r\n\t\t\t\tprod['subtype_id']=subtype_id;\r\n\t\t\t#\r\n\t\t\tif to_compute_context:\r\n\t\t\t\trb=relationship_builder(score_maps1);\r\n\t\t\t\trb.blog_id=[0 for j in range(len(cached_data1['blog_pos']))]; #use original idset\r\n\t\t\t\trb.blog_pos1=cached_data1['blog_pos'];\r\n\t\t\t\trb.relations=cached_data1['relations']; \r\n\t\t\t\tfor prod in prods: \r\n\t\t\t\t\t(left_verbs, right_verbs, adj_words, adj_attrs)=([],[],[],[]);\r\n\t\t\t\t\tprod_relations1=rb.search_subject_relations(prod['name'], rb.relations, short_name=10, long_name=True);\r\n\t\t\t\t\tfor rel in prod_relations1: \r\n\t\t\t\t\t\tif rel['class']=='left_verb': \r\n\t\t\t\t\t\t\tleft_verbs.append(T(rel['verb']));\r\n\t\t\t\t\t\telif rel['class']=='right_verb': \r\n\t\t\t\t\t\t\tright_verbs.append(T(rel['verb']));\r\n\t\t\t\t\t\telif rel['class']=='sent_phrase': \r\n\t\t\t\t\t\t\tadj_words.append(T(rel['adj']));\r\n\t\t\t\t\t\t\tif rel['obj']: \r\n\t\t\t\t\t\t\t\tadj_attrs.append(T(rel['adj']+rel['obj'])); \r\n\t\t\t\t\tprod['left_verbs']=left_verbs; \r\n\t\t\t\t\tprod['right_verbs']=right_verbs; \r\n\t\t\t\t\tprod['adj_words']=adj_words; \r\n\t\t\t\t\tprod['adj_attrs']=adj_attrs; \r\n\t\t\t#\r\n\t\t\trecord={'category':workspace+'__concept_prods', \r\n\t\t\t\t'type_id_s':type_id, \r\n\t\t\t\t'subtype_id_s':subtype_id, \r\n\t\t\t\t'post_id_s':cached_data1['id'], \r\n\t\t\t\t'date_dt': cached_data1['date_dt'],\r\n\t\t\t\t'updated_dt': datetime.now(),\r\n\t\t\t\t'prod_names_t': ':'+':'.join([r['name'] for r in prods])+':',\r\n\t\t\t\t'prods_t': encode_post_data(prods),\r\n\t\t\t\t}; \r\n\t\t\tif to_save:\r\n\t\t\t\tif rs: \r\n\t\t\t\t\trecord['id']=rs[0]['id']; \r\n\t\t\t\telse:\r\n\t\t\t\t\trecord['id']=solr_new_id('%s-%s-%s-%s'%(workspace+'__concept_prods', type_id, subtype_id, cached_data1['id']));\r\n\t\t\t\ts=solr_update_var(record); \r\n\t\t\t\ts=solr_commit();\r\n\t\t\telse: \r\n\t\t\t\tprint(\"record not saved!!\"); \r\n\t\t\t#\r\n\t\t#print(prods); \r\n\t\tproduct_names[i]=prods;\r\n\t\tif to_print: print_list(prods, ['name','left_verbs','right_verbs','adj_words','adj_attrs']); \r\n\t\t#if to_print: print_list([t['rel'] for t in prods], ['sbj','verb','adj','obj','class']); \r\n\treturn product_names;\r\n\r\n\r\ndef index_product_names(workspace, pnames): \r\n\t\"\"\"\r\n\t\t(need to use mysql, name search is not reliable here)\r\n\t\tindex inhouse product names, \r\n\t\treturn a list of the associated ids\r\n\t\"\"\"\r\n\tcategory_id=workspace + '__product_name' \r\n\tproduct_ids=[]; \r\n\tfor i, pname in enumerate(pnames): \r\n\t\tp,s=solr_query_var({'category': category_id, 'name': pname['name']});\r\n\t\tpid='';\r\n\t\tif p: \r\n\t\t\tpid=p[0]['id']; \r\n\t\telse: \r\n\t\t\tpid=solr_new_id('%s-%s'%(category_id, pname['name']));\r\n\t\t\tp,s=solr_update_var({'category': category_id, 'name': pname['name'], 'id':pid});\r\n\t\t\tsolr_commit(); \r\n\t\tproduct_ids.append(pid);\r\n\treturn product_ids; \r\n\r\n\r\ndef index_product_articles(workspace, product_title_names, blog_post, product_title_index, product_ids, to_recompute=False):\r\n\t\"\"\"\r\n\t\tindex product names found from each article\r\n\t\tproduct_title_names: product names found from articles\r\n\t\tblog_pos: articles\r\n\t\tproduct_title_index: product indices associated with each name\r\n\t\tproduct_ids: product id associated with each product index, product id is the id for workspace + '__product_name'\r\n\t\"\"\"\r\n\tcategory_id=workspace + '__product_index' \r\n\tfor i,names in enumerate(product_title_names):\r\n\t\tbid=blog_post[i]['id']; \r\n\t\tb,s=solr_query_var({'category': category_id, 'bid': bid});\r\n\t\tif b and not to_recompute: continue; \r\n\t\tif to_recompute: \r\n\t\t\tb,s=solr_delete_var({'category': category_id, 'bid': bid});\r\n\t\t\tsolr_commit(); \r\n\t\tpid_names=defaultdict(list); \r\n\t\tfor name in names: #each product name\r\n\t\t\tfor p in product_title_index[name]: # each product index associated with the product name\r\n\t\t\t\tpid_names[product_ids[p]].append(name); #use product id\r\n\t\tfor pid in pid_names.keys(): #create one record for each (bid, pid) \r\n\t\t\trecord={'category': category_id, 'bid': bid, 'pid':pid, 'names':encode_post_data(pid_names[pid]) }; \r\n\t\t\trecord['id']=solr_new_id('%s-%s-%s'%(category_id, bid, pid));\r\n\t\t\tb,s=solr_update_var(record); \r\n\t\tsolr_commit();\r\n\r\ndef apriori_products(product_names, L, min_support, min_confidence):\r\n\tproduct_sets=[set(names) for names in product_names ];\r\n\tN=len(product_sets); \r\n\tLLC=[defaultdict(int) for i in range(L+1)]; \r\n\tfor names in product_sets: \r\n\t\tfor name in names: \r\n\t\t\tLLC[1][(name,)]+=1; \r\n\tLLcache=[[defaultdict(list) for i in range(L+1)] for j in range(N) ]; \r\n\tfor j in range(N): \r\n\t\tLLcache[j][1]=[(name,) for name in product_sets[j] if LLC[1][(name,)]>=min_support]\r\n\t#\r\n\tCF=[[] for i in range(L+1)];\r\n\tLL=[[] for i in range(L+1)];\r\n\tLL[1]=sorted([(nn,c) for nn,c in LLC[1].items() if c>=min_support], key=lambda k: k[1], reverse=True); \r\n\t#\r\n\tfor l in range(2,L+1):\r\n\t\tfor i,names in enumerate(product_sets):\r\n\t\t\tif len(names)>=30: print(i, len(names));\r\n\t\t\t#subsets=subset_combinations([name for name in names if name in LL[l-1]], l);\r\n\t\t\tsubsets=subset_combinations2(LLcache[i], LLC, l, min_support);\r\n\t\t\tfor nn in subsets: \r\n\t\t\t\tLLC[l][tuple(sorted(nn))]+=1; \r\n\t\thas_confidence=(min_confidence==None);\r\n\t\tif min_confidence != None: \r\n\t\t\tfor nn,c in LLC[l].items(): \r\n\t\t\t\tif c>=min_support: \r\n\t\t\t\t\tfor nn1 in [nn2 for k in range(1, l) for nn2 in subset_combinations(nn, k)]: \r\n\t\t\t\t\t\tcf=LLC[l][nn]*1.0/LLC[len(nn1)][tuple(nn1)];\r\n\t\t\t\t\t\tif cf >= min_confidence:\r\n\t\t\t\t\t\t\thas_confidence=True;\r\n\t\t\t\t\t\t\tCF[len(nn1)].append([cf, (nn1, LLC[len(nn1)][tuple(nn1)]), (list(set(nn)-set(nn1)), LLC[l][nn])]);\r\n\t\tLL[l]=sorted([(nn,c) for nn,c in LLC[l].items() if c>=min_support and has_confidence ], key=lambda k: k[1], reverse=True);\r\n\treturn LLC, LL, CF; \r\n\r\ndef subset_combinations2(LLcache1, LLC, L, min_support):\r\n\tnames_list=[names for names in LLcache1[L-1] if LLC[L-1][tuple(names)]>=min_support]; \r\n\t#if len(names_list)>30: print(names_list);\r\n\tfound_names=set(); \r\n\told_names=set([tuple(names) for names in names_list]);\r\n\tfor i in range(0, len(names_list)):\r\n\t\tfor j in range(i, len(names_list)): \r\n\t\t\tnewset=set(names_list[i])|set(names_list[j]);\r\n\t\t\tif len(newset)!=L: continue; \r\n\t\t\tif tuple(newset) in found_names: continue; \r\n\t\t\tis_goodset=True;\r\n\t\t\tfor subset in subset_combinations(list(newset), L-1): \r\n\t\t\t\tif tuple(subset) not in old_names: \r\n\t\t\t\t\tis_goodset=False; \r\n\t\t\t\t\tbreak;\r\n\t\t\tif not is_goodset: continue; \r\n\t\t\tfound_names.add(tuple(newset) );\r\n\t\t\t#if len(names_list)>30: print(newset);\r\n\tLLcache1[L]=found_names; \r\n\t#if len(names_list)>20: \r\n\t#\tprint('------');\r\n\t#\tprint(found_names);\r\n\treturn found_names;\r\n\r\ndef subset_combinations(names, L):\r\n\t#exhaustive combinations of len L\r\n\tN=len(names);\r\n\tif N[<[^\\(\\*\\)]*/NN.*><.*/CD>]*', overlap=False);\r\n\t\t\t\tfor noun in nouns: \r\n\t\t\t\t\trelease_filtered_names[i].append(T(noun));\r\n\t\t\t\tproducts[cached_data1['id']].append(r['product_s']); \r\n\t\tprint('---'); \r\n\t\tprint(release_filtered_names[i]);\r\n\t\tprint(' '); \r\n\t#\r\n\treturn release_filtered_names;\r\n\r\ndef filter_prod_names(cached_data1, search_methods, score_maps1):\r\n\t\"\"\"\r\n\t\tfilter cached_data1 for potential product names \r\n\t\"\"\"\r\n\tsub=subject_builder(); \r\n\tsub.set_relations(cached_data1['relations'], to_print=0);\r\n\trb=relationship_builder(score_maps1);\r\n\trb.blog_id=[0]*len(cached_data1['blog_pos']);\r\n\trb.blog_pos1=cached_data1['blog_pos'];\r\n\trb.relations=cached_data1['relations'];\r\n\tfound_sbjs=[]; \r\n\tsummr=text_summarizer();\r\n\ta=htql.Tools(); \r\n\tif 'release_filter' in search_methods: \r\n\t\tfor sbj, items in sub.subjects.items():\r\n\t\t\tfor item in items: \r\n\t\t\t\tif item['target']=='sbj':\r\n\t\t\t\t\tscore=rb.item_left_verb_score(item['rel'], score_maps1['release_filter_keyword_map']);\r\n\t\t\t\t\tif score>0.5:\r\n\t\t\t\t\t\tfound_sbjs.append({'sbj':sbj, 'verb':item['rel']['verb'], 'method':'release_verb', 'isentence':item['rel']['isentence'], 'class':item['rel']['class'] });\r\n\tif 'offer_verb' in search_methods: \r\n\t\tfor sbj, items in sub.subjects.items():\r\n\t\t\tfor item in items: \r\n\t\t\t\tif item['target']=='sbj':\r\n\t\t\t\t\tscore=rb.item_right_verb_score(item['rel'], score_maps1['offer_keyword_map']);\r\n\t\t\t\t\tif score>0.5:\r\n\t\t\t\t\t\tfound_sbjs.append({'sbj':sbj, 'verb':item['rel']['verb'], 'method':'offer_verb', 'isentence':item['rel']['isentence'], 'class':item['rel']['class'] });\r\n\tif 'release_noun' in search_methods: \r\n\t\trb.np_relations=[];\r\n\t\trules=rb.get_renoun_rules(score_maps1['release_noun_names1']);\r\n\t\trb.parse_np_relations(rules, to_print=0);\r\n\t\tfor item in rb.np_relations: \r\n\t\t\tif item['np_sbj'] and item['np_obj']:\r\n\t\t\t\tfound_sbjs.append({'sbj':item['np_sbj'][0], 'verb':item['np_obj'][0], 'method':'release_noun', 'isentence':item['isentence'], 'class':item['class']});\r\n\tif 'num_amount' in search_methods: \r\n\t\trb.np_relations=[];\r\n\t\trules=rb.get_renum_rules(score_maps1['num_amount_names1']);\r\n\t\trb.parse_np_relations(rules, to_print=0);\r\n\t\tfor item in rb.np_relations: \r\n\t\t\tif item['np_obj']:\r\n\t\t\t\tfor item1 in item['np_sbj']: \r\n\t\t\t\t\tfound_sbjs.append({'sbj':item1, 'verb':item['np_obj'][0], 'method':'num_amount', 'isentence':item['isentence'], 'class':item['class']});\r\n\tsbj_names=[]; \r\n\treleased_prods=[];\r\n\tfor item in found_sbjs:\r\n\t\tsbj=item['sbj'];\r\n\t\tprodname=T(sbj);\r\n\t\tif prodname in sbj_names: continue; \r\n\t\tsbj_names.append(prodname); \r\n\t\tproduct_phrases=summr.find_product_phrases(rb, prodname);\r\n\t\tis_obj=[t[0].lower() for phrase in product_phrases['is_phrases'] for t in phrase['r']['obj'] ] + prodname.lower().split(); \r\n\t\tis_obj+=[n[:-1] for n in is_obj if n[-1]=='s'] + [n[:-1] for n in is_obj if n[-1]=='.'];\r\n\t\tis_names=[T(phrase['r']['obj']) for phrase in product_phrases['is_phrases'] ];\r\n\t\tcompany_names=[T(phrase['r']['obj']) for phrase in product_phrases['release_phrases'] ];\r\n\t\toffer_names=[T(phrase['r']['obj']) for phrase in product_phrases['offer_phrases'] ];\r\n\t\t#\r\n\t\tprod_relations=rb.search_subject_relations(prodname, short_name=3, long_name=True);\r\n\t\tsent_attrs=rb.relation_sent_scores(prod_relations);\r\n\t\tsent_scores=[t['score'] for t in sent_attrs if t['score']<-0.01 or t['score']>0.01];\r\n\t\t#\r\n\t\tprint(cached_data1['blog_pos'][item['isentence']]);\r\n\t\tsbj_extended=sbj; \r\n\t\tif 'num_amount' not in search_methods: \r\n\t\t\tsbj1=a.reSearchList(cached_data1['blog_pos'][item['isentence']], \"<.*/VBG>?\"+''.join(['<%s/%s>'%(escape_relist(s[0]), escape_relist(s[1]) ) for s in sbj])+r\"([<[^(that|which|before|after)]*/IN><.*/VBG>][<.*/DT|NN|NNP|JJ|NNS|CC|CD|PRP|VBG>]+)*\");\r\n\t\t\tif sbj1: sbj_extended=sbj1[0];\r\n\t\tprint(' ');\r\n\t\tprint(('-->', T(sbj_extended), '<--' ,T(item['verb']), item['method'], T(cached_data1['blog_pos'][item['isentence']]) ) ); \r\n\t\tprint(is_names);\r\n\t\tprint(company_names);\r\n\t\tprint(offer_names);\r\n\t\tprint(' ');\r\n\t\treleased_prod={'category':workspace+'__released_prod', \r\n\t\t\t\t\t'post_id_s':cached_data1['id'],\r\n\t\t\t\t\t'product_s': T(sbj_extended), \r\n\t\t\t\t\t'isentence_i': item['isentence'],\r\n\t\t\t\t\t'verb_s': T(item['verb']), \r\n\t\t\t\t\t'class_s': item['class'],\r\n\t\t\t\t\t'sbj_pos_s': encode_post_data(sbj), \r\n\t\t\t\t\t'is_obj_s': encode_post_data(is_obj), \r\n\t\t\t\t\t'is_names_s': encode_post_data(is_names), \r\n\t\t\t\t\t'company_names_s': encode_post_data(company_names), \r\n\t\t\t\t\t'offer_names_s': encode_post_data(offer_names),\r\n\t\t\t\t\t'sent_attrs_t': encode_post_data(sent_attrs),\r\n\t\t\t\t\t'blog_date_dt': cached_data1['date_dt'],\r\n\t\t\t\t};\r\n\t\told,s=solr_query_var({'category':workspace+'__released_prod', \r\n\t\t\t\t\t'post_id_s':cached_data1['id'],\r\n\t\t\t\t\t'product_s': T(sbj_extended), \r\n\t\t\t\t\t'isentence_i': item['isentence'],\r\n\t\t\t\t\t'verb_s': T(item['verb']), \r\n\t\t\t\t});\r\n\t\tif old: released_prod['id']=old[0]['id']; \r\n\t\telse: released_prod['id']=solr_new_id('%s-%s-%s'%(released_prod['category'], released_prod['post_id_s'], released_prod['product_s']));\r\n\t\ts=solr_update_var(released_prod); \r\n\t\ts=solr_commit();\r\n\t\treleased_prods.append(released_prod);\r\n\treturn released_prods; \r\n\r\n\r\n\r\n\r\n\"\"\"\r\nworkspace='blog-electronics';\r\nexecfile('load_data.py');\r\nblog_data=load_var('blog_data');\r\n\r\n\r\nb,s=solr_query_var({'category':workspace, 'date_dt':(datetime.now() - timedelta(4), datetime.now() ) }, page=None); \r\nfor i,b1 in enumerate(b): \r\n\tcached_data1=decode_post_data(b1['data_t']); \r\n\tdevices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['product','device', 'tool', 'tv', 'smartphone', 'computer', 'camera', 'phone', 'platform', 'pc', 'version', 'update', 'system', 'software', 'hardware', 'gadget', 'laptop', 'tablet', 'console', 'game']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['company', 'investor', 'corporation']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' and (set(T(v['obj']).lower().split()) & set(['person', 'chief', 'director', 'ceo','chairman','manager','businessman', 'reporter', 'executive', 'president', 'officer', 'cto', 'cfo']) ) ];\r\n\t#devices=[v for v in cached_data1['relations'] if v['class']=='sbj_is' ];\r\n\tif devices:\r\n\t\tprint(i, '=========== ', cached_data1['name'], ' ==========');\r\n\t\tprint_list(devices, ['sbj','verb','obj']); \r\n\t\tfor device in devices: \r\n\t\t\tprint('----------------------');\r\n\t\t\trel=[s['rel'] for s in cached_data1['subjects'][tuple(device['sbj'])] if s['target']=='sbj' ];\r\n\t\t\tprint_list(rel, ['sbj','verb','adj','obj','class']);\r\n\t\r\ni=537;\r\ncached_data1=decode_post_data(b[i]['data_t']); \r\nsubjects=cached_data1['subjects']\r\n\r\n\r\n\t\r\n\"\"\"\r\n","sub_path":"www/cgi-bin/product_discovery_functions.py","file_name":"product_discovery_functions.py","file_ext":"py","file_size_in_byte":19779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"149740374","text":"from __future__ import division, print_function, unicode_literals\r\n\r\nfrom sacred import Experiment\r\nfrom sacred.observers import FileStorageObserver\r\nfrom utils.custom_observer import CustomObserver\r\n\r\nfrom config import ingredient_config\r\nfrom utils.path_utils import filelist, remove_files\r\nimport logging\r\n\r\nimport os\r\nfrom collections import OrderedDict\r\nimport joblib\r\nimport numpy as np\r\nimport json\r\nimport pandas as pd\r\nimport random\r\nimport glob\r\nfrom functools import partial\r\nimport shutil\r\nimport re\r\nimport random\r\nimport collections\r\n\r\nimport utils.scoring\r\n#from utils.results import aggregate\r\nfrom utils.excel_writer import df_to_excel\r\nfrom utils.observers import get_observers\r\nfrom utils.plotting import plot_curves\r\nfrom utils.df_helper import filter_df, best_by_group, best_row, stringify_cols, stringify\r\n\r\nfrom utils.path_utils import find_files, copy_files\r\nfrom visualization.figures import bar_chart_grouped\r\n\r\nfrom utils.proj_setup import setup_dir\r\n\r\nfrom constants import *\r\n\r\n\r\n# Define experiment and load ingredients\r\nex = Experiment('step211_event_detect_cv_best', ingredients=[ingredient_config])\r\n\r\n\r\n@ex.config\r\ndef cfg(config):\r\n \r\n \r\n \r\n '''\r\n Input and outputs\r\n '''\r\n \r\n # Source\r\n source = 'cv_tune_event_detect'\r\n \r\n # Destination\r\n dest = 'cv_best_event_detect'\r\n \r\n \r\n '''\r\n Paths\r\n '''\r\n \r\n # Source directory\r\n source_ = config[source]\r\n dest_ = config[dest]\r\n scratch = setup_dir(dest_, config['root'], config['scratch'])\r\n \r\n \r\n \r\n cmap = 'tab10'\r\n alpha = 0.8\r\n figsize=(8,3)\r\n width = 0.2\r\n\r\n # Labeling\r\n\r\n '''\r\n Evaluation metrics\r\n '''\r\n average = config['average']\r\n metric = config['metric']\r\n\r\n column_map = config['column_map'] \r\n\r\n float_format = config['float_format']\r\n \r\n \r\n\r\n\r\n cases = OrderedDict()\r\n\r\n\r\n header = 'Determinant'\r\n cases['base'] = {'Determinant': '_MICRO', 'label': 'micro'}\r\n\r\n\r\n\r\n groupby = []\r\n order = {}\r\n\r\n params = ['rnn_type', 'rnn_hidden_size', 'xfmr_type', 'num_epochs', 'max_len', 'dropout_input', 'attn_type', 'attn_size', 'attn_dropout']\r\n\r\n \r\n\r\n #for k, v in cases.items():\r\n # v['eval_range'] = END_TO_END\r\n\r\n \r\n\r\n # Create observers\r\n file_observ = FileStorageObserver.create(dest_)\r\n cust_observ = CustomObserver(dest_)\r\n ex.observers.append(file_observ)\r\n ex.observers.append(cust_observ)\r\n \r\ndef filt(row, criteria):\r\n\r\n out = all([(row[c] is v) or (row[c] == v) for c, v in criteria.items()])\r\n\r\n return out\r\n \r\ndef as_list(X, ndigits = 3):\r\n \r\n \r\n X = [str(round(x, ndigits)) for x in X]\r\n \r\n return '[{}]'.format(', '.join(X)) \r\n \r\n\r\n \r\n \r\n@ex.automain\r\ndef main(source_, dest_, \r\n column_map, metric, \r\n float_format,\r\n average, \r\n params, cases,\r\n cmap, alpha, figsize, width, groupby, order, header\r\n ):\r\n \r\n\r\n\r\n # Find all result files\r\n files = find_files(source_, SCORES_FILE, recursive=True)\r\n logging.info(\"source_:\\t{}\".format(source_))\r\n logging.info(\"Score filenames:\\t{}\".format(SCORES_FILE))\r\n logging.info(\"Result file count:\\t{}\".format(len(files)))\r\n logging.info(\"Looping on subsets...\")\r\n\r\n df_dict = OrderedDict()\r\n logging.info(\"\\nLoading files\")\r\n n = len(files)\r\n for i, fn in enumerate(files):\r\n \r\n # Use result directory as description\r\n descrip = os.path.basename(os.path.dirname(fn))\r\n \r\n logging.info(\"Loading {} of {}: {}\".format(i + 1, n, descrip))\r\n \r\n # Load result\r\n df_dict[descrip] = pd.read_csv(fn)\r\n \r\n '''\r\n Load results into dataframe\r\n '''\r\n for case, criteria in cases.items():\r\n \r\n dfs = []\r\n logging.info(\"\\nProcessing: {}\".format(case))\r\n n = len(files)\r\n for descrip, df in df_dict.items():\r\n \r\n # Get parameters\r\n extracted_params = []\r\n for p in params:\r\n if (p not in criteria):\r\n if (p in df.iloc[0]): \r\n extracted_params.append((p, df.iloc[0][p])) \r\n else:\r\n extracted_params.append((p, 0)) \r\n\r\n # Iterate over rows in dataframe \r\n extracted_perf = [] \r\n for idx, row in df.iterrows():\r\n if filt(row, criteria):\r\n \r\n extracted_perf.append((metric, row[metric]))\r\n \r\n if len(extracted_perf) > 0:\r\n # Combine performance and params tupls\r\n extracted = extracted_perf + list(criteria.items()) + extracted_params\r\n\r\n # Build data frame\r\n cols, vals = zip(*extracted)\r\n cols = list(cols)\r\n df_tmp = pd.DataFrame([vals], columns=cols)\r\n\r\n columns = df_tmp.columns.tolist()\r\n assert len(columns) == len(set(columns)), \\\r\n \"duplicate column: {}\".format(columns)\r\n\r\n # Collect results\r\n dfs.append(df_tmp)\r\n \r\n # Concatenate dataframe and resort columns\r\n df = pd.concat(dfs)\r\n\r\n '''\r\n Create spreadsheet\r\n '''\r\n # Columns with float format\r\n columns_float = [c for c in df.columns.values.tolist() \\\r\n if c not in params] \r\n \r\n # Write to disk \r\n fn = os.path.join(dest_, '{}.xlsx'.format(case)) \r\n \r\n df_to_excel(df, fn,\r\n columns_disp = None,\r\n columns_float = columns_float,\r\n columns_int = [],\r\n columns_3_color_scale = columns_float,\r\n column_map = column_map,\r\n float_format = float_format,\r\n )\r\n\r\n\r\n return \"Complete\"\r\n \r\n","sub_path":"code/step211_event_detect_cv_best.py","file_name":"step211_event_detect_cv_best.py","file_ext":"py","file_size_in_byte":5924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"48715601","text":"import pandas as pd\n\ndf=pd.DataFrame([\n ['green', 'M', 10.1, 'class1'],\n ['red', 'L', 13.5, 'class2'],\n ['blue', 'XL', 15.3, 'class1']])\n\ndf.columns=['color','size','price','classlabel']\n\nsize_mapping={\n \"M\":1,\n \"L\":2,\n \"XL\":3}\ninverse_size_mapping={k:v for v,k in size_mapping.items()}\n\n\ndf['size']=df['size'].map(size_mapping)\nimport numpy as np\n\nclass_mapping={\n lab:idx for idx,lab in enumerate(np.unique(df['classlabel']))}\n\ndf['classlabel']=df['classlabel'].map(class_mapping)\n\nprint(df)\n\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\n\nX=df[['color','size','price']].values\n\ncolor_le=LabelEncoder()\nX[:,0]=color_le.fit_transform(X[:,0])\n\n\nprint(X)\n\nohe=OneHotEncoder(categorical_features=[0])\nohe.fit_transform(X).toarray()\n\nprint(ohe,X)\n\n\n","sub_path":"chapter4/pddata.py","file_name":"pddata.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"358658814","text":"import pandas as pd\nimport os, pickle\nfrom os.path import join\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom glob import glob\nfrom matplotlib.ticker import AutoMinorLocator\n\nfrom toPrecision import toPrecision\nimport FunctionsMLFSOMPeaks as myfunc\n\nimage_folder = '/Users/atakisi/Desktop/MLFSOM/data_gaussian_N4_1.5A'\n\ndf_peaks = myfunc.ReadGaussianPeakIntensities(image_folder)\ndf_shells = myfunc.ShellIntensities(df_peaks,20)\n\nplt.close('all')\nfig, ax = plt.subplots()\nplt.ion()\n\n# data\nd_space = df_shells.d_max*0.5+df_shells.d_min*0.5\nD_half = df_shells.D_half\nplt.scatter(d_space,D_half,edgecolors='black',s=150)\n# fitting line\nx = np.linspace(1.4, 10, 100)\nK = 0.52\ny = K * x**2\nax.plot(x, y, linestyle = '--', color='tab:red', linewidth=2)\n\n\nax.set_ylim(ymin=1)\nax.set_xticks([1,10])\n\nax.set_xscale('log')\nax.set_yscale('log')\nax.set_xlabel('Resolution ($\\mathrm{\\\\AA}$)',fontsize='x-large')\nax.set_ylabel('Half-dose (arbitrary)',fontsize='x-large')\nax.tick_params(axis='both', which='both', length=0, labelsize='x-large',pad=10)\nax.grid(which='major',linewidth=0.4)\nax.grid(which='minor',linewidth=0.2)\nax.set_facecolor('0.95')\nfor axis in ['top','bottom','left','right']: ax.spines[axis].set_visible(False)\nplt.tight_layout()\n\nplt.show()\n\n\n","sub_path":"trash.py","file_name":"trash.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"567665860","text":"from api.core.base import BaseEngine\nfrom api.core.models import AnimeMetaInfo, AnimeDetailInfo, Video, VideoCollection\nfrom api.utils.logger import logger\n\n\nclass EYunZun(BaseEngine):\n \"\"\"该引擎网络不稳定, 有时响应响应很长时间\"\"\"\n\n def __init__(self):\n self._base_url = \"https://api.eyunzhu.com/api/vatfs/resource_site_collect\"\n self._search_api = self._base_url + \"/search\"\n self._detail_api = self._base_url + \"/getVDetail\"\n\n def search(self, keyword: str):\n logger.info(f\"Searching for: {keyword}\")\n resp = self.get(self._search_api, params={\"kw\": keyword, \"per_page\": 100, \"page\": 1}) # 取前 100 条结果\n if resp.status_code != 200 or resp.json()[\"code\"] != 1:\n logger.warning(f\"Response error: {resp.status_code} {self._search_api}\")\n return\n\n data = resp.json()\n anime_meta_list = data.get(\"data\").get(\"data\") if data else []\n for meta in anime_meta_list:\n anime = AnimeMetaInfo()\n anime.title = meta[\"name\"]\n anime.cover_url = meta[\"pic\"]\n anime.category = meta[\"type\"]\n anime.detail_page_url = str(meta[\"vid\"])\n anime.desc = meta[\"label\"]\n yield anime\n\n def get_detail(self, detail_page_url: str):\n resp = self.get(self._detail_api, params={\"vid\": detail_page_url})\n if resp.status_code != 200 or resp.json()[\"code\"] != 1:\n logger.warning(f\"Response error: {resp.status_code} {self._search_api}\")\n return AnimeDetailInfo()\n\n detail = resp.json().get(\"data\") # 视频详情信息\n anime_detail = AnimeDetailInfo()\n anime_detail.title = detail[\"name\"]\n anime_detail.cover_url = detail[\"pic\"]\n anime_detail.desc = detail[\"label\"]\n anime_detail.category = detail[\"type\"]\n\n vc = VideoCollection()\n vc.name = \"视频列表\"\n video_set = dict(detail[\"playUrl\"])\n for name, url in video_set.items():\n vc.append(Video(name, url))\n anime_detail.append(vc)\n return anime_detail\n","sub_path":"api/engines/eyunzhu.py","file_name":"eyunzhu.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"399534012","text":"import pandas as pd\nimport numpy as np\n\nimport pathlib\n\ndf = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n\ndef test():\n print(\"working\")\n \ndef locality():\n df = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n df = df.set_index('S.No.')\n df = df.dropna(subset=['PIN'])\n df.drop(df[df['PIN'] == '-' ].index , inplace=True)\n graph=df['PIN'].value_counts()\n graph=graph.dropna()\n x=(graph.tolist())\n y=[]\n for i in graph.index.tolist():\n y.append(str(i))\n return(x,y)\n\ndef country():\n df = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/Bengaluru.xls\")\n country=df['Port of Origin of journey'].value_counts()\n y=(country[0:20].tolist())\n x=[]\n for i in country[0:20].index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef gender():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Gender=Diagonised[\"Gender\"].value_counts()\n y=(Gender.tolist())\n x=[]\n for i in Gender.index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef Type_of_Infection_source():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Type_of_Infection_source=Diagonised[\"Type of Infection\\nsource\"].value_counts()\n y=(Type_of_Infection_source.tolist())\n x=[]\n for i in Type_of_Infection_source.index.tolist():\n x.append(str(i))\n return(x,y)\n\ndef age():\n Diagonised = pd.read_excel(str(pathlib.Path().absolute())+\"/Data/D_Bengaluru.xlsx\")\n Age=Diagonised[\"Age\"].value_counts()\n y=(Age.tolist())\n x=[]\n for i in Age.index.tolist():\n x.append(str(i))\n return(x,y)","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"147743027","text":"a = []\nprint('Вводьте стрічки з нового рядка, після останньої натисніть \"Enter\"\\n')\nwhile True:\n\tq = input()\n\tif q == '':\n\t\tbreak\n\telse:\n\t\ta.append(q)\n\nwith_x, without_x = [], []\n\nfor i in a:\n\twith_x.append(i) if i.startswith('x') else without_x.append(i)\n\nwith_x.sort()\nwithout_x.sort()\n\na = with_x + without_x\n\nprint(a)","sub_path":"Задачі 1/0.3 Списки/2. Ті, що починаються з X на початку.py","file_name":"2. Ті, що починаються з X на початку.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"218093528","text":"\"\"\"\nDjango settings for fourpoints project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nLOG_DIR = os.path.join(BASE_DIR, 'logs')\n\ntry:\n os.makedirs(LOG_DIR)\nexcept:\n pass\n\nADMINS = (\n ('Xindong Ding', 'dxd.spirits@gmail.com'),\n)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'f^mv=5w3_+6fl=a0qed(z5-ij-g@@9o#dh79xj5e6442am^yf^'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = False\n\nTEMPLATE_DEBUG = False\n\nALLOWED_HOSTS = ['*']\n\n# Application definition\n\nINSTALLED_APPS = (\n 'suit',\n \n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n \n 'rest_framework',\n 'rest_framework.authtoken',\n 'corsheaders',\n \n 'users',\n 'polls',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.gzip.GZipMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'fourpoints.urls'\n\nWSGI_APPLICATION = 'fourpoints.wsgi.application'\n\n# Templates\n\nfrom django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP\n\nTEMPLATE_CONTEXT_PROCESSORS = TCP + (\n 'django.core.context_processors.request',\n)\n\n# Rest framework\n\nREST_FRAMEWORK = {\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.UnicodeJSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n #'rest_framework.authentication.SessionAuthentication',\n #'rest_framework.authentication.BasicAuthentication',\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),\n}\n\n# CORS\n\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_ALLOW_HEADERS = (\n 'x-requested-with',\n 'content-type',\n 'accept',\n 'origin',\n 'authorization',\n 'cache-control'\n)\n\n# Logging\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'verbose': {\n 'format': '[%(asctime)s] \"%(levelname)s %(module)s\" %(message)s',\n 'datefmt': '%d/%b/%Y %I:%M:%S'\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'console':{\n 'level':'DEBUG',\n 'class':'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n 'log_file': {\n 'level':'DEBUG',\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename': os.path.join(LOG_DIR, 'apps.log'),\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'apps': {\n 'handlers': ['mail_admins', 'log_file'],\n 'level': 'INFO',\n 'propagate': True,\n },\n }\n}\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'fourpoints',\n 'USER': 'root',\n 'PASSWORD': 'root',\n 'HOST': 'localhost',\n 'PORT': '3306',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\n#LANGUAGE_CODE = 'en-us'\nLANGUAGE_CODE = 'zh-CN'\n\nTIME_ZONE = 'Asia/Shanghai'\n\nUSE_I18N = False\nUSE_L10N = False\nUSE_TZ = False\n\nDATE_FORMAT = 'Y-m-d'\nTIME_FORMAT = 'H:i:s'\nDATETIME_FORMAT = 'Y-m-d H:i:s'\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n# URL that handles the media served from MEDIA_ROOT.\nMEDIA_URL = '/media/'\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n # Additional locations of static files\n os.path.join(BASE_DIR, 'staticfiles'),\n)\n\nTEMPLATE_DIRS = (\n # Always use forward slashes and absolute paths.\n os.path.join(BASE_DIR, 'templates'),\n)\n\n# Local settings\n\ntry:\n LOCAL_SETTINGS #@UndefinedVariable \nexcept NameError:\n try:\n from settings_local import * #@UnusedWildImport\n except ImportError:\n pass\n","sub_path":"fourpoints/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"424036776","text":"from django.conf.urls import url,include\nfrom .views import (\n\t\t\t\t\tMovieDetailView,\n\t\t\t\t\tMovieListView,\n\t\t\t\t\tMovieCreateView,\n\t\t\t\t\tMovieUpdateView,\n\t\t\t\t\tMovieDeleteView\n\t\t\t\t\t)\nfrom django.views.generic.base import RedirectView\n\nurlpatterns = [\n\turl(r'^$', RedirectView.as_view(url=\"/\")),\n\turl(r'^$', MovieListView, name='list'),\n url(r'^search/$', MovieListView,name='list'),\n url(r'^create/$', MovieCreateView.as_view(),name='create'),\n url(r'^(?P\\d+)/$', MovieDetailView.as_view(),name='detail'),\n url(r'^(?P\\d+)/update/$', MovieUpdateView.as_view(),name='update'),\n url(r'^(?P\\d+)/delete/$', MovieDeleteView.as_view(),name='delete'),\n]\n","sub_path":"src/movie/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"534885996","text":"# coding: utf-8\r\n\"\"\"\r\nBase para desarrollo de modulos externos.\r\nPara obtener el modulo/Funcion que se esta llamando:\r\n GetParams(\"module\")\r\n\r\nPara obtener las variables enviadas desde formulario/comando Rocketbot:\r\n var = GetParams(variable)\r\n Las \"variable\" se define en forms del archivo package.json\r\n\r\nPara modificar la variable de Rocketbot:\r\n SetVar(Variable_Rocketbot, \"dato\")\r\n\r\nPara obtener una variable de Rocketbot:\r\n var = GetVar(Variable_Rocketbot)\r\n\r\nPara obtener la Opcion seleccionada:\r\n opcion = GetParams(\"option\")\r\n\r\n\r\nPara instalar librerias se debe ingresar por terminal a la carpeta \"libs\"\r\n\r\n pip install -t .\r\n\r\n\"\"\"\r\nimport os.path\r\nimport sys\r\n\r\nbase_path = tmp_global_obj[\"basepath\"]\r\ncur_path = base_path + 'modules' + os.sep + 'Google-SpreadSheets' + os.sep + 'libs' + os.sep\r\n\r\ncur_path_x64 = os.path.join(cur_path, 'Windows' + os.sep + 'x64' + os.sep)\r\ncur_path_x86 = os.path.join(cur_path, 'Windows' + os.sep + 'x86' + os.sep)\r\n\r\nif cur_path_x64 not in sys.path and sys.maxsize > 2**32:\r\n sys.path.append(cur_path_x64)\r\nelif cur_path_x86 not in sys.path and sys.maxsize > 32:\r\n sys.path.append(cur_path_x86)\r\n\r\nfrom googleapiclient import discovery\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\nfrom openpyxl.utils.cell import get_column_letter\r\n\r\nimport traceback\r\nimport pickle\r\nimport re\r\n\r\n\"\"\"\r\n Obtengo el modulo que fueron invocados\r\n\"\"\"\r\nmodule = GetParams(\"module\")\r\n\r\nglobal creds\r\nglobal mod_gss_session\r\n\r\nsession = GetParams(\"session\")\r\nif not session:\r\n session = ''\r\n \r\ntry:\r\n if not mod_gss_session : #type:ignore\r\n mod_gss_session = {}\r\nexcept NameError:\r\n mod_gss_session = {}\r\n\r\nif module == \"GoogleSuite\":\r\n cred = None\r\n credential_path = GetParams(\"credentials_path\")\r\n\r\n if session == '':\r\n filename = \"token_spreadsheets.pickle\"\r\n else:\r\n filename = \"token_spreadsheets_{s}.pickle\".format(s=session)\r\n \r\n filename = os.path.join(base_path, filename)\r\n \r\n try:\r\n if not os.path.exists(credential_path):\r\n raise Exception(\r\n \"El archivo de credenciales no existe en la ruta especificada\")\r\n\r\n SCOPES = [\r\n 'https://www.googleapis.com/auth/spreadsheets',\r\n 'https://www.googleapis.com/auth/drive.file',\r\n 'https://www.googleapis.com/auth/drive',\r\n 'https://www.googleapis.com/auth/script.projects',\r\n 'https://www.googleapis.com/auth/script.external_request',\r\n 'https://www.googleapis.com/auth/drive.scripts'\r\n ]\r\n\r\n if os.path.exists(filename):\r\n with open(filename, 'rb') as token:\r\n cred = pickle.load(token)\r\n # If there are no (valid) credentials available, let the user log in.\r\n if not cred or not cred.valid:\r\n if cred and cred.expired and cred.refresh_token:\r\n cred.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n credential_path, SCOPES)\r\n cred = flow.run_local_server()\r\n # Save the credentials for the next run\r\n with open(filename, 'wb') as token:\r\n pickle.dump(cred, token)\r\n \r\n # global creds\r\n mod_gss_session[session] = cred\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif not mod_gss_session[session]:\r\n raise Exception(\"There's no credentials, nor valid token. Please, generate your credentials.\")\r\n\r\nif module == \"CreateSpreadSheet\":\r\n\r\n ss_name = GetParams('ss_name')\r\n result = GetParams('result')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n spreadsheet_body = {\r\n \"properties\": {\r\n \"title\": ss_name\r\n }\r\n }\r\n\r\n request = service.spreadsheets().create(body=spreadsheet_body)\r\n response = request.execute()\r\n if result:\r\n SetVar(result, response[\"spreadsheetId\"])\r\n \r\nif module == \"CreateSheet\":\r\n\r\n ss_id = GetParams('ss_id')\r\n name = GetParams('name')\r\n result = GetParams('result')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n body = {\r\n \"requests\": [\r\n {\r\n \"addSheet\": {\r\n \"properties\": {\r\n \"title\": name,\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\n if result:\r\n sheetId = response[\"replies\"][0][\"addSheet\"][\"properties\"][\"sheetId\"]\r\n SetVar(result, sheetId)\r\n\r\nif module == \"UpdateSheetProperties\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n newName = GetParams('newName')\r\n hidden = GetParams('hidden')\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n if not newName:\r\n newName = sheet\r\n \r\n if not hidden:\r\n hidden = False\r\n else:\r\n hidden = eval(hidden)\r\n \r\n body = {\r\n \"requests\": [\r\n {\r\n \"updateSheetProperties\": {\r\n \"properties\": {\r\n \"sheetId\": sheet_id,\r\n \"title\": newName,\r\n \"hidden\": hidden\r\n },\r\n \"fields\": \"title, hidden\",\r\n }\r\n }\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\nif module == \"DeleteSheet\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n \"requests\": [\r\n {\r\n \"deleteSheet\": {\r\n \"sheetId\": sheet_id\r\n }\r\n }\r\n\r\n ]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id,\r\n body=body)\r\n response = request.execute()\r\n\r\nif module == \"UpdateRange\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n text = GetParams('text')\r\n\r\n try:\r\n if not text.startswith(\"[\"):\r\n text = text.replace('\"', '\\\\\\\"')\r\n text = \"[[ \\\"{}\\\" ]]\".format(text)\r\n \r\n values = eval(text)\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n \"values\": values\r\n }\r\n \r\n request = service.spreadsheets().values().update(spreadsheetId=ss_id, range=range_,\r\n valueInputOption=\"USER_ENTERED\",\r\n body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\ndef get_column_index(col):\r\n try:\r\n abc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',\r\n 'v', 'w', 'x', 'y', 'z']\r\n around_abc = len(col) - 1\r\n \r\n col = col[-1].lower()\r\n col_index = around_abc * len(abc) + abc.index(col)\r\n return col_index\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"UpdateFormat\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n merge = GetParams('merge')\r\n unmerge = GetParams('unmerge')\r\n resize = GetParams('resize')\r\n number_format = GetParams('format') # select\r\n pattern = GetParams('pattern') # string\r\n \r\n foreground = GetParams('foreground') # touple\r\n font_family = GetParams('fontFamily') # string\r\n font_size = GetParams('fontSize') # int\r\n \r\n bold = GetParams('bold') # bool\r\n italic = GetParams('italic') # bool\r\n strikethrough = GetParams('strikethrough') # bool\r\n underline = GetParams('underline') # bool\r\n \r\n try:\r\n \r\n if \":\" in range_:\r\n range_\r\n else:\r\n range_ = range_ + \":\" + range_\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n regex = r\"([A-Z]+)([0-9]+):([A-Z]+)([0-9]+)\"\r\n range_re = re.findall(regex, range_)\r\n \r\n column_start = get_column_index(range_re[0][0])\r\n column_end = get_column_index(range_re[0][2]) + 1\r\n \r\n row_start = int(range_re[0][1]) - 1\r\n row_end = int(range_re[0][3]) \r\n \r\n body = {\r\n 'requests': [\r\n \r\n ]\r\n }\r\n \r\n if merge:\r\n if eval(merge) == True:\r\n\r\n merge_ = {\r\n \"mergeCells\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end\r\n },\r\n \"mergeType\": \"MERGE_ALL\"\r\n }\r\n }\r\n body['requests'].append(merge_)\r\n \r\n if unmerge:\r\n if eval(unmerge) == True:\r\n\r\n unmerge_ = {\r\n \"unmergeCells\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end\r\n }\r\n }\r\n }\r\n body['requests'].append(unmerge_)\r\n \r\n if resize:\r\n if eval(resize) == True: \r\n columms_ = {\r\n 'autoResizeDimensions':{\r\n 'dimensions': {\r\n 'sheetId': sheet_id,\r\n 'dimension': 'COLUMNS',\r\n 'startIndex': column_start,\r\n 'endIndex': column_end\r\n } \r\n } \r\n }\r\n body['requests'].append(columms_)\r\n\r\n rows_ = {\r\n 'autoResizeDimensions':{\r\n 'dimensions': {\r\n 'sheetId': sheet_id,\r\n 'dimension': 'ROWS',\r\n 'startIndex': row_start,\r\n 'endIndex': row_end \r\n } \r\n } \r\n }\r\n body['requests'].append(rows_)\r\n \r\n uef = {}\r\n fields = []\r\n \r\n if number_format != '':\r\n uef['numberFormat'] = {'type': number_format, 'pattern': ''} \r\n if pattern != '':\r\n uef['numberFormat']['pattern'] = pattern \r\n fields.append('numberFormat')\r\n \r\n if foreground:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n \r\n c = foreground.split(',')\r\n # To use RGB format, the API expects a proportion of each over the 255\r\n uef['textFormat'][\"foregroundColorStyle\"] = {\r\n \"rgbColor\": {\r\n \"red\": int(c[0])/255,\r\n \"green\": int(c[1])/255,\r\n \"blue\": int(c[2])/255,\r\n \"alpha\": 1\r\n }\r\n }\r\n \r\n if font_family != '':\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['fontFamily'] = font_family\r\n\r\n if font_size and eval(font_size) >0:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['fontSize'] = eval(font_size)\r\n \r\n if bold:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['bold'] = eval(bold)\r\n \r\n if italic:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['italic'] = eval(italic)\r\n \r\n if strikethrough:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['strikethrough'] = eval(strikethrough)\r\n \r\n if underline:\r\n if not uef.get('textFormat'):\r\n uef['textFormat'] = {}\r\n fields.append('textFormat')\r\n uef['textFormat']['underline'] = eval(underline)\r\n \r\n if fields != []:\r\n \r\n fields_ = ','.join(fields)\r\n \r\n cell_format= {\r\n 'repeatCell': {\r\n 'range': {\r\n \"sheetId\": sheet_id,\r\n 'startRowIndex': row_start,\r\n 'endRowIndex': row_end,\r\n 'startColumnIndex': column_start,\r\n 'endColumnIndex': column_end,\r\n },\r\n 'cell': {\r\n 'userEnteredFormat': uef\r\n },\r\n 'fields': f'userEnteredFormat({fields_})'\r\n }\r\n }\r\n \r\n body['requests'].append(cell_format)\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"ReadCells\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n result = GetParams('result')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n\r\n response = request.execute()\r\n try:\r\n value = response[\"values\"]\r\n except:\r\n value = \"\"\r\n\r\n if result:\r\n SetVar(result, value)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\n\r\nif module == \"copyPaste\":\r\n\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n range_ = GetParams('range')\r\n \r\n sheet2 = GetParams(\"sheetName2\")\r\n range_2 = GetParams('range2')\r\n \r\n type_ = GetParams('type')\r\n transponse = GetParams('transponse')\r\n cut = GetParams('cut')\r\n \r\n try:\r\n \r\n if \":\" in range_:\r\n range_\r\n else:\r\n range_ = range_ + \":\" + range_\r\n \r\n if \":\" in range_2:\r\n range_2 \r\n else:\r\n range_2 = range_2 + \":\" + range_2\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n if element[\"properties\"][\"title\"] == sheet2:\r\n sheet_id2 = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Source sheet could't be found...\")\r\n \r\n if not 'sheet_id2' in locals():\r\n raise Exception(\"Target sheet could't be found...\")\r\n \r\n regex = r\"([A-Z]+)([0-9]+):([A-Z]+)([0-9]+)\"\r\n # <----- Data Origin ----->\r\n range_re = re.findall(regex, range_)\r\n \r\n column_start = get_column_index(range_re[0][0])\r\n column_end = get_column_index(range_re[0][2]) + 1\r\n \r\n row_start = int(range_re[0][1]) - 1\r\n row_end = int(range_re[0][3]) \r\n \r\n # <----- Data Destination ----->\r\n range_re2 = re.findall(regex, range_2)\r\n \r\n column_start2 = get_column_index(range_re2[0][0])\r\n column_end2 = get_column_index(range_re2[0][2]) + 1\r\n \r\n row_start2 = int(range_re2[0][1]) - 1\r\n row_end2 = int(range_re2[0][3]) \r\n \r\n orientation = \"NORMAL\"\r\n if transponse:\r\n if eval(transponse) == True:\r\n orientation = 'TRANSPOSE'\r\n \r\n body = {\r\n 'requests': [\r\n ]\r\n }\r\n \r\n if not cut or eval(cut) == False:\r\n body['requests'] = {\r\n \"copyPaste\": {\r\n \"source\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end,\r\n },\r\n \"destination\": {\r\n \"sheetId\": sheet_id2,\r\n \"startRowIndex\": row_start2,\r\n \"endRowIndex\": row_end2,\r\n \"startColumnIndex\": column_start2,\r\n \"endColumnIndex\": column_end2,\r\n },\r\n \"pasteType\": type_,\r\n \"pasteOrientation\": orientation,\r\n }\r\n }\r\n else:\r\n body['requests'] = {\r\n \"cutPaste\": {\r\n \"source\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_start,\r\n \"endRowIndex\": row_end,\r\n \"startColumnIndex\": column_start,\r\n \"endColumnIndex\": column_end,\r\n },\r\n \"destination\": {\r\n \"sheetId\": sheet_id2,\r\n \"rowIndex\": row_start2,\r\n \"columnIndex\": column_start2,\r\n },\r\n \"pasteType\": type_,\r\n }\r\n }\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n \r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n \r\n\r\nif module == \"GetSheets\":\r\n ss_id = GetParams('ss_id')\r\n result = GetParams('result')\r\n \r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n request = service.spreadsheets().get(spreadsheetId=ss_id)\r\n response = request.execute()\r\n\r\n sheets = []\r\n for element in response[\"sheets\"]:\r\n sheets.append(element[\"properties\"][\"title\"])\r\n if result:\r\n SetVar(result, sheets)\r\n \r\nif module == \"CountCells\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams('sheetName')\r\n result = GetParams('result') # Here is saved the number of rows the command was originaly made for that.\r\n columns = GetParams('columns')\r\n \r\n range_ = \"A1:ZZZ999999\"\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n # Checks existence of the given sheet name and update the range\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n range_ = sheet + \"!\" + range_ # Sheet1!A1:A10\r\n \r\n if not 'range_' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n response = request.execute()\r\n\r\n length = len(response[\"values\"])\r\n \r\n width_aux = max([len(row) for row in response[\"values\"]])\r\n width = [width_aux, get_column_letter(width_aux)] # get_column_letter indexes begin with 1 (not 0)\r\n\r\n if result:\r\n SetVar(result, length)\r\n\r\n if columns:\r\n SetVar(columns, width)\r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"DeleteColumn\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams('column').lower()\r\n blank = GetParams('blank')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n sep = col.find(\":\")\r\n if sep == -1:\r\n col_index_1 = get_column_index(col)\r\n col_index_2 = col_index_1 + 1\r\n else: \r\n cols = col.split(\":\")\r\n col_index_1 = get_column_index(cols[0])\r\n col_index_2 = get_column_index(cols[1]) + 1\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank:\r\n shiftDimension = \"ROWS\"\r\n else:\r\n shiftDimension = \"COLUMNS\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"deleteRange\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startColumnIndex\": col_index_1,\r\n \"endColumnIndex\": col_index_2\r\n },\r\n \"shiftDimension\": shiftDimension\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"DeleteRow\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n row = GetParams('row')\r\n blank = GetParams('blank')\r\n\r\n try:\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n sep = row.find(\":\")\r\n if sep == -1:\r\n row_index_1 = int(row) - 1\r\n row_index_2 = int(row)\r\n else: \r\n rows = row.split(\":\")\r\n row_index_1 = int(rows[0])-1\r\n row_index_2 = int(rows[1])\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank:\r\n shiftDimension = \"COLUMNS\"\r\n else:\r\n shiftDimension = \"ROWS\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"deleteRange\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"startRowIndex\": row_index_1,\r\n \"endRowIndex\": row_index_2\r\n },\r\n \"shiftDimension\": shiftDimension\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"AddColumn\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams('column').lower()\r\n q = int(GetParams(\"q\"))\r\n blank = GetParams('blank')\r\n\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n\r\n col_index = get_column_index(col)\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n\r\n if blank == False or col_index == 0:\r\n inheritance = \"false\"\r\n else:\r\n inheritance = \"true\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"insertDimension\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"dimension\": \"COLUMNS\",\r\n \"startIndex\": col_index,\r\n \"endIndex\": col_index + q\r\n },\r\n \"inheritFromBefore\": inheritance\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"AddRow\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n row = int(GetParams('row'))\r\n q = int(GetParams(\"q\"))\r\n blank = GetParams('blank')\r\n \r\n try:\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n if blank is not None:\r\n blank = eval(blank)\r\n \r\n row_index = row - 1\r\n\r\n if blank == False or row_index == 0:\r\n inheritance = \"false\"\r\n else:\r\n inheritance = \"true\"\r\n\r\n body = {\r\n \"requests\": [{\r\n \"insertDimension\": {\r\n \"range\": {\r\n \"sheetId\": sheet_id,\r\n \"dimension\": \"ROWS\",\r\n \"startIndex\": row_index,\r\n \"endIndex\": row_index + q\r\n },\r\n \"inheritFromBefore\": inheritance\r\n }\r\n }]\r\n }\r\n\r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\ndef get_existing_basic_filters(ss_id, service, startRow=0, endRow=1000) -> dict:\r\n params = {'spreadsheetId': ss_id,\r\n 'fields': 'sheets(properties(sheetId,title),basicFilter)'}\r\n response = service.spreadsheets().get(**params).execute()\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n values_range = []\r\n for sheet in response['sheets']:\r\n if 'basicFilter' in sheet:\r\n values_range = list(sheet.values())[1]['range']\r\n # {'startRowIndex': startRow, 'endRowIndex': endRow, 'startColumnIndex': 4, 'endColumnIndex': 5}\r\n col = chr(values_range['startColumnIndex'] + 65)\r\n col = col + str(values_range['startRowIndex']+1) + \":\" + col + str(values_range['endRowIndex']+1)\r\n return col\r\n\r\ndef apply_filters(ss_id, filters, service):\r\n try:\r\n # All requests are validated before any are applied, so bundling the set and clear filter\r\n # operations in the same request would fail: only 1 basic filter can exist at a time.\r\n\r\n def clear_filters(ss_id, known_filters, service):\r\n requests = []\r\n for sheetId, filter in known_filters.items():\r\n requests.append({'clearBasicFilter': {'sheetId': sheetId}})\r\n if not requests:\r\n return\r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n service.spreadsheets().batchUpdate(**params).execute()\r\n\r\n def removekey(d, key):\r\n r = dict(d)\r\n del r[key]\r\n return r\r\n\r\n clear_filters(ss_id, filters, service)\r\n\r\n requests = []\r\n for sheetId, filter in filters.items():\r\n # By removing the starting and ending indices from the 'range' property,\r\n # we ensure the basicFilter will apply to the entire sheet bounds. If one knows the\r\n # desired values for startColumnIndex, startRowIndex, endRowIndex, endColumnIndex,\r\n # then they can be used to create a range-specific basic filter.\r\n # The 'range' property is a `GridRange`:\r\n if 'filterSpecs' not in filter:\r\n filter['filterSpecs'] = [{\r\n 'filterCriteria': {\r\n 'hiddenValues': []\r\n }\r\n }]\r\n requests.append({'setBasicFilter': {'filter': filter}})\r\n if not requests:\r\n return\r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n\r\n service.spreadsheets().batchUpdate(**params).execute()\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\ndef create_filter_structure(ranges, values, sheet_id):\r\n try:\r\n new_filter = {\r\n 'range': ranges\r\n }\r\n startColumnIndex = ranges['startColumnIndex']\r\n endColumnIndex = ranges['endColumnIndex']\r\n new_filter['filterSpecs'] = []\r\n for index in range(startColumnIndex, endColumnIndex):\r\n new_filter['filterSpecs'].append({\r\n 'columnIndex': index,\r\n 'filterCriteria': {\r\n 'hiddenValues': values\r\n }\r\n })\r\n new_filter_with_sheet_id = {\r\n sheet_id: new_filter\r\n }\r\n return new_filter_with_sheet_id\r\n except Exception as e:\r\n PrintException()\r\n raise e\r\n\r\nif module == \"unfilterData\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n if sheet == None or sheet == \"\":\r\n sheet_id = 0\r\n else:\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n requests = []\r\n requests.append({'clearBasicFilter': {'sheetId': sheet_id}})\r\n \r\n params = {'spreadsheetId': ss_id,\r\n 'body': {'requests': requests}}\r\n \r\n service.spreadsheets().batchUpdate(**params).execute() \r\n \r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"filterData\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n col = GetParams(\"col\").lower()\r\n valor_filtro = GetParams(\"valor_filtro\")\r\n try:\r\n col_index = get_column_index(col)\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n if sheet == None or sheet == \"\":\r\n sheet_id = 0\r\n else:\r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n\r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n range_ = sheet+\"!A:\"+col\r\n req = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_).execute()\r\n \r\n # It checks where the table that is going to be filtered starts and ends \r\n first_row = 0\r\n values = req[\"values\"]\r\n for cell in values:\r\n if cell == []:\r\n first_row += 1\r\n else:\r\n break\r\n last_row = len(req['values'])\r\n \r\n ranges = {\r\n \"sheetId\": sheet_id,\r\n 'startRowIndex': first_row,\r\n 'endRowIndex': last_row,\r\n 'startColumnIndex': col_index,\r\n 'endColumnIndex': col_index + 1,\r\n }\r\n \r\n hidden_values = []\r\n for row in values:\r\n # It appends a blank space to the list so the row is recognized as one in the following \"for\"\r\n if row == []:\r\n row.append(\"\")\r\n for cell in row:\r\n if valor_filtro != cell:\r\n hidden_values.append(cell)\r\n \r\n filters = create_filter_structure(ranges, hidden_values, sheet_id)\r\n apply_filters(ss_id, filters, service)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n\r\nif module == \"filterCells\":\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n res = GetParams(\"res\")\r\n range = GetParams(\"range_\")\r\n row_info = GetParams(\"row_info\")\r\n \r\n try:\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n \r\n data_ = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data_[\"sheets\"]:\r\n if sheet == None or sheet == \"\":\r\n sheet = data_[\"sheets\"][0][\"properties\"][\"title\"]\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n filter_start = element[\"basicFilter\"][\"range\"][\"startRowIndex\"]\r\n \r\n data = service.spreadsheets().get(spreadsheetId=ss_id, fields=\"sheets(data(rowMetadata(hiddenByFilter)),properties/sheetId)\").execute()\r\n\r\n #column_filter = get_existing_basic_filters(ss_id, service)\r\n list_hidden_rows = []\r\n for column in data['sheets']:\r\n if column['properties']['sheetId'] == sheet_id:\r\n for index, item in enumerate(column['data'][0]['rowMetadata']):\r\n if bool(item):\r\n list_hidden_rows.append(index)\r\n \r\n # It makes sure that always start from the first row of the filter, so the row index vs hidden rows can be done\r\n range_first_row = range[1]\r\n \r\n if range_first_row != filter_start:\r\n tmp = list(range)\r\n tmp[1] = filter_start + 1\r\n \r\n range = \"\".join(str(x) for x in tmp)\r\n \r\n \r\n range_ = sheet + \"!\" + range\r\n request = service.spreadsheets().values().get(spreadsheetId=ss_id, range=range_)\r\n response = request.execute()\r\n value = response[\"values\"]\r\n \r\n final_cells = []\r\n final_cells_row = {}\r\n for row_index, item in enumerate(value):\r\n row_index = (row_index + filter_start)\r\n if row_info and eval(row_info) == True:\r\n if row_index not in list_hidden_rows:\r\n final_cells_row[row_index+1] = item \r\n SetVar(res, final_cells_row)\r\n else:\r\n if row_index not in list_hidden_rows:\r\n final_cells.append(item) \r\n SetVar(res, final_cells)\r\n except Exception as e:\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n \r\nif module == \"CopySheet\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n ss_id_2 = GetParams('ss_id_2')\r\n result = GetParams('res')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n 'destination_spreadsheet_id': ss_id_2\r\n }\r\n \r\n request = service.spreadsheets().sheets().copyTo(spreadsheetId=ss_id, sheetId=sheet_id, body=body)\r\n response = request.execute()\r\n\r\n SetVar(res, True)\r\n except Exception as e:\r\n SetVar(res, False)\r\n traceback.print_exc()\r\n PrintException()\r\n raise e\r\n \r\nif module == \"TextToColumns\":\r\n try:\r\n ss_id = GetParams('ss_id')\r\n sheet = GetParams(\"sheetName\")\r\n separator = GetParams('separator')\r\n result = GetParams('res')\r\n\r\n service = discovery.build('sheets', 'v4', credentials=mod_gss_session[session])\r\n\r\n data = service.spreadsheets().get(spreadsheetId=ss_id).execute()\r\n \r\n for element in data[\"sheets\"]:\r\n if element[\"properties\"][\"title\"] == sheet:\r\n sheet_id = element[\"properties\"][\"sheetId\"]\r\n \r\n if not 'sheet_id' in locals():\r\n raise Exception(\"Sheet could't be found...\")\r\n \r\n body = {\r\n 'requests':[\r\n {\r\n 'textToColumns': {\r\n 'source': {\r\n 'sheetId': sheet_id,\r\n 'startColumnIndex': 0,\r\n 'endColumnIndex': 1\r\n },\r\n 'delimiterType': separator\r\n }\r\n }\r\n ]\r\n }\r\n \r\n request = service.spreadsheets().batchUpdate(spreadsheetId=ss_id, body=body)\r\n response = request.execute()\r\n\r\n SetVar(res, True)\r\n except Exception as e:\r\n SetVar(res, False)\r\n PrintException()\r\n raise e","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":41533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"357852248","text":"from .models import *\nfrom django.shortcuts import render\nfrom django.views.generic import DetailView\nfrom django.template import Template\nfrom django.template.response import TemplateResponse\n\nclass PageDetail(DetailView):\n queryset = Page.objects.filter(is_published=True)\n \n def get_context_data(self, **kwargs):\n page = self.get_object()\n for block in page.template_set.all()[0].block_set.all():\n kwargs[block.title] = block\n\n js = StaticContent.objects.filter(page=page, type='js')\n kwargs['js'] = js\n css = StaticContent.objects.filter(page=page, type='css')\n kwargs['css'] = css\n menus = Menu.objects.filter(template=page.template_set.all()[0])\n kwargs['menus'] = menus\n \n plugins = PluginBase.objects.filter(page=page)\n if plugins:\n for plugin in plugins: \n plugin.rendered = plugin.render(self.request, **kwargs)\n plugin.save()\n\n return super(PageDetail, self).get_context_data(**kwargs)\n \n def render_to_response(self, context, **response_kwargs):\n tempdata = self.get_object().template_set.all()[0].template_data\n template = Template(tempdata)\n return TemplateResponse(self.request, template, context)\n\n\n","sub_path":"cmsapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"457629643","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.colors import ListedColormap\nimport mstools.helpers.MSILibs as msi\n\n\ndef plot_sorted_snrs_from_dict(snr_d):\n \"\"\"\n Plots sorted SNR plots (with subplots)\n \"\"\"\n length = len(snr_d.keys())\n plt.figure(figsize=(10, 5))\n for i, key in enumerate(snr_d.keys()):\n plt.subplot(1, length, i+1)\n sorted_snr = sorted(snr_d[key])\n plt.title(str(key))\n plt.plot(sorted_snr)\n\n\ndef plot3D(x, y, color_map=ListedColormap(['red', 'orange', 'blue']), x_rot=0, y_rot=70):\n \"\"\"\n Plots basic 3D representation of the data\n \"\"\"\n fig = plt.figure(figsize=(14, 10))\n ax = Axes3D(fig)\n ax.view_init(x_rot, y_rot)\n ax.scatter(x.iloc[:, 0], x.iloc[:, 1], x.iloc[:, 2], c=y, cmap=color_map)\n\n\ndef visualize_on_specimen(x, index, s=1):\n y = msi.load_labels('static/Y.h5')\n x_placeholder = pd.DataFrame(np.zeros((y.shape[0], x.shape[1])))\n x_placeholder.update(x)\n plt.scatter(y['x'].values, y['y'].values, c=x_placeholder.iloc[:, index], s=s)\n","sub_path":"mstools/utils/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"73307142","text":"import webapp2\nimport jinja2\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\nimport os\nfrom datetime import datetime\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True\n)\n\nclass Incomplete(webapp2.RequestHandler):\n def post(self):\n taskboardName = self.request.get('taskBoarddata')\n email = self.request.get('email')\n unique = taskboardName+\"\"+email\n taskTitleName = self.request.get('IncompleteButton')\n taskdata = ndb.Key('taskdata', unique).get()\n for i in range(0,len(taskdata.Title)):\n if taskdata.Title[i] == taskTitleName:\n taskdata.Task_Completion[i] = \"Not Complete\"\n taskdata.Date[i] = \"Not Complete\"\n taskdata.Time[i] = \"Not Complete\"\n taskdata.put()\n self.redirect('/invite?taskBoarddata='+taskboardName+'&email='+email)\n\napp = webapp2.WSGIApplication([\n ('/Incomplete',Incomplete)\n], debug=True)\n","sub_path":"Incomplete.py","file_name":"Incomplete.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"175981371","text":"# This file is part of REANA.\n# Copyright (C) 2022, 2023 CERN.\n#\n# REANA is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\"\"\"Utilities to manage files in a workspace.\"\"\"\n\nimport errno\nimport os\nimport re\nimport stat\nfrom pathlib import Path\nfrom typing import Generator, Union\n\nimport wcmatch.glob\n\nfrom reana_commons.errors import REANAWorkspaceError\n\n# O_NOFOLLOW: do not follow symlinks\n# O_NONBLOCK: do not block when opening special files (e.g. pipes)\nSAFE_FLAGS = os.O_NOFOLLOW | os.O_NONBLOCK\n\"\"\"Flags needed to open a fd without following symlinks.\"\"\"\n\nREAD_SAFE_FLAGS = os.O_RDONLY | SAFE_FLAGS\n\"\"\"Flags to open a fd in read-only mode without following symlinks.\"\"\"\n\nPathLike = Union[str, Path]\n\n\ndef _validate_path_component(component: str) -> None:\n \"\"\"Check that a component of a path is valid.\"\"\"\n if (\n not component\n or os.sep in component\n or os.path.sep in component\n or component in [\".\", \"..\"]\n ):\n raise REANAWorkspaceError(f\"'{component}' is not a valid path component\")\n\n\ndef _open_single_component(name: str, dir_fd: int, flags: int = READ_SAFE_FLAGS) -> int:\n \"\"\"Open a file contained in a directory.\"\"\"\n _validate_path_component(name)\n try:\n fd = os.open(name, flags | SAFE_FLAGS, dir_fd=dir_fd)\n except OSError as e:\n if e.errno == errno.ELOOP:\n raise REANAWorkspaceError(f\"Opening symlink '{name}' is not allowed\")\n raise\n return fd\n\n\ndef open_fd(workspace: PathLike, path: PathLike, flags=READ_SAFE_FLAGS) -> int:\n \"\"\"Open a fd inside a workspace.\"\"\"\n path = Path(path)\n fd = os.open(workspace, READ_SAFE_FLAGS)\n for i, part in enumerate(path.parts):\n # parent directories are always opened in read-only mode\n curr_flags = READ_SAFE_FLAGS\n if i + 1 == len(path.parts):\n # the last component of the path is opened with the provided flags\n curr_flags = flags\n try:\n new_fd = _open_single_component(part, dir_fd=fd, flags=curr_flags)\n finally:\n os.close(fd)\n fd = new_fd\n return fd\n\n\ndef open_file(workspace: PathLike, path: PathLike, mode: str = \"r\"):\n \"\"\"Open a file inside a workspace.\"\"\"\n\n def opener(path, flags):\n fd = open_fd(workspace, path, flags)\n st_mode = os.fstat(fd).st_mode\n if not stat.S_ISREG(st_mode):\n os.close(fd)\n raise REANAWorkspaceError(f\"'{path}' is not a regular file\")\n return fd\n\n return open(path, mode=mode, opener=opener)\n\n\ndef delete(workspace: PathLike, path: PathLike) -> int:\n \"\"\"Delete a file or an empty directory inside a workspace.\"\"\"\n path = Path(path)\n parent_fd = open_fd(workspace, path.parent)\n try:\n st = os.lstat(path.name, dir_fd=parent_fd)\n st_mode = st.st_mode\n st_size = st.st_size\n if stat.S_ISREG(st_mode) or stat.S_ISLNK(st_mode):\n os.unlink(path.name, dir_fd=parent_fd)\n elif stat.S_ISDIR(st_mode):\n os.rmdir(path.name, dir_fd=parent_fd)\n else:\n raise REANAWorkspaceError(f\"'{path}' should be a file or a directory\")\n finally:\n os.close(parent_fd)\n return st_size\n\n\ndef move(workspace: PathLike, src: PathLike, dst: PathLike) -> None:\n \"\"\"Move the file or directory `src` to `dst`.\"\"\"\n src = Path(src)\n dst = Path(dst)\n\n # If `dst` already exists and it is a directory, we move `src` inside it\n if is_directory(workspace, dst):\n dst_fd = open_fd(workspace, dst)\n dst_name = src.name\n else:\n dst_fd = open_fd(workspace, dst.parent)\n dst_name = dst.name\n\n src_fd = None\n try:\n src_fd = open_fd(workspace, src.parent)\n os.replace(src.name, dst_name, src_dir_fd=src_fd, dst_dir_fd=dst_fd)\n finally:\n if src_fd is not None:\n os.close(src_fd)\n if dst_fd is not None:\n os.close(dst_fd)\n\n\ndef lstat(workspace: PathLike, path: PathLike) -> os.stat_result:\n \"\"\"Get the stat of a file inside a workspace.\"\"\"\n path = Path(path)\n dir_fd = open_fd(workspace, path.parent)\n try:\n st = os.lstat(path.name, dir_fd=dir_fd)\n finally:\n os.close(dir_fd)\n return st\n\n\ndef makedirs(workspace: PathLike, path: PathLike) -> None:\n \"\"\"Recursively create directories inside a workspace.\"\"\"\n path = Path(path)\n fd = os.open(workspace, READ_SAFE_FLAGS)\n for part in path.parts:\n try:\n _validate_path_component(part)\n try:\n os.mkdir(part, dir_fd=fd)\n except FileExistsError:\n pass\n new_fd = _open_single_component(part, dir_fd=fd)\n # TODO: check this is actually a directory?\n finally:\n os.close(fd)\n fd = new_fd\n os.close(fd)\n\n\ndef is_directory(workspace: PathLike, path: PathLike) -> bool:\n \"\"\"Check whether a path refers to a directory.\"\"\"\n try:\n st = lstat(workspace, path)\n if stat.S_ISDIR(st.st_mode):\n return True\n except Exception:\n pass\n return False\n\n\ndef walk(\n workspace: PathLike,\n path: PathLike = \"\",\n topdown: bool = True,\n include_dirs: bool = True,\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries inside a workspace.\"\"\"\n root_fd = open_fd(workspace, path)\n path = Path(path)\n try:\n for dirpath, dirnames, filenames, dirfd in os.fwalk(\n dir_fd=root_fd, topdown=topdown\n ):\n for dirname in dirnames:\n if include_dirs or stat.S_ISLNK(\n os.lstat(dirname, dir_fd=dirfd).st_mode\n ):\n yield str(path.joinpath(dirpath, dirname))\n for filename in filenames:\n yield str(path.joinpath(dirpath, filename))\n finally:\n os.close(root_fd)\n\n\ndef iterdir(workspace: PathLike, path: PathLike) -> Generator[str, None, None]:\n \"\"\"Iterate over the contents of a directory.\"\"\"\n dir_fd = open_fd(workspace, path)\n path = Path(path)\n try:\n for filename in os.listdir(dir_fd):\n yield str(path / filename)\n finally:\n os.close(dir_fd)\n\n\ndef glob(\n workspace: PathLike, pattern: str, topdown: bool = True, include_dirs: bool = True\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries in a workspace that match a given pattern.\"\"\"\n # `wcmatch` returns two lists of regexps, one for \"include\" and the other\n # for \"exclude\" patterns. We are only interested in the \"include\" patterns.\n include_regex, exclude_regex = wcmatch.glob.translate(\n pattern, flags=wcmatch.glob.GLOBSTAR | wcmatch.glob.DOTGLOB\n )\n if len(include_regex) != 1 or len(exclude_regex) != 0:\n raise REANAWorkspaceError(\"The provided pattern is not valid\")\n compiled_regex = re.compile(include_regex.pop())\n for filepath in walk(workspace, topdown=topdown, include_dirs=include_dirs):\n if compiled_regex.match(filepath):\n yield filepath\n\n\ndef glob_or_walk_directory(\n workspace: PathLike,\n path_or_pattern: str,\n topdown: bool = True,\n include_dirs: bool = True,\n) -> Generator[str, None, None]:\n \"\"\"Get the list of entries inside a directory or that match a given pattern.\"\"\"\n if is_directory(workspace, path_or_pattern):\n yield from walk(workspace, path_or_pattern, topdown, include_dirs)\n else:\n yield from glob(workspace, path_or_pattern, topdown, include_dirs)\n","sub_path":"reana_commons/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"395674888","text":"from lxml import etree\nimport ConfigParser, os, re\n\nsettings = ConfigParser.ConfigParser()\n\nif os.path.split(os.getcwd())[-1] == 'lib':\n settings.read('../conf/assessment.conf')\nelse:\n settings.read('conf/assessment.conf')\n\ndef evaluateReport(report_file):\n alerts = []\n ports = settings.get('NMAP_TEST', 'Ports').split(', ')\n report = etree.parse(report_file)\n for port in ports:\n find_text = etree.XPath( \"/SECANT/NMAP_TEST/ports/port[contains(@portid, \" + port + \")]\")\n if find_text(report):\n alerts.append(\"Port \" + port + \" is open\")\n return alerts","sub_path":"external_tests/ntp_amplification_test/ntp_amplification_test.py","file_name":"ntp_amplification_test.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"639882264","text":"\"\"\" Alice (localhost) \"\"\"\nimport socket, pickle, random\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization, asymmetric\nfrom lib.MyCryptoLibrary import MyCryptoLibrary\n\n\n# Key generation\nalice_private_key = asymmetric.rsa.generate_private_key(\n public_exponent=65537,\n key_size=2048,\n backend=default_backend())\n\n# Assuming that Bob has Alice's PK, thus saving it as PEM format at Bob's PC.\nalice_key_pem = alice_private_key.public_key().public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyInfo)\n\nwith open(\"PK_alice.pem\", \"wb\") as key:\n key.write(alice_key_pem)\n\n\ndef retrieve_bobs_pk():\n with open(\"PK_bob.pem\", \"rb\") as pem_file:\n PK = serialization.load_pem_public_key(\n pem_file.read(),\n backend=default_backend())\n return PK\n\n\ndef decrypt_and_verify(data, PK):\n decrypted_message = MyCryptoLibrary.decrypt_message(data[0], alice_private_key)\n MyCryptoLibrary.verify_message(decrypted_message, data[1], PK)\n return decrypted_message\n\n\ndef send_encrypted_signed_message(msg, PK):\n cipher_text = MyCryptoLibrary.encrypt_message(msg, PK)\n signature_alice = MyCryptoLibrary.sign_message(msg, alice_private_key)\n data = (cipher_text, signature_alice)\n data_string = pickle.dumps(data)\n server.send(data_string)\n\n\ndef compute_dice_throw(a, b):\n dice_throw = bin(int(a) ^ int(b))\n converted_dice_throw = (int(dice_throw, 2) % 6) + 1\n print(\"Alice computes throw to be \", converted_dice_throw)\n return converted_dice_throw\n\n\n# TCP with ipv4\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = \"127.0.0.1\"; port = 6677\naddress = (host, port)\n\n# Connect to address\nserver.connect(address)\nrunning = True\nprint(f\"[Connected to {host} at port {port}]\")\n\n\nwhile running:\n # Get prerequisites\n PK_bob = retrieve_bobs_pk()\n\n print(\"********* Alice's dice throw *********\")\n\n # [a1] Alice samples random bit a and random 128 bit string and sends Com(a,r)\n a1 = '1001' # Alice not honest!!!!!!!!!!!!!!!!\n r1 = format(random.getrandbits(128), \"b\")\n c1 = bytes(a1 + r1, encoding=\"utf-8\")\n c_hashed1 = MyCryptoLibrary.hash_message(c1)\n send_encrypted_signed_message(c_hashed1, PK_bob)\n print(\"Sending encrypted Com(a,r) to Bob\")\n\n # [a2] Message b received\n received_data = pickle.loads(server.recv(2048))\n print(\"Alice received b from Bob and tries to verify\")\n b1 = decrypt_and_verify(received_data, PK_bob)\n\n # [a3] Alice sends (a,r) to Bob\n a_r = bytes(a1 + \",\" + r1, encoding=\"utf-8\")\n send_encrypted_signed_message(a_r, PK_bob)\n\n # [a4] Compute output a XOR b under mod 6\n compute_dice_throw(a1, b1)\n\n print()\n print(\"********* Bob's dice throw *********\")\n\n # [a1] Message Com(a,r) received from Bob\n received_data2 = pickle.loads(server.recv(2048))\n print(\"Bob received Com(a,r) from Alice and tries to verify\")\n decrypted_hashed_c_from_bob = decrypt_and_verify(received_data2, PK_bob)\n\n # [a2] Alice sends random bit a to Bob\n a2 = bytes(format(random.getrandbits(4), \"b\"), encoding=\"utf-8\")\n send_encrypted_signed_message(a2, PK_bob)\n\n # [a3] Receive second message (a,r) from Bob\n received_data3 = pickle.loads((server.recv(2048)))\n print(\"Alice received (a,r) from Bob and tries to verify\")\n decrypted_b_r = decrypt_and_verify(received_data3, PK_bob)\n decoded_split_b_r = decrypted_b_r.decode(\"utf-8\").split(\",\")\n bob_b2 = decoded_split_b_r[0]\n opened_commitment = bytes(decoded_split_b_r[0] + decoded_split_b_r[1], \"utf-8\")\n\n # [a4] Alice is hashing a + r for checking and computing dice throw\n opened_commitment_hashed = MyCryptoLibrary.hash_message(opened_commitment)\n\n if decrypted_hashed_c_from_bob == opened_commitment_hashed:\n print(\"Alice is checking if the hashes match\")\n print(\"[Success] No changes we made to the message\")\n bob_b = decoded_split_b_r[0]\n alice_a = a2.decode(\"utf-8\")\n compute_dice_throw(alice_a, bob_b)\n else:\n print(\"[WARNING] Bob changed his message\")\n\n running = False\n\nserver.close()\n","sub_path":"alice_local.py","file_name":"alice_local.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"441091489","text":"from flask import Flask, render_template, request\n\nfrom mbta_helper import find_stop_near\n\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef calculate():\n if request.method == 'POST':\n Location = request.form['location']\n Near_stop,wheelchair = find_stop_near(Location)\n # Country Code = float(request.form['country code'])\n # we want results from api\n if Near_stop and wheelchair:\n return render_template('mbta_result.html',location=Location,near_stop=Near_stop,wheelchair=wheelchair)\n else:\n return render_template('mbta_form.html',error=True)\n return render_template('mbta_form.html', error=None)\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"176039889","text":"'''*************************************************************\nFileName [exp_clp_tl.py]\nProjectName [Threshold logic synthesis and verification.]\nSynopsis [Script for collapsing TL circuits experiments.]\nAuthor [Nian-Ze Lee]\nAffiliation [NTU]\nDate [16.01.2020]\n*******************************************************************'''\n\nimport os\nimport glob\nimport argparse\nimport subprocess as sp\nparser = argparse.ArgumentParser( description = \"Parsing collapsing TL circuits experimental settings ...\" )\nparser.add_argument( \"-i\", action=\"store_true\", dest=\"ite\", default=False, help=\"enabling iterative collapsing (default=False)\" )\nparser.add_argument( \"-t\", action=\"store_true\", dest=\"tcad\", default=False, help=\"enabling TCAD suggestion (default=False)\" )\nargs = parser.parse_args()\nopt1 = \" -B 100\" if args.ite else \"\"\nopt2 = \" -t\" if args.tcad else \"\"\nsyn = \"tl_syn; mt\" + opt1 + opt2 + \"; pt; q\"\nsuf1 = \"_i\" if args.ite else \"\"\nsuf2 = \"_t\" if args.tcad else \"\"\nsuf = suf1 + suf2\nfor bch in glob.glob(\"exp_TCAD/collapse/benchmark/iscas_itc/*.blif\"):\n name = os.path.basename(bch)\n log = (\"exp_TCAD/collapse/log/%s_tl%s.log\" % (name, suf))\n tcl = \"r \" + bch + \"; \" + syn\n cmd = \"bin/abc -c \\\"\" + tcl + \"\\\" &> \" + log\n sp.run(cmd, shell=True)\n","sub_path":"exp_TCAD/collapse/script/exp_clp_tl.py","file_name":"exp_clp_tl.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"558514672","text":"import sys\nimport numpy as np\nsys.path.append(\"..\")\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom Vgg19 import Vgg19\n\nbatch_norm = tf.layers.batch_normalization \nvgg_file_path = '/home/cgim/桌面/tensorflow_train/GAN/vgg19.npy'\nclass SRGAN:\n def __init__(self,is_training,vgg_weight):\n self.is_training = is_training\n self.epsilon = 1e-5\n self.weight_decay = 0.00001\n self.vgg_weight = vgg_weight\n self.REAL_LABEL=0.9\n\n def preprocess(self,images,scale=False):\n images = tf.to_float(images)\n if scale:\n images = tf.div(images, 127.5)\n images = tf.subtract(images, 1.0)\n return images\n\n def sample(self, input, type=\"down\",sample_size=4):\n shape = input.get_shape().as_list() # NHWC\n if (type == \"down\"):\n h = int(shape[1] // sample_size)\n w = int(shape[1] // sample_size)\n else:\n h = int(shape[1] * sample_size)\n w = int(shape[1] * sample_size)\n resized_image = tf.image.resize_images(input, [h, w],\n tf.image.ResizeMethod.BILINEAR)\n return resized_image\n\n def Resblock(self,inputs,scope_name):\n with tf.variable_scope(scope_name+\"/layer1\") as scope:\n conv1 = slim.conv2d(inputs,64,[3,3],[1,1])\n norm1 = slim.batch_norm(conv1)\n relu1 = tf.nn.relu(norm1)\n with tf.variable_scope(scope_name+\"/layer2\") as scope:\n conv2 = slim.conv2d(relu1,64,[3,3],[1,1])\n norm2 = slim.batch_norm(conv2)\n return inputs+norm2\n\n def get_content_loss(self,feature_a,feature_b,type=\"VGG\"):\n if type==\"VGG\":\n print(\"Using VGG loss as content loss!\")\n vgg_a, vgg_b = Vgg19(vgg_file_path), Vgg19(vgg_file_path)\n vgg_a.build(feature_a)\n vgg_b.build(feature_b)\n VGG_loss = tf.reduce_mean(tf.losses.absolute_difference(vgg_a.conv4_4, vgg_b.conv4_4))\n h = tf.cast(tf.shape(vgg_a.conv4_4)[1], tf.float32)\n w = tf.cast(tf.shape(vgg_a.conv4_4)[2], tf.float32)\n c = tf.cast(tf.shape(vgg_a.conv4_4)[3], tf.float32)\n content_loss = VGG_loss/(h*w*c)\n else:\n print(\"Using MSE loss of images as content loss!\")\n content_loss=tf.reduce_mean(tf.losses.absolute_difference(feature_a , feature_b))\n return content_loss\n\n def pixel_shuffle_layer(self,x, r, n_split):\n def PS(x, r):\n bs, a, b, c = x.get_shape().as_list()\n x = tf.reshape(x, (-1, a, b, r, r))\n x = tf.transpose(x, [0, 1, 2, 4, 3])\n x = tf.split(x, a, 1)\n x = tf.concat([tf.squeeze(x_) for x_ in x], 2)\n x = tf.split(x, b, 1)\n x = tf.concat([tf.squeeze(x_) for x_ in x], 2)\n return tf.reshape(x, (-1, a * r, b * r, 1))\n xc = tf.split(x, n_split, 3)\n return tf.concat([PS(x_, r) for x_ in xc], 3)\n\n #(64*64--->256*256)\n def generator(self,inputs,name_scope,reuse=False):\n print(\"SRGAN_onlyMSE_generator\")\n with tf.variable_scope(name_scope,reuse=reuse) as scope:\n w_init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n with slim.arg_scope([slim.conv2d],weights_initializer=w_init,padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.conv2d_transpose],weights_initializer=w_init,padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.batch_norm], decay=0.9, epsilon=1e-5, scale=True,\n activation_fn=None,is_training=self.is_training):\n print(\"inputs:\",inputs)\n net = slim.conv2d(inputs,64,[3,3],[1,1])\n net = tf.nn.relu(net)\n\n short_cut = net\n print(\"net1:\", net)\n #8 Resblock\n for i in range(6):\n net = self.Resblock(net, \"ResBlock{}\".format(i))\n \n #DeConv\n net = slim.conv2d_transpose(net, 64, [3,3], [1,1])\n net = slim.batch_norm(net)\n net = net+short_cut\n\n print(\"net2:\",net)\n net = slim.conv2d_transpose(net, 256, [3, 3], [1, 1])\n print(\"net3:\",net)\n net = self.pixel_shuffle_layer(net, 2, 64)\n net = tf.nn.relu(net)\n print(\"net4:\",net)\n net = slim.conv2d_transpose(net, 256, [3, 3], [1, 1])\n print(\"net5:\",net)\n net = self.pixel_shuffle_layer(net, 2, 64)\n net = tf.nn.relu(net)\n\n net = slim.conv2d(net, 3, [3, 3], [1, 1],activation_fn=tf.nn.tanh)\n return net\n\n # (256*256--->1)\n def discriminator(self,inputs,name_scope,reuse=False):\n print(\"SRGAN_onlyMSE_discriminator\")\n with tf.variable_scope(name_scope,reuse=reuse) as scope:\n w_init = tf.truncated_normal_initializer(mean=0.0, stddev=0.02)\n with slim.arg_scope([slim.conv2d], weights_initializer=w_init, padding=\"SAME\", activation_fn=None):\n with slim.arg_scope([slim.conv2d_transpose], weights_initializer=w_init, padding=\"SAME\",activation_fn=None):\n with slim.arg_scope([slim.batch_norm], decay=0.9, epsilon=1e-5, scale=True,activation_fn=None,is_training=self.is_training):\n nfg = 64\n net = slim.conv2d(inputs,nfg,[3,3],[1,1])\n net = tf.nn.leaky_relu(net)\n print(\"net:\",net)\n\n for i in range(1,5):\n net = slim.conv2d(net, nfg, [3, 3], [2, 2])\n net = slim.batch_norm(net)\n net = tf.nn.leaky_relu(net)\n\n net = slim.conv2d(net, nfg*2, [3, 3], [1, 1])\n net = slim.batch_norm(net)\n net = tf.nn.leaky_relu(net)\n nfg *= 2\n print(\"dis{}:\".format(i),net)\n\n net = slim.conv2d(net, nfg, [3, 3], [2, 2])\n net = slim.batch_norm(net)\n logits = tf.nn.leaky_relu(net)\n\n net_flat = tf.layers.flatten(net)\n dense_net = slim.fully_connected(net_flat,1024)\n dense_net = tf.nn.leaky_relu(dense_net)\n logits = slim.fully_connected(dense_net, 1)\n return logits\n\n def get_vars(self):\n all_vars = tf.trainable_variables()\n dis_vars = [var for var in all_vars if 'discriminator' in var.name]\n gen_vars = [var for var in all_vars if 'generator' in var.name]\n \n return gen_vars,dis_vars\n\n def build_CartoonGAN(self,LR,HR):\n #归一化\n LR_pre = self.preprocess(LR, scale=True)\n HR_pre = self.preprocess(HR, scale=True)\n\n #reality --> cartoon\n fake_HR = self.generator(LR_pre,\"generator\")\n\n fake_HR_logits = self.discriminator(fake_HR, \"discriminator\", reuse=False)\n real_HR_logits = self.discriminator(HR_pre, \"discriminator\", reuse=True)\n\n #GAN损失\n real_dis_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=real_HR_logits,labels=tf.ones_like(real_HR_logits)))\n fake_dis_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=fake_HR_logits,labels=tf.zeros_like(fake_HR_logits)))\n fake_gen_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n logits=fake_HR_logits,labels=tf.ones_like(fake_HR_logits)))\n dis_loss = real_dis_loss+fake_dis_loss\n\n print(\"size:\",HR_pre,fake_HR)\n content_loss = self.get_content_loss(HR_pre, fake_HR,\"no_VGG\")\n psnr = self.get_PSNR(HR_pre,fake_HR)\n gen_loss = fake_gen_loss + self.vgg_weight*content_loss\n\n return gen_loss,dis_loss,content_loss,psnr\n\n def get_PSNR(self,real, fake):\n mse = tf.reduce_mean(tf.square(127.5 * (real - fake) + 127.5), axis=(-3, -2, -1))\n psnr = tf.reduce_mean(10 * (tf.log(255 * 255 / tf.sqrt(mse)) / np.log(10)))\n return psnr\n def sample_generate(self,LR):\n LR_pre = self.preprocess(LR, scale=True)\n HR_out = self.generator(LR_pre,name_scope=\"generator\",reuse=True)\n return HR_out\n\n\n\n","sub_path":"GANs_Advanced/SRGAN/net/SRGAN_onlyMSE.py","file_name":"SRGAN_onlyMSE.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"388604599","text":"import sys\nimport os\nimport logging\nimport logging.handlers\nfrom common.variables import LOGGING_LEVEL\nsys.path.append('../')\n\n\nFORMATTER_FOR_CLIENT = logging.Formatter(\n '%(asctime)-27s %(levelname)-10s %(filename)-23s %(message)s')\n\nPATH = os.path.dirname(os.path.abspath(__file__))\nPATH = os.path.join(os.path.split(PATH)[0], r'files\\client.log')\n\n# создаём потоки вывода логов\nSTREAM_HANDLER = logging.StreamHandler(sys.stderr)\nSTREAM_HANDLER.setFormatter(FORMATTER_FOR_CLIENT)\nSTREAM_HANDLER.setLevel(logging.ERROR)\n\nLOG_FILE = logging.FileHandler(PATH, encoding='utf8')\nLOG_FILE.setFormatter(FORMATTER_FOR_CLIENT)\n\n# создаём регистратор и настраиваем его\nLOG_CLIENT = logging.getLogger('client')\nLOG_CLIENT.addHandler(STREAM_HANDLER)\nLOG_CLIENT.addHandler(LOG_FILE)\nLOG_CLIENT.setLevel(LOGGING_LEVEL)\n\n# отладка\nif __name__ == '__main__':\n LOG_CLIENT.critical('Критическая ошибка')\n LOG_CLIENT.error('Ошибка')\n LOG_CLIENT.debug('Отладочная информация')\n LOG_CLIENT.info('Информационное сообщение')\n","sub_path":"logs/configs/config_client_log.py","file_name":"config_client_log.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"452828497","text":"import matplotlib.pyplot as plt\nfrom matplotlib import lines\nimport sys\nfrom math import sqrt\n\ndef print_spanning_tree(points):\n x_list = []\n y_list = []\n\n for (x, y) in points:\n x_list.append(x)\n y_list.append(y)\n\n plt.plot(x_list, y_list, 'ro')\n\n reached = []\n unreached = [] + points\n\n reached.append(unreached[0])\n unreached.pop(0)\n\n while len(unreached) > 0:\n record = sys.maxsize\n r_index = None\n u_index = None\n \n for i in range(len(reached)):\n for j in range(len(unreached)):\n x = (reached[i][0] - unreached[j][0])\n y = (reached[i][1] - unreached[j][1])\n distance = sqrt(x ** 2 + y ** 2)\n\n if distance < record:\n record = distance\n r_index = i\n u_index = j\n \n line = lines.Line2D(\n [reached[r_index][0], unreached[u_index][0]],\n [reached[r_index][1], unreached[u_index][1]]\n )\n plt.axes().add_line(line)\n\n reached.append(unreached[u_index])\n unreached.pop(u_index)\n\n plt.show()\n","sub_path":"src/spanning_tree.py","file_name":"spanning_tree.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"68288019","text":"import numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport matplotlib.patches as mpatches\nimport pickle\nimport time\nimport os.path\nimport argparse\nfrom sklearn.metrics import roc_curve, auc, f1_score, confusion_matrix\nimport tensorflow as tf\nimport h5py\nimport re\n\nplt.style.use(\"./matplotlib_LHCb.mplstyle\")\n\nwith open(\"../../../data/Val_md_labels_264972.pickle\", \"rb\") as f:\n test_y = pickle.load(f)\n\nwith h5py.File(\"../../../data/Processed_Val_md_264972.h5\", \"r\") as valData:\n data = valData[\"Val\"][:]\n\nwith open(\"../../../data/inc_pca_mu_354.pickle\", \"rb\") as f:\n inc_pca = pickle.load(f)\n\ndef get_sg(fname, labels=True):\n sg = pd.read_pickle(fname)\n\n if labels:\n lbls = np.ones(sg.shape[0])\n return sg, lbls\n else:\n return sg\n\ndef get_bg(fname, labels=True):\n bg = pd.read_pickle(fname)\n\n if labels:\n lbls = np.zeros(bg.shape[0])\n return bg, lbls\n else:\n return bg\n\ndef get_sg_and_bg(file_sig, file_bkg, labels=True, shuffle=True, random_state=42):\n if labels:\n sgx, sgy = get_sg(file_sig, labels=True)\n bgx, bgy = get_bg(file_bkg, labels=True)\n else:\n sgx = get_sg(file_sig, labels=False)\n bgx = get_bg(file_bkg, labels=False)\n\n miss_in_bg = [col for col in sgx.columns.values if col not in bgx.columns.values]\n\n miss_in_signal = [col for col in bgx.columns.values if col not in sgx.columns.values]\n\n print(\"Dropped in bg: {}\\n\\n Dropped in signal: {}\".format(miss_in_bg, miss_in_signal))\n sgx.drop(miss_in_bg, inplace = True, axis = 1)\n bgx.drop(miss_in_signal, inplace = True, axis = 1)\n data = pd.concat((sgx, bgx))\n indices = np.arange(data.shape[0])\n\n if shuffle:\n np.random.seed(random_state)\n np.random.shuffle(indices)\n data = data.iloc[indices, :]\n\n if labels:\n labels = np.concatenate((sgy, bgy))[indices]\n return data, labels\n else:\n return data\n\nnr_features = data.shape[1]\nnr_classes = len(list(np.unique(test_y)))\n\ndef savefig(list_of_plots, path):\n import matplotlib.backends.backend_pdf\n pdf = matplotlib.backends.backend_pdf.PdfPages(path)\n for fig in list_of_plots:\n pdf.savefig(fig)\n pdf.close()\n\n\ndef build_csv_summary(stats_nr, filename, sortby):\n if type(stats_nr) != list:\n stats_nr = [stats_nr]\n\n curdir = os.path.abspath(os.path.curdir)\n folders = [\"{}/nn_logs{}\".format(curdir, nr) for nr in stats_nr]\n out_file = filename + \".csv\"\n\n columns = [\"stats_nr\", \"NNType\", \"nodes\", \"activations\", \"DropOut\", \"max_acc\", \"max_acc_std\", \"roc_auc\", \"F1\", \"acc\", \"std\", \"train_examples\", \"test_examples\", \"feature_size\", \"optimizer\", \"epochs\", \"time\", \"fcost\", \"batchNorm\", \"PCA\"]\n out_df = pd.DataFrame()\n\n collective_dict = {}\n for col in columns:\n collective_dict[col] = []\n\n for folder,statsNr in zip(folders, stats_nr):\n try:\n with open(folder+\"/stats{}.pickle\".format(statsNr), \"rb\") as f:\n in_dict = pickle.load(f)\n except FileNotFoundError:\n continue\n\n roc_auc = {}\n F1 = {}\n\n if in_dict[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n fpr, tpr, _ = roc_curve(test_y, pred)\n roc_auc[\"{}\".format(e)] = auc(fpr, tpr)\n\n #F1\n f1 = f1_score(test_y, pred)\n F1[\"{}\".format(e)]= f1\n\n tf.reset_default_graph()\n max_auc = max(roc_auc.values())\n max_F1 = max(F1.values())\n\n for col in columns:\n try:\n if col == \"acc\":\n collective_dict[\"max_acc\"] += [np.round(np.mean(np.amax(in_dict[col], axis=1)), 4) * 100]\n collective_dict[\"max_acc_std\"] += [np.round(np.std(np.amax(in_dict[col], axis=1)), 4) * 100]\n collective_dict[col] += [np.round(np.mean(in_dict[col][:,-1]), 4) * 100]\n collective_dict[\"std\"] += [np.round(np.std(in_dict[col][:,-1]), 4) * 100]\n elif col == \"train_examples\":\n collective_dict[col] += [in_dict[col]]\n collective_dict[\"test_examples\"] += [int(in_dict[\"test_size\"])]\n elif col == \"features\":\n collective_dict[col] += [len(in_dict[col])]\n elif col in [\"max_acc\", \"max_acc_std\", \"std\", \"test_examples\"]:\n pass\n elif col == \"time\":\n collective_dict[col] += [np.round(in_dict[col], 0)]\n elif col == \"roc_auc\":\n collective_dict[col] += [round(max_auc, 4)]\n elif col == \"F1\":\n collective_dict[col] += [round(max_F1, 4)]\n else:\n collective_dict[col] += [in_dict[col]]\n except KeyError:\n collective_dict[col] += [\"Not implemented\"]\n\n print(folder+\" used for summary.\")\n\n\n for col in columns:\n out_df[col] = collective_dict[col]\n\n out_df.sort_values(by=sortby, ascending = False, inplace = True)\n out_df.to_csv(out_file)\n print(\"\\n\" + out_file + \" successfully built.\\n\")\n\n\ndef build_full_output(stats, histogram, nr, acc, lastEpoch):\n for i in range(100):\n filename1 = \"./Logs/log{}_{}.txt\".format(i, nr)\n filename2 = \"./Figures/fig{}_{}_acc{}_last{}.pdf\".format(i, nr, str(acc)[0], str(lastEpoch)[0])\n if not os.path.isfile(filename1) and not os.path.isfile(filename2):\n with open(filename1, \"w\") as f:\n\n f.write(\"Start date: {}, Corresponding stats: {}\".format(time.strftime(\"%c\"), nr))\n f.write(\"\\n\"+\"#\"*10)\n f.write(\"\\n\\tNetwork Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nNetwork type: {}\".format(stats[\"NNType\"]))\n f.write(\"\\n\\nStructure: {}\".format(stats[\"nodes\"]))\n f.write(\"\\nActivations: {}\".format(stats[\"activations\"]))\n f.write(\"\\nDropout: {}\".format(stats[\"DropOut\"]))\n\n\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tTraining Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nTrainingSet: {}, Epochs: {}, batch_size: {}\".format(stats[\"train_examples\"], stats[\"epochs\"], stats[\"batch\"]))\n f.write(\"\\n\\nOptimizer: {}\".format(stats[\"optimizer\"]))\n f.write(\"\\n\\n#Features: {} - {}\".format(len(stats[\"features\"]), stats[\"feature_size\"]))\n f.write(\"\\n\\nStandardized Features: {}\".format(stats[\"standFeatures\"]))\n f.write(\"\\n\\nLog-transformed Features: {}\".format(stats[\"LogTransformed\"]))\n f.write(\"\\n\\nFeatures: {}\".format(stats[\"features\"]))\n try:\n f.write(\"\\n\\nApplied cuts: {}\".format(stats[\"cuts\"]))\n except KeyError:\n pass\n\n\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tEvaluation Information\")\n f.write(\"\\n\"+\"#\"*10)\n\n test_accs = stats[\"acc\"][:,-1]\n f.write(\"\\n\\nFinal test accuracy: {}\".format(test_accs))\n f.write(\"\\nK-Fold test accuracy: {} pm {}\".format(np.mean(test_accs), np.std(test_accs)))\n\n max_test_acc = np.amax(stats[\"acc\"], axis=1)\n f.write(\"\\n\\nMax test accuracies: {} --- Epoch: {}\".format(max_test_acc, np.argmax(stats[\"acc\"], axis=1)))\n f.write(\"\\nK-Fold max accuracy: {} pm {}\".format(np.mean(max_test_acc), np.std(max_test_acc)))\n\n\n lossess = stats[\"losses\"][:,-1]\n f.write(\"\\nK-Fold cost: {} pm {}\".format(np.mean(lossess), np.std(lossess)))\n\n f.write(\"\\n\\n{}\".format(create_confusion_matrix(stats, nr)))\n f.write(\"\\n\\n\"+\"#\"*10)\n f.write(\"\\n\\tEvaluation Details\")\n f.write(\"\\n\"+\"#\"*10)\n\n f.write(\"\\n\\nLosses: {}\".format(stats[\"losses\"]))\n f.write(\"\\n\\nTraining Accuracy: {}\".format(stats[\"train_acc\"]))\n f.write(\"\\n\\nTest Accuracy: {}\".format(stats[\"acc\"]))\n\n t = stats[\"time\"]\n f.write(\"\\n\\nTraining Time: {}s, {}min, {}h\".format(t, t/60, t/3600))\n\n build_figures(stats, path=filename2, histogram=histogram, nr=nr, acc=acc, lastEpoch=lastEpoch)\n print(\"Log and figures file: {}_{}\".format(i, nr))\n break\n\n\ndef create_confusion_matrix(stats, nr):\n confMatrices = \"Confusion matrix | Precision | Recall: \\n\"\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n folder = \"./nn_logs{}\".format(nr)\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n print(\"\\n\\n\\n{}\\n\\n\".format(filename))\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n confMatrices = confMatrices + \"{} Epoch {}\".format(\"---\"*10, e)\n confMatrix = confusion_matrix(test_y, pred)\n confMatrices += \"\\n\\n{}\".format(str(confMatrix))\n\n confMatrix = confMatrix / confMatrix.sum(axis=0, keepdims=True)\n confMatrices += \"\\n\\n{}\".format(str(confMatrix))\n\n confMatrix = confMatrix / confMatrix.sum(axis=1, keepdims=True)\n confMatrices += \"\\n\\n{}\\n\".format(str(confMatrix))\n tf.reset_default_graph()\n\n\n return confMatrices\n\n\ndef build_figures(stats, nr, path = None, histogram = \"Z0_MM\", acc=False, lastEpoch=False):\n epochs = np.arange(stats[\"epochs\"])\n\n figs = []\n\n print(\"Process cost...\")\n fig0 = plt.figure()\n plt.plot(epochs, stats[\"losses\"][0], label = \"Train cost\")\n try:\n plt.plot(epochs, stats[\"val_losses\"][0], label = \"Validation cost\")\n except KeyError:\n pass\n plt.legend(loc = \"upper right\")\n plt.title(\"Structure: {}, Act.: {}, batch_size: {}, \\nepochs: {}, opt.: {}\".format(stats[\"nodes\"], stats[\"activations\"], stats[\"batch\"], stats[\"epochs\"], stats[\"optimizer\"]))\n figs += [fig0]\n\n print(\"Process accuracies...\")\n colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']*2\n fig2 = plt.figure()\n plt.plot(epochs, stats[\"acc\"][0], label = \"Test Accuracy\")\n plt.plot(epochs, stats[\"train_acc\"][0], \"--\", label = \"Training Accuracy\")\n plt.legend(loc = \"upper left\")\n plt.title(\"Structure: {}, Act.: {}, batch_size: {}, \\nepochs: {}, opt.: {}\".format(stats[\"nodes\"], stats[\"activations\"], stats[\"batch\"], stats[\"epochs\"], stats[\"optimizer\"]))\n figs += [fig2]\n\n margin_q = np.linspace(-1, 1, 50)\n figMargin = plt.figure()\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n folder = \"./nn_logs{}\".format(nr)\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for line in lines[1:]:\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n\n factor = np.array([int(i) if i else int(i)-1 for i in np.equal(np.argmax(pred, axis = 1), test_y)])\n\n margins = np.max(pred, axis = 1) * factor\n\n margin_p = [len(np.where(margins<=q)[0])/len(margins) for q in margin_q ]\n plt.plot(margin_q, margin_p, label = \"Epoch {}\".format(e))\n plt.title(\"Margin CDF\")\n plt.xlabel(\"Margin\")\n plt.ylabel(\"CDF / Fraction\")\n plt.xticks(np.linspace(-1, 1, 11))\n plt.yticks(np.linspace(0, 1, 11))\n plt.legend()\n\n tf.reset_default_graph()\n\n figs += [figMargin]\n\n figs += create_sg_bg_separation_and_ROC(stats, nr, lastEpoch)\n if histogram is not None:\n figs += create_histograms(stats, histogram, nr, acc, lastEpoch)\n\n savefig(figs, path)\n\n\ndef create_sg_bg_separation_and_ROC(stats, nr, lastEpoch):\n print(\"Process ROC...\")\n\n ROCs = []\n folder = \"./nn_logs{}\".format(nr)\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for ei, line in enumerate(lines[1:]):\n if lastEpoch and not (ei == 0 or ei+1 == len(lines)-1):\n continue\n\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n\n bgDist = pred[np.where(test_y==0)[0]][:,0]\n sgDist = pred[np.where(test_y==1)[0]][:,0]\n\n fig, ax = plt.subplots(nrows = 1, ncols = 2)\n\n plt.subplot(1, 2, 1)\n x = [bgDist, sgDist]\n plt.hist(x, histtype = \"step\", bins =75, label = [\"background\", \"signal\"])\n plt.title(\"Bg-Sg-Prediction Dist.\")\n plt.xlabel(\"Prediction\")\n plt.legend(loc=\"upper center\")\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(nr_classes):\n fpr[i], tpr[i], _ = roc_curve(test_y, pred[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n plt.subplot(1, 2, 2)\n plt.plot(fpr[1], tpr[1], color='darkorange', lw=2, label='ROC area = %0.4f' % roc_auc[1])\n plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('ROC, Epoch: {}'.format(e))\n plt.legend(loc=\"lower right\")\n ROCs.append(fig)\n\n return ROCs\n\n\ndef create_histograms(stats, histograms, nr, acc, lastEpoch):\n print(\"Process histograms...\")\n hists = []\n curdir = os.path.abspath(os.path.curdir)\n\n sgname = \"../../../data/Val_md_MC_157677.pickle\"\n bgname = \"../../../data/Val_md_hf_107295.pickle\"\n\n if stats[\"PCA\"]:\n test_x = inc_pca.transform(data)\n else:\n test_x = data\n\n origData, test_y = get_sg_and_bg(sgname, bgname, labels=True, shuffle=True, random_state=42)\n\n nr_examples = test_x.shape[0]\n folder = \"./nn_logs{}\".format(nr)\n\n columns = ['runNumber', 'eventNumber', 'nCandidate', 'totCandidates', 'nTracks',\n 'nSPDHits', 'nLongTracks', 'Z0_MM', 'Z0_PT', 'Z0_ENDVERTEX_CHI2',\n 'Z0_ENDVERTEX_NDOF', 'y', 'isolation', 'muplus_MINIP', 'muplus_P', 'muplus_PT',\n 'muplus_PX', 'muplus_PY', 'muplus_PZ', 'muplus_TrEta', 'muplus_TrPChi2',\n 'muplus_TrPhi', 'muplus_cpt_0.1', 'muplus_cpt_0.5', 'muminus_MINIP',\n 'muminus_P', 'muminus_PT', 'muminus_PX', 'muminus_PY', 'muminus_PZ',\n 'muminus_TrEta', 'muminus_TrPChi2', 'muminus_TrPhi', 'muminus_cpt_0.1',\n 'muminus_cpt_0.5', 'nTrack', 'tracks_PT' 'tracks_PX', 'tracks_PY',\n 'tracks_PZ', 'tracks_IP', 'tracks_IPCHI2', 'tracks_eta', 'tracks_phi',\n 'tracks_charge', 'tracks_isMuon', 'weight']\n\n drawn = []\n for histogram in histograms:\n if histogram not in columns:\n print(\"!!!\\n {} does not in exist in this dataframe. IGNORED.\\n!!!\".format(histogram))\n histograms.remove(histogram)\n else:\n drawn.append(False)\n\n\n with open(folder+\"/Models/checkpoint\", \"r\") as f, tf.Session() as sess:\n new_saver = tf.train.import_meta_graph(folder+'/Models/NNModel-0.meta')\n lines = f.readlines()\n pattern = \"nn_logs.*\"\n for ei, line in enumerate(lines[1:]):\n if lastEpoch and not (ei == 0 or ei+1 == len(lines)-1):\n continue\n\n regExp = re.search(pattern, line)\n filename = regExp.group(0)[:-1]\n regExp = re.search(\"[0-9]+$\", filename)\n e = int(regExp.group(0))\n\n new_saver.restore(sess, filename)\n graph = tf.get_default_graph()\n x = graph.get_tensor_by_name(\"x:0\")\n y = graph.get_tensor_by_name(\"y:0\")\n tr_phase = graph.get_tensor_by_name(\"trainPhase:0\")\n pred_proba = graph.get_tensor_by_name(\"Model/predProba:0\")\n pred = pred_proba.eval({x: test_x, tr_phase: 1})\n pred = np.array([np.argmax(p) for p in pred])\n\n signal = np.where(pred==1)[0]\n bg = np.where(pred==0)[0]\n\n truesignal = np.where(test_y==1)[0]\n truebg = np.where(test_y==0)[0]\n\n truepos = np.logical_and(test_y==1, pred==1)\n trueneg = np.logical_and(test_y==0, pred==0)\n falsepos = np.logical_and(test_y==0, pred==1)\n falseneg = np.logical_and(test_y==1, pred==0)\n\n for h, histogram in enumerate(histograms):\n bincuts = np.array([10, 11.0, 11.5, 12.0, 13.0, 14.0, 15.0, 17.5, 20.0, 25.0, 30.0, 40.0, 60.0, 120.0])*1000 if histogram==\"Z0_MM\" else 50\n if not drawn[h]:\n x = [origData[histogram][test_y==1], origData[histogram][test_y==0]]\n fig = plt.figure()\n plt.hist(x, histtype = \"bar\", stacked = \"True\", bins=bincuts, color = [\"#0b0db0\", \"#b21000\"], label = [\"signal\", \"background\"])\n plt.xlabel(histogram)\n plt.title(\"True distribution\")\n plt.legend()\n plt.yscale(\"log\")\n hists += [[-1, fig]]\n fig = plt.figure()\n drawn[h] = True\n\n x = [origData[histogram][truepos], origData[histogram][falsepos], origData[histogram][trueneg], origData[histogram][falseneg]]\n fig = plt.figure()\n plt.hist(x, histtype = \"bar\", stacked = True, bins=bincuts, color = [\"#0b0db0\", \"#7172e1\", \"#b21000\",\"#e17b71\" ], label = [\"true signal\", \"false signal\", \"true background\", \"false background\"])\n plt.xlabel(histogram)\n plt.title(\"Epoch: {}\".format(e))\n plt.legend()\n plt.yscale(\"log\")\n hists += [[int(\"1{}{}0\".format(h, ei)), fig]]\n\n if acc:\n fig = plt.figure()\n n, edges, _ = plt.hist(x, histtype = \"bar\", stacked = False, bins=bincuts)\n count_trueSig = n[0]\n count_predSig = n[0] + n[1]\n count_trueBg = n[2]\n count_predBg = n[2] + n[3]\n count_correct = n[0] + n[2]\n count_signal = n[0] + n[3]\n count_bg = n[1] + n[2]\n count_all = n[0] + n[1] + n[2] + n[3]\n\n acc_sg = list(count_trueSig / count_signal)\n acc_bg = list(count_trueBg / count_bg)\n acc_al = list(count_correct / count_all)\n acc_sg.insert(0, acc_sg[0])\n acc_bg.insert(0, acc_bg[0])\n acc_al.insert(0, acc_al[0])\n\n fig = plt.figure()\n plt.step(edges, acc_bg, color =\"#ff8a65\", label= \"Recall: Bg\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, acc_al, color =\"#7dfd6a\", label= \"Recall: Total\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, acc_sg, color=\"navy\", label=\"Recall: Signal\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"Recall - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}1\".format(h, ei)), fig]]\n\n predsg = list(count_predSig/count_all)\n predbg = list(count_predBg/count_all)\n predsg.insert(0, predsg[0])\n predbg.insert(0, predbg[0])\n\n fig = plt.figure()\n plt.step(edges, predbg, color=\"#ff8a65\", label=\"Pred. Bg\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, predsg, color=\"navy\", label=\"Pred. Sg\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"Predicted rate - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}2\".format(h, ei)), fig]]\n\n predFsg = list(n[1]/count_all)\n predFbg = list(n[3]/count_all)\n predFsg.insert(0, predFsg[0])\n predFbg.insert(0, predFbg[0])\n\n fig = plt.figure()\n plt.step(edges, predFbg, color=\"#ff8a65\", label=\"False negative\", where=\"pre\", linestyle=\"--\")\n plt.step(edges, predFsg, color=\"navy\", label=\"False positive\", where=\"pre\")\n plt.xlabel(histogram)\n plt.title(\"False rate - Epoch: {}\".format(e))\n plt.legend(loc=8, fontsize = \"small\")\n plt.ylim([0,1])\n hists += [[int(\"1{}{}3\".format(h, ei)), fig]]\n\n hists = list(np.array(sorted(hists, key=lambda x: x[0]))[:, 1])\n return hists\n\n\ndef main():\n def str2bool(inpt):\n if inpt in [\"n\", \"N\", \"False\", \"F\", \"f\", \"no\"]:\n inpt = False\n else:\n inpt = True\n return inpt\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--nr\", type=int, default=None, help=\"stats number, default: None\")\n parser.add_argument(\"--summary\", type=str2bool, default=True, help=\"True if summary is requested, default: True\")\n parser.add_argument(\"--filename\", type=str, default=\"summary\", help=\"filename of summary, default: 'summary'\")\n parser.add_argument(\"--histogram\", type=str, default=\"Z0_MM\", help=\"variable to plot a histogram, features are seperated by a ':', default: 'Z0_MM'\")\n parser.add_argument(\"--acc\", type=str2bool, default=True, help=\"Presentation of histograms in terms of correct classification, default: True\")\n parser.add_argument(\"--last\", type=str2bool, default=True, help=\"True, if only last epoch should be shown, default: False\")\n parser.add_argument(\"--sortby\", type=str, default=\"roc_auc\", help=\"Sort value for summary. Possible are: 'max_acc' (default), 'roc_auc' and 'F1'\")\n args = parser.parse_args()\n \n curdir = os.path.abspath(os.path.curdir)\n if args.nr is None:\n stats_nr = []\n user_input = 0\n while True:\n user_input = input(\"Stats number: \")\n if user_input == \"\":\n break\n elif float(user_input) < 0:\n stats_nr = [i for i in range(100)]\n break\n try:\n user_input = int(user_input)\n stats_nr += [user_input]\n except:\n print(\"Invalid input. Insert integer!\")\n \n if args.summary:\n build_csv_summary(stats_nr, args.filename, args.sortby)\n else:\n for nr in stats_nr:\n filename = \"{}/nn_logs{}/stats{}.pickle\".format(curdir, nr, nr)\n with open(filename, \"rb\") as f:\n stats = pickle.load(f)\n build_full_output(stats, args.histogram.split(\":\"), nr, args.acc, args.last)\n \n else:\n filename = \"{}/nn_logs{}/stats{}.pickle\".format(curdir, args.nr, args.nr)\n with open(filename, \"rb\") as f:\n stats = pickle.load(f)\n build_full_output(stats, args.histogram.split(\":\"), args.nr, args.acc, args.last)\n\n\n # nmbrs=[0]\n # histograms = \"Z0_MM:nSPDHits:y\"\n # for nmbr in nmbrs:\n # filename = \"./nn_logs{}/stats{}.pickle\".format(nmbr, nmbr)\n # with open(filename, \"rb\") as f:\n # stats = pickle.load(f)\n # build_full_output(stats, histograms.split(\":\"), nmbr, True, False)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Programme/FCLogSaverRaw.py","file_name":"FCLogSaverRaw.py","file_ext":"py","file_size_in_byte":26488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"433042318","text":"import os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\n# 파일 탐색\r\ndef search_files(path):\r\n for root, _, files in os.walk(path):\r\n for file in files:\r\n file_name = os.path.join(root, file).replace('\\\\', '/')\r\n yield file_name\r\n\r\n\r\ndef gather_data(data_dir):\r\n # 미세먼지 데이터가 존재하는 동\r\n weather_dir = f'{data_dir}/pre/weather' # 미세먼지 경로\r\n dong = [file_name.split('/')[-1][:8] for file_name in search_files(weather_dir)]\r\n dong = sorted(list(set(dong)))\r\n\r\n # weather\r\n weather_df = pd.DataFrame()\r\n for f in search_files(weather_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n temp_df['CD'] = cd\r\n weather_df = pd.concat((weather_df, temp_df))\r\n weather_df = weather_df.groupby('CD').mean() # 평균\r\n\r\n # gs\r\n gs_dir = f'{data_dir}/pre/gs'\r\n gs_df = pd.DataFrame()\r\n for f in search_files(gs_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n gs_df = pd.concat((gs_df, temp_df))\r\n gs_df['CD'] = gs_df['CD'].apply(str)\r\n gs_df = gs_df.groupby('CD').mean() # 평균\r\n\r\n # flow\r\n flow_dir = f'{data_dir}/pre/time_floating'\r\n flow_df = pd.DataFrame()\r\n for f in search_files(flow_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n temp_df['CD'] = cd\r\n flow_df = pd.concat((flow_df, temp_df))\r\n flow_df = flow_df.groupby('CD').mean() # 평균\r\n\r\n # card\r\n card_dir = f'{data_dir}/pre/card'\r\n card_df = pd.DataFrame()\r\n for f in search_files(card_dir):\r\n cd = f.split('/')[-1][:8]\r\n if cd in dong:\r\n temp_df = pd.read_csv(f, delimiter=',', index_col=0, parse_dates=True)\r\n # 평균; 업종별 카드 이용금액; 다중공선성으로 성별, 연령대는 제외\r\n temp_df = temp_df.groupby(['MCT_CAT_CD']).mean()[['USE_AMT']].reset_index()\r\n temp_df.index = temp_df['MCT_CAT_CD'].apply(str)\r\n temp_df = temp_df[['USE_AMT']].T\r\n temp_df['CD'] = cd\r\n card_df = pd.concat((card_df, temp_df), sort=True)\r\n card_df = card_df.dropna(axis='columns') # 결측치가 존재하는 컬럼 제거\r\n\r\n # 데이터 통합\r\n result = pd.merge(weather_df, gs_df, on='CD', how='inner')\r\n result = pd.merge(result, flow_df, on='CD', how='inner')\r\n result = pd.merge(result, card_df, on='CD', how='inner')\r\n\r\n # 행정동명 추가\r\n h_code_file = f'{data_dir}/GS리테일_동별 매출지수용 기준값 확인_AMT_NEW.xlsx'\r\n code = pd.read_excel(h_code_file, skiprows=1, sheet_name='참고)구_행정동코드',\r\n usecols=[3, 4], names=['CD', '행정동'])\r\n code['CD'] = code['CD'].apply(str)\r\n result = result.join(code.set_index('CD'), on='CD')\r\n\r\n # 군집분석을 위해 컬럼명 수정\r\n # result.columns = [cn.replace(' ', '').replace('&', '').replace('/', '') for cn in result.columns]\r\n for cn in result.columns:\r\n try:\r\n result = result.rename(columns={f'{cn}': f'C{int(cn)}'})\r\n except ValueError:\r\n pass\r\n\r\n # CD, 행정동\r\n cd_list = result.iloc[:, [0, -1]]\r\n result = result.drop(columns=['CD', '행정동'])\r\n\r\n # 표준화\r\n result_norm = (result - result.mean()) / result.std()\r\n\r\n return result, result_norm, cd_list\r\n\r\n\r\n# 적합한 군집의 갯수 확인\r\ndef select_cluster(input_df, save_dir):\r\n sse = []\r\n for i in range(1, len(input_df)):\r\n km = KMeans(n_clusters=i, algorithm='auto', random_state=42)\r\n km.fit(input_df)\r\n sse.append(km.inertia_)\r\n\r\n plt.plot(range(1, len(input_df)), sse, marker='o')\r\n plt.xlabel('K')\r\n plt.ylabel('SSE')\r\n\r\n # save fig\r\n plt.savefig(f'{save_dir}/n_cluster_sse.png')\r\n\r\n\r\nif __name__ == '__main__':\r\n data_directory = '../data' # data folder directory\r\n directory = f'{data_directory}/km'\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n df, df_norm, _cd = gather_data(data_directory)\r\n df_norm.to_csv('test_norm.csv', header=True, index=False)\r\n select_cluster(df, directory)\r\n","sub_path":"code/pre_km.py","file_name":"pre_km.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"339107656","text":"#!/bin/python3\n\nimport os\nimport sys\nfrom datetime import datetime\n\ndef timeConversion(s):\n AM_PM = s[-2:]\n s = s[:8]\n hh, mm, ss = [int(x) for x in s.split(':')]\n\n if AM_PM == 'PM' and hh != 12:\n return('{:02}:{:02}:{:02}'.format(hh+12, mm, ss))\n\n elif AM_PM == 'AM' and hh == 12:\n return('{:02}:{:02}:{:02}'.format(0, mm, ss))\n\n else:\n return('{:02}:{:02}:{:02}'.format(hh, mm, ss))\n\n\n\nif __name__ == '__main__':\n f = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = timeConversion(s)\n\n f.write(result + '\\n')\n\n f.close()\n","sub_path":"Time_Conversion.py","file_name":"Time_Conversion.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"522195101","text":"from opengever.base.behaviors.translated_title import TranslatedTitleMixin\nfrom opengever.meeting import _\nfrom opengever.meeting.model import Member\nfrom opengever.meeting.sources import proposal_template_source\nfrom opengever.meeting.sources import sablon_template_source\nfrom opengever.meeting.wrapper import MemberWrapper\nfrom plone.dexterity.content import Container\nfrom plone.supermodel import model\nfrom z3c.relationfield.schema import RelationChoice\n\n\nclass ICommitteeContainer(model.Schema):\n \"\"\"Base schema for a the committee container.\n \"\"\"\n\n protocol_header_template = RelationChoice(\n title=_('label_protocol_header_template',\n default='Protocol header template'),\n source=sablon_template_source,\n required=True,\n )\n\n protocol_suffix_template = RelationChoice(\n title=_('label_protocol_suffix_template',\n default='Protocol suffix template'),\n source=sablon_template_source,\n required=False,\n )\n\n agenda_item_header_template = RelationChoice(\n title=_('label_agenda_item_header_template',\n default='Agenda item header template for the protocol'),\n source=sablon_template_source,\n required=False,\n )\n\n agenda_item_suffix_template = RelationChoice(\n title=_('label_agenda_item_suffix_template',\n default='Agenda item suffix template for the protocol'),\n source=sablon_template_source,\n required=False,\n )\n\n excerpt_header_template = RelationChoice(\n title=_('label_excerpt_header_template',\n default='Excerpt header template'),\n source=sablon_template_source,\n required=False,\n )\n\n excerpt_suffix_template = RelationChoice(\n title=_('label_excerpt_suffix_template',\n default='Excerpt suffix template'),\n source=sablon_template_source,\n required=False,\n )\n\n agendaitem_list_template = RelationChoice(\n title=_('label_agendaitem_list_template',\n default=u'Agendaitem list template'),\n source=sablon_template_source,\n required=False,\n )\n\n toc_template = RelationChoice(\n title=_('label_toc_template',\n default=u'Table of contents template'),\n source=sablon_template_source,\n required=False,\n )\n\n ad_hoc_template = RelationChoice(\n title=_('label_ad_hoc_template',\n default=u'Ad hoc agenda item template'),\n source=proposal_template_source,\n required=False,\n )\n\n paragraph_template = RelationChoice(\n title=_('label_paragraph_template',\n default=u'Paragraph template'),\n source=sablon_template_source,\n required=False,\n )\n\n\n_marker = object()\n\n\nclass CommitteeContainer(Container, TranslatedTitleMixin):\n \"\"\"Committee Container class, a container for all committees.\"\"\"\n\n Title = TranslatedTitleMixin.Title\n\n def _getOb(self, id_, default=_marker):\n \"\"\"We extend `_getOb` in order to change the context for member\n objects to `MemeberWrapper`. That allows us to register the\n members view as regular Browser view without any traversal hacks.\"\"\"\n\n obj = super(CommitteeContainer, self)._getOb(id_, default)\n if obj is not default:\n return obj\n\n if id_.startswith('member'):\n member_id = int(id_.split('-')[-1])\n member = Member.query.get(member_id)\n if member:\n return MemberWrapper.wrap(self, member)\n\n if default is _marker:\n raise KeyError(id_)\n return default\n\n def get_protocol_header_template(self):\n if self.protocol_header_template:\n return self.protocol_header_template.to_object\n return None\n\n def get_protocol_suffix_template(self):\n return getattr(self.protocol_suffix_template, 'to_object', None)\n\n def get_agenda_item_header_template(self):\n return getattr(self.agenda_item_header_template, 'to_object', None)\n\n def get_agenda_item_suffix_template(self):\n return getattr(self.agenda_item_suffix_template, 'to_object', None)\n\n def get_excerpt_header_template(self):\n if self.excerpt_header_template:\n return self.excerpt_header_template.to_object\n return None\n\n def get_excerpt_suffix_template(self):\n if self.excerpt_suffix_template:\n return self.excerpt_suffix_template.to_object\n return None\n\n def get_agendaitem_list_template(self):\n if self.agendaitem_list_template:\n return self.agendaitem_list_template.to_object\n\n return None\n\n def get_toc_template(self):\n if self.toc_template:\n return self.toc_template.to_object\n\n return None\n\n def get_ad_hoc_template(self):\n if self.ad_hoc_template:\n return self.ad_hoc_template.to_object\n\n return None\n\n def get_paragraph_template(self):\n if self.paragraph_template:\n return self.paragraph_template.to_object\n\n return None\n","sub_path":"opengever/meeting/committeecontainer.py","file_name":"committeecontainer.py","file_ext":"py","file_size_in_byte":5077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"13190337","text":"# -*- coding:utf-8 -*-\n__author__ = \"Yang Wei Min\"\nfrom selenium import webdriver\nimport unittest\nimport time\nimport HTMLTestRunner\n\nclass BaiDu(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get(\"http:www.baidu.com/\")\n time.sleep(3)\n\n def test_SearchKeyWords(self):\n self.driver.find_element_by_id(\"kw\").clear()\n time.sleep(1)\n self.driver.find_element_by_id(\"kw\").send_keys(\"Selenium\")\n self.driver.find_element_by_id(\"su\").click()\n\n def tearDown(self):\n self.driver.quit()\n\nif __name__ == \"__main__\":\n suiteTest = unittest.TestSuite()\n #将测试用例添加到测试容器中\n suiteTest.addTest(BaiDu(\"test_SearchKeyWords\"))\n filename = r\"E:\\\\Code\\\\Python\\\\Selenium_Test\\\\Results.html\"\n fp = file(filename,\"wb\")\n runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u\"测试百度搜索关键字\",description=u\"测试结果\")\n runner.run(suiteTest)","sub_path":"Selenium_Test/Baidu.py","file_name":"Baidu.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"303423407","text":"from datetime import datetime\nfrom dateutil import rrule\n\nfrom tracpro.test import factories\nfrom tracpro.test.cases import TracProDataTest\nfrom tracpro.polls.models import Answer, Response\n\nfrom ..models import BaselineTerm\n\n\nclass BaselineTermTest(TracProDataTest):\n\n def setUp(self):\n \"\"\"\n There will be a set of results for 3 contacts, in 2 regions\n self.contact1 and self.contact2 are in self.region1\n self.contact4 is in self.region2\n \"\"\"\n super(BaselineTermTest, self).setUp()\n\n contacts = [self.contact1, self.contact2, self.contact4]\n self.start_date = datetime(2015, 1, 1, 8)\n self.end_date = datetime(2015, 1, 3, 8) # Two days of follow up results\n\n self.baselineterm = BaselineTerm.objects.create(\n org=self.unicef,\n name=\"Test BaselineTerm\",\n start_date=self.start_date,\n end_date=self.end_date,\n baseline_poll=self.poll1,\n baseline_question=self.poll1_question1,\n follow_up_poll=self.poll2,\n follow_up_question=self.poll2_question1\n )\n\n # Create a single PollRun for the Baseline Poll\n self.baseline_pollrun = factories.RegionalPollRun(\n poll=self.poll1, conducted_on=self.start_date)\n # Create a Response AKA FlowRun for each contact for Baseline\n answer_value = 10 # Baseline values will be 10, 20 and 30\n for contact in contacts:\n response = factories.Response(\n pollrun=self.baseline_pollrun,\n contact=contact,\n created_on=self.start_date,\n updated_on=self.start_date,\n status=Response.STATUS_COMPLETE)\n # Create an Answer for each contact for Baseline\n Answer.objects.create(\n response=response,\n question=self.poll1_question1,\n value=answer_value,\n submitted_on=self.start_date,\n category=u'')\n answer_value += 10 # Increase next answer's value by 10\n\n # Answers for contacts found in this dictionary\n self.contact_dict = {\n self.contact1: {\"answers\": [9, 8, 8]},\n self.contact2: {\"answers\": [15, 10, 10]},\n self.contact4: {\"answers\": [25, 20, 15]}\n }\n\n # Create a PollRun for each date from start to end dates for the Follow Up Poll\n date_iter = 0\n for follow_up_date in rrule.rrule(rrule.DAILY, dtstart=self.start_date, until=self.end_date):\n follow_up_pollrun = factories.RegionalPollRun(\n poll=self.poll2, conducted_on=follow_up_date)\n for contact in contacts:\n # Create a Response AKA FlowRun for each contact for Follow Up\n response = factories.Response(\n pollrun=follow_up_pollrun,\n contact=contact,\n created_on=follow_up_date,\n updated_on=follow_up_date,\n status=Response.STATUS_COMPLETE)\n answer = self.contact_dict[contact][\"answers\"][date_iter]\n # Create a randomized Answer for each contact for Follow Up\n Answer.objects.create(\n response=response,\n question=self.poll2_question1,\n value=answer,\n submitted_on=follow_up_date,\n category=u'')\n date_iter += 1\n\n def test_baseline_all_regions(self):\n \"\"\" Answers were 10, 20 and 30: Total should be 10 + 20 + 30 = 60 \"\"\"\n baseline_dict, dates = self.baselineterm.get_baseline(regions=None, region_selected=0)\n\n self.assertEqual(len(baseline_dict), 2) # Two regions, two sets of baseline values\n # Two answers, 10 + 20 = 30\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30])\n # One answer, 30 = 30\n self.assertEqual(\n baseline_dict[self.region2.name][\"values\"],\n [30])\n\n def test_baseline_single_region(self):\n \"\"\" Answers were 10 and 20 for region1 \"\"\"\n baseline_dict, dates = self.baselineterm.get_baseline(regions=[self.region1], region_selected=0)\n\n self.assertEqual(len(baseline_dict), 1) # One regions, one baseline\n # Two answers sum = 10 + 20 = 30\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30])\n\n def test_baseline_single_region_multiple_answers(self):\n \"\"\"\n Answers were 10 and 20 for region1\n Add another answer for both region contacts at a later date\n Baseline should be retrieved from all responses\n \"\"\"\n for contact in [self.contact1, self.contact2]:\n response = factories.Response(\n pollrun=self.baseline_pollrun,\n contact=contact,\n created_on=self.end_date,\n updated_on=self.end_date,\n status=Response.STATUS_COMPLETE)\n Answer.objects.create(\n response=response,\n question=self.poll1_question1,\n value=100,\n submitted_on=self.end_date,\n category=u'')\n\n baseline_dict, dates = self.baselineterm.get_baseline(regions=[self.region1], region_selected=0)\n\n self.assertEqual(len(baseline_dict), 1) # One regions, one baseline\n # Two sets of baseline answers\n # sum 1 = 10 + 20 = 30\n # sum 2 = 100 + 100 = 200\n self.assertEqual(\n baseline_dict[self.region1.name][\"values\"],\n [30, 200])\n\n def test_follow_up_all_regions(self):\n \"\"\"\n Region 1 values [9, 8] + [15, 10] = [24, 18]\n Region 2 values [25, 20]\n \"\"\"\n follow_ups, dates, all_regions = self.baselineterm.get_follow_up(regions=None, region_selected=0)\n\n self.assertEqual(len(dates), 3) # 3 dates\n self.assertEqual(len(follow_ups), 2) # 2 regions for the follow up dictionary\n self.assertEqual(len(all_regions), 2) # 2 regions in all the data\n # Sum the follow up data for two contacts in Region 1\n self.assertEqual(\n follow_ups[self.region1.name][\"values\"],\n [24, 18, 18])\n # Data for Region 2 only from one contact\n self.assertEqual(\n follow_ups[self.region2.name][\"values\"],\n [25, 20, 15])\n\n def test_follow_up_single_region(self):\n \"\"\"\n Region 1 values [9, 8] + [15, 10] = [24, 18]\n Region 2 values [25, 20]\n \"\"\"\n follow_ups, dates, all_regions = self.baselineterm.get_follow_up(regions=[self.region2], region_selected=0)\n\n self.assertEqual(len(dates), 3) # 3 dates\n self.assertEqual(len(follow_ups), 1) # One region for the follow up dictionary\n self.assertEqual(len(all_regions), 1) # 1 region\n # Data for Region 2 only from one contact\n self.assertEqual(\n follow_ups[self.region2.name][\"values\"],\n [25, 20, 15])\n","sub_path":"tracpro/baseline/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":7085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"311427165","text":"# -*- coding: utf-8 -*-\n\"\"\"\napply changes to the classification in the db.\n\ninput:\n- glottolog-data/languoids/changes.json\n\"\"\"\nfrom __future__ import unicode_literals\nimport transaction\n\nfrom sqlalchemy import desc\n\nfrom clld.util import jsonload\nfrom clld.db.models.common import Identifier, LanguageIdentifier, IdentifierType\nfrom clld.db.meta import DBSession\n\nfrom glottolog3.models import Languoid, Superseded, LanguoidLevel, LanguoidStatus\nfrom glottolog3.scripts.util import (\n recreate_treeclosure, get_args, glottolog_name, glottolog_names,\n)\n\n\nMAX_IDENTIFIER_PK = None\n\n\ndef create_identifier(identifier, l, **kw):\n global MAX_IDENTIFIER_PK\n if identifier is None:\n MAX_IDENTIFIER_PK += 1\n DBSession.add(Identifier(pk=MAX_IDENTIFIER_PK, id=str(MAX_IDENTIFIER_PK), **kw))\n pk = MAX_IDENTIFIER_PK\n else:\n pk = identifier.pk\n DBSession.add(LanguageIdentifier(language_pk=l.pk, identifier_pk=pk))\n\n\ndef main(args): # pragma: no cover\n global MAX_IDENTIFIER_PK\n\n with transaction.manager:\n MAX_IDENTIFIER_PK = DBSession.query(\n Identifier.pk).order_by(desc(Identifier.pk)).first()[0]\n\n gl_name = glottolog_name()\n gl_names = glottolog_names()\n\n languoids = {l.pk: l for l in DBSession.query(Languoid)}\n for attrs in jsonload(args.data_dir.joinpath('languoids', 'changes.json')):\n replacement = attrs.pop('replacement', None)\n hname = attrs.pop('hname', None)\n\n for name, enum in [('level', LanguoidLevel), ('status', LanguoidStatus)]:\n if name in attrs:\n attrs[name] = enum.from_string(attrs[name])\n\n l = languoids.get(attrs['pk'])\n if l:\n for k, v in attrs.items():\n setattr(l, k, v)\n #\n # We do not assign ISO codes for existing languages, because it could be\n # that the ISO code is now assigned to a family node, due to a change\n # request, e.g. see https://github.com/clld/glottolog-data/issues/40\n #\n if len(l.hid or '') == 3 and not l.iso_code:\n args.log.warn('Language with hid %s but no iso code!' % l.hid)\n else:\n l = Languoid(**attrs)\n DBSession.add(l)\n languoids[l.pk] = l\n\n if len(attrs.get('hid', '')) == 3:\n create_identifier(\n None, l, name=attrs['hid'], type=IdentifierType.iso.value)\n\n create_identifier(\n gl_names.get(l.name),\n l,\n name=l.name,\n description=gl_name.description,\n type=gl_name.type)\n\n if hname:\n l.update_jsondata(hname=hname)\n\n if replacement:\n DBSession.add(Superseded(\n languoid_pk=l.pk,\n replacement_pk=replacement,\n relation='classification update'))\n\n DBSession.flush()\n\n recreate_treeclosure()\n\n\nif __name__ == '__main__':\n main(get_args())\n","sub_path":"glottolog3/scripts/import_tree.py","file_name":"import_tree.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"69734841","text":"import scrapy\nfrom demo.items import DmozItem\nclass DmozSpider(scrapy.spiders.Spider):\n name = \"dmoz\"\n allowed_domains = [\"dmoz.org\"]\n start_urls = [\n \"https://scrapy-chs.readthedocs.io/zh_CN/latest/intro/tutorial.html#id2\"\n ]\n\n def parse(self, response):\n i=0\n for sel in response.xpath('//ul/li'):\n item = DmozItem()\n item['title'] = sel.xpath('a/text()').extract()\n i+=1\n print(i)\n print(item[\"title\"]);\n item['link'] = sel.xpath('a/@href').extract()\n item['desc'] = sel.xpath('text()').extract()\n yield item","sub_path":"demo/demo/spiders/DemoSpider.py","file_name":"DemoSpider.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"474002181","text":"import json\nimport os\nimport sys\nfrom gooey import Gooey, GooeyParser\nfrom argparse import ArgumentParser\n\n\ndef load_json(filename):\n data = {}\n try:\n with open(filename, 'r', encoding=\"utf-8\") as infile:\n data = json.load(infile)\n except FileNotFoundError:\n print(\"file {} not found\".format(os.path.abspath(filename)))\n\n return data\n\n\ndef save_json(filename, data):\n try:\n with open(filename, 'w', encoding=\"utf-8\") as outfile:\n json.dump(data, outfile, indent=4)\n except FileNotFoundError:\n print(\"file {} not found\".format(os.path.abspath(filename)))\n\n\ndef replace_values(json_data, mapping, keys, path=''):\n for k in json_data:\n e = json_data[k]\n p = path + '.' + k\n \n # first check id we must replace the entry\n if p in keys:\n if json_data[k] in mapping:\n json_data[k] = mapping[e]\n else:\n print(\"no mapping found for {} read '{}'\".format(e, p))\n \n if type(e) is dict:\n replace_values(json_data[k], mapping, keys, p)\n \n if type(e) is list:\n for i in e:\n replace_values(i, mapping, keys, p)\n\n\ndef add_arguments(parser):\n parser.add_argument(\n '-p',\n '--project',\n action=\"store\",\n metavar=\"Project File\",\n required=True,\n widget=\"FileChooser\",\n help=\"Select the general project json-file with translation keys.\"\n )\n parser.add_argument(\n '-t',\n '--translation',\n action=\"store\",\n metavar=\"Translation File\",\n required=True,\n widget=\"FileChooser\",\n help=\"Select the translation file (json with key/value pairs).\"\n )\n parser.add_argument(\n '-k',\n '--key-list',\n action=\"store\",\n metavar=\"List of Replaceable Paths\",\n required=False,\n default=\".canvas.name\",\n help=\"Comma separated list of keys which can be translated\"\n )\n\n@Gooey(\n program_name=\"Json-Translator\",\n optional_cols=1\n)\ndef interview_arguments():\n parser = GooeyParser(\n description=\"Replace all keys from translation file find in given json-path.\"\n )\n\n pg = parser.add_argument_group()\n add_arguments(pg)\n return parser.parse_args()\n\n\ndef parse_arguments():\n parser = ArgumentParser(\n description='Replace all keys from translation file find in given json-path.')\n\n add_arguments(parser)\n return parser.parse_args()\n\n\ndef main():\n\n if 1 < len(sys.argv) and \"--nogui\" == sys.argv[1]:\n args = parse_arguments()\n else:\n args = interview_arguments()\n\n project_file = args.project\n project_name = os.path.splitext(os.path.basename(project_file))[0]\n\n translation_file = args.translation\n translation_name = os.path.splitext(os.path.basename(translation_file))[0]\n\n basepath = os.path.dirname(project_file)\n result = basepath + \"/\" + project_name + \"-\" + translation_name + \".json\"\n\n key_list = args.key_list.split(',')\n\n mapping = load_json(translation_file)\n data = load_json(project_file)\n\n print(\"load mapping {} with {} entries\".format(translation_file, len(mapping)))\n print(\"key list contains {} entries\".format(len(key_list)))\n replace_values(data, mapping, key_list)\n\n save_json(result, data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"494200018","text":"import argparse\nimport csv\nimport json\nimport os\nimport re\nimport zipfile\nfrom collections import OrderedDict\nfrom configparser import ConfigParser\nfrom functools import lru_cache\n\nfrom PIL import Image\n\nfrom scrappers.apps.config.http.engine import RequestsManager\nfrom scrappers.apps.config.logs import default\nfrom scrappers.apps.images.mixins import ScrapperMixins\n\n\nclass ImageDownloader(ScrapperMixins, RequestsManager):\n \"\"\"This class is the base class to send requests\n to the SawFirst website.\n\n Description\n -----------\n\n It creates a requests and scraps all the images from a given page then\n downloads the images on a local or cloud storage.\n\n Parameters\n ----------\n\n celebrity_name: accepts a celebrity name to use in order to use\n either in a file or some kind of request.\n\n div_id: allows you to change the start searching point in\n order to scrap the different images of the page.\n\n headers: add additional headers to the request\n \"\"\"\n app_name = 'image_downloader'\n memory = OrderedDict(csv=[], json=[], html=[])\n\n def __init__(self, current_file, url=None, \n html_path=None, download_dir=None):\n self.current_dir = os.path.dirname(current_file)\n self.logger = default(\n self.__class__.__name__, \n logfile_name=os.path.join(self.current_dir, 'scrappers.log')\n )\n self.url = url\n self.html_path = html_path\n\n path, _, files = list(os.walk(os.path.dirname(current_file)))[0]\n\n self.memory.update({'path': path})\n for item in files:\n self._sort_files(item)\n\n state = self._construct_download_dir(download_dir=download_dir)\n if not state:\n raise FileExistsError('Could not create or find a download directory for your application')\n\n def _sort_files(self, item, base_path=None):\n if '.':\n _, extension = item.split('.', 1)\n try:\n self.memory[extension].append(item)\n except KeyError:\n pass\n else:\n return False\n\n @lru_cache(maxsize=1)\n def load_images(self):\n loaded_images = []\n base, _, images = list(os.walk(self._scrappers_dir))[0]\n for image in images:\n full_path = os.path.join(base, image)\n if full_path.endswith('jpg'):\n loaded_images.append(\n (\n full_path,\n Image.open(full_path)\n )\n )\n return loaded_images\n\n\n @lru_cache(maxsize=1)\n def load(self, filename, run_request=False, limit=0):\n extension, _, full_path = self.lookup(filename, just_path=False)\n with open(full_path, 'r') as f:\n if extension == 'csv':\n reader = csv.reader(f)\n self.urls = list(reader)\n self.urls.pop(0)\n self.urls = [url[1] for url in self.urls]\n\n if extension == 'json':\n data = json.load(f)\n for item in data['gallery']:\n self.urls.append(item['link'])\n\n if run_request:\n self._download_images(limit=limit)\n return self.urls\n\n def save_gallery(self, filename, depth=3, f=None):\n \"\"\"\n Save the links and their parents in an HTML file\n \"\"\" \n sample_tag = self.raw_tags[0]\n parents = sample_tag.find_parents()\n \n if f is not None:\n parent = None\n for item in parents:\n parent = item.parent()[0]\n if 'class' in parent.attrs or 'id' in parent.attrs:\n for _, values in parent.attrs.items():\n if f in values:\n parent = item\n break\n else:\n parent = parents[depth]\n \n with open(os.path.join(self.current_dir, filename), 'w') as f:\n f.write(str(parent))\n\n def save_links(self, filename=None, file_type='csv',\n headers=[], with_index=False):\n if filename is not None:\n filename = f'{filename}.{file_type}'\n\n full_path = os.path.join(self.current_dir, filename) \n\n with open(full_path, 'w', newline='') as f:\n if file_type == 'csv':\n writer = csv.writer(f)\n if with_index:\n if not 'index' in headers:\n headers.insert(0, 'index')\n new_urls = [[index, url]\n for index, url in enumerate(self.urls)]\n else:\n new_urls = [[url] for url in self.urls]\n if headers:\n new_urls.insert(0, headers)\n writer.writerows(new_urls)\n print(f'Saved {len(self.urls)} images in {full_path}')\n\n if file_type == 'json':\n base = {\n 'gallery': []\n }\n for index, link in enumerate(self.urls):\n base['gallery'].append(\n {'index': index, 'link': link}\n )\n json.dump(base, f, indent=4)\n\n def _construct_download_dir(self, download_dir=None, using=None):\n if download_dir is None:\n path = os.path.join(\n os.environ.get('HOMEDRIVE'),\n os.environ.get('HOMEPATH')\n )\n images_dir = os.path.join(path, 'Pictures')\n self.logger.info(f'Created download directory in {path}')\n self.images_dir = images_dir\n return True\n else:\n if using is not None:\n pass\n else:\n self.images_dir = download_dir\n return True\n return False\n\n def lookup(self, filename, just_path=False):\n \"\"\"\n Result\n ------\n\n (key, filename.ext, /path/to/file.ext)\n \"\"\"\n if '.' not in filename:\n raise ValueError('Please specify a file with an extension')\n\n found = False\n\n for key, values in self.memory.items():\n if filename in values:\n found = True\n break\n \n if found:\n full_path = os.path.join(self.memory['path'], values[values.index(filename)])\n self.html_path = full_path\n if just_path:\n return full_path\n return (key, values[values.index(filename)], full_path)\n else:\n return found\n\n def _download_images(self, limit=0):\n # responses = self.get(self.urls)\n responses = self.threaded_get(*self.urls)\n path_exists = os.path.exists(self._scrappers_dir)\n if not path_exists:\n os.mkdir(self._scrappers_dir)\n\n for index, response in enumerate(responses, start=1):\n if limit != 0:\n if index == limit:\n break\n if response.status_code == 200:\n new_name = self.create_name(index)\n full_path = os.path.join(self._scrappers_dir, f'{new_name}.jpg')\n with open(full_path, 'wb') as f:\n for data in response.iter_content(chunk_size=1024):\n if not data:\n break\n f.write(data)\n self.saved_images.append(full_path)\n # self.saved_images.append(\n # Image.load(os.path.join(self._scrappers_dir, name))\n # )\n\n self.logger.warning(f'downloaded {len(self.urls)} images to {self._scrappers_dir}')\n \n def build(self, f, limit=0, regex=None, replace_with=None, pop_value:int=None, zip_files=False):\n if self.html_path is not None:\n soup = self.lazy_request(path=self.html_path)\n \n if self.url is not None:\n soup = self.get_html(*(self.url))\n\n if self.html_path is None and self.url is None:\n raise ValueError('You need to provide either a URL or an HTML path to use for parsing the images. You can also use the .lookup() method.')\n \n try:\n images = soup.find_all('img')\n except Exception:\n raise\n else:\n for image in images:\n url = image['src']\n if f in url and url.endswith('jpg'):\n self.raw_tags.append(image)\n if regex:\n if replace_with is None:\n replace_with = '.jpg'\n self.urls.append(\n self.replace_with_regex(url, regex, replace_with)\n )\n else:\n self.urls.append(url)\n if pop_value is not None:\n self.urls.pop(pop_value)\n print(f'Found {len(self.urls)} images')\n # self._download_images(limit=limit)\n\n if zip_files is not None:\n images = self.load_images()\n with zipfile.ZipFile(os.path.join(self._scrappers_dir, 'images.zip'), mode='w') as z:\n for image in images:\n with open(image[0], 'rb') as img:\n z.write(img.read())\n","sub_path":"apps/images/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"631561099","text":"#!/usr/bin/env python3\n\nimport os\nimport requests\nfrom datetime import datetime as dt\n\nfrom assistant.utils import thread\n\nAPIKEY_WEATHER = os.environ[\"APIKEY_WEATHER\"]\n\n\nINTERVALS = {\n \"north east\": (22.5, 67.5),\n \"east\": (67.5, 112.5),\n \"south east\": (112.5, 157.5),\n \"south\": (157.5, 202.5),\n \"south west\": (202.5, 247.5),\n \"west\": (247.5, 292.5),\n \"north west\": (292.5, 337.5),\n}\n\n\ndef direction(degree):\n \"\"\"Derive side of the world from a degree.\"\"\"\n\n def belongs(n, interval):\n return True if interval[0] < n <= interval[1] else False\n\n if not belongs(degree, (0, 360)):\n raise ValueError(f\"input degree {degree} does not belong [0, 360]\")\n\n for direction in INTERVALS:\n return direction if belongs(degree, INTERVALS[direction]) else \"north\"\n\n\nclass WeatherRecord(object):\n def __init__(self, r):\n statements = [\n \"self.temp = round(r['main']['temp'])\",\n \"self.temp_max = round(r['main']['temp_max'])\",\n \"self.temp_min = round(r['main']['temp_min'])\",\n \"self.pressure = int(r['main']['pressure'] * 0.75)\",\n \"self.humidity = r['main']['humidity']\",\n \"self.sunrise = None\",\n \"self.sunset = None\",\n \"self.conditions = [x['description'] for x in r['weather']]\",\n \"self.wind_deg = r['wind']['deg']\",\n \"self.wind_dir = direction(self.wind_deg)\",\n \"self.wind_speed = r['wind']['speed']\",\n \"self.dt = dt.utcfromtimestamp(r['dt'])\",\n ]\n\n for statement in statements:\n try:\n exec(statement)\n except Exception:\n variable = statement.split(\" = \")[0]\n exec(f\"{variable} = None\")\n # traceback.print_exc()\n\n\nclass Weather(WeatherRecord):\n def __init__(self, city=None, coordinates=None, zip=None):\n arguments = {}\n if city:\n arguments[\"q\"] = city\n self.city = city\n if coordinates:\n self.lan, self.lon = coordinates\n arguments[\"lat\"], arguments[\"lon\"] = coordinates\n if zip:\n self.zip = zip\n arguments[\"zip\"] = zip\n\n self.params = \"&\".join(f\"{key}={arguments[key]}\" for key in arguments)\n self.params += f\"&units=metric&APPID={APIKEY_WEATHER}\"\n thread((self.__current, self.__forecast), wait_to_finish=True)\n\n def __current(self):\n record = requests.get(\n f\"http://api.openweathermap.org/data/2.5/weather?{self.params}\"\n ).json()\n WeatherRecord.__init__(self, record)\n\n def __forecast(self):\n r = requests.get(\n f\"http://api.openweathermap.org/data/2.5/forecast?{self.params}\"\n ).json()\n records = r[\"list\"]\n r1 = WeatherRecord(records[0])\n self.forecasts = [[r1], [], [], [], [], []]\n count = 0\n for record in records[1:]:\n current = dt.utcfromtimestamp(record[\"dt\"])\n previous = self.forecasts[count][-1].dt\n if current.day != previous.day:\n count += 1\n self.forecasts[count].append(WeatherRecord(record))\n\n def __str__(self):\n conditions = \", \".join(self.conditions)\n return f\"\"\"\nTemperature:\n current {self.temp} °C\n max {self.temp_max} °C\n min {self.temp_min} °C\n\nConditions: {conditions}\n\nWind: {self.wind_speed} m/s, {self.wind_dir}\n\nPressure: {self.pressure} mmHg\n\nHumidity: {self.humidity} %\n\nSunrise: {self.sunrise}\n\nSunset: {self.sunset}\n\"\"\"\n\n def summary(self):\n if self.temp_max - self.temp_min >= 3:\n summary = f\"\"\"\n You can observe {self.conditions[0]} in {self.city} right now,\n the temperature varies between {self.temp_min} and {self.temp_max}\n and is currently {self.temp} degrees\"\"\"\n else:\n summary = f\"\"\"\n You can observe {self.conditions[0]} in {self.city} right now,\n the temperature is currently {self.temp} degrees\"\"\"\n return summary\n\n def tempSummary(self):\n return f\"The current temperature in {self.city} is {self.temp} degrees\"\n\n def fullSummary(self):\n if self.temp_max - self.temp_min >= 3:\n opts = f\"\"\"\n Current temperature in {self.city} is {self.temp} degrees,\n you can observe {self.conditions[0]}.\n The {self.wind_dir}ern wind's speed is {self.wind_speed}\n meters per second. Humidity is {self.humidity} %\"\"\"\n else:\n opts = f\"\"\"\n The temperature in {self.city} varies between\n {self.temp_min} and {self.temp_max} today and\n is currently {self.temp} degrees.\n You can observe {self.conditions[0]}.\n The {self.wind_dir}ern wind's speed is {self.wind_speed}\n meters per second. Humidity is {self.humidity} %\"\"\"\n return opts\n\n def max(self, days_ahead=0):\n return max([temp.temp for temp in self.forecasts[days_ahead]])\n\n def min(self, days_ahead=0, daily=True):\n if daily:\n return min([temp.temp for temp in self.forecasts[days_ahead]])\n else:\n return min(\n [temp.temp for temp in self.forecasts[days_ahead] if temp]\n )\n\n def aver(self, days_ahead=0):\n res = [temp.temp for temp in self.forecasts[days_ahead]]\n return sum(res) / len(res)\n\n def forecast(self, days_ahead=0, hour=12):\n self.forecasts[days_ahead][int(hour / 3)]\n","sub_path":"assistant/modules/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"451255285","text":"\"\"\"In this file, we test to ensure that the output of\nrun_code is as expected. The tests we do here\nare almost identical to those for check_syntax,\nfound in test_check_syntax.py\n\nWe also test to ensure that run_code does not accidently\nchange any existing error handling settings.\n\n\"\"\"\n\nimport friendly_traceback as friendly\n\n\ndef test_run_code():\n # set-up\n bad_code_syntax = \"True = 1\"\n bad_code_exec = \"a = b\" # Not a syntax error, but a NameError\n good_code = \"c = 1\"\n\n friendly.set_stream(\"capture\")\n original_level = friendly.get_level()\n installed = friendly.is_installed()\n # ----- end of set-up\n\n # When a SyntaxError is raised, run_code returns False\n\n assert not friendly.run_code(source=bad_code_syntax)\n result = friendly.get_output() # content is flushed\n assert \"Python exception\" in result\n assert \"SyntaxError\" in result\n\n assert not friendly.get_output() # confirm that content was flushed\n\n assert not friendly.run_code(source=bad_code_exec)\n result = friendly.get_output()\n assert \"Python exception\" in result\n assert \"NameError\" in result\n\n assert friendly.run_code(source=good_code)\n assert not friendly.get_output() # no new exceptions recorded\n\n try:\n exec(bad_code_syntax, {})\n except Exception:\n assert not friendly.get_output()\n\n # When friendly-traceback is not installed, a call to run_code\n # will end with level set to 0, which corresponds to normal Python\n # tracebacks\n friendly.uninstall()\n friendly.run_code(source=bad_code_syntax)\n assert friendly.get_level() == 0\n friendly.run_code(source=bad_code_syntax, level=4)\n assert friendly.get_level() == 0\n\n # When friendly-traceback is \"installed\", a call to run_code\n # leaves its level unchanged.\n friendly.install()\n\n friendly.set_level(3)\n friendly.run_code(source=bad_code_syntax)\n assert friendly.get_level() == 3\n friendly.run_code(source=bad_code_syntax, level=4)\n assert friendly.get_level() == 3\n\n # Clean up and restore for other tests\n friendly.get_output()\n friendly.set_stream(None)\n if installed:\n friendly.uninstall()\n friendly.set_level(original_level)\n\n\nif __name__ == '__main__':\n test_run_code()\n print(\"Success!\")\n","sub_path":"tests/unit/test_run_code.py","file_name":"test_run_code.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"412747293","text":"import math\nimport numpy as np\n\nclass Persona:\n def __init__(self,i, posx, posy, objx, objy, v, t_contagiado, fijo):\n # movement speed\n self.v=v\n # target position\n self.objx=objx\n self.objy=objy\n #ID and name\n self.indice=i\n self.nombre=\"Persona \"+str(i)\n #State: Susceptible, Infected or Retired\n self.infectado = False\n self.suceptible = True\n self.retirado = False\n #Current position\n self.posx = posx\n self.posy=posy\n #is it fixed (in quarantine)?\n self.fijo = fijo\n\n # displacement per iteration\n if self.fijo:\n\n self.deltax = 0\n self.deltay = 0\n else:\n self.deltax = (self.objx - self.posx) / self.v\n self.deltay = (self.objy - self.posy) / self.v\n #time in which the person was infected\n self.i_contagio=-1\n #time that the infection lasts, recover time\n self.t_contagiado = t_contagiado\n\n\n def __str__(self):\n return self.nombre+\" en posicin \"+str(self.posx)+\", \"+str(self.posy)\n\n def infectar(self,i):\n #infect\n self.infectado=True\n self.suceptible=False\n self.retirado = False\n self.i_contagio=i\n\n def retirar(self):\n #heal\n self.retirado=True\n self.suceptible=False\n self.infectado=False\n\n def set_objetivo(self,objx,objy):\n #this function is used to create a new target position\n self.objx=objx\n self.objy=objy\n if self.fijo:\n self.deltax = 0\n self.deltay=0\n else:\n self.deltax = (self.objx - self.posx) / self.v\n self.deltay = (self.objy - self.posy) / self.v\n print(\"Nuevo OBJ \", self.objx,self.objy,\" \",self.indice)\n\n def check_contagio(self,i):\n #this function is used to heal the person if the established infection time has passed\n if self.i_contagio>-1:\n if i-self.i_contagio>self.t_contagiado:\n self.retirar()\n\n\n def update_pos(self, n_posx, n_posy):\n #this funcion animates the movement\n if(n_posx==0 and n_posy==0):\n self.posx=self.posx+self.deltax\n self.posy=self.posy+self.deltay\n else:\n self.posx=n_posx\n self.posy=n_posy\n\n if abs(self.posx-self.objx)<3 and abs(self.posy-self.objy)<3:\n self.set_objetivo(np.random.random()*100, np.random.random()*100)\n if self.posx>100:\n self.posx=100\n if self.posy>100:\n self.posy=100\n if self.posx<0:\n self.posx=0\n if self.posy<0:\n self.posy=0\n\n def get_color(self):\n if self.infectado:\n return 'red'\n if self.suceptible:\n return 'blue'\n if self.retirado:\n return 'gray'\n\n def get_pos(self):\n return (self.posx,self.posy)\n\n def get_dist(self,x,y):\n #this funcion calculates the distance between this person an another.\n return math.sqrt(abs((self.posx-x)**2+(self.posy-y**2)))\n \n","sub_path":"persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"461985178","text":"import os\nimport re\nimport subprocess\nimport tarfile\nfrom datetime import datetime\nfrom itertools import chain\nfrom tempfile import TemporaryDirectory\n\nfrom pkgcore.ebuild.misc import sort_keywords\nfrom pkgcore.ebuild.repository import UnconfiguredTree\nfrom pkgcore.exceptions import PkgcoreException\nfrom snakeoil.demandload import demand_compile_regexp\nfrom snakeoil.klass import jit_attr\nfrom snakeoil.osutils import pjoin\nfrom snakeoil.strings import pluralism as _pl\n\nfrom .. import base, git, results, sources\nfrom ..log import logger\nfrom . import ExplicitlyEnabledCheck, GentooRepoCheck\n\ndemand_compile_regexp(\n 'ebuild_copyright_regex',\n r'^# Copyright (\\d\\d\\d\\d(-\\d\\d\\d\\d)?) .+')\n\n\nclass GitCommitsRepoSource(sources.RepoSource):\n \"\"\"Repository source for locally changed packages in git history.\n\n Parses git log history to determine packages with changes that\n haven't been pushed upstream yet.\n \"\"\"\n\n required_addons = (git.GitAddon,)\n\n def __init__(self, *args, git_addon):\n super().__init__(*args)\n self._repo = git_addon.commits_repo(git.GitChangedRepo)\n\n\nclass GitCommitsSource(sources.Source):\n \"\"\"Source for local commits in git history.\n\n Parses git log history to determine commits that haven't been pushed\n upstream yet.\n \"\"\"\n\n feed_type = base.commit_scope\n required_addons = (git.GitAddon,)\n\n def __init__(self, *args, git_addon):\n super().__init__(*args, source=git_addon.commits())\n\n\nclass OutdatedCopyright(results.VersionResult, results.Warning):\n \"\"\"Changed ebuild with outdated copyright.\"\"\"\n\n def __init__(self, year, line, **kwargs):\n super().__init__(**kwargs)\n self.year = year\n self.line = line\n\n @property\n def desc(self):\n return f'outdated copyright year {self.year!r}: {self.line!r}'\n\n\nclass BadCommitSummary(results.PackageResult, results.Warning):\n \"\"\"Local package commit with poorly formatted or unmatching commit summary.\n\n Git commit messages for packages should be formatted in the standardized\n fashion described in the devmanual [#]_. Specifically, a\n ``${CATEGORY}/${PN}:`` or ``${CATEGORY}/${P}:`` prefix should be used in\n the summary relating to the modified package.\n\n .. [#] https://devmanual.gentoo.org/ebuild-maintenance/git/#git-commit-message-format\n \"\"\"\n\n def __init__(self, error, summary, commit, **kwargs):\n super().__init__(**kwargs)\n self.error = error\n self.summary = summary\n self.commit = commit\n\n @property\n def desc(self):\n return f'commit {self.commit}, {self.error}: {self.summary!r}'\n\n\nclass DirectStableKeywords(results.VersionResult, results.Error):\n \"\"\"Newly committed ebuild with stable keywords.\"\"\"\n\n def __init__(self, keywords, **kwargs):\n super().__init__(**kwargs)\n self.keywords = tuple(keywords)\n\n @property\n def desc(self):\n return f'directly committed with stable keyword%s: [ %s ]' % (\n _pl(self.keywords), ', '.join(self.keywords))\n\n\nclass _DroppedKeywords(results.PackageResult):\n \"\"\"Unstable keywords dropped from package.\"\"\"\n\n _status = None\n\n def __init__(self, keywords, commit, **kwargs):\n super().__init__(**kwargs)\n self.keywords = tuple(keywords)\n self.commit = commit\n\n @property\n def desc(self):\n keywords = ', '.join(self.keywords)\n return (\n f'commit {self.commit} (or later) dropped {self._status} '\n f'keyword{_pl(self.keywords)}: [ {keywords} ]'\n )\n\n\nclass DroppedUnstableKeywords(_DroppedKeywords, results.Warning):\n \"\"\"Unstable keywords dropped from package.\"\"\"\n\n _status = 'unstable'\n\n\nclass DroppedStableKeywords(_DroppedKeywords, results.Error):\n \"\"\"Stable keywords dropped from package.\"\"\"\n\n _status = 'stable'\n\n\nclass DirectNoMaintainer(results.PackageResult, results.Error):\n \"\"\"Directly added, new package with no specified maintainer.\"\"\"\n\n @property\n def desc(self):\n return 'directly committed with no package maintainer'\n\n\nclass _RemovalRepo(UnconfiguredTree):\n \"\"\"Repository of removed packages stored in a temporary directory.\"\"\"\n\n def __init__(self, repo):\n self.__parent_repo = repo\n self.__tmpdir = TemporaryDirectory()\n self.__created = False\n repo_dir = self.__tmpdir.name\n\n # set up some basic repo files so pkgcore doesn't complain\n os.makedirs(pjoin(repo_dir, 'metadata'))\n with open(pjoin(repo_dir, 'metadata', 'layout.conf'), 'w') as f:\n f.write('masters =\\n')\n os.makedirs(pjoin(repo_dir, 'profiles'))\n with open(pjoin(repo_dir, 'profiles', 'repo_name'), 'w') as f:\n f.write('old-repo\\n')\n super().__init__(repo_dir)\n\n def __call__(self, pkgs):\n \"\"\"Update the repo with a given sequence of packages.\"\"\"\n self._populate(pkgs, eclasses=(not self.__created))\n if self.__created:\n # notify the repo object that new pkgs were added\n for pkg in pkgs:\n self.notify_add_package(pkg)\n self.__created = True\n return self\n\n def _populate(self, pkgs, eclasses=False):\n \"\"\"Populate the repo with a given sequence of historical packages.\"\"\"\n pkg = pkgs[0]\n commit = pkgs[0].commit\n\n paths = [pjoin(pkg.category, pkg.package)]\n if eclasses:\n paths.append('eclass')\n git_cmd = f\"git archive {commit}~1 {' '.join(paths)}\"\n\n old_files = subprocess.Popen(\n git_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n cwd=self.__parent_repo.location)\n with tarfile.open(mode='r|', fileobj=old_files.stdout) as tar:\n tar.extractall(path=self.location)\n if old_files.poll():\n error = old_files.stderr.read().decode().strip()\n raise PkgcoreException(error)\n\n def __del__(self):\n self.__tmpdir.cleanup()\n\n\nclass GitPkgCommitsCheck(GentooRepoCheck):\n \"\"\"Check unpushed git package commits for various issues.\"\"\"\n\n scope = base.package_scope\n _source = (sources.PackageRepoSource, (), (('source', GitCommitsRepoSource),))\n required_addons = (git.GitAddon,)\n known_results = frozenset([\n DirectStableKeywords, DirectNoMaintainer, BadCommitSummary,\n OutdatedCopyright, DroppedStableKeywords, DroppedUnstableKeywords,\n ])\n\n def __init__(self, *args, git_addon):\n super().__init__(*args)\n self.today = datetime.today()\n self.repo = self.options.target_repo\n self.valid_arches = self.options.target_repo.known_arches\n self._git_addon = git_addon\n\n @jit_attr\n def removal_repo(self):\n \"\"\"Create a repository of packages removed from git.\"\"\"\n return _RemovalRepo(self.repo)\n\n @jit_attr\n def added_repo(self):\n \"\"\"Create/load cached repo of packages added to git.\"\"\"\n return self._git_addon.cached_repo(git.GitAddedRepo)\n\n def removal_checks(self, removed):\n \"\"\"Check for issues due to package removals.\"\"\"\n pkg = removed[0]\n commit = removed[0].commit\n\n try:\n removal_repo = self.removal_repo(removed)\n except PkgcoreException as e:\n logger.warning('skipping git removal checks: %s', e)\n return\n\n old_keywords = set(chain.from_iterable(\n pkg.keywords for pkg in removal_repo.match(pkg.unversioned_atom)))\n new_keywords = set(chain.from_iterable(\n pkg.keywords for pkg in self.repo.match(pkg.unversioned_atom)))\n\n dropped_keywords = old_keywords - new_keywords\n dropped_stable_keywords = dropped_keywords & self.valid_arches\n dropped_unstable_keywords = set()\n for keyword in (x for x in dropped_keywords if x[0] == '~'):\n arch = keyword[1:]\n if arch in self.valid_arches and arch not in new_keywords:\n dropped_unstable_keywords.add(keyword)\n\n if dropped_stable_keywords:\n yield DroppedStableKeywords(\n sort_keywords(dropped_stable_keywords), commit, pkg=pkg)\n if dropped_unstable_keywords:\n yield DroppedUnstableKeywords(\n sort_keywords(dropped_unstable_keywords), commit, pkg=pkg)\n\n def feed(self, pkgset):\n removed = [pkg for pkg in pkgset if pkg.status == 'D']\n if removed:\n yield from self.removal_checks(removed)\n\n for git_pkg in pkgset:\n # check git commit summary formatting\n try:\n summary = git_pkg.message[0]\n except IndexError:\n summary = ''\n summary_prefix_re = rf'^({git_pkg.key}|{git_pkg.cpvstr}): '\n if not re.match(summary_prefix_re, summary):\n error = 'summary missing matching package prefix'\n yield BadCommitSummary(error, summary, git_pkg.commit, pkg=git_pkg)\n\n try:\n pkg = self.repo.match(git_pkg.versioned_atom)[0]\n except IndexError:\n # weird situation where an ebuild was locally committed and then removed\n return\n\n # check copyright on new/modified ebuilds\n try:\n line = next(pkg.ebuild.text_fileobj())\n except StopIteration:\n # empty ebuild, should be caught by other checks\n return\n copyright = ebuild_copyright_regex.match(line)\n if copyright:\n year = copyright.group(1).split('-')[-1]\n if int(year) < self.today.year:\n yield OutdatedCopyright(year, line.strip('\\n'), pkg=pkg)\n\n # checks for newly added ebuilds\n if git_pkg.status == 'A':\n # check for stable keywords\n stable_keywords = sorted(x for x in pkg.keywords if x[0] not in '~-')\n if stable_keywords:\n yield DirectStableKeywords(stable_keywords, pkg=pkg)\n\n # pkg was just added to the tree\n newly_added = not self.added_repo.match(git_pkg.unversioned_atom)\n\n # check for no maintainers\n if not pkg.maintainers and newly_added:\n yield DirectNoMaintainer(pkg=pkg)\n\n\nclass MissingSignOff(results.CommitResult, results.Error):\n \"\"\"Local commit with missing sign offs.\n\n Sign offs are required for commits as specified by GLEP 76 [#]_.\n\n .. [#] https://www.gentoo.org/glep/glep-0076.html#certificate-of-origin\n \"\"\"\n\n def __init__(self, missing_sign_offs, **kwargs):\n super().__init__(**kwargs)\n self.missing_sign_offs = missing_sign_offs\n\n @property\n def desc(self):\n sign_offs = ', '.join(self.missing_sign_offs)\n return (\n f'commit {self.commit}, '\n f'missing sign-off{_pl(self.missing_sign_offs)}: {sign_offs}'\n )\n\n\nclass GitCommitsCheck(GentooRepoCheck, ExplicitlyEnabledCheck):\n \"\"\"Check unpushed git commits for various issues.\"\"\"\n\n scope = base.commit_scope\n _source = GitCommitsSource\n known_results = frozenset([MissingSignOff])\n\n def feed(self, commit):\n # check for missing git sign offs\n sign_offs = {\n line[15:].strip() for line in commit.message\n if line.startswith('Signed-off-by: ')}\n required_sign_offs = {commit.author, commit.committer}\n missing_sign_offs = required_sign_offs - sign_offs\n if missing_sign_offs:\n yield MissingSignOff(tuple(sorted(missing_sign_offs)), commit=commit)\n","sub_path":"src/pkgcheck/checks/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":11562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"652171023","text":"from sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\nimport json\nimport re\n\nBase = declarative_base()\n\nclass UserDeviceMap(Base):\n\n __tablename__ = 'user_device_map'\n\n id = Column(Integer, primary_key=True)\n device_id = Column(String)\n user_id = Column(String)\n first_active = Column(DATETIME)\n last_active = Column(DATETIME)\n\n## UserDevicePair = (user_id, device_id)\n# def send2DB(UserDevicePair, engine):\n# # Initialize connect:\n# # Create DBSession object:\n# DBSession = sessionmaker(bind=engine)\n# session = DBSession()\n# new_mapping = UserDeviceMap(user_id=UserDevicePair[0], device_id=UserDevicePair[1],\n# first_active=UserDevicePair[2], last_active=UserDevicePair[3])\n# session.add(new_mapping)\n# session.commit()\n# session.close()\n ##add one week to the record's send_at attribute\n\ndef main():\n valid_id = re.compile('[0-9A-Za-z/-]{36,36}|[0-9a-z]{12,16}')\n\n with open('UserDeviceMap.json', 'r', encoding='utf-8') as f:\n reader = f.readlines()\n f.close()\n mapSet = json.loads(reader[0])\n\n engine = create_engine('mysql+pymysql://HSDBADMIN:NestiaHSPWD@hsdb.cd29ypfepkmi.ap-southeast-1.rds.amazonaws.com:3306/notification?charset=utf8mb4')\n DBSession = sessionmaker(bind=engine)\n session = DBSession()\n for device_id in mapSet.keys():\n if valid_id.search(device_id) or device_id == 'None':\n user_id = ','.join(mapSet[device_id][0])\n UserDevicePair = (user_id, device_id, mapSet[device_id][1], mapSet[device_id][2])\n new_mapping = UserDeviceMap(user_id=UserDevicePair[0], device_id=UserDevicePair[1],\n first_active=UserDevicePair[2], last_active=UserDevicePair[3])\n session.add(new_mapping)\n session.commit()\n print('Sending successful')\n session.close()\n\nmain()\n\n","sub_path":"src/device_user_pair/src/send2DB.py","file_name":"send2DB.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"181078482","text":"\"\"\"\nfuocore.daemon.handlers.helper\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n良好的用文字展示一个对象\n\n展示的时候需要注意以下几点:\n1. 让 awk、grep 等 shell 工具容易处理\n\nTODO: 让代码长得更好看\n\"\"\"\n\n\ndef show_song(song, brief=False):\n artists = song.artists or []\n artists_name = ','.join([artist.name for artist in artists])\n if song.album is not None:\n album_name = song.album.name\n album_uri = str(song.album)\n else:\n album_name = 'Unknown'\n album_uri = ''\n if brief:\n s = '{song}\\t#{title}-{artists_name}-{album_name}'.format(\n song=song,\n title=song.title,\n artists_name=artists_name,\n album_name=album_name)\n return s\n artists_uri = ','.join(str(artist) for artist in artists)\n msgs = (\n 'provider {}'.format(song.source),\n 'uri {}'.format(str(song)),\n 'title {}'.format(song.title),\n 'duration {}'.format(song.duration),\n 'url {}'.format(song.url),\n 'artists {}\\t#{}'.format(artists_uri, artists_name),\n 'album {}\\t#{}'.format(album_uri, album_name),\n )\n return '\\n'.join(msgs)\n\n\ndef show_songs(songs):\n return '\\n'.join([show_song(song, brief=True) for song in songs])\n\n\ndef show_artist(artist):\n msgs = [\n 'provider {}'.format(artist.source),\n 'identifier {}'.format(artist.identifier),\n 'name {}'.format(artist.name),\n ]\n if artist.songs:\n songs_header = ['songs::\\n']\n songs = ['\\t' + each for each in show_songs(artist.songs).split('\\n')]\n msgs += songs_header\n msgs += songs\n return '\\n'.join(msgs)\n\n\ndef show_album(album, brief=False):\n msgs = [\n 'provider {}'.format(album.source),\n 'identifier {}'.format(album.identifier),\n 'name {}'.format(album.name),\n ]\n if album.artists is not None:\n artists = album.artists\n artists_id = ','.join([str(artist.identifier) for artist in artists])\n artists_name = ','.join([artist.name for artist in artists])\n msgs_artists = ['artists {}\\t#{}'.format(artists_id, artists_name)]\n msgs += msgs_artists\n if not brief:\n msgs_songs_header = ['songs::\\n']\n msgs_songs = ['\\t' + each for each in show_songs(album.songs).split('\\n')]\n msgs += msgs_songs_header\n msgs += msgs_songs\n return '\\n'.join(msgs)\n\n\ndef show_playlist(playlist, brief=False):\n if brief:\n content = '{playlist}\\t#{name}'.format(\n playlist=playlist,\n name=playlist.name)\n else:\n parts = [\n 'name {}'.format(playlist.name),\n 'songs::\\n',\n ]\n parts += ['\\t' + show_song(song, brief=True) for song in playlist.songs]\n content = '\\n'.join(parts)\n return content\n\n\ndef show_user(user):\n parts = [\n 'name {}'.format(user.name),\n 'playlists::\\n',\n ]\n parts += ['\\t' + show_playlist(p, brief=True) for p in user.playlists]\n return '\\n'.join(parts)\n","sub_path":"fuocore/protocol/handlers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"581872813","text":"import os\nimport struct\nimport datetime\nimport subprocess\nimport time\n\nimport pandas\n\nfrom config import config\nfrom util import pylinuxauto, util\nfrom util.log import logger\n\n\ndef basic_info(filepath):\n \"\"\"\n struct TdxSymbolMap {\n char symbol[6]; // 6 digits\n char dummy1[18]\n char name[8]; // 4 characters in GB2312\n char dummy2[218];\n }\n \"\"\"\n infos = []\n with open(filepath, 'rb') as f:\n # file_object_path = 'D:/new_tdx/quote/sh/' + name +'.csv'\n # file_object = open(file_object_path, 'w+')\n\n f.seek(50)\n i = 0\n while True:\n line = f.read(314)\n if not line:\n break\n code = line[:6].decode()\n # name = line[23:31]\n name = line[23:55]\n name = name.decode('gbk')\n name = name.strip(b'\\x00'.decode())\n i += 1\n print(i, code, name)\n infos.append((code, name))\n\n return infos\n\n\ndef parse_quote(filepath, start_date=None, end_date=None):\n code = os.path.basename(filepath)[2:-4]\n quote = []\n with open(filepath, 'rb') as f:\n while True:\n stock_date = f.read(4)\n stock_open = f.read(4)\n stock_high = f.read(4)\n stock_low = f.read(4)\n stock_close = f.read(4)\n stock_amount = f.read(4)\n stock_vol = f.read(4)\n stock_reservation = f.read(4) # date,open,high,low,close,amount,vol,reservation\n if not stock_date:\n break\n # 4字节如20091229\n stock_date = struct.unpack(\"l\", stock_date)\n # 开盘价*100\n stock_open = struct.unpack(\"l\", stock_open)\n # 最高价*100\n stock_high = struct.unpack(\"l\", stock_high)\n # 最低价*100\n stock_low = struct.unpack(\"l\", stock_low)\n # 收盘价*100\n stock_close = struct.unpack(\"l\", stock_close)\n # 成交额\n stock_amount = struct.unpack(\"f\", stock_amount)\n # 成交量\n stock_vol = struct.unpack(\"l\", stock_vol)\n # 保留值\n stock_reservation = struct.unpack(\"l\", stock_reservation)\n # 格式化日期\n date_format = datetime.datetime.strptime(str(stock_date[0]), '%Y%M%d')\n\n if start_date and date_format.date() < start_date:\n continue\n if end_date and date_format.date() >= end_date:\n continue\n\n row = (code, date_format.strftime('%Y-%M-%d'), str(stock_open[0] / 100), str(\n stock_high[0] / 100.0), str(stock_low[0] / 100.0), str(\n stock_close[0] / 100.0), str(stock_amount[0]), str(stock_vol[0]))\n quote.append(row)\n\n df = pandas.DataFrame(quote, columns=['code', 'trade_date', 'open', 'high', 'low', 'close', 'amount', 'volume'])\n return df\n\n\ndef download_quote():\n # now = datetime.datetime.now()\n # if now.hour < 15:\n # return\n\n if util.get_pid_by_exec('tdxw.exe') < 0:\n logger.info('tdx is stopped, start...')\n subprocess.Popen(['playonlinux', '--run', 'tdxw'])\n\n tdx_window_name = config.tdx_window_name\n tdx_version = 'V7.56'\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n if not handle:\n while not handle:\n time.sleep(1)\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n time.sleep(10)\n logger.info('tdx is running')\n\n name = pylinuxauto.get_window_name(handle)\n if name[-5:] == tdx_version:\n # 登录\n logger.info('tdx login...')\n pylinuxauto.send_key('Return')\n while name[-5:] == tdx_version:\n handle = pylinuxauto.search_window_handle(tdx_window_name)\n name = pylinuxauto.get_window_name(handle)\n time.sleep(1)\n time.sleep(10)\n logger.info('tdx login succeed')\n\n pylinuxauto.active_window_by_name(tdx_window_name)\n\n # 方案一\n pylinuxauto.send_key('alt+F4')\n time.sleep(1)\n pylinuxauto.send_key('Return')\n time.sleep(1)\n pylinuxauto.send_key('Return')\n\n while util.get_pid_by_exec('tdxw.exe') > 0:\n time.sleep(5)\n\n logger.info('tdx quote is downloaded')\n\n return\n\n # 方案二\n # if pylinuxauto.has_popup('tdx'):\n # pylinuxauto.close_popup()\n #\n # pos_option = ('1562', '19')\n # pos_download = ('1625', '240')\n # pylinuxauto.mouse_move(pos_option)\n # time.sleep(0.3)\n # pylinuxauto.click_left()\n # time.sleep(0.3)\n # pylinuxauto.mouse_move(pos_download)\n # pylinuxauto.click_left()\n # time.sleep(0.3)\n # pylinuxauto.send_key('space')\n # time.sleep(0.3)\n # pylinuxauto.send_key('Return')\n #\n # while pylinuxauto.has_popup('tdx'):\n # time.sleep(5)\n","sub_path":"acquisition/quote_tdx.py","file_name":"quote_tdx.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"490714267","text":"import os\nimport wave\nimport time\nimport pickle\nimport sounddevice as sd\nimport warnings\nimport numpy as np\nfrom sklearn import preprocessing\nfrom scipy.io.wavfile import read\nimport python_speech_features as mfcc\nfrom sklearn.mixture import GaussianMixture\nfrom scipy.io.wavfile import write\n\nwarnings.filterwarnings(\"ignore\")\n\ndef calculate_delta(array):\n rows, cols = array.shape\n #print(rows)\n #print(cols)\n deltas = np.zeros((rows, 20))\n N = 2\n for i in range(rows):\n index = []\n j = 1\n while j <= N:\n if i - j < 0:\n first = 0\n else:\n first = i - j\n if i + j > rows - 1:\n second = rows - 1\n else:\n second = i + j\n index.append((second, first))\n j += 1\n deltas[i] = (array[index[0][0]] - array[index[0][1]] + (2 * (array[index[1][0]] - array[index[1][1]]))) / 10\n return deltas\n\n\ndef extract_features(audio, rate):\n mfcc_feature = mfcc.mfcc(audio, rate, 0.025, 0.01, 20, nfft=2048, appendEnergy=True)\n mfcc_feature = preprocessing.scale(mfcc_feature)\n #print(mfcc_feature)\n delta = calculate_delta(mfcc_feature)\n combined = np.hstack((mfcc_feature, delta))\n return combined\n\n\ndef record_audio_train():\n Name = (input(\"Please Enter Your Name:\"))\n for count in range(5):\n FORMAT = \"float32\"\n CHANNELS = 1\n RATE = 16000\n RECORD_SECONDS = 2\n\n print(\"recording started\")\n \n recording = sd.rec(samplerate=RATE, channels=CHANNELS,\n dtype=FORMAT, frames=RATE*RECORD_SECONDS)\n sd.wait()\n\n print(\"recording stopped\")\n if not os.path.exists('training_set'):\n os.makedirs('training_set')\n OUTPUT_FILENAME = Name + \"-sample\" + str(count) + \".wav\"\n WAVE_OUTPUT_FILENAME = os.path.join(\"training_set\", OUTPUT_FILENAME)\n trainedfilelist = open(\"training_set_addition.txt\", 'a')\n trainedfilelist.write(OUTPUT_FILENAME + \"\\n\")\n write(WAVE_OUTPUT_FILENAME, RATE, recording)\n\n\n\ndef record_audio_test():\n FORMAT = \"float32\"\n CHANNELS = 1\n RATE = 16000\n RECORD_SECONDS = 2\n\n print(\"recording started\")\n\n recording = sd.rec(samplerate=RATE, channels=CHANNELS,\n dtype=FORMAT, frames=RATE*RECORD_SECONDS)\n sd.wait()\n \n print(\"recording stopped\")\n \n OUTPUT_FILENAME = \"sample.wav\"\n WAVE_OUTPUT_FILENAME = os.path.join(\"testing_set\", OUTPUT_FILENAME)\n write(WAVE_OUTPUT_FILENAME, RATE, recording)\n\ndef train_model():\n source = \"./training_set/\"\n if not os.path.exists('trained_models'):\n os.makedirs('trained_models')\n dest = \"./trained_models/\"\n train_file = \"./training_set_addition.txt\"\n file_paths = open(train_file, 'r')\n count = 1\n features = np.asarray(())\n for path in file_paths:\n path = path.strip()\n print(path)\n\n sr, audio = read(source + path)\n vector = extract_features(audio, sr)\n\n if features.size == 0:\n features = vector\n else:\n features = np.vstack((features, vector))\n\n if count == 5:\n gmm = GaussianMixture(n_components=20, max_iter=200, covariance_type='diag', n_init=3)\n gmm.fit(features)\n\n # dumping the trained gaussian model\n picklefile = path.split(\"-\")[0] + \".gmm\"\n pickle.dump(gmm, open(dest + picklefile, 'wb'))\n print('+ modeling completed for speaker:', picklefile, \" with data point = \", features.shape)\n features = np.asarray(())\n count = 0\n count = count + 1\n\ndef test_model(audio_data, sr):\n modelpath = \"./trained_models/\"\n\n gmm_files = [os.path.join(modelpath, fname) for fname in os.listdir(modelpath) if fname.endswith('.gmm')]\n\n models = [pickle.load(open(fname, 'rb')) for fname in gmm_files]\n speakers = [fname.split(\"\\\\\")[-1].split(\".gmm\")[0] for fname in gmm_files]\n \n vector = extract_features(audio_data, sr)\n\n log_likelihood = np.zeros(len(models))\n\n for i in range(len(models)):\n gmm = models[i]\n scores = np.array(gmm.score(vector))\n log_likelihood[i] = scores.sum()\n print(log_likelihood)\n winner = np.argmax(log_likelihood)\n if np.max(log_likelihood) > -35:\n print(\"\\tdetected as -\", speakers[winner].split(\"/\")[2])\n return True\n else:\n return False\n","sub_path":"speaker_recog.py","file_name":"speaker_recog.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"365172155","text":"import time\r\nimport urllib.request\r\nimport pylast\r\nimport discord\r\nfrom bs4 import BeautifulSoup\r\nfrom lyricsgenius import Genius\r\nimport lyricsgenius\r\nfrom pyowm import OWM\r\nimport config\r\nimport sqlite3\r\nimport asyncio\r\n\r\nAPI_KEY = config.API_KEY\r\nAPI_SECRET = config.API_SECRET\r\nOMV_KEY = config.OMV_KEY\r\nCLIENT_RUN = config.CLIENT_RUN\r\nLYRICS_KEY = config.LYRICS_KEY\r\n\r\n# Wer das liest ist blöd XD\r\n\r\nuserdict = {}\r\n\r\n# connection\r\nconnection = sqlite3.connect('reminder.db')\r\ncursor = connection.cursor()\r\n\r\n# table createn\r\ntry:\r\n creation = \"\"\"CREATE TABLE IF NOT EXISTS\r\n reminders(id INTEGER PRIMARY KEY, user_id INTEGER, reminder_text TEXT, reminder_time INTEGER, channel INTEGER, message_id INTEGER)\"\"\"\r\n cursor.execute(creation)\r\nexcept:\r\n pass\r\n\r\n\r\nclass MyClient(discord.Client):\r\n\r\n @staticmethod\r\n async def on_ready():\r\n print(\"Hallo I bim omnline :^)\")\r\n await get_reminder_startup()\r\n\r\n # Nachricht\r\n @staticmethod\r\n async def on_message(message):\r\n\r\n if message.author == client.user:\r\n return\r\n else:\r\n if message.content.startswith('+'):\r\n message.content = message.content[1:]\r\n if str(message.author) in userdict:\r\n timealt = userdict[str(message.author)]\r\n else:\r\n userdict[str(message.author)] = 10\r\n timealt = userdict[str(message.author)]\r\n dauer = time.time() - timealt\r\n\r\n if dauer > 5:\r\n await wiki(message)\r\n await wetter(message)\r\n await helpfunction(message)\r\n await reminder(message)\r\n #if message.channel.id == 608746970340786282:\r\n await lyrics(message)\r\n\r\n\r\nasync def reminder(message):\r\n if \"remindme\" in message.content:\r\n try:\r\n userdict[str(message.author)] = time.time()\r\n user_id = message.author.id\r\n split_message = message.content.split(\" \")\r\n if split_message[2] == \"seconds\" or split_message[2] == \"s\":\r\n reminder_time1 = round(time.time() + float(split_message[1]), 2)\r\n elif split_message[2] == \"minutes\" or split_message[2] == \"m\":\r\n reminder_time1 = round(time.time() + (float(split_message[1]) * 60), 2)\r\n elif split_message[2] == \"hours\" or split_message[2] == \"h\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 3600), 2)\r\n elif split_message[2] == \"days\" or split_message[2] == \"d\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 86400), 2)\r\n elif split_message[2] == \"weeks\" or split_message[2] == \"w\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 604800), 2)\r\n elif split_message[2] == \"months\":\r\n reminder_time1 = round(time.time() + (int(split_message[1]) * 2678400), 2)\r\n del split_message[:3]\r\n reminder_text = \" \".join(split_message)\r\n channel = message.channel.id\r\n sql = \"INSERT INTO reminders (user_id, reminder_text, reminder_time, channel, message_id) VALUES (?, ?, ?, ?, ?)\"\r\n val = (user_id, reminder_text, reminder_time1, channel, message.id)\r\n cursor.execute(sql, val)\r\n connection.commit()\r\n await message.add_reaction('\\N{THUMBS UP SIGN}')\r\n await wait_for_reminder(reminder_text, reminder_time1, message)\r\n except:\r\n await message.channel.send(\"Hm ne irgendwas gefällt mir daran nich. Nochmal? 🤷\")\r\n\r\n\r\nasync def get_reminder_startup():\r\n try:\r\n cursor.execute(\"SELECT * FROM reminders ORDER BY reminder_time ASC LIMIT 1\")\r\n result = cursor.fetchall()\r\n if result:\r\n id = result[0][0]\r\n user_id = result[0][1]\r\n reminder_text = result[0][2]\r\n reminder_time1 = result[0][3]\r\n channel_id = result[0][4]\r\n channel = client.get_channel(channel_id)\r\n message = await channel.fetch_message(id=result[0][5])\r\n await wait_for_reminder_startup(id, user_id, reminder_text, reminder_time1, channel_id, message)\r\n except:\r\n await message.channel.send(\r\n 'Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: get_reminder_startup()')\r\n\r\n\r\nasync def wait_for_reminder(reminder_text, reminder_time1, message):\r\n try:\r\n if (reminder_time1 - time.time()) < 0:\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE reminder_time=?\", (reminder_time1,))\r\n connection.commit()\r\n else:\r\n await asyncio.sleep(reminder_time1 - time.time())\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE reminder_time=?\", (reminder_time1,))\r\n connection.commit()\r\n except:\r\n await message.channel.send('Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: wait_for_reminder()')\r\n\r\n\r\nasync def wait_for_reminder_startup(id, user_id, reminder_text, reminder_time1, channel_id, message):\r\n try:\r\n channel = client.get_channel(channel_id)\r\n if (reminder_time1 - time.time()) < 0:\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE id=?\", (id,))\r\n connection.commit()\r\n else:\r\n await asyncio.sleep(reminder_time1 - time.time())\r\n await message.reply(\r\n \"Ich werde dich wissen lassen:\\n **{}**\".format(reminder_text), mention_author=True)\r\n cursor.execute(\"DELETE FROM reminders WHERE id=?\", (id,))\r\n connection.commit()\r\n await get_reminder_startup()\r\n except:\r\n await channel.send('Irgendwas klappt nedde. Scheiß Zicklaa zsamme gschwind. Hint: wait_for_reminder_startup()')\r\n\r\n\r\nasync def helpfunction(message):\r\n if message.content == \"help\":\r\n userdict[str(message.author)] = time.time()\r\n embed = discord.Embed(title='Help', description='Hier wird Ihnen geholfen!', color=0x00ff00)\r\n embed.add_field(name='+help', value=\"Öffnet das Hilfefenster \", inline=False)\r\n embed.add_field(name='+lyrics', value=\"Format: +lyrics (full/link) [USERNAME]\",\r\n inline=False)\r\n embed.add_field(name='+wetter', value=\"Format: +wetter [ORTNAME]\", inline=False)\r\n embed.add_field(name='+wiki', value=\"Format: +wiki [SUCHBEGRIFF]\", inline=False)\r\n embed.add_field(name='+remindme',\r\n value=\"Format: +remindme [ZAHL] [seconds or s/minutes or m/hours or h/days or d/months] [TEXT]\",\r\n inline=False)\r\n embed.set_author(name='Gott', icon_url='https://cdn.psychologytoday.com/sites'\r\n '/default/files/field_blog_entry_images/God_the_Father.jpg')\r\n await message.channel.send(embed=embed)\r\n\r\n\r\nasync def wiki(message):\r\n try:\r\n if message.content.startswith('wiki'):\r\n userdict[str(message.author)] = time.time()\r\n wiki1 = message.content.replace('wiki ', '')\r\n wiki2 = wiki1.replace(' ', '_')\r\n url = 'https://de.wikipedia.org/wiki/' + wiki2.title()\r\n page = urllib.request.urlopen(url)\r\n soup = BeautifulSoup(page, \"html.parser\")\r\n embed = discord.Embed(title=wiki1.title(), url=url, color=0x00ff00)\r\n start = soup('p')\r\n x = 0\r\n text2 = \"\"\r\n for i in start:\r\n t = str(i.getText())\r\n if len(t) > 200:\r\n text = str(i.getText())\r\n text2 = text2 + text\r\n x = x + 1\r\n if x == 2:\r\n break\r\n text2 = (text2[:1020] + '...') if len(text2) > 1024 else text2\r\n text2 = text2.replace('[1]', '').replace('[2]', '').replace('[3]', '').replace('[4]', '') \\\r\n .replace('[5]', '').replace('[6]', '').replace('[7]', '') \\\r\n .replace('[8]', '').replace('[9]', '').replace('[10]', '')\r\n embed.add_field(name=\"Beschreibung\", value=text2, inline=False)\r\n\r\n image_tag = soup.findAll('img')\r\n for bild in image_tag:\r\n bild_url = 'https:' + bild.get('src')\r\n if bild_url == 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Disambig-dark.svg/25px' \\\r\n '-Disambig-dark.svg.png' or bild_url == 'https://upload.wikimedia.org/wikipedia/c' \\\r\n 'ommons/thumb/f/f3/Photo-request.svg/40px-P' \\\r\n 'hoto-request.svg.png' or \\\r\n bild_url == 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Qsicon_lesenswert.' \\\r\n 'svg/15px-Qsicon_lesenswert.svg.png' or bild_url == 'https://upload.wikimedia.' \\\r\n 'org/wikipedia/commons/thumb' \\\r\n '/a/a1/Qsicon_gesprochen.svg/' \\\r\n '15px-Qsicon_gesprochen.' \\\r\n 'svg.png' or bild_url == \\\r\n 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/' \\\r\n 'Wiktfavicon_en.svg/16px-Wiktfavicon_en.svg.png':\r\n pass\r\n else:\r\n bild_url = 'https:' + bild.get('src')\r\n embed.set_thumbnail(url=bild_url)\r\n break\r\n await message.channel.send(embed=embed)\r\n except:\r\n if message.content.startswith('wiki'):\r\n userdict[str(message.author)] = time.time()\r\n wiki1 = message.content.replace('wiki ', '')\r\n wiki2 = wiki1.replace(' ', '_')\r\n wiki22 = wiki2.title()\r\n url = 'https://de.wikipedia.org/wiki/' + wiki22\r\n await message.channel.send('Jibtet nit. Probier doch mal selber: ' + url)\r\n\r\n\r\nasync def lyrics(message):\r\n if message.content.startswith('lyrics'):\r\n userdict[str(message.author)] = time.time()\r\n if message.content == 'lyrics':\r\n await message.channel.send('Format: \"+lyrics (full/link) [USERNAME]\"')\r\n return\r\n if message.content == 'lyrics full' or message.content == 'lyrics link':\r\n await message.channel.send('Ein Username wäre ganz hilfreich, retard.')\r\n return\r\n username = message.content.replace('lyrics full ', '').replace('lyrics link ', '')\r\n wort = message.content.replace('lyrics ', '')\r\n try:\r\n network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)\r\n user = network.get_user(username)\r\n except:\r\n await message.channel.send('User nit gefunden.')\r\n return\r\n if wort.startswith('full'):\r\n try:\r\n lied = user.get_now_playing()\r\n seconds = (lied.get_duration() / 1000) % 60\r\n seconds = int(seconds)\r\n minutes = (lied.get_duration() / (1000 * 60)) % 60\r\n minutes = int(minutes)\r\n if seconds < 10:\r\n seconds = \"0\" + str(seconds)\r\n\r\n artisturl = 'https://www.last.fm/de/music/' + str(lied.get_artist()).replace(' ', '+')\r\n songurl = artisturl + '/_/' + str(lied.get_name()).replace(' ', '+').replace('/', '%2F')\r\n name = str('[' + str(lied.get_name()) + '](' + str(songurl) + ')')\r\n artist = str('[' + str(lied.get_artist()) + '](' + str(artisturl) + ')')\r\n\r\n embed = discord.Embed(title='', color=1917791)\r\n\r\n if user.get_image() is not None:\r\n embed.set_author(name=username, icon_url=user.get_image(),\r\n url='https://www.last.fm/user/' + username)\r\n else:\r\n embed.set_author(name=username, url='https://www.last.fm/user/' + username)\r\n\r\n embed.set_thumbnail(url=str(lied.get_cover_image()))\r\n embed.add_field(name='Titel', value=name)\r\n album = str(lied.get_album())\r\n album = album.replace(str(lied.get_artist()), '').replace(' - ', '')\r\n embed.add_field(name='Artist', value=artist, inline=True)\r\n footer = 'Album: ' + album + ' | ' + 'Duration: ' \\\r\n + str(minutes) + ':' + str(seconds) + ' | ' + 'Plays: ' + str(lied.get_playcount())\r\n embed.set_footer(text=footer)\r\n try:\r\n genius = lyricsgenius.Genius(LYRICS_KEY)\r\n text = genius.search_song(title=str(lied.get_name()), artist=str(lied.get_artist()))\r\n gesamter_text = str(text.lyrics).replace('EmbedShare URLCopyEmbedCopy', '')[0:5500]\r\n while gesamter_text != \"\":\r\n embed.add_field(name='Fortsetzung', value=(gesamter_text[0:1020]), inline=False)\r\n gesamter_text = gesamter_text[1020:]\r\n except:\r\n await message.channel.send(\r\n 'Irgendwas is schiefgelaufen lol. Vielleicht ist der Songtext länger als Discord zulässt?')\r\n\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send('Dieser User hört gerade nix.')\r\n elif wort.startswith('link'):\r\n try:\r\n lied = user.get_now_playing()\r\n seconds = (lied.get_duration() / 1000) % 60\r\n seconds = int(seconds)\r\n minutes = (lied.get_duration() / (1000 * 60)) % 60\r\n minutes = int(minutes)\r\n if seconds < 10:\r\n seconds = \"0\" + str(seconds)\r\n\r\n artisturl = 'https://www.last.fm/de/music/' + str(lied.get_artist()).replace(' ', '+')\r\n songurl = artisturl + '/_/' + str(lied.get_name()).replace(' ', '+').replace('/', '%2F')\r\n name = str('[' + str(lied.get_name()) + '](' + str(songurl) + ')')\r\n artist = str('[' + str(lied.get_artist()) + '](' + str(artisturl) + ')')\r\n embed = discord.Embed(title='', color=1917791)\r\n\r\n if user.get_image() is not None:\r\n embed.set_author(name=username, icon_url=user.get_image(),\r\n url='https://www.last.fm/user/' + username)\r\n else:\r\n embed.set_author(name=username, url='https://www.last.fm/user/' + username)\r\n\r\n embed.set_thumbnail(url=str(lied.get_cover_image()))\r\n embed.add_field(name='Titel', value=name)\r\n album = str(lied.get_album())\r\n album = album.replace(str(lied.get_artist()), '').replace(' - ', '')\r\n embed.add_field(name='Artist', value=artist, inline=True)\r\n footer = 'Album: ' + album + ' | ' + 'Duration: ' \\\r\n + str(minutes) + ':' + str(seconds) + ' | ' + 'Plays: ' + str(lied.get_playcount())\r\n embed.set_footer(text=footer)\r\n genius = Genius(LYRICS_KEY)\r\n song = genius.search_song(title=lied.get_title(), artist=lied.get_artist())\r\n embed.add_field(name='Link', value=str('[' + str(lied) + '](' + str(song.url) + ')'),\r\n inline=False)\r\n\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send('Dieser User hört gerade nix.')\r\n\r\n\r\nasync def wetter(message):\r\n owm = OWM(OMV_KEY)\r\n if message.content.startswith('wetter'):\r\n try:\r\n userdict[str(message.author)] = time.time()\r\n mgr = owm.weather_manager()\r\n place = message.content.replace('wetter ', '')\r\n observation = mgr.weather_at_place(place)\r\n wetter_neu = observation.weather\r\n embed = discord.Embed(title='Wetter in ' + place.title(), color=1917791)\r\n embed.set_author(name='Gott', icon_url='https://cdn.psychologytoday.com/sites'\r\n '/default/files/field_blog_entry_images/God_the_Father.jpg')\r\n temp = wetter_neu.temperature('celsius')\r\n embed.add_field(name='Temperatur', value=str(round(temp['temp'], 1)) + '°C')\r\n embed.add_field(name='Luftfeuchtigkeit', value=str(wetter_neu.humidity) + '%', inline=True)\r\n embed.add_field(name='Status', value=wetter_neu.detailed_status, inline=False)\r\n await message.channel.send(embed=embed)\r\n except:\r\n await message.channel.send(\r\n 'Wetter schmetter, sag ich schon immer.')\r\n\r\n\r\n''' def test(message):\r\n if message.content == \"stop\":\r\n liste = []\r\n blacklist = ['ich', 'das', 'die', 'ist', 'von', 'in', 'was', 'der', 'du', 'a', 'nicht', 'so', 'ja',\r\n 'zu', 'und'\r\n , 'mit', 'dann', 'es', 'auch', 'hier', 'aber', 'nur', 'da', 'man', 'ein', 'hat', 'mal', 'hab',\r\n 'schon'\r\n , 'wie', 'auf', 'hat', 'wird', 'wenn', 'is', 'mein', 'alles', 'ne', 'dass', 'bin', 'den', 'aus',\r\n 'mich',\r\n 'ok', 'für', 'mir', 'sind', 'eine', 'doch', 'warum', '', '', '', '', '', '', '', '', '',\r\n '', '',\r\n '', '', '']\r\n blackliste = []\r\n dict = {}\r\n nummer = 25000\r\n zahl = 0\r\n messages = await message.channel.history(limit=nummer).flatten()\r\n for m in messages:\r\n if str(m.author) == str(message.author):\r\n zahl = zahl + 1\r\n liste = m.content.lower().split()\r\n for i in liste:\r\n if i in blackliste:\r\n pass\r\n else:\r\n if i in dict:\r\n number = dict.get(i)\r\n dict[str(i)] = number + 1\r\n else:\r\n dict[str(i)] = 1\r\n sorted_dict = sorted(dict.items(), key=operator.itemgetter(1), reverse=True)\r\n embed = discord.Embed(title='Häufigste Wörter', color=0x00ff00)\r\n d = sorted_dict[:8]\r\n for i in d:\r\n embed.add_field(name='Wort', value=i[0])\r\n embed.add_field(name='Anzahl', value=i[1], inline=True)\r\n embed.add_field(name='Häufigkeit', value=(str(round((int(i[1]) / zahl) * 100))) + \"%\", inline=True)\r\n await message.channel.send(embed=embed)'''\r\n\r\n'''async def bruh(message):\r\n if message.content == \"bruh\":\r\n userdict[str(message.author)] = time.time()\r\n await message.delete()\r\n embed = discord.Embed(title='Bruh', description='Bruh', url='https://www.youtube.com/watch?v=2ZIpFytCSVc',\r\n color=0x00ff00)\r\n embed.set_footer(text='Bruh')\r\n embed.add_field(name='Bruh', value=message.author.mention + \" sagt:\")\r\n embed.set_image(url='https://i.imgur.com/qslkBXI.gif')\r\n embed.set_thumbnail(url='https://i.imgur.com/qslkBXI.gif')\r\n embed.set_author(name='Bruh', url='https://i.imgur.com/qslkBXI.gif')\r\n await message.channel.send(embed=embed)'''\r\n\r\nclient = MyClient()\r\nclient.run(CLIENT_RUN)\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":20318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"379014026","text":"'''\n# This is an 80 character line #\nCompute the per-particle active pressure\n (with both swim and interparticle contributions)\n'''\n\nimport sys\n\n# Run locally\nsys.path.append('/Users/kolbt/Desktop/compiled/hoomd-blue/build')\nsys.path.append('/Users/kolbt/Desktop/compiled/gsd/build')\n# Run on the cpu\nsys.path.append('/nas/longleaf/home/kolbt/programs/cpu-hoomd/hoomd-blue/build')\n# Run on the gpu\n\nsys.path.append('/nas/longleaf/home/kolbt/programs/hoomd_2.2.1/hoomd-blue/build')\nsys.path.append('/nas/longleaf/home/kolbt/programs/gsd/build')\n\nimport gsd\nfrom gsd import hoomd\nfrom gsd import pygsd\n\nimport freud\nfrom freud import parallel\nfrom freud import box\nfrom freud import density\nfrom freud import cluster\n\nimport numpy as np\nimport math\nimport random\nfrom scipy import stats\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.collections\nfrom matplotlib import colors\nimport matplotlib.gridspec as gridspec\nimport matplotlib.patches as patches\n \ndef distComps(point1, point2x, point2y):\n '''Given points output x, y and r'''\n dx = point2x - point1[0]\n dy = point2y - point1[1]\n r = np.sqrt((dx**2) + (dy**2))\n return dx, dy, r\n \ndef computeFLJ(r, dx, dy, eps):\n sig = 1.\n f = (24. * eps / r) * ( (2*((sig/r)**12)) - ((sig/r)**6) )\n fx = f * (dx) / r\n fy = f * (dy) / r\n return fx, fy\n\ndef computeTauPerTstep(epsilon, mindt=0.000001):\n '''Read in epsilon, output tauBrownian per timestep'''\n# if epsilon != 1.:\n# mindt=0.00001\n kBT = 1.0\n tstepPerTau = float(epsilon / (kBT * mindt))\n return 1. / tstepPerTau\n\ndef roundUp(n, decimals=0):\n '''Round up size of bins to account for floating point inaccuracy'''\n multiplier = 10 ** decimals\n return math.ceil(n * multiplier) / multiplier\n \ndef getNBins(length, minSz=(2**(1./6.))):\n \"Given box size, return number of bins\"\n initGuess = int(length) + 1\n NBins = initGuess\n # This loop only exits on function return\n while True:\n if length / NBins > minSz:\n return NBins\n else:\n NBins -= 1\n \n# Get lattice spacing for particle size\ndef ljForce(r, eps, sigma=1.):\n div = (sigma/r)\n dU = (24. * eps / r) * ((2*(div**12)) - (div)**6)\n return dU\n \ndef avgCollisionForce(pe, power=1.):\n '''Computed from the integral of possible angles'''\n magnitude = np.sqrt(28.)\n return (magnitude * (pe)) / (np.pi)\n \ndef conForRClust(pe, eps):\n out = []\n r = 1.112\n skip = [0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001]\n for j in skip:\n while ljForce(r, eps) < avgCollisionForce(pe):\n r -= j\n r += j\n out = r\n return out\n\n# Get infile and open\ninFile = str(sys.argv[1])\nif inFile[0:7] == \"cluster\":\n add = 'cluster_'\nelse:\n add = ''\n \nf = hoomd.open(name=inFile, mode='rb')\n# Inside and outside activity from command line\npeA = float(sys.argv[2])\npeB = float(sys.argv[3])\nparFrac = float(sys.argv[4])\neps = float(sys.argv[5])\ntry:\n phi = float(sys.argv[6])\n intPhi = int(phi)\n phi /= 100.\nexcept:\n phi = 0.6\n intPhi = 60\ntry:\n dtau = float(sys.argv[7])\nexcept:\n dtau = 0.000001\n \nlat = conForRClust(peA, eps)\n \n# Get number of particles for textfile name\nwith hoomd.open(name=inFile, mode='rb') as t:\n snap = t[0]\n typ = snap.particles.typeid\n partNum = len(typ)\n\n# Outfile to write data to\nbase = add + 'hmap_pressure_pa' + str(peA) +\\\n '_pb' + str(peB) +\\\n '_xa' + str(parFrac) +\\\n '_phi' + str(intPhi) +\\\n '_ep' + '{0:.3f}'.format(eps) +\\\n '_N' + str(partNum)\n\nstart = 0 # first frame to process\ndumps = int(f.__len__()) # get number of timesteps dumped\nend = dumps # final frame to process\nstart = end - 1\n\nbox_data = np.zeros((1), dtype=np.ndarray) # box dimension holder\nr_cut = 2**(1./6.) # potential cutoff\ntauPerDT = computeTauPerTstep(epsilon=eps) # brownian time per timestep\n\nwith hoomd.open(name=inFile, mode='rb') as t:\n snap = t[0]\n first_tstep = snap.configuration.step\n box_data = snap.configuration.box\n l_box = box_data[0]\n h_box = l_box / 2.\n typ = snap.particles.typeid\n partNum = len(typ)\n # Compute each mesh\n NBins = getNBins(l_box, r_cut)\n sizeBin = roundUp((l_box / NBins), 6)\n # Set some values for plotting\n parts = [lat for i in range(0, partNum)]\n myCols = plt.cm.jet\n \n # Loop through each timestep\n for j in range(start, end):\n snap = t[j]\n # Easier accessors\n pos = snap.particles.position # position\n pos[:,-1] = 0.0\n xy = np.delete(pos, 2, 1)\n typ = snap.particles.typeid # type\n tst = snap.configuration.step # timestep\n tst -= first_tstep # normalize by first timestep\n tst *= dtau # convert to Brownian time\n \n # Mesh and bin the particles by position\n binParts = [[[] for b in range(NBins)] for a in range(NBins)]\n for k in range(0, partNum):\n # Convert position to be > 0 to place in list mesh\n tmp_posX = pos[k][0] + h_box\n tmp_posY = pos[k][1] + h_box\n x_ind = int(tmp_posX / sizeBin)\n y_ind = int(tmp_posY / sizeBin)\n # Append all particles to appropriate bin\n binParts[x_ind][y_ind].append(k)\n \n # Loop through particles and compute pressure\n pressure = [0. for i in range(0, partNum)]\n for k in range(0, partNum):\n # Get mesh indices\n tmp_posX = pos[k][0] + h_box\n tmp_posY = pos[k][1] + h_box\n x_ind = int(tmp_posX / sizeBin)\n y_ind = int(tmp_posY / sizeBin)\n # Get index of surrounding bins\n l_bin = x_ind - 1 # index of left bins\n r_bin = x_ind + 1 # index of right bins\n b_bin = y_ind - 1 # index of bottom bins\n t_bin = y_ind + 1 # index of top bins\n if r_bin == NBins:\n r_bin -= NBins # adjust if wrapped\n if t_bin == NBins:\n t_bin -= NBins # adjust if wrapped\n h_list = [l_bin, x_ind, r_bin] # list of horizontal bin indices\n v_list = [b_bin, y_ind, t_bin] # list of vertical bin indices\n\n # Loop through all bins\n for h in range(0, len(h_list)):\n for v in range(0, len(v_list)):\n # Take care of periodic wrapping for position\n wrapX = 0.0\n wrapY = 0.0\n if h == 0 and h_list[h] == -1:\n wrapX -= l_box\n if h == 2 and h_list[h] == 0:\n wrapX += l_box\n if v == 0 and v_list[v] == -1:\n wrapY -= l_box\n if v == 2 and v_list[v] == 0:\n wrapY += l_box\n # Compute distance between particles\n for b in range(0, len(binParts[h_list[h]][v_list[v]])):\n ref = binParts[h_list[h]][v_list[v]][b]\n dx, dy, r = distComps(pos[k],\n pos[ref][0] + wrapX,\n pos[ref][1] + wrapY)\n r = round(r, 4) # round value to 4 decimal places\n\n # If LJ potential is on, compute pressure\n if 0.1 < r <= r_cut:\n # Compute the x and y components of force\n fx, fy = computeFLJ(r, dx, dy, eps)\n # Compute the x force times x distance\n sigx = fx * (dx)\n # Likewise for y\n sigy = fy * (dy)\n # Test the code\n if sigx < 0 or sigy < 0:\n print(\"Negative value for force times r!!!\")\n # Add the pressure from this neighbor\n pressure[k] += ((sigx + sigy) / 2.)\n \n outDPI = 500.\n fig, ax = plt.subplots()\n xy = np.delete(pos, 2, 1)\n coll = matplotlib.collections.EllipseCollection(parts, parts,\n np.zeros_like(parts),\n offsets=xy, units='xy',\n cmap=myCols,\n transOffset=ax.transData)\n coll.set_array(np.ravel(pressure))\n# minCol = min(pressure)\n# maxCol = max(pressure)\n# coll.set_clim([minCol, 1.0])\n ax.add_collection(coll)\n cbar = plt.colorbar(coll, format='%.0f')\n cbar.set_label(r'Interparticle Pressure $(\\Pi^{P})$', labelpad=20, rotation=270)\n\n # Limits and ticks\n viewBuff = 0.0\n ax.set_xlim(-h_box - viewBuff, h_box + viewBuff)\n ax.set_ylim(-h_box - viewBuff, h_box + viewBuff)\n ax.tick_params(axis='both', which='both',\n bottom=False, top=False, left=False, right=False,\n labelbottom=False, labeltop=False, labelleft=False, labelright=False)\n\n pad = str(j).zfill(4)\n ax.set_aspect('equal')\n plt.tight_layout()\n plt.savefig(base + '_' + pad + '.png', dpi=outDPI)\n plt.close()\n","sub_path":"post_proc/swim_pressure_heatmap.py","file_name":"swim_pressure_heatmap.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"358480724","text":"import os, json\nfrom copy import deepcopy\nfrom matplotlib.pylab import *\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom scripts.model.nl2sql.models.sel_predict import *\nfrom scripts.model.nl2sql.models.cond_predict import *\nfrom scripts.model.nl2sql.utils.utils_data import *\nfrom scripts.model.nl2sql.utils.utils import *\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass NL2SQL(nn.Module):\n def __init__(self, iS, hS, lS, dr, n_cond_ops, n_agg_ops, n_order_ops, old=False):\n super(NL2SQL, self).__init__()\n self.iS = iS\n self.hS = hS\n self.ls = lS\n self.dr = dr\n\n self.max_wn = 4\n self.n_cond_ops = n_cond_ops\n self.n_agg_ops = n_agg_ops\n self.n_order_ops = n_order_ops\n # where col prediction\n self.snp = SNP(iS, hS, lS, dr)\n # select column prediction\n self.scp = SCP(iS, hS, lS, dr)\n # select agg prediction\n self.sap = SAP(iS, hS, lS, dr, n_agg_ops, old=old)\n # where num prediction\n self.wnp = WNP(iS, hS, lS, dr)\n\n self.wcp = WCP(iS, hS, lS, dr)\n self.wop = WOP(iS, hS, lS, dr, n_cond_ops)\n self.wvp = WVP_se(iS, hS, lS, dr, n_cond_ops, old=old) # start-end-search-discriminative model\n\n def forward(self, wemb_n, l_n, wemb_hpu, l_hpu, l_hs,\n g_sn=None, g_sc=None, g_sa=None, g_wn=None, g_wc=None, g_wo=None, g_wvi=None,\n show_p_sc=False, show_p_sa=False,\n show_p_wn=False, show_p_wc=False, show_p_wo=False, show_p_wv=False):\n\n # sn\n s_sn = self.snp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n\n if g_wn:\n pr_sn = g_sn\n else:\n pr_sn = pred_sn(s_sn)\n\n # sc\n s_sc = self.scp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_sc=show_p_sc)\n\n if g_sc:\n pr_sc = g_sc\n else:\n pr_sc = pred_sc(s_sc)\n\n # sa\n s_sa = self.sap(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, pr_sn, pr_sc, show_p_sa=show_p_sa)\n if g_sa:\n # it's not necessary though.\n pr_sa = g_sa\n else:\n pr_sa = pred_sa(s_sa)\n\n\n # wn\n s_wn = self.wnp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n\n if g_wn:\n pr_wn = g_wn\n else:\n pr_wn = pred_wn(s_wn)\n\n # wc\n s_wc = self.wcp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wc=show_p_wc, penalty=True)\n\n if g_wc:\n pr_wc = g_wc\n else:\n pr_wc = pred_wc(pr_wn, s_wc)\n\n # wo\n s_wo = self.wop(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn, wc=pr_wc, show_p_wo=show_p_wo)\n\n if g_wo:\n pr_wo = g_wo\n else:\n pr_wo = pred_wo(pr_wn, s_wo)\n\n # wv\n s_wv = self.wvp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn, wc=pr_wc, wo=pr_wo, show_p_wv=show_p_wv)\n\n return s_sn, s_sc, s_sa, s_wn, s_wc, s_wo, s_wv\n\n def beam_forward(self, wemb_n, l_n, wemb_hpu, l_hpu, l_hs, engine, tb,\n nlu_t, nlu_wp_t, wp_to_wh_index, nlu,\n beam_size=4,\n show_p_sc=False, show_p_sa=False,\n show_p_wn=False, show_p_wc=False, show_p_wo=False, show_p_wv=False):\n \"\"\"\n Execution-guided beam decoding.\n \"\"\"\n # sc\n s_sc = self.scp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_sc=show_p_sc)\n prob_sc = F.softmax(s_sc, dim=-1)\n bS, mcL = s_sc.shape\n\n # minimum_hs_length = min(l_hs)\n # beam_size = minimum_hs_length if beam_size > minimum_hs_length else beam_size\n\n # sa\n # Construct all possible sc_sa_score\n prob_sc_sa = torch.zeros([bS, beam_size, self.n_agg_ops]).to(device)\n prob_sca = torch.zeros_like(prob_sc_sa).to(device)\n\n # get the top-k indices. pr_sc_beam = [B, beam_size]\n pr_sc_beam = pred_sc_beam(s_sc, beam_size)\n\n # calculate and predict s_sa.\n for i_beam in range(beam_size):\n pr_sc = list( array(pr_sc_beam)[:,i_beam] )\n s_sa = self.sap(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, pr_sc, show_p_sa=show_p_sa)\n prob_sa = F.softmax(s_sa, dim=-1)\n prob_sc_sa[:, i_beam, :] = prob_sa\n\n prob_sc_selected = prob_sc[range(bS), pr_sc] # [B]\n prob_sca[:, i_beam, :] = (prob_sa.t() * prob_sc_selected).t()\n # [mcL, B] * [B] -> [mcL, B] (element-wise multiplication)\n # [mcL, B] -> [B, mcL]\n\n # Calculate the dimension of tensor\n # tot_dim = len(prob_sca.shape)\n\n # First flatten to 1-d\n idxs = topk_multi_dim(torch.tensor(prob_sca), n_topk=beam_size, batch_exist=True)\n # Now as sc_idx is already sorted, re-map them properly.\n\n idxs = remap_sc_idx(idxs, pr_sc_beam) # [sc_beam_idx, sa_idx] -> [sc_idx, sa_idx]\n idxs_arr = array(idxs)\n # [B, beam_size, remainig dim]\n # idxs[b][0] gives first probable [sc_idx, sa_idx] pairs.\n # idxs[b][1] gives of second.\n\n # Calculate prob_sca, a joint probability\n beam_idx_sca = [0] * bS\n beam_meet_the_final = [False] * bS\n while True:\n pr_sc = idxs_arr[range(bS), beam_idx_sca, 0]\n pr_sa = idxs_arr[range(bS), beam_idx_sca, 1]\n\n # map index properly\n\n check = check_sc_sa_pairs(tb, pr_sc, pr_sa)\n\n if sum(check) == bS:\n break\n else:\n for b, check1 in enumerate(check):\n if not check1: # wrong pair\n beam_idx_sca[b] += 1\n if beam_idx_sca[b] >= beam_size:\n beam_meet_the_final[b] = True\n beam_idx_sca[b] -= 1\n else:\n beam_meet_the_final[b] = True\n\n if sum(beam_meet_the_final) == bS:\n break\n\n\n # Now pr_sc, pr_sa are properly predicted.\n pr_sc_best = list(pr_sc)\n pr_sa_best = list(pr_sa)\n\n # Now, Where-clause beam search.\n s_wn = self.wnp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wn=show_p_wn)\n prob_wn = F.softmax(s_wn, dim=-1).detach().to('cpu').numpy()\n\n # Found \"executable\" most likely 4(=max_num_of_conditions) where-clauses.\n # wc\n s_wc = self.wcp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, show_p_wc=show_p_wc, penalty=True)\n prob_wc = F.sigmoid(s_wc).detach().to('cpu').numpy()\n # pr_wc_sorted_by_prob = pred_wc_sorted_by_prob(s_wc)\n\n # get max_wn # of most probable columns & their prob.\n pr_wn_max = [self.max_wn]*bS\n pr_wc_max = pred_wc(pr_wn_max, s_wc) # if some column do not have executable where-claouse, omit that column\n prob_wc_max = zeros([bS, self.max_wn])\n for b, pr_wc_max1 in enumerate(pr_wc_max):\n prob_wc_max[b,:] = prob_wc[b,pr_wc_max1]\n\n # get most probable max_wn where-clouses\n # wo\n s_wo_max = self.wop(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn_max, wc=pr_wc_max, show_p_wo=show_p_wo)\n prob_wo_max = F.softmax(s_wo_max, dim=-1).detach().to('cpu').numpy()\n # [B, max_wn, n_cond_op]\n\n pr_wvi_beam_op_list = []\n prob_wvi_beam_op_list = []\n for i_op in range(self.n_cond_ops-1):\n pr_wo_temp = [ [i_op]*self.max_wn ]*bS\n # wv\n s_wv = self.wvp(wemb_n, l_n, wemb_hpu, l_hpu, l_hs, wn=pr_wn_max, wc=pr_wc_max, wo=pr_wo_temp, show_p_wv=show_p_wv)\n prob_wv = F.softmax(s_wv, dim=-2).detach().to('cpu').numpy()\n\n # prob_wv\n pr_wvi_beam, prob_wvi_beam = pred_wvi_se_beam(self.max_wn, s_wv, beam_size)\n pr_wvi_beam_op_list.append(pr_wvi_beam)\n prob_wvi_beam_op_list.append(prob_wvi_beam)\n # pr_wvi_beam = [B, max_wn, k_logit**2 [st, ed] paris]\n\n # pred_wv_beam\n\n # Calculate joint probability of where-clause\n # prob_w = [batch, wc, wo, wv] = [B, max_wn, n_cond_op, n_pairs]\n n_wv_beam_pairs = prob_wvi_beam.shape[2]\n prob_w = zeros([bS, self.max_wn, self.n_cond_ops-1, n_wv_beam_pairs])\n for b in range(bS):\n for i_wn in range(self.max_wn):\n for i_op in range(self.n_cond_ops-1): # do not use final one\n for i_wv_beam in range(n_wv_beam_pairs):\n # i_wc = pr_wc_max[b][i_wn] # already done\n p_wc = prob_wc_max[b, i_wn]\n p_wo = prob_wo_max[b, i_wn, i_op]\n p_wv = prob_wvi_beam_op_list[i_op][b, i_wn, i_wv_beam]\n\n prob_w[b, i_wn, i_op, i_wv_beam] = p_wc * p_wo * p_wv\n\n # Perform execution guided decoding\n conds_max = []\n prob_conds_max = []\n # while len(conds_max) < self.max_wn:\n idxs = topk_multi_dim(torch.tensor(prob_w), n_topk=beam_size, batch_exist=True)\n # idxs = [B, i_wc_beam, i_op, i_wv_pairs]\n\n # Construct conds1\n for b, idxs1 in enumerate(idxs):\n conds_max1 = []\n prob_conds_max1 = []\n for i_wn, idxs11 in enumerate(idxs1):\n i_wc = pr_wc_max[b][idxs11[0]]\n i_op = idxs11[1]\n wvi = pr_wvi_beam_op_list[i_op][b][idxs11[0]][idxs11[2]]\n\n # get wv_str\n temp_pr_wv_str, _ = convert_pr_wvi_to_string([[wvi]], [nlu_t[b]], [nlu_wp_t[b]], [wp_to_wh_index[b]], [nlu[b]])\n merged_wv11 = merge_wv_t1_eng(temp_pr_wv_str[0][0], nlu[b])\n conds11 = [i_wc, i_op, merged_wv11]\n\n prob_conds11 = prob_w[b, idxs11[0], idxs11[1], idxs11[2] ]\n\n # test execution\n # print(nlu[b])\n # print(tb[b]['id'], tb[b]['types'], pr_sc[b], pr_sa[b], [conds11])\n pr_ans = engine.execute(tb[b]['id'], pr_sc[b], pr_sa[b], [conds11])\n if bool(pr_ans):\n # pr_ans is not empty!\n conds_max1.append(conds11)\n prob_conds_max1.append(prob_conds11)\n conds_max.append(conds_max1)\n prob_conds_max.append(prob_conds_max1)\n\n # May need to do more exhuastive search?\n # i.e. up to.. getting all executable cases.\n\n # Calculate total probability to decide the number of where-clauses\n pr_sql_i = []\n prob_wn_w = []\n pr_wn_based_on_prob = []\n\n for b, prob_wn1 in enumerate(prob_wn):\n max_executable_wn1 = len(conds_max[b])\n prob_wn_w1 = []\n prob_wn_w1.append(prob_wn1[0]) # wn=0 case.\n for i_wn in range(max_executable_wn1):\n prob_wn_w11 = prob_wn1[i_wn+1] * prob_conds_max[b][i_wn]\n prob_wn_w1.append(prob_wn_w11)\n pr_wn_based_on_prob.append(argmax(prob_wn_w1))\n prob_wn_w.append(prob_wn_w1)\n\n pr_sql_i1 = {'agg': pr_sa_best[b], 'sel': pr_sc_best[b], 'conds': conds_max[b][:pr_wn_based_on_prob[b]]}\n pr_sql_i.append(pr_sql_i1)\n # s_wv = [B, max_wn, max_nlu_tokens, 2]\n return prob_sca, prob_w, prob_wn_w, pr_sc_best, pr_sa_best, pr_wn_based_on_prob, pr_sql_i\n\n\ndef Loss_sn(s_sn, g_sn):\n loss = F.cross_entropy(s_sn, torch.tensor(g_sn).to(device))\n return loss\n\n\ndef Loss_sc(s_sc, g_sc):\n # Construct index matrix\n bS, max_h_len = s_sc.shape\n im = torch.zeros([bS, max_h_len]).to(device)\n for b, g_sc1 in enumerate(g_sc):\n for g_sc11 in g_sc1:\n im[b, g_sc11] = 1.0\n # Construct prob.\n p = F.sigmoid(s_sc)\n loss = F.binary_cross_entropy(p, im)\n\n return loss\n\n\ndef Loss_sa(s_sa, g_sn, g_sa):\n loss = 0\n for b, g_wn1 in enumerate(g_sn):\n if g_wn1 == 0:\n continue\n g_wo1 = g_sa[b]\n s_wo1 = s_sa[b]\n loss += F.cross_entropy(s_wo1[:g_wn1], torch.tensor(g_wo1).to(device))\n\n return loss\n\n\ndef Loss_wn(s_wn, g_wn):\n loss = F.cross_entropy(s_wn, torch.tensor(g_wn).to(device))\n\n return loss\n\n\ndef Loss_wc(s_wc, g_wc):\n\n # Construct index matrix\n bS, max_h_len = s_wc.shape\n im = torch.zeros([bS, max_h_len]).to(device)\n for b, g_wc1 in enumerate(g_wc):\n for g_wc11 in g_wc1:\n im[b, g_wc11] = 1.0\n # Construct prob.\n p = F.sigmoid(s_wc)\n loss = F.binary_cross_entropy(p, im)\n\n return loss\n\n\ndef Loss_wo(s_wo, g_wn, g_wo):\n\n # Construct index matrix\n loss = 0\n for b, g_wn1 in enumerate(g_wn):\n if g_wn1 == 0:\n continue\n g_wo1 = g_wo[b]\n s_wo1 = s_wo[b]\n loss += F.cross_entropy(s_wo1[:g_wn1], torch.tensor(g_wo1).to(device))\n\n return loss\n\n\ndef Loss_wv_se(s_wv, g_wn, g_wo, g_wvi):\n \"\"\"\n s_wv: [bS, 4, mL, 2], 4 stands for maximum # of condition, 2 tands for start & end logits.\n g_wvi: [ [1, 3, 2], [4,3] ] (when B=2, wn(b=1) = 3, wn(b=2) = 2).\n \"\"\"\n loss = 0\n # g_wvi = torch.tensor(g_wvi).to(device)\n for b, g_wvi1 in enumerate(g_wvi):\n # for i_wn, g_wvi11 in enumerate(g_wvi1):\n\n g_wn1 = g_wn[b]\n g_wo1 = g_wo[b]\n\n flag = True\n\n if g_wn1 == 0:\n flag = False\n\n # todo: work for comparision\n for i in g_wo1:\n if i not in [2, 3, 4, 5, 6, 7]:\n flag = False\n\n if flag is not True:\n continue\n\n g_wvi1 = torch.tensor(g_wvi1).to(device)\n g_st1 = g_wvi1[:, 0]\n g_ed1 = g_wvi1[:, 1]\n # loss from the start position\n loss += F.cross_entropy(s_wv[b, :g_wn1, :, 0], g_st1)\n\n # print(\"st_login: \", s_wv[b,:g_wn1,:,0], g_st1, loss)\n # loss from the end position\n loss += F.cross_entropy(s_wv[b, :g_wn1, :, 1], g_ed1)\n # print(\"ed_login: \", s_wv[b,:g_wn1,:,1], g_ed1, loss)\n\n return loss\n\n\ndef Loss_sw_se(s_sn, s_sc, s_sa, s_wn, s_wc, s_wo, s_wv, g_sn, g_sc, g_sa, g_wn, g_wc, g_wo, g_wvi):\n \"\"\"\n\n :param s_wv: score [ B, n_conds, T, score]\n :param g_wn: [ B ]\n :param g_wvi: [B, conds, pnt], e.g. [[[0, 6, 7, 8, 15], [0, 1, 2, 3, 4, 15]], [[0, 1, 2, 3, 16], [0, 7, 8, 9, 16]]]\n :return:\n \"\"\"\n loss = 0\n loss += Loss_sn(s_sn, g_sn)\n loss += Loss_sc(s_sc, g_sc)\n loss += Loss_sa(s_sa, g_sn, g_sa)\n loss += Loss_wn(s_wn, g_wn)\n loss += Loss_wc(s_wc, g_wc)\n loss += Loss_wo(s_wo, g_wn, g_wo)\n loss += Loss_wv_se(s_wv, g_wn, g_wo, g_wvi)\n\n return loss\n","sub_path":"scripts/model/nl2sql/nl2sql.py","file_name":"nl2sql.py","file_ext":"py","file_size_in_byte":14433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"539311397","text":"#!/usr/bin/env python\n\n\"\"\"\nlockdown.py updates release.yaml files\n\nThis script does:\n* Parses those external image and adds sha value to them in\n the release.yaml file\n\"\"\"\n\nimport argparse\nimport os\nimport re\nimport string\nimport sys\nimport docker\nfrom typing import List\n\ndef scan_release(omit: List[str], path: str) -> List[str]:\n \"\"\"Extracts built images from the release.yaml at path\n Args:\n omit: The list of images that are omitted from the static image list\n path: The path to the file (release.yaml) that will contain the built images\n Returns:\n list of the images parsed from the file\n \"\"\"\n print(\"scan_release\")\n images = []\n with open(path) as f:\n print(\"path: \" + path)\n for line in f:\n match = re.search(\"image:\" + \".*\" + \"latest\", line)\n if match:\n exclude = False\n for image in omit:\n if image in line:\n exclude = True\n if not(exclude):\n images.append(match.group(0).replace(\"image:\", \"\").strip())\n return images\n\ndef lockdown_image(images: List[str]) -> List[str]:\n \"\"\"Lockdown images with the sha value\n Args:\n images: The list of images that are lockdowned\n Returns:\n list of the lockdowned images\n \"\"\"\n print(\"lockdown_image\")\n taggedimages = []\n client = docker.DockerClient(base_url='unix://var/run/docker.sock')\n for image in images:\n print(\"image:\" + image)\n imageobj = client.images.pull(image)\n taggedimages.append(imageobj.attrs[\"RepoDigests\"][0])\n return taggedimages\n\ndef replace_images(org: List[str], new: List[str], path: str):\n \"\"\"Replace original images with new images in the release.yaml at path\n Args:\n org: The list of original images that are replaced by the new images\n new: The list of new images\n path: The path to the file (release.yaml) that will contain the built images\n \"\"\"\n print(\"replace_image\")\n with open(path) as f:\n with open(path+\".temp\", \"x\") as ff:\n for line in f:\n newline = line\n i = 0\n for o in org:\n match = re.search(o , line)\n if match:\n newline = line.replace(o, new[i])\n i = i + 1\n ff.write(newline)\n os.replace(path+\".temp\", path)\n\nif __name__ == \"__main__\":\n arg_parser = argparse.ArgumentParser(\n description=\"Lockdown external images with sha in a release.yaml\")\n arg_parser.add_argument(\"--path\", type=str, required=True,\n help=\"Path to the release.yaml\")\n arg_parser.add_argument(\"--omit\", type=str, required=True,\n help=\"String prefix which is omitted from the external images\")\n args = arg_parser.parse_args()\n\n images = scan_release(args.omit.split(\",\") , args.path)\n taggedimages = lockdown_image(images)\n replace_images(images, taggedimages, args.path)\n\n print(\"Done.\\n\")\n\n","sub_path":"tekton/scripts/lockdown.py","file_name":"lockdown.py","file_ext":"py","file_size_in_byte":3071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"252633269","text":"\"\"\"https://github.com/django-helpdesk/django-helpdesk/issues/348\nMust have username/passwork credentials for sender\nUse a 'Reply-To' header to specify the party who initiated the inquiry\"\"\"\n\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\n\nfrom django.shortcuts import render\n\nfrom django.core.mail import BadHeaderError, send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import redirect, render\n\nfrom .forms import ContactForm\n\ndef email(request):\n if request.method == 'GET':\n form = ContactForm()\n else:\n form = ContactForm(request.POST)\n if form.is_valid():\n subject = 'Website Inquiry: ' # subject prefix\n subject = subject + form.cleaned_data['subject'] # append user input\n #from_email = form.cleaned_data['from_email']\n headers = {'Reply-To': form.cleaned_data['from_email']}\n message = 'Website Inquiry:'\n message = '\\n'.join([message, '\\n', form.cleaned_data['message']])\n #message = message.join(['\\n', '\\n', form.cleaned_data['message']])\n #message = message + form.cleaned_data['message']\n try:\n #send_mail(subject, message, from_email, ['admin@example.com'])\n msg = EmailMultiAlternatives(subject, message, '00mstacy@gmail.com', ['00mstacy@gmail.com',], headers=headers)\n msg.send(fail_silently=False)\n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n return redirect('success')\n return render(request, \"email.html\", {'form': form})\n\ndef success(request):\n return HttpResponse('Success! Thank you for your message.')\n","sub_path":"send_email/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"597026544","text":"\n\nfrom xai.brain.wordbase.nouns._science import _SCIENCE\n\n#calss header\nclass _SCIENCES(_SCIENCE, ):\n\tdef __init__(self,): \n\t\t_SCIENCE.__init__(self)\n\t\tself.name = \"SCIENCES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"science\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sciences.py","file_name":"_sciences.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"570647376","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import *\nimport os\nimport urllib.request\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\nimport ast\nfrom django.http import HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom PIL import Image\nfrom math import sqrt\nfrom collections import Counter, defaultdict\nfrom .google_ocr import *\nimport time\nimport sys\nimport subprocess\nfrom random import randint\nimport json\nimport csv\nimport boto3\nfrom random import randint\nfrom time import sleep\n\ndef syncImages():\n streetviewImages = StreetviewImage.objects.all()\n for streetviewImage in streetviewImages:\n if streetviewImage.image_is_set is False:\n streetviewImage.check_if_image_is_set()\n else:\n print(str(streetviewImage.pk) + \" was previously set\")\n\ndef saveImages_async_deprecated():\n # parameters\n xdim = 640\n ydim = 640\n count_continuous_error = 0\n\n # get mapPoints\n mapPoints = MapPoint.objects.all()\n for mapPoint in mapPoints:\n\n # check if we should create the image\n # if we don't have exactly two streetviewImage objects, then we need to (re)create the images\n streetviewImages = mapPoint.streetviewimage_set.all()\n if len(streetviewImages) != 2:\n streetviewImages.delete()\n mapPoint.createStreetviewImages()\n recreate_image = True\n # if we have previously flagged streetviewImage objects as set, then we don't need to recreate\n elif streetviewImages[0].image_is_set and streetviewImages[1].image_is_set:\n recreate_image = False\n #print(\"skipping \" + str(streetviewImages[0].pk) + \" and \" + str(streetviewImages[1].pk))\n # check if we need to recreate explicitly\n elif streetviewImages[0].check_if_image_is_set() and streetviewImages[1].check_if_image_is_set():\n streetviewImages[0].image_is_set = True\n streetviewImages[0].save()\n streetviewImages[1].image_is_set = True\n streetviewImages[1].save()\n recreate_image = False\n print(\"skipping \" + str(streetviewImages[0].pk) + \" and \" + str(streetviewImages[1].pk))\n # we need to recreate image\n else:\n recreate_image = True\n\n try:\n if recreate_image:\n for streetviewImage in mapPoint.streetviewimage_set.all():\n sleep(randint(0,6))\n if settings.USE_S3:\n image_name = 'temp6.jpg'\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude, \\\n streetviewImage.fov,streetviewImage.heading, \\\n streetviewImage.pitch, image_name)\n # upload image to s3\n s3 = boto3.client('s3', \\\n aws_access_key_id=settings.AWS_ACCESS_KEY,\n aws_secret_access_key=settings.AWS_SECRET, \\\n )\n s3.upload_file(fi, settings.AWS_BUCKET_NAME, streetviewImage.image_name())\n streetviewImage.image_is_set = True\n streetviewImage.save()\n print(streetviewImage.image_name() + ' uploaded to s3')\n else:\n image_name = streetviewImage.image_name()\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude, \\\n streetviewImage.fov,streetviewImage.heading, \\\n streetviewImage.pitch, image_name)\n streetviewImage.image_is_set = True\n streetviewImage.save()\n print(streetviewImage.image_name() + ' saved')\n count_continuous_error = 0\n except BaseException as e:\n print(str(e))\n count_continuous_error += 1\n print(\"continuous error = \" + str(count_continuous_error))\n if count_continuous_error > 3:\n break\n else:\n continue\n\n\n\n\n# saves concatenated image from google streetview to local disk\ndef saveImages_async_deprecated():\n # get mapPoints\n mapPoints = MapPoint.objects.all()\n xdim = 640\n ydim = 640\n pitch=0\n for mapPoint in mapPoints:\n # check if image associated here to prevent worker collisions\n if mapPoint.streetviewimage_set.all().count() != 0:\n continue\n\n # fov right is wider because we are nearer to the right side of the road.\n for rl in [{'heading':mapPoint.photographerHeading+90,'fov':35}, \\\n {'heading':mapPoint.photographerHeading-90,'fov':22.5}]:\n # save object\n streetviewImage = StreetviewImage(mapPoint=mapPoint, \\\n heading=rl['heading'], \\\n fov=rl['fov'], \\\n pitch=pitch)\n streetviewImage.save()\n\n # make image, save local\n\n if settings.USE_S3:\n image_name = 'temp6.jpg'\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude,rl['fov'],rl['heading'],pitch,image_name)\n # upload image to s3\n s3 = boto3.client('s3', \\\n aws_access_key_id=settings.AWS_ACCESS_KEY,\n aws_secret_access_key=settings.AWS_SECRET, \\\n )\n s3.upload_file(fi, settings.AWS_BUCKET_NAME, streetviewImage.image_name())\n print(streetviewImage.image_name() + ' uploaded to s3')\n else:\n image_name = streetviewImage.image_name()\n fi = saveConcatImage(xdim,ydim,mapPoint.latitude,mapPoint.longitude,rl['fov'],rl['heading'],pitch,image_name)\n print(streetviewImage.image_name() + ' saved')\n\ndef saveConcatImage(xdim,ydim,latitude,longitude,fov,heading,pitch,image_name):\n #saveImage2(xdim,ydim,latitude,longitude,fov,heading-(2*fov-0.5),pitch,'temp1.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading-(fov-0.5),pitch,'temp2.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading ,pitch,'temp3.jpg')\n saveImage2(xdim,ydim,latitude,longitude,fov,heading+(fov-0.5),pitch,'temp4.jpg')\n #saveImage2(xdim,ydim,latitude,longitude,fov,heading+(2*fov-0.5),pitch,'temp5.jpg')\n\n #I1 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp1.jpg'))\n I2 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp2.jpg'))\n I3 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp3.jpg'))\n I4 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp4.jpg'))\n #I5 = Image.open(os.path.join(settings.MEDIA_ROOT,'temp5.jpg'))\n\n # crop\n #I1 = I1.crop((0, 0, I1.size[0], I1.size[1]-20))\n I2 = I2.crop((0, 0, I2.size[0], I2.size[1]-20))\n I3 = I3.crop((0, 0, I3.size[0], I3.size[1]-20))\n I4 = I4.crop((0, 0, I4.size[0], I4.size[1]-20))\n #I5 = I5.crop((0, 0, I5.size[0], I5.size[1]-20))\n\n\n I_concatenate = concatenateImage(I2,I3,'left')\n #I_concatenate = concatenateImage(I1,I_concatenate,'left')\n I_concatenate = concatenateImage(I_concatenate,I4,'right')\n #I_concatenate = concatenateImage(I_concatenate,I5,'right')\n\n # crop x-dimension ( 3600x620 to 2500x620 ) so that textDetector doesn't run out of memory\n #final_dimx = 2500\n #width, height = I_concatenate.size\n #I_concatenate = I_concatenate.crop(( round(width/2- final_dimx/2) , 0, round(width/2+ final_dimx/2), height))\n\n fi_path = os.path.join(settings.MEDIA_ROOT,image_name)\n I_concatenate.save(fi_path)\n #\n return fi_path\n\ndef concatenateImage(I_left, I_right, shiftRightOrLeft):\n # get column of right-most pixels for I_left and left-most pixels for I_right\n column_left = get_column(I_left,'last')\n column_right = get_column(I_right,'first')\n # find shift that minimizes distance\n dimy = len(column_left)\n shift_range = int(dimy/6) # decrease to speed up\n min_average_distance = float(\"inf\")\n shift = 0\n for i in range(-shift_range,shift_range):\n sum_distance = 0\n count = 0\n for j in range(0,dimy):\n if j+i<0 or j+i>=dimy:\n continue\n else:\n v1 = column_left[j]\n v2 = column_right[j+i]\n distance = sqrt( (v1[0]-v2[0])**2 + (v1[1]-v2[1])**2 + (v1[2]-v2[2])**2 )\n sum_distance += distance\n count = count + 1\n average_distance = sum_distance/count\n if average_distance < min_average_distance:\n min_average_distance=average_distance\n shift=i\n # shift right image to match left image\n if shiftRightOrLeft == 'right':\n I_right_shift = Image.new('RGB', (I_right.size[0], I_right.size[1]))\n I_right_shift.paste(I_right, (0,-shift))\n # concatenate right and left image\n dimy = max(I_left.size[1],I_right_shift.size[1])\n dimx = I_left.size[0]+I_right_shift.size[0]\n I_concatenate = Image.new('RGB', (dimx,dimy))\n I_concatenate.paste(I_left, (0,0))\n I_concatenate.paste(I_right_shift, (I_left.size[0],0))\n elif shiftRightOrLeft == 'left':\n I_left_shift = Image.new('RGB', (I_left.size[0], I_left.size[1]))\n I_left_shift.paste(I_left, (0,shift))\n # concatenate right and left image\n dimy = max(I_right.size[1],I_left_shift.size[1])\n dimx = I_right.size[0]+I_left_shift.size[0]\n I_concatenate = Image.new('RGB', (dimx,dimy))\n I_concatenate.paste(I_left_shift, (0,0))\n I_concatenate.paste(I_right, (I_left_shift.size[0],0))\n return I_concatenate\n\ndef get_column(I,firstOrLast):\n pix = I.load()\n dimx = I.size[0]\n dimy = int(I.size[1])\n column = [None]*dimy\n for i in range(0,dimy):\n if firstOrLast == 'first':\n column[i] = pix[0,i]\n elif firstOrLast == 'last':\n column[i] = pix[dimx-1,i]\n return column\n\nclass AppURLopener(urllib.request.FancyURLopener):\n version = \"Mozilla/5.0\"\n\ndef saveImage2(xdim,ydim,latitude,longitude,fov,heading,pitch,filename):\n url = \"http://maps.googleapis.com/maps/api/streetview?size=%dx%d&location=%f,%f&fov=%d&heading=%f&pitch=%f\"%(xdim,ydim,latitude,longitude,fov,heading,pitch) \\\n + '&key='+ settings.GOOGLE_MAPS_API_KEY\n\n fi_path = os.path.join(settings.MEDIA_ROOT,filename)\n\n urllib._urlopener = AppURLopener()\n print(url)\n #urllib.URLopener.version = 'Mozilla/5.0' # (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0\n data = urllib.request.urlretrieve(url, fi_path)\n","sub_path":"streetviewInterface/mySite/ImagePicker/views_saveImage.py","file_name":"views_saveImage.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"582657291","text":"# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html\n# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE\nfrom typing import Tuple\n\n__version__ = \"2.11.1\"\n\n\ndef get_numversion_from_version(v: str) -> Tuple:\n \"\"\"Kept for compatibility reason\n\n See https://github.com/PyCQA/pylint/issues/4399\n https://github.com/PyCQA/pylint/issues/4420,\n \"\"\"\n v = v.replace(\"pylint-\", \"\")\n version = []\n for n in v.split(\".\")[0:3]:\n try:\n version.append(int(n))\n except ValueError:\n num = \"\"\n for c in n:\n if c.isdigit():\n num += c\n else:\n break\n try:\n version.append(int(num))\n except ValueError:\n version.append(0)\n while len(version) != 3:\n version.append(0)\n return tuple(version)\n\n\nnumversion = get_numversion_from_version(__version__)\n","sub_path":".venv/lib/python3.8/site-packages/pylint/__pkginfo__.py","file_name":"__pkginfo__.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"162213196","text":"import numpy as np\n\nimport scipy.sparse as sparse\nimport scipy.sparse.linalg as sp_linalg\n\n\ndef discretesample(p, n):\n \"\"\"independently draws n samples (with replacement) from the\n distribution specified by p, where p is a probability array\n whose elements sum to 1.\"\"\"\n return np.random.choice(len(p), n, p=p)\n\n\ndef similarity(x1, x2):\n norm_x1 = np.linalg.norm(x1)\n norm_x2 = np.linalg.norm(x2)\n return np.dot(x1, x2) / (norm_x1 * norm_x2)\n\n\ndef calc_centroid(X):\n return np.mean(X, 0)\n\n\ndef count_diff(a, prev_a):\n diff = np.abs(a - prev_a)\n diff[diff > 1] = 1\n\n return np.sum(diff)\n\n\ndef k_means_sphere(X, k, max_iter=100):\n # kmeans++ init\n n = X.shape[0]\n\n def kmeanspp(_X, _k):\n n_inst = _X.shape[0]\n dim = _X.shape[1]\n\n # select initial centroids\n C = np.zeros((_k, dim)) # k++ means\n rands = np.random.randint(0, n_inst)\n C[0, :] = _X[rands]\n\n probs = np.zeros(n_inst)\n\n for centroidN in range(1, _k):\n # compute probabilities for new ctroid\n for recN in range(0, n_inst):\n rec = _X[recN, :]\n\n # compute distance to nearest centroid\n nearest_dist = np.inf\n for exist_centroidN in range(0, centroidN):\n centroid = C[exist_centroidN, :]\n clust_rec_sim = similarity(rec, centroid)\n clust_rec_dist = 0.5 * (1 - clust_rec_sim)\n\n if clust_rec_dist < nearest_dist:\n nearest_dist = clust_rec_dist\n # the probability is proportional to d^2\n probs[recN] = nearest_dist * nearest_dist\n norm_factor = 1.0 / np.sum(probs)\n probs = probs * norm_factor\n\n chosenN = discretesample(probs, 1)[0]\n C[centroidN, :] = _X[chosenN, :]\n print('Chosen centroid {}, probability: {}, max probability: {} '.format(chosenN, probs[centroidN],\n probs.max()))\n return C\n\n C = kmeanspp(X, k)\n prev_assignment = np.zeros(n)\n assignment = np.zeros(n)\n\n change = True\n iterN = 0\n\n while change and iterN < max_iter:\n iterN += 1\n lost_centroid = True\n\n while lost_centroid:\n lost_centroid = False\n\n # assign vectors\n for recN in range(0, n):\n xi = X[recN, :]\n best_idx = -1\n best_sim = np.NINF\n\n for clustN in range(0, k):\n sim = similarity(xi, C[clustN, :])\n if sim > best_sim:\n best_idx = clustN\n best_sim = sim\n\n assignment[recN] = best_idx\n\n # recompute centroids\n for clustN in range(0, k):\n assigned_idxs = assignment == clustN\n\n if assigned_idxs.astype(dtype=int).sum() > 0:\n Yn = X[assigned_idxs, :]\n C[clustN, :] = calc_centroid(Yn)\n else:\n C = kmeanspp(X, k)\n lost_centroid = True\n print(\"Lost a centroid, reinitialized at {}\".format(iterN))\n break\n\n diff = count_diff(assignment, prev_assignment)\n change = diff > 0\n tmp = prev_assignment\n prev_assignment = assignment\n assignment = tmp\n\n return assignment\n\n\ndef k_means_sphere_vectorized(X, k, max_iter=100, debug_assert=False):\n print('running k-means')\n\n # dimensions and other variables\n n = X.shape[0]\n d = X.shape[1]\n\n range_n = range(n)\n range_k = range(k)\n\n # kmeans++ init\n def kmeanspp(_X, _X_norm, _k):\n n_inst = _X_norm.shape[0]\n dim = _X_norm.shape[1]\n\n # select initial centroids\n C = np.empty((_k, dim)) # k++ means\n C_norm_t = np.empty((dim, _k))\n\n rands = np.random.randint(0, n_inst)\n C[0, :] = _X[rands, :]\n C_norm_t[:, 0] = _X_norm[rands, :]\n\n select_prob_vec = np.empty(n_inst)\n mn_clust_dist_vec = np.empty(n_inst)\n\n for centroidN in range(1, _k):\n # compute probabilities for the new centroid\n C_curr_norm_t = C_norm_t[:, :centroidN]\n\n # compute the distance as 0.5*(1 - sim)\n ftrv_clust_dist_mat = np.dot(_X_norm, C_curr_norm_t)\n np.subtract(1, ftrv_clust_dist_mat, out=ftrv_clust_dist_mat)\n np.multiply(0.5, ftrv_clust_dist_mat, out=ftrv_clust_dist_mat)\n\n # for each of the examples compute the distance to the nearest centroid\n np.min(ftrv_clust_dist_mat, axis=1, out=mn_clust_dist_vec)\n\n # the probability of selecting the instance should be\n # proportional to d^2\n np.multiply(mn_clust_dist_vec, mn_clust_dist_vec, select_prob_vec)\n\n prob_sum = np.sum(select_prob_vec)\n if prob_sum < 1e-12:\n np.multiply(np.ones(n_inst), 1 / n_inst, out=select_prob_vec)\n prob_sum = n_inst\n\n norm_factor = 1.0 / prob_sum\n np.multiply(select_prob_vec, norm_factor, out=select_prob_vec)\n\n # sample the new centroid according to the computed distribution\n chosenN = discretesample(select_prob_vec, 1)[0]\n C[centroidN, :] = _X[chosenN, :]\n C_norm_t[:, centroidN] = _X_norm[chosenN, :]\n\n return C\n\n # normalize the rows of X so it will be faster to compute the cosine\n # similarity\n one_by_row_norm_X_vec = np.linalg.norm(X, axis=1)\n np.reciprocal(one_by_row_norm_X_vec, out=one_by_row_norm_X_vec)\n Dx = sparse.csr_matrix((one_by_row_norm_X_vec, (range_n, range_n)), shape=(n, n))\n X_norm = Dx.dot(X)\n del one_by_row_norm_X_vec\n del Dx\n\n if debug_assert:\n # check that the rows of X are of unit length\n row_norm_vec = np.linalg.norm(X_norm, axis=1)\n assert np.linalg.norm(np.ones(n) - row_norm_vec) < 1e-7\n assert isinstance(X_norm, np.ndarray)\n\n C = kmeanspp(X, X_norm, k)\n prev_assignment = -np.ones(n, dtype=int)\n assignment_vec = np.empty(n, dtype=int)\n assign_diff_vec = np.empty(n, dtype=int)\n\n clust_sim_ftrvv = np.empty((n, k))\n clust_sum_vec = np.empty(d)\n\n change = True\n iterN = 0\n\n while change and iterN < max_iter:\n iterN += 1\n lost_centroid = True\n\n if iterN % 10 == 0:\n print('iterN: ' + str(iterN))\n\n # normalize the centroids to make the computation of the cosine\n # similarity faster\n inv_row_norm_C_vec = np.linalg.norm(C, axis=1)\n np.reciprocal(inv_row_norm_C_vec, out=inv_row_norm_C_vec)\n D_one_by_norm = sparse.csr_matrix((inv_row_norm_C_vec, (range_k, range_k)), shape=(k, k))\n C_norm_t = D_one_by_norm.dot(C).T\n\n del inv_row_norm_C_vec\n del D_one_by_norm\n\n if debug_assert:\n # check that the columns of C are of unit length\n col_norm_vec = np.linalg.norm(C_norm_t, axis=0)\n assert np.linalg.norm(np.ones(k) - col_norm_vec) < 1e-7\n assert isinstance(C_norm_t, np.ndarray)\n\n while lost_centroid:\n lost_centroid = False\n\n # assign vectors\n np.dot(X_norm, C_norm_t, out=clust_sim_ftrvv)\n # the assignment is the index of the maximal value\n # in each row\n np.argmax(clust_sim_ftrvv, axis=1, out=assignment_vec)\n\n # recompute centroids\n for clustN in range(0, k):\n assigned_idxs = assignment_vec == clustN\n\n clust_size = np.sum(assigned_idxs)\n\n if clust_size > 0:\n np.dot(assigned_idxs, X, out=clust_sum_vec)\n np.multiply(1 / clust_size, clust_sum_vec, out=C[clustN, :])\n # centroid_ftrvv = (1 / clust_size) * clust_sum_vec\n # C[clustN, :] = centroid_vec\n else:\n C = kmeanspp(X_norm, k)\n lost_centroid = True\n print(\"Lost a centroid, reinitialized at {}\".format(iterN))\n break\n\n # check if the assignments changed\n np.subtract(assignment_vec, prev_assignment, out=assign_diff_vec)\n np.abs(assign_diff_vec, out=assign_diff_vec)\n change = np.sum(assign_diff_vec) > 0\n\n # swap the assignment and prev_assignment vectors\n tmp = prev_assignment\n prev_assignment = assignment_vec\n assignment_vec = tmp\n\n return assignment_vec\n","sub_path":"src/modules/partitioning/k_means_sphere.py","file_name":"k_means_sphere.py","file_ext":"py","file_size_in_byte":8627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"47349299","text":"from torchvision.ops import nms as nms_torch\nfrom ..core import bbox_overlaps\nimport torch\n\ndef batched_iou_nms(bboxes, scores, locs, labels, iou_threshold, score_thr=None):\n \"\"\"IoU guided NMS, bboxes are sorted by iou, score of the current bbox is taking the max of \n scores of all the bboxes suppressed by the bbox.\n \n Args:\n bboxes (Tensor): shape (n, 4)\n scores (Tensor): shape (n,), classification score\n locs (Tensor): shape(n,) iou score\n labels (Tensor): label of bboxes, help to do batched nms\n iou_threshold (float): iou threshold\n score_thr (float): filter scores belowing this number\"\"\"\n filt_mask = scores >= score_thr\n if filt_mask.sum().item() == 0:\n return \\\n bboxes.new_empty(0, 4), \\\n scores.new_empty(0), \\\n locs.new_empty(0), \\\n labels.new_empty(0)\n bboxes = bboxes[filt_mask]\n scores = scores[filt_mask]\n locs = locs[filt_mask]\n labels = labels[filt_mask]\n nms_bboxes = bboxes + (labels * (bboxes.max() + 1)).view(-1, 1)\n \n keep = nms_torch(nms_bboxes, locs, iou_threshold)\n keep_bboxes = nms_bboxes[keep]\n overlaps = bbox_overlaps(keep_bboxes, nms_bboxes)\n # find the suppressed bboxes for each kept bbox\n suppressed = overlaps > iou_threshold\n # accumulate suppression count\n suppressed = suppressed.long().cummax(0)[0].cumsum(0)\n # the real suppressed bboxes should be the ones that are suppressed exactly once\n suppressed = (suppressed == 1)\n span_scores = scores.view(1, overlaps.size(1)).repeat(overlaps.size(0), 1)\n span_scores[~suppressed] = scores.min() - 1\n # taking the max of the suppressed group\n keep_scores = span_scores.max(1)[0]\n # sort by scores, following tradition\n keep_scores, srt_idx = keep_scores.sort(descending=True)\n keep = keep[srt_idx]\n return bboxes[keep], keep_scores, locs[keep], labels[keep]\n\n","sub_path":"mmdet/iounet/nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"269498474","text":"from turtle import *\r\nfrom random import *\r\nfrom math import *\r\n\r\nscreen= getscreen() #Untuk menampilkan layar\r\nscreen.colormode(255) #untuk mensetting colormode menjadi RGB\r\nspeed(10.5) #untuk mengatur kecepatan \r\ntitle(\" Colorful Chessboard and Flowers\") #untuk title screen\r\nscreensize(canvwidth=7000, canvheight=7000, bg=None) #untuk mengatur ukuran canvas\r\nhideturtle() #untuk menyembunyikan turtle\r\nrows = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number of rows\",None,minval=2, maxval=25)) #numinput di gunakan untuk input menggunakan dialog box\r\npixel = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number of square size\",None,minval=2, maxval=None)) \r\npetals = int(screen.numinput(\"Colorful Chessboard and Flowers\",\"Enter the number petals\",None,minval=1, maxval=360))\r\nshowturtle() #untuk menunjukkan turtle\r\npenup()\r\ngoto (0,250)\r\npendown()\r\nsetheading(360/petals) #untuk mengarahkan turtle sesuai dengan sudut yang diberikan, sudut itu dihitung dari x-axis positif\r\npensize(3) #untuk mengatur ketebalan garis cetakan turtle\r\nfor i in range(1,petals+1) :\r\n r = (randint(0,255))\r\n g = (randint(0,255))\r\n b = (randint(0,255))\r\n color((r,g,b),(r,g,b))\r\n pendown()\r\n circle(100,60) #untuk membuat tali busur\r\n right(-120)\r\n circle(100,60)\r\n setheading(360/petals+(360/petals)*i)\r\npenup()\r\nif rows % 2 == 0 : #untuk mengecek barisnya genap atau ganjil\r\n x = -((rows)/2)*pixel \r\n y = 120-pixel\r\n goto (x,y) #untuk menempatkan turtle\r\nelse :\r\n x = -((rows+1)/2)*pixel + (pixel//2)\r\n y = 120-pixel\r\n goto (x,y)\r\nsetheading(90)\r\npensize(0)\r\nfor numb in range(rows) : # loop untuk kolom\r\n for k in range(1,rows+1) : # lopp untuk baris\r\n r = (randint(0,255)) #untuk memberi nilai random pada variable\r\n g = (randint(0,255))\r\n b = (randint(0,255))\r\n color((r,g,b),(r,g,b)) #untuk mengaplikasikan nilai nilai rgb menjadi suatu warna isian dan garis\r\n pendown() #untuk membuat turtle mencetak garis\r\n begin_fill() # untuk memberi tanda awal permulaan pewarnaan\r\n for j in range(4) : #loop untuk membuat persegi\r\n forward(pixel) #untuk membuat turtle bergerak maju\r\n right(90) #untuk membuat turtle belok sebesar 90 derajat\r\n end_fill() #untuk memberi tanda akhir pewarnaan\r\n penup()\r\n goto(x+(pixel*k),y)\r\n y = y - pixel\r\n goto(x,y)\r\ntext = \"Colorful Chessboard of \" + str(rows**2) + \" Squares and Flower of \" + str(petals) + \" Petals\"\r\ngoto(0,(-pixel*rows)+50)\r\ncolor(\"blue\")\r\nwrite(text,align='center',font=('Arial',16,'normal')) #untuk menulis text di canvas\r\nhideturtle()\r\nexitonclick() #untuk memerintahkan agar exit pada saat canvas di klik\r\n\r\n \r\n\r\n\r\n \r\n","sub_path":"Archive-Code/B_PDD_1806235832_DiptaLaksmanaBaswaraD_Tugas01.py","file_name":"B_PDD_1806235832_DiptaLaksmanaBaswaraD_Tugas01.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"390374631","text":"import speech_recognition as sr \nimport colorama\nfrom colorama import Fore as f\n \nAUDIO_FILE = (input(\"Enter the Files Name: \")+\".wav\") \n \n# use the audio file as the audio source \n \nr = sr.Recognizer() \n \nwith sr.AudioFile(AUDIO_FILE) as source: \n\n audio = r.record(source) #Reads the audio file\n \ntry: \n\tprint(f.LIGHTGREEN_EX + \"Success\")\n\tprint(f.LIGHTYELLOW_EX + \"The audio file contains: \" + f.LIGHTBLUE_EX + r.recognize_google(audio)) \n \nexcept sr.UnknownValueError: \n print(f.LIGHTRED_EX + \"Google Speech Recognition could not understand the audio\") \n \nexcept sr.RequestError as e: \n print(f.LIGHTRED_EX + \"Could not request results from Google Speech Recognition service; {0}\".format(e)) \n","sub_path":"Update.py","file_name":"Update.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"499113619","text":"import torchvision.transforms as transforms\nfrom PIL import Image\nfrom torch.utils.data import Dataset, DataLoader\nimport random\nimport json\nimport os\nfrom os.path import join\nimport torch\nimport numpy as np\n\n\nclass PatchAllface(Dataset):\n def __init__(self, txtpath, transform):\n self.data_json = json.load(open(txtpath))\n self.transform = transform\n\n def __getitem__(self, idx):\n video_paths = self.data_json[idx]\n fake_video_path, real_video_path = video_paths\n\n fake_image_names = os.listdir(fake_video_path)\n fake_image_nums = np.linspace(0, len(fake_image_names) - 1, 10, dtype=int).tolist()\n fake_image_names = [fake_image_names[num] for num in fake_image_nums]\n fake_image_paths = [join(fake_video_path, image_name) for image_name in fake_image_names]\n fake_images = [Image.open(imagepath).convert('RGB') for imagepath in fake_image_paths]\n\n real_image_names = os.listdir(real_video_path)\n real_image_nums = np.linspace(0, len(real_image_names) - 1, 10, dtype=int).tolist()\n real_image_names = [real_image_names[num] for num in real_image_nums]\n real_image_paths = [join(real_video_path, image_name) for image_name in real_image_names]\n real_images = [Image.open(imagepath).convert('RGB') for imagepath in real_image_paths]\n\n fake_images = [self.transform(image) for image in fake_images]\n real_images = [self.transform(image) for image in real_images]\n\n fake_images = torch.stack(fake_images, dim=0)\n real_images = torch.stack(real_images, dim=0)\n\n if random.randint(0, 1) == 0:\n images = torch.stack((real_images, fake_images), dim=0)\n label = torch.tensor([0, 1])\n else:\n images = torch.stack((fake_images, real_images), dim=0)\n label = torch.tensor([1, 0])\n return images, label\n\n def __len__(self):\n return len(self.data_json)\n\n\ntransform_train = transforms.Compose([\n transforms.Resize((299, 299)),\n transforms.RandomVerticalFlip(),\n transforms.RandomHorizontalFlip(),\n transforms.RandomRotation(15),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\ntransform_test = transforms.Compose([\n transforms.Resize((299, 299)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n])\n\n\ndef get_dataloader(BATCH_SIZE):\n datatrain = \"/root/data/wzy/datalocker/corres_large_factor_train.json\"\n dataval = \"/root/data/wzy/datalocker/corres_large_factor_validate.json\"\n data_image = PatchAllface(txtpath=datatrain, transform=transform_train)\n data_loader_image = DataLoader(dataset=data_image, shuffle=True, batch_size=BATCH_SIZE, num_workers=4)\n test_data = PatchAllface(txtpath=dataval, transform=transform_test)\n test_data_loader = DataLoader(dataset=test_data, shuffle=False, batch_size=BATCH_SIZE, num_workers=4)\n\n return data_loader_image, test_data_loader\n\n\nif __name__ == '__main__':\n train_dataloader, test_dataloader = get_dataloader(16)\n for video_images, video_label in train_dataloader:\n video_images = video_images.view(16 * 2, 8, 3, 299, 299)\n video_label = video_label.view(16 * 2)\n video_images = video_images.permute(0, 2, 1, 3, 4)\n print(video_images.size())\n exit()\n","sub_path":"dataloader/dataloader_face_corredpond_299.py","file_name":"dataloader_face_corredpond_299.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"16588292","text":"#! /usr/bin/env python\n# -*- mode: python; coding: utf-8 ; python-indent: 2 -*-\n\nimport downstream as ds\nnewdir = \"/data/videos/hp2012/\"\n\nimport sys, os\nsys.path.append('..')\nimport vsutils as vsu\n\narg = sys.argv[1]\nif not os.path.isfile(arg):\n sys.exit(0)\nf = file(arg)\nauthor=''\nname=''\nfor l in f.readlines():\n if l[0]=='*': \n author=l.split()[1].strip()\n if l[0:4]==\"http\": \n url = l.split()[0]\n ds.transcode_youtube(url.strip(), newdir)\n","sub_path":"va_chercher_fichier_liens.py","file_name":"va_chercher_fichier_liens.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"621714762","text":"from skimage import data, filters,io, feature, morphology\nimport matplotlib.pyplot as plt\nimport findtraces\nimport drawtraces\n\ndef main(imgpath, sigma, speed):\n img = io.imread(imgpath, as_grey=True)\n img = feature.canny(img, sigma=sigma)\n print(\"关闭图像窗口后将会开始绘制\")\n plt.imshow(img, cmap=\"gray\")\n plt.show()\n traces = findtraces.do(img==False)\n drawtraces.do(traces, img.shape[0], img.shape[1])\n\nif __name__ == '__main__':\n import sys\n if(len(sys.argv) < 2):\n print(\"缺少参数(fundraw.py [] [])\")\n else:\n imgpath = sys.argv[1]\n sigma = float(sys.argv[2]) if len(sys.argv)>=3 else 2\n speed = int(sys.argv[3]) if len(sys.argv)>=4 else 10\n main(imgpath=imgpath, sigma=sigma, speed=speed)\n","sub_path":"Python/素描图片/fundraw.py","file_name":"fundraw.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"245937495","text":"#sequenceingsPrimers\n\nfrom Bio.Blast import NCBIWWW\nfrom Bio.Blast import NCBIXML\nfile_string = \"\" \nx = 1\nn=1\n\nfasta_files = [\"result\"]\nfor i in fasta_files:\n File = open(\"output\"+str(x)+\".txt\",\"w\")\n fasta_string = open(i+\".fasta\").read() #or make the names fasta1.fasta and just do open(i).read\n result_handle = NCBIWWW.qblast(\"blastn\", \"nr\", fasta_string, hitlist_size=10)\n\n #blast_records = NCBIXML.parse(result_handle) \n blast_record = NCBIXML.read(result_handle)# if you only have one seq in file\n E_VALUE_THRESH = 0.001\n for blast_record in blast_record:\n for alignment in blast_record.alignments:\n for hsp in alignment.hsps:\n if hsp.expect < E_VALUE_THRESH:\n file_string += \"alignment:\",alignment.title+\"\\n\"\n file_string += \"e-value:\",hsp.expect+\"\\n\"\n x += 1\n File.write(file_string)\n","sub_path":"SeqAuto.py","file_name":"SeqAuto.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"562888020","text":"import sys\nsys.stdin = open('2007. 패턴 마디의 길이.txt')\n\nt = int(input())\nfor tc in range(1, t+1):\n array = list(input())\n # print(array)\n\n minLen = 10\n for i in range(10, 0, -1):\n if array[0:i] == array[i:i*2]:\n if i < minLen: minLen = i\n \n print('#{} {}'.format(tc, minLen))","sub_path":"SWExpert/D2/2007. 패턴 마디의 길이.py","file_name":"2007. 패턴 마디의 길이.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"243298483","text":"import threading\n\nimport discord\n\nimport brian.AI as train\nimport brian.getreply as rp\nfrom brian.update_dataset import main, create_text_review\n\ntrain_bot = train.AI()\nclient = discord.Client()\ncachemsg = []\ndataset_raw = []\nreply = rp.getrply()\nidreply = []\n\n\ndef train_reload():\n train_bot.train()\n reply.__init__()\n print('reload models')\n\ndef save_text_raw(fpath: dir, data):\n file = open(fpath, \"a+\", encoding=\"utf-8\")\n for item in data:\n file.write(\"{}<=:=>{}|=:=|{}\\n\".format(item[0], item[1], item[2]))\n file.close()\n\n\n@client.event\nasync def on_ready():\n print('Đang khởi chạy')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n\n@client.event\nasync def on_message(ctx):\n idnow = 0\n if ctx.reference:\n idnow = ctx.reference.message_id\n cachemsg.append((ctx.id, ctx.content))\n if (ctx.author == client.user):\n idreply.append(ctx.id)\n return\n idref = ctx.reference\n if idref != None:\n idref = idref.message_id\n for item in cachemsg:\n if item[0] == idref:\n msg, tag = reply.chatbot_response(msg=item[1])\n dataset_raw.append((item[1], ctx.content, tag))\n print(cachemsg)\n print(dataset_raw)\n if len(idreply) >= 100:\n for item in idreply[0:50]:\n idreply.remove(item)\n if len(cachemsg) >= 100:\n for item in cachemsg[0:50]:\n cachemsg.remove(item)\n if (ctx.channel.id == 863726369951580210) or (ctx.channel.id == 861883913009889290) or (idnow in idreply) or (\n 'bot' in ctx.content.lower().replace(',', '').replace('.', '').split(\" \")):\n msg, tag = reply.chatbot_response(msg=ctx.content)\n await ctx.reply(msg, mention_author=True)\n if len(dataset_raw) >= 100:\n save_text_raw('brian/data/raw.txt', dataset_raw)\n dataset_raw.clear()\n main('brian/data/raw.txt', 'brian/data/intents.json')\n # train and reload\n th1 = threading.Thread(target=train_reload)\n th1.start()\n if ctx.channel.id == 861544200045592597:\n if ctx.content == 'học':\n save_text_raw('brian/data/raw.txt', dataset_raw)\n dataset_raw.clear()\n main('brian/data/raw.txt', 'brian/data/intents.json')\n # train and reload\n th1 = threading.Thread(target=train_reload)\n th1.start()\n if ctx.content == 'xemdataset':\n create_text_review()\n await ctx.channel.send(file=discord.File('brian/data/textout.txt'))\n\n\nclient.run(\"TOKEN\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"4707626","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nfrom baseline_agent import BaselineAgent\nfrom adv_human import AdvancedHumanAgent\nfrom adv_human_mistake import AdvancedHumanMistakeAgent\n# from adv_human_mistake2 import AdvancedHumanMistake2Agent\nfrom training_observer import TrainingObserver\n# from mdk2 import MDK2\nimport sys\nimport argparse\nfrom random import seed\nimport numpy as np\nimport json\n\n\nfrom hanabi_learning_environment import pyhanabi\n\n\nclass ModObservation(pyhanabi.HanabiObservation):\n def __init__(self):\n self.obs = None\n self.obs_cards = None\n moves = []\n for card_index in range(5):\n moves.append(pyhanabi.HanabiMove.get_play_move(card_index))\n moves.append(pyhanabi.HanabiMove.get_discard_move(card_index))\n moves.append(pyhanabi.HanabiMove.get_reveal_color_move(1, card_index))\n moves.append(pyhanabi.HanabiMove.get_reveal_rank_move(1, card_index))\n self.moves = moves\n self._observation = None\n self.flag = 1\n\n def observation(self):\n \"\"\"Returns the C++ HanabiObservation object.\"\"\"\n return self._observation\n\n def cur_player_offset(self):\n \"\"\"Returns the player index of the acting player, relative to observer.\"\"\"\n return self.flag\n\n def num_players(self):\n \"\"\"Returns the number of players in the game.\"\"\"\n return self.obs.num_players()\n\n def observed_hands(self):\n \"\"\"Returns a list of all hands, with cards ordered oldest to newest.\n\n The observing player's cards are always invalid.\n \"\"\"\n return self.obs_cards\n\n def card_knowledge(self):\n \"\"\"Returns a per-player list of hinted card knowledge.\n\n Each player's entry is a per-card list of HanabiCardKnowledge objects.\n Each HanabiCardKnowledge for a card gives the knowledge about the cards\n accumulated over all past reveal actions.\n \"\"\"\n return self.obs.card_knowledge()\n\n def discard_pile(self):\n \"\"\"Returns a list of all discarded cards, in order they were discarded.\"\"\"\n return self.obs.discard_pile()\n\n def fireworks(self):\n \"\"\"Returns a list of fireworks levels by value, ordered by color.\"\"\"\n return self.obs.fireworks()\n\n def deck_size(self):\n \"\"\"Returns number of cards left in the deck.\"\"\"\n return self.obs.deck_size()\n\n def last_moves(self):\n \"\"\"Returns moves made since observing player last acted.\n\n Each entry in list is a HanabiHistoryItem, ordered from most recent\n move to oldest. Oldest move is the last action made by observing\n player. Skips initial chance moves to deal hands.\n \"\"\"\n return self.obs.last_moves()\n\n def information_tokens(self):\n \"\"\"Returns the number of information tokens remaining.\"\"\"\n return self.obs.information_tokens()\n\n def life_tokens(self):\n \"\"\"Returns the number of information tokens remaining.\"\"\"\n return self.obs.life_tokens()\n\n def legal_moves(self):\n \"\"\"Returns list of legal moves for observing player.\n\n List is empty if cur_player() != 0 (observer is not currently acting).\n \"\"\"\n return self.moves\n\n\n def card_playable_on_fireworks(self, color, rank):\n return self.obs.card_playable_on_fireworks(color, rank)\n\ndef run_game(game_parameters, agents, trainmodel=None, verbose=1, train=False):\n \"\"\"Play a game, selecting random actions.\"\"\"\n\n def print_state(state):\n \"\"\"Print some basic information about the state.\"\"\"\n print(\"\")\n print(\"Current player: {}\".format(state.cur_player()))\n print(state)\n\n # Example of more queries to provide more about this state. For\n # example, bots could use these methods to to get information\n # about the state in order to act accordingly.\n print(\"### Information about the state retrieved separately ###\")\n print(\"### Information tokens: {}\".format(state.information_tokens()))\n print(\"### Life tokens: {}\".format(state.life_tokens()))\n print(\"### Fireworks: {}\".format(state.fireworks()))\n print(\"### Deck size: {}\".format(state.deck_size()))\n print(\"### Discard pile: {}\".format(str(state.discard_pile())))\n print(\"### Player hands: {}\".format(str(state.player_hands())))\n print(\"\")\n\n def print_observation(observation):\n \"\"\"Print some basic information about an agent observation.\"\"\"\n print(\"--- Observation ---\")\n print(observation)\n\n print(\"### Information about the observation retrieved separately ###\")\n print(\"### Current player, relative to self: {}\".format(\n observation.cur_player_offset()))\n print(\"### Observed hands: {}\".format(observation.observed_hands()))\n print(\"### Card knowledge: {}\".format(observation.card_knowledge()))\n print(\"### Discard pile: {}\".format(observation.discard_pile()))\n print(\"### Fireworks: {}\".format(observation.fireworks()))\n print(\"### Deck size: {}\".format(observation.deck_size()))\n move_string = \"### Last moves:\"\n for move_tuple in observation.last_moves():\n move_string += \" {}\".format(move_tuple)\n print(move_string)\n print(\"### Information tokens: {}\".format(observation.information_tokens()))\n print(\"### Life tokens: {}\".format(observation.life_tokens()))\n print(\"### Legal moves: {}\".format(observation.legal_moves()))\n print(\"--- EndObservation ---\")\n\n def print_encoded_observations(encoder, state, num_players):\n print(\"--- EncodedObservations ---\")\n print(\"Observation encoding shape: {}\".format(encoder.shape()))\n print(\"Current actual player: {}\".format(state.cur_player()))\n for i in range(num_players):\n print(\"Encoded observation for player {}: {}\".format(\n i, encoder.encode(state.observation(i))))\n print(\"--- EndEncodedObservations ---\")\n\n game = pyhanabi.HanabiGame(game_parameters)\n\n encoder = pyhanabi.ObservationEncoder(game)\n mod_obs = [ModObservation() for _ in range(len(agents) + train)]\n\n if verbose > 3:\n print(game.parameter_string(), end=\"\")\n obs_encoder = pyhanabi.ObservationEncoder(\n game, enc_type=pyhanabi.ObservationEncoderType.CANONICAL)\n\n state = game.new_initial_state()\n last_mistake, move, mistake = None, None, None\n while not state.is_terminal():\n if state.cur_player() == pyhanabi.CHANCE_PLAYER_ID:\n state.deal_random_card()\n continue\n\n observation = state.observation(state.cur_player())\n\n for idx, agt in enumerate(agents):\n if idx == state.cur_player():\n last_mistake = mistake\n move, mistake = agt.act2(observation)\n # print('Move:', move, mistake)\n else:\n mod_obs[idx].obs = observation\n mod_obs[idx].obs_cards = None\n mod_obs[idx].flag = 1\n agt.act(mod_obs[idx])\n if train:\n mod_obs[-1].obs = observation\n mod_obs[-1].obs_cards = None\n mod_obs[-1].flag = 1\n trainmodel.act3(mod_obs[-1], last_mistake)\n\n state.apply_move(move)\n\n if verbose > 3:\n print_state(state)\n print_observation(observation)\n if verbose > 4:\n print_encoded_observations(obs_encoder, state, game.num_players())\n print(\"\")\n print(\"Number of legal moves: {}\".format(len(observation.legal_moves())))\n if verbose > 2:\n print(\"Agent has chosen: {}\".format(move))\n if verbose > 2:\n print(\"\")\n print(\"Game done. Terminal state:\")\n print(\"\")\n print(state)\n print(\"\")\n if verbose > 1:\n print(\"score: {}\".format(state.score()))\n return state.score()\n\n\nreinforcement_agents = []\n\np = argparse.ArgumentParser(prog='PROG')\np.add_argument('foo')\nfor i in [('-p', 'players', 2, int), ('-c', 'colors', 5, int), ('-r', 'rank', 5, int), ('-hs', 'hand_size', 5, int),\n ('-i', 'max_information_tokens', 8, int), ('-l', 'max_life_tokens', 3, int), ('-s', 'seed', -1, int),\n ('-v', 'verbose', 0, int), ('-n', 'num_rounds', 1, int), ('-tr', 'training_rounds', 0, int),\n ('-al', 'alpha', 0.05, float), ('-a2', 'alpha2', 0, float), ('-a3', 'alpha3', 0, float), ('-t', 'train', 1, int)]:\n p.add_argument(i[0], dest=i[1], default=i[2], type=i[3])\np.add_argument('-a', dest='agents', default=['baseline', 'baseline'], nargs='*')\nargs = vars(p.parse_args(sys.argv))\nagent_dict = {'baseline': BaselineAgent, 'advhm': AdvancedHumanMistakeAgent, 'advh': AdvancedHumanAgent,\n 'mdk': TrainingObserver}\n\nseed(1)\nscore_list = []\ntraining_to_go = args['training_rounds']\nagents=[]\nlabels = []\nargs['print'] = 0\nfor agent in args['agents']:\n agents.append(agent_dict[agent](args))\ntrainagt = TrainingObserver(args)\n\nfor _ in range(args['num_rounds']):\n if _%50 == 0 and args['verbose'] >= 0:\n print('#################'+str(_))\n if _ == args['num_rounds'] - 1:\n args['print'] = 1\n for agent in agents:\n agent.reset(args)\n trainagt.reset(args)\n score_list.append(run_game(args, agents, trainmodel=trainagt, verbose=args['verbose'], train=True))\n\nif args['verbose'] >= 0:\n print(sum(score_list)/args['num_rounds'])\n agents = agents[:-1] + [trainagt]\n score_list=[]\n print('##################################')\n\n if args['train'] == 1:\n '''trainagt.k_means()\n print('Clusters: ')\n print(trainagt.clusters)\n np.savetxt('./clusters.txt', trainagt.clusters)'''\n data = np.concatenate([trainagt.data, np.array(trainagt.labels).reshape((-1,1))], axis=1)\n np.savetxt('./train_data.txt', data)\n\n trainagt = TrainingObserver(args)\n for _ in range(args['num_rounds']):\n if _%50 == 0 and args['verbose'] >= 0:\n print('#################'+str(_))\n if _ == args['num_rounds'] - 1:\n args['print'] = 1\n for agent in agents:\n agent.reset(args)\n trainagt.reset(args)\n score_list.append(run_game(args, agents, trainmodel=trainagt, verbose=args['verbose'], train=True))\n data = np.concatenate([trainagt.data, np.array(trainagt.labels).reshape((-1, 1))], axis=1)\n np.savetxt('./val_data.txt', data)\n\n","sub_path":"gen_model_data.py","file_name":"gen_model_data.py","file_ext":"py","file_size_in_byte":11029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"88607844","text":"\n\"\"\"\n\nWrite a program that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates.\n\n\"\"\"\n\nimport numpy\n\n# The first function used for and if to iterate the elements in that list\ndef dupe1(a):\n y=[]\n for i in a:\n if i not in y:\n y.append(i)\n y.sort()\n return y\n\n# The second one used list(set(a)) to remove duplicates directly.\ndef dupe2(a):\n return list(set(a))\n\na=[1,2,3,5,6,7,5,4,2,1]\nprint(dupe1(a))\nprint(dupe2(a))\n","sub_path":"First Programs/List of set.py","file_name":"List of set.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"574698206","text":"import traceback\nimport sys\nfrom discord.ext import commands\nimport discord\nimport asyncio\n\n\nclass errors_Cog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n embed = discord.Embed(colour=discord.Colour(0xa9219b))\n\n #embed.set_image(url=\"https://cdn.discordapp.com/embed/avatars/0.png\")\n embed.set_thumbnail(url=\"https://n0tj.com/g_center.png\")\n embed.set_author(name=\"Join the gearBot discord\", url=\"https://discord.gg/jZAJ7Yy\", icon_url=\"https://n0tj.com/g_center.png\")\n embed.set_footer(text=\"Message jay#8008 with any bugs or concerns.\", icon_url=\"https://n0tj.com/buddha.jpeg\")\n embed.add_field(name=\"**Updating your gear screenshot**\", value=\"**!gear **\")\n embed.add_field(name=\"**Looking up someone or your own gear**\", value=\"**!gear <@user>**\")\n\n\n await ctx.send(embed=embed)\n\n\ndef setup(bot):\n bot.add_cog(errors_Cog(bot))\n","sub_path":"cogs/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"484997514","text":"from time import sleep\nimport Adafruit_GPIO.SPI as SPI\nimport Adafruit_SSD1306\nimport Adafruit_LSM303\nimport RPi.GPIO as GPIO\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(17, GPIO.IN)\n\nRST = 24\nDC = 23\nSPI_PORT = 0\nSPI_DEVICE = 0\n\nlsm303 = Adafruit_LSM303.LSM303()\ndisp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3d)\ndisp.begin()\n\ndisp.clear()\ndisp.display()\n\nwidth = disp.width\nheight = disp.height\nimage = Image.new('1', (width, height))\n\npadding = 2\nshape_width = 20\ntop = padding\nbottom = height-padding\n# x = padding\nfont = ImageFont.load_default()\n\ndata = []\nlength = 25\ngraphWidth = 110\ngraphHeight = 50\nxPadding = width - graphWidth\nspacing = graphWidth / length\nyAxisText = 'a(m/s^2)'\n#batteryFull = None\nshowIcon = False\nflashCounter = 0\n\ndef mapNum(value, leftMin, leftMax, rightMin, rightMax):\n leftSpan = leftMax - leftMin\n rightSpan = rightMax - rightMin\n valueScaled = float(value - leftMin) / float(leftSpan)\n return rightMin + (valueScaled * rightSpan)\n\nwhile True:\n accel, mag = lsm303.read()\n accel_x, accel_y, accel_z = accel\n mag_x, mag_y, mag_z = mag\n\n accel_x /= 100\n accel_y /= 100\n accel_z /= 100\n\n draw = ImageDraw.Draw(image)\n draw.rectangle((0,0,width,height), outline=0, fill=0)\n\n data.append(accel_x)\n if(len(data) > length) :\n data.pop(0)\n\n draw.line((xPadding, 5, xPadding, graphHeight), fill=255)\n draw.line((xPadding, graphHeight, width -5, graphHeight), fill=255)\n draw.text((width / 2, graphHeight + 5), 't(s)', font=font, fill=255)\n #draw.line((width - width, graphHeight / 2), yAxisText, font = font, fill=255)\n\n rotImg = Image.new('1',\n (font.getsize(yAxisText)[0] + 2,\n font.getsize(yAxisText)[1] + 2), color=0)\n rotDraw = ImageDraw.Draw(rotImg)\n rotDraw.text((0,0), yAxisText, fill = 255)\n rotImg = rotImg.rotate(90, expand = 1)\n image.paste(rotImg, (2, top))\n\n for x, y in enumerate(data):\n if(x < len(data) -1):\n draw.line((\n (x * spacing) + xPadding,\n ((mapNum(y, -10, 10, 0, graphHeight))),\n ((x + 1) * spacing) + xPadding,\n ((mapNum(data[x+1], -10, 10, 0, graphHeight)))),\n fill = 255)\n\n# batteryFull = GPIO.input(17)\n\n if(flashCounter > 1):\n showIcon = False if(showIcon) else True\n flashCounter = 0\n else:\n flashCounter += 1\n#\n# if(showIcon and batteryFull == 0):\n# draw.rectangle((width - 20, 4, width - 7, 10), outline=255, fill=0)\n# draw.rectangle((width - 20, 4, width - 17, 10), outline=255, fill=255)\n# draw.rectangle((width - 7, 6, width - 5, 8), outline=255, fill=255)\n# elif(batteryFull == 1):\n# draw.rectangle((width - 20, 4, width - 7, 10), outline=255, fill=0)\n# draw.rectangle((width - 20, 4, width - 11, 10), outline=255, fill=255)\n# draw.rectangle((width - 7, 6, width - 5, 8), outline=255, fill=255)\n \n disp.image(image)\n disp.display()\n sleep(0.01)\n","sub_path":"Python/headless.py","file_name":"headless.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"162679667","text":"import scipy.io\r\nimport numpy as np\r\nfrom datascience import Table\r\nfrom sklearn import svm\r\nimport pandas as pd\r\n\r\npd.set_option('display.max_columns', 500)\r\npd.set_option('display.width', 1000)\r\n\r\n#--------------------------------------DATA EXTRACTION--------------------------------------\r\ndef read_file(file_name,data_type):\r\n mat = scipy.io.loadmat(file_name)\r\n if data_type == 1:\r\n RWEM = mat['rwe']\r\n return RWEM\r\n elif data_type == 2:\r\n EM = mat['em']\r\n return EM\r\n elif data_type == 3:\r\n SM = mat['sm']\r\n return SM\r\n elif data_type == 4:\r\n AM = mat['am']\r\n return AM\r\n \r\ndef allData(file,data_type,test_type):\r\n data = [[],[]]\r\n dataMatrix = read_file(file,data_type)\r\n l = len(dataMatrix)\r\n if test_type == 1:\r\n for i in range(l):\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(dataMatrix[i,-2])\r\n elif test_type == 2:\r\n for i in range(l):\r\n if dataMatrix[i,-1] == 1:\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(dataMatrix[i,-2])\r\n return data\r\n\r\ndef allWordData(file,data_type,word,test_type):\r\n possible_words = ['A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n index = possible_words.index(word)+1\r\n dataMatrix = read_file(file,data_type)\r\n l = len(dataMatrix)\r\n data = [[],[]]\r\n if test_type == 1:\r\n for i in range(l):\r\n if dataMatrix[i,-2] == index:\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(file[:3])\r\n elif test_type == 2:\r\n for i in range(l):\r\n if (dataMatrix[i,-2] == index) and (dataMatrix[i,-1] == 1):\r\n data[0].append(dataMatrix[i,0:-3])\r\n data[1].append(file[:3])\r\n\r\n return data\r\n\r\n\r\n#--------------------------------------CLASSIFICATION---------------------------------------\r\n\r\ndef classification(training_data,labels,prediction_values,real_labels,c,g): \r\n clf = svm.SVC(C=c,gamma=g,cache_size=10000,class_weight='balanced')\r\n clf.fit(training_data,labels) \r\n algorithm_labels = clf.predict(prediction_values) \r\n comparisson = []\r\n for i in range(len(algorithm_labels)):\r\n if algorithm_labels[i] == real_labels[i]:\r\n comparisson.append(1)\r\n else:\r\n comparisson.append(0)\r\n accuracy = (sum(comparisson)/len(comparisson))*100\r\n results = [algorithm_labels,real_labels,accuracy]\r\n return results\r\n\r\n\r\n#------------------------------------------TESTS--------------------------------------------\r\n\r\ndef loocv(excluded,all_files,data_type,g,c,test_type):\r\n training_set = []\r\n for i in all_files:\r\n training_set.append(i)\r\n training_set.remove(excluded)\r\n training_data = []\r\n training_labels = []\r\n for i in training_set:\r\n data = allData(i,data_type,test_type)\r\n for j in data[0]:\r\n training_data.append(j)\r\n for j in data[1]:\r\n training_labels.append(j)\r\n data = allData(excluded,data_type,test_type)\r\n prediction_data = []\r\n prediction_labels = data[1]\r\n for i in data[0]:\r\n prediction_data.append(i)\r\n results = classification(training_data,training_labels,prediction_data,prediction_labels,g,c)\r\n codes = [1,2,3,4,5,6,7,8,9,10,11]\r\n total_codes = [0,0,0,0,0,0,0,0,0,0,0]\r\n for i in results[1]:\r\n total_codes[int(i)-1]+=1\r\n predicted_codes = [0,0,0,0,0,0,0,0,0,0,0]\r\n for i in range(len(results[0])):\r\n if results[0][i] == results[1][i]:\r\n predicted_codes[int(results[0][i])-1]+=1\r\n codes_accuracy = []\r\n for i in range(11):\r\n codes_accuracy.append((predicted_codes[i]/total_codes[i])*100)\r\n return [codes_accuracy,results[2]]\r\n\r\ndef tfcv(word,files,data_type,c,g,test_type):\r\n all_possibilities = []\r\n for file in files:\r\n data = allWordData(file,data_type,word,test_type)\r\n for i in range(len(data[0])):\r\n all_possibilities.append((data[0][i],data[1][i]))\r\n for i in range(np.random.choice(3,1)[0]+1):\r\n np.random.shuffle(all_possibilities)\r\n training_set = np.random.choice(len(all_possibilities),int(len(all_possibilities)*0.75),replace=False)\r\n training_data = []\r\n training_labels = []\r\n prediction_data = []\r\n prediction_labels = []\r\n for i in range(len(all_possibilities)):\r\n data = all_possibilities[i]\r\n if i in training_set:\r\n training_data.append(data[0])\r\n training_labels.append(data[1])\r\n else:\r\n prediction_data.append(data[0])\r\n prediction_labels.append(data[1])\r\n results = classification(training_data,training_labels,prediction_data,prediction_labels,c,g) \r\n codes = ['S01','S02','S03','S04','S05','S06','S07','S08','S09','S10','S11','S12','S13','S14','S15']\r\n total_codes = []\r\n for i in codes:\r\n total_codes.append(results[1].count(i))\r\n predicted_codes = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\r\n for i in range(len(results[0])):\r\n if results[0][i] == results[1][i]:\r\n predicted_codes[int(results[0][i][1:])-1]+=1\r\n codes_accuracy = []\r\n for i in range(15):\r\n if total_codes[i] != 0:\r\n codes_accuracy.append((predicted_codes[i]/total_codes[i])*100)\r\n else:\r\n if predicted_codes[i] == 0:\r\n codes_accuracy.append(100)\r\n else:\r\n codes_accuracy.append(0)\r\n return [codes_accuracy,results[2]]\r\n\r\ndef leaveOneOutCrossValidation(data_type,c,g,test_type):\r\n if data_type == 1:\r\n files = ['S01_RWEM.mat','S02_RWEM.mat','S03_RWEM.mat','S04_RWEM.mat','S05_RWEM.mat','S06_RWEM.mat','S07_RWEM.mat','S08_RWEM.mat','S09_RWEM.mat','S10_RWEM.mat','S11_RWEM.mat','S12_RWEM.mat','S13_RWEM.mat','S14_RWEM.mat','S15_RWEM.mat'] \r\n elif data_type == 2:\r\n files = ['S01_EM.mat','S02_EM.mat','S03_EM.mat','S04_EM.mat','S05_EM.mat','S06_EM.mat','S07_EM.mat','S08_EM.mat','S09_EM.mat','S10_EM.mat','S11_EM.mat','S12_EM.mat','S13_EM.mat','S14_EM.mat','S15_EM.mat'] \r\n elif data_type == 3:\r\n files = ['S01_SM.mat','S02_SM.mat','S03_SM.mat','S04_SM.mat','S05_SM.mat','S06_SM.mat','S07_SM.mat','S08_SM.mat','S09_SM.mat','S10_SM.mat','S11_SM.mat','S12_SM.mat','S13_SM.mat','S14_SM.mat','S15_SM.mat'] \r\n elif data_type == 4:\r\n files = ['S01_AM.mat','S02_AM.mat','S03_AM.mat','S04_AM.mat','S05_AM.mat','S06_AM.mat','S07_AM.mat','S08_AM.mat','S09_AM.mat','S10_AM.mat','S11_AM.mat','S12_AM.mat','S13_AM.mat','S14_AM.mat','S15_AM.mat'] \r\n results = []\r\n for file in files:\r\n results.append(loocv(file,files,data_type,c,g,test_type))\r\n table_rows = []\r\n means = [[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for i in results:\r\n row = []\r\n row.append(i[1])\r\n means[0].append(i[1])\r\n for j in range(len(i[0])):\r\n row.append(i[0][j])\r\n means[j+1].append(i[0][j])\r\n table_rows.append(row)\r\n mean = []\r\n for i in means:\r\n mean.append(np.mean(i))\r\n codes = ['General accuracy','A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n T = Table().with_columns('Codes',codes,'S01',table_rows[0],'S02',table_rows[1],'S03',table_rows[2],'S04',table_rows[3],'S05',table_rows[4],'S06',table_rows[5],'S07',table_rows[6],'S08',table_rows[7],'S09',table_rows[8],'S10',table_rows[9],'S11',table_rows[10],'S12',table_rows[11],'S13',table_rows[12],'S14',table_rows[13],'S15',table_rows[14],'MEAN',mean)\r\n df = T.to_df()\r\n df = df.round(3)\r\n return df\r\n\r\ndef tenFoldCrossValidation(data_type,c,g,test_type):\r\n if data_type == 1:\r\n files = ['S01_RWEM.mat','S02_RWEM.mat','S03_RWEM.mat','S04_RWEM.mat','S05_RWEM.mat','S06_RWEM.mat','S07_RWEM.mat','S08_RWEM.mat','S09_RWEM.mat','S10_RWEM.mat','S11_RWEM.mat','S12_RWEM.mat','S13_RWEM.mat','S14_RWEM.mat','S15_RWEM.mat'] \r\n elif data_type == 2:\r\n files = ['S01_EM.mat','S02_EM.mat','S03_EM.mat','S04_EM.mat','S05_EM.mat','S06_EM.mat','S07_EM.mat','S08_EM.mat','S09_EM.mat','S10_EM.mat','S11_EM.mat','S12_EM.mat','S13_EM.mat','S14_EM.mat','S15_EM.mat'] \r\n elif data_type == 3:\r\n files = ['S01_SM.mat','S02_SM.mat','S03_SM.mat','S04_SM.mat','S05_SM.mat','S06_SM.mat','S07_SM.mat','S08_SM.mat','S09_SM.mat','S10_SM.mat','S11_SM.mat','S12_SM.mat','S13_SM.mat','S14_SM.mat','S15_SM.mat'] \r\n elif data_type == 4:\r\n files = ['S01_AM.mat','S02_AM.mat','S03_AM.mat','S04_AM.mat','S05_AM.mat','S06_AM.mat','S07_AM.mat','S08_AM.mat','S09_AM.mat','S10_AM.mat','S11_AM.mat','S12_AM.mat','S13_AM.mat','S14_AM.mat','S15_AM.mat'] \r\n words = ['A','E','I','O','U','Arriba','Abajo','Adelante','Atrás','Derecha','Izquierda']\r\n whole_table = []\r\n aux = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for word in words:\r\n results=[]\r\n for i in range(10):\r\n results.append(tfcv(word,files,data_type,c,g,test_type))\r\n grouped_data = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\r\n for i in results:\r\n aux1 = i[0]\r\n aux2 = i[1]\r\n for j in range(1,16):\r\n grouped_data[j].append(aux1[j-1])\r\n grouped_data[0].append(aux2)\r\n means = []\r\n for i in grouped_data:\r\n means.append(np.mean(i))\r\n whole_table.append(means)\r\n for i in range(len(means)):\r\n aux[i].append(means[i])\r\n mean_column = []\r\n for i in aux:\r\n mean_column.append(np.mean(i))\r\n codes = ['General accuracy','S01','S02','S03','S04','S05','S06','S07','S08','S09','S10','S11','S12','S13','S14','S15']\r\n T = Table().with_columns('Codes',codes,'A',whole_table[0],'E',whole_table[1],'I',whole_table[2],'O',whole_table[3],'U',whole_table[4],'Arriba',whole_table[5],'Abajo',whole_table[6],'Adelante',whole_table[7],'Atrás',whole_table[8],'Derecha',whole_table[9],'Izquierda',whole_table[10],'MEAN',mean_column)\r\n df = T.to_df()\r\n df = df.round(3)\r\n return df\r\n\r\ndf1 = leaveOneOutCrossValidation(1,200,0.1,1)\r\ndf2 = tenFoldCrossValidation(1,200,0.1,1)\r\n\r\n","sub_path":"Tests.py","file_name":"Tests.py","file_ext":"py","file_size_in_byte":10124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"561650567","text":"#!/usr/bin/python\nimport pandas as pd\nimport time\n\n# Constants\n# Value of Interval Time in second\nTIME = 300\nTIME_MS = TIME * 1000\n# Scale factor for the packet rate. It will be equal to [ pkts / scale ] per second.\nSCALE = 400\n# CSV Entries\nSIZE = 576\n# Simulation Time in CSV hours\nSIM = 720\n# Simulation in number of intevals\nSIM_N = SIM * 12\ncomputername=\"jedi\"\n# CSV File\nCSV = '/home/'+computername+'/Scrivania/RyuDatapathMonitor-master/CSV/vlan_interfaccia1_DOS.csv'\n# ToS \nSERV_0 = \"0\"\nSERV_1 = \"32\"\nSERV_2 = \"72\"\nSERV_3 = \"96\"\nSERV_4 = \"136\"\nSERV_5 = \"160\"\nSERV_6 = \"192\"\nSERV_7 = \"224\"\n\n# IDT_OPT\n# constant\nc_idt = \"-C\"\n#poisson\np_idt = \"-O\"\n#esponential\ne_idt =\"-E\"\n\n# PS_OPT\n# constant\nc_ps = \"-c\"\n# poisson\np_ps = \"-o\"\n# esponential\ne_ps =\"-e\"\n\n# default value for protocol and packet size \nDEFAULT_P = \"UDP\"\nDEFAULT_PS = \"512\"\n\n# Host Ip\nsrc = \"10.0.0.11\"\ndst = \"10.0.0.13\"\n\n# Type of distribution\nchoice_i = c_idt\nchoice_s = c_ps\n\n\n# Cmd creation\ndef createCmd(src, dst, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\n com = 'ITGManager ' + src + ' -a ' + dst + ' -b ' + tos + ' ' + choice_i + ' ' + str(avg) + ' ' + choice_s + ' ' + ps_dim + ' -t ' + str(TIME_MS-8000)\n return com\n\n# Cmd creation\ndef createCmd_2(dst, port, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\t\t\n com = 'ITGSend -a ' + dst + ' -rp ' + str(port) + ' -b ' + tos + ' ' + choice_i + ' ' + str(avg) + ' ' + choice_s + ' ' + ps_dim + ' -t ' + str(TIME_MS-10000) + ' &'\t\t\t\t\n return com\n\n# Cmd creation Iperf\ndef createCmd_3(dst, port, tos, nPkts, avg, protocol=DEFAULT_P, ps_dim=DEFAULT_PS):\t\t\n com = 'iperf3 -c ' + dst + ' -p ' + str(port) + ' -S ' + tos + ' ' + ' -k ' + str(nPkts) + ' &'\t\t\n return com\n","sub_path":"ditg.py","file_name":"ditg.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"604454814","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport requests\nimport json\nimport re\nfrom selenium.common.exceptions import NoSuchElementException\nimport csv\n\nheader = {'User-Agent': ''}\nd = webdriver.Chrome('./chromedriver')\nd.implicitly_wait(3)\nd.get('http://www.melon.com/chart/index.htm')\nd.get(\"http://www.melon.com/chart/search/index.htm\")\nd.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/h4[1]/a').click()\n\n\nfor i in range(1, 5):\n # age 10년 단위\n age_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[1]/div[1]/ul/li[' + str(i) + ']/span/label'\n age = d.find_element_by_xpath(age_xpath)\n age.click()\n\n # year\n for i in range(1, 11):\n\n\n try:\n year_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[2]/div[1]/ul/li[' + str(i) + ']/span/label'\n year = d.find_element_by_xpath(year_xpath)\n year.click()\n print(year.text)\n\n except:\n print(\"year_xpath not found\")\n continue\n \n # month\n for i in range(1,13):\n try:\n month_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[3]/div[1]/ul/li[' + str(i) + ']/span/label'\n month = d.find_element_by_xpath(month_xpath)\n month.click()\n print(month.text)\n\n except:\n print(\"month_xpath not found\")\n continue\n \n # week\n for i in range(1,6):\n # weekly save\n result = list()\n try:\n week_xpath = '//*[@id=\"d_chart_search\"]/div/div/div[4]/div[1]/ul/li[' + str(i) + ']/span/label'\n week = d.find_element_by_xpath(week_xpath)\n week.click()\n print(week.text)\n\n except:\n print(\"week_xpath not found\")\n continue\n \n\n # genre selection\n try:\n classCd = d.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/div/div[5]/div[1]/ul/li[2]/span/label')\n except:\n classCd = d.find_element_by_xpath('//*[@id=\"d_chart_search\"]/div/div/div[5]/div[1]/ul/li/span/label')\n \n \n classCd.click()\n print(classCd.text)\n\n # search button\n d.find_element_by_xpath('//*[@id=\"d_srch_form\"]/div[2]/button/span/span').click()\n sleep(10)\n\n # check whether next_page exists\n next_exist = True\n page_list = ['''\"lst50\"'''] # initialize with the first page\n try:\n next_xpath = '//*[@id=\"frm\"]/div[2]/span/a'\n next_button = d.find_element_by_xpath(next_xpath)\n except: \n next_exist = False\n if next_exist:\n page_list.append('''\"lst100\"''') # next page\n\n for page in page_list:\n song_ids = d.find_elements_by_xpath('//*[@id={}]/td[4]/div/a'.format(page))\n song_ids = [re.sub('[^0-9]', '', song_id.get_attribute(\"href\")) for song_id in song_ids]\n ranks = d.find_elements_by_xpath('//*[@id={}]/td[2]/div/span[1]'.format(page))\n\n for rank, song_id in zip(ranks, song_ids):\n sleep(5)\n print(song_id)\n\n req = requests.get('http://www.melon.com/song/detail.htm?songId=' + song_id, headers = header)\n html = req.text\n soup = BeautifulSoup(html, \"html.parser\")\n\n title = soup.find(attrs={\"class\": \"song_name\"}).text.replace('곡명', '')\n\n if '19금' in title:\n title = title.replace('19금', '')\n\n title = re.sub('^\\s*|\\s+$','', title)\n \n # 가수\n singers = re.sub('<[^>]*>|\\s|\\[|\\]', '', str(soup.find('div', class_ = \"artist\")))\n\n album = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[0].text\n date = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[1].text\n genre = soup.select('#downloadfrm > div > div > div.entry > div.meta > dl > dd')[2].text \n \n # 작사가\n creator = re.sub('<[^>]*>|\\s|\\[|\\]', '', str(soup.find_all(\"div\", attrs={\"class\": \"entry\"})))\n creator = re.sub('^\\s*|\\s+$', '', creator)\n clist = creator.split(',')\n creator = []\n for x in clist:\n if '작사' in x:\n creator.append(x[:-2])\n creator = ','.join(creator) \n \n # 가사\n lyric = re.sub('<[^>]*>|\\s|\\[|\\]', ' ', str(soup.find_all(attrs={\"class\": \"lyric\"})[0]))\n lyric = re.sub('^\\s*|\\s+$', '', lyric)\n \n result.append({\n 'time': re.sub('[^0-9~]', '.', year.text + week.text),\n 'rank': rank.text,\n 'song_id': song_id,\n 'title': title,\n 'singers': singers,\n 'album': album,\n 'date' : date,\n 'genre': genre,\n 'creator' : creator,\n 'lyric' : lyric\n })\n print(\"차트 기간:\", year.text +\" \"+ week.text)\n print(\"순위:\", rank.text)\n print(\"곡 id:\", song_id)\n print(\"제목:\", title)\n print(\"가수:\", singers)\n print(\"앨범:\", album)\n print(\"발매날짜:\", date)\n print(\"장르:\", genre)\n print(\"작사:\", creator)\n print(\"가사:\", lyric)\n print(\"*_*_*_*_*_*_*_*_*_*_*__*_*_*\")\n\n try:\n next_button.click()\n except:\n print(\"No next page\")\n\n with open('./result_{}_{}.csv'.format(year.text, week.text), 'w') as csvfile:\n fieldnames = [\"time\", \"rank\", \"song_id\", \"title\", \"singers\", \"album\", \"date\", \"genre\", \"creator\", \"lyric\"]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n for i in range(len(result)):\n writer.writerow(result[i])","sub_path":"crawler/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":7006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"33595987","text":"# Resolve the problem!!\nimport re\n\nFILE_NAME = 'encoded.txt'\n\n\ndef run():\n with open(FILE_NAME, encoding = 'utf-8') as input_file:\n contents = input_file.read()\n message = ''.join(re.findall(r'[a-z]', contents))\n print(message)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"567988486","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 8 14:29:47 2018\n\n@author: gonsoomoon\n\"\"\"\n\nimport pandas as pd\nfrom pandas import Series\n\n\nimport time\ndef time_start():\n start_time = time.time()\n return start_time\n\ndef time_end(start_time):\n end_time = time.time()\n duration = end_time - start_time\n print(\"start time: \", start_time)\n print(\"end time: \", end_time) \n print(\"Total exectution time (Min): \" + str(duration/60))\n \ndef set_seed():\n from numpy.random import seed\n seed(1)\n from tensorflow import set_random_seed\n set_random_seed(2)\n \ndef save_csv_file(data, filename=\"../debug/df.csv\"):\n if(type(data) is Series):\n df = pd.DataFrame(data.values.reshape(-1,1))\n elif(type(data) is numpy.ndarray):\n df = pd.DataFrame(data)\n elif(type(data) is list):\n df = pd.DataFrame(data)\n elif(type(data) is pd.DataFrame):\n df = data\n else:\n print(\"data is not either Series or numpy .array\")\n return None\n df.to_csv(filename)\n \n ","sub_path":"time-series-prediction/util/fresh_general_util.py","file_name":"fresh_general_util.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"484183291","text":"from collections import deque, Counter\nimport itertools\n\nfrom util.distribution import Distribution\nfrom util.pipeline import PipelineProcess, get_all_from_queue\nfrom util.schedule import create_periodic_event\n\n\nclass AudioFeature(PipelineProcess):\n\n def __init__(self, feature_id, audio_sources, audio_video_pair_map, window_length=10):\n super().__init__(pipeline_id=feature_id,\n target_function=AudioFeature.establish_process_loop,\n params=(audio_video_pair_map, window_length),\n sources=audio_sources)\n\n @staticmethod\n def establish_process_loop(input_queue, output_queue, audio_video_pair_map, window_length):\n window = deque(maxlen=window_length) # A sliding window containing the most active stream for each frame\n video_ids = set(audio_video_pair_map.values())\n\n def weight_sources():\n # Inform Python we are using vars from the outer scope.\n nonlocal window, video_ids, audio_video_pair_map\n\n source_audio = {source_id: [] for source_id in audio_video_pair_map}\n for update_step in get_all_from_queue(input_queue):\n for source_id, audio_frame_list in update_step.items():\n source_audio[source_id] += list(itertools.chain.from_iterable(audio_frame_list))\n\n # Determine loudest source; append corresponding video ID to sliding window\n max_audio_id = max(source_audio, key=lambda id: max(source_audio[id], default=0))\n window.append(audio_video_pair_map[max_audio_id])\n\n # Vote proportionally based on count in window\n vote = Distribution(Counter(window))\n for key in video_ids - vote.keys(): # add missing keys\n vote[key] = 0.0\n vote.normalize() # scale down to [0, 1]\n\n # Output vote distribution\n output_queue.put_nowait(vote)\n\n scheduler = create_periodic_event(interval=1 / 30, action=weight_sources)\n scheduler.run()\n\n\n\n\n\n","sub_path":"features/audio_feature.py","file_name":"audio_feature.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"113806443","text":"\"\"\"\n\nThis is a program designed to help someone understand the concept of recursion.\n\nA recursive function is a function that calls itself until a base condition is met.\n\nSo what does this mean? Well it means that the function in question will continue to call itself until\nthe thing it was waiting for becomes true.\n\nThe factorial of a number is simply the product of all the positive integers less than or equal to that number.\n\nIt is denoted with n!. For example 5! = 5 * 4 * 3 * 2 * 1 = 120.\n\nYou can use a recursive function to find the factorial of a given number.\n\n\"\"\"\nnumber = 0\n\n\ndef factorial(number):\n if number == 0 or number == 1:\n return 1\n else:\n return number * factorial(number - 1)\n\n\nfactorial(5)\n\n\"\"\"\n\nSo what exactly did this do? First, we have the base condition:\n\nif number == 0 or number == 1:\n return 1\n \nThis is the way to exit the recursive function. The function will not end until this is true (or the computer runs out\nof memory). \n\nThen we have the recursive bit:\n\nelse:\n return number * factorial(number - 1)\n \nIf you look closely, you can see that the function calls itself again, with a slightly different parameter. Rather\nthan calling itself with the original parameter it was given, it gives the new copy of the function the original\nparameter minus 1. I'll show you why this is important later.\n\nFinally, the code runs the recursive function with the parameter 5. This means we want to find the factorial of 5.\n\nSo how does this work in context?\n\nGiving the parameter 5, we can see that it doesn't pass the base condition. 5 is neither 0 nor 1, and so it moves on.\nThe function then runs itself, but with the original parameter (5) minus 1 (i.e 4). The function is now awaiting the\nresult of factorial(4), so that it can multiply it by its original parameter (5) and return to the caller of the\nfunction.\n\nSo now that the function has run itself and awaiting response, we can see what happens to the second iteration.\nThe function is now running with the parameter 4, which doesn't meet the base condition. It does the same thing as the\nfirst function, and multiplies its parameter (4) by the return value of itself with the parameter 3 (4 - 1). This means\nthat this iteration of the function is now awaiting the return value of itself with the new parameters.\n\nSo now we're looking at the function thats been run for a third time, this time with the parameter 3. Once again, 3\ndoesn't meet the base condition (0 or 1), and so continues to the else statement. It then tries to return its parameter\n(3) multiplied by the result of itself with the parameter (2). Awaiting the response, we follow the new iteration.\n\nThe new iteration is running with the parameter 2. Once again, it doesn't meet the base condition, so it tries to \nreturn its original parameter (2) multiplied by the result of the same function with the parameter 1.\n\nNow it gets interesting. The new instance of the function has the parameter 1, which meets the base value. This returns\n1 back to the previous function (i.e the function with the parameter of 2. The previous function, now knowing the\nvalue of the called function, it can return (2 * 1) to the function that called it.\n\nThe function that called it (i.e the function with the original parameter of 3) now can return (3 * 2) (With 2 being\nthe result of the function it called) to the function that called it. Said function (the function with the original\nparameter of 4) can now return (4 * 6) (Keep in mind that 6 is the result of 2 * 3) to the function that called it.\n\nThat function (with the original parameter of 5) is the first function to be called. It can now return the result of\n(5 * 24) to the thing that called it. That would be factorial(5), the thing that started it all. And thats how\nyou can get the value of 5!. Thats also the concept of recursive functions.\n\nOf course, there's a lot more to cover, like how it compares to iterative programming, other parts of recursion, etc -\nbut you know what, I'm too lazy to do that now. So as it stands, this is what you get. You're welcome.\n\n\"\"\"","sub_path":"understanding_recursion.py","file_name":"understanding_recursion.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"329399671","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n# In[8]:\n\n\n# This class create a on-lattice KMC model which simulates the\n# non-reactive surface processes.\nclass KMC_lattice():\n\n def __init__(self, height, width, k_ads_expo, p, k_des):\n\n # Height and width are sizes of the lattice we create.\n self.height = height\n\n self.width = width\n\n # Pre-exponential of adsorption rate constant.\n self.k_ads_expo = k_ads_expo\n\n # Partial pressure of adsorbates.\n self.p = p\n\n # Rate constant of desorption.\n self.alpha_ads = self.k_ads_expo * self.p\n\n # The rate constant of desorption.\n self.alpha_des = k_des\n\n # Since rate of diffusion has no influence on the results, we assume it\n # is one.\n self.alpha_diff = 1\n\n # Since for different events, there are different rate constants.\n # We Create a list named \"alpha_type\" to store different types of\n # alpha.\n self.alpha_type = [self.alpha_ads, self.alpha_des, self.alpha_diff]\n\n self.t = 0\n\n # Initialize a vacant lattice based on the given height and width.\n # Create a list named 'lattice_state' which contains the state(vacant or occupied)\n # of all sites on the lattice.\n # If a value in the list 'lattice_state' equals zero, it means the corresponding site\n # is vacant. If it is one, it means the site is occupied.\n\n def lattice_initialization(self):\n twoD_matrix = np.zeros((self.height, self.width), dtype=np.int)\n lattice_state = []\n for x_pos in range(self.height):\n for y_pos in range(self.width):\n lattice_state.append(twoD_matrix[x_pos, y_pos])\n return twoD_matrix, lattice_state\n\n # This function gives a list named 'neighbours' which contains the four neighbouring site's\n # states of each site on the lattice.\n # The list 'neighbours' looks like [[0,1,0,1],[0,0,0,0], [1,0,1,0],...]\n\n def site_neighbours(self):\n\n neighbours = []\n self.N_sites = np.size(self.twoD_matrix)\n\n for n in range(self.N_sites):\n # upper-left corner site\n if n == 0:\n up = (self.height - 1) * self.width\n right = n + 1\n down = n + self.width\n left = self.width - 1\n\n # uppermost boundary sites except lupper-eft and upper-right corner\n # sites\n elif 0 < n < self.width - 1:\n up = n + (self.height - 1) * self.width\n right = n + 1\n down = n + self.width\n left = n - 1\n\n # upper-right corner site\n elif n == self.width - 1:\n up = self.height * self.width - 1\n right = 0\n down = n + self.width\n left = n - 1\n\n # bottom-left corner site\n elif n == (self.height - 1) * self.width:\n up = n - self.width\n right = n + 1\n down = 0\n left = self.height * self.width - 1\n\n # bottom-right corner site\n elif n == self.height * self.width - 1:\n up = n - self.width\n right = (self.height - 1) * self.width\n down = self.width - 1\n left = n - 1\n\n # bottom sites except bottom-left and bottom-right corner sites\n elif (self.height - 1) * self.width < n < self.height * self.width - 1:\n up = n - self.width\n right = n + 1\n down = n - (self.height - 1) * self.width\n left = n - 1\n\n # left boundary sites except upper-left and bottom-left corner\n # sites\n elif n % self.width == 0 & n != 0 & n != (self.height - 1) * self.width:\n up = n - self.width\n right = n + 1\n down = n + self.width\n left = n + self.width - 1\n\n # right boundary sites except upper-right and bottom-right corner\n # sites\n elif (n + 1) % self.width == 0 & n != self.width - 1 & n != self.height * self.width - 1:\n up = n - self.width\n right = n - (self.width - 1)\n down = n + self.width\n left = n - 1\n\n # inner sites\n else:\n up = n - self.width\n right = n + 1\n down = n + self.width\n left = n - 1\n\n neighbours.append([up, right, down, left])\n\n return neighbours, self.N_sites\n\n def events_list(self):\n\n events = []\n\n alpha_list = []\n\n for i_site in range(self.N_sites):\n\n # This site is vacant. The only possible elementary event for it is\n # adsorption.\n if self.lattice_state[i_site] == 0:\n\n # 7 denotes adsorption\n i_site_event = [7]\n\n alpha_list.append(self.alpha_type[0])\n\n # This site is occupied and the events of this site depends on\n # status of its 4 neighbouring sites.\n else:\n\n # This site is occupied and its four neighbouring sites are vacant.\n # There are 5 possible events for this site. Go up/right/down/left or desorption.\n # 0 denotes the vacant site.\n # 1 denotes the occupied site.\n # 6 desorption\n # 7 adsorption\n # 8 go up\n # 9 go right\n # 10 go down\n # 11 left\n if self.neighbours[i_site] == [0, 0, 0, 0]:\n i_site_event = [8, 9, 10, 11, 6]\n # with no occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n else:\n if np.sum(self.neighbours[i_site]) == 1:\n\n if self.neighbours[i_site] == [1, 0, 0, 0]:\n i_site_event = [9, 10, 11, 6]\n\n elif self.neighbours[i_site] == [0, 1, 0, 0]:\n i_site_event = [8, 10, 11, 6]\n\n elif self.neighbours[i_site] == [0, 0, 1, 0]:\n i_site_event = [8, 9, 11, 6]\n\n else:\n # status_i_neighbours == [0,0,0,1]:\n i_site_event = [8, 9, 10, 6]\n\n # with one occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n elif np.sum(self.neighbours[i_site]) == 2:\n\n if self.neighbours[i_site] == [1, 1, 0, 0]:\n i_site_event = [10, 11, 6]\n\n elif self.neighbours[i_site] == [1, 0, 1, 0]:\n i_site_event = [9, 11, 6]\n\n elif self.neighbours[i_site] == [1, 0, 0, 1]:\n i_site_event = [9, 10, 6]\n\n elif self.neighbours[i_site] == [0, 1, 1, 0]:\n i_site_event = [8, 11, 6]\n\n elif self.neighbours[i_site] == [0, 1, 0, 1]:\n i_site_event = [8, 10, 6]\n\n else:\n # status_i_neighbours == [0,0,1,1]:\n i_site_event = [8, 9, 6]\n\n # with two occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n elif np.sum(self.neighbours[i_site]) == 3:\n\n if self.neighbours[i_site] == [1, 1, 1, 0]:\n i_site_event = [11, 6]\n\n elif self.neighbours[i_site] == [1, 1, 0, 1]:\n i_site_event = [10, 6]\n\n elif self.neighbours[i_site] == [1, 0, 1, 1]:\n i_site_event = [9, 6]\n\n else:\n # status_i_neighbours == [0,1,1,1]:\n i_site_event = [8, 6]\n\n # with three occupied neighbouring site\n alpha_list.append(self.alpha_type[2])\n alpha_list.append(self.alpha_type[1])\n\n # This site is occupied and all of its neighbouring sites are occupied.\n # The only possible elementary event is desorption.\n else:\n i_site_event = [6]\n alpha_list.append(self.alpha_type[1])\n\n events.append(i_site_event)\n\n return events, alpha_list\n\n # This function gives sum of rate constants of all events.\n def sum_of_alpha(self):\n\n sum_alpha = np.sum(self.alpha_list)\n\n return sum_alpha\n\n # This function gives a random waiting time for the selected event.\n def waiting_time_generation(self):\n\n r1 = np.random.rand()\n\n waiting_time = - 1.0 / self.sum_alpha * np.log(1.0 - r1)\n\n return waiting_time\n\n # Direct method.\n\n def site_event_selection(self):\n\n r2 = np.random.rand()\n\n left_side = 0\n\n medium = 0\n\n right_side = self.alpha_list[medium]\n\n exit_flag = False\n\n for i_site in range(self.N_sites):\n\n for i_event in range(len(self.events[i_site])):\n\n if left_side < r2 * self.sum_alpha < right_side:\n\n site_to_change = i_site\n\n which_event_to_execute = i_event\n\n exit_flag = True\n\n break\n\n else:\n\n left_side = right_side\n\n medium += 1\n\n right_side += self.alpha_list[medium]\n\n if exit_flag:\n\n break\n\n return site_to_change, which_event_to_execute\n\n # Once an event is executed, this function updates the list\n # 'lattice_state'.\n def event_executing(self):\n\n event_chosen = self.events[self.site_to_change][self.which_event_to_execute]\n\n # desorption\n if event_chosen == 6:\n self.lattice_state[self.site_to_change] = 0\n\n # adsorption\n elif event_chosen == 7:\n self.lattice_state[self.site_to_change] = 1\n\n # go up\n elif event_chosen == 8:\n self.lattice_state[site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][0]\n self.lattice_state[site_influenced] = 1\n\n # go right\n elif event_chosen == 9:\n self.lattice_state[self.site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][1]\n self.lattice_state[site_influenced] = 1\n\n # go down\n elif event_chosen == 10:\n self.lattice_state[site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][2]\n self.lattice_state[site_influenced] = 1\n\n # go left (event_chosen == 11)\n else:\n self.lattice_state[self.site_to_change] = 0\n site_influenced = self.neighbours[self.site_to_change][3]\n self.lattice_state[site_influenced] = 1\n\n return self.lattice_state\n\n # This function calculates the coverage of the lattice.\n def coverage(self):\n\n num_occupied = np.sum(self.lattice_state)\n\n cov = num_occupied / len(self.lattice_state)\n\n return cov\n\n def events_progressing(self):\n\n self.twoD_matrix, self.lattice_state = self.lattice_initialization()\n\n self.neighbours, self.N_sites = self.site_neighbours()\n\n cov_all = []\n\n time_all = []\n\n for i in range(10000):\n\n self.cov = self.coverage()\n\n cov_all.append(self.cov)\n\n self.events, self.alpha_list = self.events_list()\n\n self.sum_alpha = self.sum_of_alpha()\n\n self.waiting_time = self.waiting_time_generation()\n\n self.site_to_change, self.which_event_to_execute = self.site_event_selection()\n\n self.lattice_state = self.event_executing()\n\n time_all.append(self.t)\n\n self.t += self.waiting_time\n\n average_coverage = np.sum(cov_all) / len(cov_all)\n\n print('The average covergae from KMC simulation is {0}.'.format(average_coverage))\n\n return cov_all, time_all\n\n def plot(self):\n cov_all, time_all = self.events_progressing()\n plt.figure()\n plt.plot(time_all, cov_all, color='black')\n plt.xlabel('time')\n plt.ylabel('coverage')\n plt.title('Simulation results of KMC')\n plt.savefig('average coverage from KMC simulation')\n plt.show()\n\n\n# In[ ]:\n\n\n# In[ ]:\n","sub_path":"OnLatticeKMC.py","file_name":"OnLatticeKMC.py","file_ext":"py","file_size_in_byte":13308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"241889150","text":"# -*- coding: utf-8 -*- \n# @Time : 2021/4/7 9:25 \n# @Author : 张丽雯 \n# @File : test_weightwo.py \n# @中文描述 : 称量工单-用例\nimport sys\nimport pytest\nfrom DataApp.WeightWoData import *\nfrom src.pageobjectAPP.pageWeightwo import *\nfrom src.public.common.Close_current_tab import Close_current_tab\nfrom src.public.common.Search_Item import *\n\n\nclass Test_Weightwo:\n def setup_class(self):\n app_login(username, password)\n login_weightwo()\n\n def teardown_class(self):\n Close_current_tab()\n app_logout()\n\n # 称量工单-筛选工单\n def test_weightwo_search(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item('编码', WO1)\n sleep(1)\n assert is_text_present(WO1)\n\n # 称量工单-净重模式-结束称量\n @pytest.mark.parametrize('n,tare,selectmode', over_net)\n def test_weightwo_net_001(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-净重模式-取消称量\n @pytest.mark.parametrize('n,tare,selectmode', cancel_net)\n def test_weightwo_net_002(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_js_text(input_container) == ''\n\n # 称量工单-净重模式-相同容器\n @pytest.mark.parametrize('n,tare,selectmode', same_net)\n def test_weightwo_net_003(self, n, tare, selectmode):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_net(n, tare, selectmode)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-人工输入模式\n @pytest.mark.parametrize('n, netvalue, tarevalue', manual_list)\n def test_weightwo_manual(self, n, netvalue, tarevalue):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_manual(n, netvalue, tarevalue)\n assert new_page_source('保存成功')\n\n # 称量工单-计数称量模式\n @pytest.mark.parametrize('n,tare',count_list)\n def test_weightwo_count(self,n,tare):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item('编码', WO2)\n sleep(1)\n weight_wo_count(n,tare)\n sleep(1)\n assert new_page_source('保存成功')\n\n # 称量工单-批次信息\n def test_weightwo_lot_detail(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_lot_detail('0')\n sleep(1)\n assert new_js_text(input_container) != ''\n\n # 称量工单-取消称量\n @pytest.mark.parametrize('n,cancel1,cancel2', [('0', '取消称量', '否'), ('0', '否', '取消称量')])\n def test_weightwo_cancel_weight(self, n, cancel1, cancel2):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_cancel(n, cancel1, cancel2)\n sleep(2)\n assert new_js_text(input_container) == ''\n\n\t # 毛重称量\n def test_gross_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n grossweighmode(\"0.2\")\n time.sleep(2)\n\n # RM混合\n def test_rmmix_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n rmweighmode(\"0.2\")\n time.sleep(2)\n\n # 称量次数\n def test_weigh_times(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n sleep(7)\n times1 = new_js_text(weightimes)\n grossweighmode(\"0.2\")\n time.sleep(2)\n times2 = new_js_text(weightimes)\n assert int(times1)+1 == int(times2)\n\n # 总重量\n def test_total_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n sleep(7)\n weigh1 = new_js_text(totalweigh)\n grossweighmode(\"0.2\")\n time.sleep(2)\n weigh2 = new_js_text(totalweigh)\n assert float(weigh1)+3.087 == float(weigh2)\n\n # 强制称量\n def test_force_weigh(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n forceweigh()\n assert new_page_source('称量完成')\n\n # 物料信息\n def test_material_info(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n material_info()\n sleep(1)\n assert new_get_text(stage) == '0001'\n assert new_get_text(seq) == '0001'\n assert new_get_text(dose) == '1'\n new_click(closed)\n\n # 托盘标签\n def test_pallet_label(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n pallet_label()\n assert new_get_text(alert_txt) == '打印信息发送成功'\n\n\n # 输入容器识别号-容器号不存在\n @pytest.mark.parametrize('CID', ['1232323'])\n def test_weightwo_containerid_adnormal_001(self, CID):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_container_ID(CID)\n sleep(1)\n assert is_text_present('不存在该批次信息的容器')\n\n # 输入容器识别号-容器已过期\n @pytest.mark.parametrize('CID', ['RL00000033 0001'])\n def test_weightwo_containerid_adnormal_002(self, CID):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n weight_wo_container_ID(CID)\n sleep(1)\n assert is_text_present('容器已过期')\n\n # 净重称量模式-剩余量正确性比对\n def test_weightwo_net_remain(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n new_click(material(n3))\n sleep(1)\n remain1 = float(new_js_text(remain_number))\n weight_wo_net(n3, tarevalue1, selectmode1)\n sleep(1)\n remain2 = float(new_js_text(remain_number))\n net = round(remain1 - remain2, 3)\n weight_wo_net(n3, tarevalue1, selectmode1)\n sleep(1)\n remain3 = round(float(new_js_text(remain_number)), 3)\n assert remain3 == round(remain2 - net, 3)\n\n # 人工输入模式-剩余量正确性比对\n def test_weightwo_manual_remain(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n new_click(material(n3))\n sleep(1)\n remain1 = float(new_js_text(remain_number))\n weight_wo_manual(n3, '10', '0.002')\n sleep(1)\n remain2 = float(new_js_text(remain_number))\n assert remain2 == remain1 - 10\n\n # 净重称量模式-净重正确性比对\n def test_weightwo_net_netvalue(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n weight_wo_net_netvalue(n3, tarevalue1)\n sleep(1)\n netvalue = new_js_text(net_number)\n # 3.090是秤的度数,这值根据实际情况而定\n assert netvalue == '3.090'\n new_click(CanWeigh)\n\n # 净重称量模式-皮重正确性比对\n def test_weightwo_net_tarevalue(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n # 选择称量工单物料\n weight_wo_net_netvalue(n3, '0.033')\n sleep(1)\n tare_value = new_js_text(tare_number)\n assert tare_value == '0.033'\n","sub_path":"TestcaseApp/Weigh/test_weightwo.py","file_name":"test_weightwo.py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"439807143","text":"def height(root):\n if not root:\n return 0\n return 1 + max(height(root.left), height(root.right))\n\ndef recursive_append(node,cur_height,lo,hi,output):\n if node is None:\n return\n mid = (lo + hi)//2\n output[cur_height][mid] = str(node.val)\n recursive_append(node.left,cur_height+1,lo,mid-1,output)\n recursive_append(node.right,cur_height+1,mid+1,hi,output)\n\n\ndef binaryTreeToStr(root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[str]]\n \"\"\"\n tree_height = height(root)\n length = 2**tree_height-1\n output = [[\" \" for x in range(length)] for x in range(tree_height)]\n recursive_append(root,0,0,length-1,output)\n str_out = \"\"\n for row in output:\n for c in row:\n str_out += c\n str_out += \"\\n\"\n return str_out","sub_path":"Recursion/prettyPrint.py","file_name":"prettyPrint.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"47897672","text":"from itertools import combinations, chain\nfrom collections import Counter\n\n\ndef generation_list(total_person):\n \"\"\"Создает список человек\"\"\"\n return [x + 1 for x in range(total_person)]\n\n\ndef count_elements(general_list, list_of_elements):\n \"\"\"Считает количество переданных элементов в списке\"\"\"\n count = Counter(general_list)\n res = {i: count[i] for i in list_of_elements}\n return res\n\n\ndef get_a_combination(roll, count=2, iterable=False):\n \"\"\"Составляет все пары для списка\n (также можно использовать для генерации любых других\n сочетаний указывая второй параметр, а ещё получать итерируемый объект)\"\"\"\n if iterable:\n return combinations(roll, count)\n else:\n return list(combinations(roll, count))\n\n\ndef find_pairs(schedule):\n \"\"\"Функция составляет пары для каждой смены в переданном расписании\"\"\"\n return [get_a_combination(shift) for shift in schedule]\n\n\ndef concatenate_lists(lists):\n \"\"\"Функция сцепляет несколько списков в один\"\"\"\n return list(chain(*lists))\n\n\ndef did_everyone_meet(schedule, all_pairs):\n \"\"\"Проверяет все ли встетились в переданном расписании\"\"\"\n return 0 not in count_elements(concatenate_lists(find_pairs(schedule)), all_pairs).values()\n\n\ndef calc(number_of_people, people_in_shift):\n \"\"\"Считает расписания с указанными данными\"\"\"\n # Определение задачи\n list_people = generation_list(number_of_people)\n all_pairs = get_a_combination(list_people)\n all_shifts = get_a_combination(list_people, people_in_shift)\n list_schedule = []\n\n number_of_shifts = 0\n find_min_count_shift = True\n while find_min_count_shift:\n # Итерируемый объект - все варианты расписаний для переданного кол-ва смен\n timetables = get_a_combination(all_shifts, number_of_shifts, True)\n for schedule in timetables:\n if did_everyone_meet(schedule, all_pairs):\n find_min_count_shift = False\n list_schedule.append(schedule)\n number_of_shifts += 1\n return list_schedule\n\n\nif __name__ == '__main__':\n i, j = map(int, input('Кол-во игроков и кол-во людей в смене (через пробел): ').split())\n timetables = calc(i, j)\n [print(i) for i in timetables]\n input()\n","sub_path":"v1/1.1/make_a_schedule.py","file_name":"make_a_schedule.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"635652581","text":"import tornado.options\nimport tornado.httpserver\nimport tornado.ioloop\n\nimport logging\nimport os\n\nimport app.main\nimport app.courses\nimport app.affairs\nimport app.dining\nimport app.athletics\nimport app.housing\nimport app.uem\nimport app.auth\nimport app.documentation\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n logging.getLogger().setLevel(logging.DEBUG)\n\n app_settings = {\n 'debug': \"dev\",\n \"xsrf_cookies\" : False,\n \"cookie_secret\" : \"32oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=\",\n \"template_path\" : os.path.join(os.path.dirname(__file__), \"templates\"),\n \"static_path\" : os.path.join(os.path.dirname(__file__), \"static\"),\n \"autoescape\" : None,\n \"login_url\" : \"http://data.adicu.com/login\",\n }\n\n handlers = [\n (r\"/$\", app.main.MainHandler),\n (r\"/ping$\", PingHandler),\n (r\"/courses$\", app.courses.CoursesHandler),\n (r\"/dining$\", app.dining.DiningHandler),\n (r\"/uem$\", app.uem.UemHandler),\n (r\"/affairs$\", app.affairs.AffairsHandler),\n (r\"/affairs/([^/]+)\", app.affairs.AffairsHandler),\n (r\"/athletics$\", app.athletics.athleticsHandler),\n (r\"/housing/rooms$\", app.housing.RoomHandler),\n (r\"/housing/buildings$\", app.housing.BuildingHandler),\n (r\"/docs$\", app.main.MainHandler),\n (r\"/docs/([^/]+)\", app.documentation.DocsHandler),\n (r\"/login$\", app.auth.LoginHandler),\n (r\"/logout$\", app.auth.LogoutHandler),\n (r\"/profile$\", app.main.ProfileHandler),\n\n ]\n debug = True\n tornado.web.Application.__init__(self, handlers, **app_settings)\n\nclass PingHandler(tornado.web.RequestHandler):\n def get(self):\n self.finish('OK')\n def head(self):\n self.finish('OK')\n\n\nif __name__ == \"__main__\":\n # this port should be unique system wide; all ports used should be listed in ~/services.py\n tornado.options.define(\"port\", default=int(os.environ[\"PORT\"]), help=\"Listen on port\", type=int)\n tornado.options.parse_command_line()\n logging.info(\"starting app on 0.0.0.0:%d\" % tornado.options.options.port)\n http_server = tornado.httpserver.HTTPServer(request_callback=Application())\n http_server.listen(tornado.options.options.port, address=\"0.0.0.0\")\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"data/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"250917053","text":"import os\nimport sys\nimport click\nfrom stringprocessor import StringProcessor as sp\nimport loggers\n\nimport app\nfrom yammler import DownloadLog\nfrom settings import (\n FSEC_DOWNLOAD_DIR,\n EXCLUDE_TOKENS,\n FSEC_FTP_URL,\n FSEC_OUTPUT_DIR,\n FSEC_TO_CSV,\n FSEC_TO_DATABASE,\n DATABASE_URI,\n FRAC_SCHEDULE_TABLENAME,\n DOWNLOADLOGPATH,\n)\nfrom util import tokenize\n\n\nCONTEXT_SETTINGS = dict(help_option_names=[\"-h\", \"--help\"])\n\nOP_COLOR = \"red\"\n\n\ndef set_verbosity(level: int):\n if level is not None:\n loggers.standard_config(verbosity=level)\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n pass\n\n\n@click.command()\n@click.option(\n \"--download_to\",\n \"-d\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=f\"Directory to save downloads from the FTP ({FSEC_FTP_URL}). If no location is specified here, the file will be downloaded to the value of the FSEC_DOWNLOAD_DIR environment variable. If that also doesn't exists, the schedule will be downloaded to the ./data directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--output_to\",\n \"-out\",\n default=os.path.abspath(FSEC_OUTPUT_DIR or \"\") or os.path.abspath(\"./output\"),\n show_default=True,\n help=f\"Directory to save the parsed output schedule. If no location is specified here, the output will be saved to the location specified in the FSEC_OUTPUT_DIR environment variable. If that also doesn't exists, the schedule will be saved to the ./output directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_OUTPUT_DIR\",\n)\n@click.option(\n \"--no-download\",\n is_flag=True,\n show_default=True,\n help=f\"Skips downloading any new files before initiating the parsing process. If enabled, only existing files will be parsed.\",\n)\n@click.option(\"--no-parse\", is_flag=True, help=f\"Skips parsing the frac schedules.\")\n@click.option(\n \"--no-cleanup\",\n is_flag=True,\n show_default=True,\n help=f\"Disables the removal of previously downloaded frac schedules.\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\n@click.pass_context\ndef run(ctx, download_to, no_download, no_parse, no_cleanup, verbose):\n \"\"\"Run the app\"\"\"\n set_verbosity(verbose)\n\n app.run(to, no_cleanup=no_cleanup, no_download=no_download, no_parse=no_parse)\n\n\n@click.command()\n@click.option(\n \"--path\",\n \"-p\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=\"Specify an alternate filepath to the directory containing the frac schedules.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=(\"FSEC_DOWNLOAD_DIR\"),\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\ndef show(path, verbose):\n \"List the currently downloaded frac schedules\"\n click.secho(\n \"\\n\" + f\"Current download directory: {os.path.abspath(path)}\",\n bold=True,\n fg=\"cyan\",\n )\n paths = app.list_downloads(os.path.abspath(path))\n op_paths = app.operator_filenames(paths)\n click.secho(\n \"\\n\"\n + f\"{'operator alias':<25} {'original name':<25} {'conf':<10} {'filename':<75}\",\n bold=True,\n )\n click.secho(\"-\" * 125 + \"\\n\", bold=True)\n for idx, x in enumerate(op_paths):\n path, op = x\n p = os.path.basename(path)\n\n click.secho(\n f\"{op.alias:<25} {op.orig:<25} {op.pscore:<10} {p:<75}\",\n dim=True if idx % 2 else False,\n )\n\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True)\n\n\n@click.command()\n@click.option(\n \"--to\",\n \"-t\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=f\"Directory to save downloads from the FTP ({FSEC_FTP_URL}). If no location is specified here, the file will be downloaded to the value of the FSEC_DOWNLOAD_DIR environment variable. If that also doesn't exists, the schedule will be downloaded to the ./data directory in the project root.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\ndef download(to, verbose):\n \"Download all frac schedules\"\n\n set_verbosity(verbose)\n click.echo(\n click.style(\n \"\\n\" + f\"Downloading frac schedules to: {os.path.abspath(to)}\",\n fg=\"cyan\",\n bold=True,\n )\n )\n\n with DownloadLog.context(DOWNLOADLOGPATH) as dlog:\n for path, filename, status in app.download(to):\n click.secho(\n f\"{filename:<60} {status:<25}\",\n fg=\"green\" if status == \"success\" else \"red\",\n )\n dlog.add(os.path.abspath(os.path.join(path, filename)))\n\n\n@click.command()\n@click.option(\n \"--operator\",\n \"-o\",\n help=\"Attempt to locate and parse an operator's latest frac schedule\",\n)\n@click.option(\n \"--filename\",\n \"-f\",\n help=\"Parse a specific frac schedule\",\n type=click.Path(exists=True, dir_okay=False, file_okay=True),\n)\n@click.option(\n \"--directory\",\n \"-d\",\n default=os.path.abspath(FSEC_DOWNLOAD_DIR or \"\") or os.path.abspath(\"./data\"),\n show_default=True,\n help=\"Parse all frac schedules in a directory. The directory should ONLY include original frac schedules.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_DOWNLOAD_DIR\",\n)\n@click.option(\n \"--to\",\n \"-t\",\n default=os.path.abspath(FSEC_OUTPUT_DIR or \"\") or os.path.abspath(\"./output\"),\n show_default=True,\n help=f\"Directory to save the parsed output schedule. If no location is specified here, the output will be saved to the location specified in the FSEC_OUTPUT_DIR environment variable.\",\n type=click.Path(exists=True, dir_okay=True, file_okay=False),\n envvar=\"FSEC_OUTPUT_DIR\",\n)\n@click.option(\n \"--merge\",\n \"-m\",\n is_flag=True,\n default=True,\n help=f\"Option to merge the parsed output into a single file.\",\n show_default=True,\n envvar=\"FSEC_AUTO_MERGE\",\n)\n@click.option(\n \"--csv\",\n \"-c\",\n is_flag=True,\n default=True,\n help=f\"Option to save parsed output as a csv file\",\n show_default=True,\n envvar=\"FSEC_TO_CSV\",\n)\n@click.option(\n \"--db\",\n is_flag=True,\n default=FSEC_TO_DATABASE or False,\n help=f\"Option to save the parsed output to the configured database. The currently configured database is: {DATABASE_URI.split('@')[-1]}. The frac schedule table is set to {FSEC_FRAC_SCHEDULE_TABLE}\",\n show_default=True,\n envvar=\"FSEC_TO_DATABASE\",\n)\n@click.option(\n \"--verbose\",\n \"-v\",\n help=\"Set the verbosity level. A higher verbosity level will generate more output during the process' execution. Repeat the flag to increase the verbosity level. (ex. -vvv)\",\n show_default=True,\n count=True,\n)\n@click.pass_context\ndef parse(ctx, to, operator, filename, directory, merge, csv, db, verbose):\n \"Parse a frac schedule\"\n\n set_verbosity(verbose)\n from operator_index import Operator\n import pandas as pd\n\n click.echo(\"\") # spacer\n path = None\n to_parse = []\n try:\n basepath = os.path.abspath(directory or FSEC_DOWNLOAD_DIR)\n paths: list = app.list_downloads(basepath)\n paths_with_ops: list = app.operator_filenames(paths, with_index=False)\n except Exception:\n raise Exception(\"Unable to load paths\")\n\n if operator is not None:\n op = Operator(operator)\n # search in paths for resemblence to passed operator name\n to_parse = [f for f in paths_with_ops if f[1].alias == op.alias]\n\n elif filename is not None:\n # search in paths based on matching the given filename\n filename = os.path.basename(filename)\n to_parse = [f for f in paths_with_ops if os.path.basename(f[0]) == filename]\n\n elif directory is not None:\n # parse 'em all\n to_parse = paths_with_ops\n\n if len(to_parse) > 0:\n n = len(to_parse)\n click.secho(f\"Found {n} schedule{'s' if n > 1 else ''} to parse\", fg=\"green\")\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True, dim=True)\n\n else:\n msg = f\"Could not find any frac schedules matching the given criteria :(\"\n click.secho(\"\\n\" + msg, bold=True, fg=\"red\")\n ctx.invoke(show, path=basepath)\n\n # print(\"\\n\".join([x[0] for x in to_parse]))\n # return 0\n # click.secho(\"\\n\" + f\"parsing {n} schedules...\")\n parsers = []\n to_save = []\n\n click.secho() # spacer\n for p, op in to_parse:\n path = os.path.dirname(p)\n basename = os.path.basename(p)\n\n pl = click.style(\"(\", dim=True)\n pr = click.style(\")\", dim=True)\n fs = click.style(\"/\", dim=True)\n # s = click.style(f\"{spath} {p1}{sop_a}{fs}{sop_n}{p2}\", dim=True)\n\n try:\n parser = app.parse(filepath=p)\n\n color = \"red\"\n msgs = []\n dim = True\n\n if parser.status == \"ok\":\n color = \"green\"\n bold = False\n elif parser.status == \"warning\":\n color = \"yellow\"\n msgs = parser.status_messages[\"warning\"]\n dim = False\n bold = True\n elif parser.status == \"error\":\n color = \"red\"\n msgs = parser.status_messages[\"error\"]\n dim = False\n bold = True\n else:\n pass\n\n s_basename = click.style(\n basename,\n dim=True if parser.status == \"ok\" else False,\n bold=False if parser.status == \"ok\" else True,\n fg=\"white\" if parser.status == \"ok\" else color,\n )\n s_status = click.style(\n f\"{op.name:<20} {parser.status:<10}\", fg=color, bold=bold\n )\n s_n_records = click.style(f\"{len(parser.df)} records\", dim=True)\n\n click.echo(f\"{s_status} {s_basename} {pl}{s_n_records}{pr}\")\n # print([\"messages\"] + msgs)\n if len(msgs) > 0:\n\n for m in msgs:\n click.secho(\"\\t\" + m, bold=True, fg=color)\n # for m in msgs:\n # for cats in m:\n # for c in cats:\n # click.secho(c, fg=color, bold=False)\n\n parsers.append(parser)\n\n if not merge:\n to_save.append((op.alias, p.df, None))\n\n except:\n s_basename = f\"{click.style(basename, dim=False, bold=True, fg=color)}\"\n s_status = click.style(\n f\"{op.name:<20} {parser.status:<10}\", fg=color, bold=True\n )\n s_n_records = click.style(f\"{len(parser.df)} records\", dim=True)\n\n click.secho(f\"{s_status} {s_basename} {pl}{s_n_records}{pr}\")\n\n click.secho(\"\\n\" + \"-\" * 125 + \"\\n\", bold=True, dim=True)\n\n if merge:\n df = pd.concat([p.df for p in parsers], sort=False)\n to_save.append((\"Combined frac schedule saved to:\", df, \"frac-schedules\"))\n\n nframes = len(to_save)\n\n if db:\n # click.secho(f\"Saving {nframes} schedule{'s' if nframes > 1 else ''}\")\n\n for msg, frame, _ in to_save:\n try:\n n = frame.shape[0]\n loc = app.to_db(frame)\n click.secho(f\"{msg} -> {loc} ({n} records)\", bold=True)\n except Exception as e:\n click.secho(\n f\"{msg} -> Failed writing to database: {e}\", fg=\"red\", bold=True\n )\n csv = True\n click.secho(f\"{msg} -> Trying csv instead...\", fg=\"yellow\")\n\n if csv:\n # click.secho(f\"Saving {nframes} csv file{'s' if nframes > 1 else ''}\")\n\n for msg, frame, prefix in to_save:\n s_n = click.style(f\"({frame.shape[0]} records)\", dim=True)\n s_loc = click.style(\n os.path.basename(app.to_csv(frame, to, prefix)), bold=True, fg=\"cyan\"\n )\n try:\n if n > 0:\n click.secho(f\"{msg} -> {s_loc} {s_n}\" + \"\\n\\n\")\n except Exception as e:\n click.secho(f\"{msg} -> Failed writing to csv: {e}\" + \"\\n\\n\", fg=\"red\")\n\n\n@click.command()\n@click.option(\"--simulate\", \"-s\", is_flag=True, default=False, show_default=True)\n@click.option(\"--force\", \"-f\", is_flag=True, default=False, show_default=True)\ndef cleanup(simulate, force):\n to_be_cleaned = os.path.abspath(FSEC_DOWNLOAD_DIR)\n ct = 0\n click.echo() # spacer\n for fname, status, status_message in app.remove_previous_downloads(\n to_be_cleaned, simulate\n ):\n\n if status == \"success\":\n color = \"green\"\n elif status == \"warning\":\n color = \"yellow\"\n elif status == \"failed\":\n color = \"red\"\n else:\n color = \"white\"\n\n click.secho(f\"{fname:<60} {status_message}\", fg=color, bold=False)\n ct += 1\n click.secho(\n \"\\n\" + f\"Deleted {ct} frac schedules from {to_be_cleaned}\" + \"\\n\",\n fg=\"cyan\",\n bold=True,\n )\n\n remaining = os.listdir(to_be_cleaned)\n n = len(remaining)\n\n if n > 0:\n click.secho(\n f\"{n} lingering file{'s' if n > 0 else ''} in {to_be_cleaned}\" + \"\\n\",\n dim=False if n > 0 else True,\n fg=\"yellow\" if n > 0 else \"white\",\n bold=True if n > 0 else False,\n )\n\n for f in remaining:\n click.secho(\"\\t\" + f\"{f}\", bold=False, dim=True)\n\n click.secho(\n \"\\n\\trun 'fsec cleanup --force' to cleanup the remaining files\\n\\n\"\n if n > 0\n else \"\",\n dim=False,\n fg=\"yellow\",\n bold=True,\n )\n\n\n# Error\n# cli.add_command(initdb)\n# cli.add_command(dropdb)\ncli.add_command(run)\ncli.add_command(download)\ncli.add_command(parse)\ncli.add_command(show)\ncli.add_command(cleanup)\n\n\ndef main(argv=sys.argv):\n \"\"\"\n Args:\n argv (list): List of arguments\n Returns:\n int: A return code\n Does stuff.\n \"\"\"\n # print(argv)\n cli()\n return 0\n","sub_path":"src/fsec/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":14800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"66582580","text":"\n\n#calss header\nclass _ORWELLIAN():\n\tdef __init__(self,): \n\t\tself.name = \"ORWELLIAN\"\n\t\tself.definitions = [u'used to describe a political system in which the government tries to control every part of people\\'s lives, similar to that described in the novel \"Nineteen Eighty Four\", by George Orwell: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_orwellian.py","file_name":"_orwellian.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"632855737","text":"import itertools\nimport textwrap\nfrom pairs import Direction, add_dir, add_pair\nfrom enum import Enum\n\n\nclass LightGrid(object):\n _neighbor_pairs = [\n (0, -1),\n (-1, 0), (1, 0),\n (0, 1)\n ]\n # _neighbor_pairs = [\n # (-1, -1), (0, -1), (1, -1),\n # (-1, 0), (1, 0),\n # (-1, 1), (0, 1), (1, 1)\n # ]\n\n def __init__(self, width, height):\n self.grid = list([[0 for _ in range(width)] for _ in range(height)])\n self.width = width\n self.height = height\n\n def __str__(self):\n return '\\n'.join(''.join('#' if v else '.' for v in row) for row in self.grid)\n\n def __eq__(self, other):\n return self.grid == other.grid\n\n def __ne__(self, other):\n return self.grid != other.grid\n\n def biodiversity(self):\n return sum(pow(2, idx) if gridval == 1 else 0 for idx, gridval in enumerate(itertools.chain(*self.grid)))\n\n def at(self, x, y):\n if not (0 <= x < self.width and 0 <= y < self.height):\n raise IndexError\n return self.grid[y][x]\n\n def turn_on(self, x, y):\n self.grid[y][x] = 1\n\n def turn_off(self, x, y):\n self.grid[y][x] = 0\n\n def toggle(self, x, y):\n self.grid[y][x] = (self.grid[y][x] + 1) % 2\n\n def num_lit(self):\n return sum(v for row in self.grid for v in row)\n\n def num_lit_neighbors(self, x, y):\n num_lit = 0\n for offset in LightGrid._neighbor_pairs:\n try:\n num_lit += self.at(x+offset[0], y+offset[1])\n except IndexError:\n pass\n return num_lit\n\n def step(self):\n to_modify = dict()\n for x, y in itertools.product(range(self.width), range(self.height)):\n num_lit_neighbors = self.num_lit_neighbors(x, y)\n if self.at(x, y) == 1 and num_lit_neighbors != 1:\n to_modify[(x, y)] = 0\n elif self.at(x, y) == 0 and num_lit_neighbors in [1, 2]:\n to_modify[(x, y)] = 1\n for loc, val in to_modify.items():\n self.grid[loc[1]][loc[0]] = val\n\n\nclass FractalBugGrid(object):\n def __init__(self):\n self.width = self.height = 5\n self.grid = list([[0 for _ in range(self.width)] for _ in range(self.height)])\n self.center = (2, 2)\n self.inner_grid = None\n self.outer_grid = None\n self.lifetime = 0\n\n def __str__(self):\n return '\\n'.join(''.join('#' if v else '.' for v in row) for row in self.grid)\n\n def __eq__(self, other):\n return self.grid == other.grid\n\n def __ne__(self, other):\n return self.grid != other.grid\n\n def num_bugs(self):\n return self._num_bugs_outward() + self._num_bugs_inward() + self._num_bugs_thislevel()\n\n def _num_bugs_thislevel(self):\n return sum(itertools.chain(*self.grid))\n\n def _num_bugs_outward(self):\n if self.outer_grid is None:\n return 0\n else:\n return self.outer_grid._num_bugs_thislevel() + self.outer_grid._num_bugs_outward()\n\n def _num_bugs_inward(self):\n if self.inner_grid is None:\n return 0\n else:\n return self.inner_grid._num_bugs_thislevel() + self.inner_grid._num_bugs_inward()\n\n def at(self, x, y):\n if not (0 <= x < self.width and 0 <= y < self.height):\n raise IndexError\n return self.grid[y][x]\n\n def outer_grid_at(self, x, y):\n return 0 if self.outer_grid is None else self.outer_grid.at(x, y)\n\n def inner_grid_at(self, x, y):\n return 0 if self.inner_grid is None else self.inner_grid.at(x, y)\n\n def adj_bugs(self, x, y, d):\n if x == 0 and d == Direction.WEST:\n return self.outer_grid_at(1, 2)\n elif y == 0 and d == Direction.NORTH:\n return self.outer_grid_at(2, 1)\n elif x == self.width-1 and d == Direction.EAST:\n return self.outer_grid_at(3, 2)\n elif y == self.height-1 and d == Direction.SOUTH:\n return self.outer_grid_at(2, 3)\n elif x == 1 and y == 2 and d == Direction.EAST:\n return sum(self.inner_grid_at(0, yp) for yp in range(self.height))\n elif x == 2 and y == 1 and d == Direction.SOUTH:\n return sum(self.inner_grid_at(xp, 0) for xp in range(self.width))\n elif x == 3 and y == 2 and d == Direction.WEST:\n return sum(self.inner_grid_at(self.width-1, yp) for yp in range(self.height))\n elif x == 2 and y == 3 and d == Direction.NORTH:\n return sum(self.inner_grid_at(xp, self.height-1) for xp in range(self.width))\n else:\n return self.at(*add_dir((x, y), d))\n\n def turn_on(self, x, y):\n self.grid[y][x] = 1\n\n def turn_off(self, x, y):\n self.grid[y][x] = 0\n\n def num_lit_neighbors(self, x, y):\n return sum(self.adj_bugs(x, y, d) for d in Direction)\n\n def step(self, step_outward=True, step_inward=True):\n if step_outward and self.outer_grid is None:\n self.outer_grid = FractalBugGrid()\n self.outer_grid.inner_grid = self\n self.outer_grid.lifetime = -2\n if step_inward and self.inner_grid is None:\n self.inner_grid = FractalBugGrid()\n self.inner_grid.outer_grid = self\n self.inner_grid.lifetime = -2\n\n to_modify = dict()\n for x, y in itertools.product(range(self.width), range(self.height)):\n if (x, y) == self.center:\n continue\n num_lit_neighbors = self.num_lit_neighbors(x, y)\n if self.at(x, y) == 1 and num_lit_neighbors != 1:\n to_modify[(x, y)] = 0\n elif self.at(x, y) == 0 and num_lit_neighbors in [1, 2]:\n to_modify[(x, y)] = 1\n\n if self.outer_grid is not None and step_outward and self.lifetime >= 0:\n self.outer_grid.step(step_inward=False, step_outward=True)\n if self.inner_grid is not None and step_inward and self.lifetime >= 0:\n self.inner_grid.step(step_inward=True, step_outward=False)\n\n for loc, val in to_modify.items():\n self.grid[loc[1]][loc[0]] = val\n self.lifetime += 1\n\n\ndef parse_input(big_str):\n light_grid = LightGrid(5, 5)\n for y, line in enumerate(big_str.splitlines(keepends=False)):\n for x, c in enumerate(line):\n if c == '#':\n light_grid.turn_on(x, y)\n print('{:b}'.format(light_grid.biodiversity()))\n return light_grid\n\n\ndef parse_input_2(big_str):\n bug_grid = FractalBugGrid()\n for y, line in enumerate(big_str.splitlines(keepends=False)):\n for x, c in enumerate(line):\n if c == '#':\n bug_grid.turn_on(x, y)\n return bug_grid\n\n\ndef test():\n light_grid = parse_input(textwrap.dedent(\"\"\"\\\n ....#\n #..#.\n #..##\n ..#..\n #....\"\"\"))\n for step in range(5):\n print(step)\n print(light_grid)\n light_grid.step()\n\n\ndef part_1(big_str):\n light_grid = parse_input(big_str)\n biodiversities = set()\n while light_grid.biodiversity() not in biodiversities:\n biodiversities.add(light_grid.biodiversity())\n light_grid.step()\n return light_grid.biodiversity()\n\n\ndef part_2(grid_str):\n bug_grid = parse_input_2(grid_str)\n for _ in range(200):\n bug_grid.step()\n return bug_grid.num_bugs()\n\n\nif __name__ == \"__main__\":\n with open('input/dec24.txt', 'r') as file:\n the_big_str = file.read()\n\n test_str = textwrap.dedent(\"\"\"\\\n ....#\n #..#.\n #..##\n ..#..\n #....\"\"\")\n\n # print('Part 1:', part_1(the_big_str))\n print('Part 2:', part_2(the_big_str))\n","sub_path":"2019/dec24.py","file_name":"dec24.py","file_ext":"py","file_size_in_byte":7608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"57171334","text":"\"\"\"\nReceiver hooks to use oauth data provided by Aalto-LeTech/django-lti-login.\nThis is modified from the example app:\nhttps://github.com/Aalto-LeTech/django-lti-login/blob/master/example/\n\"\"\"\n\nimport logging\nfrom django.conf import settings\nfrom django.contrib.auth.signals import user_logged_in\nfrom django.contrib import messages\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import reverse\nfrom django.dispatch import receiver\nfrom django_lti_login.signals import lti_login_authenticated\n\nfrom .utils import add_user_to_course\n\n\nlogger = logging.getLogger(__name__)\n\n\n@receiver(lti_login_authenticated)\ndef store_last_login(sender, **kwargs):\n \"\"\"\n Example thing to do before user is actually authenticated, but does exists.\n Django sets user.last_login after this, so it's last time to use it.\n \"\"\"\n request = kwargs.get('request', None)\n user = kwargs.get('user', None)\n if request and user:\n request.session['last_login'] = str(user.last_login)\n\n\n@receiver(user_logged_in)\ndef store_course_info(sender, **kwargs):\n \"\"\"\n Get required course information after user is fully authenticated.\n \"\"\"\n request = kwargs.get('request', None)\n user = kwargs.get('user', None)\n oauth = getattr(request, 'oauth', None)\n\n if request and user and oauth:\n required_fields = [\"context_label\", \"context_title\", \"roles\",\n \"custom_context_api\", \"tool_consumer_instance_guid\",\n \"custom_user_api_token\", \"custom_context_api_id\"]\n accepted_roles = [\"Instructor\", \"TA,TeachingAssistant\"]\n login_info = {}\n\n for field in required_fields:\n login_info[field] = getattr(oauth, field, None)\n\n if None in login_info.values():\n logger.error(\"LTI login request doesn't contain all required \"\n \"fields for course membership update. User that \"\n \"tried to login: {}\".format(user))\n raise PermissionDenied(\"Not all required fields \"\n \"present in LTI login\")\n\n if login_info[\"roles\"] not in accepted_roles:\n raise PermissionDenied(\"Allowed only for teachers and TA's\")\n\n logger.info(\"New authentication by {user} for {label} {name}.\".format(\n user=user,\n label=login_info[\"context_label\"],\n name=login_info[\"context_title\"],\n ))\n\n # Add user to the course according to login information\n if not add_user_to_course(user, login_info):\n messages.error(request, f\"Requested course not found. Only \"\n f\"teachers can create new courses.\")\n\n # Redirect to notresponded page after login\n oauth.redirect_url = reverse('submissions:index')\n\n # List LTI params in debug\n if settings.DEBUG:\n logger.debug(\"LTI login accepted for user %s\", user)\n for k, v in sorted(oauth.params):\n print(\" \\w param -- %s: %s\", k, v)\n","sub_path":"submissions/receivers.py","file_name":"receivers.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"129782007","text":"from django.core.management.base import BaseCommand\nfrom query.models import Video, Face\nfrom scannerpy import Database, DeviceType, Job\nfrom scannerpy.stdlib import parsers, pipelines\nimport os\nimport cv2\n\nclass Command(BaseCommand):\n help = 'Detect faces in videos'\n\n def add_arguments(self, parser):\n parser.add_argument('path')\n\n def handle(self, *args, **options):\n with open(options['path']) as f:\n paths = [s.strip() for s in f.readlines()]\n\n with Database() as db:\n # Only run the detector over videos we haven't yet processed\n filtered = []\n for path in paths:\n video = Video.objects.filter(path=path)\n if len(video) == 0: continue\n video = video[0]\n if len(Face.objects.filter(video=video)) > 0: continue\n filtered.append(path)\n\n # Run the detector via Scanner\n stride = 12\n c = db.new_collection('tmp', filtered, force=True)\n faces_c = pipelines.detect_faces(\n db, c, lambda t: t.strided(stride), 'tmp_faces')\n\n # Save the results to the database\n for path, video_faces_table in zip(filtered, faces_c.tables()):\n video = Video.objects.filter(path=path).get()\n table = db.table(path)\n frames = table.load(['frame'], rows=range(0, table.num_rows(), stride))\n\n video_faces = video_faces_table.load(['bboxes'], parsers.bboxes)\n for (i, frame_faces), (_, frame) in zip(video_faces, frames):\n for bbox in frame_faces:\n f = Face()\n f.video = video\n f.frame = i * stride\n f.bbox = bbox\n f.save()\n\n thumbnail_path = 'assets/thumbnails/{}_{}.jpg'.format(video.id, f.id)\n thumbnail = frame[0][int(bbox.y1):int(bbox.y2),\n int(bbox.x1):int(bbox.x2)]\n cv2.imwrite(thumbnail_path, cv2.cvtColor(thumbnail, cv2.COLOR_RGB2BGR))\n","sub_path":"esper/query/management/commands/face_detect.py","file_name":"face_detect.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"284588459","text":"class Solution:\r\n def rotate(self, matrix):\r\n \"\"\"\r\n :type matrix: List[List[int]]\r\n :rtype: void Do not return anything, modify matrix in-place instead.\r\n \"\"\"\r\n n = len(matrix)\r\n\r\n def r(x, y):\r\n if y == 0 or y == 1:\r\n return\r\n for i in range(x, x + y - 1):\r\n matrix[x][i], matrix[i][x + y - 1], \\\r\n matrix[x + y - 1][2 * x + y - i - 1], matrix[2 * x + y - i - 1][x] \\\r\n = matrix[2 * x + y - i - 1][x], matrix[x][i], \\\r\n matrix[i][x + y - 1], matrix[x + y - 1][2 * x + y - i - 1]\r\n r(x + 1, y - 2)\r\n\r\n r(0, n)\r\n\r\n\r\nsol = Solution()\r\nl1 = [[1, 2], [3, 4]]\r\nsol.rotate(l1)\r\nprint(l1)\r\nl1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\r\nsol.rotate(l1)\r\nprint(l1)\r\nl1 = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]\r\nsol.rotate(l1)\r\nprint(l1)\r\n","sub_path":"Python3/48. Rotate Image.py","file_name":"48. Rotate Image.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"110175595","text":"# !/user/bin/env python\n# _*_ coding: utf-8 _*_\n# @Time : 2021/5/16 17:57\n# @Author : 王俊\n# @File : read_config.py\n# @Software : PyCharm\nimport os\nimport yaml\nfrom common import CONF_DIR\n\n\nclass ReadeConfig(object):\n __instance = None\n\n def __new__(cls, *args, **kwargs):\n if cls.__instance is None:\n cls.__instance = super().__new__(cls)\n return cls.__instance\n\n def __init__(self, f):\n \"\"\" 此类用于读取配置文件信息,配置文件采用yaml形式\n :param f: config配置文件的配置文件名称\n \"\"\"\n self.filename = os.path.join(CONF_DIR, f)\n self._data = None\n\n def get(self, key=None, index=0, hot=False) -> dict:\n \"\"\" 用于获取配置文件某个值\n :param key: 需要获取的配置文件项\n :param index: 索引,配置项以‘---’分隔,默认为0\n :param hot:热加载配置,默认为False不启动,True表示每次都从文件中读取数据\n :return: 返回配置项信息\n \"\"\"\n if self._data is None or hot:\n with open(self.filename, \"rb\") as f:\n self._data = list(yaml.safe_load_all(f))\n if key is None:\n return self._data[index]\n else:\n return self._data[index][key]\n\n\nconf = ReadeConfig(\"dbconfig.yaml\").get()\nbase_conf = ReadeConfig(\"baseconfig.yaml\")\n\n\ndef select_db(db_type):\n db_map = {\n \"weijian\": conf.get(\"WeiJianDBConfig\"),\n \"mydb\": conf.get(\"MyDBConfig\"),\n \"dbpoolmaster\": conf.get(\"MyDBConfig\"),\n \"dbpoollocal\": conf.get(\"DBPoolLocalHostConfig\"),\n }\n db_conf = db_map.get(db_type)\n return db_conf\n","sub_path":"common/read_config.py","file_name":"read_config.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"503308879","text":"import asyncio\nfrom builtins import dict\nfrom contextlib import suppress\nfrom copy import copy\nfrom io import BytesIO\n\nimport discord\nimport pprint\n\nfrom redbot.core import commands, checks, Config\nfrom redbot.core.utils import common_filters, mod\nfrom redbot.core.utils.chat_formatting import pagify, humanize_list\nfrom redbot.core.utils.predicates import MessagePredicate\nfrom redbot.core.i18n import Translator, cog_i18n\n\ncheck_permissions = getattr(mod, \"check_permissions\", checks.check_permissions)\n\nfrom .converter import RiftConverter, search_converter, SearchError\n\n\nCog = getattr(commands, \"Cog\", object)\n\n\n_ = Translator(\"Rift\", __file__)\n\n\nmax_size = 8_000_000 # can be 1 << 23 but some unknowns also add to the size\nm_count = 0\n\nasync def close_check(ctx):\n \"\"\"Admin / manage channel OR private channel\"\"\"\n if isinstance(ctx.channel, discord.DMChannel):\n return True\n return await mod.is_admin_or_superior(ctx.bot, ctx.author) or await check_permissions(\n ctx, {\"manage_channels\": True}\n )\n\n\nclass RiftError(Exception):\n pass\n\n\nclass Rift(Cog):\n \"\"\"\n Communicate with other servers/channels.\n \"\"\"\n\n def __init__(self, bot):\n super().__init__()\n self.bot = bot\n self.open_rifts = {}\n self.requesting_users = []\n self.bot.loop.create_task(self.load_rifts())\n\n self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True)\n self.config.register_global(rifts=[])\n self.config.register_channel(blacklisted=False)\n self.config.register_guild(blacklisted=False)\n self.config.register_user(blacklisted=False)\n\n async def save_rift(self, rift):\n async with self.config.rifts() as rifts:\n rifts.append(rift.toIDs())\n\n async def load_rifts(self):\n\n def add_rift(sources, rift):\n if rift.source in sources:\n sources[rift.source].append(rift)\n else:\n sources[rift.source] = [rift]\n\n loaded = []\n sources = {}\n async with self.config.rifts() as rifts:\n for rift in rifts:\n author = self.bot.get_user(rift[0])\n if not isinstance(author, discord.User): continue\n source = self.bot.get_channel(rift[1]) or self.bot.get_user(rift[1])\n if not isinstance(source, discord.TextChannel) and not isinstance(source, discord.User): continue\n destination = self.bot.get_channel(rift[2]) or self.bot.get_user(rift[2])\n if not isinstance(destination, discord.TextChannel) and not isinstance(destination, discord.User): continue\n rift = RiftConverter.create(author, source, destination)\n loaded.append(rift)\n add_rift(sources, rift)\n\n self.open_rifts.update(((rift, {}) for rift in loaded))\n for source, rifts in sources.items():\n try:\n embed = await self.create_simple_embed(rift.author,\n \"Rift has been reloaded! \\n{}\".format(\"\\n\".join(str(rift) for rift in rifts)),\n \"Rift Loaded\" if len(rifts) == 1 else \"Rifts Loaded\")\n await source.send(embed=embed)\n except (discord.Forbidden, discord.HTTPException):\n pass\n\n # COMMANDS\n\n @commands.group()\n async def rift(self, ctx):\n \"\"\"\n Communicate with other channels through Red.\n \"\"\"\n pass\n\n @rift.group()\n async def blacklist(self, ctx):\n \"\"\"\n Configures blacklists.\n\n Blacklisted destinations cannot have rifts opened to them.\n \"\"\"\n pass\n\n @blacklist.command(name=\"channel\")\n @commands.check(close_check)\n async def blacklist_channel(self, ctx, *, channel: discord.TextChannel = None):\n \"\"\"\n Blacklists the current channel or the specified channel.\n\n Can also blacklist DM channels.\n \"\"\"\n if channel and isinstance(ctx.channel, discord.DMChannel):\n raise commands.BadArgument(_(\"You cannot blacklist a channel in DMs.\"))\n if isinstance(ctx.channel, discord.DMChannel):\n channel = ctx.author\n group = self.config.user(channel)\n else:\n channel = channel or ctx.channel\n group = self.config.channel(channel)\n blacklisted = not await group.blacklisted()\n await group.blacklisted.set(blacklisted)\n await ctx.maybe_send_embed(\n _(\"Channel is {} blacklisted.\".format(\"now\" if blacklisted else \"no longer\"))\n )\n if blacklisted:\n await self.close_rifts(ctx, ctx.author, channel)\n\n @blacklist.command(name=\"server\")\n @commands.guild_only()\n @checks.admin_or_permissions(manage_guild=True)\n async def blacklist_server(self, ctx):\n \"\"\"\n Blacklists the current server.\n\n All channels and members in a server are considered blacklisted if the server is blacklisted.\n Members can still be reached if they are in another, non-blacklisted server.\n \"\"\"\n group = self.config.guild(ctx.guild)\n blacklisted = not await group.blacklisted()\n await group.blacklisted.set(blacklisted)\n await ctx.maybe_send_embed(\n _(\"Server is {} blacklisted.\".format(\"now\" if blacklisted else \"no longer\"))\n )\n if blacklisted:\n await self.close_rifts(ctx, ctx.author, ctx.guild)\n\n @rift.command(name=\"close\")\n @commands.check(close_check)\n async def rift_close(self, ctx, channel : discord.TextChannel = None):\n \"\"\"\n Closes all rifts that lead to this channel.\n \"\"\"\n if channel is None:\n channel = ctx.author if isinstance(ctx.channel, discord.DMChannel) else ctx.channel\n await self.close_rifts(ctx, ctx.author, channel)\n\n @rift.command(name=\"open\")\n async def rift_open(self, ctx, *rifts: RiftConverter(_, globally=True)):\n \"\"\"\n Opens a rift to the specified destination.\n\n The destination may be any channel or user that both you and the bot are connected to, even across servers.\n \"\"\"\n if not rifts:\n return await ctx.send_help()\n rifts = set(rifts)\n create_queue = []\n for rift in rifts:\n if not await self.rift_exists(rift):\n if ctx.guild is None or rift.destination not in ctx.guild.channels:\n accepted, reason = await self.request_access(ctx, rift)\n if not accepted:\n continue\n dest_open_embed = await self.create_simple_embed(ctx.author,\n _(rift.mention()),\n \"A Rift has been opened.\"\n )\n #ctx.bot.loop.create_task(\n # rift.destination.send(embed=dest_open_embed)\n #)\n await rift.destination.send(embed=dest_open_embed)\n create_queue.append(rift)\n\n with suppress(NameError):\n if reason is not None:\n await ctx.maybe_send_embed(reason)\n if not accepted:\n return\n if not create_queue:\n return await ctx.maybe_send_embed(\"Rift(s) already exist.\")\n # add new rifts\n self.open_rifts.update(((rift, {}) for rift in create_queue))\n for rift in create_queue:\n await self.save_rift(rift)\n\n open_embed = await self.create_simple_embed(ctx.author,\n _(\"A rift has been opened to {}! Everything you say will be relayed there.\\n\"\n \"Responses will be relayed here.\\nType `exit` here to quit.\"\n ).format(humanize_list([str(rift.destination) for rift in create_queue]))\n , \"Rift Opened!\")\n await ctx.send(embed=open_embed)\n\n @rift.command(name=\"sources\")\n async def rift_list_sources(self, ctx, destination: discord.TextChannel = None):\n \"\"\"List sources for opened rifts\"\"\"\n if destination is None:\n destination = ctx.channel\n rifts = await self.get_rifts(destination, False)\n if rifts:\n message = (\"Rifts:\") + \"\\n\\n\"\n message += \"\\n\".join(rift.mention() for rift in rifts)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n else:\n embed = await self.create_simple_embed(self.bot.user, \"No Rift Found.\")\n await ctx.send(embed=embed)\n\n @rift.command(name=\"destinations\", aliases=[\"dests\"])\n async def rift_list_destinations(self, ctx, source: discord.TextChannel = None):\n \"\"\"List destinations for opened rifts\"\"\"\n if source is None:\n source = ctx.channel\n rifts = await self.get_rifts(source, True)\n if rifts:\n message = (\"Rifts:\") + \"\\n\\n\"\n message += \"\\n\".join(rift.mention() for rift in rifts)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n else:\n embed = await self.create_simple_embed(self.bot.user, \"No Rift Found.\")\n await ctx.send(embed=embed)\n\n @rift.command(name=\"search\")\n async def rift_search(self, ctx, searchby: search_converter(_) = None, *, search=None):\n \"\"\"\n Searches through open rifts.\n\n searchby: author, source, or destination. If this isn't provided, all\n three are searched through.\n search: Search for the specified author/source/destination. If this\n isn't provided, the author or channel of the command is used.\n \"\"\"\n searchby = searchby or list(range(3))\n if search is None:\n search = [ctx.author, ctx.channel, ctx.author]\n else:\n try:\n search = await RiftConverter.search(ctx, search, False, _)\n except commands.BadArgument as e:\n embed = await self.create_simple_embed(self.bot.user, str(e), \"Bot Exception\")\n return await ctx.send(embed=embed)\n results = set()\n for rift in self.open_rifts:\n for i in searchby:\n if rift[i] in search:\n results.add(rift)\n if not results:\n return await ctx.maybe_send_embed(_(\"No rifts were found with these parameters.\"))\n message = _(\"Results:\") + \"\\n\\n\"\n message += \"\\n\".join(str(rift) for rift in results)\n for page in pagify(message):\n await ctx.maybe_send_embed(page)\n\n @rift_open.error\n @rift_search.error\n async def rift_error(self, ctx, error):\n if isinstance(error, commands.ConversionError):\n embed = discord.Embed(color=ctx.guild.me.color, \n description=str(error.__cause__),\n title=\"Destination not found\")\n return await ctx.send(embed=embed)\n raise error\n\n # UTILITIES\n\n #async def select_from_rifts(self, rifts):\n # message = (\"Rifts:\") + \"\\n\\n\"\n # message += f\"\\n**{rifts.index(rift) + 1}.** \".join(rift.mention() for rift in rifts)\n # for page in pagify(message):\n # await ctx.maybe_send_embed(page)\n\n # await ctx.send(\"Select the rift's number you would like to edit the settings of\")\n # try:\n # msg = await ctx.bot.wait_for(\"message\", check=MessagePredicate.same_context(ctx), timeout=15)\n # except asyncio.TimeoutError:\n # await ctx.maybe_send_embed(\"Timeout. Selection cancelled.\")\n # return None\n # try:\n # index = int(msg.content)\n # except ValueError:\n # await ctx.maybe_send_embed(\"Invalid input.\")\n # return None\n # try:\n # rift = rifts[index]\n # return rift\n # except IndexError:\n # await ctx.maybe_send_embed(\"Rift not found\")\n # return None\n\n async def request_access(self, ctx, rift) -> (bool, str):\n author = ctx.author\n if author.id in self.requesting_users:\n failed_embed = await self.create_simple_embed(author,\n \"You currently have a Rift request open. Please wait \"\n \"until that expires before trying again.\",\n \"Existing rift request.\")\n try:\n await ctx.send(embed=failed_embed)\n except discord.Forbidden:\n pass\n return False, None\n destination = rift.destination\n source = rift.source\n self.requesting_users.append(author.id)\n embed = await self.create_simple_embed(\n author,\n (f\"{author} is requesting to open a rift to here from #{source} in {ctx.guild.name}\" + \"\\n\" +\n f\"{rift}\" + \"\\n\\n\" +\n f\"An admin can enter `accept` or `decline` to accept/decline this request.\"),\n \"Requesting Cross-Server Rift Permission\")\n try:\n request_msg = await destination.send(embed=embed)\n except discord.Forbidden:\n return False, f\"I do not have permissions to send in {destination}\"\n\n def check(m):\n is_accept_message = m.content.lower().strip() in [\"accept\", \"yes\", \"y\", \"decline\", \"no\", \"n\"]\n is_correct_channel = m.channel.id == rift.destination.id\n if isinstance(m.channel, discord.channel.DMChannel):\n is_correct_channel = m.channel.recipient.id == rift.destination.id or m.channel.id == rift.destination.id\n return is_correct_channel and is_accept_message\n return is_correct_channel and is_accept_message and m.author.guild_permissions.manage_channels\n\n try:\n msg = await ctx.bot.wait_for(\"message\", check=check, timeout=25)\n except asyncio.TimeoutError:\n try:\n await request_msg.delete()\n except discord.NotFound:\n pass\n if author.id in self.requesting_users:\n self.requesting_users.remove(author.id)\n return False, \"No staff response to request.\"\n response = msg.content.lower().strip()\n if response in [\"accept\", \"yes\", \"y\"]:\n accepted, reason = True, f\"{msg.author.name} has __**accepted**__ the request to open the cross-server rift.\\n{rift}\"\n elif response in [\"decline\",\"no\",\"n\"]:\n accepted, reason = False, f\"{msg.author.name} has __**declined**__ the request to open the cross-server rift.\\n{rift}\"\n else:\n accepted, reason = False, \"Unknown response.\"\n\n try:\n await request_msg.delete()\n except discord.NotFound:\n pass\n if author.id in self.requesting_users:\n self.requesting_users.remove(author.id)\n return accepted, reason\n\n async def close_rifts(self, ctx, closer, destination, search_source : bool = False):\n rifts = await self.get_rifts(destination, search_source)\n if rifts:\n for rift in rifts:\n del self.open_rifts[rift]\n async with self.config.rifts() as rifts:\n if rift.toIDs() in rifts:\n rifts.remove(rift.toIDs())\n source_embed = await self.create_simple_embed(ctx.author,\n _(\"{} has closed the rift to {}.\").format(closer, rift.destination),\n \"Rift Closed\")\n await rift.source.send(embed=source_embed)\n dest_embed = await self.create_simple_embed(ctx.author,\n _(\"Rift from {} closed by {}.\").format(rift.source, closer),\n \"Rift Closed\")\n await rift.destination.send(embed=dest_embed)\n else:\n embed = await self.create_simple_embed(self.bot.user, _(\"No rifts were found that connect to here.\"), \"No Rifts Found\")\n await ctx.send(embed=embed)\n\n async def get_rifts(self, destination, toggle=False):\n rifts = []\n if isinstance(destination, discord.Guild):\n if toggle:\n check = lambda rift: rift.source in destination.channels\n else:\n check = lambda rift: rift.destination in destination.channels\n else:\n if toggle:\n check = lambda rift: rift.source == destination\n else:\n check = lambda rift: rift.destination == destination\n for rift in self.open_rifts.copy():\n if check(rift):\n rifts.append(rift)\n return rifts\n\n async def get_embed(self, destination, attachments):\n attach = attachments[0]\n if (\n hasattr(destination, \"guild\")\n and await self.bot.db.guild(destination.guild).use_bot_color()\n ):\n color = destination.guild.me.colour\n else:\n color = self.bot.color\n description = \"\\n\\n\".join(\n f\"{self.xbytes(attach.size)}\\n**[{attach.filename}]({attach.url})**\"\n for a in attachments\n )\n embed = discord.Embed(colour=color, description=description)\n embed.set_image(url=attach.url)\n return embed\n\n async def rift_exists(self, rift):\n for rift2 in await self.get_rifts(rift.source, True):\n if rift2.destination == rift.destination:\n return True\n return False\n\n\n def permissions(self, destination, user, is_owner=False):\n if isinstance(destination, discord.User):\n return destination.dm_channel.permissions_for(user)\n if not is_owner:\n member = destination.guild.get_member(user.id)\n if member:\n return destination.permissions_for(member)\n else:\n every = destination.guild.default_role\n overs = destination.overwrites_for(every)\n overs.read_messages = True\n overs.send_messages = True\n perms = (every.permissions.value & ~overs[1].value) | overs[0].value\n return discord.Permissions(perms)\n return discord.Permissions.all()\n\n async def process_message(self, rift, message, destination):\n if isinstance(destination, discord.Message):\n send_coro = destination.edit\n else:\n send_coro = destination.send\n channel = (\n message.author if isinstance(message.channel, discord.DMChannel) else message.channel\n )\n send = channel == rift.source\n destination = rift.destination if send else rift.source\n source = rift.source if send else rift.destination\n author = message.author\n me = (\n destination.dm_channel.me\n if isinstance(destination, discord.User)\n else destination.guild.me\n )\n is_owner = await self.bot.is_owner(author)\n author_perms = self.permissions(destination, author, is_owner)\n bot_perms = self.permissions(destination, me)\n content = message.content\n if not is_owner:\n if not author_perms.administrator:\n content = common_filters.filter_invites(content)\n if not author_perms.mention_everyone:\n content = common_filters.filter_mass_mentions(content)\n attachments = message.attachments\n files = []\n embed = None\n if attachments and author_perms.attach_files and bot_perms.attach_files:\n overs = await asyncio.gather(*(self.save_attach(file, files) for file in attachments))\n overs = list(filter(bool, overs))\n if overs:\n content += (\n \"\\n\\n\"\n + _(\"Attachments:\")\n + \"\\n\"\n + \"\\n\".join(f\"({self.xbytes(a.size)}) {a.url}\" for a in attachments)\n )\n if not any((content, files, embed)):\n raise RiftError(_(\"No content to send.\"))\n msg_embed = await self.create_message_embed(ctx=message, source=source, content=content, files=attachments)\n return await send_coro(embed=msg_embed)\n\n async def save_attach(self, file: discord.Attachment, files) -> discord.File:\n if file.size > max_size:\n return file\n buffer = BytesIO()\n await file.save(buffer, seek_begin=True)\n files.append(discord.File(buffer, file.filename))\n return None\n\n def xbytes(self, b):\n blist = (\"B\", \"KB\", \"MB\")\n index = 0\n while True:\n if b > 900:\n b = b / 1024.0\n index += 1\n else:\n return \"{:.3g} {}\".format(b, blist[index])\n\n # EVENTS\n\n async def on_message(self, m):\n if m.author.bot:\n return\n channel = m.author if isinstance(m.channel, discord.channel.DMChannel) else m.channel\n sent = {}\n ctx = (await self.bot.get_context(m))\n is_command = ctx.valid or m.content.startswith(str(ctx.prefix))\n if is_command: return\n for rift, record in self.open_rifts.copy().items():\n privilege_check = (rift.author == m.author if not isinstance(m.channel, discord.channel.DMChannel) else m.author == channel)\n if privilege_check and m.content.lower() == \"exit\":\n await self.close_rifts(ctx, m.author, channel, search_source=(True if channel == rift.source else False))\n return\n\n if rift.source == channel:\n try:\n record[m] = await self.process_message(rift, m, rift.destination)\n except discord.HTTPException as e:\n embed = await self.create_simple_embed(self.bot.user,\n _(\"I couldn't send your message due to an error: {}\").format(e),\n \"Bot Exception\")\n await channel.send(embed=embed)\n elif rift.destination == channel:\n rift_chans = (rift.source, rift.destination)\n if rift_chans in sent:\n record[m] = sent[rift_chans]\n else:\n record[m] = sent[rift_chans] = await self.process_message(rift, m, rift.source)\n\n async def on_message_delete(self, m):\n if m.author.bot and not self.bot.user:\n return\n deleted = set()\n for record in self.open_rifts.copy().values():\n for source_m, embed_m in record.items():\n if m.id == source_m.id:\n with suppress(KeyError, discord.NotFound):\n record.pop(source_m)\n if embed_m not in deleted:\n deleted.add(source_m)\n await embed_m.delete()\n break\n elif m.id == embed_m.id:\n with suppress(KeyError, discord.NotFound):\n record.pop(source_m)\n if source_m not in deleted:\n deleted.add(source_m)\n await source_m.delete()\n break\n\n async def on_message_edit(self, b, a):\n if a.author.bot:\n return\n channel = a.author if isinstance(a.channel, discord.DMChannel) else a.channel\n sent = set()\n for rift, record in self.open_rifts.copy().items():\n if rift.source == channel and rift.author == a.author:\n with suppress(KeyError, discord.NotFound):\n await self.process_message(rift, a, record[a])\n elif rift.destination == channel:\n rift_chans = (rift.source, rift.destination)\n if rift_chans not in sent:\n sent.add(rift_chans)\n with suppress(KeyError, discord.NotFound):\n await self.process_message(rift, a, record[a])\n\n async def create_message_embed(self, ctx, source, content, files):\n message_content = (content[:1000] if len(content) > 1000 else content)\n embed = discord.Embed(color=ctx.author.color, description=message_content)\n embed.set_author(icon_url=ctx.author.avatar_url,name=ctx.author.name + \" from #\" + source.name)\n if len(files) == 1:\n file = files[0]\n if file.height is not None and file.height > 64 and file.width > 64 and not file.is_spoiler():\n embed.set_image(url=file.url)\n else:\n embed.add_field(name=\"Attachment:\", value=file.url)\n elif len(files) > 1:\n file_str = \"\"\n for file in files:\n file_str += file.url\n file_str += \"\\n\\n\"\n embed.add_field(name=\"Attachments:\", value=file_str)\n return embed\n\n async def create_simple_embed(self, author: discord.Member, message: str, title: str = None):\n simple_embed = discord.Embed(color=author.color, description=message)\n if title is not None:\n simple_embed.set_author(icon_url=author.avatar_url,name=title)\n return simple_embed\n","sub_path":"rift/rift.py","file_name":"rift.py","file_ext":"py","file_size_in_byte":25331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"327538039","text":"# 이번 가을학기에 '문제 해결' 강의를 신청한 학생들은 텀 프로젝트를 수행해야 한다.\n# 프로젝트 팀원 수에는 제한이 없다. 심지어 모든 학생들이 동일한 팀의 팀원인 경우와 같이 한 팀만 있을 수도 있다.\n# 프로젝트 팀을 구성하기 위해, 모든 학생들은 프로젝트를 함께하고 싶은 학생을 선택해야 한다.\n# (단, 단 한 명만 선택할 수 있다.)\n# 혼자 하고 싶어하는 학생은 자기 자신을 선택하는 것도 가능하다.\n#\n# 학생들이(s1, s2, ..., sr)이라 할 때, r=1이고 s1이 s1을 선택하는 경우나,\n# s1이 s2를 선택하고, s2가 s3를 선택하고,..., sr-1이 sr을 선택하고, sr이 s1을 선택하는 경우에만 한 팀이 될 수 있다.\n#\n# 예를 들어, 한 반에 7명의 학생이 있다고 하자. 학생들을 1번부터 7번으로 표현할 때, 선택의 결과는 다음과 같다.\n#\n# 1 2\t3\t4\t5\t6\t7\n# 3\t 1 3\t7\t3\t4\t6\n# 위의 결과를 통해 (3)과 (4, 7, 6)이 팀을 이룰 수 있다. 1, 2, 5는 어느 팀에도 속하지 않는다.\n#\n# 주어진 선택의 결과를 보고 어느 프로젝트 팀에도 속하지 않는 학생들의 수를 계산하는 프로그램을 작성하라.\n#\n# 입력\n# 첫째 줄에 테스트 케이스의 개수 T가 주어진다.\n# 각 테스트 케이스의 첫 줄에는 학생의 수가 정수 n (2 ≤ n ≤ 100,000)으로 주어진다.\n# 각 테스트 케이스의 둘째 줄에는 선택된 학생들의 번호가 주어진다. (모든 학생들은 1부터 n까지 번호가 부여된다.)\n#\n# 출력\n# 각 테스트 케이스마다 한 줄에 출력하고, 각 줄에는 프로젝트 팀에 속하지 못한 학생들의 수를 나타내면 된다.\n\n\nimport sys\n\n\nT = int(sys.stdin.readline().rstrip())\nfor t in range(T):\n n = int(sys.stdin.readline().rstrip())\n wish = [0] + list(map(int, sys.stdin.readline().rstrip().split()))\n\n alone = []\n visited = [False] * (n + 1)\n\n for start in range(1, n + 1):\n if visited[start]:\n continue\n\n start_of_2nd_loop = start\n # v가 두번째 루프의 시작이 될 때까지 이동\n # (start == wish[start]일 경우 그대로 있음)\n while not visited[start_of_2nd_loop]:\n visited[start_of_2nd_loop] = True\n start_of_2nd_loop = wish[start_of_2nd_loop]\n\n w = start\n # 두번째 루프의 시작 v == 첫번째 루프의 시작 인덱스값.\n # 따라서 v와 만나기 전까지 start부터 이동시키며 alone을 센다.\n while w != start_of_2nd_loop:\n alone.append(w)\n w = wish[w]\n\n print(len(alone))\n","sub_path":"Baekjoon/TermProject_2.py","file_name":"TermProject_2.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"570126800","text":"#!/usr/bin/env python3\n\nimport pika\nimport sys, os\nimport time\nimport threading\nimport logging\nimport redis\nimport queue\nimport pdfkit\nimport time\n\ntime.sleep(20)\n\nxrange=range\n\nif sys.argv[1:]:\n max_threads = int(sys.argv[1])\nelse:\n max_threads = int(os.environ.get('MAX_THREADS'))\n\nlogfile = os.environ.get('LOGFILE')\nrabbit_host = os.environ.get('RABBIT_HOST')\nrabbit_queue = os.environ.get('RABBIT_QUEUE')\nrabbit_user = os.environ.get('RABBIT_USER')\nrabbit_password = os.environ.get('RABBIT_PASS')\nredis_host = os.environ.get('REDIS_HOST')\nredis_port = os.environ.get('REDIS_PORT')\nredis_db = os.environ.get('REDIS_DB')\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)-15s - %(threadName)-10s - %(message)s',filename=logfile)\n\npdfkitoptions = {\n 'enable-local-file-access': None,\n 'javascript-delay': 200,\n 'wait-for-network-idle': None\n}\n\ntime.sleep(15)\n\ndef render_pdf(msg_id):\n output_file = '/tmp/' + msg_id + '.pdf'\n input_file = '/tmp/' + msg_id + '.html'\n logging.debug('loading html from redis')\n redis_server = redis.Redis(redis_host, port=redis_port, db=redis_db)\n redis_response = redis_server.get(msg_id)\n logging.debug('html loaded')\n m = open(input_file, \"wb\")\n m.write(redis_response)\n m.close()\n logging.debug('html writed')\n start_time = time.time()\n sys_output = pdfkit.from_file(input_file, output_file, options=pdfkitoptions)\n finish_time = time.time()\n input_size = str(os.path.getsize(input_file)/1024) #.decode('utf-8')\n output_size = str(os.path.getsize(output_file)/1024) #.decode('utf-8')\n dbg_mesg = '[R] Render [msg.id:' + msg_id + '] ' + '[rend.time:' + str(finish_time-start_time) + 'sec]' + '[in.fle:' + input_file + '(' + input_size + 'kb)]' + '[ou.fle:' + output_file + '(' + output_size + 'kb)]'\n logging.debug(dbg_mesg)\n n = open(output_file, \"rb\")\n binary_data = n.read()\n n.close()\n logging.debug('pdf loaded')\n msg_out = msg_id.split('_')\n msg = 'R_' + msg_out[1]\n redis_server.set(msg, binary_data)\n logging.debug('pdf writed')\n redis_server.delete(msg_id)\n logging.debug('db record removed: ' + msg_id)\n os.remove(output_file)\n logging.debug('tmp file removed: ' + input_file)\n os.remove(input_file)\n logging.debug('tmp file removed: ' + output_file)\n logging.debug('render done')\n if not sys_output:\n return True, output_file\n return False, sys_output\n\n#logging.debug('backend node starting...')\nprint('backend node starting...')\nTQ = queue.Queue()\n#logging.debug('threads pool starting...')\nprint('threads pool starting...')\n\ndef catcher(q):\n while True:\n try:\n print (\"trying...\")\n print (q)\n item = q.get()\n print (\"wut...\")\n except Empty:\n break\n\n #logging.debug('render get task: ' + item.strip().decode('utf-8'))\n print('render get task: ' + item.strip().decode('utf-8'))\n render_pdf(item.strip().decode('utf-8'))\n q.task_done()\n\nfor i in xrange(max_threads):\n wrkr_T = threading.Thread(target = catcher, args=(TQ,))\n print('thread created...')\n wrkr_T.daemon = True\n wrkr_T.start()\n logging.debug('thread: ' + str(i) + ' started')\n\nlogging.debug('consumer started...')\ncredentials = pika.PlainCredentials(rabbit_user, rabbit_password)\ntry:\n rabbit_server = pika.BlockingConnection(pika.ConnectionParameters(host=rabbit_host,credentials=credentials))\n channel = rabbit_server.channel()\n channel.queue_declare(queue=rabbit_queue)\n def callback(ch, method, properties, body):\n TQ.put(body)\n logging.debug('consumer got task: ' + body.strip().decode('utf-8'))\n channel.basic_consume(rabbit_queue, callback, auto_ack = True)\n channel.start_consuming()\n\nexcept KeyboardInterrupt:\n logging.debug('backen daemon stopt')\n print (\"backend node stopt\")\n\n\n","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"508701429","text":"# -*- coding: utf-8 -*-\n# !/usr/bin/python\n# python 3.6\n\nimport pandas as pd\nfrom numpy import asmatrix\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split, RandomizedSearchCV\nfrom numpy import abs, mean\nimport scipy.stats as st\n\n# 读取文件\nfile_name = 'C.test_data201803.csv'\ndata = pd.read_csv(file_name)\nY = data['KWH']\n\nprint('real y values: ')\nprint(Y)\n\ndata = asmatrix(data)\nX = data[:, 0]\nprint(X)\n\n\n# 划分训练集和测试集\nseed = 7\ntest_size = 0.1\nX_train, X_test, y_train, y_test = train_test_split(X,\n Y,\n test_size=test_size,\n random_state=seed)\n\nX_train = asmatrix(X_train)\n\n\n# 建立模型\nmodel = XGBClassifier()\nmodel.fit(X_train, y_train)\n\n\n# 预测\ny_pred = model.predict(X)\nmape = mean(abs(Y - y_pred)/Y)\n\nprint('prediction of y')\nprint(y_pred)\nprint('Mean Absolute Percentage Error')\nprint(mape)\n\n# 通过交叉验证寻找最优参数并且优化模型\nparams = {\"n_estimators\": st.randint(100, 500),\n 'max_depth': st.randint(6, 30)}\nmodel_updated = RandomizedSearchCV(\n model, params, cv=10, random_state=1, n_iter=20)\n\n# 预测\ny_pred_update = model_updated.predict(X)\nmape_update = mean(abs(Y - y_pred_update)/Y)\n\nprint('prediction updated of y')\nprint(y_pred_update)\nprint('Mean Absolute Percentage Error')\nprint(mape_update)\n","sub_path":"entretien/xgboost/example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"247628392","text":"\"\"\"Problem:\n Given a staircase with N stairs and a set X of steps \n that you can take at a time i.e. {1,2} write an algorithm \n that determines the number of possible paths to reach the \n top of the staircase.\n Note: There are multiple solutions, however, the dynamic\n programming solution is preferable to the others. \"\"\"\n#It would take minimal effort to modify this to output the \n#actual paths i.e. N=4, X=[1,3,5], Paths=[[4,3,2,1,0],[4,1,0],[4,3,0]]\n\ndef num_ways(N,X,current_stair):\n ways = 0\n if current_stair == N:\n return 1; #The trivial case, only one way to get from step 4 to step 4\n for i in range(len(X)): #Walk through all the cases on the current step\n if X[i] + current_stair <= N:\n ways += num_ways(N,X,X[i] + current_stair) #if we've found a possible case take the step\n return ways\n\ndef num_ways_bottomup(N,X):\n if 0 == N:\n return 1;\n ways = list(range(N+1))\n ways[0] = 1 #Trival Solution\n for i in range(1,N+1,1):\n total = 0\n #print(i)\n for j in range(len(X)):\n #print(X[j])\n if i - X[j] >= 0:\n #print(i,\"-\",X[j],\">=\",0)\n total += ways[i-X[j]]\n ways[i] = total\n #print(\"ways to \",i,\" = \",ways[i])\n return ways[N]\n\nN=4\n#N=3\n#N=2\nX=[1,3,5] #Should be 3 for N = 4\n#X=[1,2] #Should be 5 for N = 4, 3 for N = 3, 2 for N = 2\nx=[[1,2],[1,3,5]]\nfor n in range(N+1): #Use the for loops to test multiple cases.\n for i in range(len(x)):\n print(\"The staircase is: \",n,\" steps.\")\n print(\"We can take: \",x[i],\" steps at a time.\")\n #print(\"There are: \",num_ways(n,x[i],0),\" ways to the top.\")\n print(\"There are: \",num_ways_bottomup(n,x[i]),\" way(s) to the top.\")\n print(' ')\n\"\"\"print(\"The staircase is: \",N,\" steps.\")\nprint(\"We can take: \",X,\" steps at a time.\")\n#print(\"There are: \",num_ways(N,X,0),\" way(s) to the top.\")\nprint(\"There are: \",num_ways_bottomup(N,X),\" ways to the top.\")\"\"\"","sub_path":"Python/staircase.py","file_name":"staircase.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"33361885","text":"# project/server/auth/views.py\n\nimport datetime\n\nfrom flask import Blueprint, request, make_response, jsonify\nfrom flask.views import MethodView\n\nfrom project.server import bcrypt, db\nfrom project.server.models.DPIAudit import DpiAudit\nfrom flask_cors import CORS\n\ndpiaudit_blueprint = Blueprint('Dpiaudit', __name__)\nCORS(dpiaudit_blueprint)\n\nclass DPIAuditPOSTAPI(MethodView):\n def post(self):\n\n post_data = request.get_json()\n try:\n assObj = DpiAudit(\n question_id=post_data.get('question_id'),\n section_id=post_data.get('section_id'),\n owner_id=post_data.get('owner_id'),\n description=post_data.get('description')\n )\n db.session.add(assObj)\n db.session.commit()\n print(assObj.to_dict())\n responseObject = {\n \"id\":assObj.id,\n \"question_id\":assObj.question_id,\n \"section_id\":assObj.section_id,\n \"description\":assObj.owner_id,\n \"owner_id\":assObj.owner_id\n }\n return make_response(jsonify(responseObject)), 200\n except Exception as e:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return make_response(jsonify(responseObject)), 401\n\n\nclass DPIAuditGETAPI(MethodView):\n def get(self):\n try:\n assessments = DpiAudit.query.all()\n assessmentArr = []\n for assessment in assessments:\n assessmentArr.append(assessment.to_dict())\n return jsonify(assessmentArr)\n except Exception as e:\n responseObject = {\n 'status': 'fail',\n 'message': 'Some error occurred. Please try again.'\n }\n return make_response(jsonify(responseObject)), 401\n\n\n\n@dpiaudit_blueprint.route('/dpiaudit/', methods=['GET', 'PUT', 'DELETE'])\ndef bucketlist_manipulation(id, **kwargs):\n gotData = DpiAudit.query.filter_by(id=id).first()\n\n if request.method == \"DELETE\":\n if(gotData):\n db.session.delete(gotData)\n db.session.commit()\n response = {\n \"id\":gotData.id,\n 'message':\"Removed successfully\"\n }\n return make_response(jsonify(response)), 201\n else:\n return \"Error while deleting\"\n\n elif request.method == 'PUT':\n obj = request.get_json()\n if(obj):\n\n # gotData.active = obj.get('active')\n gotData.question_id = obj.get('question_id')\n gotData.section_id = obj.get('section_id')\n gotData.owner_id = obj.get('owner_id')\n gotData.description = obj.get('description')\n gotData.modified_date = datetime.datetime.now()\n\n db.session.add(gotData)\n db.session.commit()\n\n response = {\n \"id\":gotData.id,\n \"question_id\":gotData.question_id,\n \"section_id\":gotData.section_id,\n \"owner_id\":gotData.owner_id,\n \"description\":gotData.description,\n 'message':\"Updated successfully\"\n }\n return make_response(jsonify(response)), 200\n else:\n return \"Error while updating\"\n else:\n if(gotData):\n response = {\n \"id\":gotData.id,\n \"question_id\":gotData.question_id,\n \"section_id\":gotData.section_id,\n \"owner_id\":gotData.owner_id,\n \"description\":gotData.description,\n 'message': \"Retrieved successfully\"\n }\n return make_response(jsonify(response)), 200\n else:\n return \"Error while fetching data\"\n\n# define the API resources\n\n\ndpiaudit_post_view = DPIAuditPOSTAPI.as_view('dpiaudit_post_api')\ndpiaudit_get_view = DPIAuditGETAPI.as_view('dpiaudit_get_api')\n\ndpiaudit_blueprint.add_url_rule(\n '/dpiaudit',\n view_func=dpiaudit_post_view,\n methods=['POST']\n)\n\n\ndpiaudit_blueprint.add_url_rule(\n '/dpiaudit',\n view_func=dpiaudit_get_view,\n methods=['GET']\n)\n","sub_path":"DPIA_WEBSERVICE/project/server/DPIAuditViews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"314038165","text":"from django.shortcuts import render, get_object_or_404, get_list_or_404, reverse, redirect\nfrom .models import Article, Comment, UserProfile\nfrom .forms import CommentForm\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nimport random\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\nimport markdown\n\n\n# _LABEL_COLOR = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple']\n# UniformMetaData.article_all = Article.objects.order_by('-created_at')\n\n# # make sure labels is unique in template\n# def labels():\n# labels = set()\n# for article in UniformMetaData.article_all:\n# labels.add(article.label)\n# return sample(labels,15)\n#\n#\n# def created_date():\n# created_date = set()\n# for article in UniformMetaData.article_all:\n# dt = article.created_at.strftime('%Y-%m')\n# created_date.add(dt)\n# return created_date\n\n#\nclass UniformMetaData(object):\n label_color = ['red', 'orange', 'yellow', 'green', 'teal', 'blue', 'purple']\n\n @classmethod\n def article_all(cls):\n article_all = Article.objects.order_by('-id')\n return article_all\n\n @classmethod\n def label(cls):\n labels = set()\n for article in cls.article_all():\n if article.label.strip():\n labels.add(article.label.strip())\n print(labels)\n # if len(labels) > 15:\n # return random.sample(labels, 15)\n # else:\n return labels\n\n @classmethod\n def created_date(cls):\n created_date = set()\n for article in cls.article_all():\n dt = article.created_at.strftime('%Y-%m')\n created_date.add(dt)\n return created_date\n\n\n# 本来写了好几段的重复代码,这里取相同的变量article——list就好了,不用重复写渲染的代码了\ndef article(request, article_set=None, article_date=None):\n if article_set:\n article_list = get_list_or_404(Article, label=article_set)\n # print('article_set ======================= ' , article_list)\n\n elif article_date:\n article_list = []\n for article in UniformMetaData.article_all():\n if article.created_at.strftime('%Y-%m') == article_date:\n article_list.append(article)\n # print('article_cate ======================= ' , article_list)\n else:\n article_list = UniformMetaData.article_all()\n # print('article_all ======================= ', article_list)\n # print(article_list)\n # articles已经变成page对象,不再是普通的变量\n paginator = Paginator(article_list, 5)\n page = request.GET.get('page')\n try:\n articles = paginator.page(page)\n except EmptyPage:\n articles = paginator.page(paginator.num_pages)\n except PageNotAnInteger: # 如果get到none则捕捉此错误\n articles = paginator.page(1)\n # print('article in page ==========', articles)\n for article in articles:\n article.content = markdown.markdown(article.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n return render(request, 'blog/blog.html', {'articles': articles,\n 'labels': UniformMetaData.label(),\n 'label_color': UniformMetaData.label_color,\n 'article_all': UniformMetaData.article_all(),\n 'article_filter_by_month': UniformMetaData.created_date(),\n }\n )\n\n\ndef article_detail(request, article_id, err_form=None):\n article = get_object_or_404(Article, pk=article_id)\n article.content = markdown.markdown(article.content,\n extensions=[\n 'markdown.extensions.extra',\n 'markdown.extensions.codehilite',\n 'markdown.extensions.toc',\n ])\n comment_list = article.comment_set.order_by('-created_at')\n if err_form:\n comment_form = err_form\n else:\n comment_form = CommentForm\n # if request.method == 'POST':\n # comment_form = CommentForm(request.POST) # 绑定表单\n # if comment_form.is_valid(): # 没有此行,校验依然可行,添加此行只是为了逻辑判断\n # comment_content = comment_form.cleaned_data['comment_content']\n # comment = Comment(article=article,content=comment_content)\n # comment.save()\n # return HttpResponseRedirect(reverse('blog:article', args=[article.id, ])) # 记得return\n return render(request, 'blog/article.html', {'article': article,\n 'label_color': UniformMetaData.label_color,\n 'labels': UniformMetaData.label(),\n 'article_all': UniformMetaData.article_all(),\n 'article_filter_by_month': UniformMetaData.created_date(),\n 'comment_form': comment_form,\n 'comment_list': comment_list,\n }\n )\n\n\n@login_required(login_url='blog:login')\ndef article_detail_comment(request, article_id):\n comment_form = CommentForm(request.POST) # 绑定表单\n # if not authenticate(request.user):\n # redirect(to=)\n\n if comment_form.is_valid(): # 没有此行,校验依然可行,添加此行只是为了逻辑判断\n article = Article.objects.get(pk=article_id)\n comment_content = comment_form.cleaned_data['comment_content']\n comment = Comment(article=article, content=comment_content, author=request.user)\n comment.save()\n return HttpResponseRedirect(reverse('blog:article', args=(article.id,)))\n else:\n return article_detail(request, article_id, err_form=comment_form) # view内传递数据依然可以传递表单错误信息,而直接重定向则失效\n\n\ndef blog_login(request):\n redirect_to = request.POST.get('next', request.GET.get('next', ''))\n if request.method == 'GET':\n form = AuthenticationForm\n elif request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n login(request, form.get_user())\n if redirect_to:\n return redirect(redirect_to)\n else:\n return redirect('/blog')\n context = {}\n context['form'] = form\n context['next'] = redirect_to\n return render(request, 'blog/register_login.html', context)\n\n\ndef blog_register(request):\n if request.user.is_authenticated:\n logout(request)\n context = {}\n redirect_to = request.POST.get('next', request.GET.get('next', ''))\n if request.method == 'GET':\n form = UserCreationForm\n elif request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n user = authenticate(username=form.cleaned_data['username'],\n password=form.cleaned_data['password1'],\n )\n avatar = request.FILES.get('avatar') # 注意这里是files\n userprofile = UserProfile(belong_to=user, profile_image=avatar)\n userprofile.save()\n login(request, user)\n if redirect_to:\n return redirect(redirect_to)\n else:\n return redirect('blog:article_list')\n context['form'] = form\n context['next'] = redirect_to\n return render(request, 'blog/register_login.html', context)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"21158927","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib\nimport subprocess\nimport simplejson\nimport mimetypes\nimport os\nimport shutil\n\nclass ImageSearch:\n\tdef __init__(self, folder = '/tmp/CoverGrabber'):\n\t\tself.folder = folder\n\t\tif os.path.exists(self.folder):\n\t\t\tshutil.rmtree(self.folder)\n\t\tos.mkdir(self.folder)\n\t\t\n\tdef search(self, search):\n\t\tquery = urllib.urlencode({'q' : search})\n\t\turl = 'http://ajax.googleapis.com/ajax/services/search/' + \\\n\t\t\t'images?v=1.0&%s'%(query)\n\t\tsearchResults = urllib.urlopen(url)\n\t\tjson = simplejson.loads(searchResults.read())\n\t\tresults = json['responseData']['results']\n\n\t\tfilenameRoot = os.path.join(\n\t\t\tself.folder,\n\t\t\t'-'.join(search)\n\t\t)\n\t\tf = []\n\t\tc = 1\n\t\tfor i in results:\n\t\t\tfilename = filenameRoot + '-%i.jpg'%c\n\t\t\turllib.urlretrieve(i['url'], filename)\n\t\t\tmime = subprocess.Popen(\n\t\t\t\t'file -i \"%s\"'%filename, \n\t\t\t\tshell=True,\n\t\t\t\tstdout=subprocess.PIPE\n\t\t\t\t).communicate()[0]\n\t\t\tif not 'image/jpeg;' in mime:\n\t\t\t\tos.remove(filename)\n\t\t\telse:\n\t\t\t\tc += 1\n\t\t\t\tf.append(filename)\n\t\treturn f\n","sub_path":"imagesearch.py","file_name":"imagesearch.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"566847734","text":"\ndef output_student(L):\n name_w = 15\n age_w = 10\n score_w = 10\n print()\n head1 = '+' + '-'*name_w + '+' + '-'*age_w + '+' + '-'*score_w + '+'\n print(head1)\n head_text = '|' + '姓名'.center(name_w - 2) +\\\n '|' + '年龄'.center(age_w - 2)+ '|' + '成绩'.center(score_w - 2) + '|'\n print(head_text)\n print(head1)\n for i in L:\n fmt = '|%s|%s|%s|'\n name_text = i['name'].center(name_w)\n age_text = str(i['age']).center(age_w)\n score_text = str(i['score']).center(score_w)\n print(fmt % (name_text, age_text, score_text))\n print(head1)","sub_path":"aid1807a/练习题/python练习题/python基础习题/13/homework/chengjipaixu/dayin.py","file_name":"dayin.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"189606814","text":"import numpy as np\nimport sys\n\nf = open(sys.argv[1])\ndata = np.loadtxt(f)\ntrain = data[:,1:]\ntrainlabels = data[:,0]\n\nonearray = np.ones((train.shape[0],1))\ntrain = np.append(train,onearray,axis=1)\n\nprint(train)\nprint(\"train shape=\",train.shape)\n\nf = open(sys.argv[2])\ndata = np.loadtxt(f)\ntest = data[:,1:]\ntestlabels = data[:,0]\n\nrows = train.shape[0]\ncols = train.shape[1]\n\nw = np.random.rand(cols)\n#w = np.ones(cols)\nprint(\"w=\",w)\n\nepochs = 10000\neta = .001\nprevobj = np.inf\ni=0\n\nobj = np.sum(np.square(np.matmul(train, np.transpose(w)) - trainlabels))\nprint(\"Obj=\",obj)\n\nwhile(prevobj - obj > 0 and i < epochs):\n#while(prevobj - obj > 0):\n\n\t#Update previous objective\n\tprevobj = obj\n\n\t#Calculate gradient\n\tdellf = (np.dot(train[0,:],w)-trainlabels[0])*train[0,:]\n\tfor j in range(1, rows):\n\t\tdellf += (np.dot(train[j,:],w)-trainlabels[j])*train[j,:]\n\n#\tprint(\"dellf=\",dellf)\n\t\n\t#Update w\n\tw = w - eta*dellf\n\n\t#Recalculate objective\n\tobj = np.sum(np.square(np.matmul(train, np.transpose(w)) - trainlabels))\n\t\n\ti = i + 1\n\tprint(\"Objective=\",obj)\n\t\n\npredictions = np.sign(np.matmul(train, np.transpose(w)))\nprint(predictions)\n\nprint(w)\n","sub_path":"Assignment4/least_squares_gd.py","file_name":"least_squares_gd.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"209624575","text":"from manimlib.imports import *\r\nimport math\r\nimport numpy as np\r\n\r\nclass CountDown(Scene):\r\n def construct(self):\r\n self.count_down()\r\n\r\n def count_down(self):\r\n count_down = TexMobject(\r\n \"\\\\sqrt{25}\",\r\n \"2^2\",\r\n \"\\\\lfloor\\\\pi\\\\rfloor\",\r\n \"\\\\sum_{n=0}^{\\\\infty} \\\\frac{1}{2^n}\",\r\n \"-e^{\\\\pi i}\"\r\n )\r\n for i in range(0,len(count_down)):\r\n count_down[i].to_corner(DR)\r\n self.play(Write(count_down[0]))\r\n for i in range(0,len(count_down)-1):\r\n self.play(ReplacementTransform(count_down[i],count_down[i+1]))\r\n self.wait(0.5)\r\n self.play(FadeOut(count_down[len(count_down)-1]))\r\n\r\n\r\nclass ForCoins(Scene):\r\n def construct(self):\r\n self.for_coins()\r\n\r\n def for_coins(self):\r\n text = [\r\n \"如果你觉得不错就点个三连吧\",\r\n \"你的三连是对我最好的支持\",\r\n \"我是病态小鸽\",\r\n \"我们下期再见~~~~\"\r\n ]\r\n texts = VGroup(*[TextMobject(t) for t in text])\r\n texts.arrange(DOWN, buff=1)\r\n texts.set_color_by_gradient(RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE)\r\n\r\n for i in range(0,len(text)):\r\n self.play(Write(texts[i]))\r\n self.wait(0.7)\r\n self.wait()","sub_path":"useful_code.py","file_name":"useful_code.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"580463463","text":"from tkinter import *\nimport json\nfrom itertools import product\nimport math\nimport time\n\n\nwith open(\"DBV2.json\") as f:\n DB = json.load(f)\n\nwith open(\"Int.json\") as f:\n Int = json.load(f)\n\n\ndef convtime(timec):\n timestr = time.localtime(timec)\n if len(str(timestr[3])) == 1:\n hour = +str(timestr[3])\n else:\n hour = str(timestr[3])\n\n if len(str(timestr[4])) == 1:\n minute = str(timestr[4])\n else:\n minute = str(timestr[4])\n\n if len(str(timestr[5])) == 1:\n second = \"0\"+str(timestr[5])\n else:\n second = str(timestr[5])\n \n return(hour+\":\"+minute+\":\"+second)\n\n\ndef timen():\n return time.time()\ndef et(t1,t2):\n time = t2-t1\n return(time)\n\n\ndef checker(item,source):\n if item in source:\n return(True)\n else:\n return(False)\n\ndef check2(v1 , v2 , v3 ,v4):\n if v1 in v4:\n return False\n\n elif v2 in v4:\n return False\n \n elif v1 == v3:\n return True\n\n elif v2 == v3:\n return True\n\n else:\n return False\n\ndef match(searching):\n weapons = []\n head = []\n chest = []\n legs = []\n hands = []\n for query in searching:\n typ = DB[\"12\"][query]\n for item in DB[\"10\"]:\n if DB[\"10\"][item][\"Cell0\"] == int(query):\n weapons.append(item)\n print(\"Pass\")\n\n## elif check2(DB[\"10\"][item][\"Cell1\"],DB[\"10\"][item][\"Cell2\"],typ,weapons) == True:\n## weapons.append(item)\n\n for item in DB[\"0\"]:\n if DB[\"0\"][item][\"Cell0\"] == int(query):\n head.append(item)\n \n## elif check2(DB[\"0\"][item][\"Cell1\"],DB[\"0\"][item][\"Cell2\"],typ,weapons) == True:\n## head.append(item)\n\n \n for item in DB[\"1\"]:\n if DB[\"1\"][item][\"Cell0\"] == int(query):\n chest.append(item)\n## elif check2(DB[\"1\"][item][\"Cell1\"],DB[\"1\"][item][\"Cell2\"],typ,weapons) == True:\n## chest.append(item)\n\n\n for item in DB[\"2\"]:\n if DB[\"2\"][item][\"Cell0\"] == int(query):\n legs.append(item)\n## elif check2(DB[\"2\"][item][\"Cell1\"],DB[\"2\"][item][\"Cell2\"],typ,weapons) == True:\n## legs.append(item)\n\n for item in DB[\"3\"]:\n if DB[\"3\"][item][\"Cell0\"] == int(query):\n hands.append(item)\n## elif check2(DB[\"3\"][item][\"Cell1\"],DB[\"3\"][item][\"Cell2\"],typ,weapons) == True:\n## hands.append(item)\n\n\n z = set(product(weapons,head,chest,legs,hands))\n print(\"GG\") \n tt = [] \n for combo in z:\n tt.append(combo)\n print(len(tt))\n return(tt)\n\n\ndef build(Sets):\n begin = timen()\n\n Criteria = {}\n for item in Sets:\n if item[0] != \"None\":\n if item[0] not in Criteria: \n Criteria.update({item[0] : int(item[1])})\n else:\n Criteria[item[0]] += int(item[1])\n# for item in Criteria:\n# Criteria[item] = int(math.ceil(float(Criteria[item]/3)))\n\n pack = []\n for item in Criteria:\n pack.append(item) \n##This Is Going To Form All Possible Matches Based On Perks Asked For\n con = match(pack)\n end3 = timen()\n print(et(begin,end3),\"Time Time To Make All Matches\")\n values = Criteria\n mat = []\n for item in con:\n val = perfect(extract(item),values,item)\n if val == False:\n fin = item\n# fin.append(extract(item))\n mat.append(str(fin))\n# print(item)\n print(len(mat))\n end = timen()\n\n nam = \"XX\"\n fn = nam+\".txt\"\n final = open(fn,\"w\")\n\n final.write(str(\"\\n\\n\".join(mat)))\n final.close()\n end2 = timen()\n print(\"Done\")\n print(et(begin,end),\"Time To Check All Comboes\")\n print(et(begin,end2),\"Time Including Writing To Disc\")\n\ndef perfect(setii,crit,arm):\n# print(rej)\n crit = dict(crit)\n orig = dict(crit)\n seti = setii\n cri = crit\n# print(seti,\"set perks\")\n# print(cri,\"criteria perks\")\n\n for item in seti:\n# print(item)\n if item in cri:\n cri[item] = cri[item] - seti[item]\n# print(cri)\n fail = False\n# print()\n for item in cri:\n if cri[item] != 0:\n# print(item)\n fail = True\n if fail == True:\n cri = celcheck(setii,cri)\n# print(cri)\n\n fail = False\n for item in cri:\n if cri[item] != 0:\n # print(item)\n fail = True\n## for item in rej:\n## if item in setii and item != \"None\":\n## fail = True\n## \n return(fail)\n\ndef build2(Sets):\n begin = timen()\n\n Criteria = {}\n for item in Sets:\n if item[0] != \"None\":\n if item[0] not in Criteria: \n Criteria.update({item[0] : int(item[1])})\n else:\n Criteria[item[0]] += int(item[1])\n for item in Criteria:\n Criteria[item] = int(math.ceil(float(Criteria[item]/3)))\n\n pack = []\n for item in Criteria:\n pack.append(item) \n##This Is Going To Form All Possible Matches Based On Perks Asked For\n con = match2(pack)\n\n end3 = timen()\n print(et(begin,end3),\"Time Time To Make All Matches\")\n\n values = Criteria\n mat = []\n for item in con:\n print(con.index(item))\n val = perfect(extract(item),values,item)\n if val == False:\n fin = list(item)\n fin.append(extract(item))\n mat.append(fin)\n# print(item)\n# print(len(mat))\n end = timen()\n end2 = timen()\n print(\"Done\")\n print(et(begin,end),\"Time To Check All Comboes\")\n print(et(begin,end2),\"Time Including Writing To Disc\")\n\ndef celcheck(setii,crit):\n# print(crit)\n for item in crit:\n if item !=0:\n if DB[\"12\"][item] in setii:\n if (setii[DB[\"12\"][item]] - crit[item]) >= 0:\n setii[DB[\"12\"][item]] = setii[DB[\"12\"][item]] - crit[item]\n crit[item] = 0\n return(crit)\n\n\ndef extract(Set):\n com = {\"4\" : 1}\n# Weap,Helm,Chest,Legs,Hands\n for item in Set:\n\n if DB[\"13\"][item][\"Cell0\"] not in com:\n com.update({DB[\"13\"][item][\"Cell0\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell0\"]] += 1\n\n if DB[\"13\"][item][\"Cell1\"] not in com:\n com.update({DB[\"13\"][item][\"Cell1\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell1\"]] += 1\n\n if DB[\"13\"][item][\"Cell2\"] not in com:\n com.update({DB[\"13\"][item][\"Cell2\"] : 1})\n else:\n com[DB[\"13\"][item][\"Cell2\"]] += 1\n \n\n return(com)\n\n#def rank(mat,cri)\n# for item in \n\n\n\n#print(extract(('151', '135', '28', '2', '3')))\n\n#build([[\"33\",2],[\"0\",2]])\n\nbuild([[\"5\",2],[\"38\",2],[\"24\",2],[\"22\",2],[\"40\",2],[\"42\",2]])\n\n#x = extract(['Charrogg Exotic Weapon', 'Rezakiri Head', 'Drask Chest', 'Boreus Legs', 'Boreus Hands'])\n#print(x)\n##find()\n#perfect(extract(['Charrogg Exotic Weapon', 'Rezakiri Head', 'Drask Chest', 'Boreus Legs', 'Boreus Hands']),{'Aetheric Attunement': 2},('Charrogg Exotic Weapon', 'Hellion Head', 'Charrogg Chest', 'Charrogg Legs', 'Charrogg Hands'),[])\n","sub_path":"DBV2/DBV2.py","file_name":"DBV2.py","file_ext":"py","file_size_in_byte":7158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"298492971","text":"import pyperclip\nfrom tkinter import *\nfrom customModelSettingsAts1 import *\n\n\n\ndef scanProduct():\n root = Tk()\n root.geometry(\"800x150\")\n root.title(\"ATS Bot\")\n label = Label(root, text=\"Escanee la pieza del modelo a configurar:\")\n label.config(font=('ARIAL', '30'), fg='blue')\n global product\n product = StringVar()\n textBox = Entry(root, textvariable=product, width=20)\n textBox.config(font=('Arial', 30), bd=4)\n\n def enterEvent(event):\n global workOrder\n workOrder = StringVar()\n workOrder.set(product.get())\n root.destroy()\n\n root.bind('', enterEvent)\n\n label.pack()\n textBox.pack()\n textBox.focus()\n\n root.mainloop()\n\n\ndef mes():\n showDesktop()\n findAndClick(mesIconPic, 5, 0.9, True)\n findAndClick(mesLoginBtnPic, 10, 0.9, False)\n findAndClick(mesSideMenuBtnPic,10, 0.9,False)\n findAndClick(startWorkingSideMenuPic,10, 0.9,False)\n time.sleep(0.2)\n pag.press('tab')\n pag.write(workOrder.get())\n pag.press('enter')\n findAndClick(blueOKbtnPic,4, 0.9,False)\n time.sleep(0.2)\n pag.press('enter')\n findAndClick(processScanSearchPic, 5, 0.9, False)\n findAndClick(processScanSearchTextBoxPic, 5, 0.9, False)\n time.sleep(0.2)\n\n pag.write(workOrder.get())\n findAndClick(mesSearchBtnPic, 5, 0.9, False)\n time.sleep(0.5)\n pag.press('tab', presses=5)\n time.sleep(0.2)\n pag.keyDown('ctrlleft')\n pag.press('c')\n pag.keyUp('ctrlleft')\n global model\n model = pyperclip.paste()\n model = eval(model.replace('-',''))\n time.sleep(0.2)\n showDesktop()\n\n\ndef ats():\n # Open ATS\n findAndClick(atsShortcutPic,10, 0.90, True)\n time.sleep(0.2)\n\n #findAndClick(runBtnPic, 5, 0.9, False)\n findAndClick(settingsBtnPic, 20, 0.9, False)\n if findAndBool(barcodeLabelPic, 10, 0.9):\n time.sleep(1)\n pag.press('tab', presses=2, interval=0.1)\n pag.press('enter')\n findAndClick(botTestFilesPic, 5, 0.95, True)\n findAndClick(ATS1FolderPic if AtsModel() else ATS2FolderPic, 5, 0.95, True)\n\n # FIRST TIME OPENING FILE\n while pag.locateCenterOnScreen(modelAtsFile, confidence=0.95) is None:\n print('Encontré el archivo')\n pag.scroll(-300)\n # LOAD FILE\n pag.doubleClick(pag.locateCenterOnScreen(modelAtsFile, confidence=0.95))\n print('cargué el archivo')\n time.sleep(0.3)\n while pag.locateCenterOnScreen(atsOpenBtnPic, confidence=0.95) is None:\n print('no encuentro el boton de abrir')\n pag.scroll(-300)\n time.sleep(0.5)\n pag.click(pag.locateCenterOnScreen(atsOpenBtnPic))\n print('Ya encontré el botón de abrir y le piqué')\n findAndClick(botTestFilesPic, 5, 0.95, True)\n findAndClick(ATS1FolderPic if AtsModel() else ATS2FolderPic, 5, 0.95, True)\n\n\n # SECOND TIME OPENING FILE\n while pag.locateCenterOnScreen(modelAtsFile, confidence=0.95) is None:\n pag.scroll(-300)\n pag.doubleClick(pag.locateCenterOnScreen(modelAtsFile, confidence=0.95))\n print('Ya cargué el segundo archivo')\n time.sleep(0.3)\n\n\n print('termine proceso normal ats')\n # FINISHED LOADING FILE\n # NEXT COMES CUSTOM MODEL SETTINGS\n print('antes de custom settings')\n setSettings(model.writeCurrent, model.dwSwitch)\n print('despues de custom settings')\n\n ### VALIDATE EVERYTHINGS OK\n if findAndBool(inventronicsLogoPic, 5, 0.95):\n pag.alert('¡Configuración Exitosa! Puede comenza a probar.')\n\n\n\n# killTasks()\n# scanProduct()\n# mes()\n# print(model)\n# print(model.get_data)\n# modelAtsFile = model.ssAts1 if AtsModel() else model.ssAts2\n# print(modelAtsFile)\n# print(model)\n# ats()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"botTest.py","file_name":"botTest.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"191135383","text":"import logging\nfrom argparse import Namespace\n\nfrom train import train\n\n\ndef main():\n logging.basicConfig(format='%(asctime)s | %(levelname)s | %(message)s', level=logging.INFO)\n\n args = Namespace()\n\n # args.ower_dir\n args.class_count = 100\n # args.sent_count\n\n args.activation = 'sigmoid'\n args.batch_size = 1024\n args.device = 'cuda'\n args.emb_size = None\n args.epoch_count = 200\n # args.log_dir\n args.log_steps = False\n args.lr = 0.003\n args.mode = 'mean'\n # args.model\n args.optim = 'adam'\n # args.save_dir\n args.sent_len = 64\n args.test = True\n args.tokenizer = 'spacy'\n args.update_vectors = True\n args.vectors = 'fasttext.simple.300d'\n # args.weight_factor\n\n dataset_choices = [\n ('ower-v4-cde-cde-100-1', 1),\n ('ower-v4-cde-irt-100-1', 1),\n ('ower-v4-cde-irt-100-5', 5),\n ('ower-v4-cde-irt-100-15', 15),\n ('ower-v4-cde-irt-100-30', 20),\n ('ower-v4-fb-irt-100-1', 1),\n ('ower-v4-fb-irt-100-5', 5),\n ('ower-v4-fb-irt-100-15', 15),\n ('ower-v4-fb-irt-100-30', 30),\n ('ower-v4-fb-owe-100-1', 1)\n ]\n\n for dataset, sent_count in dataset_choices:\n for model in ['base', 'ower']:\n for weight_factor in [0, 0.5, 1.0, 2.0]:\n args.ower_dir = f'data/ower/{dataset}'\n args.sent_count = sent_count\n\n args.log_dir = f'runs/weight_factor/{dataset}_{model}_{weight_factor}'\n args.model = model\n args.save_dir = f'models/weight_factor/{dataset}_{model}_{weight_factor}'\n args.weight_factor = weight_factor\n\n logging.info(f'Training on dataset {dataset} using model {model} with weight factor {weight_factor}')\n train(args)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/grid_search_weight_factor.py","file_name":"grid_search_weight_factor.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"89175410","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\n# 텐서플로우를 활용한 머신러닝 예제\n\n# 학습데이터 정의 (회귀분석용 데이터)\nX_train = [10, 20, 30, 40, 50]\ny_train = [5, 7, 15, 20, 25]\n\n# 1. 데이터를 전달받기 위한 실행매개변수 선언\nX = tf.placeholder(tf.float32, shape=[None])\ny = tf.placeholder(tf.float32, shape=[None])\n\n# 2. 머신러닝을 위한 가설 정의\n# - 선형회기 분석을 위한 선형방정식\n# - X * W + b\n\n# 기울기(가중치) 변수 선언\nw = tf.Variable(0, dtype=tf.float32)\n\n# 절편(편향) 변수 선언\nb = tf.Variable(0, dtype=tf.float32)\n\n# 가설(문제를 해결하기 위한 식)\nh = X * w + b\n\n# 머신러닝 모델의 학습을 진행하기 위한\n# 오차 값의 계산(평균제곱오차)\nloss_1 = y - h\nloss_2 = tf.square(loss_1)\nloss = tf.reduce_mean(loss_2)\n\n# 오차 값을 감소시키는 방향으로\n# 학습을 진행할 수 있는 객체의 선언\n# (학습률(learning_rate)을 지정하여 학습의 속도를 제어)\noptimizer = tf.train.GradientDescentOptimizer(\n learning_rate=0.0001)\ntrain = optimizer.minimize(loss)\n\nwith tf.Session() as sess :\n sess.run(tf.global_variables_initializer())\n \n feed_dict = {X : X_train, y : y_train}\n for step in range(1, 1001): \n sess.run(train, feed_dict=feed_dict)\n \n if step % 10 == 0 :\n pred_loss = sess.run(loss, feed_dict=feed_dict)\n w_val, b_val = sess.run([w, b], feed_dict=feed_dict)\n print(\"(step-{0}) 오차 : {1}, w : {2}, b : {3}\".format(\n step, pred_loss, w_val, b_val))\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"최종 오차 : {}\".format(pred_loss))\n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n from matplotlib import pyplot as plt\n \n plt.plot(X_train, y_train, 'or')\n plt.plot(X_train, pred, '--b')\n \n X_test = [37, 22]\n pred_test = sess.run(h, feed_dict={X : X_test})\n plt.plot(X_test, pred_test, 'xg')\n \n plt.show()\n \n \"\"\"\n feed_dict = {X : X_train, y : y_train}\n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n pred_loss = sess.run(loss_1, feed_dict=feed_dict)\n print(\"오차 값 1 : \", pred_loss)\n \n pred_loss = sess.run(loss_2, feed_dict=feed_dict)\n print(\"오차 값 2 : \", pred_loss)\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"오차 값 : \", pred_loss)\n \n # 학습을 진행시키는 코드\n # (오차를 줄여나가는 방향으로 가중치(기울기)와 \n # 졀편의 값을 보정시킴)\n sess.run(train, feed_dict=feed_dict)\n \n pred = sess.run(h, feed_dict=feed_dict)\n print(\"예측 결과 : \", pred)\n \n pred_loss = sess.run(loss_1, feed_dict=feed_dict)\n print(\"오차 값 1 : \", pred_loss)\n \n pred_loss = sess.run(loss_2, feed_dict=feed_dict)\n print(\"오차 값 2 : \", pred_loss)\n \n pred_loss = sess.run(loss, feed_dict=feed_dict)\n print(\"오차 값 : \", pred_loss)\n \"\"\"\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Lecture_note_ML/3_tensorflow/1_basic/2_function_matrix/tf_11_example.py","file_name":"tf_11_example.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"226654222","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@created on 2019/4/21\n@author Yao Li\n\"\"\"\n\n\ndef bf(ts, ps):\n \"\"\"\n 暴力破解\n :param ts: 主串\n :param ps: 模式串\n :return: 如果找到返回主串中第一个模式字符出现索引,否则返回-1\n \"\"\"\n t_list = list(ts) # 主串索引\n p_list = list(ps) # 模式串索引\n i = j = 0\n while i < len(t_list) and j < len(p_list):\n if t_list[i] == p_list[j]: # 对应字符相同,就比较下一个\n i += 1\n j += 1\n else: # 一旦不匹配,则i本轮后移一位;j清0\n i = i - j + 1\n j = 0\n if j == len(p_list):\n return i - j\n else:\n return -1\n\n\nif __name__ == '__main__':\n import time\n t1 = time.time()\n ts = 'abcdbc' * 100000 + 'ABCDBCAABEFG'\n ps = 'ABEFG'\n index = bf(ts, ps)\n t2 = time.time()\n print('index=%s, time=%s' % (str(index), str(t2 - t1)))\n\n","sub_path":"KMP/violent_version.py","file_name":"violent_version.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"565309493","text":"# Copyright (c) 2016 b<>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 __future__ import absolute_import\nfrom watcher_dashboard import api\nfrom watcher_dashboard.test import helpers as test\n\n\nclass WatcherAPITests(test.APITestCase):\n\n def test_goal_list(self):\n goals = {'goals': self.api_goals.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.goal = self.mox.CreateMockAnything()\n watcherclient.goal.list(detail=True).AndReturn(goals)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Goal.list(self.request)\n self.assertIsInstance(ret_val, dict)\n self.assertIn('goals', ret_val)\n for n in ret_val['goals']:\n self.assertIsInstance(n, dict)\n\n def test_goal_get(self):\n goal = self.api_goals.first()\n goal_id = self.api_goals.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.goal = self.mox.CreateMockAnything()\n watcherclient.goal.get(goal_id).AndReturn(goal)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Goal.get(self.request, goal_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_strategy_list(self):\n strategies = {'strategies': self.api_strategies.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.strategy = self.mox.CreateMockAnything()\n watcherclient.strategy.list(detail=True).AndReturn(strategies)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Strategy.list(self.request)\n self.assertIn('strategies', ret_val)\n for n in ret_val['strategies']:\n self.assertIsInstance(n, dict)\n\n def test_strategy_get(self):\n strategy = self.api_strategies.first()\n strategy_id = self.api_strategies.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.strategy = self.mox.CreateMockAnything()\n watcherclient.strategy.get(strategy_id).AndReturn(strategy)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Strategy.get(self.request, strategy_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_list(self):\n audit_templates = {\n 'audit_templates': self.api_audit_templates.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.list(\n detail=True).AndReturn(audit_templates)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.list(self.request)\n\n self.assertIn('audit_templates', ret_val)\n for n in ret_val['audit_templates']:\n self.assertIsInstance(n, dict)\n\n def test_audit_template_list_with_filters(self):\n search_opts = {'name': 'Audit Template 1'}\n audit_templates = {\n 'audit_templates': self.api_audit_templates.filter(**search_opts)}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit_template = self.mox.CreateMockAnything()\n\n watcherclient.audit_template.list(\n detail=True, **search_opts).AndReturn(audit_templates)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.list(\n self.request, **search_opts)\n\n self.assertIn('audit_templates', ret_val)\n for n in ret_val['audit_templates']:\n self.assertIsInstance(n, dict)\n\n self.assertEqual(ret_val, audit_templates)\n\n def test_audit_template_get(self):\n audit_template = self.api_audit_templates.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.get(\n audit_template_id=audit_template_id).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.get(self.request,\n audit_template_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_create(self):\n audit_template = self.api_audit_templates.first()\n name = audit_template['name']\n goal = audit_template['goal_uuid']\n strategy = audit_template['strategy_uuid']\n description = audit_template['description']\n scope = audit_template['scope']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.create(\n name=name,\n goal=goal,\n strategy=strategy,\n description=description,\n scope=scope).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.create(\n self.request, name, goal, strategy,\n description, scope)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_patch(self):\n audit_template = self.api_audit_templates.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n form_data = {'name': 'new Audit Template 1'}\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.patch(\n audit_template_id,\n [{'name': 'name', 'value': 'new Audit Template 1'}]\n ).AndReturn(audit_template)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.AuditTemplate.patch(\n self.request, audit_template_id,\n form_data)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_template_delete(self):\n audit_template_list = self.api_audit_templates.list()\n audit_template_id = self.api_audit_templates.first()['uuid']\n deleted_at_list = self.api_audit_templates.delete()\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit_template = self.mox.CreateMockAnything()\n watcherclient.audit_template.delete(\n audit_template_id=audit_template_id)\n self.mox.ReplayAll()\n api.watcher.AuditTemplate.delete(self.request,\n audit_template_id)\n self.assertEqual(audit_template_list, deleted_at_list)\n self.assertEqual(len(audit_template_list), len(deleted_at_list))\n\n def test_audit_list(self):\n audits = {'audits': self.api_audits.list()}\n\n watcherclient = self.stub_watcherclient()\n\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.list(detail=True).AndReturn(audits)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.list(self.request)\n\n self.assertIn('audits', ret_val)\n for n in ret_val['audits']:\n self.assertIsInstance(n, dict)\n\n def test_audit_get(self):\n audit = self.api_audits.first()\n audit_id = self.api_audits.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.get(audit_id=audit_id).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.get(self.request, audit_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create(self):\n audit = self.api_audits.first()\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type, auto_trigger=False).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create_with_interval(self):\n audit = self.api_audits.list()[1]\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n interval = audit['interval']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type,\n auto_trigger=False,\n interval=interval).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type, False, interval)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_create_with_auto_trigger(self):\n audit = self.api_audits.list()[1]\n audit_template_id = self.api_audit_templates.first()['uuid']\n\n audit_type = self.api_audits.first()['audit_type']\n audit_template_uuid = audit_template_id\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.create(\n audit_template_uuid=audit_template_uuid,\n audit_type=audit_type,\n auto_trigger=True).AndReturn(audit)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Audit.create(\n self.request, audit_template_uuid, audit_type, True)\n self.assertIsInstance(ret_val, dict)\n\n def test_audit_delete(self):\n audit_id = self.api_audits.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.audit = self.mox.CreateMockAnything()\n watcherclient.audit.delete(\n audit_id=audit_id)\n self.mox.ReplayAll()\n\n api.watcher.Audit.delete(self.request, audit_id)\n\n def test_action_plan_list(self):\n action_plans = {'action_plans': self.api_action_plans.list()}\n\n watcherclient = self.stub_watcherclient()\n\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.list(detail=True).AndReturn(action_plans)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.ActionPlan.list(self.request)\n\n self.assertIn('action_plans', ret_val)\n for n in ret_val['action_plans']:\n self.assertIsInstance(n, dict)\n\n def test_action_plan_get(self):\n action_plan = self.api_action_plans.first()\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.get(\n action_plan_id=action_plan_id).AndReturn(action_plan)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.ActionPlan.get(self.request, action_plan_id)\n self.assertIsInstance(ret_val, dict)\n\n def test_action_plan_start(self):\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.start(action_plan_id)\n self.mox.ReplayAll()\n\n api.watcher.ActionPlan.start(self.request, action_plan_id)\n\n def test_action_plan_delete(self):\n action_plan_id = self.api_action_plans.first()['uuid']\n\n watcherclient = self.stub_watcherclient()\n watcherclient.action_plan = self.mox.CreateMockAnything()\n watcherclient.action_plan.delete(\n action_plan_id=action_plan_id)\n self.mox.ReplayAll()\n\n api.watcher.ActionPlan.delete(self.request, action_plan_id)\n\n def test_action_list(self):\n actions = {'actions': self.api_actions.list()}\n watcherclient = self.stub_watcherclient()\n\n watcherclient.action = self.mox.CreateMockAnything()\n watcherclient.action.list(detail=True).AndReturn(actions)\n self.mox.ReplayAll()\n\n ret_val = api.watcher.Action.list(self.request)\n\n self.assertIn('actions', ret_val)\n for n in ret_val['actions']:\n self.assertIsInstance(n, dict)\n","sub_path":"watcher_dashboard/test/api_tests/watcher_tests.py","file_name":"watcher_tests.py","file_ext":"py","file_size_in_byte":12677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"478167320","text":"import urllib\nimport json\nimport re\nfrom urllib import FancyURLopener\n\n\nclass MyOpener(FancyURLopener):\n\tversion = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.77.4 (KHTML, like Gecko) Version/7.0.5 Safari/537.77.4'\n\ndef geturl(v):\n\tmyopener = MyOpener()\n\tpage = myopener.open(v)\n\ttxt = page.read()\n\tvideodata = re.findall(r'data-config-url=\"([^\"]*)\"', txt)[0].replace(\"&\", \"&\")\n\tfp=urllib.urlopen(videodata)\n\tj = json.load(fp)\n\n\treturn j[\"request\"][\"files\"][j[\"request\"][\"files\"][\"codecs\"][0]][\"sd\"][\"url\"]\n\n\n\ndef search(pattern):\n\tmyopener = MyOpener()\n\tpage = myopener.open(\"http://vimeo.com/search/sort:relevant/format:detail?\"+urllib.urlencode({\"q\": pattern}))\n\thtml = page.read()\n\t\n\tclipIDs = re.findall(r\"clip_([0-9]+)\", html,re.M)\n\t\n\toptions = []\n\tfor clipID in clipIDs:\n\t\tfp=urllib.urlopen(\"http://vimeo.com/api/v2/video/\"+clipID+\".json\")\n\t\tresults = json.load(fp)\n\t\toptions.append({\n\t\t\t\"title\": results[0][\"title\"],\n\t\t\t\"description\": results[0][\"description\"],\n\t\t\t\"author\": results[0][\"user_name\"],\n\t\t\t\"url\": results[0][\"url\"],\n\t\t\t\"platform\": \"vimeo\",\n\t\t\t\"SERVICE_MOD\": __name__\n\t\t})\n\n\treturn options\n\t#fp=urllib.urlopen(\"http://vimeo.com/search/sort:relevant/format:detail?\"+urllib.urlencode({\"q\": pattern}))\n\t#pattern=re.compile(r\"]*>(.*?)\", re.S|re.DOTALL)\t\n\n#print search(\"all of me john legend\")\n","sub_path":"services/vimeo.py","file_name":"vimeo.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"617638119","text":"from scipy import *\nfrom pylab import *\nfrom numpy import *\nfrom matplotlib.animation import *\nimport time\n\n\n\"\"\"\nTakes two functions containing variables x, y and computes Newton's method.\n\"\"\"\n\n\nclass fractal2D:\n def __init__(self, f1, f2, f1dx, f1dy, f2dx, f2dy, tol=1.e-8, z=[]):\n self.f1 = f1\n self.f2 = f2\n self.f1dx = f1dx\n self.f1dy = f1dy\n self.f2dx = f2dx\n self.f2dy = f2dy\n self.tol = tol\n self.z = z\n\n # prints the two functions in the form of a Matrix\n def __repr__(self):\n return 'matrix([[{}], [{}]])'.format(self.f1, self.f2)\n def numdif(self, initial, h):\n v = array(initial)\n x, y = v[0], v[1]\n Jh = array([[self.f1(x+h,y), self.f1(x,y+h)],\n [self.f2(x+h,y), self.f2(x,y+h)]])\n J = array([[self.f1(x,y), self.f1(x,y)],\n [self.f2(x,y), self.f2(x,y)]])\n dif = (Jh-J)/h\n return dif\n # implements Newton's method\n def newton(self, initial,simplified, exact, h):\n if simplified == False:\n \"\"\"\n initial should be in the form [x0, y0]\n \"\"\"\n iterations=0\n v = array(initial)\n for i in range(200):\n iterations=iterations+1\n # used for comparison\n vold = v\n x, y = v[0], v[1]\n # computes Jacobian matrix at a given point\n if exact:\n J = array([[self.f1dx(x,y), self.f1dy(x,y)],\n [self.f2dx(x,y), self.f2dy(x,y)]])\n else:\n J = self.numdif(v,h)\n invert = inv(J)\n # computes function matrix at a given point\n F = array([self.f1(x,y), self.f2(x,y)])\n # implements Newton's method\n v = v - invert.dot(F)\n # tolerance check\n if abs(v[0]-vold[0]) < self.tol:\n if abs(v[1]-vold[1]) < self.tol:\n conv = ([v[0], v[1]], i)\n break\n else:\n conv = ((5,5),iterations)\n return conv\n else:\n \"\"\"\n initial should be in the form [x0, y0]\n \"\"\"\n iterations=0\n v = array(initial)\n x, y = v[0], v[1]\n # computes Jacobian matrix at a given point\n if exact:\n J = array([[self.f1dx(x,y), self.f1dy(x,y)],\n [self.f2dx(x,y), self.f2dy(x,y)]])\n else:\n J = self.numdif(v,h)\n invert = inv(J)\n for i in range(200):\n iterations=iterations+1\n # used for comparison\n vold = v\n x, y = v[0], v[1]\n # computes function matrix at a given point\n F = array([self.f1(x,y), self.f2(x,y)])\n # implements Newton's method\n v = v - invert.dot(F)\n # tolerance check\n if abs(v[0]-vold[0]) < self.tol:\n if abs(v[1]-vold[1]) < self.tol:\n conv = ([v[0], v[1]], i)\n break\n else:\n conv = ((5,5),iterations)\n return conv\n \n def zeroes(self, initial, simplified, exact, h):\n \n \"\"\"\n Takes two values. An initial guess in the shape [x0,y0] and a boolean.\n The boolean determines wheter the simplified method should be used or not.\n If the zero value already is in the list it returns the index where it is.\n Otherwise it appends the zero to the list and returns the index where \n the zero is placed. If the list is empty it appends the zero and returns \n index 0. If the newton method doesn't detect convergence it returns the \n index 10.\n \"\"\"\n \n u=self.newton(initial, simplified, exact, h)[:-1]\n u1=u[0][0]\n u2=u[0][1]\n if u1==5 and u2==5:\n return 5\n if not self.z:\n self.z.append(u)\n return 0\n else:\n for n in range(len(self.z)):\n if abs(self.z[n][0][0]-u1) > self.tol and abs(self.z[n][0][1]-u2) > self.tol:\n self.z.append(u)\n return n+1\n else:\n if abs(self.z[n][0][0]-u1) < self.tol and abs(self.z[n][0][1]-u2) < self.tol:\n return n\n \n \n def plot1(self, N, a, b, c, d, simplified, exact, h):\n \n \"\"\"\n Takes two intervals, a step size and a boolean value. The intervals\n determine the initival values of the newton method and the step size how \n many points the grid will be. The grid contains N*N points. The boolean\n if true makes so that the plot method uses the simplified newtonmethod \n and false the regular newtonmethod. It plots the index of where the zero \n is found in red, green, blue and black.\n \"\"\"\n \n X, Y = meshgrid(linspace(a,b, num=N), linspace(c, d, num=N), indexing='ij')\n A=[]\n for i in range(N):\n for j in range(N):\n p=array([X[i,j],Y[i,j]])\n A.append(self.zeroes(p, simplified, exact, h))\n A=reshape(array(A), (N,N))\n\n \n \n colors=matplotlib.colors.ListedColormap(['red', 'green', 'blue','black'])\n bounds=[0,1,2,3,10]\n norm=matplotlib.colors.BoundaryNorm(bounds,colors.N)\n axis([X.min(),X.max(),Y.min(),Y.max()])\n return pcolormesh(X,Y,A, cmap=colors,norm=norm), colorbar(), savefig('Fractal.png')\n \n def IterPlot(self, N, a,b,c,d,simplified, exact, h):\n xmin= a; xmax= b; dx = (xmax-xmin)/N\n ymin= c; ymax= d; dy= (ymax-ymin)/N\n x,y = meshgrid(linspace(xmin,xmax,N),linspace(ymin,ymax,N))\n I=empty((N,N))\n for r in range(N):\n for k in range(N):\n I[r,k]=self.newton((xmin+k*dx+0.0001,ymin+r*dy+0.0001), simplified, exact, h)[1]\n axis([x.min(),x.max(),y.min(),y.max()])\n return pcolormesh(x,y,I,cmap='rainbow'),colorbar(cmap='rainbow')\n \n def animation(self, N, a,b,c,d, simplified, exact, h):\n \n X, Y = meshgrid(linspace(a,b+1, num=N), linspace(c, d+1, num=N), indexing='ij')\n A=[]\n for i in range(N):\n for j in range(N):\n p=array([X[i,j],Y[i,j]])\n A.append(5*self.zeroes(p, simplified, exact, h))\n A=reshape(array(A), (N,N))\n \n xmin= a; xmax= b; dx = (xmax-xmin)/N\n ymin= c; ymax= d; dy= (ymax-ymin)/N\n x,y = meshgrid(arange(xmin,xmax,dx)-dx/2.,arange(ymin,ymax,dy)-dy/2.)\n I=empty((N,N))\n for r in range(N):\n for k in range(N):\n p=array([x[r,k],y[r,k]])\n I[r,k]=self.newton((xmin+k*dx+0.0001,ymin+r*dy+0.0001), simplified, exact, h)[1]\n B=I\n \n self.fig = figure()\n self.ax = self.fig.add_subplot(1,1,1)\n \n def update(i): #funktion som upprepas varje gång processorn \"tickar\", med ökande i\n C = (A*(1+sin(i*pi/16)) + B*(1-sin(i*pi/16)))/2\n pcolor(C)\n time.sleep(0.25)\n \n self.anim = FuncAnimation(self.fig, update)\n \n \n \n#F = fractal2D(lambda x,y: x**3-3*x*y**2-1, lambda x,y: 3*x**2*y-y**3,\n# lambda x,y: 3*x**2 - 3*y**2, lambda x,y: -6*x*y,\n# lambda x,y: 6*x*y, lambda x,y: 3*x**2 - 3*y**2, 1.e-8, z=[])\n#F.animation(40,-10,10,-10,10, False)","sub_path":"newton - Copy.py","file_name":"newton - Copy.py","file_ext":"py","file_size_in_byte":7635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"1318378","text":"\nfrom enthought.traits.api import \\\n Array, Bool, Enum, Float, HasTraits, \\\n HasStrictTraits, \\\n Instance, Int, Trait, Str, Enum, \\\n Callable, List, TraitDict, Any, Range, \\\n Delegate, Event, on_trait_change, Button, \\\n Interface, Property, cached_property, WeakRef, Dict\n\nfrom enthought.traits.ui.api import \\\n Item, View, HGroup, ListEditor, VGroup, \\\n HSplit, Group, Handler, VSplit\n\nfrom enthought.traits.ui.menu import \\\n NoButtons, OKButton, CancelButton, \\\n Action\n\nfrom numpy import zeros, float_\n\nfrom ibvpy.api import\\\n ISDomain, SDomain, SContext, RTraceMngr, ITStepperEval, TStepperEval, TStepper\n#from sdomain import SDomain\n#from scontext import SContext\n\nfrom mgrid_domain import MeshManager\nfrom dots_eval_enr import DOTSManager\n\nfrom ibvpy.core.bc_mngr import BCondMngr\n#from rtrace_mngr import RTraceMngr\nfrom ibvpy.core.ibv_resource import IBVResource\n#from tstepper_eval import ITStepperEval, TStepperEval\n\nclass TStepper_enr(TStepper):\n \"\"\"\n The TStepper is a spatially bounded TStepperEval.\n\n @TODO update this for the new class names\n \n The binding is done by associating the time-stepper with a spatial\n object. In fact, any TStepper, not only the top-level one must\n be associated with spatial object. For the chained\n sub-time-steppers, this association is done using a parameter sctx\n (see the specification above). This parameters stands for spatial\n context. Note, the distinction between the spatial object and\n spatial context. While the spatial object represents a single\n spatial entity (one of domain, element, layer or material point)\n the spatial context represents a complex reference within the\n spatial object In particular, spatial context of a particular\n material point is represented as tuple containing tuple of\n references to [domain, element, layer, integration cell, material\n point].\n \"\"\"\n\n # service specifiers - used to link the service to this object\n service_class = 'ibvpy.plugins.tstepper_service.TStepperService'\n service_attrib = 'tstepper'\n\n # Sub-time-stepper or integrator.\n #\n tse = Instance( DOTSManager )\n\n # Spatial domain to bind the time-stepper to.\n #\n sdomain = Instance( MeshManager )\n# def _sdomain_default( self ):\n# return SDomain()\n\n state_array = Array\n\n sctx = Instance( SContext )\n \n # Boundary condition manager\n #\n bcond_mngr = Instance( BCondMngr )\n def _bcond_mngr_default( self ):\n return BCondMngr()\n\n # Convenience constructor \n #\n # This property provides the possibility to write\n # tstepper.bcond_list = [BCDof(var='u',dof=5,value=0, ... ]\n # The result gets propageted to the BCondMngr\n #\n bcond_list = Property( List )\n def _set_bcond_list( self, bcond_list ):\n self.bcond_mngr.bcond_list = bcond_list\n\n # Response variable manager\n #\n rtrace_mngr = Instance( RTraceMngr )\n def _rtrace_mngr_default( self ):\n return RTraceMngr( tstepper = self )\n\n # Convenience constructor \n #\n # This property provides the possibility to write\n # tstepper.bcond_list = [RVDof(var='u',dof=5,value=0, ... ]\n # The result gets propageted to the RTraceMngr\n #\n rtrace_list = Property( List )\n def _set_rtrace_list( self, rtrace_list ):\n self.rtrace_mngr.rtrace_list = rtrace_list\n\n # Backward reference to the time-loop in order to accommadate the\n # response-trace-evaluators from the top level. These include\n # bookkeeping data like memory usage or solving time per selected\n # type of operation.\n #\n tloop = WeakRef\n\n rte_dict = Property( Dict, depends_on = 'tse:rte_dict')\n def _get_rte_dict( self ):\n '''\n Gather all the currently applicable evaluators from the sub-ts\n and from the time-loop.\n\n Note the control data (time-loop data) is available within the\n model to construct flexible views (tracers) on the model.\n '''\n _rte_dict = {}\n _rte_dict.update( self.tse.rte_dict )\n if self.tloop:\n _rte_dict.update( self.tloop.rte_dict )\n return _rte_dict\n\n new_cntl_var = Delegate( 'tse' )\n\n new_resp_var = Delegate( 'tse' )\n\n # Vector of external forces\n #\n F_ext = Array\n\n # missing - setup of the time-stepper itself. reacting to changes\n # in the sub time-steppers. bcond_list and rtrace_list must be reset once\n # a change has been performed either in a spatial domain or in\n # tse.\n #\n def setup( self ):\n\n # Put the spatial domain into the spatial context\n #\n self.sctx = sctx = self.sdomain.new_scontext()\n\n # Let the boundary conditions setup themselves within the\n # spatial context\n #\n # TODO - the setup needs the link to the algorithm and to the\n # time-steppers as well.!\n #\n self.bcond_mngr.setup( sctx )\n\n # Let the response variables setup themselves within the\n # spatial context\n #\n self.rtrace_mngr.setup( sctx )\n\n # Get the size of the state state and set it up\n #\n sarr_size = self.tse.get_state_array_size( )\n self.state_array = zeros( sarr_size, float_ )\n sctx.state_array = self.state_array\n\n # Let the time-step-evaluators setup themselves within spatial context\n #\n # This steps includes initialization of state arrays and\n # eventual DOF mappings.\n #\n self.tse.setup( sctx )\n\n # Return the response variable to be used when assembling the\n # boundary conditions. Should the bcond_mngr take care of this? \n # That's the source object, isn't it? BCondMngr is the bounded\n # version of the conditions, it could supply the matrix\n # autonomously.\n #\n self.F_ext = self.new_resp_var()\n \n # Prepare the global update flag\n sctx.update_state_on = False\n\n def eval( self, step_flag, U_k, d_U, t_n, t_n1 ):\n\n # Put the spatial domain into the spatial context\n #\n sctx = self.sctx\n\n # Let the time sub-stepper evaluate its contribution.\n #\n F_int, K = self.tse.get_corr_pred( sctx, U_k, d_U, t_n, t_n1 )\n \n #Switch off the global update flag\n sctx.update_state_on = False\n\n self.F_ext[:] = 0.\n\n # Apply the boundary conditions\n #\n self.bcond_mngr.apply( step_flag, K, F_int, self.F_ext, t_n, t_n1 )\n\n return K, F_int, self.F_ext\n \n def update_state(self, U):\n '''\n spatial context represents a stack with the top object\n representing the current level.\n @param U: \n '''\n #sctx = ( self.sdomain, )\n self.sctx.update_state_on = True\n #self.tse.update_state( sctx, U )\n\n def register_mv_pipelines(self,e):\n '''Register the visualization pipelines in mayavi engine\n '''\n self.tse.register_mv_pipelines(e)\n scene = e.new_scene()\n scene.name = 'Spatial domain'\n self.sdomain.register_mv_pipelines(e)\n self.rtrace_mngr.register_mv_pipelines(e)\n\n traits_view = View( Group( Item('sdomain', style = 'custom', show_label = False),\n label = 'Discretization'),\n Group( Item( 'tse', style = 'custom', show_label = False),\n label = 'Integrator'),\n Group( Item('bcond_mngr', style = 'custom', show_label = False),\n label = 'Boundary conditions'),\n resizable = True,\n height = 0.8,\n width = 0.8,\n buttons = [OKButton,CancelButton],\n kind = 'subpanel',\n )\n","sub_path":"scratch/KRAMS/src/apps/scratch/jakub/multiscale/tstepper_enr.py","file_name":"tstepper_enr.py","file_ext":"py","file_size_in_byte":7848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"523404823","text":"\"\"\"\nA basic emulator of a pySerial connection.\nBased off of code from D. Thiebaut (http://cs.smith.edu/dftwiki/index.php/PySerial_Simulator)\n\"\"\"\n\n\nclass FakeSerial:\n \"\"\"\n Emulate a serial port connection.\n \"\"\"\n def __init__(self, port='/dev/USB0', baudrate=19200, timeout=1,\n bytesize=8, parity='N', stopbits=1, xonxoff=0,\n rtscts=0):\n self.port = port\n self.timeout = timeout\n self.parity = parity\n self.baudrate = baudrate\n self.bytesize = bytesize\n self.stopbits = stopbits\n self.xonxoff = xonxoff\n self.rtscts = rtscts\n self._isOpen = True\n self._buffer = \"\"\n\n def isOpen(self):\n \"\"\"\n Get the status of the serial connection\n\n Return (boolean): True if open, False if closed.\n \"\"\"\n return self._isOpen\n\n def open(self):\n \"\"\"\n Open the serial port.\n \"\"\"\n self._isOpen = True\n\n def close(self):\n \"\"\"\n Close the serial port.\n \"\"\"\n self._isOpen = False\n\n def write(self, string):\n \"\"\"\n Write characters to the buffer.\n \"\"\"\n self._buffer += string\n\n def read(self, n=1):\n \"\"\"\n Read characters from the buffer.\n\n Remove the first n characters from the buffer.\n\n Arguments:\n n (integer): number of characters to read\n\n Returns (string): First n characters in the buffer.\n \"\"\"\n s = self._buffer[0:n]\n self._buffer = self._buffer[n:]\n return s\n\n def readline(self):\n \"\"\"\n Read characters from the buffer until a \\n is found.\n\n Returns (string): First n characters in the buffer preceding a \\n\n \"\"\"\n returnIndex = self._buffer.index(r\"\\n\")\n if returnIndex != -1:\n s = self._buffer[0:returnIndex+1]\n self._buffer = self._buffer[returnIndex+1:]\n return s\n else:\n return \"\"\n\n def __str__(self):\n \"\"\"\n Generate a string representation of the serial object\n \"\"\"\n return \"Serial(port='%s', baudrate=%d,\" \\\n % (str(self._isOpen), self.port, self.baudrate) \\\n + \" bytesize=%d, parity='%s', stopbits=%d, xonxoff=%d, rtscts=%d)\"\\\n % (self.bytesize, self.parity, self.stopbits, self.xonxoff,\n self.rtscts)\n","sub_path":"server/fakeserial.py","file_name":"fakeserial.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"237345348","text":"def setup():\n size(500, 500)\n smooth()\n background(150)\n strokeWeight(1)\n \n\nflug = 1\n\ndef draw():\n global flug\n fill(flug, random(0, 30))\n sizeY2 = random(-10, 10)*20\n sizeX2 = random(-10, 10)*20\n ellipse(mouseX, mouseY, sizeX2, sizeY2)\n\ndef keyPressed():\n global flug\n \n if(key=='w'):\n flug = 255\n \n if(key=='b'):\n flug = 0\n \n if (key == 'a'):\n saveFrame(\"myProcessing.pngwwbbbbbbb\")\n \n","sub_path":"Processing Py_!/task_6_4/task_6_4.pyde","file_name":"task_6_4.pyde","file_ext":"pyde","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"407802378","text":"import torch\nimport gym\nfrom gym_starcraft.simple_battle_env import SimpleBattleEnv,Unit_State\n\n\nfrom copy import deepcopy\nfrom itertools import count\n\nfrom Model_hierarchical import *\nfrom config import *\n\n\nconfig = DefaultConfig()\nnp.random.seed(config.RANDOM_SEED)\ntorch.manual_seed(config.RANDOM_SEED)\nif config.GPU >= 0 :\n torch.cuda.manual_seed(config.RANDOM_SEED)\n\n\n# for debug\n\n# from hyperboard import Agent\n# HBagent = Agent(username='jlb',password='123',address='127.0.0.1',port=5002)\n#\n# hp = deepcopy(config.todict())\n# hp['mode'] = 'train_reward'\n# train_r = HBagent.register(hp, 'reward',overwrite=True)\n# hp['mode'] = 'test_reward'\n# test_r = HBagent.register(hp, 'reward',overwrite=True)\n\nenv = SimpleBattleEnv(config.ip,config.port,config.MYSELF_NUM,config.ENEMY_NUM,config.ACTION_DIM,config.DISTANCE_FACTOR,config.POSITION_RANGE,\n config.SCREEN_BOX,config.DIE_REWARD,config.HEALTH_REWARD_WEIGHT,config.DONE_REWARD_WEIGHT,config.MY_HEALTH_WEIGHT,config.ENEMY_HEALTH_WEIGHT,\n config.FOCUS_WEIGHT,config.FRAME_SKIP,config.MAX_STEP,)\n\nenv.seed(config.RANDOM_SEED)\n\n\nddpg_agent = DDPG(env,config=config)\n\nfor episode in count(1):\n print('\\n',episode,ddpg_agent.epsilon)\n obs = env.reset()\n state = ddpg_agent.extract_state(obs)\n cl_total,al_total,qe_total,qt_total = 0,0,0,0\n rs = []\n for step in range(config.MAX_STEP):\n action,command = ddpg_agent.select_action(state,decay_e=True)\n next_obs,reward,done,info = env.step(action)\n\n rs.append(np.asarray(reward))\n next_state = ddpg_agent.extract_state(next_obs)\n ddpg_agent.append_memory(state,command,action,next_state,reward,not done)\n\n ddpg_agent.train_unit()\n ddpg_agent.train_commander()\n # print(reward)\n\n if done:\n qs = []\n q = np.zeros((config.MYSELF_NUM))\n total_reward = 0\n for r in rs[::-1]:\n q = r + config.GAMMA*q\n total_reward += r.sum()/config.MYSELF_NUM\n qs.append(q)\n qs = np.asarray(qs)\n q_mean = np.mean(qs)\n ddpg_agent.train_record[episode] = total_reward\n print('memory: {}/{}'.format(ddpg_agent.commander_memory.current_index,ddpg_agent.commander_memory.max_len))\n print('q_mean: ',q_mean)\n print('train_reward',total_reward)\n # HBagent.append(train_r,episode,total_reward)\n\n break\n\n state = next_state\n\n\n if episode % config.SAVE_ITERVAL == 0:\n print('\\nsave model\\n')\n ddpg_agent.save(episode)\n\n if episode % config.TEST_ITERVAL == 0:\n test_reward,_,_ = ddpg_agent.test(episode,2)\n # HBagent.append(test_r, episode, test_reward)\n\n\n\n\n\n\n\n\n","sub_path":"sc1_train_hierarchical.py","file_name":"sc1_train_hierarchical.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"570915660","text":"from worker import Worker\nimport threading\nfrom K10CR1.k10cr1 import K10CR1\n\n\nclass WK10CR1(Worker):\n type = 'K10CR1'\n\n def setup(self):\n # setup motor\n self.ser_num = self.config.get('CHANNEL{}'.format(self.channel), 'Address')\n self.motor = K10CR1(self.ser_num)\n # setup thread for actuator since moving rotator can take some time\n self.restart = threading.Event() # make an event for unpausing execution thread\n self.thread = threading.Thread(target=self.loop, name=self.wname)\n self.thread.daemon = True # stop thread on exit of main program\n self.thread.start()\n\n def update_output(self):\n # wake up thread (which will push the new output to the rotator)\n self.restart.set()\n self.restart.clear()\n\n def loop(self):\n while True:\n self.restart.wait() # wait for event from main thread\n msg = '{}: Pushing new output to rotator: {}'\n self.logger.debug(msg.format(self.wname, self.ser_num))\n self.motor.moverel(self.delta)\n self.ready = True # let the controller know it can accept new inputs\n","sub_path":"worker_K10CR1.py","file_name":"worker_K10CR1.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"462577871","text":"from rest_framework import generics, viewsets\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\nfrom rest_framework.response import Response\n\nfrom gastos.models import Gastos\nfrom gastos.serializers import GastosSerializer\n\n\"\"\"\n@api_view(('GET',))\ndef api_root(request, format=None):\n return Response({\n 'snippets': reverse('snippet-list', request=request, format=format)\n })\n\n\"\"\"\n\nclass GastosCentro(viewsets.ViewSet):\n queryset = Gastos.objects.all()\n serializer_class = GastosSerializer\n\n def list(self, request, centro=None, seccion=None, programa=None, capitulo=None, economico=None):\n centro = centro.lower()\n d = {'ayuntamiento': 'AYUNTAMIENTO DE MADRID',\n 'informatica': 'Informatica del Ayuntamiento',\n 'empleo': 'Agencia para el Empleo de Madrid',\n 'tributaria': 'Agencia Tributaria Madrid',\n 'salud':'Madrid Salud',\n 'licencias': 'Agencia Gestion Licencias de Actividades'}\n queryset = self.queryset.filter(centro__icontains=d[centro]).values('desc_seccion').distinct()\n seccion_values = queryset\n if seccion or seccion==0:\n seccion = int(seccion)\n seccion = [e for e in seccion_values[seccion].values()][0]\n queryset = queryset.filter(desc_seccion__icontains=seccion).values('desc_programa').distinct()\n programa_values = queryset\n if programa or programa==0:\n programa = int(programa)\n programa = [e for e in programa_values[programa].values()][0]\n print('ales pain menee ', programa)\n queryset = queryset.filter(desc_programa__icontains=programa).values('desc_capitulo').distinct()\n capitulo_values = queryset\n if capitulo or capitulo==0:\n capitulo = int(capitulo)\n capitulo = [e for e in capitulo_values[capitulo].values()][0]\n print('ales pain menee ', capitulo)\n queryset = queryset.filter(desc_capitulo__icontains=capitulo).values('desc_economico').distinct()\n economico_values = queryset\n if economico or economico ==0:\n economico = int(economico)\n economico = [e for e in economico_values[economico].values()][0]\n queryset = queryset.filter(desc_economico__icontains=economico).values('valor')\n print('query values = ', queryset.values())\n queryset = sum([list(e.values())[0] for e in queryset])\n\n queryset = {'valor-final':queryset}\n #serializer = self.serializer_class(queryset, many=True)\n return Response(queryset)#(serializer.data)","sub_path":"democrapp/gastos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"70117068","text":"# Copyright 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nDEPS = [\n 'clang_tidy',\n 'fuchsia',\n 'recipe_engine/buildbucket',\n 'recipe_engine/json',\n 'recipe_engine/raw_io',\n 'recipe_engine/step',\n]\n\n\ndef RunSteps(api):\n api.clang_tidy.ensure_clang()\n checkout_dir = api.fuchsia.checkout(\n build_input=api.buildbucket.build.input,\n manifest='manifest/minimal',\n remote='tools',\n ).root_dir\n compile_commands = api.clang_tidy.gen_compile_commands(checkout_dir)\n\n all_checks = api.clang_tidy.run('step one', 'path/to/file', compile_commands)\n one_check = api.clang_tidy.run('step two', 'other/path/to/file',\n compile_commands,\n ['-*', 'fuchsia-default-arguments'])\n\n api.clang_tidy.get_line_from_offset('path/to/file', 12)\n api.clang_tidy.get_line_from_offset('other/path/to/file', 65)\n\n\ndef GenTests(api):\n read_output = '''test\nnewline output\n'''\n\n has_errors = '''- DiagnosticName: 'check'\n Message: 'error'\n FileOffset: 1\n FilePath: 'path/to/file'\n'''\n has_errors_json = [{\n 'FileOffset': 1,\n 'DiagnosticName': 'check',\n 'Message': 'error',\n 'FilePath': 'path/to/file'\n }]\n\n yield (api.test('basic') +\n api.buildbucket.try_build(\n git_repo='https://fuchsia.googlesource.com/tools'\n ) +\n api.step_data(\n 'step one.load yaml', stdout=api.json.output(has_errors_json)) +\n api.step_data('step two.load yaml', stdout=api.json.output(''))\n )\n","sub_path":"recipe_modules/clang_tidy/examples/full.py","file_name":"full.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"363531339","text":"# -*- coding: utf-8 -*-\n\n#!/usr/bin/env python3\n\n\"\"\"\n manage\n ~~~~~~\n\n Manager module\n\"\"\"\n\nfrom flask_script import Manager\nfrom lumbermill.api import create_app\nfrom flask import url_for\n\napp = create_app()\nmanager = Manager(app)\n\n\n@manager.command\ndef list_routes():\n output = []\n for rule in app.url_map.iter_rules():\n\n options = {}\n for arg in rule.arguments:\n options[arg] = \"[{0}]\".format(arg)\n\n methods = ','.join(rule.methods)\n url = url_for(rule.endpoint, **options)\n line = \"%s %s %s\" % (rule.endpoint, methods, url)\n output.append(line)\n \n print(\"\\n=== lumbermill Routes ===\\n\")\n \n for line in sorted(output):\n print(line)\n\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"224470235","text":"import os\nfrom datetime import datetime\nimport pytz\n\nfrom datalabframework import logging\nfrom datalabframework.yaml import yaml\nfrom datalabframework._utils import merge, to_ordered_dict\n\nimport json\nimport jsonschema\n\nfrom dotenv import load_dotenv\nfrom jinja2 import Environment\n\nloaded_md_files = []\nprofiles = {}\n\n# metadata files are cached once read the first time\ndef read(file_paths=None):\n \"\"\"\n Return all profiles, stored in a nested dictionary\n Profiles are merged over the list provided of provided metadata files to read. \n The order in the list of metadata files determines how profile properties are override\n :param file_paths: list of yaml files paths\n :return: dict of profiles\n \"\"\"\n global loaded_md_files, profiles\n \n # empty profiles, before start reading \n profiles = {}\n\n if not file_paths:\n file_paths = []\n \n loaded_md_files = []\n for filename in file_paths:\n if os.path.isfile(filename):\n with open(filename, 'r') as f:\n try:\n docs = list(yaml.load_all(f))\n loaded_md_files.append(filename)\n except yaml.YAMLError as e:\n if hasattr(e, 'problem_mark'):\n mark = e.problem_mark\n logging.error(\"Error loading yml file {} at position: (%s:%s): skipping file\".format(filename, mark.line+1, mark.column+1))\n docs = []\n finally:\n for doc in docs:\n doc['profile'] = doc.get('profile', 'default')\n profiles[doc['profile']] = merge(profiles.get(doc['profile'],{}), doc)\n\n return profiles\n\ndef inherit(profiles):\n \"\"\"\n Profiles inherit from a default profile.\n Inherit merges each profile with the configuration of the default profile.\n :param profiles: dict of profiles\n :return: dict of profiles\n \"\"\"\n\n # inherit from default for all other profiles\n for k in profiles.get('default', {}).keys():\n for p in set(profiles.keys()) - {'default'}:\n profiles[p][k] = merge(profiles['default'][k], profiles[p].get(k))\n\n return profiles\n\ndef render(metadata, max_passes=5):\n \"\"\"\n Renders jinja expressions in the given input metadata.\n jinja templates can refer to the dictionary itself for variable substitution\n\n :param metadata: profile dict, values may contain jinja templates\n :param max_passes: max number of rendering passes\n :return: profile dict, rendered jinja templates if present\n \"\"\"\n\n env = Environment()\n \n def env_func(key, value=None):\n return os.getenv(key, value)\n \n def now_func(tz='UTC', format='%Y-%m-%d %H:%M:%S'):\n dt=datetime.now(pytz.timezone(tz))\n return datetime.strftime(dt, format)\n \n env.globals['env'] = env_func\n env.globals['now'] = now_func\n \n doc = json.dumps(metadata)\n\n rendered = metadata\n\n for i in range(max_passes):\n dictionary = json.loads(doc)\n\n #rendering with jinja\n template = env.from_string(doc)\n doc = template.render(dictionary)\n\n # all done, or more rendering required?\n rendered = json.loads(doc)\n if dictionary == rendered:\n break\n\n return rendered\n\ndef v(d, schema):\n msg_error=None\n try:\n jsonschema.validate(d, schema)\n return\n except jsonschema.exceptions.ValidationError as e:\n msg_error = f'{e.message} \\n\\n## schema path:\\n'\n msg_error += f'\\'{\"/\".join(e.schema_path)}\\'\\n\\n'\n msg_error += f'## metadata schema definition '\n msg_error += f'{\"for \" + str(e.parent) if e.parent else \"\"}:'\n msg_error += f'\\n{yaml.dump(e.schema)}'\n \n if msg_error:\n raiseException(msg_error)\n \ndef validate_schema(md, schema_filename):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n filename = os.path.abspath(os.path.join(dir_path, 'schemas/{}'.format(schema_filename)))\n with open(filename) as f:\n v(md, yaml.load(f))\n\ndef validate(md):\n\n # validate data structure\n validate_schema(md, 'top.yml')\n \n # for d in md['providers']:\n # _validate_schema(d, 'provider.yml')\n #\n # for d in md['resources']:\n # _validate_schema(d, 'resource.yml')\n\n # validate semantics\n providers = md.get('providers', {}).keys()\n for resource_alias, r in md.get('resources',{}).items():\n resource_provider = r.get('provider')\n if resource_provider and resource_provider not in providers:\n print(f'resource {resource_alias}: given provider \"{resource_provider}\" '\n 'does not match any metadata provider')\n\ndef formatted(md):\n keys = (\n 'profile',\n 'variables',\n ('engine',(\n 'type',\n 'master',\n 'jobname',\n 'timezone',\n ('submit',(\n 'detect',\n 'jars',\n 'packages',\n 'py-files',\n )),\n 'config',\n )\n ),\n 'providers',\n 'resources',\n ('loggers',(\n ('root',('severity',)),\n ('datalabframework',(\n 'name',\n ('stream',(\n 'severity',\n 'enable',\n )),\n ('stdout',(\n 'severity',\n 'enable',\n )),\n ('file',(\n 'severity',\n 'enable',\n 'path',\n )),\n ('kafka',(\n 'severity',\n 'enable',\n 'hosts',\n 'topic',\n ))\n ))\n )),\n )\n \n d = to_ordered_dict(md, keys)\n \n if d['variables']:\n d['variables'] = dict(sorted(d['variables'].items()))\n \n return d\n\ndef debugMetadataFiles():\n message = '\\nList of loaded metadata files:\\n'\n if loaded_md_files:\n for f in loaded_md_files:\n message += f' - {f}\\n'\n else:\n message += 'None'\n \n return message\n\ndef debugProfiles():\n message = '\\nList of available profiles:\\n'\n if profiles:\n for f in profiles.keys():\n message += f' - {f}\\n'\n else:\n message += 'None'\n \n return message\n\ndef raiseException(message=''):\n message += '\\n'\n message += debugMetadataFiles()\n message += debugProfiles()\n raise ValueError(message)\n \ndef load(profile='default', metadata_files=None, dotenv_path=None):\n \"\"\"\n Load the profile, given a list of yml files and a .env filename\n profiles inherit from the defaul profile, a profile not found will contain the same elements as the default profile\n\n :param profile: the profile to load (default: 'default')\n :param metadata_files: a list of metadata files to read \n :param dotenv_path: the path of a dotenv file to read\n :return: the loaded metadata profile dict\n \"\"\"\n # get env variables from .env file\n if dotenv_path and os.path.isfile(dotenv_path):\n load_dotenv(dotenv_path)\n \n profiles = read(metadata_files)\n \n # empty profile if profile not found\n if profile not in profiles.keys():\n raiseException(f'Profile \"{profile}\" not found.')\n\n # read metadata, get the profile, if not found get an empty profile\n profiles = inherit(profiles)\n metadata = profiles[profile]\n\n # render any jinja templates in the profile\n md = render(metadata)\n \n # validate\n validate(md)\n \n # format\n md = formatted(md)\n return md\n","sub_path":"datalabframework/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":7862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"53283240","text":"# -*- coding:utf-8 -*-\nimport logging\nlogger = logging.getLogger(__name__)\nfrom functools import partial\nimport pkg_resources\nimport sys\n\n\nPHASE1_CONFIG = -20\nPHASE2_CONFIG = -10\n\n\nclass ConfigurationError(Exception):\n pass\n\n\ndef import_symbol(symbol):\n return pkg_resources.EntryPoint.parse(\"x=%s\" % symbol).load(False)\n\n\ndef caller_module(level=2):\n module_globals = sys._getframe(level).f_globals\n name = module_globals.get(\"__name__\", \"__main__\")\n return sys.modules[name]\n\n\nclass Control(object):\n pass\n\n\nclass ConfiguratorCore(object):\n def __init__(self, settings=None, module=None, queue=None, control=None):\n self.settings = settings or {}\n self.module = module or caller_module()\n self.queue = queue or []\n self.control = control or Control()\n\n def build_import_symbol_string(self, fn_or_string):\n if not fn_or_string.startswith(\".\"):\n return fn_or_string\n\n nodes = self.module.__name__.split(\".\")\n if fn_or_string.endswith(\".\"):\n fn_or_string = fn_or_string[1:]\n\n for i, c in enumerate(fn_or_string):\n if c != \".\":\n break\n nodes.pop()\n if fn_or_string == \"\" or fn_or_string.endswith(\".\"):\n return \".\".join(nodes)\n return \".\".join(nodes) + \".\" + fn_or_string[i:]\n\n def include(self, fn_or_string):\n if callable(fn_or_string):\n includeme = fn_or_string\n module = getattr(fn_or_string, \"__module__\", None)\n else:\n symbol_string = self.build_import_symbol_string(fn_or_string)\n if \":\" in symbol_string:\n module_string, fn_name = symbol_string.split(\":\", 1)\n else:\n module_string, fn_name = symbol_string, \"includeme\"\n module = import_symbol(module_string)\n includeme = getattr(module, fn_name)\n\n config = self.__class__(self.settings,\n module=module,\n queue=self.queue,\n control=self.control)\n return includeme(config)\n\n def action(self, callback, order=0):\n self.queue.append((order, callback))\n\n def commit(self):\n for o, callback in sorted(self.queue, key=lambda xs: xs[0]):\n callback()\n self.queue = []\n\n def maybe_dotted(self, fn_or_string):\n if callable(fn_or_string):\n return fn_or_string\n symbol_string = self.build_import_symbol_string(fn_or_string)\n return import_symbol(symbol_string)\n\n def add_directive(self, name, fn_or_string):\n fn = self.maybe_dotted(fn_or_string)\n setattr(self.control, name, fn)\n\n def __getattr__(self, name):\n attr = getattr(self.control, name)\n if callable(attr):\n return partial(attr, self)\n return attr\n","sub_path":"miniconfig/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"69481009","text":"import os\nimport cv2\nimport matplotlib.pyplot as plt\ndef main():\n \n \n img=cv2.imread('im2.jpg') \n laplacian=cv2.Laplacian(img,cv2.CV_64F)\n sobelx=cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)\n sobely=cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)\n edges=cv2.Canny(img,100,100)\n cv2.imshow('edges',edges)\n cv2.imshow('sobelx',sobelx)\n cv2.imshow('sobely',sobely)\n cv2.imshow('img',img)\n cv2.imshow('laplacian',laplacian)\n cv2.waitKey()\n cv2.destroyAllWindows\n \nmain()","sub_path":"EdgeDetection.py","file_name":"EdgeDetection.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"20312899","text":"board = [[' ', ' ', ' '],\r\n [' ', ' ', ' '],\r\n [' ', ' ', ' ']]\r\nplayer1 = True\r\nframeCount = 0\r\nsystemCheck = 0\r\nwwonn = ''\r\n\r\nBLACKTRSP = 0, 0, 0\r\n\r\nHEIGHT = 700\r\nWIDTH = HEIGHT\r\n\r\ndef draw():\r\n screen.draw.filled_rect(Rect((0, 0), (WIDTH, HEIGHT)), BLACKTRSP)\r\n drawLines()\r\n drawBoard()\r\n\r\n screen.draw.text('Please put in an\\nempty square', center=(WIDTH / 2, HEIGHT / 2), fontsize=p5map(100, 0, 700, 0, HEIGHT), color=(0, 255, 255), alpha=systemCheck / 255)\r\n if wwonn != '':\r\n screen.clear()\r\n screen.draw.text(wwonn + \" has won!\\n'Y' to replay,\\n'N' not to\", center=(WIDTH / 2, HEIGHT / 2), fontsize=p5map(100, 0, 700, 0, HEIGHT), color=(255, 0, 255))\r\n\r\ndef on_key_down(key):\r\n global wwonn\r\n if wwonn != '':\r\n if key == keys.Y:\r\n global board\r\n board = [[' ', ' ', ' '],\r\n [' ', ' ', ' '],\r\n [' ', ' ', ' ']]\r\n wwonn = ''\r\n systemCheck = 0\r\n elif key == keys.N:\r\n exit()\r\n\r\ndef on_mouse_down(pos):\r\n x = pos[0]\r\n y = pos[1]\r\n # board[(p5rund(x - (WIDTH / 6)) - 1) + 1][(p5rund(y - (HEIGHT / 6)) - 1) + 1] = 1\r\n x = (p5rund(x - (WIDTH / 6), WIDTH) - 1) + 1\r\n y = (p5rund(y - (HEIGHT / 6), HEIGHT) - 1) + 1\r\n global player1\r\n if board[y][x] == ' ':\r\n if player1 == True:\r\n board[y][x] = 'X'\r\n player1 = False\r\n else:\r\n board[y][x] = 'O'\r\n player1 = True\r\n else:\r\n global systemCheck\r\n systemCheck = 300\r\n\r\n if checkWon() != 'n':\r\n clock.schedule_unique(cch, 0.1)\r\n\r\ndef cch():\r\n global wwonn\r\n wwonn = checkWon()\r\n\r\ndef update():\r\n global frameCount\r\n frameCount += 1\r\n\r\n global systemCheck\r\n systemCheck -= 3\r\n\r\ndef checkWon():\r\n for y in range(0, len(board), 1): # Check rows\r\n if board[y][0] == board[y][1] and board[y][1] == board[y][2] and board[y][0] != ' ':\r\n return board[y][0] # Who won\r\n for x in range(0, len(board), 1): # Check columns\r\n if board[0][x] == board[1][x] and board[1][x] == board[2][x] and board[0][x] != ' ':\r\n return board[0][x]\r\n if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[0][0] != ' ': # Check diagonals\r\n return board[0][0]\r\n if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[0][2] != ' ': # Check diagonals\r\n return board[0][0]\r\n return 'n'\r\n\r\ndef drawBoard():\r\n for y in range(0, len(board), 1):\r\n for x in range(0, len(board[0]), 1):\r\n screen.draw.text(board[y][x], center=((x * (WIDTH / 3)) + (WIDTH/6), y * (HEIGHT / 3) + (HEIGHT / 6)), fontsize=HEIGHT / 3)\r\n\r\ndef drawLines():\r\n strk = p5map(10, 0, 600, 0, HEIGHT)\r\n screen.draw.filled_rect(Rect((((WIDTH / 3) - (strk / 2)), 0), (strk, HEIGHT)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect(((((WIDTH / 3) * 2) - (strk / 2)), 0), (strk, HEIGHT)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect((0, ((HEIGHT / 3) - (strk / 2))), (WIDTH, strk)), (255, 255, 0))\r\n screen.draw.filled_rect(Rect((0, (((HEIGHT / 3) * 2) - (strk / 2))), (WIDTH, strk)), (255, 255, 0))\r\n\r\ndef p5rund(n, rw):\r\n return round((n * len(board)) / rw)\r\n\r\ndef p5map(n, start1, stop1, start2, stop2):\r\n return ((n-start1) / (stop1-start1)) * (stop2 - start2) + start2","sub_path":"intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"60999729","text":"from application import database, ps\nfrom typing import List\nfrom uuid import uuid4, UUID\n\n\nasync def add_new_group(new_group: str):\n query = ps.UserGroup.insert()\n values = {\n \"id\": uuid4(),\n \"group\": new_group\n }\n await database.execute(query=query, values=values)\n return values\n\n\nasync def get_all_groups(offset: int = 0, limit: int = 10):\n query = ps.UserGroup.select().offset(offset).limit(limit)\n groups = await database.fetch_all(query)\n return groups\n\n\nasync def get_all_groups_count() -> int:\n query = ps.UserGroup.count()\n count = await database.execute(query)\n return count\n\n\nasync def get_user_group_by_name(group: str):\n query = ps.UserGroup.select().where(ps.UserGroup.columns.group == group)\n group = await database.fetch_one(query)\n return group\n\n\nasync def get_user_group_by_id(group_id: UUID):\n query = ps.UserGroup.select().where(ps.UserGroup.columns.id == group_id)\n group = await database.fetch_one(query)\n return group\n\n\nasync def delete_group_in_db(group_id: UUID) -> bool:\n query = ps.UserGroup.delete().where(ps.UserGroup.columns.id == group_id)\n await database.execute(query)\n exists = await get_user_group_by_id(group_id)\n return True if not exists else False\n","sub_path":"ra_graphql/crud/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"414201449","text":"import db\n\nclass Recipe(object):\n def __init__(self, name, ingredients):\n self.name = name\n self.ingredients = ingredients\n # you could also check here for properly formatted ingredients\n\n def need_ingredients(self):\n needed = []\n for (generic_type, amount) in self.ingredients:\n matching = db.check_inventory_for_type(generic_type)\n\n max_m = ''\n max_l = ''\n max_amount = 0.0\n\n for (m, l, t) in matching:\n if t > max_amount:\n max_amount = t\n\n amount_needed = db.convert_to_ml(amount)\n\n if max_amount < amount_needed:\n needed.append((generic_type, amount_needed - max_amount))\n\n return needed\n\ndef filter_recipes_by_ingredients(recipe_list):\n x = []\n \n for r in recipe_list:\n if not r.need_ingredients():\n x.append(r)\n\n return x\n","sub_path":"drinkz/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"380122537","text":"from django import forms\nfrom django.contrib.auth import get_user_model\n\nfrom datetimewidget.widgets import DateWidget\n\nfrom .models import Monster, UserMonsterAction, UserMonster\n\n\nclass UserMonsterActionForm(forms.ModelForm):\n class Meta:\n model = UserMonsterAction\n fields = [\n 'timestamp',\n 'monsteraction',\n 'remarks',\n ]\n widgets = {\n 'timestamp': DateWidget(usel10n=True, bootstrap_version=3),\n }\n\n\nclass UserMonsterForm(forms.ModelForm):\n class Meta:\n model = UserMonster\n fields = [\n # 'user',\n # 'monster',\n # 'monster_number',\n ]\n","sub_path":"lalalalife/monsters/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"332268858","text":"import matplotlib.pyplot as plt\nimport Nio, sys, argparse\nimport numpy as np\nfrom scipy import signal\nfrom pprint import pprint\n\ndef SpectralVariance(y):\n c = np.fft.rfft(signal.detrend(y), norm=\"ortho\") # Ortho means normalized by sqrt N\n return abs(c)**2.0\n \nparser = argparse.ArgumentParser()\nparser.add_argument('--input-dir', dest='input_dir')\nparser.add_argument('--output-dir', dest='output_dir')\nparser.add_argument('--casenames', dest='casenames')\nparser.add_argument('--legends')\nparser.add_argument('--data-file', dest='data_file')\nparser.add_argument('--varname', dest='varname')\n\nargs = parser.parse_args()\n\npprint(args)\n\ncasenames = args.casenames.split(\",\")\nlegends = args.legends.split(\",\")\n\nprint(\"Going to compare these models:\")\npprint(casenames)\n\ntss = []\nsps = []\n\nfor i in range(len(casenames)):\n\n f = Nio.open_file(\"%s/%s/%s.nc\" % (args.input_dir, casenames[i], args.data_file), \"r\")\n \n ts = f.variables[args.varname][:]\n ts /= np.std(ts)\n\n sp = SpectralVariance(ts)\n\n tss.append(ts)\n sps.append(sp)\n\n f.close()\n\n\nN = len(tss[0])\nfreq = np.fft.rfftfreq(N, d=1.0/12.0)\ntime = np.arange(N) / 12\nnyears = N / 12.0\nperiod = 1.0 / freq\n\nmarked_periods = np.array([0.5, 1, 2, 3, 4, 5, 10, 20, 30, 40])\n\nfig, ax = plt.subplots(2, 1, figsize=(12, 10))\n\nax[0].set_title(\"%s indices (%d years)\" % (args.varname, nyears, ))\nax[0].set_xlabel(\"Time [years]\")\nax[0].plot([time[0], time[-1]], [0, 0], \"-\", color=\"#cccccc\", linewidth=2)\n\nfor i in range(len(casenames)): \n ax[0].plot(time, tss[i], linewidth=2, label=casenames[i])\n\nax[0].legend()\n\nax[1].set_title(\"Spectrum Analysis\")\nax[1].set_xlabel(\"Period [years]\")\n\nfor i in range(len(casenames)): \n ax[1].loglog(period[1:], sps[i][1:], linewidth=2, label=legends[i])\n #ax[1].plot(period[1:], sps[i][1:], linewidth=2, label=casenames[i])\n\nax[1].legend()\n\nax[1].set_xticks(marked_periods)\nax[1].set_xticklabels([(\"%.1f\" if v<1 else \"%d\") % (v,) for v in marked_periods])\n\nfig.savefig(\"%s/mc_climate_indices_%s.png\" % (args.output_dir, args.varname), dpi=200)\n\n#plt.show()\n","sub_path":"other_src/diagnose_scripts/plot/plot_mc_global_mean_temperature.py","file_name":"plot_mc_global_mean_temperature.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"115977375","text":"class Solution:\n def solve(self, board) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n m = len(board)\n if m < 3:\n return\n n = len(board[0])\n if n < 3:\n return\n visited = [[False if board[i][j] == 'O' else True for j in range(n)] for i in range(m)]\n mask, flip = {}, {}\n\n def dfs(r, c, count):\n if r < 0 or r >= m or c < 0 or c >= n or visited[r][c]:\n return\n if board[r][c] == 'O':\n visited[r][c] = True\n mask[(r, c)] = count\n if r == 0 or r == m - 1 or c == 0 or c == n - 1:\n flip[count] = 'O'\n dfs(r - 1, c, count)\n dfs(r + 1, c, count)\n dfs(r, c - 1, count)\n dfs(r, c + 1, count)\n\n count = 0\n for i in range(m):\n for j in range(n):\n if not visited[i][j]:\n count += 1\n flip[count] = 'X'\n dfs(i, j, count)\n for c in mask:\n board[c[0]][c[1]] = flip[mask[c]]\n return\n\n\ns = Solution()\nboard = [[\"X\", \"O\", \"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"O\", \"O\"],\n [\"X\", \"O\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\", \"X\"],\n [\"X\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\", \"X\", \"X\"],\n [\"X\", \"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\", \"X\", \"O\", \"X\", \"O\", \"X\", \"O\", \"X\"],\n [\"X\", \"X\", \"O\", \"X\", \"X\", \"O\", \"O\", \"X\", \"X\", \"X\"],\n [\"O\", \"X\", \"X\", \"O\", \"O\", \"X\", \"O\", \"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\", \"X\", \"X\", \"X\", \"O\", \"X\", \"X\", \"X\"],\n [\"X\", \"O\", \"O\", \"X\", \"X\", \"O\", \"X\", \"X\", \"O\", \"O\"],\n [\"X\", \"X\", \"X\", \"O\", \"O\", \"X\", \"O\", \"X\", \"X\", \"O\"]]\ns.solve(board)\nprint(board)\n","sub_path":"leetcode/2020/SurroundRegion.py","file_name":"SurroundRegion.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"189084662","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\nimport tornado.template\nimport urllib.request\nfrom urllib.parse import urljoin\n\nfrom pkg_resources import parse_version\n\nfrom lilaclib import *\n\ndebug = False\n_version = '1.16.0'\n_version_date = '2016-12-23'\n\nSTDS = [\n 'arm-unknown-linux-gnueabihf',\n 'armv7-unknown-linux-gnueabihf',\n 'x86_64-unknown-linux-gnu',\n 'i686-unknown-linux-gnu',\n 'i686-pc-windows-gnu', # need libgcc_s_dw2-1.dll\n 'x86_64-pc-windows-gnu',\n 'asmjs-unknown-emscripten',\n 'wasm32-unknown-emscripten',\n 'wasm32-unknown-unknown',\n 'aarch64-linux-android',\n]\n\ndist_url = 'https://static.rust-lang.org/dist/index.html'\n\nbuild_prefix = 'extra-x86_64'\n\ntoolchain = {\n 'x86_64-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-pc-windows-gnu': ['mingw-w64-gcc'],\n 'i686-unknown-linux-gnu': ['gcc-multilib'],\n 'asmjs-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-emscripten': ['emsdk', 'emscripten'],\n 'wasm32-unknown-unknown': [],\n 'aarch64-linux-android': ['android-ndk'],\n}\n\ndef get_latest_version():\n if not debug:\n res = urllib.request.urlopen(dist_url)\n page = res.read().decode('utf-8')\n version_date = re.findall(r'(\\d{4}-\\d{2}-\\d{2})/', page)[-1]\n stable = sorted(set(re.findall(r'\\d+\\.\\d+\\.\\d+', page)), key=parse_version)[-1]\n major, minor, patchlevel = stable.split('.')\n version = '%s.%s.%s' % (major, int(minor) + 2, patchlevel)\n return version, version_date\n else:\n return _version, _version_date\n\nclass Std:\n def __init__(self, platform, date):\n self.name = 'rust-std-nightly-' + platform\n self.url = urljoin(dist_url, date + '/' + self.name + '.tar.xz')\n self.platform = platform\n self.optdepends = toolchain.get(platform)\n\ndef pre_build():\n version, version_date = get_latest_version()\n if not debug:\n oldfiles = glob.glob('*.xz') + glob.glob('*.xz.asc') + glob.glob('*.part')\n for f in oldfiles:\n os.unlink(f)\n\n stds = [Std(x, version_date) for x in STDS]\n\n loader = tornado.template.Loader('.')\n content = loader.load('PKGBUILD.tmpl').generate(\n stds = stds,\n version = version,\n version_date = version_date.replace('-', ''),\n version_date_raw = version_date,\n )\n with open('PKGBUILD', 'wb') as output:\n output.write(content)\n\ndef post_build():\n git_add_files(['PKGBUILD'])\n git_commit()\n\nif __name__ == '__main__':\n single_main()\n","sub_path":"rust-nightly/lilac.py","file_name":"lilac.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"198305489","text":"import sys\nfrom collections import deque\n\nDIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\nH, W = map(int, input().split())\na = {}\nsecs = {}\nwarps = {}\nfor i in range(H):\n l = input()\n for j in range(len(l)):\n c = l[j]\n\n p = (i, j)\n a[p] = c\n\n if c == '#':\n secs[p] = -1\n elif c == 'S':\n S = p\n secs[p] = 0\n elif c == 'G':\n G = p\n elif c.islower():\n if c not in warps:\n warps[c] = [p]\n else:\n warps[c].append(p)\n\nqueue = deque()\nqueue.append(S)\n\nwhile len(queue):\n p = queue.popleft()\n c = a[p]\n s = secs[p]\n ns = s + 1\n\n for dir in DIRS:\n np = (p[0] + dir[0], p[1] + dir[1])\n if np[0] < 0 or np[0] >= H or np[1] < 0 or np[1] >= W:\n continue\n\n nc = a[np]\n\n if np in secs:\n continue\n if nc == '#':\n continue\n if nc == 'G':\n print(ns)\n sys.exit(0)\n \n secs[np] = ns\n queue.append(np)\n\n if c.islower():\n for wp in [wp for wp in warps[c] if wp != p and wp not in secs]:\n secs[wp] = ns\n queue.append(wp)\n\nprint(-1)","sub_path":"tasks/abc184/abc184_e.py","file_name":"abc184_e.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"523634245","text":"#Full credit to https://raw.githubusercontent.com/pcfens/RaspberryPi-AS3935 (or who ever\n#originally wrote this)\n\n#This is a mod for micropython on a NodeMCU v3.0\nfrom time import sleep, sleep_ms\nfrom machine import reset\n\n# AS3935 default address.\nAS3935_I2CADDR = 0x03\n\nclass ESP_AS3935:\n \"\"\"A basic class used for interacting with the AS3935 lightning\n sensor from a esp8266 over I2C\"\"\"\n\n def __init__(self,\n i2c_address=AS3935_I2CADDR,\n i2c=None,\n indoors=True,\n noise_floor=2,\n min_strikes=1,\n on_init=True):\n self.i2c_address = i2c_address\n if i2c is None:\n raise ValueError('An I2C object is required.')\n self.i2c = i2c\n # temporary data holders which stay allocated\n self._1_barray = bytearray(1)\n self._3_barray = bytearray(3)\n #sleep(0.5)\n #self.reset()\n if on_init == True:\n print('init AS3935')\n self.reset()\n sleep(0.5)\n self.set_indoors(indoors)\n self.set_noise_floor(noise_floor)\n #self.set_min_strikes(min_strikes)\n sleep(0.5)\n self.calibrate(tun_cap=0x02)\n\n def calibrate(self, tun_cap=None): #check\n \"\"\"Calibrate the lightning sensor - this takes up to half a second\n and is blocking.\n The value of tun_cap should be between 0 and 15, and is used to set\n the internal tuning capacitors (0-120pF in steps of 8pF)\n \"\"\"\n sleep(0.08)\n if tun_cap is not None:\n if tun_cap < 0x10 and tun_cap > -1:\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0xF0) | tun_cap\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0xF0) | tun_cap\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n else:\n raise Exception(\"Value of TUN_CAP must be between 0 and 15\")\n\n self._1_barray[0] = 0x96\n self.i2c.writeto_mem(self.i2c_address, 0x3D, self._1_barray)\n\n sleep_ms(2)\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = self._1_barray[0] | 0x20\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) | 0x20)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n self._1_barray[0] = self._1_barray[0] & 0xDF\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0xDF)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n sleep_ms(2)\n\n def reset(self):\n \"\"\"Reset all registers to their default power on values\n \"\"\"\n self._1_barray[0] = 0x96\n self.i2c.writeto_mem(self.i2c_address, 0x3C, self._1_barray)\n #self.i2c.writeto_mem(self.i2c_address, 0x3C, bytes(int_to_bytes(0x96,1)))\n\n def get_interrupt(self):\n \"\"\"Get the value of the interrupt register\n 0x01 - Too much noise\n 0x04 - Disturber\n 0x08 - Lightning\n \"\"\"\n try:\n self.i2c.readfrom_mem_into(self.i2c_address, 0x03, self._1_barray)\n except OSError:\n reset()\n return self._1_barray[0] & 0x0F\n #return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x03,1))) & 0x0F)\n\n def get_distance(self):\n \"\"\"Get the estimated distance of the most recent lightning event\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x07, self._1_barray)\n if (self._1_barray[0] & 0x3F) == 0x3F:\n return False\n else:\n return self._1_barray[0] & 0x3F\n\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x07,1))) & 0x3F) == 0x3F:\n # return False\n #else:\n # return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x07,1))) & 0x3F)\n\n def get_energy(self):\n \"\"\"Get the calculated energy of the most recent lightning event (3 bytes)\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x04, self._3_barray)\n return ((self._3_barray[2] & 0x1F) << 16 | self._3_barray[1] << 8 | self._3_barray[0])\n\n def get_noise_floor(self):\n \"\"\"Get the noise floor value.\n\n Actual voltage levels used in the sensor are located in Table 16\n of the data sheet.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x01, self._1_barray)\n return (self._1_barray[0] & 0x70) >> 4\n\n #return (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x01,1))) & 0x70) >> 4\n\n def set_noise_floor(self, noisefloor):\n \"\"\"Set the noise floor value.\n\n Actual voltage levels used in the sensor are located in Table 16\n of the data sheet.\n \"\"\"\n noisefloor = (noisefloor & 0x07) << 4\n self.i2c.readfrom_mem_into(self.i2c_address, 0x01, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0x8F) + noisefloor\n self.i2c.writeto_mem(self.i2c_address, 0x01, self._1_barray)\n\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x01,1))) & 0x8F) + noisefloor\n #self.i2c.writeto_mem(self.i2c_address, 0x01, bytes(int_to_bytes(write_value,1)))\n\n def lower_noise_floor(self, min_noise=0):\n \"\"\"Lower the noise floor by one step.\n\n min_noise is the minimum step that the noise_floor should be\n lowered to.\n \"\"\"\n floor = self.get_noise_floor()\n if floor > min_noise:\n floor = floor - 1\n self.set_noise_floor(floor)\n return floor\n\n def raise_noise_floor(self, max_noise=7):\n \"\"\"Raise the noise floor by one step\n\n max_noise is the maximum step that the noise_floor should be\n raised to.\n \"\"\"\n floor = self.get_noise_floor()\n if floor < max_noise:\n floor = floor + 1\n self.set_noise_floor(floor)\n return floor\n\n def get_min_strikes(self):\n \"\"\"Get the number of lightning detections required before an\n interrupt is raised.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x02, self._1_barray)\n value = (self._1_barray[0] >> 4 ) & 0x03\n #value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x02,1))) >> 4) & 0x03\n if value == 0:\n return 1\n elif value == 1:\n return 5\n elif value == 2:\n return 9\n elif value == 3:\n return 16\n\n def set_min_strikes(self, minstrikes):\n \"\"\"Set the number of lightning detections required before an\n interrupt is raised.\n\n Valid values are 1, 5, 9, and 16, any other raises an exception.\n \"\"\"\n if minstrikes == 1:\n minstrikes = 0\n elif minstrikes == 5:\n minstrikes = 1\n elif minstrikes == 9:\n minstrikes = 2\n elif minstrikes == 16:\n minstrikes = 3\n else:\n raise Exception(\"Value must be 1, 5, 9, or 16\")\n\n minstrikes = (minstrikes & 0x03) << 4\n self.i2c.readfrom_mem_into(self.i2c_address, 0x02, self._1_barray)\n self._1_barray[0] = (self._1_barray[0] & 0xCF) + minstrikes\n self.i2c.writeto_mem(self.i2c_address, 0x02, self._1_barray)\n\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x02,1))) & 0xCF) + minstrikes\n #self.i2c.writeto_mem(self.i2c_address, 0x02, bytes(int_to_bytes(write_value,1)))\n\n def get_indoors(self):\n \"\"\"Determine whether or not the sensor is configured for indoor\n use or not.\n Returns True if configured to be indoors, otherwise False.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x0, self._1_barray)\n if ((self._1_barray[0] & 0x20) == 0x20):\n #if int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0x20 == 0x20:\n return True\n else:\n return False\n\n def set_indoors(self, indoors):\n \"\"\"Set whether or not the sensor should use an indoor configuration.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x0, self._1_barray)\n if indoors:\n self._1_barray[0] = (self._1_barray[0] & 0xC1) | 0x24\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0xc1) | 0x24\n else:\n self._1_barray[0] = (self._1_barray[0] & 0xC1) | 0x1C\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x0,1))) & 0xc1) | 0x1C\n self.i2c.writeto_mem(self.i2c_address, 0x0, self._1_barray)\n\n def set_mask_disturber(self, mask_dist):\n \"\"\"Set whether or not disturbers should be masked (no interrupts for\n what the sensor determines are man-made events)\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x3, self._1_barray)\n if mask_dist:\n self._1_barray[0] = (self._1_barray[0] | 0x20)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) | 0x20)\n else:\n self._1_barray[0] = (self._1_barray[0] & 0xDF)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) & 0xDF)\n self.i2c.writeto_mem(self.i2c_address, 0x03, self._1_barray)\n\n def get_mask_disturber(self):\n \"\"\"Get whether or not disturbers are masked or not.\n Returns True if interrupts are masked, false otherwise\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x3, self._1_barray)\n if ((self._1_barray[0] & 0x20) == 0x20):\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x3,1))) & 0x20) == 0x20:\n return True\n else:\n return False\n'''\n def set_disp_lco(self, display_lco):\n \"\"\"Have the internal LC oscillator signal displayed on the interrupt pin for\n measurement.\n\n Passing display_lco=True enables the output, False disables it.\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n if display_lco:\n self._1_barray[0] = (self._1_barray[0] & 0x80)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) | 0x80)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n else:\n self._1_barray[0] = (self._1_barray[0] & 0x7F)\n #write_value = (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0x7F)\n #self.i2c.writeto_mem(self.i2c_address, 0x08, bytes(int_to_bytes(write_value,1)))\n self.i2c.writeto_mem(self.i2c_address, 0x08, self._1_barray)\n sleep(0.002)\n\n def get_disp_lco(self):\n \"\"\"Determine whether or not the internal LC oscillator is displayed on the\n interrupt pin.\n\n Returns True if the LC oscillator is being displayed on the interrupt pin,\n False otherwise\n \"\"\"\n self.i2c.readfrom_mem_into(self.i2c_address, 0x08, self._1_barray)\n if ((self._1_barray[0] & 0x80) == 0x80):\n #if (int(ord(self.i2c.readfrom_mem(self.i2c_address,0x08,1))) & 0x80) == 0x80:\n return True\n else:\n return False\n'''\n","sub_path":"MicroPython/esp8266/esp8266-AS3935/AS3935.py","file_name":"AS3935.py","file_ext":"py","file_size_in_byte":11597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"596477142","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport django.contrib.postgres.fields\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('feeds', '0002_auto_20150404_1501'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='feed',\n name='tags',\n ),\n migrations.AddField(\n model_name='feed',\n name='tags',\n field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=150), verbose_name='keywords', null=True, size=None, blank=True),\n ),\n migrations.RemoveField(\n model_name='subscription',\n name='tags',\n ),\n migrations.AddField(\n model_name='subscription',\n name='tags',\n field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=150), verbose_name='keywords', null=True, size=None, blank=True),\n ),\n migrations.DeleteModel(\n name='Tag',\n ),\n ]\n","sub_path":"feedpocket/feeds/migrations/0003_auto_20150408_0651.py","file_name":"0003_auto_20150408_0651.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"289497073","text":"\"\"\"\nSomewhat hacky solution to create conda lock files.\n\"\"\"\n\nimport datetime\nimport logging\nimport os\nimport pathlib\nimport posixpath\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom types import TracebackType\nfrom typing import (\n AbstractSet,\n Any,\n Dict,\n Iterator,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n Type,\n Union,\n)\nfrom urllib.parse import urlsplit\n\nimport click\nimport pkg_resources\nimport yaml\n\nfrom ensureconda import ensureconda\nfrom typing_extensions import Literal\n\nfrom conda_lock.click_helpers import OrderedGroup\nfrom conda_lock.common import (\n read_file,\n read_json,\n relative_path,\n temporary_file_with_contents,\n write_file,\n)\nfrom conda_lock.conda_solver import solve_conda\nfrom conda_lock.errors import MissingEnvVarError, PlatformValidationError\nfrom conda_lock.invoke_conda import (\n PathLike,\n _invoke_conda,\n determine_conda_executable,\n is_micromamba,\n)\nfrom conda_lock.models.channel import Channel\n\n\ntry:\n from conda_lock.pypi_solver import solve_pypi\n\n PIP_SUPPORT = True\nexcept ImportError:\n PIP_SUPPORT = False\nfrom conda_lock.src_parser import (\n Dependency,\n LockedDependency,\n Lockfile,\n LockMeta,\n LockSpecification,\n UpdateSpecification,\n aggregate_lock_specs,\n)\nfrom conda_lock.src_parser.environment_yaml import parse_environment_file\nfrom conda_lock.src_parser.lockfile import parse_conda_lock_file, write_conda_lock_file\nfrom conda_lock.src_parser.meta_yaml import parse_meta_yaml_file\nfrom conda_lock.src_parser.pyproject_toml import parse_pyproject_toml\nfrom conda_lock.virtual_package import (\n FakeRepoData,\n default_virtual_package_repodata,\n virtual_package_repo_from_specification,\n)\n\n\nlogger = logging.getLogger(__name__)\nDEFAULT_FILES = [pathlib.Path(\"environment.yml\")]\n\n# Captures basic auth credentials, if they exists, in the second capture group.\nAUTH_PATTERN = re.compile(r\"^(https?:\\/\\/)(.*:.*@)?(.*)\")\n\n# Captures the domain in the second group.\nDOMAIN_PATTERN = re.compile(r\"^(https?:\\/\\/)?([^\\/]+)(.*)\")\n\n# Captures the platform in the first group.\nPLATFORM_PATTERN = re.compile(r\"^# platform: (.*)$\")\nINPUT_HASH_PATTERN = re.compile(r\"^# input_hash: (.*)$\")\n\n\nHAVE_MAMBA = (\n ensureconda(\n mamba=True, micromamba=False, conda=False, conda_exe=False, no_install=True\n )\n is not None\n)\n\n\nif not (sys.version_info.major >= 3 and sys.version_info.minor >= 6):\n print(\"conda_lock needs to run under python >=3.6\")\n sys.exit(1)\n\n\nDEFAULT_PLATFORMS = [\"osx-64\", \"linux-64\", \"win-64\"]\n\nKIND_EXPLICIT: Literal[\"explicit\"] = \"explicit\"\nKIND_LOCK: Literal[\"lock\"] = \"lock\"\nKIND_ENV: Literal[\"env\"] = \"env\"\nTKindAll = Union[Literal[\"explicit\"], Literal[\"lock\"], Literal[\"env\"]]\nTKindRendarable = Union[Literal[\"explicit\"], Literal[\"lock\"], Literal[\"env\"]]\n\n\nDEFAULT_KINDS: List[Union[Literal[\"explicit\"], Literal[\"lock\"]]] = [\n KIND_EXPLICIT,\n KIND_LOCK,\n]\nDEFAULT_LOCKFILE_NAME = \"conda-lock.yml\"\nKIND_FILE_EXT = {\n KIND_EXPLICIT: \"\",\n KIND_ENV: \".yml\",\n KIND_LOCK: \".\" + DEFAULT_LOCKFILE_NAME,\n}\nKIND_USE_TEXT = {\n KIND_EXPLICIT: \"conda create --name YOURENV --file {lockfile}\",\n KIND_ENV: \"conda env create --name YOURENV --file {lockfile}\",\n KIND_LOCK: \"conda-lock install --name YOURENV {lockfile}\",\n}\n\n\ndef _extract_platform(line: str) -> Optional[str]:\n search = PLATFORM_PATTERN.search(line)\n if search:\n return search.group(1)\n return None\n\n\ndef _extract_spec_hash(line: str) -> Optional[str]:\n search = INPUT_HASH_PATTERN.search(line)\n if search:\n return search.group(1)\n return None\n\n\ndef extract_platform(lockfile: str) -> str:\n for line in lockfile.strip().split(\"\\n\"):\n platform = _extract_platform(line)\n if platform:\n return platform\n raise RuntimeError(\"Cannot find platform in lockfile.\")\n\n\ndef extract_input_hash(lockfile_contents: str) -> Optional[str]:\n for line in lockfile_contents.strip().split(\"\\n\"):\n platform = _extract_spec_hash(line)\n if platform:\n return platform\n return None\n\n\ndef _do_validate_platform(platform: str) -> Tuple[bool, str]:\n from ensureconda.resolve import platform_subdir\n\n determined_subdir = platform_subdir()\n return platform == determined_subdir, determined_subdir\n\n\ndef do_validate_platform(lockfile: str) -> None:\n platform_lockfile = extract_platform(lockfile)\n try:\n success, platform_sys = _do_validate_platform(platform_lockfile)\n except KeyError:\n raise RuntimeError(f\"Unknown platform type in lockfile '{platform_lockfile}'.\")\n if not success:\n raise PlatformValidationError(\n f\"Platform in lockfile '{platform_lockfile}' is not compatible with system platform '{platform_sys}'.\"\n )\n\n\ndef do_conda_install(\n conda: PathLike, prefix: str, name: str, file: pathlib.Path\n) -> None:\n\n _conda = partial(_invoke_conda, conda, prefix, name, check_call=True)\n\n kind = \"env\" if file.name.endswith(\".yml\") else \"explicit\"\n\n if kind == \"explicit\":\n with open(file) as explicit_env:\n pip_requirements = [\n line.split(\"# pip \")[1]\n for line in explicit_env\n if line.startswith(\"# pip \")\n ]\n else:\n pip_requirements = []\n\n _conda(\n [\n *([\"env\"] if kind == \"env\" and not is_micromamba(conda) else []),\n \"create\",\n \"--file\",\n str(file),\n *([] if kind == \"env\" else [\"--yes\"]),\n ],\n )\n\n if not pip_requirements:\n return\n\n with temporary_file_with_contents(\"\\n\".join(pip_requirements)) as requirements_path:\n _conda([\"run\"], [\"pip\", \"install\", \"--no-deps\", \"-r\", str(requirements_path)])\n\n\ndef fn_to_dist_name(fn: str) -> str:\n if fn.endswith(\".conda\"):\n fn, _, _ = fn.partition(\".conda\")\n elif fn.endswith(\".tar.bz2\"):\n fn, _, _ = fn.partition(\".tar.bz2\")\n else:\n raise RuntimeError(f\"unexpected file type {fn}\", fn)\n return fn\n\n\ndef make_lock_spec(\n *,\n src_files: List[pathlib.Path],\n virtual_package_repo: FakeRepoData,\n channel_overrides: Optional[Sequence[str]] = None,\n platform_overrides: Optional[Sequence[str]] = None,\n required_categories: Optional[AbstractSet[str]] = None,\n) -> LockSpecification:\n \"\"\"Generate the lockfile specs from a set of input src_files. If required_categories is set filter out specs that do not match those\"\"\"\n lock_specs = parse_source_files(\n src_files=src_files, platform_overrides=platform_overrides or DEFAULT_PLATFORMS\n )\n\n lock_spec = aggregate_lock_specs(lock_specs)\n lock_spec.virtual_package_repo = virtual_package_repo\n lock_spec.channels = (\n [Channel.from_string(co) for co in channel_overrides]\n if channel_overrides\n else lock_spec.channels\n )\n lock_spec.platforms = (\n list(platform_overrides) if platform_overrides else lock_spec.platforms\n ) or list(DEFAULT_PLATFORMS)\n\n if required_categories is not None:\n\n def dep_has_category(d: Dependency, categories: AbstractSet[str]) -> bool:\n return d.category in categories\n\n lock_spec.dependencies = [\n d\n for d in lock_spec.dependencies\n if dep_has_category(d, categories=required_categories)\n ]\n\n return lock_spec\n\n\ndef make_lock_files(\n *,\n conda: PathLike,\n src_files: List[pathlib.Path],\n kinds: Sequence[TKindAll],\n lockfile_path: pathlib.Path = pathlib.Path(DEFAULT_LOCKFILE_NAME),\n platform_overrides: Optional[Sequence[str]] = None,\n channel_overrides: Optional[Sequence[str]] = None,\n virtual_package_spec: Optional[pathlib.Path] = None,\n update: Optional[List[str]] = None,\n include_dev_dependencies: bool = True,\n filename_template: Optional[str] = None,\n filter_categories: bool = True,\n extras: Optional[AbstractSet[str]] = None,\n check_input_hash: bool = False,\n) -> None:\n \"\"\"\n Generate a lock file from the src files provided\n\n Parameters\n ----------\n conda :\n Path to conda, mamba, or micromamba\n src_files :\n Files to parse requirements from\n kinds :\n Lockfile formats to output\n lockfile_path :\n Path to a conda-lock.yml to create or update\n platform_overrides :\n Platforms to solve for. Takes precedence over platforms found in src_files.\n channel_overrides :\n Channels to use. Takes precedence over channels found in src_files.\n virtual_package_spec :\n Path to a virtual package repository that defines each platform.\n update :\n Names of dependencies to update to their latest versions, regardless\n of whether the constraint in src_files has changed.\n include_dev_dependencies :\n Include development dependencies in explicit or env output\n filename_template :\n Format for names of rendered explicit or env files. Must include {platform}.\n extras :\n Include the given extras in explicit or env output\n filter_categories :\n Filter out unused categories prior to solving\n check_input_hash :\n Do not re-solve for each target platform for which specifications are unchanged\n \"\"\"\n\n # initialize virtual package fake\n if virtual_package_spec and virtual_package_spec.exists():\n virtual_package_repo = virtual_package_repo_from_specification(\n virtual_package_spec\n )\n else:\n virtual_package_repo = default_virtual_package_repodata()\n\n required_categories = {\"main\"}\n if include_dev_dependencies:\n required_categories.add(\"dev\")\n if extras is not None:\n required_categories.update(extras)\n\n with virtual_package_repo:\n lock_spec = make_lock_spec(\n src_files=src_files,\n channel_overrides=channel_overrides,\n platform_overrides=platform_overrides,\n virtual_package_repo=virtual_package_repo,\n required_categories=required_categories if filter_categories else None,\n )\n lock_content: Optional[Lockfile] = None\n\n platforms_to_lock: List[str] = []\n platforms_already_locked: List[str] = []\n if lockfile_path.exists():\n import yaml\n\n try:\n lock_content = parse_conda_lock_file(lockfile_path)\n except (yaml.error.YAMLError, FileNotFoundError):\n logger.warning(\n \"Failed to parse existing lock. Regenerating from scratch\"\n )\n lock_content = None\n else:\n lock_content = None\n\n if lock_content is not None:\n platforms_already_locked = list(lock_content.metadata.platforms)\n update_spec = UpdateSpecification(\n locked=lock_content.package, update=update\n )\n for platform in lock_spec.platforms:\n if (\n update\n or platform not in lock_content.metadata.platforms\n or not check_input_hash\n or lock_spec.content_hash_for_platform(platform)\n != lock_content.metadata.content_hash[platform]\n ):\n platforms_to_lock.append(platform)\n if platform in platforms_already_locked:\n platforms_already_locked.remove(platform)\n else:\n platforms_to_lock = lock_spec.platforms\n update_spec = UpdateSpecification()\n\n if platforms_already_locked:\n print(\n f\"Spec hash already locked for {sorted(platforms_already_locked)}. Skipping solve.\",\n file=sys.stderr,\n )\n platforms_to_lock = sorted(set(platforms_to_lock))\n\n if platforms_to_lock:\n print(f\"Locking dependencies for {platforms_to_lock}...\", file=sys.stderr)\n lock_content = lock_content | create_lockfile_from_spec(\n conda=conda,\n spec=lock_spec,\n platforms=platforms_to_lock,\n lockfile_path=lockfile_path,\n update_spec=update_spec,\n )\n\n if \"lock\" in kinds:\n write_conda_lock_file(lock_content, lockfile_path)\n print(\n \" - Install lock using:\",\n KIND_USE_TEXT[\"lock\"].format(lockfile=str(lockfile_path)),\n file=sys.stderr,\n )\n\n assert lock_content is not None\n\n do_render(\n lock_content,\n kinds=[k for k in kinds if k != \"lock\"],\n include_dev_dependencies=include_dev_dependencies,\n filename_template=filename_template,\n extras=extras,\n check_input_hash=check_input_hash,\n )\n\n\ndef do_render(\n lockfile: Lockfile,\n kinds: Sequence[Union[Literal[\"env\"], Literal[\"explicit\"]]],\n include_dev_dependencies: bool = True,\n filename_template: Optional[str] = None,\n extras: Optional[AbstractSet[str]] = None,\n check_input_hash: bool = False,\n override_platform: Optional[Sequence[str]] = None,\n) -> None:\n \"\"\"Render the lock content for each platform in lockfile\n\n Parameters\n ----------\n lockfile :\n Lock content\n kinds :\n Lockfile formats to render\n include_dev_dependencies :\n Include development dependencies in output\n filename_template :\n Format for the lock file names. Must include {platform}.\n extras :\n Include the given extras in output\n check_input_hash :\n Do not re-render if specifications are unchanged\n override_platform :\n Generate only this subset of the platform files\n \"\"\"\n platforms = lockfile.metadata.platforms\n if override_platform is not None and len(override_platform) > 0:\n platforms = list(sorted(set(platforms) & set(override_platform)))\n\n if filename_template:\n if \"{platform}\" not in filename_template and len(platforms) > 1:\n print(\n \"{platform} must be in filename template when locking\"\n f\" more than one platform: {', '.join(platforms)}\",\n file=sys.stderr,\n )\n sys.exit(1)\n for kind, file_ext in KIND_FILE_EXT.items():\n if file_ext and filename_template.endswith(file_ext):\n print(\n f\"Filename template must not end with '{file_ext}', as this \"\n f\"is reserved for '{kind}' lock files, in which case it is \"\n f\"automatically added.\"\n )\n sys.exit(1)\n\n for plat in platforms:\n for kind in kinds:\n if filename_template:\n context = {\n \"platform\": plat,\n \"dev-dependencies\": str(include_dev_dependencies).lower(),\n \"input-hash\": lockfile.metadata.content_hash,\n \"version\": pkg_resources.get_distribution(\"conda_lock\").version,\n \"timestamp\": datetime.datetime.utcnow().strftime(\"%Y%m%dT%H%M%SZ\"),\n }\n\n filename = filename_template.format(**context)\n else:\n filename = f\"conda-{plat}.lock\"\n\n if pathlib.Path(filename).exists() and check_input_hash:\n with open(filename) as f:\n previous_hash = extract_input_hash(f.read())\n if previous_hash == lockfile.metadata.content_hash.get(plat):\n print(\n f\"Lock content already rendered for {plat}. Skipping render of {filename}.\",\n file=sys.stderr,\n )\n continue\n\n print(f\"Rendering lockfile(s) for {plat}...\", file=sys.stderr)\n lockfile_contents = render_lockfile_for_platform(\n lockfile=lockfile,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n kind=kind,\n platform=plat,\n )\n\n filename += KIND_FILE_EXT[kind]\n with open(filename, \"w\") as fo:\n fo.write(\"\\n\".join(lockfile_contents) + \"\\n\")\n\n print(\n f\" - Install lock using {'(see warning below)' if kind == 'env' else ''}:\",\n KIND_USE_TEXT[kind].format(lockfile=filename),\n file=sys.stderr,\n )\n\n if \"env\" in kinds:\n print(\n \"\\nWARNING: Using environment lock files (*.yml) does NOT guarantee \"\n \"that generated environments will be identical over time, since the \"\n \"dependency resolver is re-run every time and changes in repository \"\n \"metadata or resolver logic may cause variation. Conversely, since \"\n \"the resolver is run every time, the resulting packages ARE \"\n \"guaranteed to be seen by conda as being in a consistent state. This \"\n \"makes them useful when updating existing environments.\",\n file=sys.stderr,\n )\n\n\ndef render_lockfile_for_platform( # noqa: C901\n *,\n lockfile: Lockfile,\n include_dev_dependencies: bool,\n extras: Optional[AbstractSet[str]],\n kind: Union[Literal[\"env\"], Literal[\"explicit\"]],\n platform: str,\n) -> List[str]:\n \"\"\"\n Render lock content into a single-platform lockfile that can be installed\n with conda.\n\n Parameters\n ----------\n lockfile :\n Locked package versions\n include_dev_dependencies :\n Include development dependencies in output\n extras :\n Optional dependency groups to include in output\n kind :\n Lockfile format (explicit or env)\n platform :\n Target platform\n\n \"\"\"\n lockfile_contents = [\n \"# Generated by conda-lock.\",\n f\"# platform: {platform}\",\n f\"# input_hash: {lockfile.metadata.content_hash.get(platform)}\\n\",\n ]\n\n categories = {\n \"main\",\n *(extras or []),\n *([\"dev\"] if include_dev_dependencies else []),\n }\n\n conda_deps: List[LockedDependency] = []\n pip_deps: List[LockedDependency] = []\n\n # ensure consistent ordering of generated file\n lockfile.toposort_inplace()\n\n for p in lockfile.package:\n if p.platform == platform and ((not p.optional) or (p.category in categories)):\n if p.manager == \"pip\":\n pip_deps.append(p)\n elif p.manager == \"conda\":\n # exclude virtual packages\n if not p.name.startswith(\"__\"):\n conda_deps.append(p)\n\n def format_pip_requirement(\n spec: LockedDependency, platform: str, direct: bool = False\n ) -> str:\n if spec.source and spec.source.type == \"url\":\n return f\"{spec.name} @ {spec.source.url}\"\n elif direct:\n s = f\"{spec.name} @ {spec.url}\"\n if spec.hash.sha256:\n s += f\"#sha256={spec.hash.sha256}\"\n return s\n else:\n s = f\"{spec.name} === {spec.version}\"\n if spec.hash.sha256:\n s += f\" --hash=sha256:{spec.hash.sha256}\"\n return s\n\n def format_conda_requirement(\n spec: LockedDependency, platform: str, direct: bool = False\n ) -> str:\n if direct:\n # inject the environment variables in here\n return posixpath.expandvars(f\"{spec.url}#{spec.hash.md5}\")\n else:\n path = pathlib.Path(urlsplit(spec.url).path)\n while path.suffix in {\".tar\", \".bz2\", \".gz\", \".conda\"}:\n path = path.with_suffix(\"\")\n build_string = path.name.split(\"-\")[-1]\n return f\"{spec.name}={spec.version}={build_string}\"\n\n if kind == \"env\":\n lockfile_contents.extend(\n [\n \"channels:\",\n *(\n f\" - {channel.env_replaced_url()}\"\n for channel in lockfile.metadata.channels\n ),\n \"dependencies:\",\n *(\n f\" - {format_conda_requirement(dep, platform, direct=False)}\"\n for dep in conda_deps\n ),\n ]\n )\n lockfile_contents.extend(\n [\n \" - pip:\",\n *(\n f\" - {format_pip_requirement(dep, platform, direct=False)}\"\n for dep in pip_deps\n ),\n ]\n if pip_deps\n else []\n )\n elif kind == \"explicit\":\n lockfile_contents.append(\"@EXPLICIT\\n\")\n\n lockfile_contents.extend(\n [format_conda_requirement(dep, platform, direct=True) for dep in conda_deps]\n )\n\n def sanitize_lockfile_line(line: str) -> str:\n line = line.strip()\n if line == \"\":\n return \"#\"\n else:\n return line\n\n lockfile_contents = [sanitize_lockfile_line(line) for line in lockfile_contents]\n\n # emit an explicit requirements.txt, prefixed with '# pip '\n lockfile_contents.extend(\n [\n f\"# pip {format_pip_requirement(dep, platform, direct=True)}\"\n for dep in pip_deps\n ]\n )\n else:\n raise ValueError(f\"Unrecognised lock kind {kind}.\")\n\n logging.debug(\"lockfile_contents:\\n%s\\n\", lockfile_contents)\n return lockfile_contents\n\n\ndef _solve_for_arch(\n conda: PathLike,\n spec: LockSpecification,\n platform: str,\n channels: List[Channel],\n update_spec: Optional[UpdateSpecification] = None,\n) -> List[LockedDependency]:\n \"\"\"\n Solve specification for a single platform\n \"\"\"\n if update_spec is None:\n update_spec = UpdateSpecification()\n # filter requested and locked dependencies to the current platform\n dependencies = [\n dep\n for dep in spec.dependencies\n if (not dep.selectors.platform) or platform in dep.selectors.platform\n ]\n locked = [dep for dep in update_spec.locked if dep.platform == platform]\n requested_deps_by_name = {\n manager: {dep.name: dep for dep in dependencies if dep.manager == manager}\n for manager in (\"conda\", \"pip\")\n }\n locked_deps_by_name = {\n manager: {dep.name: dep for dep in locked if dep.manager == manager}\n for manager in (\"conda\", \"pip\")\n }\n\n conda_deps = solve_conda(\n conda,\n specs=requested_deps_by_name[\"conda\"],\n locked=locked_deps_by_name[\"conda\"],\n update=update_spec.update,\n platform=platform,\n channels=channels,\n )\n\n if requested_deps_by_name[\"pip\"]:\n if not PIP_SUPPORT:\n raise ValueError(\"pip support is not enabled\")\n if \"python\" not in conda_deps:\n raise ValueError(\"Got pip specs without Python\")\n pip_deps = solve_pypi(\n requested_deps_by_name[\"pip\"],\n use_latest=update_spec.update,\n pip_locked={\n dep.name: dep for dep in update_spec.locked if dep.manager == \"pip\"\n },\n conda_locked={dep.name: dep for dep in conda_deps.values()},\n python_version=conda_deps[\"python\"].version,\n platform=platform,\n )\n else:\n pip_deps = {}\n\n return list(conda_deps.values()) + list(pip_deps.values())\n\n\ndef create_lockfile_from_spec(\n *,\n conda: PathLike,\n spec: LockSpecification,\n platforms: List[str] = [],\n lockfile_path: pathlib.Path,\n update_spec: Optional[UpdateSpecification] = None,\n) -> Lockfile:\n \"\"\"\n Solve or update specification\n \"\"\"\n assert spec.virtual_package_repo is not None\n virtual_package_channel = spec.virtual_package_repo.channel\n\n locked: Dict[Tuple[str, str, str], LockedDependency] = {}\n\n for platform in platforms or spec.platforms:\n\n deps = _solve_for_arch(\n conda=conda,\n spec=spec,\n platform=platform,\n channels=[*spec.channels, virtual_package_channel],\n update_spec=update_spec,\n )\n\n for dep in deps:\n locked[(dep.manager, dep.name, dep.platform)] = dep\n\n return Lockfile(\n package=[locked[k] for k in locked],\n metadata=LockMeta(\n content_hash=spec.content_hash(),\n channels=[c for c in spec.channels],\n platforms=spec.platforms,\n sources=[str(source.resolve()) for source in spec.sources],\n ),\n )\n\n\ndef parse_source_files(\n src_files: List[pathlib.Path],\n platform_overrides: Sequence[str],\n) -> List[LockSpecification]:\n \"\"\"\n Parse a sequence of dependency specifications from source files\n\n Parameters\n ----------\n src_files :\n Files to parse for dependencies\n platform_overrides :\n Target platforms to render meta.yaml files for\n \"\"\"\n desired_envs: List[LockSpecification] = []\n for src_file in src_files:\n if src_file.name == \"meta.yaml\":\n desired_envs.append(\n parse_meta_yaml_file(src_file, list(platform_overrides))\n )\n elif src_file.name == \"pyproject.toml\":\n desired_envs.append(parse_pyproject_toml(src_file))\n else:\n desired_envs.append(\n parse_environment_file(src_file, pip_support=PIP_SUPPORT)\n )\n return desired_envs\n\n\ndef _add_auth_to_line(line: str, auth: Dict[str, str]) -> str:\n matching_auths = [a for a in auth if a in line]\n if not matching_auths:\n return line\n # If we have multiple matching auths, we choose the longest one.\n matching_auth = max(matching_auths, key=len)\n replacement = f\"{auth[matching_auth]}@{matching_auth}\"\n return line.replace(matching_auth, replacement)\n\n\ndef _add_auth_to_lockfile(lockfile: str, auth: Dict[str, str]) -> str:\n lockfile_with_auth = \"\\n\".join(\n _add_auth_to_line(line, auth) if line[0] not in (\"#\", \"@\") else line\n for line in lockfile.strip().split(\"\\n\")\n )\n if lockfile.endswith(\"\\n\"):\n return lockfile_with_auth + \"\\n\"\n return lockfile_with_auth\n\n\n@contextmanager\ndef _add_auth(lockfile: str, auth: Dict[str, str]) -> Iterator[pathlib.Path]:\n lockfile_with_auth = _add_auth_to_lockfile(lockfile, auth)\n with temporary_file_with_contents(lockfile_with_auth) as path:\n yield path\n\n\ndef _strip_auth_from_line(line: str) -> str:\n return AUTH_PATTERN.sub(r\"\\1\\3\", line)\n\n\ndef _extract_domain(line: str) -> str:\n return DOMAIN_PATTERN.sub(r\"\\2\", line)\n\n\ndef _strip_auth_from_lockfile(lockfile: str) -> str:\n lockfile_lines = lockfile.strip().split(\"\\n\")\n stripped_lockfile_lines = tuple(\n _strip_auth_from_line(line) if line[0] not in (\"#\", \"@\") else line\n for line in lockfile_lines\n )\n stripped_domains = sorted(\n {\n _extract_domain(stripped_line)\n for line, stripped_line in zip(lockfile_lines, stripped_lockfile_lines)\n if line != stripped_line\n }\n )\n stripped_lockfile = \"\\n\".join(stripped_lockfile_lines)\n if lockfile.endswith(\"\\n\"):\n stripped_lockfile += \"\\n\"\n if stripped_domains:\n stripped_domains_doc = \"\\n\".join(f\"# - {domain}\" for domain in stripped_domains)\n return f\"# The following domains require authentication:\\n{stripped_domains_doc}\\n{stripped_lockfile}\"\n return stripped_lockfile\n\n\n@contextmanager\ndef _render_lockfile_for_install(\n filename: pathlib.Path,\n include_dev_dependencies: bool = True,\n extras: Optional[AbstractSet[str]] = None,\n) -> Iterator[pathlib.Path]:\n \"\"\"\n Render lock content into a temporary, explicit lockfile for the current platform\n\n Parameters\n ----------\n filename :\n Path to conda-lock.yml\n include_dev_dependencies :\n Include development dependencies in output\n extras :\n Optional dependency groups to include in output\n\n \"\"\"\n\n if not filename.name.endswith(DEFAULT_LOCKFILE_NAME):\n yield filename\n return\n\n from ensureconda.resolve import platform_subdir\n\n lock_content = parse_conda_lock_file(pathlib.Path(filename))\n\n platform = platform_subdir()\n if platform not in lock_content.metadata.platforms:\n raise PlatformValidationError(\n f\"Dependencies are not locked for the current platform ({platform})\"\n )\n\n # TODO: Move to LockFile\n required_env_vars: Set[str] = set()\n for channel in lock_content.metadata.channels:\n required_env_vars.update(channel.used_env_vars)\n existing_env_vars = {k for k, v in os.environ.items() if v}\n missing_env_vars = required_env_vars - existing_env_vars\n if missing_env_vars:\n msg = \", \".join(sorted(missing_env_vars))\n raise MissingEnvVarError(\n f\"Cannot run render lockfile. Missing environment variables: {msg}\"\n )\n\n content = render_lockfile_for_platform(\n lockfile=lock_content,\n kind=\"explicit\",\n platform=platform,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n )\n with temporary_file_with_contents(\"\\n\".join(content) + \"\\n\") as path:\n yield path\n\n\ndef run_lock(\n environment_files: List[pathlib.Path],\n *,\n conda_exe: Optional[str],\n platforms: Optional[List[str]] = None,\n mamba: bool = False,\n micromamba: bool = False,\n include_dev_dependencies: bool = True,\n channel_overrides: Optional[Sequence[str]] = None,\n filename_template: Optional[str] = None,\n kinds: Optional[Sequence[TKindAll]] = None,\n lockfile_path: pathlib.Path = pathlib.Path(DEFAULT_LOCKFILE_NAME),\n check_input_hash: bool = False,\n extras: Optional[AbstractSet[str]] = None,\n virtual_package_spec: Optional[pathlib.Path] = None,\n update: Optional[List[str]] = None,\n filter_categories: bool = False,\n) -> None:\n if environment_files == DEFAULT_FILES:\n if lockfile_path.exists():\n lock_content = parse_conda_lock_file(lockfile_path)\n # reconstruct native paths\n locked_environment_files = [\n pathlib.Path(\n pathlib.PurePosixPath(lockfile_path).parent\n / pathlib.PurePosixPath(p)\n )\n for p in lock_content.metadata.sources\n ]\n if all(p.exists() for p in locked_environment_files):\n environment_files = locked_environment_files\n else:\n missing = [p for p in locked_environment_files if not p.exists()]\n print(\n f\"{lockfile_path} was created from {[str(p) for p in locked_environment_files]},\"\n f\" but some files ({[str(p) for p in missing]}) do not exist. Falling back to\"\n f\" {[str(p) for p in environment_files]}.\",\n file=sys.stderr,\n )\n else:\n long_ext_file = pathlib.Path(\"environment.yaml\")\n if long_ext_file.exists() and not environment_files[0].exists():\n environment_files = [long_ext_file]\n\n _conda_exe = determine_conda_executable(\n conda_exe, mamba=mamba, micromamba=micromamba\n )\n make_lock_files(\n conda=_conda_exe,\n src_files=environment_files,\n platform_overrides=platforms,\n channel_overrides=channel_overrides,\n virtual_package_spec=virtual_package_spec,\n update=update,\n kinds=kinds or DEFAULT_KINDS,\n lockfile_path=lockfile_path,\n filename_template=filename_template,\n include_dev_dependencies=include_dev_dependencies,\n extras=extras,\n check_input_hash=check_input_hash,\n filter_categories=filter_categories,\n )\n\n\n@click.group(cls=OrderedGroup, default=\"lock\", default_if_no_args=True)\ndef main() -> None:\n \"\"\"To get help for subcommands, use the conda-lock --help\"\"\"\n pass\n\n\nTLogLevel = Union[\n Literal[\"DEBUG\"],\n Literal[\"INFO\"],\n Literal[\"WARNING\"],\n Literal[\"ERROR\"],\n Literal[\"CRITICAL\"],\n]\n\n\n@main.command(\"lock\")\n@click.option(\n \"--conda\", default=None, help=\"path (or name) of the conda/mamba executable to use.\"\n)\n@click.option(\n \"--mamba/--no-mamba\",\n default=HAVE_MAMBA,\n help=\"don't attempt to use or install mamba.\",\n)\n@click.option(\n \"--micromamba/--no-micromamba\",\n default=False,\n help=\"don't attempt to use or install micromamba.\",\n)\n@click.option(\n \"-p\",\n \"--platform\",\n multiple=True,\n help=\"generate lock files for the following platforms\",\n)\n@click.option(\n \"-c\",\n \"--channel\",\n \"channel_overrides\",\n multiple=True,\n help=\"\"\"Override the channels to use when solving the environment. These will replace the channels as listed in the various source files.\"\"\",\n)\n@click.option(\n \"--dev-dependencies/--no-dev-dependencies\",\n is_flag=True,\n default=True,\n help=\"include dev dependencies in the lockfile (where applicable)\",\n)\n@click.option(\n \"-f\",\n \"--file\",\n \"files\",\n default=DEFAULT_FILES,\n type=click.Path(),\n multiple=True,\n help=\"path to a conda environment specification(s)\",\n)\n@click.option(\n \"-k\",\n \"--kind\",\n default=[\"lock\"],\n type=str,\n multiple=True,\n help=\"Kind of lock file(s) to generate [should be one of 'lock', 'explicit', or 'env'].\",\n)\n@click.option(\n \"--filename-template\",\n default=\"conda-{platform}.lock\",\n help=\"Template for single-platform (explicit, env) lock file names. Filename must include {platform} token, and must not end in '.yml'. For a full list and description of available tokens, see the command help text.\",\n)\n@click.option(\n \"--lockfile\",\n default=DEFAULT_LOCKFILE_NAME,\n help=\"Path to a conda-lock.yml to create or update\",\n)\n@click.option(\n \"--strip-auth\",\n is_flag=True,\n default=False,\n help=\"Strip the basic auth credentials from the lockfile.\",\n)\n@click.option(\n \"-e\",\n \"--extras\",\n \"--category\",\n default=[],\n type=str,\n multiple=True,\n help=\"When used in conjunction with input sources that support extras/categories (pyproject.toml) will add the deps from those extras to the render specification\",\n)\n@click.option(\n \"--filter-categories\",\n \"--filter-extras\",\n is_flag=True,\n default=False,\n help=\"In conjunction with extras this will prune out dependencies that do not have the extras specified when loading files.\",\n)\n@click.option(\n \"--check-input-hash\",\n is_flag=True,\n default=False,\n help=\"Check existing input hashes in lockfiles before regenerating lock files. If no files were updated exit with exit code 4. Incompatible with --strip-auth\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--pdb\", is_flag=True, help=\"Drop into a postmortem debugger if conda-lock crashes\"\n)\n@click.option(\n \"--virtual-package-spec\",\n type=click.Path(),\n help=\"Specify a set of virtual packages to use.\",\n)\n@click.option(\n \"--update\",\n multiple=True,\n help=\"Packages to update to their latest versions. If empty, update all.\",\n)\n@click.pass_context\ndef lock(\n ctx: click.Context,\n conda: Optional[PathLike],\n mamba: bool,\n micromamba: bool,\n platform: List[str],\n channel_overrides: List[str],\n dev_dependencies: bool,\n files: List[pathlib.Path],\n kind: List[Union[Literal[\"lock\"], Literal[\"env\"], Literal[\"explicit\"]]],\n filename_template: str,\n lockfile: PathLike,\n strip_auth: bool,\n extras: List[str],\n filter_categories: bool,\n check_input_hash: bool,\n log_level: TLogLevel,\n pdb: bool,\n virtual_package_spec: Optional[PathLike],\n update: Optional[List[str]] = None,\n) -> None:\n \"\"\"Generate fully reproducible lock files for conda environments.\n\n By default, the lock files are written to conda-{platform}.lock. These filenames can be customized using the\n --filename-template argument. The following tokens are available:\n\n \\b\n platform: The platform this lock file was generated for (conda subdir).\n dev-dependencies: Whether or not dev dependencies are included in this lock file.\n input-hash: A sha256 hash of the lock file input specification.\n version: The version of conda-lock used to generate this lock file.\n timestamp: The approximate timestamp of the output file in ISO8601 basic format.\n \"\"\"\n logging.basicConfig(level=log_level)\n\n # bail out if we do not encounter the default file if no files were passed\n if ctx.get_parameter_source(\"files\") == click.core.ParameterSource.DEFAULT:\n candidates = list(files)\n candidates += [f.with_name(f.name.replace(\".yml\", \".yaml\")) for f in candidates]\n for f in candidates:\n if f.exists():\n break\n else:\n print(ctx.get_help())\n sys.exit(1)\n\n if pdb:\n sys.excepthook = _handle_exception_post_mortem\n\n if not virtual_package_spec:\n candidates = [\n pathlib.Path(\"virtual-packages.yml\"),\n pathlib.Path(\"virtual-packages.yaml\"),\n ]\n for c in candidates:\n if c.exists():\n logger.info(\"Using virtual packages from %s\", c)\n virtual_package_spec = c\n break\n else:\n virtual_package_spec = pathlib.Path(virtual_package_spec)\n\n files = [pathlib.Path(file) for file in files]\n extras_ = set(extras)\n lock_func = partial(\n run_lock,\n environment_files=files,\n conda_exe=conda,\n platforms=platform,\n mamba=mamba,\n micromamba=micromamba,\n include_dev_dependencies=dev_dependencies,\n channel_overrides=channel_overrides,\n kinds=kind,\n lockfile_path=pathlib.Path(lockfile),\n extras=extras_,\n virtual_package_spec=virtual_package_spec,\n update=update,\n filter_categories=filter_categories,\n )\n if strip_auth:\n with tempfile.TemporaryDirectory() as tempdir:\n filename_template_temp = f\"{tempdir}/{filename_template.split('/')[-1]}\"\n lock_func(filename_template=filename_template_temp)\n filename_template_dir = \"/\".join(filename_template.split(\"/\")[:-1])\n for file in os.listdir(tempdir):\n lockfile = read_file(os.path.join(tempdir, file))\n lockfile = _strip_auth_from_lockfile(lockfile)\n write_file(lockfile, os.path.join(filename_template_dir, file))\n else:\n lock_func(\n filename_template=filename_template, check_input_hash=check_input_hash\n )\n\n\n@main.command(\"install\")\n@click.option(\n \"--conda\", default=None, help=\"path (or name) of the conda/mamba executable to use.\"\n)\n@click.option(\n \"--mamba/--no-mamba\",\n default=HAVE_MAMBA,\n help=\"don't attempt to use or install mamba.\",\n)\n@click.option(\n \"--micromamba/--no-micromamba\",\n default=False,\n help=\"don't attempt to use or install micromamba.\",\n)\n@click.option(\"-p\", \"--prefix\", help=\"Full path to environment location (i.e. prefix).\")\n@click.option(\"-n\", \"--name\", help=\"Name of environment.\")\n@click.option(\n \"--auth\",\n help=\"The auth file provided as string. Has precedence over `--auth-file`.\",\n default=\"\",\n)\n@click.option(\"--auth-file\", help=\"Path to the authentication file.\", default=\"\")\n@click.option(\n \"--validate-platform/--no-validate-platform\",\n default=True,\n help=\"Whether the platform compatibility between your lockfile and the host system should be validated.\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--dev/--no-dev\",\n is_flag=True,\n default=True,\n help=\"install dev dependencies from the lockfile (where applicable)\",\n)\n@click.option(\n \"-E\",\n \"--extras\",\n multiple=True,\n default=[],\n help=\"include extra dependencies from the lockfile (where applicable)\",\n)\n@click.argument(\n \"lock-file\", default=pathlib.Path(DEFAULT_LOCKFILE_NAME), type=click.Path()\n)\n@click.pass_context\ndef install(\n ctx: click.Context,\n conda: Optional[str],\n mamba: bool,\n micromamba: bool,\n prefix: Optional[str],\n name: Optional[str],\n lock_file: pathlib.Path,\n auth: Optional[str],\n auth_file: Optional[PathLike],\n validate_platform: bool,\n log_level: TLogLevel,\n dev: bool,\n extras: List[str],\n) -> None:\n # bail out if we do not encounter the lockfile\n lock_file = pathlib.Path(lock_file)\n if not lock_file.exists():\n print(ctx.get_help())\n sys.exit(1)\n\n \"\"\"Perform a conda install\"\"\"\n logging.basicConfig(level=log_level)\n _auth = (\n yaml.safe_load(auth) if auth else read_json(auth_file) if auth_file else None\n )\n _conda_exe = determine_conda_executable(conda, mamba=mamba, micromamba=micromamba)\n install_func = partial(do_conda_install, conda=_conda_exe, prefix=prefix, name=name)\n if validate_platform and not lock_file.name.endswith(DEFAULT_LOCKFILE_NAME):\n lockfile_contents = read_file(lock_file)\n try:\n do_validate_platform(lockfile_contents)\n except PlatformValidationError as error:\n raise PlatformValidationError(\n error.args[0] + \" Disable validation with `--no-validate-platform`.\"\n )\n with _render_lockfile_for_install(\n lock_file, include_dev_dependencies=dev, extras=set(extras)\n ) as lockfile:\n if auth:\n with _add_auth(read_file(lockfile), _auth) as lockfile_with_auth:\n install_func(file=lockfile_with_auth)\n else:\n install_func(file=lockfile)\n\n\n@main.command(\"render\")\n@click.option(\n \"--dev-dependencies/--no-dev-dependencies\",\n is_flag=True,\n default=True,\n help=\"include dev dependencies in the lockfile (where applicable)\",\n)\n@click.option(\n \"-k\",\n \"--kind\",\n default=[\"explicit\"],\n type=click.Choice([\"explicit\", \"env\"]),\n multiple=True,\n help=\"Kind of lock file(s) to generate.\",\n)\n@click.option(\n \"--filename-template\",\n default=\"conda-{platform}.lock\",\n help=\"Template for the lock file names. Filename must include {platform} token, and must not end in '.yml'. For a full list and description of available tokens, see the command help text.\",\n)\n@click.option(\n \"-e\",\n \"--extras\",\n default=[],\n type=str,\n multiple=True,\n help=\"When used in conjunction with input sources that support extras (pyproject.toml) will add the deps from those extras to the input specification\",\n)\n@click.option(\n \"--log-level\",\n help=\"Log level.\",\n default=\"INFO\",\n type=click.Choice([\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"]),\n)\n@click.option(\n \"--pdb\", is_flag=True, help=\"Drop into a postmortem debugger if conda-lock crashes\"\n)\n@click.option(\n \"-p\",\n \"--platform\",\n multiple=True,\n help=\"render lock files for the following platforms\",\n)\n@click.argument(\"lock-file\", default=DEFAULT_LOCKFILE_NAME)\n@click.pass_context\ndef render(\n ctx: click.Context,\n dev_dependencies: bool,\n kind: Sequence[Union[Literal[\"env\"], Literal[\"explicit\"]]],\n filename_template: str,\n extras: List[str],\n log_level: TLogLevel,\n lock_file: PathLike,\n pdb: bool,\n platform: Sequence[str],\n) -> None:\n \"\"\"Render multi-platform lockfile into single-platform env or explicit file\"\"\"\n logging.basicConfig(level=log_level)\n\n if pdb:\n sys.excepthook = _handle_exception_post_mortem\n\n # bail out if we do not encounter the lockfile\n lock_file = pathlib.Path(lock_file)\n if not lock_file.exists():\n print(ctx.get_help())\n sys.exit(1)\n\n lock_content = parse_conda_lock_file(lock_file)\n\n do_render(\n lock_content,\n filename_template=filename_template,\n kinds=kind,\n include_dev_dependencies=dev_dependencies,\n extras=set(extras),\n override_platform=platform,\n )\n\n\ndef _handle_exception_post_mortem(\n exc_type: Type[BaseException],\n exc_value: BaseException,\n exc_traceback: Optional[TracebackType],\n) -> Any:\n import pdb\n\n pdb.post_mortem(exc_traceback)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"conda_lock/conda_lock.py","file_name":"conda_lock.py","file_ext":"py","file_size_in_byte":44368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"265473155","text":"import networkx as nx\nimport matplotlib.pyplot as pb\n\nclass Move:\n\n def __init__(self):\n self.end_search = False\n self.visited = []\n\n def greedy(self, graph, start, destination):\n queue = []\n queue.append(start)\n self.visited.append(start)\n print(f'Starting point -> {start}')\n\n while len(queue) > 0 and not self.end_search:\n min_stld = 99999\n min_child = {}\n\n current_node = queue.pop(0)\n\n for child in list(graph.adj[current_node]):\n if child is destination:\n print(f'Destination -> {child}')\n self.end_search = True\n self.visited.append(child)\n break\n else:\n if hlsd_mapping[child] < min_stld:\n min_stld = hlsd_mapping[child]\n min_child = child\n self.visited.append(child)\n \n\n if(not self.end_search): \n queue.append(min_child)\n print(f'Next item -> {min_child}')\n return self.visited\n \n \n def ucs(self, G, start, destination): \n queue = []\n queue.append(start)\n\n self.visited = []\n self.end_search = False\n \n self.visited.append(start)\n\n print(f'Starting point -> {start}')\n\n while len(queue) > 0 and not self.end_search:\n current_node = queue.pop(0)\n max_dist = 99999\n min_child = \"\"\n\n if current_node is destination:\n print(f'Destination -> {current_node}')\n self.end_search = True\n self.visited.append(current_node)\n break\n \n for child in list(G.adj[current_node]):\n if current_node + child and child + current_node not in self.visited:\n w = G[current_node][child][\"weight\"]\n if w < max_dist:\n max_dist = w\n min_child = child\n self.visited.append(current_node + child) \n if(not self.end_search): \n queue.append(min_child)\n print(f'Next item -> {min_child}')\n return self.visited\n\nG = nx.Graph()\n\nE = [(\"Sports Complex\", \"Siwaka\", {\"weight\": 450}), (\"Siwaka\", \"Phase 1B\", {\"weight\" : 230}), (\"Siwaka\", \"Phase 1A\", {\"weight\" : 10}), (\"Phase 1B\", \"Phase 2\", {\"weight\": 112}), (\"Phase 1A\", \"Phase 1B\", {\"weight\": 100}), (\"Phase 1B\", \"STC\", {\"weight\" : 50}), (\"Phase 1A\", \"Phase 1B\", {\"weight\" : 100}), (\"Phase 1A\", \"Madaraka\", {\"weight\": 850}), (\"STC\", \"Parking Lot\", {\"weight\": 250}), (\"STC\", \"Phase 2\", {\"weight\": 50}), (\"Phase 2\", \"J1\", {\"weight\": 600}), (\"Phase 2\", \"Phase 3\", {\"weight\": 500}), (\"J1\", \"Madaraka\", {\"weight\": 200}), (\"Madaraka\", \"Parking Lot\", {\"weight\": 700 }), (\"Phase 3\", \"Parking Lot\", {\"weight\": 350})]\n\n\nN = [\"Sports Complex\", \"Siwaka\", \"Phase 1A\", \"Phase 1B\", \"STC\", \"Phase 2\", \"Parking Lot\", \"Phase 3\", \"J1\", \"Madaraka\"]\n\n\nC = [(0, 10), (10, 10), (20, 10), (10, 5), (10, 2), (20, 5), (30, 0), (30, 3), (30, 5), (40, 5)]\n\nhlsd = [730, 405, 380, 280, 213, 210, 0, 160, 500, 630]\n\nP = { N[i] : v for i, v in enumerate(C) }\nhlsd_mapping = { N[i] : v for i, v in enumerate(hlsd) }\n\nG.add_nodes_from(N)\nG.add_edges_from(E)\n\nfor k, l in P.items():\n G.nodes[k]['position'] = l\n\nprint(G[\"Sports Complex\"][\"Siwaka\"][\"weight\"])\n\nt1 = Move()\nprint('Greedy Breadth First Search:')\nprint(t1.greedy(G, \"Sports Complex\", \"Parking Lot\"))\nprint('\\nEnd')\n\n\nt2 = Move()\nprint('Uniform Cost Search:')\nprint(t2.ucs(G, \"Sports Complex\", \"Parking Lot\"))\nprint('\\nEnd')\n\n\npositions = nx.get_node_attributes(G, 'position')\nlabels = nx.get_edge_attributes(G, 'weight')\n\n\nnx.draw_networkx(G, positions, node_size = 350)\nnx.draw_networkx_edges(G, positions)\nnx.draw_networkx_edge_labels(G, positions, edge_labels = labels)\npb.axis('off')\npb.show()","sub_path":"walk_rob.py","file_name":"walk_rob.py","file_ext":"py","file_size_in_byte":4065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"651841289","text":"# -*- coding: utf-8 -*-\nfrom numpy import modf\n\nfrom color import Color\nfrom component import Component\nfrom componenttypes import TYPE_SIM_CONTINUOUS\nfrom lib.pseqt import * # @UnusedWildImport\nfrom terminal import TERM\n\n\nclass GenConst(Component):\n \"\"\"!\n @if English\n\n @endif\n\n @if Slovak\n\n Zdroj konštantnej hodnoty typu INT alebo FLOAT.\n\n @endif\n \"\"\"\n\n def __init__(self, name, pos):\n Component.__init__(self, name, pos)\n\n self.compType = TYPE_SIM_CONTINUOUS\n self.box = QRectF(-30, -15, 60, 30)\n self.shapeColor = Color.black\n self.addTerminal('OUT', 1, TERM.OUT, QPointF(30, 0), TERM.DIR_EAST, TERM.OUT_ARROW_SMALL_FILL, TERM.OUT_ARROW_SMALL)\n\n self.addParameter('Value', 1.0)\n\n def drawShape(self, gc):\n grad = QLinearGradient(0, -10, 0, 20)\n grad.setColorAt(0, Color.white)\n grad.setColorAt(1, Color.green)\n gc.setBrush(QBrush(grad))\n\n gc.setPen(QPen(self.shapeColor, 1))\n gc.drawRoundedRect(-25, -10, 50, 20, 5, 5)\n\n value = self.parameter['Value'].value\n # uprava zobrazenia celocisenych udajov bez desatinnej casti\n if type(value) == float:\n if modf(value)[0] == 0.0:\n s = str(int(value))\n else:\n s = str(value)\n\n self.font = QFont('Decorative', 10)\n fm = QFontMetrics(self.font)\n # urcenie rozmerov textu a centrovanie vzhladom\n # tw = fm.width(s)\t # k zadanej polohe referencneho bodu\n th = fm.height()\n\n qr = QRectF(-25, -th / 2, 50, th)\n gc.drawText(qr, Qt.AlignCenter, s)\n\n def sim(self, flag, value, time, step):\n self.terminal[1].value = self.parameter['Value'].value\n","sub_path":"src/lib/sources/gen_const.py","file_name":"gen_const.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"447979549","text":"import numpy as np\nimport math\nimport json\nimport cv2\n\ndef openposeCoG(jsonFilePath):\n #傾き\n def inclination(x1,y1,x2,y2):\n return (y2-y1)/(x2-x1)\n #切片\n def intercept(d,x,y):\n return y-d*x\n #2直線の交点x座標\n def intersection(d1,b1,d2,b2):\n return (b2-b1)/(d1-d2)\n\n #重心座標\n cogs = list()\n #json読み取り\n j = open(jsonFilePath, 'r')\n json_dict = json.load(j)\n\n\n\n #関節位置配列\n #対応位置はopenpose.pngを参照\n #[x座標,y座標,信頼度]\n P = list()\n\n #必要なデータを抜き取る\n for i, kpt in enumerate(json_dict['keypoint']):\n P.append([kpt[0],kpt[1]])\n #信頼度を追加\n P[i].append(kpt[2])\n # #値チェック\n # for i, p in enumerate(P):\n # print(i,p)\n #足元----------\n #足先2点の中点\n f0 = [(P[13][0]+P[10][0])/2, (P[13][1]+P[10][1])/2]\n\n #足先2点の直線f0\n #傾き\n d0 = inclination(P[10][0],P[10][1],P[13][0],P[13][1])\n #切片\n b0 = intercept(d0,P[13][0],P[13][1])\n\n #fに直交する傾き\n dd0 = -1*(1/d0)\n\n #膝2点の中点を通りfに直行する直線f1\n #切片\n b1 = intercept(dd0, (P[12][0]+P[9][0])/2, (P[12][1]+P[9][1])/2)\n #fとの交点f1\n f1 = [intersection(d0,b0,dd0,b1)]\n f1.append(dd0*f1[0]+b1)\n\n #腰2点の中点を通りfに直行する直線f2\n #切片\n b2 = intercept(dd0, (P[11][0]+P[8][0])/2, (P[11][1]+P[8][1])/2)\n #fとの交点f2\n f2 = [intersection(d0,b0,dd0,b2)]\n f2.append(dd0*f2[0]+b2)\n\n #f,f1,f2の重心点under\n under = [(f0[0]+f1[0]+f2[0])/3, (f0[1]+f1[1]+f2[1])/3]\n # if math.isnan(under[0]) or math.isnan(under[1]):\n # continue;\n #足元---------\n\n #頭----------\n centerID = 0\n if not (P[16][0] == 0 or P[16][1] == 0 or P[17][0] == 0 or P[17][1] == 0):\n #右耳と左耳の中点\n center = [(P[16][0]+P[17][0])/2, (P[16][1]+P[17][1])/2]\n centerID = 1\n else:\n # 鼻と首の中点\n center = [(P[0][0]+P[1][0])/2, (P[0][1]+P[1][1])/2]\n centerID = 2\n #underからcenterへの直線f3\n #傾き\n d3 = inclination(center[0],center[1],under[0],under[1])\n #切片\n b3 = intercept(d3,center[0],center[1])\n\n #f3に直交する傾き\n dd3 = -1*(1/d3)\n\n #首を通りf3に直交する直線f4\n #切片\n b4 = intercept(dd3, P[1][0], P[1][1])\n #f3との交点\n f4 = [intersection(d3, b3, dd3, b4)]\n f4.append(dd3*f4[0]+b4)\n #ベクトルを生成\n f4v = np.array([f4[0], f4[1]])\n\n if centerID == 1:\n #f3とf4の交点とcenterの距離\n l = np.linalg.norm(center-f4v)\n else:\n #鼻を通りf3に直交する直線f5\n #切片\n b5 = intercept(dd3, P[0][0], P[0][1])\n #f3との交点\n f5 = [intersection(d3, b3, dd3, b5)]\n f5.append(dd3 * f5[0] + b5)\n #ベクトルを生成\n f5v = np.array([f5[0], f5[1]])\n\n #f3とf4の交点とf3とf5の交点の距離\n l = np.linalg.norm(f5v-f4v)\n\n #underからcenterへの単位ベクトルuを生成\n #underからcenterへのベクトルv\n v = np.array([center[0]-under[0],center[1]-under[1]])\n #正規化\n u = v / np.linalg.norm(v)\n\n #f3とf4の交点からベクトルuの向きにlを2倍伸ばした座標の点top\n top = [f4[0] + u[0]*l*2, f4[1] + u[1]*l*2]\n # if math.isnan(top[0]) or math.isnan(top[1]):\n # continue;\n #頭----------\n\n #underからtopへのベクトル\n utvec = np.array([top[0]-under[0],top[1]-under[1]])\n #重心点\n cog__ = [under[0] + utvec[0]*0.6, under[1] + utvec[1]*0.6]\n\n cog_ = list()\n #重心の座標をappend\n cog_.append(cog__[0])\n cog_.append(cog__[1])\n #足元基準点の座標をappend\n cog_.append(under[0])\n cog_.append(under[1])\n #頭部基準点の座標をappend\n cog_.append(top[0])\n cog_.append(top[1])\n #右手の座標をappend\n cog_.append(P[4][0])\n cog_.append(P[4][1])\n #左手の座標をappend\n cog_.append(P[7][0])\n cog_.append(P[7][1])\n #首の座標をappend\n cog_.append(P[1][0])\n cog_.append(P[1][1])\n #信頼度の合計をappend\n cog_.append(np.sum(P,0)[2])\n cogs.append(cog_)\n\n\n # #要点確認\n # img = cv2.imread('./resource/wally000024_resize_rendered.png')\n # img = cv2.circle(img, (int(center[0]), int(center[1])), 10, (0,0,255), -1)\n # img = cv2.circle(img, (int(top[0]), int(top[1])), 10, (0,100,100), -1)\n # img = cv2.circle(img, (int(under[0]), int(under[1])), 10, (100,100,0), -1)\n # img = cv2.circle(img, (int(cog_[0]), int(cog_[1])), 10, (100,100,100), -1)\n # cv2.imshow('test', img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n #\n # #画像出力\n # print(\"save this image?\")\n # save = input(\"0,1 or n >> \")\n # if save == '0' or save == '1':\n # cv2.imwrite(\"./output/024_\"+save+\".png\", img)\n\n # #値の確認\n # print(\"under:\",under[0], under[1])\n # print(\"top:\",top[0], top[1])\n # print(\"cog\", cog[0], cog[1])\n # print(cogs)\n cog = cogs[np.argmax(cogs, 0)[2]]\n return cog\n\nif __name__ == '__main__':\n print('view', openposeCoG('./resource/re18_keypoints.json'))\n","sub_path":"programs/test/cog/cog.py","file_name":"cog.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"301788579","text":"from dolfin import *\nimport numpy as np\n\nmesh_file = UnitSquareMesh(10, 10)\n#mesh_file = refine(mesh_file)\n#Parameters for each numerical case\ncommon = {\"mesh\": mesh_file,\n \"v_deg\": 2, #Velocity degree\n \"p_deg\": 1, #Pressure degree\n \"d_deg\": 2, #Deformation degree\n \"T\": 1E-4, # End time\n \"dt\": 1E-5, # Time step\n \"rho_f\": 1.0, #\n \"mu_f\": 1.,\n \"rho_s\" : Constant(1.0),\n \"mu_s\" : Constant(1.0),\n \"nu_s\" : Constant(1.0)\n }\n\nvars().update(common)\nlamda_s = nu_s*2*mu_s/(1 - 2.*nu_s)\nnu = mu_f/rho_f\n#plot(mesh, interactive=True)\n\n\n#Allboundaries = DomainBoundary()\nFluid_area = AutoSubDomain(lambda x, on_bnd: (x[0] <= 0.5) and on_bnd)\nboundaries = FacetFunction(\"size_t\", mesh_file)\nboundaries.set_all(0)\nDomainBoundary().mark(boundaries, 2)\nFluid_area.mark(boundaries, 1)\n\nplot(boundaries,interactive=True)\n\nds = Measure(\"ds\", subdomain_data = boundaries)\ndS = Measure(\"dS\", subdomain_data = boundaries)\nn = FacetNormal(mesh_file)\n\nFluid_area = AutoSubDomain(lambda x: (x[0] <= 0.5))\ndomains = CellFunction(\"size_t\", mesh_file)\ndomains.set_all(2)\nFluid_area.mark(domains, 1)\ndx = Measure(\"dx\", subdomain_data = domains)\n\n#plot(domains,interactive = True)\n\ndx_f = dx(1, subdomain_data = domains)\ndx_s = dx(2, subdomain_data = domains)\n\ndef initiate(DVP, dvp_, mesh_file, t, rho_f, rho_s, mu_f, mu_s, nu, \\\n dx_f, dx_s, F_fluid_linear, F_solid_linear, phi, psi, **monolithic):\n t_ = Constant(0)\n x = SpatialCoordinate(mesh_file)\n\n def sigma_f(p_, u_, mu_f):\n return -p_*Identity(2) + 2.*mu_f*sym(grad(u_))\n\n def F_(U):\n \treturn Identity(len(U)) + grad(U)\n\n def J_(U):\n \treturn det(F_(U))\n\n def E(U):\n \treturn 0.5*(F_(U).T*F_(U) - Identity(len(U)))\n\n def S(U,lamda_s,mu_s):\n I = Identity(len(U))\n return 2*mu_s*E(U) + lamda_s*tr(E(U))*I\n\n def Piola1(U,lamda_s,mu_s):\n \treturn F_(U)*S(U,lamda_s,mu_s)\n\n d_x = \"0\"\n d_y = \"t_*(x[0] - 0.5)\"\n u_x = \"0\"\n u_y = \"(x[0] - 0.5)\"\n p_c = \"2\"\n\n p_e = Expression(p_c, nu=nu, t_=0.0, degree=6)\n\n u_e = Expression((u_x,\\\n u_y), nu=nu, t_=0.0, degree=6)\n\n d_e = Expression((d_x,\\\n d_y), nu=nu, t_=0.0, degree=6)\n\n assign(dvp_[\"n-1\"].sub(0), interpolate(d_e, DVP.sub(0).collapse()))\n assign(dvp_[\"n-1\"].sub(1), interpolate(u_e, DVP.sub(1).collapse()))\n assign(dvp_[\"n-1\"].sub(2), interpolate(p_e, DVP.sub(2).collapse()))\n\n #For a non-zero initial guess on first newtoniteration\n assign(dvp_[\"n\"].sub(0), interpolate(d_e, DVP.sub(0).collapse()))\n assign(dvp_[\"n\"].sub(1), interpolate(u_e, DVP.sub(1).collapse()))\n assign(dvp_[\"n\"].sub(2), interpolate(p_e, DVP.sub(2).collapse()))\n\n t_ = Constant(0)\n d_x = 0\n d_y = t_*(x[0] - 0.5)\n u_x = 0\n u_y = (x[0] - 0.5)\n p_c = 2\n\n #exec(\"d_x = %s\" % d_x) in locals(), globals()\n #exec(\"d_y = %s\" % d_y) in locals(), globals()\n #exec(\"u_x = %s\" % u_x) in locals(), globals()\n #exec(\"u_y = %s\" % u_y) in locals(), globals()\n #exec(\"p_c = %s\" % p_c) in locals(), globals()\n\n d_vec = as_vector([d_x, d_y])\n u_vec = as_vector([u_x, u_y])\n\n f_fluid = rho_f*diff(u_vec, t_) + rho_f*dot(grad(u_vec), u_vec - diff(d_vec, t_)) - div(sigma_f(p_c, u_vec, mu_f))\n #f_fluid = rho_f*diff(u_vec, t_) + rho_f*dot(u_vec - diff(d_vec, t_), grad(u_vec)) - div(sigma_f(p_c, u_vec, mu_f))\n\n f_solid = rho_s*diff(d_vec, t_) - div(Piola1(d_vec, lamda_s, mu_s))\n\n F_fluid_linear -= inner(Constant((10,0)), phi)*dx_f\n #F_fluid_linear -= inner(J_(d_vec)*f_fluid, phi)*dx_f\n F_solid_linear -= inner(f_solid, psi)*dx_s\n\n return dict(t_=t_, d_e=d_e, u_e=u_e, p_e=p_e)\n\ndef create_bcs(DVP, dvp_, u_e, p_e, d_e, boundaries, **semimp_namespace):\n #displacement conditions:\n d_bc = DirichletBC(DVP.sub(0), d_e, \"on_boundary\")\n\n #Fluid velocity conditions\n u_bc = DirichletBC(DVP.sub(1), u_e, \"on_boundary\")\n\n #Pressure Conditions\n p_bc = DirichletBC(DVP.sub(2), p_e, boundaries, 1)\n\n #Assemble boundary conditions\n bcs = [d_bc, u_bc, p_bc]\n\n return dict(bcs = bcs)\n\ndef pre_solve(t, t_, p_e, d_e, u_e, **semimp_namespace):\n t_.assign(t)\n p_e.t_ = t\n u_e.t_ = t\n d_e.t_ = t\n return {}\n\n\ndef after_solve(**semimp_namespace):\n\n\n return {}\n\ndef post_process(E_u, u_e, d_e, dvp_, mu_f, lamda_s, mu_s, mesh_file, boundaries, **semimp_namespace):\n def F_(U):\n \treturn (Identity(len(U)) + grad(U))\n\n def J_(U):\n \treturn det(F_(U))\n\n def E(U):\n \treturn 0.5*(F_(U).T*F_(U) - Identity(len(U)))\n\n def S(U,lamda_s,mu_s):\n I = Identity(len(U))\n return 2*mu_s*E(U) + lamda_s*tr(E(U))*I\n\n def Piola1(U,lamda_s,mu_s):\n \treturn F_(U)*S(U,lamda_s,mu_s)\n\n def sigma_f_new(v, p, d, mu_f):\n \treturn -p*Identity(len(v)) + mu_f*(grad(v)*inv(F_(d)) + inv(F_(d)).T*grad(v).T)\n\n d, v, p = dvp_[\"n\"].split(True)\n\n F_Dr = -assemble((sigma_f_new(v(\"-\"),p(\"-\"),d(\"-\"),mu_f)*n(\"-\"))[0]*dS(5))\n F_Li = -assemble((sigma_f_new(v(\"-\"),p(\"-\"),d(\"-\"),mu_f)*n(\"-\"))[1]*dS(5))\n\n S_Dr = -assemble((Piola1(d(\"-\"),lamda_s, mu_s)*n(\"-\"))[0]*dS(5))\n S_Li = -assemble((Piola1(d(\"-\"),lamda_s, mu_s)*n(\"-\"))[0]*dS(5))\n\n\n #To evaluate error on fluid and structure\n submesh_fluid = SubMesh(mesh, boundaries, 1)\n submesh_struc = SubMesh(mesh, boundaries, 2)\n\n #E_d = errornorm(d_e, d_s, norm_type=\"l2\", degree_rise=2, mesh=submesh_struc)\n E_u.append(errornorm(u_e, v_s, norm_type=\"l2\", degree_rise=2, mesh=submesh_fluid))\n h_ = mesh_file.hmin()\n #print \"E_u=%g, E_d=%g\" % (E_u, E_d)\n return {}\n","sub_path":"FSIVerification/ALE_Fresh/Problems/mms.py","file_name":"mms.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"318759211","text":"def add(a, b):\n print(f\"ADDING {a} + {b}\")\n return a + b\n\ndef subtract(a, b):\n print(f\"SUBTRACTING {a} - {b}\")\n return a - b\n\ndef multiply(a, b):\n print(f\"MULTIPLYING {a} * {b}\")\n return a * b\n\ndef divide(a, b):\n print(f\"DIVIDING {a} / {b}\")\n return a / b\n\nprint(\"Let's do some math with just functions!\")\n\nage = add(30, 5)\nheight = subtract(78, 4)\nweight = multiply(90, 2)\niq = divide(100, 2)\n\nprint(f\"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}\")\n\n# A puzzle for the extra credit, type it in anyway.\nprint(\"Here is a puzzle.\")\n\nwhat = subtract(add(divide(3, 3), multiply(300, 25)), 1200)\n\nprint(\"That becomes: \", what, \"Can you do it by hand?\")\n\ndef pet(name):\n print(\"That's a nice name.\")\n return name\n\ndef pet_age(age):\n print(\"Wow.\")\n return age\n\ndog_name = pet(\"King\")\ndog_age = pet_age(102)\n\nprint(f\"Your pet, {dog_name} is {dog_age} years old.\")","sub_path":"ex21.py","file_name":"ex21.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"613886697","text":"import copy\n\nfrom django.contrib import admin, messages\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.utils.encoding import force_text\n\nfrom watson.search import default_search_engine\n\nfrom ...attachments.admin import DocumentAdminInline\nfrom ...utils.admin import ConfigurableModelAdmin, remove_from_fieldsets\nfrom ...utils.base import update_url_params\nfrom ..models import Article, ArticleDocument, BaseArticle, Category, SampleArticle, Subscriber, Tag\nfrom ..watson_adapters import ArticleAdapter\nfrom .forms import ArticleAdminForm\n\n\nclass ArticleDocumentInline(DocumentAdminInline):\n model = ArticleDocument\n\n\nclass BaseArticleAdmin(ConfigurableModelAdmin):\n form = ArticleAdminForm\n change_form_template = 'admin/custom_change_form.html'\n\n fieldsets = (\n (None, {'fields': ['title', 'slug', 'status', 'published_at']}),\n (None, {'fields': ['cover_image', 'short_description', 'content']}),\n )\n\n _status_colors = {\n BaseArticle.STATUS_PUBLISHED: '#008000',\n BaseArticle.STATUS_READY_FOR_PUBLISH: '#0079FF',\n BaseArticle.STATUS_DRAFT: '#717171',\n }\n\n def change_status(self, request, queryset, status):\n model = queryset.model\n opts = model._meta\n\n status_display = force_text(dict(opts.get_field('status').flatchoices).get(status, status), strings_only=True)\n objects_count = queryset.count()\n\n update_fields = {'status': status}\n if status == model.STATUS_PUBLISHED:\n update_fields['published_at'] = models.Case(models.When(~models.Q(status=model.STATUS_PUBLISHED),\n then=timezone.now()),\n default=models.F('published_at'))\n queryset.update(**update_fields)\n messages.success(request, 'Status set to \"%s\" in %s %s.' % (\n status_display, objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n change_status.short_description = 'Mark as \"%(status_name)s\"'\n\n def colorized_status(self, obj):\n color = self._status_colors[obj.status]\n return '%s' % (color, obj.get_status_display()\n .replace(' ', ' '))\n colorized_status.short_description = 'Status'\n colorized_status.admin_order_field = 'status'\n colorized_status.allow_tags = True\n\n def make_action(self, action, kwargs, context):\n if callable(action):\n func = action\n action = action.__name__\n\n elif hasattr(self.__class__, action):\n func = getattr(self.__class__, action)\n\n description = func.short_description % context\n action += '__' + '__'.join(map(lambda x: '%s__%s' % x, kwargs.items()))\n return lambda s, r, q: func(s, r, q, **kwargs), action, description\n\n def get_actions(self, request):\n actions = super(BaseArticleAdmin, self).get_actions(request)\n\n for value, name in BaseArticle.CHOICES_STATUS:\n action = self.make_action('change_status', {'status': value}, {'status_name': name})\n actions[action[1]] = action\n\n return actions\n\n def list_display_hits(self, request):\n return request.user.has_perm('blog.view_article_hits')\n\n def get_readonly_fields(self, request, obj=None):\n readonly_fields = super(BaseArticleAdmin, self).get_readonly_fields(request, obj=obj)[:]\n if obj:\n readonly_fields += ('slug', )\n return readonly_fields\n\n def get_fieldsets(self, request, obj=None):\n fieldsets = copy.deepcopy(super(BaseArticleAdmin, self).get_fieldsets(request, obj=obj))\n if not obj:\n remove_from_fieldsets(fieldsets, 'published_at')\n return fieldsets\n\n\n@admin.register(Article)\nclass ArticleAdmin(BaseArticleAdmin):\n list_display = [\n 'title', 'categories_list', 'tags_list', 'short_description',\n 'published_at', 'is_featured', 'colorized_status', 'hits', 'words_count'\n ]\n list_filter = ['is_featured', 'status', 'categories', 'published_at']\n\n fieldsets = copy.deepcopy(BaseArticleAdmin.fieldsets)\n fieldsets[0][1]['fields'].insert(2, 'tags')\n fieldsets[0][1]['fields'].insert(2, 'categories')\n fieldsets[0][1]['fields'] += ['is_featured']\n\n search_adapter_cls = ArticleAdapter\n search_engine = default_search_engine\n # Dirty hack for displaying search input\n search_fields = [None]\n\n inlines = (ArticleDocumentInline,)\n\n actions = ['mark_featured', 'unmark_featured']\n\n def mark_featured(self, request, queryset):\n model = queryset.model\n opts = model._meta\n\n objects_count = queryset.count()\n\n queryset.update(is_featured=True)\n messages.success(request, '%s %s marked as featured.' % (\n objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n mark_featured.short_description = 'Mark as featured'\n\n def unmark_featured(self, request, queryset):\n model = queryset.model\n opts = model._meta\n\n objects_count = queryset.count()\n\n queryset.update(is_featured=False)\n messages.success(request, 'Featured flag removed from %s %s.' % (\n objects_count, opts.verbose_name if objects_count == 1 else opts.verbose_name_plural\n ))\n unmark_featured.short_description = 'Remove featured flag'\n\n def get_queryset(self, request):\n return super(ArticleAdmin, self).get_queryset(request).prefetch_related('tags', 'categories')\n\n def get_search_results(self, request, queryset, search_term):\n if not search_term:\n return queryset, False\n\n return self.search_engine.filter(queryset, search_term, ranking=False), False\n\n def changelist_view(self, request, extra_context=None):\n # Dirty hack for tags\n self.request = request\n return super(ArticleAdmin, self).changelist_view(request, extra_context=extra_context)\n\n def get_form(self, request, obj=None, **kwargs):\n form = super(ArticleAdmin, self).get_form(request, obj, **kwargs)\n form.base_fields['tags'].widget.can_add_related = False\n return form\n\n def tags_list(self, obj):\n return ', '.join([\n u'%s' % (\n update_url_params(self.request.get_full_path(), {'tags__id__exact': tag.id}), tag\n ) for tag in obj.tags.all()\n ])\n tags_list.short_description = 'Tags'\n tags_list.allow_tags = True\n\n def categories_list(self, obj):\n return ', '.join(obj.categories.values_list('name', flat=True))\n categories_list.short_description = 'Categories'\n\n\n@admin.register(SampleArticle)\nclass SampleArticleAdmin(ArticleAdmin):\n new_article_action_name = '_create_article'\n\n list_display = [\n 'title', 'tags_list', 'short_description', 'words_count'\n ]\n list_filter = ['categories']\n actions = []\n\n def render_change_form(self, request, context, **kwargs):\n if kwargs.get('obj'):\n context = context or {}\n context.update({\n 'additional_actions': [\n {'text': 'Create new article from sample', 'name': self.new_article_action_name}\n ]\n })\n return super(SampleArticleAdmin, self).render_change_form(request, context, **kwargs)\n\n def response_change(self, request, obj):\n if self.new_article_action_name in request.POST:\n article = Article(sample=obj)\n article.save()\n article.tags.add(*obj.tags.all())\n\n msg = 'New article was created from \"%(obj)s\" successfully.' % {'obj': force_text(obj)}\n self.message_user(request, msg, messages.SUCCESS)\n redirect_url = reverse('admin:%s_%s_change' % (self.model._meta.app_label, 'article'),\n current_app=self.admin_site.name, args=[article.pk])\n return HttpResponseRedirect(redirect_url)\n\n else:\n return super(SampleArticleAdmin, self).response_change(request, obj)\n\n def get_fieldsets(self, request, obj=None):\n fieldsets = super(SampleArticleAdmin, self).get_fieldsets(request, obj)\n remove_from_fieldsets(fieldsets, ['status', 'published_at', 'is_featured'])\n return fieldsets\n\n\n@admin.register(Category)\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ('name', )\n\n\n@admin.register(Tag)\nclass TagAdmin(admin.ModelAdmin):\n search_fields = ('name', )\n list_display = ('name', 'article_count')\n\n def get_queryset(self, request):\n return super(TagAdmin, self).get_queryset(request) \\\n .extra(select={'article_count': \"\"\"\n SELECT COUNT(1)\n FROM blog_article_tags as ET1\n INNER JOIN blog_article as ET2\n ON ET1.article_id = ET2.id AND ET2.is_sample = false\n WHERE ET1.tag_id = blog_tag.id\n \"\"\"})\n\n def article_count(self, obj):\n return obj.article_count\n article_count.short_description = 'Articles'\n article_count.admin_order_field = 'article_count'\n\n\n@admin.register(Subscriber)\nclass SubscriberAdmin(admin.ModelAdmin):\n list_display = ('email', 'send_email')\n\n\n\n\n","sub_path":"iwg_blog/blog/admin/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"490758728","text":"import requests\nfrom geocode import geocode\n\ndef bolder(address):\n \"\"\" координаты объекта по его адресу\n обращаемся к функции geocode из файла geocode.py\"\"\"\n toponym = geocode(address)\n if toponym:\n # Рамка вокруг объекта:\n envelope = toponym[\"boundedBy\"][\"Envelope\"]\n\n # левая, нижняя, правая и верхняя границы из координат углов:\n l, b = envelope[\"lowerCorner\"].split(\" \")\n r, t = envelope[\"upperCorner\"].split(\" \")\n\n # Вычисляем полуразмеры по вертикали и горизонтали\n dx = abs(float(l) - float(r)) / 2.0\n dy = abs(float(t) - float(b)) / 2.0\n\n return str(max(dx, dy))\n return None\n\n\n# print(bolder('Москва, ул. Ак. Королева, 12'))\n","sub_path":"Maps API/bolder.py","file_name":"bolder.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"511599102","text":"import pymysql\nimport json\nimport requests\nimport threading\n\n#connect to DB\ndef getweather():\n smart_mirror_db = pymysql.connect(\n user = 'root',\n passwd = '3695812tF!@',\n host = '127.0.0.1',\n db = 'smartmirrordb',\n charset='utf8'\n )\n cursor = smart_mirror_db.cursor()\n\n # get licence information\n lic = open(\"AppFiles\\weatherWidget\\APIlicence.txt\", 'r')\n licStr = ''\n while True:\n line = lic.readline()\n if not line:\n break\n licStr = line\n lic.close()\n\n #get weather information from api\n\n #get locaion info(city)\n citySQL = \"select lat, lon from geolocation\"\n cursor.execute(citySQL)\n\n cityStr = cursor.fetchone()\n\n #Access API\n apiurl = \"https://api.openweathermap.org/data/2.5/weather?lat=\"+str(cityStr[0])+\"&lon=\"+str(cityStr[1])+\"&appid=\"+licStr\n\n #receive json\n text = (requests.get(apiurl)).text\n data = json.loads(text)\n\n #extrack data\n currentTemp = round(data['main']['temp'] - 273.15)\n currentWthId = data['weather'][0]['id']\n currentWeather = data['weather'][0]['main']\n humidity = data['main']['humidity']\n windspd =round(data['wind']['speed'])\n wind_dict = data['wind']['deg']\n\n print(\"-----------------------------------------------------------\")\n print(\"< Data from API >\")\n print(data)\n print()\n \n #update to database\n param1 = \"currentTemp=\"+str(currentTemp)+\",currentWthId=\"+str(currentWthId)+\",currentWeather=\"+'\"'+str(currentWeather)+'\"'+\",humidity=\"+str(humidity)+\",windspd=\"+str(windspd)+\",wind_dict=\"+str(wind_dict)\n\n updateSQL = \"update weatherinfo set \"+ param1\n cursor.execute(updateSQL)\n\n smart_mirror_db.commit()\n smart_mirror_db.close()\n\n print(\"weather information update complete\")\n\n threading.Timer(600, getweather).start()\n\n\nif __name__ == '__main__':\n getweather()","sub_path":"AppFiles/weatherWidget/wthInfomain.py","file_name":"wthInfomain.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"53234380","text":"a=float(input('Введите число '))\r\na1=a//10\r\na2=a%10\r\nif ((a1==3)or(a1==7))and((a2==3)or(a2==7)):\r\n print('Да, в это число входят цифры 3 и 7')\r\nelse:\r\n print('Нет, в это число не входят цифры 3 и 7')\r\n\r\nif ((a1==4)or(a1==8))and((a2==4)or(a2==8))or((a1==9)or(a2==9)):\r\n print('Да, в это число входят цифры (4 и 8) или цифра 9')\r\nelse:\r\n print('Нет, в это число не входят цифры (4 и 8) или цифра 9')\r\n\r\n","sub_path":"Lab2/lab2.6.py","file_name":"lab2.6.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"329150045","text":"# coding=utf-8\n\"\"\"根据搜索词下载百度图片\"\"\"\nimport re\nimport sys\nimport urllib\nimport io\nimport requests\nfrom PIL import Image\nimport os\nimport time\n\ndef getPage(keyword, page, n):\n page = page * n\n\n keyword = urllib.parse.quote(keyword, safe='/')\n url_begin = \"http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word=\"\n url = url_begin + keyword + \"&pn=\" + str(page) + \"&gsm=\" + str(hex(page)) + \"&ct=&ic=0&lm=-1&width=0&height=0\"\n return url\n\n\ndef get_onepage_urls(onepageurl):\n headers = {\n 'Connection': 'close',\n }\n try:\n html = requests.get(onepageurl,headers=headers ,allow_redirects=False).text\n except Exception as e:\n # print('getOnepage_url-------'+e)\n pic_urls = []\n return pic_urls\n pic_urls = re.findall('\"objURL\":\"(.*?)\",', html, re.S)\n return pic_urls\n\n\ndef down_pic(pic_urls ,name ):\n \"\"\"给出图片链接列表, 下载所有图片\"\"\"\n for i, pic_url in enumerate(pic_urls):\n try:\n pic = requests.get(pic_url, timeout=15)\n # iofile = io.BytesIO(pic.content)\n # im =Image.open(iofile)\n\n # /home/ec2-user/tensorflow-for-poets-2/tf_files/anim/\n dirString = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/' +name + '/one/'\n dirConvertString = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/'+name +'/'\n string = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/' +name + '/one/' + str(time.time()) + '.jpg'\n stringConvert = 'C:/Users/hanwenmao/Desktop/tensorflow/Album classification/'+name +'/' +str(time.time()) +'convert'+ '.jpg'\n\n if not os.path.exists(dirString):\n os.makedirs(dirString)\n if not os.path.exists(dirConvertString):\n os.makedirs(dirConvertString)\n\n with open(string, 'wb') as f:\n try:\n f.write(pic.content)\n im = Image.open(string)\n im.convert(\"RGB\")\n im.save(stringConvert)\n except Exception as e :\n if os.path.exists(stringConvert):\n os.remove(stringConvert)\n print('写入失败----------' ,str(e))\n\n print('成功下载第%s张图片: %s' % (str(i + 1), str(pic_url)))\n except Exception as e:\n print('下载第%s张图片时失败: %s' % (str(i + 1), str(pic_url)))\n print('all exception---------'+str(e))\n continue\n\ndef start( index ,name ) :\n\n keyword = index # 关键词, 改为你想输入的词即可, 相当于在百度图片里搜索一样\n page_begin = 11 #0-3 / 4-10\n page_number = 80\n image_number = 13\n all_pic_urls = []\n while 1:\n if page_begin > image_number:\n break\n print(\"第%d次请求数据\", [page_begin])\n url = getPage(keyword, page_begin, page_number)\n onepage_urls = get_onepage_urls(url)\n page_begin += 1\n\n all_pic_urls.extend(onepage_urls)\n\n down_pic(list(set(all_pic_urls)) , name)\n\n\nif __name__ == '__main__':\n # 个人自拍 ,证件照 ,动物 ,美食 ,风景,多人合照 ,手机截图\n items = {'个人自拍': 'Personal selfie', '证件照': 'Document photo', '动物': 'animal'\n , '美食': 'Food', '风景': 'landscape', '多人合照': 'Multi-personphoto', '手机截图': 'Phone-screenshot'}\n\n for item in items:\n start(item , str(items[item]))","sub_path":"downPage/downImage2.py","file_name":"downImage2.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"138016159","text":"\"\"\"\nProblem: 890. Find and Replace Pattern\nUrl: https://leetcode.com/problems/find-and-replace-pattern/\nAuthor: David Wang\nDate: 10/29/2018\n\"\"\"\n\nclass Solution:\n def findAndReplacePattern(self, words, pattern):\n \"\"\"\n :type words: List[str]\n :type pattern: str\n :rtype: List[str]\n \"\"\"\n matches = []\n for word in words:\n if self.is_match(word, pattern):\n matches.append(word)\n return matches\n\n def is_match(self, word, pattern):\n p2w = {}\n w2p = {}\n for w, p in zip(word, pattern):\n if p not in p2w: p2w[p] = w\n if w not in w2p: w2p[w] = p\n if p2w[p] != w or w2p[w] != p:\n return False\n\n return True\n\nif __name__ == '__main__':\n words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"]\n pattern = 'abb'\n s = Solution()\n print(s.findAndReplacePattern(words, pattern))\n","sub_path":"890_Find_and_Replace_Pattern/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"10053520","text":"import tkinter as tk\nfrom tkinter import *\nfrom PIL import Image, ImageTk # for windows is this option , ImageGrab\n# for windows is this option\n#from PIL import ImageGrab\n#for linux\nimport pyscreenshot as ImageGrab\nfrom math import sqrt,ceil\nfrom tkinter import filedialog\nimport os\nfrom tkinter import messagebox\n\nclass Gui():\n\tdef __init__(self, root):\n\t\tself.root=root\n \n\t\tframeCanvas=Frame(self.root)\n\t\tframeCanvas.grid(row=0,column=0,pady=20,sticky=\"n\")\n\t\tself.canvas=tk.Canvas(frameCanvas, width=450, height=500,borderwidth=2, relief=\"groove\",cursor=\"cross\")\n\t\tself.canvas.grid(row=0,column=0, pady=0, padx=10)\n\t\tbuttonNext = tk.Button(frameCanvas, text=\"Next\", command=self.ImageNext).grid(row=1,column=0,pady=5,sticky=\"n\")\n\t\n\t\tself.x = self.y = 0\n\n\t#Image Loaded or not\n\t\tself.ImageLoaded=0\n\t\t\n\t\t#variables to be able to erase elements on the canvas\n\t\tself.rec_id=list()\n\t\tself.text_id_DM=list()\n\t\tself.text_id_ST=list()\n\t\tself.erase=0\n\t\tself.recErase=\"a\"\n\n\t#Image Canvas\n\t\tself.canvas.bind(\"\", self.on_button_press)\n\t\tself.canvas.bind(\"\", self.on_move_press)\n\t\tself.canvas.bind(\"\", self.on_button_release)\n\n\t \n\t#variables necesary to draw rectangles on the canvas\n\t\tself.rect = None\n\t\tself.start_x = None\n\t\tself.start_y = None\n\n\t#don't ask for Output.txt again\n\t\tself.Out=0\n\n\t# add a File Save menu\n\t\tmenu=Menu(root)\n\t\troot.config(menu=menu)\n\t\tfilemenu = Menu(menu)\n\t\tmenu.add_cascade(label=\"File\", menu=filemenu)\n\t\tfilemenu.add_command(label=\"Open the Original Image of the File you want to Review...\", command=self.open_file)\n\t\t#filemenu.add_command(label=\"Open All files in folder...\", command=self.open_folder)\n\t\tfilemenu.add_command(label=\"Select Output folder...\", command=self.out_folder)\n\t\tfilemenu.add_command(label=\"Enter Loc of File with labels\", command=self.open_fileText)\n\t\tfilemenu.add_separator()\n\t\tfilemenu.add_command(label=\"Exit\", command=root.quit)\n\n\t\thelpmenu = Menu(menu)\n\t\tmenu.add_cascade(label=\"Help\", menu=helpmenu)\n\t\thelpmenu.add_command(label=\"Instructions...\", command=self.help)\n\t\thelpmenu.add_command(label=\"About C.I.T.T ...\", command=self.about)\n\t\tself.path_out=\"/Out\"\n\t\tself.path=\"/images\"\n\n\t\t#list for names of images ina a folder\n\t\tself.ImageList=[]\n\t\tself.ImageListIndex=1\n\t\t\n\t\tself.pathText=\"/Out\" #labels path Output.txt\"\n\t\tself.pathAnnotations=\"/annotations\" #path where xml for each file is saved by default\t\n\t\t\n\t\t#delete labels two buttons\n\t\tframeM=Frame(root)\n\t\tframeM.grid(row=0,column=1,pady=20, padx=10,sticky=\"n\")\n\t\t\n\t\t#buttonOutFile=tk.Button(frameM, width=25,text=\"Enter Loc of File with labels\", command=self.open_fileText).grid(row=2,column=1,sticky=\"n\")\n\t\tself.reviewLabel=tk.Label(frameM,width=25,borderwidth=2, relief=\"groove\", text=\"REVIEW IMAGE\")\n\t\tself.reviewLabel.grid(row=2,column=1,sticky=\"n\")\n\t\t\n\t\tl4=tk.Label(frameM,borderwidth=2, relief=\"groove\",text=\"Delete Options\").grid(row=11,column=1,pady=10,sticky=\"n\")\n\t\tbuttonDeleteStart=tk.Button(frameM, width=25,text=\"Start Deleting\", command=self.deleteStart).grid(row=12,column=1,sticky=\"n\")\n\t\tbuttonDeleteStop=tk.Button(frameM, width=25,text=\"Stop Deleting\", command=self.deleteEnd).grid(row=13,column=1,sticky=\"n\")\n\t\t\n\t\t#console\n\t\tself.consoleLabel=tk.Label(frameM,width=25,borderwidth=2, relief=\"groove\", text=\"Current Labels\")\n\t\tself.consoleLabel.grid(row=7,column=1,pady=5,sticky=\"n\")\n\t\t#Console History\n\t\tself.consoleHist=tk.Listbox(frameM,background=\"light gray\", width=50, height=15)\n\t\tself.consoleHist.grid(row=8,column=1,padx=10,sticky=\"n\")\n\t\tself.scrollbar2=tk.Scrollbar(frameM,orient=VERTICAL)\n\t\tself.scrollbar2.grid(row=8,column=2,sticky=N+S)\n\t\tself.consoleHist.config(yscrollcommand=self.scrollbar2.set)\n\t\tself.scrollbar2.config(command=self.consoleHist.yview)\n\n\n\t\t#add the new labels also\n\t\tframeD=Frame(self.root)\n\t\tframeD.grid(row=0,column=2,pady=20,sticky=\"n\")\n\t\t#Damages\n\t\tDAMAGES = [\n\t\t\t(\"Shear cracking\", \"Scrack\"),\n\t\t\t\t(\"Flexural cracking\", \"Fcrack\"),\n\t\t\t\t(\"Concrete spalling\", \"spal\"),\n\t\t\t\t(\"Concrete core crushing\", \"contcrush\"),\n\t\t\t(\"Longitudinal bar buckling\", \"LbarB\"),\n\t\t\t(\"Longitudinal bar fracture\", \"LbarF\"),\n\t\t\t(\"Failure of confining hoops/ties\", \"FailHopp\"),\n\t\t\t(\"Anchorage/connection failure\", \"AnchFail\"),\n\t\t\t(\"Lap splice failure\", \"LapSFail\"),\n\t\t\t(\"Distributed plastic hinging\", \"DistPlas\"),\n\t\t\t(\"Concentrated flexural cracking\", \"ConcFlex\"),\n\t\t\t(\"Global buckling/instability\", \"GlobalBuck\"),\n\t\t\t(\"Shear/diagonal failure\", \"ShearFail\"),\n\t\t\t(\"Shear/compression failure\", \"ShearCompFail\"),\n\t\t\t(\"Interface sliding\", \"IntSlid\"),\n\t\t\t(\"Interaction b/w infill and frame\", \"Interac\"),\n\t\t\t(\"Slab fracture\", \"SlabFrac\"),\n\t\t\t(\"Punching shear failure\", \"PunchShearFrac\"),\n\t\t\t(\"Unseating/collapse of stairs\", \"Unseating\"),\n\t\t\t(\"Pounding\", \"Pounding\"),\n\t\t\t(\"Differential settlement\", \"DiffSett\"),\n\t\t\t(\"Residual displacement\", \"ResidualDisp\"),\n\t\t\t(\"soft story fail\", \"SoftStoryFail\"),\n\t\t\t(\"Partial/full collapse\", \"Collapse\"),\n\t\t\t]\n\t\t#VARIABLE FOR DAMAGE SELECTION\n\t\tself.DamageStr=tk.StringVar()\n\t\tself.DamageStr.set(\"Damage Label\") # initialize\n\t\tl = tk.Label(frameD,borderwidth=2, relief=\"groove\", text=\"Type of Damage\").grid(row=0,column=2,sticky=\"nw\")\n\t\tr=1\n\t\tfor text, mode in DAMAGES:\n\t\t\tself.panelB = tk.Radiobutton(frameD, text=text, variable=self.DamageStr, value=text,command=self.DamageSel)\n\t\t\tself.panelB.grid(row=r,column=2,pady=2,sticky=\"w\")\n\t\t\tr=r+1\n\t\t\t\n\n\t\t\n\t\tframeS=Frame(root)\n\t\tframeS.grid(row=0,column=3,pady=20, padx=10,sticky=\"n\")\n\t\t#Structures\n\t\tSTRUCTURES = [\n\t\t\t\t(\"short/captive column\", \"Scrack\"),\n\t\t\t\t(\"slender column\", \"Fcrack\"),\n\t\t\t\t(\"structural wall\", \"spal\"),\n\t\t\t\t(\"infill wall\", \"contcrush\"),\n\t\t\t(\"tilt-up precast panel\", \"LbarB\"),\n\t\t\t(\"joint-column connection\", \"LbarF\"),\n\t\t\t(\"beam\", \"FailHopp\"),\n\t\t\t(\"coupling beam\", \"AnchFail\"),\n\t\t\t(\"foundation beam\", \"LapSFail\"),\n\t\t\t(\"floor diaphragm/slab\", \"DistPlas\"),\n\t\t\t(\"frame\", \"ConcFlex\"),\n\t\t\t(\"scissor stairs\", \"GlobalBuck\"),\n\t\t\t(\"corbel/support\", \"ShearFail\"),\n\t\t\t(\"cantilevered balcony\", \"ShearCompFail\"),\n\t\t\t(\"construction joint\", \"IntSlid\"),\n\t\t\t(\"full Story\", \"Interac\"),\n\t\t\t(\"full/partial building\", \"SlabFrac\"),\n\t\t\t(\"unknow\", \"PunchShearFrac\"),\n\t\t] \t\t\n\t\t#VARIABLE FOR STRUCTURES\n\t\tself.StructureStr=tk.StringVar()\n\t\tself.StructureStr.set(\"Structure Label\") # initialize\n\t\tl1 = tk.Label(frameS,borderwidth=2, relief=\"groove\", text=\"Type of Structure\").grid(row=0,column=3,sticky=\"nw\")\n\t\tr=1\n\t\tfor text, mode in STRUCTURES:\n\t\t\tself.panelC = tk.Radiobutton(frameS, text=text, variable=self.StructureStr, value=text,command=self.StructureSel)\n\t\t\tself.panelC.grid(row=r,column=3,pady=4,sticky=\"w\")\n\t\t\tr=r+1\n\t\t\n\n\t\t#Add the delete New Label and Delete Label to screen\n\t\tl2 = tk.Label(frameM,borderwidth=2, relief=\"groove\", text=\"Create a New Label\").grid(row=14,column=1,sticky=\"n\")\n\t\tself.newST=tk.StringVar(frameM, value=self.StructureStr.get())\n\t\tself.newDM=tk.StringVar(frameM, value=self.DamageStr.get())\n\t\tself.textST=tk.Entry(frameM, width=25, textvariable=self.newST).grid(row=15,column=1,sticky=\"n\")\n\t\tself.textDM=tk.Entry(frameM, width=25, textvariable=self.newDM).grid(row=16,column=1,sticky=\"n\")\n\n\t\t#label History\n\t\tself.labelHist=tk.Listbox(frameM, width=50, height=5)\n\t\tself.labelHist.grid(row=17,column=1,pady=5,sticky=\"ns\")\n\t\tself.scrollbar=Scrollbar(frameM,orient=VERTICAL)\n\t\tself.scrollbar.grid(row=17, column=2,sticky=N+S)\n\t\tself.labelHist.config(yscrollcommand=self.scrollbar.set)\n\t\tself.scrollbar.config(command=self.labelHist.yview)\n\n\t\tself.labelHist.insert(10,\"New Label History list:\")\n\t\t#read This from a file\n\t\tfileHistLabel=open(\"histlabel.txt\",\"r\")\n\t\tfor item in fileHistLabel:\n\t\t\titem=item[:-1] #erases the stupid /0 end of string char\n\t\t\tself.labelHist.insert(20,item)\n\t\tfileHistLabel.close()\n\t\t#button that creates label once you are done entering values Necesary???\n\t\tdoneButton=tk.Button(frameM,text=\"Done Creating Label\", command= self.create_new_label)\n\t\tdoneButton.grid(row=18,column=1,pady=10,sticky=\"n\")\n\n\t\t#add the save Image/ Exit\n\t\tl4=tk.Label(frameM,borderwidth=2, relief=\"groove\",text=\"Save/exit Options\").grid(row=19,column=1,pady=15,sticky=\"n\")\n\t\t\n\t\tbuttonE = tk.Button(frameM, text=\"Save and Exit\", command=self.save_exit).grid(row=20,column=1,sticky=\"n\")\n\t\tbuttonC = tk.Button(frameM, text=\"Cancel (DO NO SAVE)\", command=self.exit).grid(row=21,column=1,sticky=\"n\")\n\n\t#selects the Damage Label\n\tdef DamageSel(self):\n\t\tpass\n \n\t#select the structure label\n\tdef StructureSel(self):\n\t\tpass\n\n\tdef _draw_image(self, path):\n\t\t#write to console hist name of file\n\t\tself.consoleHist.insert(20,os.path.basename(path)+\"\\n\")\n\t\tself.im = Image.open(path)\n\t\tself.tk_im = ImageTk.PhotoImage(self.im)\n\t\tself.canvas.create_image(0,0,anchor=\"nw\",image=self.tk_im)\n\t\tself.ImageSize=self.im.size \n\t\t#make size of canvas same as image\n\t\tself.canvas.config(width=self.ImageSize[0], height=self.ImageSize[1])\n\t\tself.ImageLoaded=1\n\t\t\n\n\tdef ImageNext(self):\n\t#save stuff from Image first, than load the new Image\n\t\tself.save()\n\t\t#erase stuff on the console\n\t\tself.consoleHist.delete(0,END)\n\t\tif self.ImageListIndex < len(self.ImageList):\n\t\t\t\n\t\t\tpathNext= self.ImageList[self.ImageListIndex]\n\t\t\tdirpath=os.path.dirname(self.path)\n\t\t\tself._draw_image(dirpath+'/'+pathNext)\n\t\t\t#make the new picture the path\n\t\t\tself.path=dirpath+'/'+pathNext\n\t\t\t#draw the labels\n\t\t\tself.pathText=os.getcwd()+\"/Out/Output.txt\"\n\t\t\tself.open_fileText()\n\t\t\tself.ImageListIndex=self.ImageListIndex+1\n\t\telse:\n\t\t\troot.quit()\n\t\n\tdef on_button_press(self, event):\n\t\t# save mouse drag start position\n\t\tself.start_x = event.x\n\t\tself.start_y = event.y\n\n\t\t# create rectangle, initial dot if not erasing it but only if there is an image already loaded\n\t\tif self.ImageLoaded==1:\n\t\t\tif self.erase == 0:\n\t\t\t\t\tself.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline=\"red\")\n\t\t\t\t\tself.testDM=self.canvas.create_text(self.start_x,self.start_y-10,fill=\"red\", font=\"Times 10\", text=self.DamageStr.get())\n\t\t\t\t\tself.testST=self.canvas.create_text(self.start_x,self.start_y,fill=\"red\", font=\"Times 10\", text=self.StructureStr.get())\n\t\t\t\t\t#add recId to a list so then it can be erased\n\t\t\t\t\tself.rec_id.append(self.rect)\n\t\t\t\t\tself.text_id_DM.append(self.testDM)\n\t\t\t\t\tself.text_id_ST.append(self.testST)\n\t\t\telse:\n\t\t\t\t#if delete rec pressed than check if there is a rectangle to be erased\n\t\t\t\tself.collision(self.start_x,self.start_y)\n\n\tdef on_move_press(self, event):\n\t\tif self.ImageLoaded==1:\n\t\t\tcurX, curY = (event.x, event.y)\n\t\t\t# expand rectangle as you drag the mouse if not erasing\n\t\t\tif self.erase == 0:\n\t\t\t\tself.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)\n\n\tdef on_button_release(self, event):\n\t#show rec coord and labels on console self.consoleHist.insert(20,self.DamageStr.get())\n\t#save rect to out\n\t\tif self.ImageLoaded==1:\n\t\t\tif self.erase==0:\n\t\t\t\t#erase label if less than 3 pixel width or height\n\t\t\t\tif abs(self.start_x - event.x) <=3 or abs(self.start_y - event.y) <=3 :\n\t\t\t\t\tlast=len(self.rec_id) -1\n\t\t\t\t\t#delete rectangle and labels\n\t\t\t\t\tself.canvas.delete(self.rec_id[last])\n\t\t\t\t\tdel self.rec_id[last]\n\t\t\t\t\tself.canvas.delete(self.text_id_DM[last])\n\t\t\t\t\tdel self.text_id_DM[last]\n\t\t\t\t\tself.canvas.delete(self.text_id_ST[last])\n\t\t\t\t\tdel self.text_id_ST[last]\n\t\t\t\telse:\t \n\t\t\t\t\ttext=\"rect:\" + str(self.start_x)+\" \"+str(self.start_y)+\" \"+str(event.x)+\" \"+str(event.y)+\" \"+ self.DamageStr.get()+ \" \"+ self.StructureStr.get()+\"\\n\"\n\t\t\t\t\t#write to console history\n\t\t\t\t\tself.consoleHist.insert(20,text)\n\t#check this function\t\n\tdef collision(self,x,y):\n\t\tprint (len(self.rec_id))\n\t\t\n\t\tfor rec in range(len(self.rec_id)):\n\t\t\t#print rec\n\t\t\tpt=self.canvas.coords(self.rec_id[rec])\n\t\t\tdistance= sqrt((pt[0]-x)**2+(pt[1]-y)**2)\n\t\t\tif distance< 5:\n\t\t\t#create a text to search on the \n\t\t\t\tself.recErase=\"rect:\" + str(int(ceil(pt[0])))+\" \"+str(int(ceil(pt[1])))+\" \"+str(int(ceil(pt[2])))+\" \"+str(int(ceil(pt[3])))+\" \"+ \"\\n\"\n\t\t#self.recErase=\"rect:\" + str(pt[0])+\" \"+str(pt[1])+\" \"+str(pt[2])+\" \"+str(pt[3])+\" \"+ \"\\n\" \n\t\t#delete rectangle and labels\n\t\tself.canvas.delete(self.rec_id[rec])\n\t\tdel self.rec_id[rec]\n\t\tself.canvas.delete(self.text_id_DM[rec])\n\t\tdel self.text_id_DM[rec]\n\t\tself.canvas.delete(self.text_id_ST[rec])\n\t\tdel self.text_id_ST[rec]\n\t\t\n\t\t#erase from list\n\t\t# get a list of listbox lines\n\t\ti=0\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\tfor item in temp_list:\n\t\t\tprint (item[0:20])\n\t\t\tprint (self.recErase[0:20])\n\t\t\tif item[0:20] == self.recErase[0:20]:\n\t\t\t\tdel temp_list[i]\n\t\t\ti=i+1\n\t\t#write the temp list back to consoleHist\n\t\tself.consoleHist.delete(0,END)\n\t\tfor item in temp_list:\n\t\t\tself.consoleHist.insert(20,item)\n\t\t\t\n\t#delete last label/rectangle entered\n\tdef deleteStart(self):\n\t\tself.erase=1\n\t\n\tdef deleteEnd(self):\n\t\tself.erase=0\n\t\n\t#Create the new Structure+Damage Label\n\t#allows to select name from the radio button just in case one one of the entries needs to change\n\tdef create_new_label(self):\n\t#set label to the new one created\n\t\tself.DamageStr.set(self.newDM.get())\n\t\tself.StructureStr.set(self.newST.get())\n\t\twith open(\"histlabel.txt\", \"a+\") as text_file:\n\t\t\t\ttext_file.write(self.newDM.get()+\"\\n\")\n\t\t\t\ttext_file.write(self.newST.get()+\"\\n\")\n\n\t\t#add to history\n\t\tself.labelHist.insert(20, self.StructureStr.get()+\" \"+self.DamageStr.get())\n\n\t#function to save the annotations for the PASCAL VOC FORM so the tags can be used in Tensorflow \n\tdef create_xml(self):\n\t# get a list of listbox lines from the console\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\n\t#save label Annotations\n\t\tdirpath=os.path.dirname(self.path)\n\t\tImagefolder=os.path.basename(dirpath)\n\t\tImagefilename=os.path.basename(self.path)\n\t\t#change filename to xml\n\t\tindex=Imagefilename.index('.')\n\t\txmlfilename=Imagefilename[0:index]+\".xml\"\n\t\tp=\"annotations/\"+xmlfilename\n\t\twith open(p, \"w\") as text_file:\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(Imagefolder) #filename no path\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(Imagefilename) #filename no path\n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\\n\")\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(str(self.ImageSize[0])) \n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(str(self.ImageSize[1])) \n\t\t\ttext_file.write(\"\\n\")\n\n\t\t\ttext_file.write(\"\\t\\t\")\n\t\t\ttext_file.write(\"3\") \n\t\t\ttext_file.write(\"\\n\")\n\t\t\ttext_file.write(\"\\t\\n\")\n\t\t\ttext_file.write(\"\\t\")\n\t\t\ttext_file.write(\"0\") \n\t\t\ttext_file.write(\"\\n\")\n\t\t\t\n\t\t\t\t\n\t\t\tfor line in temp_list:\n\t\t\t\t#if line statrt with rec than is a rectangles and create an obj\n\t\t\t\t#create the xml bound box\n\t\t\t\tif 'rect'==line[0:4]:\n\t\t\t\t\t#ERASE THE WORD RECT: FIRST from line\t\n\t\t\t\t\twords=line[5:].split()\n\t\t\t\t\n\t\t\t\t\t#numElem=(len(words)-4)/2\n\t\t\t\t\t#strDM=' '.join(words[4:(4+numElem)])\n\t\t\t\t\t#strST=' '.join(words[4+numElem:])\n\t\t\t\t\t\n\t\t\t\t\ttext_file.write(\"\\t\\n\")\n\n\n\t\t\ttext_file.write(\"\\n\")\n \n\t\n\t#save image and exit progrma\n\tdef save(self):\n\t# get a list of listbox lines\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\t# add a trailing newline char to each line, no need\n\t\t#temp_list = [chem + '\\n' for chem in temp_list]\n\t\t# save to file use path_out\n\t\tindex=self.path.index('.')\n\t\toutfilename=self.path[0:index]+\"-out.jpeg\"\n\n\t\tif self.path_out==\"a\":\n\t\t\tp=\"Output.txt\"\n\t\t\tp1=outfilename\n\t\telse:\n\t\t\tp=os.path.join(os.getcwd(),self.path_out, \"Output.txt\")\n\t\t\t#print p\n\t\t\tfilename=os.path.basename(self.path)\n\t\t\tindex2=filename.index('.')\n\t\t\tfilename=filename[0:index2]+\"-out.jpeg\"\n\t\t\tp1=os.path.join(self.path_out,filename)\n\t\t\t#print p1\n\t\ttemp_list = list(self.consoleHist.get(0, tk.END))\n\t\twith open(p, \"a+\") as text_file:\n\t\t\ttext_file.writelines(temp_list)\n\t\t#for WINDOWS ImageGrab(0,0,self.width,self.height).save(\"out.jpeg\")\n\t\twidget=self.canvas \n\t\tx=root.winfo_rootx()+widget.winfo_x()\n\t\ty=root.winfo_rooty()+widget.winfo_y()\n\t\tx1=x+widget.winfo_width()\n\t\ty1=y+widget.winfo_height() \n\t\tImageGrab.grab(bbox=(x,y,x1,y1)).save(p1)\n\t\tself.create_xml()\n\n\t#save image and exit program\n\tdef save_exit(self):\n\t\t#call save\n\t\tself.save()\n\t\t#create xml file\n\t\tself.create_xml()\n\t\t#exit\n\t\tsys.exit()\n\n\t#exit without saving changes\n\tdef exit(self):\n\t\tsys.exit()\n\n\tdef open_file(self):\n\t# open a file chooser dialog and allow the user to select an input\n\t\topts = {}\n\t\topts['filetypes'] = [('Supported types',('.jpeg','.jpg','.JPG','.JPEG')),\n\t\t\t\t\t\t\t\t ('EEG files','.eeg'),('all files','.*')]\n\t\t\t\n\t\tself.path = filedialog.askopenfilename(title='Enter Input File',**opts)\n\t\tif self.path == '': return\n\t\t\t\n\t\tself._draw_image(self.path) \n\n\t#open file with tags and redraw them on the original image, now they are erasable\n\tdef open_fileText(self):\n\t# open a file chooser dialog and allow the user to select an input\n\t\topts = {}\n\t\topts['filetypes'] = [('Supported types',('.txt'))]\n\t\t\t\n\t\tif self.Out==0:\n\t\t\tself.pathText = filedialog.askopenfilename(title='Enter File with labels for Image',**opts)\n\t\t\tif self.pathText == '': return\n\t\t\t\n\t\t\t#create a list qith all images names on the directory the file is selected \n\t\t\tdirpath=os.path.dirname(self.path)\n\t\t\tlistin=os.listdir(dirpath)\n\t\t\tfor file in listin:\n\t\t\t\t#enter the name of the file into a list\n\t\t\t\t#the next element of the list will be loaded when Next button is clicked \n\t\t\t\tself.ImageList.append(file) \n\t\t\tself.Out=1 \n\t\t\t\n\t\t#Fill Console History with labels for Image\n\t\tfin = open(self.pathText, 'r')\n\t\tftemp=open(os.path.dirname(self.pathText)+'/temp.txt' ,'w')\n\n\t\tmarkerStart=-1\n\t\tfor line in fin:\n\t\t\tif markerStart==0:\n\t\t\t\tif 'rect'==line[0:4]:\n\t\t\t\t\t#erase all rectangles from file we will write them all together at end with save\n\t\t\t\t\tself.consoleHist.insert(20,line)\n\t\t\t\t\t#recreate the rectangle again\n\t\t\t\t\t#ERASE THE WORD RECT: FIRST\t\n\t\t\t\t\twords=line[5:].split()\n\t\t\t\t\t#paint a rectangle\n\t\t\t\t\tself.rect = self.canvas.create_rectangle(words[0], words[1], words[2], words[3], outline=\"red\")\n\t\t\t\t\t#add recId to a list so then it can be erased later\n\t\t\t\t\tself.rec_id.append(self.rect)\n\t\t\t\t\t#Add the labels\n\t\t\t\t\t#since more than two words can belong to label first calculate how many strings add them to label divided in two\n\t\t\t\t\tnumElem=(len(words)-4)/2\n\t\t\t\t\tstrDM=' '.join(words[4:(4+numElem)])\n\t\t\t\t\tstrST=' '.join(words[4+numElem:])\n\t\t\t\t\tself.testDM=self.canvas.create_text(words[0],int(words[1])-10,fill=\"red\", font=\"Times 10\", text=strDM)\t\t\t\t\n\t\t\t\t\tself.testST=self.canvas.create_text(words[0],words[1],fill=\"red\", font=\"Times 10\", text=strST)\n\t\t\t\t\tself.text_id_DM.append(self.testDM)\n\t\t\t\t\tself.text_id_ST.append(self.testST)\n\t\t\t\t\t\n\t\t\t\t\t#erase info from file we will add all together at the end\n\t\t\t\t\tline=line.replace(line,\"\")\n\t\t\t\telse:\n\t\t\t\t\t# we are done no more labels for the image needs to be displayed\n\t\t\t\t\tmarkerStart=-1 \t\t\n\t\t\t#if self.path in line:\n\t\t\tif os.path.basename(self.path) in line: #search for filename (no fullpath) on file\n\t\t\t\t#erase title\n\t\t\t\tline=line.replace(line,\"\")\n\t\t\t\tmarkerStart=0\t\n\t\t\tftemp.write(line) #probably better to not replace line and only write when necessary\n\t\tfin.close()\n\t\tftemp.close()\n\t\t#rename the old with the new file, this is an OS system call\n\t\t#erase file so it can be renamed\n\t\tos.remove(self.pathText)\n\t\tos.rename(os.path.dirname(self.pathText)+'/temp.txt' ,self.pathText)\n\t\t\t\n\t#select where to save all outputs\t\n\tdef out_folder(self):\n\t#output folder by default is same as the input images folder\n\t#out.txt file contains all labels and by default will be on the same folder as the \n\t\tself.path_out = filedialog.askdirectory(title='Enter Output Directory')\n\t\n\t\t\n\tdef help(self):\n\t\tmessagebox.showinfo(\"Help\",\"For Instructions of how to use CITT:\\nhttps://github.com/mpantoja314/Image\")\n\tdef about(self):\n\t\tmessagebox.showinfo(\"Information\",\"C.I.T.T Civil Infrastructure Tagging Tool: \\nVersion 1.0. \\nUpdated October 2017. \\nDeveloped by:\\nMaria Pantoja and Anahid Behrouzi \\nCalPoly SLO\")\n \n#MAIN LOOP\nif __name__== '__main__':\n\troot=tk.Tk()\n\tgui=Gui(root)\n\troot.title(\"C.I.T.T. Civil Infrastructure Tagging Tool\");\n\t#root.geometry(\"1000x1500+0+0\")\n\timgicon = ImageTk.PhotoImage(file=os.path.join(os.getcwd(),'logo.ico'))\n\troot.tk.call('wm', 'iconphoto', root._w, imgicon)\n\troot.configure(background='blue')\n\troot.mainloop()\n\t\n\t\n","sub_path":"ReviewTag.py","file_name":"ReviewTag.py","file_ext":"py","file_size_in_byte":20841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"177388207","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport collections\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom django.core.exceptions import ValidationError\n\n\nclass BaseImporter:\n \"\"\"\n Importer users Retriever to get FileLike object with raw data and pass it to the Parser.\n When parser returns arguments for models, Importer creates models\n \"\"\"\n parser_class = None\n retriever = None\n model = None\n\n def __init__(self, model=None, parser_class=None, retriever=None):\n if model:\n self.model = model\n if parser_class:\n self.parser_class = parser_class\n self.parser = self.parser_class(self.model)\n if retriever:\n self.retriever = retriever\n\n def import_data(self):\n \"\"\"\n Main method for importing data\n \"\"\"\n data_obj = self.retriever.get_raw_data()\n parsed_data = self.parser.parse(data_obj)\n if isinstance(parsed_data, collections.Iterable):\n for item in parsed_data:\n self.create_model(item)\n elif isinstance(parsed_data, dict):\n self.create_model(parsed_data)\n\n def create_model(self, item_data):\n \"\"\"\n\n :param item_data: dictionary, where:\n - keys are model fields\n - values are a data for that fields. If field is Foreign key or ManyToMany field,\n value should contain only id of relation.\n All exceptions are handled and logged\n :return:\n \"\"\"\n try:\n self.model.objects.create(**item_data)\n except ValidationError as exc:\n logger.error(\"Error during import model: {0}\".format(exc))\n","sub_path":"django_importer/importers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"628674546","text":"import numpy\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom losses.focal import criterion_margin_focal_binary_cross_entropy\n\nclass DiceLoss(nn.Module):\n def __init__(self, weight=None, size_average=True, smooth=1):\n super(DiceLoss, self).__init__()\n self.smooth = smooth\n\n def forward(self, inputs, targets):\n \n #comment out if your model contains a sigmoid or equivalent activation layer\n inputs = torch.sigmoid(inputs) \n \n #flatten label and prediction tensors\n inputs = inputs.view(-1)\n targets = targets.view(-1)\n \n intersection = (inputs * targets).sum() \n dice = (2.*intersection + self.smooth)/(inputs.sum() + targets.sum() + self.smooth) \n \n return 1 - dice\n \nclass HybridLoss(nn.Module):\n def __init__(self, alpha=1, beta=1, weight=None, size_average=True, smooth=1):\n super(HybridLoss, self).__init__()\n self.smooth = smooth\n self.alpha = alpha\n self.beta = beta\n self.focal = criterion_margin_focal_binary_cross_entropy\n self.dice = DiceLoss(weight=weight, size_average=size_average)\n\n def forward(self, inputs, targets):\n \n focal_loss = self.focal(inputs, targets)\n dice_loss = self.dice(inputs, targets)\n\n \n return self.alpha*focal_loss + self.beta*dice_loss","sub_path":"losses/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"501011191","text":"from keras.models import load_model\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport os\r\n\r\n### CHECK IT BEFORE RUNNING ###\r\n\r\ndataset_way = 'partirnated_dataset/' ### way of dataset folder\r\nmodel_name = 'good_model.hdf5'\r\n###############################\r\n\r\n\r\ndef get_names():\r\n names = os.listdir('./' + dataset_way)\r\n names.sort()\r\n return names\r\n\r\n\r\ndef Test_model(model, w, h):\r\n X = load_image(w, h)\r\n y = model.predict_classes(X)\r\n print(y)\r\n\r\n\r\ndef load_image(w, h):\r\n names = get_names()\r\n pict_count = len(names)\r\n pixels = np.zeros(pict_count * w * h * 3).reshape(pict_count, w, h, 3)\r\n\r\n for pict in range(len(names)):\r\n name = dataset_way + names[pict]\r\n img_start = Image.open(name)\r\n img = Image.new(\"RGBA\", img_start.size)\r\n img.paste(img_start)\r\n img = img.resize((w, h))\r\n pix = img.load()\r\n for line in range(h):\r\n for column in range(w):\r\n pixels[pict, line, column, 0] = np.array(pix[line, column][0])\r\n pixels[pict, line, column, 1] = np.array(pix[line, column][1])\r\n pixels[pict, line, column, 2] = np.array(pix[line, column][2])\r\n\r\n pixels = pixels.astype('float32')\r\n pixels = pixels / 255.0\r\n return pixels\r\n\r\n\r\nmodel = load_model(model_name)\r\nTest_model(model, 32, 32)","sub_path":"Test_model.py","file_name":"Test_model.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"5487529","text":"#pressure test for maxium number of balls\n\nimport pygame\npygame.init()\nimport math, random, sys\n\n\n#consts\ngame_fps = 60\ngame_res = screen_width, screen_height = 1280, 720\nbkg_color = 0xFFFFFF\nmax_speed = 5\nnum_faces = 2000\n\n#handles\nscreen = pygame.display.set_mode((screen_width, screen_height))\nmain_clk = pygame.time.Clock()\n\n\n#house cleaning\nscreen.fill(bkg_color)\nballs = []\npygame.display.set_caption('TITLE')\n\n#class\nclass Balls(object):\n ball_img = pygame.image.load(\"face_1.gif\").convert()\n def __init__(self, index, max_speed):\n self.index = index\n self.image = self.ball_img\n self.dx = random.randint(1,max_speed)\n self.dy = random.randint(1,max_speed)\n self.pos = self.image.get_rect()\n self.pos.x = random.randint(0, screen_width - self.pos.width)\n self.pos.y = random.randint(0, screen_height - self.pos.height)\n \n def update(self):\n #move\n self.pos.move_ip(self.dx, self.dy)\n #collision\n if self.pos.left < 0 or self.pos.right > screen_width:\n self.dx = -self.dx\n\n if self.pos.top < 0 or self.pos.bottom > screen_height:\n self.dy = -self.dy\n\n def draw(self, screen):\n screen.blit(self.image, self.pos)\n\n def debug_print(self):\n print(self.index, self.dx, \\\n self.dy, self.pos.x, self.pos.y)\n\n#construct balls\nfor i in range(num_faces):\n balls.append(Balls(i, max_speed))\n\n#main loop\nwhile 1:\n #events\n for event in pygame.event.get():\n if event.type == pygame.QUIT: sys.exit()\n\n #draw\n screen.fill(bkg_color)\n for b in balls:\n b.update()\n b.draw(screen)\n #render\n pygame.display.flip()\n main_clk.tick(game_fps)\n print(main_clk.get_fps())","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"82727486","text":"import os\r\nimport time\r\n \r\ndef WaitForDownload(fileName,timer=150):\r\n counter = 0\r\n oldFileSize = -1\r\n while counter < timer:\r\n fileSize = int(os.stat(fileName).st_size)\r\n if fileSize == oldFileSize and oldFileSize != 0:\r\n counter += 1\r\n else:\r\n counter = 0\r\n oldFileSize = fileSize\r\n time.sleep(0.01)\r\n return True\r\n","sub_path":"sizecheck.py","file_name":"sizecheck.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"388346093","text":"import psycopg2\nfrom flask import Flask, request, jsonify,json\nfrom config import config\n\napp = Flask(__name__)\n\nconn = None\ncur=None\nresponse=None\n\ndef connect():\n \"\"\" Connect to the PostgreSQL database server \"\"\"\n \n try:\n # read connection parameters\n params = config()\n\n # connect to the PostgreSQL server\n print('Connecting to the PostgreSQL database...')\n conn = psycopg2.connect(**params)\n\n # create a cursor\n cur = conn.cursor()\n\n # execute a statement\n print('PostgreSQL database version:')\n cur.execute('SELECT version()')\n\n # display the PostgreSQL database server version\n db_version = cur.fetchone()\n print(db_version)\n\n \n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n \n\n\n@app.route('/login', methods=[\"POST\"])\ndef login():\n connect()\n data = request.json\n \n cur.execute('SELECT name, phone, pass FROM public.users WHERE phone =? AND pass =?',data['phone'],data['pass'])\n columns = ('name', 'phone', 'pass')\n rows=cur.fetchone()\n\n if cur == None:\n results = []\n for row in rows:\n results.append(dict(zip(columns, row)))\n \n response = app.response_class(\n response=json.dumps(results),\n status=200,\n mimetype='application/json'\n )\n else:\n response = app.response_class(\n response=json.dumps(\"{'status':'0'}\"),\n status=200,\n mimetype='application/json'\n )\n\n print(results)\n return response\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"429872350","text":"import resources\nimport pyglet\nfrom GameObjects import PlayerObject\nfrom MinionObjects import Cowboy, Blob\nfrom pyglet.window import key\nfrom Time import Timer\nfrom shoot import hit_cowboy, hit_blob\nfrom pyglet.window import mouse\nimport sys\n\n# Window setting\nwindow = pyglet.window.Window(width=1200, height=900, caption=\"Space Invaders\", resizable=False)\nwindow.set_location(400, 100)\nframe_rate = 1/16\n\n# Make background\nglobal background_sprite\nbackground = pyglet.resource.image('battleback1.png')\nbackground.width = 1200\nbackground.height = 900\nbackground_sprite = pyglet.sprite.Sprite(img=background, x=0, y=0)\n\n# Create player\nplayer = PlayerObject(600, 0, \"main2.png\")\n\n# Game settings\ncharacter_speed = 5.0\nspawn_speed = 4 # seconds\n\n# Cowboy handle\ncowboys = []\nnumber = 2\ncowboyBatch = pyglet.graphics.Batch()\n\n# Blob handle\nblobs = []\nblobnumber = 1\nblobBatch = pyglet.graphics.Batch()\n\n# Other\npressing_keys=[]\n\n\ndef spawn(dt):\n global number\n for i in range(number):\n cowboy = Cowboy(cowboyBatch, \"Cowboy2.png\")\n cowboys.append(cowboy)\n number += 1\n\n for i in range(blobnumber):\n blob = Blob(blobBatch, \"blob.png\")\n blobs.append(blob)\n\n\ndef moveCharacter(dt):\n if pyglet.window.key.LEFT in pressing_keys:\n player.move(-character_speed, 0)\n if pyglet.window.key.RIGHT in pressing_keys:\n player.move(character_speed, 0)\n if pyglet.window.key.UP in pressing_keys:\n player.move(0, character_speed)\n if pyglet.window.key.DOWN in pressing_keys:\n player.move(0, -character_speed)\n\n\n@window.event\ndef on_draw():\n window.clear()\n background_sprite.draw()\n player.sprite.draw()\n for cowboy in cowboys:\n cowboy.draw()\n for blob in blobs:\n blob.draw()\n timer.label.draw()\n\n\n@window.event\ndef on_mouse_press(x, y, button, modifier):\n for cowboy in cowboys:\n if button == mouse.LEFT:\n if hit_cowboy(x, y, cowboy.cowboy_sprite.x, cowboy.cowboy_sprite.y) is True:\n cowboys.remove(cowboy)\n break\n\n for blob in blobs:\n if button == mouse.LEFT:\n if hit_blob(x, y, blob.blob_sprite.x, blob.blob_sprite.y) is True:\n blobs.remove(blob)\n break\n\n\n@window.event\ndef on_key_press(symbol, modifiers):\n pressing_keys.append(symbol)\n\n\n@window.event\ndef on_key_release(symbol, modifiers):\n pressing_keys.remove(symbol)\n\n\ndef update(dt):\n player.update(dt)\n pos = player.update(dt)\n for cowboy in cowboys:\n # if hit(player.sprite.x, player.sprite.y, cowboy.cowboy_sprite.x, cowboy.cowboy_sprite.y) is True:\n #\n cowboy.update(dt, pos)\n\n for blob in blobs:\n blob.update(dt, pos)\n\n on_draw()\n\nif __name__ == \"__main__\":\n timer = Timer()\n pyglet.clock.schedule_interval(update, 1.0/60)\n pyglet.clock.schedule_interval(spawn, spawn_speed)\n pyglet.clock.schedule_interval(moveCharacter, 1.0/60)\n pyglet.clock.schedule_interval(timer.update, 1.0)\n pyglet.app.run()\n","sub_path":"Game/GameWindow.py","file_name":"GameWindow.py","file_ext":"py","file_size_in_byte":3028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"54980127","text":"from direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import Lens, LensNode, PerspectiveLens, OrthographicLens\n# from direct.interval.IntervalGlobal import Sequence, Func, Wait, SoundInterval\nfrom ursina.sequence import Sequence, Func, Wait\nfrom direct.interval.IntervalGlobal import SoundInterval\nfrom direct.task.Task import Task\nfrom panda3d.core import NodePath, PandaNode\nfrom panda3d.core import Vec2, Vec3, Point3\nfrom panda3d.core import loadPrcFileData, Filename, AntialiasAttrib\nfrom panda3d.core import PNMImage, Texture\n\nimport sys\nimport os\nimport math\nimport random\nimport inspect\nimport importlib\nimport subprocess\nimport time\nfrom pathlib import Path\n\nfrom ursina import application\nfrom ursina.entity import Entity\nfrom ursina import scene\nfrom ursina import window\nfrom ursina import mouse\nfrom ursina import camera\nfrom ursina import raycaster\nfrom ursina.raycaster import raycast, boxcast\nfrom ursina import color\nfrom ursina.input_handler import held_keys\nfrom ursina import input_handler\n\n\ndef save_prefab(target, name=None, path='prefabs'):\n if not name:\n name = target.name\n\n prefab_path = os.path.join(\n path,\n target.name + '_' + str(target.get_key()) + '.py')\n\n with open(prefab_path, 'w') as file:\n file.write('from ursina import *\\n\\n')\n\n file.write('class ' + name.title() + '_' + str(target.get_key()) + '(Entity):\\n\\n')\n file.write(' def __init__(self):\\n')\n file.write(' super().__init__()\\n')\n\n entities_to_save = list()\n entities_to_save.append(target)\n for e in scene.entities:\n if e.has_ancestor(target):\n entities_to_save.append(e)\n\n for e in entities_to_save:\n if e is target:\n prefix = ' self'\n else:\n prefix = ' self.' + e.name + '_' + str(e.get_key())\n\n color_str = ('(' + str(e.color[0]) + ', '\n + str(e.color[1]) + ', '\n + str(e.color[2]) + ', '\n + str(e.color[3]) + ')')\n\n palette = [item for item in dir(color) if not item.startswith('__')]\n for colorname in palette:\n if getattr(color, colorname) == e.color:\n color_str = 'color.' + colorname\n break\n\n if e is not target:\n file.write(prefix + ' = Entity()' + '\\n')\n\n parent_str = 'self.' + e.parent.name + '_' + str(e.parent.get_key())\n if e.parent == target:\n parent_str = 'self'\n\n file.write(prefix + '.enabled = ' + str(e.enabled) + '\\n'\n + prefix + '.is_editor = ' + str(e.is_editor) + '\\n'\n + prefix + '.name = ' + '\\'' + str(e.name) + '\\'' + '\\n'\n + prefix + '.parent = ' + parent_str + '\\n')\n\n if e.origin != Vec3(0,0,0):\n file.write(prefix + '.origin = ' + vec3_to_string(e.origin) + '\\n')\n if e.position != Vec3(0,0,0):\n file.write(prefix + '.position = ' + vec3_to_string(e.position) + '\\n')\n if e.rotation != Vec3(0,0,0):\n file.write(prefix + '.rotation = ' + vec3_to_string(e.rotation) + '\\n')\n if e.scale != Vec3(1,1,1):\n file.write(prefix + '.scale = ' + vec3_to_string(e.scale) + '\\n')\n\n if e.model:\n file.write(prefix + '.model = ' + '\\'' + os.path.basename(str(e.model))[:4] + '\\'' + '\\n')\n if e.color:\n file.write(prefix + '.color = ' + color_str + '\\n')\n if e.texture:\n file.write(prefix + '.texture = ' + str(e.texture) + '\\n')\n\n file.write(prefix + '.collision = ' + str(e.collision) + '\\n')\n if e.collider:\n file.write(prefix + '.collider = ' + str(e.collider) + '\\n')\n\n\n\n\n\n for s in e.scripts:\n if e is target:\n script_prefix = prefix + '.' + str(s.__class__.__name__).lower()\n else:\n script_prefix = prefix + '_' + str(s.__class__.__name__).lower()\n\n file.write(script_prefix + ' = ' + prefix[8:] + '.add_script(\\'' + s.__class__.__name__ + '\\')\\n')\n\n for var in [item for item in vars(s) if not item.startswith('_')]:\n\n varvalue = getattr(s, var)\n\n if not varvalue:\n continue\n\n print(type(varvalue))\n\n if varvalue.__class__ == Entity:\n if varvalue is target:\n varvalue = 'self'\n else:\n varvalue = str(varvalue.name) + '_' + str(varvalue.get_key())\n\n print('hyhrh')\n file.write(script_prefix + '.' + var + ' = ' + str(varvalue) + '\\n')\n\n print('saved prefab:', path, target.name)\n\ndef _vec3_to_string(vec3):\n string = '(' + str(round(vec3[0], 3)) + ', ' + str(round(vec3[1], 3))\n if vec3[2] is not 0:\n string += ', ' + str(round(vec3[2]), 3)\n string += ')'\n return string\n\n\ndef invoke(function, *args, **kwargs):\n delay = 0\n if 'delay' in kwargs:\n delay = kwargs['delay']\n del kwargs['delay']\n\n if not delay:\n function(*args, **kwargs)\n return function\n\n s = Sequence()\n s.append(Wait(delay))\n s.append(Func(function, *args, **kwargs))\n s.start()\n return s\n\n\ndef destroy(entity, delay=0):\n if delay == 0:\n _destroy(entity)\n return\n\n s = Sequence()\n s.append(Wait(delay))\n s.append(Func(_destroy, entity))\n s.start()\n\ndef _destroy(entity):\n if not entity:\n print('entity is None')\n return\n if entity in scene.entities:\n scene.entities.remove(entity)\n\n if hasattr(entity, 'on_destroy'):\n entity.on_destroy()\n\n if hasattr(entity, 'scripts'):\n for s in entity.scripts:\n del s\n\n if hasattr(entity, 'animations'):\n for anim in entity.animations:\n anim.finish()\n anim.kill()\n\n if hasattr(entity, 'tooltip'):\n destroy(entity.tooltip)\n # entity.tooltip.removeNode()\n\n entity.removeNode()\n\n #unload texture\n # if hasattr(entity, 'texture') and entity.texture != None:\n # entity.texture.releaseAll()\n\n del entity\n\n\ndef import_all_classes(path=application.asset_folder, debug=False):\n path = str(path)\n sys.path.append(path)\n from ursina.string_utilities import snake_to_camel\n from glob import iglob\n imported_successfully = list()\n\n for file_path in iglob(path + '**/*.py', recursive=True):\n if '\\\\build\\\\' in file_path or '__' in file_path:\n continue\n\n rel_path = file_path[len(path):][:-3].replace('\\\\', '.')\n if rel_path.startswith('.'):\n rel_path = rel_path[1:]\n module_name = os.path.basename(file_path).split('.')[0]\n class_name = snake_to_camel(module_name)\n module_name = module_name\n import_statement = 'from ' + rel_path + ' import *'\n\n try:\n exec(import_statement, globals())\n imported_successfully.append(module_name)\n if debug:\n print(import_statement)\n except:\n if debug:\n print(' x', import_statement)\n pass\n\n return imported_successfully\n\n\nfrom ursina.text import Text\ndef print_on_screen(text):\n text_entity = Text(\n # parent = camera.ui,\n text = str(text),\n position = window.top_left,\n origin = (-.5, .5),\n # scale = (.1, .1)\n )\n destroy(text_entity, 1)\n\n\nif __name__ == '__main__':\n\n from ursina import *\n app = Ursina()\n def test_func(item, x=None, y=None):\n print(item, x, y)\n\n test_func('test')\n invoke(test_func, 'test', delay=.1)\n invoke(test_func, 'test1', 1, 2, delay=.2)\n invoke(test_func, 'test2', x=1, y=2, delay=.3)\n\n app.run()\n","sub_path":"ursina/ursinastuff.py","file_name":"ursinastuff.py","file_ext":"py","file_size_in_byte":8026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"423938202","text":"# Py 2 & 3 support\nfrom __future__ import division, print_function, unicode_literals\n\n# Common Imports\nimport numpy as np\nimport os\n\n# ML Imports\nfrom sklearn.svm import SVC\nfrom sklearn import datasets\n\n# Graph Imports\n# %matplotlib inline # notebook magics\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Instantiate datasets\nX = iris = datasets.load_iris()\nX = iris[\"data\"][:, (2, 3)]\ny = iris[\"target\"]\n\nsetosa_or_versicolor = (y == 0) | (y == 1)\nX = X[setosa_or_versicolor]\ny = y[setosa_or_versicolor]\n\n# Save directory\nPROJECT_ROOT_DIR = \".\"\n\n# Declare functions\n\n\ndef save_fig(fig_id, tight_layout=True):\n path = os.path.join(PROJECT_ROOT_DIR, \"images\", fig_id + \".png\")\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format='png', dpi=300)\n\n\ndef plot_svc_decision_boundary(svm_clf, xmin, xmax):\n w = svm_clf.coef_[0]\n b = svm_clf.intercept_[0]\n x0 = np.linspace(xmin, xmax, 200)\n decision_boundary = -w[0] / w[1] * x0 - b / w[1]\n margin = 1 / w[1]\n gutter_up = decision_boundary + margin\n gutter_down = decision_boundary - margin\n svs = svm_clf.support_vectors_\n plt.scatter(svs[:, 0], svs[:, 1], s=180, facecolors=\"#FFAAAA\")\n plt.plot(x0, decision_boundary, \"k-\", linewidth=2)\n plt.plot(x0, gutter_up, \"k--\", linewidth=2)\n plt.plot(x0, gutter_down, \"k--\", linewidth=2)\n\n\n# Outlier sensitivity\nX_outliers = np.array([[3.4, 1.3], [3.2, 0.8]])\ny_outliers = np.array([0, 0])\nXo1 = np.concatenate([X, X_outliers[:1]], axis=0)\nyo1 = np.concatenate([y, y_outliers[:1]], axis=0)\nXo2 = np.concatenate([X, X_outliers[1:]], axis=0)\nyo2 = np.concatenate([y, y_outliers[1:]], axis=0)\n\nsvm_clf2 = SVC(kernel=\"linear\", C=10**9)\nsvm_clf2.fit(Xo2, yo2)\n\nplt.figure(figsize=(12, 2.7))\n\nplt.subplot(121)\nplt.plot(Xo1[:, 0][yo1 == 1], Xo1[:, 1][yo1 == 1], \"bs\")\nplt.plot(Xo1[:, 0][yo1 == 0], Xo1[:, 1][yo1 == 0], \"yo\")\nplt.text(0.3, 1.0, \"Impossible\", fontsize=24, color=\"red\")\nplt.xlabel(\"Petal length\", fontsize=14)\nplt.ylabel(\"Petal width\", fontsize=14)\nplt.annotate(\n \"Outlier\",\n xy=(X_outliers[0][0], X_outliers[0][1]),\n xytext=(2.5, 1.7),\n ha=\"center\",\n arrowprops=dict(facecolor='black', shrink=0.1),\n fontsize=16,\n)\n\nplt.axis([0, 5.5, 0, 2])\n\nplt.subplot(122)\nplt.plot(Xo2[:, 0][yo2 == 1], Xo2[:, 1][yo2 == 1], \"bs\")\nplt.plot(Xo2[:, 0][yo2 == 0], Xo2[:, 1][yo2 == 0], \"yo\")\nplot_svc_decision_boundary(svm_clf2, 0, 5.5)\nplt.xlabel(\"Petal length\", fontsize=14)\nplt.annotate(\n \"Outlier\",\n xy=(X_outliers[1][0], X_outliers[1][1]),\n xytext=(3.2, 0.08),\n ha=\"center\",\n arrowprops=dict(facecolor='black', shrink=0.1),\n fontsize=16,\n)\n\nplt.axis([0, 5.5, 0, 2])\n\nsave_fig(\"sensitivity_to_outliers_plot\")\nplt.show()\n","sub_path":"support_vector_machine/examples/outliers.py","file_name":"outliers.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"216078129","text":"import pickle\nimport troposphere\nfrom troposphere import *\nfrom troposphere.route53 import RecordSetType\nimport troposphere.ecs as ecs\nfrom troposphere.ecs import Service, ContainerDefinition, TaskDefinition, Environment, Cluster\nfrom netaddr import *\nimport troposphere.ec2 as ec2\nfrom troposphere.iam import Role, InstanceProfile\nfrom awacs.aws import Allow, Statement, Principal, Policy\nfrom awacs.sts import AssumeRole\nimport os\n\nregion = 'us-east-2'\n\nip = IPNetwork('239.254.99.0/25')\nip_list = list(ip)\n\necs_template = Template()\n\ncustomer_cluster = ecs.Cluster('CustomerCluster')\nmatching_engine_cluster = ecs.Cluster('MatchingEngineCluster')\nmarket_data_cluster = ecs.Cluster('MarketDataCluster')\nbroker_dealer_cluster = ecs.Cluster('BrokerDealerCluster')\necs_template.add_resource(customer_cluster)\necs_template.add_resource(matching_engine_cluster)\necs_template.add_resource(market_data_cluster)\necs_template.add_resource(broker_dealer_cluster)\n\n#ddog task and service\ndata_dog_environment_api_key = ecs.Environment(Name='API_KEY', Value=os.environ['DD_API_KEY'])\ndata_dog_environment_app_key = ecs.Environment(Name='APP_KEY', Value=os.environ['DD_APP_KEY'])\n\nif region == 'us-west-2':\n eip_list = ['eipalloc-a9f662cd', 'eipalloc-05b57d62', 'eipalloc-62fc6c06', 'eipalloc-e7b42183', 'eipalloc-18c9017f']\n ImageId='ami-3dc2165d'\n HostedZoneId='Z2J9AY0IWC7L8U'\n fileName='aex_us_west_2.json'\n Image='007038732177.dkr.ecr.us-west-2.amazonaws.com/aex:latest'\n Image\nif region == 'us-east-1':\n eip_list = ['eipalloc-f93c46c6', 'eipalloc-7d596542', 'eipalloc-6f5c6050', 'eipalloc-115e622e', 'eipalloc-8a5f63b5']\n ImageId='ami-f66607e1'\n HostedZoneId='Z1W96SO54I67M9'\n fileName='aex_us_east_1.json'\n Image='007038732177.dkr.ecr.us-east-1.amazonaws.com/aex:latest'\nif region == 'us-east-2':\n eip_list = ['eipalloc-ee15ec87', 'eipalloc-6c08f105', 'eipalloc-5a0bf233', 'eipalloc-9e16eff7', 'eipalloc-f816ef91']\n ImageId='ami-704f1515'\n HostedZoneId='Z1W96SO54I67M9'\n fileName='aex_us_east_2.json'\n Image='007038732177.dkr.ecr.us-east-2.amazonaws.com/aex:latest'\necs_instance_sg = ecs_template.add_resource(\n ec2.SecurityGroup(\n \"InstanceSecurityGroup\",\n GroupDescription=\"Allow access to 3000 ports\",\n SecurityGroupIngress=[\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"30000\",\n ToPort=\"40000\",\n CidrIp=\"0.0.0.0/0\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"22\",\n ToPort=\"22\",\n CidrIp=\"0.0.0.0/0\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"6783\",\n ToPort=\"6793\",\n CidrIp=\"172.31.0.0/16\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"udp\",\n FromPort=\"6783\",\n ToPort=\"6784\",\n CidrIp=\"172.31.0.0/16\",\n ),\n ec2.SecurityGroupRule(\n IpProtocol=\"tcp\",\n FromPort=\"4040\",\n ToPort=\"4040\",\n CidrIp=\"172.31.0.0/16\",\n )\n ]\n )\n)\n\necs_instance_role = ecs_template.add_resource(Role(\n \"ecsRole\",\n AssumeRolePolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=Allow,\n Action=[AssumeRole],\n Principal=Principal(\"Service\", [\"ec2.amazonaws.com\"])\n )\n ]\n ),\n ManagedPolicyArns=['arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role', 'arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess', 'arn:aws:iam::aws:policy/AmazonEC2ContainerServiceFullAccess', 'arn:aws:iam::aws:policy/AmazonKinesisFullAccess']\n))\n\necs_task_role = ecs_template.add_resource(Role(\n \"ecsTaskRole\",\n AssumeRolePolicyDocument=Policy(\n Statement=[\n Statement(\n Effect=Allow,\n Action=[AssumeRole],\n Principal=Principal(\"Service\", [\"ecs-tasks.amazonaws.com\"])\n )\n ]\n ),\n ManagedPolicyArns=['arn:aws:iam::aws:policy/AmazonKinesisFirehoseFullAccess', 'arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess', 'arn:aws:iam::aws:policy/AmazonKinesisFullAccess']\n))\n\necs_instance_profile = ecs_template.add_resource(InstanceProfile(\n \"ecsInstanceProfile\",\n Roles=[Ref(ecs_instance_role)]\n))\n\n#customer cluster instances\ncount = 1\nfor eip in eip_list:\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"customerClusterInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(customer_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n eipassoc1 = ecs_template.add_resource(ec2.EIPAssociation(\n \"EIPAssoc1\" + str(count),\n InstanceId=Ref(instance1),\n AllocationId=eip\n ))\n count +=1\n\n#matching engine cluster instances\nfor count in range(0, 5):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"matchingEngineInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(matching_engine_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n\n#market data instances\nfor count in range(0, 2):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"marketDataInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(market_data_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n#docker run -d --name dogstatsd -h `hostname` -e ef3d399b75961da5e51f63f0b3addf0b datadog/docker-dogstatsd\n#broker dealer instances\nfor count in range(0, 5):\n instance1 = ecs_template.add_resource(ec2.Instance(\n \"brokerDealerInstance\" + str(count),\n SecurityGroups=[Ref(ecs_instance_sg)],\n IamInstanceProfile=Ref(ecs_instance_profile),\n KeyName='aws',\n InstanceType='r3.4xlarge',\n ImageId=ImageId,\n Tags=[ec2.Tag('weave:peerGroupName','reInvent')],\n BlockDeviceMappings=[ec2.BlockDeviceMapping(DeviceName='/dev/xvda',Ebs=ec2.EBSBlockDevice(VolumeSize=100))],\n UserData=Base64(Join('', [\n \"#!/bin/bash\\n\",\n \"echo ECS_CLUSTER=\", Ref(broker_dealer_cluster), \" >> /etc/ecs/ecs.config\\n\",\n \"echo SERVICE_TOKEN=\", os.environ['WEAVE_SERVICE_TOKEN'], \" >> /etc/weave/scope.config\\n\",\n \"docker run -d --name dogstatsd -e API_KEY=\", os.environ['DD_API_KEY'], \" datadog/docker-dogstatsd\\n\",\n ]))\n )\n )\n\nwith open('symbols.pickle', 'rb') as handle:\n symbols = pickle.load(handle)\n\n#print symbols\n\nfor symbol in symbols:\n myDNSRecord = ecs_template.add_resource(RecordSetType(symbol,HostedZoneId=HostedZoneId,Comment=symbol,Name=symbol + \".aex.com\",Type=\"A\", TTL=60, ResourceRecords=[str((ip_list.pop()))]))\n\n\n#matching-engine task\nmyEnvironment = ecs.Environment(Name='symbol', Value='AMZN')\ndefaultMode = ecs.Environment(Name='mode', Value='production')\nlog = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/matching-engine\", \"awslogs-region\": \"us-west-2\"})\ncontainer_definition = ecs.ContainerDefinition(Name='matchingEngine', Image=Image, Cpu=100, Memory=1024, Command=[\"/bin/sh\", \"start_me.sh\"], Environment=[myEnvironment, defaultMode, data_dog_environment_api_key, data_dog_environment_app_key], LogConfiguration=log)\ntask_definition = ecs.TaskDefinition('matchingEngine', ContainerDefinitions=[container_definition], TaskRoleArn=Ref(ecs_task_role))\nmytask = ecs_template.add_resource(task_definition)\n\n#fix-gateway task\nfix_gateway_environment_connectiontype = ecs.Environment(Name='ConnectionType', Value='default')\nfix_gateway_environment_sendercompid = ecs.Environment(Name='SenderCompID', Value='default')\nfix_gateway_environment_targetcompid = ecs.Environment(Name='TargetCompID', Value='default')\nfix_gateway_environment_socketconnecthost = ecs.Environment(Name='SocketConnectHost', Value='default')\nfix_gateway_environment_socketconnectport = ecs.Environment(Name='SocketConnectPort', Value='default')\nfix_gateway_web_port = ecs.PortMapping(ContainerPort=80, HostPort=0)\nfix_gateway_fix_port = ecs.PortMapping(ContainerPort=11310, HostPort=0)\nfix_gateway_log = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/fix-gateway\", \"awslogs-region\": \"us-west-2\"})\nfix_gateway_container_definition = ecs.ContainerDefinition(\n Name='customerGateway',\n Image=Image,\n Cpu=100,\n Memory=1024,\n Command=[\"/bin/sh\", \"start_acceptor.sh\"],\n Environment=[fix_gateway_environment_connectiontype,\n fix_gateway_environment_sendercompid,\n fix_gateway_environment_targetcompid,\n fix_gateway_environment_socketconnecthost,\n fix_gateway_environment_socketconnectport,\n data_dog_environment_api_key,\n data_dog_environment_app_key],\n LogConfiguration=fix_gateway_log,\n PortMappings=[fix_gateway_web_port, fix_gateway_fix_port])\n\nfix_gateway_task_definition = ecs.TaskDefinition('customerGateway', ContainerDefinitions=[fix_gateway_container_definition])\nfix_task = ecs_template.add_resource(fix_gateway_task_definition)\n\n#customer-oms task\noms_gateway_environment_connectiontype = ecs.Environment(Name='ConnectionType', Value='default')\noms_gateway_environment_sendercompid = ecs.Environment(Name='SenderCompID', Value='default')\noms_gateway_environment_targetcompid = ecs.Environment(Name='TargetCompID', Value='default')\noms_gateway_environment_socketconnecthost = ecs.Environment(Name='SocketConnectHost', Value='default')\noms_gateway_environment_socketconnectport = ecs.Environment(Name='SocketConnectPort', Value='default')\noms_gateway_web_port = ecs.PortMapping(ContainerPort=80, HostPort=0)\noms_gateway_fix_port = ecs.PortMapping(ContainerPort=11310, HostPort=0)\noms_gateway_log = ecs.LogConfiguration(LogDriver='awslogs', Options={\"awslogs-group\":\"/aex/oms-gateway\", \"awslogs-region\": \"us-west-2\"})\noms_gateway_container_definition = ecs.ContainerDefinition(\n Name='omsGateway',\n Image=Image,\n Cpu=100,\n Memory=1024,\n Command=[\"/bin/sh\", \"start_oms.sh\"],\n Environment=[oms_gateway_environment_connectiontype,\n oms_gateway_environment_sendercompid,\n oms_gateway_environment_targetcompid,\n oms_gateway_environment_socketconnecthost,\n oms_gateway_environment_socketconnectport,\n data_dog_environment_api_key,\n data_dog_environment_app_key],\n LogConfiguration=oms_gateway_log,\n PortMappings=[oms_gateway_web_port, oms_gateway_fix_port])\n\noms_gateway_task_definition = ecs.TaskDefinition('omsEngine', ContainerDefinitions=[oms_gateway_container_definition])\noms_task = ecs_template.add_resource(oms_gateway_task_definition)\n\n#utility task\nterminal_environment = ecs.Environment(Name='TERM', Value='screen')\nutility_container_definition = ecs.ContainerDefinition(Name='utility', Image=Image, Cpu=100, Memory=1024, Command=[\"/bin/sh\", \"start_ui.sh\"], Environment=[myEnvironment, defaultMode, data_dog_environment_api_key, data_dog_environment_app_key, terminal_environment], LogConfiguration=log)\nutility_task_definition = ecs.TaskDefinition('utilityTask', ContainerDefinitions=[utility_container_definition], TaskRoleArn=Ref(ecs_task_role))\nmytask = ecs_template.add_resource(utility_task_definition)\necs_file = open(fileName, \"wb\")\necs_file.write(ecs_template.to_json())\necs_file.close()\n","sub_path":"generate_aex_cloudformation.py","file_name":"generate_aex_cloudformation.py","file_ext":"py","file_size_in_byte":13820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"496491157","text":"# https://atcoder.jp/contests/abc144/tasks/abc144_b\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda :sys.stdin.readline().rstrip()\ndef resolve():\n s=set()\n for i in range(1,10):\n for j in range(1,10):\n s.add(i*j)\n n=int(input())\n print(\"Yes\" if n in s else \"No\")\nresolve()\n","sub_path":"ABC144/b_81.py","file_name":"b_81.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"640237105","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom gum.utils import elasticsearch_connection\n\n\nclass ElasticsearchManager(object):\n \"\"\"Like a `ModelManager` gives to the user methods to apply queries\n to Elasticsearch from a specific model.\n \"\"\"\n\n def __init__(self, model=None, mapping_type=None):\n self.model = None\n self.mapping_type = None\n\n def search(self, **kwargs):\n \"\"\"Partial application of `search` function from Elasticsearch\n module.\n \"\"\"\n es = elasticsearch_connection()\n if 'index' not in kwargs:\n kwargs[\"index\"] = self.mapping_type.index\n if 'doc_type' not in kwargs:\n kwargs[\"doc_type\"] = self.mapping_type.get_type()\n return es.search(**kwargs)","sub_path":"gum/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"508272473","text":"# Copyright 2018, Antoine \"hashar\" Musso\n# Copyright 2018, Wikimedia Foundation Inc.\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 logging\nimport os\nimport subprocess\n\n\ndef update(args, mwdir=None):\n log = logging.getLogger('mw.maintenance.update')\n\n cmd = ['php', 'maintenance/update.php', '--quick']\n cmd.extend(args)\n log.info(' '.join(cmd))\n\n update_env = {}\n update_env.update(os.environ)\n if mwdir is not None:\n update_env['MW_INSTALL_PATH'] = mwdir\n\n p = subprocess.Popen(cmd, cwd=mwdir, env=update_env)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'Update failed with exit code: %s' % p.returncode)\n\n\ndef install(args, mwdir=None):\n log = logging.getLogger('mw.maintenance.install')\n\n cmd = ['php', 'maintenance/install.php']\n cmd.extend(args)\n cmd.extend([\n '--with-extensions', # T189567\n '--pass=testwikijenkinspass',\n 'TestWiki',\n 'WikiAdmin'\n ])\n log.info(' '.join(cmd))\n\n install_env = {}\n install_env.update(os.environ)\n\n # LANG is passed to $wgShellLocale\n install_env.update({'LANG': 'C.UTF-8'})\n\n p = subprocess.Popen(cmd, cwd=mwdir, env=install_env)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'Install failed with exit code: %s' % p.returncode)\n\n\ndef rebuildLocalisationCache(lang=['en'], mwdir=None):\n log = logging.getLogger('mw.maintenance.rebuildLocalisationCache')\n cmd = ['php', 'maintenance/rebuildLocalisationCache.php']\n cmd.extend(['--lang', ','.join(lang)])\n log.info(' '.join(cmd))\n\n p = subprocess.Popen(cmd, cwd=mwdir)\n p.communicate()\n if p.returncode > 0:\n raise Exception(\n 'rebuildLocalisationCache failed with exit code: %s' % (\n p.returncode))\n","sub_path":"quibble/mediawiki/maintenance.py","file_name":"maintenance.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"132457225","text":"from flask import request\nfrom . import metrics\n\n\nclass MetricsRegister:\n common_counter = metrics.counter(\n \"flask_by_endpoint_counter\",\n \"Request count by endpoints\",\n labels={\"endpoint\": lambda: request.endpoint},\n )\n\n @classmethod\n def register_defaults(cls):\n # register additional default metrics\n metrics.register_default(\n metrics.counter(\n \"flask_by_path_counter\",\n \"Request count by request paths\",\n labels={\"path\": lambda: request.path},\n )\n )\n","sub_path":"webserver/metrics/metrics_register.py","file_name":"metrics_register.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"458921931","text":"import sys, os \nimport pandas as pd\nimport datetime\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"winerama.settings\")\n\nimport django\ndjango.setup()\n\nfrom reviews.models import Review, Wine \n\ndef save_review_from_row(review_row):\n review = Review()\n\n # id, username, wine_id, rating, published_date, comment\n\n review.id = int(review_row[0]) + 1\n\n review.user_name = review_row[5]\n\n review.wine = Wine.objects.get(id=review_row[2])\n\n review.rating = review_row[3]\n\n review.pub_date = datetime.datetime.now()\n\n review.comment = datetime.datetime.fromtimestamp(\n int(review_row[4])\n ).strftime('%Y-%m-%d %H:%M:%S')\n\n print(review.id, \n review.user_name,\n review.wine,\n review.rating,\n review.pub_date,\n review.comment)\n\n review.save()\n \n \nif __name__ == \"__main__\":\n \n if len(sys.argv) == 2:\n print(\"Reading from file \" + str(sys.argv[1]))\n reviews_df = pd.read_csv(sys.argv[1])\n print(reviews_df)\n\n #reviews_df.apply(\n # save_review_from_row,\n # axis=1\n #)\n \n objs = [\n Review(\n id=index,\n user_name=e.username,\n user_id = e.UserID,\n wine=Wine.objects.get(id=e.MovieID),\n rating=e.Rating,\n pub_date=datetime.datetime.now(),\n comment=e.Timestamp\n )\n for index, e in reviews_df.iterrows()\n ]\n\n msg = Review.objects.bulk_create(objs)\n\n print(\"There are {} reviews in DB\".format(Review.objects.count()))\n \n else:\n print(\"Please, provide Reviews file path\")\n","sub_path":"load_ratings.py","file_name":"load_ratings.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"200971952","text":"from dimensions import DIMENSIONS\n\n\ndef test_list_structure():\n \"\"\"\n 1. Test DIMENSIONS is a list of dictionaries\n 2. Test the number of dimensions IMPORTANT: If test is to be restructured on a different number\n of dimension this is the only test that should be corrected\n \"\"\"\n assert type(DIMENSIONS).__name__ == 'list'\n actual_list_structure = set((type(elem).__name__ for elem in DIMENSIONS))\n expected_list_structure = {'dict'}\n assert actual_list_structure == expected_list_structure\n assert len(DIMENSIONS) == 6\n\n\ndef test_element_structure():\n \"\"\"\n 1. Test that all dictionaries have proper keys\n \"\"\"\n actual_element_keys = set(k for elem in DIMENSIONS for k in elem)\n expected_element_keys = {'name', 'answers'}\n assert actual_element_keys == expected_element_keys\n\n\ndef test_number_of_answers_per_dimension():\n \"\"\"\n 1. Test the correlation between the number of dimensions and the number of answers\n \"\"\"\n n = len(DIMENSIONS)\n actual_number = set(len(elem['answers']) for elem in DIMENSIONS)\n expected_number = {2 * (n - 1)}\n assert actual_number == expected_number\n","sub_path":"python-solution/tests/test_dimensions.py","file_name":"test_dimensions.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"459338390","text":"import matplotlib.pyplot as plt\nimport torch\n\n\ndef show_batch(dataloader):\n n = dataloader.batch_size\n imgs, masks = next(iter(dataloader))\n print(len(imgs), imgs.shape)\n imgs = imgs.permute(0, 2, 3, 1)\n plt.figure(figsize=(12, 5))\n for i in range(dataloader.batch_size):\n ax1 = plt.subplot(2, n, i+1)\n ax1.imshow(imgs[i])\n ax1.axis('off')\n ax2 = plt.subplot(2, n, n+i+1)\n ax2.imshow(masks[i])\n ax2.axis('off')\n plt.show()","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"577589355","text":"#!/usr/bin/python\nimport os,datetime\nfrom time import *\nimport time \nfrom datetime import datetime,timedelta\nfrom time import mktime\n#Zugriff auf den Feiertagskalender des gewaehlten Jahres\n\ndef Feiertagskalender():\n\t\tJahr = raw_input(\"Jahr:\")\n\t\tJahr = int(Jahr)\n\t\ta = Jahr % 19\n\t\tb = Jahr % 4\n\t\tc = Jahr % 7\n\t\tk = Jahr / 100\n\t\tp = (8 * k + 13) / 25\n\t\tq = k / 4\n\t\tM = (15 + k - p - q) % 30\n\t\td = (19 * a + M) % 30\n\t\tN = (4 + k -q) % 7\n\t\te = (2 * b + 4 * c + 6 * d + N) % 7\n\t\tTage = (21 + d + e)\n\t\tdatum = '01.03.' + str(Jahr)\n\t\tdatum1 = time.strptime(datum,'%d.%m.%Y')\n\t\tostern = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage)\n\t\tostern = ostern.strftime('%d.%m.%Y')\n\t\taschermittwoch = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(46)\n\t\taschermittwoch = aschermittwoch.strftime('%d.%m.%Y')\n\t\tpalmsonntag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(7)\n\t\tpalmsonntag = palmsonntag.strftime('%d.%m.%Y')\n\t\tgruendonnerstag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(3)\n\t\tgruendonnerstag = gruendonnerstag.strftime('%d.%m.%Y')\n\t\tkarfreitag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) - timedelta(2)\n\t\tkarfreitag = karfreitag.strftime('%d.%m.%Y')\n\t\tostermontag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(1)\n\t\tostermontag = ostermontag.strftime('%d.%m.%Y')\n\t\tchristihimmelfahrt = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(39)\n\t\tchristihimmelfahrt = christihimmelfahrt.strftime('%d.%m.%Y')\n\t\tpfingstsonntag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(49)\n\t\tpfingstsonntag = pfingstsonntag.strftime('%d.%m.%Y')\n\t\tpfingstmontag = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(50)\n\t\tpfingstmontag = pfingstmontag.strftime('%d.%m.%Y')\n\t\tfronleichnam = datetime.fromtimestamp(mktime(datum1)) + timedelta(Tage) + timedelta(60)\n\t\tfronleichnam = fronleichnam.strftime('%d.%m.%Y')\n\t\tneujahr = '01.01.' + str(Jahr)\n\t\tdreikoenige = '06.01.' + str(Jahr)\n\t\tweihnachten = '25.12.' + str(Jahr)\n\t\tstephanstag = '26.12.' + str(Jahr)\n\t\tnationalfeiertag = '01.08.' + str(Jahr)\n\t\tsilvester = '31.12.' + str(Jahr)\n\t\tf = open('Feiertagskalender.txt','w')\n\t\tf.write((str(\"Ostern:\")) + \"\" + (str(ostern)) + \"\\n\") \n\t\tf.write((str(\"Aschermittwoch:\")) + \"\" + (str(aschermittwoch)) + \"\\n\")\n\t\tf.write((str(\"Palmsonntag:\")) + \"\" + (str(palmsonntag)) + \"\\n\")\n\t\tf.write((str(\"Gruendonnertag:\")) + \"\" +(str(gruendonnerstag)) + \"\\n\")\n\t\tf.write((str(\"Karfreitag:\")) + \"\" + (str(karfreitag)) + \"\\n\")\n\t\tf.write((str(\"Ostermontag:\")) + \"\" +(str(ostermontag))+ \"\\n\")\n\t\tf.write((str(\"Christihimmelfahrt:\")) + \"\" + (str(christihimmelfahrt)) + \"\\n\")\n\t\tf.write((str(\"Pfingssonntag:\")) + \"\" + (str(pfingstsonntag)) + \"\\n\")\n\t\tf.write((str(\"Pfingsmontag:\")) + \"\" + (str(pfingstmontag)) + \"\\n\")\n\t\tf.write((str(\"Fronleichnahm:\")) + \"\" + (str(fronleichnam)) + \"\\n\")\n\t\tf.write((str(\"Neujahr:\")) + \"\" + (str(neujahr)) + \"\\n\")\n\t\tf.write((str(\"Dreikoenigstag:\")) + \"\" + (str(dreikoenige)) + \"\\n\")\n\t\tf.write((str(\"Weihnachten:\")) + \"\" + (str(weihnachten)) + \"\\n\")\n\t\tf.write((str(\"Stephanstag:\")) + \"\" + (str(stephanstag)) + \"\\n\")\n\t\tf.write((str(\"Nationalfeiertag:\")) + \"\" + (str(nationalfeiertag)) + \"\\n\" )\n\t\tf.write((str(\"Silvester:\")) + \"\" + (str(silvester)) + \"\\n\")\n\n\t\tf.close()\nFeiertagskalender()\n\ndef Sortieren():\n\t\tos.system('sort Feiertagskalender.txt > Feiertage.txt')\n\t\tos.system('rm Feiertagskalender.txt')\n\nSortieren()\n","sub_path":"Time/ostern/Feiertage.py","file_name":"Feiertage.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"15025638","text":"# -*- coding: utf-8 -*-\nimport pusher\nimport json\nimport requests\nimport webapp2\nfrom django.shortcuts import render_to_response\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.template import RequestContext\n# from django.core.serializers.json import DjangoJSONEncoder\nfrom ChatAdmin.models import PeopleModelForm\n\n\npusher.app_id = settings.PUSHER_APP_ID\npusher.key = settings.PUSHER_KEY\npusher.secret = settings.PUSHER_SECRET\n\np = pusher.Pusher()\n\n\ndef home(request):\n if not request.session.get('user'):\n request.session['user'] = 'user-%s' % request.session.session_key\n return render_to_response('pusher_index.html', {\n 'PUSHER_KEY': settings.PUSHER_KEY,\n }, RequestContext(request))\n\n\ndef message(request):\n if request.session.get('user') and request.POST.get('name') and request.POST.get('message') \\\n and request.POST.get('email'):\n p['chat'].trigger('message', {\n 'user': request.session['user'],\n 'name': request.POST.get('name'),\n 'email': request.POST.get('email'),\n 'message': request.POST.get('message'),\n })\n return HttpResponse('')\n\n\nclass AuthHandler(webapp2.RequestHandler):\n def post(self):\n channel_name = self.request.get('chat')\n socket_id = self.request.get('socket_id')\n p = pusher.Pusher(app_id=pusher.app_id, key=pusher.key, secret=pusher.secret)\n\n auth = p[channel_name].authenticate(socket_id)\n json_data = json.dumps(auth)\n self.response.out.write(json_data)\n\n\ndef main():\n application = webapp2.WSGIApplication([('/pusher/auth', AuthHandler)])\n\n\n\n\n\n\n\n","sub_path":"SupportChat/pusher_server_api.py","file_name":"pusher_server_api.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"366653203","text":"# -*- coding: utf-8 -*-\n\ndef isPalindrome(x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n ret = 0\n temp = abs(x)\n \n while temp != 0:\n remainder = temp % 10\n ret = ret * 10 + remainder\n temp = int (temp / 10)\n \n if x >= 0 and x == ret:\n return True\n else:\n return False","sub_path":"PalindromeNumber.py","file_name":"PalindromeNumber.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"357748969","text":"#!/usr/bin/env python3\nimport asyncio\n\nimport argparse\nimport raftos\nimport random\nimport string\n\ndef randomword(length):\n return ''.join(random.choice(string.ascii_lowercase) for i in range(length))\n\nasync def run(node_id, peers):\n # List of songs\n song_list = raftos.ReplicatedList(name = 'song_list')\n\n # Song distributions\n which_song = raftos.ReplicatedDict(name = 'which_song')\n\n await raftos.wait_until_leader(node_id)\n for i in range(5):\n song = node_id + ' => ' + randomword(random.randint(3, 5))\n print (song)\n await song_list.append(song)\n\n while True:\n # Brought to you by :\n await raftos.wait_until_leader(node_id)\n snapshot = await song_list.get()\n song = snapshot.pop() if(len(snapshot) > 0) else None\n await song_list.set(snapshot)\n\n song is not None and print ('leader: select, %r' % song)\n\n # And boom goes the dynamite\n snapshot = await which_song.get()\n for peer in peers:\n snapshot[peer] = song\n await which_song.set(snapshot)\n\n # The Devil opened up his case and he said, \"I'll start this show.\"\n # And fire flew from his fingertips as he rosined up his bow.\n # And he pulled the bow across the strings and it made an evil hiss.\n # And a band of demons joined in and it sounded something like this.\n keys = await which_song.keys()\n if (node_id in keys):\n song = await which_song[node_id]\n\n print (song)\n await asyncio.sleep(60)\n\nif (__name__ == '__main__'):\n parser = argparse.ArgumentParser()\n parser.add_argument('--node')\n parser.add_argument('--cluster')\n args = parser.parse_args()\n\n cluster = ['127.0.0.1:{}'.format(port) for port in args.cluster.split()]\n node = '127.0.0.1:{}'.format(args.node)\n\n raftos.configure({\n 'log_path': './',\n 'serializer': raftos.serializers.JSONSerializer\n })\n\n loop = asyncio.get_event_loop()\n loop.create_task(raftos.register(node, cluster=cluster))\n loop.run_until_complete(run(node, cluster))\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"599830422","text":"import spacy\nfrom spacy.matcher import Matcher\n\nnlp = spacy.load(\"zh_core_web_sm\")\nmatcher = Matcher(nlp.vocab)\n\ndoc = nlp(\n \"我之前有去下载Dota到电脑上面,但是根本打不开游戏,怎么办?\"\n \"我下载Minecraft,是Windows的版本,下载后是一个'.zip'的文件夹,然后我用了默认软件做了\"\n \"解压...我是不是还需要去下载Winzip?\"\n)\n\n# 写一个模板来匹配\"下载\"加一个代词\npattern = [{\"TEXT\": \"下载\"}, {\"POS\": \"PROPN\"}]\n\n# 把模板加入到matcher中,然后把matcher应用到doc上面\nmatcher.add(\"DOWNLOAD_THINGS_PATTERN\", None, pattern)\nmatches = matcher(doc)\nprint(\"Total matches found:\", len(matches))\n\n# 遍历所有的匹配,打印span的文本\nfor match_id, start, end in matches:\n print(\"Match found:\", doc[start:end].text)","sub_path":"exercises/zh/solution_01_12_02.py","file_name":"solution_01_12_02.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"637571581","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n# operation codes:\nHLT = 0b00000001\nLDI = 0b10000010\nPRN = 0b01000111\nMUL = 0b10100010\nPUSH = 0b01000101\nPOP = 0b01000110\n # reserved registers\nIM = 5\nIS = 6\nSP = 7\n # flags\nFL_LT = 0b100\nFL_GT = 0b010\nFL_EQ = 0b001\nFL_TIMER = 0b00000001\nFL_KEYBOARD = 0b00000010\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0]*256\n self.reg = [0]*8\n self.reg[SP] = 0xf4\n\n self.processCounter = 0\n self.flags = 0\n # self.interrupts = 1;\n self.isPaused = False\n # self.last_timer_int = None\n self.instruction_sets_processCounter = False\n\n self.branchTree = {\n HLT: self.op_HLT,\n LDI: self.op_LDI,\n PRN: self.op_PRN,\n MUL: self.op_MUL,\n PUSH: self.op_PUSH,\n POP: self.op_POP\n }\n\n def load(self):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n fp = open(filename, \"r\")\n for line in fp:\n # split by comment and strip empty spaces\n instruction = line.split(\"#\")[0].strip()\n if instruction == \"\":\n continue\n value = int(instruction, 2)\n self.ram[address] = value\n address += 1\n\n def stack_push(self, val):\n self.reg[SP] -= 1\n self.ram_write(self.reg[SP], val)\n\n def stack_pop(self):\n val = self.ram_read(self.reg[SP])\n self.reg[SP] += 1\n return val\n\n def ram_read(self, index):\n return self.ram[index]\n\n def ram_write(self, index, value):\n self.ram[index] = value\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 == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\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 not self.isPaused:\n ir = self.ram[self.processCounter]\n operand_a = self.ram_read(self.processCounter + 1)\n operand_b = self.ram_read(self.processCounter + 2)\n\n instruction_size = ( ir >> 6 ) + 1\n self.instruction_sets_processCounter = ( (ir >> 4) &0b1 ) == 1\n\n if ir in self.branchTree:\n self.branchTree[ir](operand_a, operand_b)\n else:\n raise Exception(f'Unknown Instruction {bin(ir)} at {hex(self.processCounter)}')\n\n if not self.instruction_sets_processCounter:\n self.processCounter += instruction_size\n\n def op_HLT(self, operand_a, operand_b):\n self.isPaused = True\n\n def op_LDI(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_PRN(self, operand_a, operand_b):\n print(self.reg[operand_a])\n \n def op_MUL(self, operand_a, operand_b):\n self.alu(\"MUL\", operand_a, operand_b)\n\n def op_PUSH(self, operand_a, operand_b):\n self.stack_push(self.reg[operand_a])\n\n def op_POP(self, operand_a, operand_b):\n self.reg[operand_a] = self.stack_pop()\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":3694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"272670376","text":"#-*- coding:utf-8 -*_\r\nimport os\r\nimport numpy\r\n\r\n\r\n#-------将目录下的图片路径逐行读入txt文件中-----------\r\npath = os.getcwd()\r\nimg_path = os.path.join(path, \"res/video/white\")\r\nimg_list = [os.path.join(img_path, x) for x in os.listdir(img_path) if x.endswith(\".jpg\")]\r\n\r\ntxt_file = \"realdata.txt\"\r\ntxt_path = os.path.join(path, txt_file)\r\nif os.path.exists(txt_path):\r\n os.remove(txt_path)\r\n\r\nobj = open(txt_path, 'w')\r\nfor img in img_list:\r\n obj.writelines(img)\r\n obj.writelines('\\n') #每次写入一个路径之后再写一个换行符\r\nobj.close()\r\nprint(\"the txt file has done\")\r\n\r\n\r\n","sub_path":"press_detect/some_file/to_txt.py","file_name":"to_txt.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"245326690","text":"# udp的recvfrom是阻塞的,\n# 一個recvfrom(x)必須對唯一一個sendinto(y),收完了x個字節的數據就算完成,若是y>x數據就丟失,\n# 這意味著udp根本不會粘包,但是會丟數據,不可靠\n\nfrom socket import *\n\nip_port = ('127.0.0.1', 8000)\nbuffer_size = 1024\n\nudp_server = socket(AF_INET, SOCK_DGRAM) # SOCK_DGRAM基於UDP協議\nudp_server.bind(ip_port) # 將地址綁到服務器\n\nwhile True:\n data, addr = udp_server.recvfrom(buffer_size)\n print('客戶端發來的信息 ', data)\n udp_server.sendto(data.upper(), addr)\n","sub_path":"SelfLearn/網路編程/180802_socket/180803_UDPserver.py","file_name":"180803_UDPserver.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"581169282","text":"#!/usr/bin/env python\r\n\r\nfrom os.path import exists\r\nfrom setuptools import setup\r\n\r\npackages = [\"rapidz\", \"rapidz.dataframe\"]\r\n\r\ntests = [p + \".tests\" for p in packages]\r\n\r\n\r\nsetup(\r\n name=\"rapidz\",\r\n version='0.2.1',\r\n description=\"Streams\",\r\n url=\"http://github.com/xpdAcq/rapidz/\",\r\n maintainer=\"Simon Billinge\",\r\n maintainer_email=\"simon.billinge@gmail.com\",\r\n license=\"BSD\",\r\n keywords=\"streams\",\r\n packages=packages + tests,\r\n python_requires='>=3.9',\r\n long_description=(\r\n open(\"README.rst\").read() if exists(\"README.rst\") else \"\"\r\n ),\r\n install_requires=list(open(\"requirements.txt\").read().strip().split(\"\\n\")),\r\n zip_safe=False,\r\n)\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"122529476","text":"import random\n\nclass Room(object):\n\n def __init__(self, terrain, pos):\n self.name = terrain.name\n self.description = terrain.description\n self.terrain = terrain\n self.pos = pos\n self.exits = dict()\n self.contents = list()\n self.contents.extend(terrain.gen_resources())\n\n def mine(self):\n \"\"\"Yield some material from mining.\"\"\"\n mined_resource = None\n total_weight = 1000\n for resource in self.contents:\n if not resource.is_mineral_resource: continue\n\n total_weight += resource.weight\n if random.random() < resource.weight/total_weight:\n mined_resource = resource\n\n if not mined_resource:\n return None\n\n result = mined_resource.mine()\n if not result:\n return None\n\n self.contents.append(result)\n\n if mined_resource.weight <= 0:\n self.contents.remove(mined_resource)\n\n return result\n","sub_path":"mineraffair/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"189067863","text":"class Solution:\n def countAndSay(self, n: int) -> str:\n if n == 1:\n return \"1\"\n\n s = self.countAndSay(n - 1)\n ans = \"\"\n count = 0\n i = 0\n c = s[i]\n while i < len(s):\n if c == s[i]:\n count += 1\n else:\n ans += str(count) + s[i - 1]\n c = s[i]\n count = 1\n i += 1\n ans += str(count) + s[i - 1]\n return ans\n\n\ndef main():\n print(\"hello world\")\n test = Solution()\n for i in range(1, 10):\n print(test.countAndSay(i))\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/38_count_and_say.py","file_name":"38_count_and_say.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"106988343","text":"import time\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.by import By\n\ndef scroll_to(driver, element):\n y_pos = element.location['y']\n driver.execute_script(\"window.scrollTo(0, \" + str(y_pos - 100) + \")\")\n time.sleep(0.5)\n\ndef wait_for_element(driver, class_name, ind):\n times = 0\n while len(driver.find_elements_by_class_name(class_name)) < ind+1:\n time.sleep(0.2)\n times = times + 0.2\n if times > 5:\n return 1\n return 0\n\ndef wait_for_results(driver):\n '''\n Wait for page to load all results\n '''\n time.sleep(1)\n # Pick location if needed\n if len(driver.find_elements_by_class_name('gdpr-vx-consent-bar-button'))>0:\n driver.find_element_by_class_name('gdpr-vx-consent-bar-button').click()\n time.sleep(1)\n if len(driver.find_elements(By.ID, \"setting-location\"))!=0:\n driver.find_element_by_class_name('close').click()\n time.sleep(1)\n select = Select(driver.find_element_by_id('setting-location'))\n select.select_by_index(1)\n time.sleep(1)\n driver.find_element_by_class_name('energy-button').click()\n time.sleep(1)\n\n # Wait until first results are loaded\n wait_for_element(driver, 'result-price', 0)\n prices = driver.find_elements_by_class_name('result-price')\n time.sleep(1)\n\n # Only one offer per company\n\n button = driver.find_element_by_class_name('foldout-trigger.button-toggle-touch')\n scroll_to(driver, button)\n time.sleep(3)\n button.click()\n time.sleep(1)\n button = driver.find_elements_by_class_name('energy-select')[-2]\n scroll_to(driver, button)\n select = Select(button)\n select.select_by_index(0)\n time.sleep(1)\n\n\n\n # Scroll to end of page and pick all results\n\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(1)\n driver.find_elements_by_class_name('highlight-text')[-10].click()\n time.sleep(5)\n prices = driver.find_elements_by_class_name('result-price')\n return prices\n\ndef get_info(driver, class_name, ind, times=1):\n time.sleep(times)\n wait = wait_for_element(driver, class_name, ind)\n if wait:\n return 0\n else:\n element = driver.find_elements_by_class_name(class_name)[ind]\n return element.get_attribute('innerText')\n\ndef get_infos(driver, class_name, times=1):\n time.sleep(times)\n element = driver.find_elements_by_class_name(class_name)\n texts = [ele.get_attribute('innerText') for ele in element]\n return texts\n\ndef show_details(driver, ind):\n button = driver.find_elements_by_class_name('button-text-open')[ind]\n scroll_to(driver, button)\n time.sleep(1)\n button.click()\n\ndef hide_details(driver, ind):\n button = driver.find_elements_by_class_name('button-text-close')[ind]\n scroll_to(driver, button)\n button.click()\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"163081616","text":"# -*- coding: utf-8 -*-\n\n# python std lib\nimport sys\nimport os\nimport unittest\nfrom contextlib import contextmanager\n\n# Ensures that the $PACKAGE$ lib/ folder exists in path so imports will work proper.\nsys.path.append('lib')\n\n# Import used to localize source files\nimport pykwalify\n\n# python std logging\nimport logging\nimport logging.config\n\nLog = None\nIN_VIRTUALENV = True if hasattr(sys, 'real_prefix') else False\nif IN_VIRTUALENV:\n path = os.path.join(sys.prefix, 'etc', \"pykwalify\", 'logging.ini')\n if not os.path.exists(path): # we are not installed, running from source tree\n (prefix, bindir) = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0])))\n path = os.path.join(prefix, \"pykwalify\", \"config\", \"logging.ini\")\n logging.config.fileConfig(path)\nelse:\n logging.config.fileConfig(os.path.join(os.sep, 'etc', \"pykwalify\", 'logging.ini'))\nLog = logging.getLogger()\n\n# Use this regexp to validate any logging output\nlogging_regex = \"%s - %s:[0-9]+ - %s\" # % (LoggingLevel, LoggerName, Msg)\n\n# Set the root logger to be silent so all code that uses the python logger\n# will not print anything unless we want it to, then it should be specified\n# in each test and reseted after that test\ndef _set_log_lv(level = 1337, loggers = None):\n \"\"\" If no level is set then level will be so high all logging is silenced\n \"\"\"\n if loggers is None:\n # If no additional loggers is specified then only apply to root logger\n Log.setLevel(level)\n for handler in Log.handlers:\n handler.level = level\n else:\n # If we have other logging instances specified apply to root logger and them\n if not Log in loggers:\n loggers.append(Log)\n\n for log_instance in loggers:\n log_instance.setLevel(level)\n for handler in log_instance.handlers:\n handler.level = level\n\ndef get_log_lv():\n return Log.level\n\n# Initially silence all logging \n_set_log_lv()\n\nfrom io import StringIO\nfrom pykwalify.utils import *\n\nclass TestHelper(unittest.TestCase):\n \"\"\" NEVER EVER do assertion inside one of the context managers in this class unless it is\n specified in each functions documentation that it is safe to use assertsions inside it\n \"\"\"\n\n @contextmanager\n def _custom_argv(self, new_args): \n \"\"\" Used when simulating a call to an script/code that requires cli inputs.\n\n new_args - must be a list [] type\n \"\"\"\n self.assertTrue(isinstance(new_args, list),\n msg=\"input argument not valid list\")\n\n new_args.insert(0, \"\")\n backup_args = sys.argv # Backups the existing argv:s\n sys.argv = new_args # Sets the new argv\n yield\n sys.argv = backup_args\n\n @contextmanager\n def _set_log_lv(self, level=1337, loggers = None):\n \"\"\" Sets a specified logging level and resets it when done\n \"\"\"\n backup_log_lv = get_log_lv()\n _set_log_lv(level = level, loggers = loggers)\n yield\n _set_log_lv(level = backup_log_lv, loggers = loggers)\n\n\n__all__ = []\n\ndef run(argv):\n #unittest.main()\n loader = unittest.TestLoader()\n loader.sortTestMethodsUsing = None\n suite = unittest.TestSuite()\n \n tests = []\n \n # called without arguments\n if len(argv) == 1:\n for test in __all__:\n suite.addTests(loader.loadTestsFromTestCase(test))\n tests.append(str(test))\n # called with arguments, iterate over the list and run specified tests\n else:\n argv.pop(0) # remove ourself\n for name in sys.argv:\n try:\n test = getattr(sys.modules['tests'], name)\n except AttributeError:\n continue\n suite.addTests(loader.loadTestsFromTestCase(test))\n tests.append(name)\n \n print(\"TESTS: %s\" % ', '.join(tests))\n \n # Can be used to reduce the output from the tests if so desired\n if \"verbosity\" in os.environ:\n verbosity = int(os.environ[\"verbosity\"])\n else:\n verbosity = 2\n\n unittest.TextTestRunner(verbosity=verbosity).run(suite)\n\n\ndef gettestcwd(*args):\n \"\"\" Because os.getcwd() cannot be guaranted to work in all cases where the invoke path is\n from another place rather then where runtests.py script is located.\n This function should be used because it returns the abspath to the runtets.py script that \n should manually be concated with any relative path to locate any testfiles.\n To get to the subfolder /tests/ that must be explicit added as extra positional argument to *args\n \"\"\"\n (prefix, bindir) = os.path.split(os.path.dirname(os.path.abspath(sys.argv[0])))\n return concat_path(prefix, bindir, *args)\n\n\ndef concat_path(b, *args):\n \"\"\" Concats b with all arguments in '*args', handles if any argument contains more then 1 directory, example: foo/bar/asd/\n\n Note: this is analogous to list_path() except that this function returns a\n string, though this function is not cross-platform since it uses a\n hardcoded \"/\" instead of os.sep.\n\n Arguments:\n - `b`: string - base from where to concat all '*args'\n - `*args`: strings - all extra paths to concat, concats in order of list\n \"\"\"\n base = b # tmp var\n for a in args:\n if \"/\" in a:\n for s in a.split(\"/\"):\n base = os.path.join(base, s)\n else:\n base = os.path.join(base, a)\n\n return base\n","sub_path":"tests/testhelper.py","file_name":"testhelper.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"503960829","text":"# -*- coding: utf-8 -*-\n\nimport pytest\n\nfrom ..parser.parser import EmailParser, Tokenizer\nfrom ..exc import ParseError, TokenizeError\n\n\nclass TestEmailParser(object):\n\n @pytest.mark.parametrize('from_address, expected_nickname, expected_email', [\n pytest.param('Eva Chen ',\n 'Eva Chen',\n 'ceo1.ccs@trend.com.tw',\n id='FAST001'),\n pytest.param('eva_chen@trendmicro.com ',\n 'eva_chen@trendmicro.com',\n 'ceo2.ccs@trend.com.jp',\n id='FAST002'),\n pytest.param('',\n None,\n 'ceo3.ccs@trend.com.jp',\n id='FAST003'),\n pytest.param('ceo4.ccs@roadrunner.com',\n None,\n 'ceo4.ccs@roadrunner.com',\n id='FAST004'),\n ])\n def test_parse_from_addr_fast(self,\n from_address,\n expected_nickname,\n expected_email):\n\n actual_nickname, actual_email = EmailParser.parse_addr(from_address)\n assert expected_nickname == actual_nickname\n assert expected_email == actual_email\n\n @pytest.mark.parametrize('from_address', [\n pytest.param('', id='TOFT002'),\n pytest.param('<>', id='TOFT003'),\n ])\n def test_parse_from_address_toft(self, from_address):\n _, _ = EmailParser.parse_addr(from_address)\n\n @pytest.mark.parametrize('from_address', [\n pytest.param(None, id='FET001')\n ])\n def test_parse_from_address_fet(self, from_address):\n with pytest.raises(ParseError):\n _, _ = EmailParser.parse_addr(from_address)\n\n @pytest.mark.parametrize('email,expected_domain', [\n pytest.param('ceo.ccs@roadrunner.com',\n 'roadrunner.com',\n id='FAST001'),\n pytest.param('ceo.ccs@not_me@roadrunner.com',\n 'roadrunner.com',\n id='FAST002'),\n pytest.param('ceo.ccsnot_meroadrunner.com',\n None,\n id='FAST003')\n ])\n def test_parse_domain_from_email_fast(self, email, expected_domain):\n actual_domain = EmailParser.parse_domain(email)\n assert expected_domain == actual_domain\n\n\nclass TestTokenizer(object):\n\n @pytest.mark.parametrize('raw_str,expected_token_list', [\n pytest.param('eva_chen@trendmicro.com',\n {'eva', 'chen', 'trendmicro', 'com'},\n id='FAST001'),\n pytest.param('Eva Chen',\n {'eva', 'chen'},\n id='FAST002'),\n pytest.param('Eva;Chen#Luby,Lien.Vincent Lee,',\n {'eva', 'chen', 'luby', 'lien', 'vincent', 'lee'},\n id='FAST003'),\n pytest.param('(Eva Chen)',\n {'eva', 'chen'},\n id='FAST004'),\n pytest.param('[Eva Chen]',\n {'eva', 'chen'},\n id='FAST005'),\n pytest.param('{Eva Chen}',\n {'eva', 'chen'},\n id='FAST006'),\n pytest.param('Eva_Chen',\n {'eva', 'chen'},\n id='FAST007'),\n pytest.param('\"Eva_Chen\"',\n {'eva', 'chen'},\n id='FAST008'),\n ])\n def test_normalized_tokenize_fast(self, raw_str, expected_token_list):\n actual_token_list = Tokenizer.normalized_tokenize(raw_str)\n assert expected_token_list == actual_token_list\n\n @pytest.mark.parametrize('raw_str', [\n pytest.param(None, id='FET001')\n ])\n def test_normalized_tokenize_fet(self, raw_str):\n with pytest.raises(TokenizeError):\n _ = Tokenizer.normalized_tokenize(raw_str)\n","sub_path":"common/parser/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"372507297","text":"#!/usr/bin/env python\n\nimport os, re, string, subprocess, sys, importlib\nImport('env')\nsys.path.append(os.getenv(\"MUSE_WORK_DIR\")+'/site_scons')\n#------------------------------------------------------------------------------\n# print(\"Stntuple/SConscript:muse branch: PWD:\"+os.getenv(\"PWD\"))\n\n# pass the package name as a parameter\n\nx = subprocess.call(os.getenv(\"MUSE_WORK_DIR\")+'/Stntuple/scripts/build_config_muse Stntuple',shell=True)\n# print(\"Stntuple/SConscript back from build_config_muse\")\n\nstntuple_env = env.Clone()\n#------------------------------------------------------------------------------\n# done\n#------------------------------------------------------------------------------\nexec(open(os.environ['MUSE_WORK_DIR']+\"/site_scons/stntuple_site_init.py\").read())\n\nfrom stntuple_helper import *\n\nstntuple_env.Append(BUILDERS = {'StntupleCodegen' : stntuple_codegen })\nstntuple_env.Append(BUILDERS = {'StntupleRootCint' : stntuple_rootcint})\n\nstntuple_env['CPPPATH' ].append(os.environ['MUSE_WORK_DIR']+'/include');\n\nstntuple_env.Append(FORTRANPATH = [os.environ['MUSE_WORK_DIR']+'/include']);\n\n# print(stntuple_env.Dump())\n\nExport('stntuple_env')\nExport('stntuple_helper')\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"409250130","text":"from odoo import fields, models, api, _\nfrom datetime import datetime, date, timedelta\nimport requests\nimport json\nfrom odoo.exceptions import UserError\n\nclass ResUesrs(models.Model):\n _inherit= 'res.users'\n\n @api.model\n def create(self, vals):\n res = super(ResUesrs, self).create(vals)\n data = {\n 'name': res.name,\n 'username': res.login,\n 'password': res.password,\n 'userid': res.name,\n 'wing_id': res.name,\n 'section_id': res.name,\n 'designation_id': res.name,\n 'email': res.login,\n 'mobile': res.name,\n 'user_type_id': res.name,\n 'is_wing_head': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/add-user/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)\n\n\n\nclass HrDepartment(models.Model):\n _inherit= 'hr.department'\n\n @api.model\n def create(self, vals):\n res = super(HrDepartment, self).create(vals)\n data = {\n 'name': res.name,\n 'dept_id': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/department/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)\n\n\nclass HrJob(models.Model):\n _inherit= 'hr.job'\n\n @api.model\n def create(self, vals):\n res = super(HrJob, self).create(vals)\n data = {\n 'name': res.name,\n 'designation_id': res.name,\n 'user_id': res.name,\n }\n\n req = requests.post('http://103.92.47.152/STPI/www/web-service/designation/', data=data,\n json=None)\n try:\n # print('=====================================================', req)\n pastebin_url = req.text\n print('===========================pastebin_url==========================', pastebin_url)\n dictionary = json.loads(pastebin_url)\n except Exception as e:\n print('=============Error==========', e)","sub_path":"smart_office/models/res_users.py","file_name":"res_users.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"327066656","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\nclass Ui_Target(object):\r\n def setupUi(self, Dialog):\r\n Dialog.setObjectName(\"Dialog\")\r\n Dialog.resize(467, 160)\r\n icon = QtGui.QIcon()\r\n icon.addPixmap(QtGui.QPixmap(\":/images/1.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\r\n Dialog.setWindowIcon(icon)\r\n Dialog.setStyleSheet(\"border-image: url(:/images/BackGround.jpg);\")\r\n self.gridLayout = QtWidgets.QGridLayout(Dialog)\r\n self.gridLayout.setObjectName(\"gridLayout\")\r\n self.verticalLayout = QtWidgets.QVBoxLayout()\r\n self.verticalLayout.setObjectName(\"verticalLayout\")\r\n spacerItem = QtWidgets.QSpacerItem(428, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)\r\n self.verticalLayout.addItem(spacerItem)\r\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\r\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\r\n spacerItem1 = QtWidgets.QSpacerItem(28, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem1)\r\n self.label = QtWidgets.QLabel(Dialog)\r\n self.label.setMinimumSize(QtCore.QSize(215, 21))\r\n font = QtGui.QFont()\r\n font.setFamily(\"MS Shell Dlg 2\")\r\n font.setPointSize(10)\r\n self.label.setFont(font)\r\n self.label.setStyleSheet(\"border-image: url(:/images/1WhiteTransparent.png);\\n\"\r\n\"\")\r\n self.label.setObjectName(\"label\")\r\n self.horizontalLayout_2.addWidget(self.label)\r\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem2)\r\n self.TargetBox = QtWidgets.QComboBox(Dialog)\r\n self.TargetBox.setMinimumSize(QtCore.QSize(81, 18))\r\n font = QtGui.QFont()\r\n font.setPointSize(9)\r\n self.TargetBox.setFont(font)\r\n self.TargetBox.setStyleSheet(\"border-image: url(:/images/1WhiteBackground.jpg);\")\r\n self.TargetBox.setObjectName(\"TargetBox\")\r\n self.TargetBox.addItem(\"\")\r\n self.horizontalLayout_2.addWidget(self.TargetBox)\r\n spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout_2.addItem(spacerItem3)\r\n self.verticalLayout.addLayout(self.horizontalLayout_2)\r\n spacerItem4 = QtWidgets.QSpacerItem(428, 28, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)\r\n self.verticalLayout.addItem(spacerItem4)\r\n self.horizontalLayout = QtWidgets.QHBoxLayout()\r\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\r\n spacerItem5 = QtWidgets.QSpacerItem(318, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout.addItem(spacerItem5)\r\n self.Targets = QtWidgets.QDialogButtonBox(Dialog)\r\n font = QtGui.QFont()\r\n font.setPointSize(10)\r\n self.Targets.setFont(font)\r\n self.Targets.setStyleSheet(\"border-image: url(:/images/1WhiteBackground.jpg);\")\r\n self.Targets.setOrientation(QtCore.Qt.Horizontal)\r\n self.Targets.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)\r\n self.Targets.setObjectName(\"Targets\")\r\n self.horizontalLayout.addWidget(self.Targets)\r\n spacerItem6 = QtWidgets.QSpacerItem(38, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)\r\n self.horizontalLayout.addItem(spacerItem6)\r\n self.verticalLayout.addLayout(self.horizontalLayout)\r\n self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)\r\n\r\n self.retranslateUi(Dialog)\r\n self.Targets.accepted.connect(Dialog.accept)\r\n self.Targets.rejected.connect(Dialog.reject)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Select target\"))\r\n self.label.setText(_translate(\"Dialog\", \"Which is your target column?
\"))\r\n self.TargetBox.setItemText(0, _translate(\"Dialog\", \"SELECT\"))\r\nimport Images_rc\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n Dialog = QtWidgets.QDialog()\r\n ui = Ui_Target()\r\n ui.setupUi(Dialog)\r\n Dialog.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"Target.py","file_name":"Target.py","file_ext":"py","file_size_in_byte":4481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"644126219","text":"import pymongo\n\nclass Mongo:\n \n # 登录注册部分\n def find_by_name(self, username):\n res = self.login.find_one({'username': username})\n return res\n \n def login_add(self, username, nickname, password):\n uid = self.max_uid = self.max_uid + 1\n data = {\n 'username': username,\n 'nickname': nickname,\n 'password': password,\n 'uid': uid\n }\n self.login.insert_one(data)\n return uid\n\n # 设置部分\n def find_by_uid(self, uid):\n res = self.login.find_one({'uid': uid})\n return res\n\n def setting_reset(self, find_res, item, data):\n uid = find_res['uid']\n find_res[item] = data\n cond = {'uid': uid}\n print(data)\n res = self.login.update_one(cond, {'$set': find_res})\n\n # 好友部分\n def friend_add(self, src, dst):\n cond = {'src': src, 'dst': dst}\n res = self.friend.find_one(cond)\n if res is not None:\n res['accept'] = True\n self.friend.update_one(cond, {'$set': res})\n print('{} and {} become friend!'.format(src, dst))\n return\n data = {\n 'src': src,\n 'dst': dst,\n 'accept': False\n }\n self.friend.insert_one(data)\n print('insert data {}'.format(data))\n \n def friend_find(self, src, dst, accept, remove):\n l = []\n cond = {}\n if src != None:\n cond['src'] = src\n if dst != None:\n cond['dst'] = dst\n if accept != None:\n cond['accept'] = accept\n results = self.friend.find(cond)\n for result in results:\n l.append(result)\n if remove == True:\n self.friend.remove(cond)\n return l\n\n def message_add(self, msg):\n data = {\n 'src': msg.src,\n 'dst': msg.dst,\n 'time': msg.time,\n 'text': msg.text,\n 'image': msg.image\n }\n self.message.insert_one(data)\n\n def message_find(self, uid, time):\n l = []\n r1 = self.message.find({'src': uid})\n r2 = self.message.find({'dst': uid})\n for r in r1:\n l.append(r)\n for r in r2:\n l.append(r)\n return l\n \n def post_add(self, post):\n data = {\n 'uid': post.uid,\n 'text': post.text,\n 'image': post.image,\n 'time': post.time,\n 'desc': post.desc,\n 'username': post.username,\n 'nickname': post.nickname,\n 'icon': post.icon\n }\n self.post.insert_one(data)\n return ''\n\n def post_find(self, time):\n res = self.post.find({'time': {'$gt': time}},sort=[(\"time\", -1)])\n t = 0\n l = []\n for r in res:\n l.append(r)\n t += 1\n if t >= 5:\n break\n return l\n\n def __init__(self):\n self.client = pymongo.MongoClient(host='localhost')\n # 在此处更改 db 即可\n self.db = self.client.test2\n # login part\n self.login = self.db.login\n # friend request part\n self.friend = self.db.friend\n # message part\n self.message = self.db.message\n # post part\n self.post = self.db.post\n m = self.login.find_one(sort=[(\"uid\",-1)])\n if m is None:\n self.max_uid = 0\n else:\n self.max_uid = m['uid']\n\n# login 部分: 包含每个用户的用户名,昵称,密码,uid 等信息","sub_path":"Server/src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"495318396","text":"__author__ = 'Vegard'\nfrom math import pow, sqrt\nfrom heapq import heapify, heappop, heappush\nimport glob\nclass Board:\n\n def __init__(self, file):\n self.board = []\n #Reads in file, saves A and B values, and creates new nodes in a matrix\n with open(file) as fil:\n linjer = fil.readlines()\n self.gridHeight = len(linjer)\n\n for x, linje in enumerate(linjer):\n\n self.board.append([])\n self.gridLength = len(linje)\n for y, char in enumerate(linje):\n if char ==\"\\n\":\n pass\n\n self.board[x].append(Node(x, y, char))\n\n if char==\"A\":\n self.start = (x, y)\n if char==\"B\":\n self.goal = (x, y)\n\n\n\n\n def heuristic(self, cell):\n return abs(cell.x-self.goal[0]) + abs(cell.y-self.goal[1])\n\n\n def bestFirstSearch(self):\n self.closed = []\n self.opened = []\n heapify(self.opened)\n startNode = self.board[self.start[0]][self.start[1]]\n gCost = 0\n hCost = self.heuristic(startNode)\n totalCost = gCost+hCost\n startNode.g = gCost\n startNode.f = totalCost\n heappush(self.opened, (startNode.g, startNode))\n while len(self.opened):\n\n node = heappop(self.opened)[1]\n\n self.closed.append(node)\n #Return with node if it is the final solution\n if node.x==self.goal[0] and node.y==self.goal[1]:\n return self.printPath(node)\n\n\n for neighbour in self.generateSuccessors(node):\n\n #node.children.append(neighbour)\n if neighbour not in self.closed and neighbour.cost!=\"#\":\n\n if (neighbour.g, neighbour) not in self.opened:\n\n self.updateCell(neighbour, node)\n heappush(self.opened, (neighbour.g, neighbour))\n elif node.g+neighbour.cost0:\n children.append(self.board[x-1][y])\n if y >0:\n children.append(self.board[x][y-1])\n if x\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 click\n\nfrom platformio.account.client import AccountClient\n\n\n@click.command(\"logout\", short_help=\"Log out of PlatformIO Account\")\ndef account_logout_cmd():\n client = AccountClient()\n client.logout()\n click.secho(\"Successfully logged out!\", fg=\"green\")\n","sub_path":"platformio/account/commands/logout.py","file_name":"logout.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"550142229","text":"\"\"\"\nBuilt from Alexa Skill example, info here: http://amzn.to/1LzFrj6\n\"\"\"\n\nfrom __future__ import print_function\nimport requests\nimport json\nfrom datetime import datetime\nimport responses\n\nalexa = responses.alexa()\n\n# --------------- Helpers that build all of the responses ---------------------\n\n\ndef build_speechlet_response(title, speech_output, reprompt_text,\n should_end_session, card_output):\n card_text = card_output.replace(\"TinRiss\", \"TNRIS\")\n\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': speech_output\n },\n 'card': {\n 'type': 'Simple',\n 'title': title,\n 'content': card_text\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n\n\ndef build_nocard_response(speech_output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': speech_output\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n\n\ndef build_ssml_response(speech_output, reprompt_text, should_end_session):\n return {\n 'outputSpeech': {\n 'type': 'SSML',\n 'ssml': speech_output\n },\n 'reprompt': {\n 'outputSpeech': {\n 'type': 'PlainText',\n 'text': reprompt_text\n }\n },\n 'shouldEndSession': should_end_session\n }\n\n\ndef build_response(session_attributes, speechlet_response):\n return {\n 'version': '1.0',\n 'sessionAttributes': session_attributes,\n 'response': speechlet_response\n }\n\n\ndef build_nocard(attr, speech, reprompt, end):\n return build_response(attr, build_nocard_response(speech, reprompt, end))\n\n\ndef build_yescard(attr, title, speech, reprompt, end, card):\n return build_response(attr, build_speechlet_response(title, speech,\n reprompt, end, card))\n\n\n# -------------- Functions that control the skill's behavior -----------------\ndef get_welcome_response():\n \"\"\" If we wanted to initialize the session to have some attributes we could\n add those here\n \"\"\"\n\n session_attributes = {}\n speech_output = \"Howdy! Welcome to the Texas Natural Resources \" \\\n \"Information System. \" + alexa.instruction\n # If the user either does not reply to the welcome message or\n # says something that is not understood, they will be prompted again\n # with this text.\n reprompt_text = alexa.instruction\n should_end_session = False\n return build_response(session_attributes, build_nocard_response(\n speech_output, reprompt_text, should_end_session))\n\n\ndef handle_session_end_request():\n speech_output = \"Thanks for chatting with TinRiss. Goodbye.\"\n # Setting this to true ends the session and exits the skill.\n should_end_session = True\n return build_response({}, build_nocard_response(\n speech_output, None, should_end_session))\n\n\ndef create_session_ref(county):\n return {\"county\": county}\n\n\ndef get_county_fips(name):\n with open('counties_lower.json') as json_data:\n d = json.load(json_data)\n lower = name.lower()\n fips = d[lower]\n return fips\n\n\ndef format_year_list(the_list):\n no_none = [value for value in the_list if value is not None]\n return [int(i.split(\"-\")[0]) for i in no_none]\n\n\ndef get_hist_imagery_years(fips):\n url_base = 'https://historical-aerials.tnris.org/api/v1/' \\\n 'records?countyFips='\n url = url_base + str(fips)\n r = requests.get(url)\n imgs = r.json()\n if len(imgs) == 0:\n return 0\n if len(imgs) == 1:\n single_year = imgs[0]['Date']\n try:\n year = single_year.split(\"-\")[0]\n return int(year)\n except:\n return 0\n else:\n try:\n years = [int(i['Date'].split(\"-\")[0]) for i in imgs]\n except:\n init = [i['Date'] for i in imgs]\n years = format_year_list(init)\n\n unique_years = sorted(set(years))\n print(unique_years)\n oldest = unique_years[0]\n newest = unique_years[-1]\n length = len(unique_years)\n return [length, oldest, newest]\n\n\ndef get_imagery_years_list(fips):\n url_base = 'https://historical-aerials.tnris.org/api/v1/' \\\n 'records?countyFips='\n url = url_base + str(fips)\n print(url)\n r = requests.get(url)\n imgs = r.json()\n print(r)\n print(imgs)\n if len(imgs) == 0:\n return 0\n if len(imgs) == 1:\n single_year = imgs[0]['Date']\n try:\n year = single_year.split(\"-\")[0]\n return int(year)\n except:\n return 0\n else:\n try:\n years = [int(i['Date'].split(\"-\")[0]) for i in imgs]\n except:\n init = [i['Date'] for i in imgs]\n years = format_year_list(init)\n\n unique_years = sorted(set(years))\n print(unique_years)\n return unique_years\n\n\ndef confirm_year(years, requested_year):\n multiple = isinstance(years, list)\n year_num = int(requested_year)\n if multiple:\n if year_num in years:\n return True\n else:\n return min(years, key=lambda x: abs(x-year_num))\n elif years == 0:\n return None\n else:\n if year_num == years:\n return True\n else:\n return False\n\n\ndef lookup_session(intent, session):\n \"\"\"\n Looks up general information on file on a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if 'County' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n session_attributes = create_session_ref(historical_county)\n fips = get_county_fips(historical_county)\n years = get_hist_imagery_years(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_range(historical_county, years[0],\n years[1], years[2])\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(historical_county, years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef list_years_session(intent, session):\n \"\"\"\n Lists the specific years on file for a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n else:\n session_county = \"\"\n print(session_county)\n if 'County' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n if session_county != historical_county:\n session_attributes = create_session_ref(historical_county)\n fips = get_county_fips(historical_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.list_range(historical_county, years)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(historical_county, years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title, speech_output,\n reprompt_text, should_end_session, text)\n except:\n try:\n if session_county == \"\":\n msg = 'No county saved in session and no new ' \\\n 'county requested.'\n print(msg)\n raise Exception(msg)\n session_attributes = create_session_ref(session_county)\n fips = get_county_fips(session_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n\n if multiple:\n reprompt_text = alexa.reprompt_1\n text = alexa.list_range(session_county, years)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(session_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n text = alexa.imagery_single(session_county, years)\n speech_output = text + reprompt_text\n\n card_title = session_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef specific_year_session(intent, session):\n \"\"\"\n Verify a specific year on file for a county\n \"\"\"\n session_attributes = {}\n should_end_session = False\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n else:\n session_county = \"\"\n print(session_county)\n if 'County' in intent['slots'] and 'ImageryYear' in intent['slots']:\n try:\n historical_county = intent['slots']['County']['value']\n if session_county != historical_county:\n session_attributes = create_session_ref(historical_county)\n try:\n requested_year = intent['slots']['ImageryYear']['value']\n fips = get_county_fips(historical_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n confirmation = confirm_year(years, requested_year)\n\n if multiple:\n reprompt_text = alexa.reprompt_3\n if confirmation is True:\n text = alexa.affirmative_year(historical_county,\n requested_year)\n else:\n text = alexa.negative_year(historical_county,\n requested_year,\n confirmation)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(historical_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n if confirmation is True:\n text = alexa.affirmative_year(historical_county,\n requested_year)\n else:\n text = alexa.negative_year_single(historical_county,\n requested_year,\n years)\n speech_output = text + reprompt_text\n\n card_title = historical_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused_2 + \"Please try again.\"\n reprompt_text = alexa.confused_2 + alexa.instruction\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n\n except:\n try:\n if session_county == \"\":\n msg = 'No county saved in session and no new ' \\\n 'county requested.'\n print(msg)\n raise Exception(msg)\n else:\n session_attributes = create_session_ref(session_county)\n\n try:\n requested_year = intent['slots']['ImageryYear']['value']\n fips = get_county_fips(session_county)\n years = get_imagery_years_list(fips)\n multiple = isinstance(years, list)\n confirmation = confirm_year(years, requested_year)\n\n if multiple:\n reprompt_text = alexa.reprompt_3\n if confirmation is True:\n text = alexa.affirmative_year(session_county,\n requested_year)\n else:\n text = alexa.negative_year(session_county,\n requested_year,\n confirmation)\n speech_output = text + reprompt_text\n elif years == 0:\n reprompt_text = alexa.reprompt_2\n text = alexa.imagery_none(session_county)\n speech_output = text + reprompt_text\n else:\n reprompt_text = alexa.reprompt_1\n if confirmation is True:\n text = alexa.affirmative_year(session_county,\n requested_year)\n else:\n text = alexa.negative_year_single(session_county,\n requested_year,\n years)\n speech_output = text + reprompt_text\n\n card_title = session_county.title() + \" County\"\n return build_yescard(session_attributes, card_title,\n speech_output, reprompt_text,\n should_end_session, text)\n except:\n speech_output = alexa.confused_2 + \"Please try again.\"\n reprompt_text = alexa.confused_2 + alexa.instruction\n\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n\n except:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output,\n reprompt_text, should_end_session)\n else:\n speech_output = alexa.confused + \"Please try again.\"\n reprompt_text = alexa.confused + alexa.instruction\n\n return build_nocard(session_attributes, speech_output, reprompt_text,\n should_end_session)\n\n\ndef band_session(intent, session):\n \"\"\"\n Easter Egg\n \"\"\"\n session_attributes = {}\n should_end_session = True\n\n if session.get('attributes', {}) and \"county\" in session.get('attributes',\n {}):\n session_county = session['attributes']['county']\n session_attributes = create_session_ref(session_county)\n speech_output = \"Oh, that's an easy one. Primus is the greatest \" \\\n \"band in the world. Well, I don't \" \\\n \"know. It could be \" \\\n \"Led Zeppelin. Nah, it's definitely \" \\\n \"Primus.\"\n reprompt_text = alexa.instruction\n return build_response(session_attributes, build_ssml_response(\n speech_output, reprompt_text, should_end_session))\n\n# --------------- Events ------------------\n\n\ndef on_session_started(session_started_request, session):\n \"\"\" Called when the session starts \"\"\"\n\n print(\"on_session_started requestId=\" +\n session_started_request['requestId']\n + \", sessionId=\" + session['sessionId'])\n\n\ndef on_launch(launch_request, session):\n \"\"\" Called when the user launches the skill without specifying what they\n want\n \"\"\"\n\n print(\"on_launch requestId=\" + launch_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # Dispatch to your skill's launch\n return get_welcome_response()\n\n\ndef on_intent(intent_request, session):\n \"\"\" Called when the user specifies an intent for this skill \"\"\"\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n print(intent_name)\n\n # Dispatch to your skill's intent handlers\n if intent_name == \"SpecificYearIntent\":\n return specific_year_session(intent, session)\n elif intent_name == \"ListYearsIntent\":\n return list_years_session(intent, session)\n elif intent_name == \"LookupIntent\":\n return lookup_session(intent, session)\n elif intent_name == \"BandIntent\":\n return band_session(intent, session)\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif (intent_name == \"AMAZON.CancelIntent\" or\n intent_name == \"AMAZON.StopIntent\"):\n return handle_session_end_request()\n else:\n raise ValueError(\"Invalid intent\")\n\n\ndef on_session_ended(session_ended_request, session):\n \"\"\" Called when the user ends the session.\n\n Is not called when the skill returns should_end_session=true\n \"\"\"\n print(\"on_session_ended requestId=\" + session_ended_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # add cleanup logic here\n\n\n# --------------- Main handler ------------------\n\ndef lambda_handler(event, context):\n \"\"\" Route the incoming request based on type (LaunchRequest, IntentRequest,\n etc.) The JSON body of the request is provided in the event parameter.\n \"\"\"\n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID\n to prevent someone else from configuring a skill that sends requests to\n this function.\n \"\"\"\n # if (event['session']['application']['applicationId'] !=\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\n # raise ValueError(\"Invalid Application ID\")\n\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event['request'], event['session'])\n","sub_path":"lambda-code/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":21510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"157570170","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport re\nimport requests\nimport bs4\nimport pymysql\nimport time\n# 打开数据库连接\ndb = pymysql.connect(\"101.132.195.63\", \"rc\", \"rc123\", \"pydb\", charset='utf8')\n# 使用 cursor() 方法创建一个游标对象 cursor\ncursor = db.cursor()\nprint('start')\nm = 1\nwhile m <= 73:\n\n # 要抓取的目标页码地址\n # url = 'http://list.mogujie.com/book/accessories/10061955?mt=12.18940.r153160.24443&acm=3.mce.1_10_188k2.18940..iOPIAqQwjmQFc.pos_0-m_192141-sd_119-mf_15261_944839-idx_0-mfs_46-dm1_5000&ptp=1._mf1_1239_15261.0.0.mVsdTMSI'\n # url = 'https://search.51job.com/list/020000,000000,0000,00,9,99,Java%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='\n url = 'https://search.51job.com/list/020000,000000,0000,00,9,99,Java%25E5%25BC%2580%25E5%258F%2591%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,' + '%d' % m + \\\n '.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='\n print('url is :' + url)\n m = m + 1\n # 抓取页码内容,返回响应对象\n response = requests.get(url)\n\n encod = response.encoding\n # print(encod)\n # 查看响应状态码\n status_code = response.status_code\n # print(status_code)\n content = bs4.BeautifulSoup(\n response.content.decode(encod).encode(encod), \"lxml\")\n # print(content)\n\n texts = content.find_all('div', class_='el')\n\n jobinfo = texts[17:len(texts)]\n # print(jobinfo)\n for infos in jobinfo:\n t1info = infos.find_all('p', class_='t1')\n t2info = infos.find_all('span', class_='t2')\n t3info = infos.find_all('span', class_='t3')\n t4info = infos.find_all('span', class_='t4')\n t5info = infos.find_all('span', class_='t5')\n a, b, c, d, e, f, g, h = '0', '1', '2', '3', '4', '5', '6', '51job'\n for t1 in t1info:\n t1hr = t1.find('a')\n t1strs = t1hr['href']\n e = t1strs\n # c = t1hr.text.split()\n for cs in t1hr.text.split():\n c = cs\n print(c)\n # print(t1strs + '---------' + t1hr.text)\n for t2 in t2info:\n t2hr = t2.find('a')\n t2strs = t2hr['href']\n f = t2strs\n b = t2hr.text\n # print(t2strs + '---------' + t2hr.text)\n for t3 in t3info:\n d = t3.text\n # print('---------' + t3.text)\n for t4 in t4info:\n # print('---------' + t4.text)\n g = t4.text\n for t5 in t5info:\n # print('---------' + t5.text)\n a = t5.text\n cursor.execute('insert into wuyoujob (public_date, companyname, title, work_add,job_url,company_url,salary,source) values(%s,%s,%s,%s,%s,%s,%s,%s)', (\n a, b, c, d, e, f, g, h))\n\n # 提交到数据库执行\n db.commit()\n # sleep(5)\nprint('end')\n","sub_path":"jobtitle.py","file_name":"jobtitle.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"60357985","text":"def medianfilter(img1,height,width):\n import numpy as np\n #import math\n a=0\n b=0\n q=[]\n img2=np.zeros((height,width,1),np.uint8)\n #img2=img1\n for d in range(1):\n\n for h in range(3,height,+3):\n for w in range(3,width,+3):\n q=[]\n for i in range(a,h):\n for j in range(b,w):\n q=[img1[i,j],img1[i,j-1],img1[i,j+1],img1[i-1,j],img1[i-1,j-1],img1[i-1,j+1],img1[i+1,j],img1[i+1,j+1],img1[i+1,j-1]]\n img2[i,j]=int(np.median(q))\n \n b=w\n a=h\t\t\n return img2\n \n\n","sub_path":"medianfilter.py","file_name":"medianfilter.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"54766029","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\n @file ProjectEuler/0004.py\n @author SHawnHardy\n @date 2020-04-25\n @copyright MIT License\n\"\"\"\n\nimport sys\n\nsys.setrecursionlimit(1000000)\n\nans = 101 * 101\nfor i in range(100, 1000):\n for j in range(ans // i + 1, 1000):\n num = str(i * j)\n if num == num[::-1]:\n ans = i * j\nprint(ans)\n# 906609\n","sub_path":"ProjectEuler/0004.py","file_name":"0004.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"293280143","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\n\nr = requests.get('https://www.airbnb.com/s/Paris--France?guests=&checkin=11%2F16%2F2015&checkout=11%2F20%2F2015&ss_id=zru0ehp2&source=bb')\n\nairbnbSoup = BeautifulSoup(r.content)\n\nprices = airbnbSoup.find_all(\"span\", {\"class\": \"price-amount\"})\nnames = airbnbSoup.find_all(\"h3\", {\"class\": \"listing-name\"})\n\npricesText = [];\nnamesText = [];\ndata = [];\n\nindex = 0;\nfor p in prices:\n pricesText.append(p.text.strip())\n namesText.append(names[index].find('a').text.strip())\n data.append({'price': p.text.strip(), 'description': names[index].find('a').text.strip()})\n index += 1\n\n\n\n\nwith open(\"parisText.json\", \"w\") as outfile:\n json.dump({'data': data}, outfile, indent=4)","sub_path":"parisPython.py","file_name":"parisPython.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"238268917","text":"from keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\nimport socket\nimport time\n\n\n\nimg_width, img_height = 160, 120\n\n\nmodel = load_model('./data/models/beispiel1.h5')\nmodel.compile(loss='binary_crossentropy',optimizer='rmsprop', metrics=['accuracy'])\n\n\nimg = image.load_img('picture.png', target_size=(img_width, img_height))\nx = image.img_to_array(img)\nx = np.expand_dims(x, axis=0)\n\nclasses = model.predict_classes(x, batch_size=128)\nfor i in classes:\n\tprint(i[0])\n\tif i == 0:\n\t\tip = \"192.168.178.103\"\n\t\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \n\t\ts.connect((ip, 50002))\n\t\ts.send(b\"forward_go\")\n\t\ts.close()\n\n\tif i == 1:\n\t\tprint(\"Hindernis erkannt!\")\n","sub_path":"ML_AP/beispiel1/code/keras/predict_test.py","file_name":"predict_test.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"251797448","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 03 15:26:49 2016\n\n@author: jzhu0922\n\"\"\"\n\nfrom pylab import *\n\nsubplot(2,2,1)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,1)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,2)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,2)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,3)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,3)',ha='center',va='center',size=20,alpha=.5)\n\nsubplot(2,2,4)\nxticks([]), yticks([])\ntext(0.5,0.5, 'subplot(2,2,4)',ha='center',va='center',size=20,alpha=.5)\n\n# savefig('../figures/subplot-grid.png', dpi=64)\nshow()\n\n\n#=================gridspec==========================================\n\nimport matplotlib.gridspec as gridspec\n\nG = gridspec.GridSpec(3, 3)\n\naxes_1 = subplot(G[0, :])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5)\n\naxes_2 = subplot(G[1,:-1])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5)\n\naxes_3 = subplot(G[1:, -1])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5)\n\naxes_4 = subplot(G[-1,0])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5)\n\naxes_5 = subplot(G[-1,-2])\nxticks([]), yticks([])\ntext(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5)\n\n#plt.savefig('../figures/gridspec.png', dpi=64)\nshow()\n\n\n#==================axes===============================================\n\naxes([0.1,0.1,.8,.8])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.1,0.1,.8,.8])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.2,0.2,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.3,0.3,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\naxes([0.4,0.4,.5,.5])\nxticks([]), yticks([])\ntext(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5)\n\n# plt.savefig(\"../figures/axes-2.png\",dpi=64)\nshow()\n\n#==================grid============================\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nax = plt.axes([0.025,0.025,0.95,0.95])\n\nax.set_xlim(0,4)\nax.set_ylim(0,3)\nax.xaxis.set_major_locator(plt.MultipleLocator(1.0))\nax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))\nax.yaxis.set_major_locator(plt.MultipleLocator(1.0))\nax.yaxis.set_minor_locator(plt.MultipleLocator(0.1))\nax.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='0.75')\nax.grid(which='minor', axis='x', linewidth=0.25, linestyle='-', color='0.75')\nax.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='0.75')\nax.grid(which='minor', axis='y', linewidth=0.25, linestyle='-', color='0.75')\nax.set_xticklabels([])\nax.set_yticklabels([])\n\n# savefig('../figures/grid_ex.png',dpi=48)\nplt.show()\n\n\n","sub_path":"2-Matplotlib/subplot_axes.py","file_name":"subplot_axes.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"602931896","text":"#!/usr/bin/python\n\n\"\"\"\nmultitasking.managers.base\n\"\"\"\n\nimport gevent\nimport logging\nimport logging.handlers\nimport signal\nimport sys\n\nfrom gevent import socket as _socket\n\nfrom multitasking.util.exceptions import StopTaskException\n\nclass TaskManager(object):\n \"\"\"\n Manager of tasks.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Create a new instance of a TaskManager.\n \"\"\"\n self._tasks = []\n self._logger = self._setup_logging()\n gevent.signal(signal.SIGINT, self.stop)\n\n def __repr__(self):\n \"\"\"\n The name of the TaskManager should be enough representation.\n \"\"\"\n return self.__class__.__name__\n\n def _setup_logging(self):\n \"\"\"\n Setup logging for this TaskManager.\n \"\"\"\n logger = logging.getLogger(self.__class__.__name__)\n logger.setLevel(logging.DEBUG)\n\n format_str = \"[MT] %(name)s - %(levelname)s - %(message)s\"\n formatter = logging.Formatter(format_str)\n\n syslog_handler = logging.handlers.SysLogHandler(address='/dev/log', facility='daemon')\n syslog_handler.setLevel(logging.DEBUG)\n syslog_handler.setFormatter(formatter)\n\n logger.addHandler(syslog_handler)\n\n return logger\n\n def stop(self):\n \"\"\"\n Called when this task manager should stop.\n \"\"\"\n for task in self._tasks:\n if task.started and not task.successful():\n task.kill(exception=StopTaskException, block=False)\n gevent.joinall(self._tasks)\n\n def execute(self, task, *args):\n \"\"\"\n Execute the given task. This task manager executes tasks locally,\n and all communications between tasks occurs over sockets.\n\n @param task: The task to run.\n @param args: Any arguments to pass to the task.\n \"\"\"\n # Create two connected sockets\n sock_one, sock_two = _socket.socketpair()\n\n # Assign one of the sockets to the task\n task = task(self)\n task._socket = sock_one\n\n # Start the task\n self._tasks.append(gevent.spawn(task, *args))\n\n # Return the other socket\n return sock_two\n\n def join(self):\n \"\"\"\n Join the manager, blocking until all tasks are complete.\n \"\"\"\n gevent.joinall(self._tasks)\n","sub_path":"multitasking/managers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"360432885","text":"import sqlite3 as sq\n\n\nclass DataBase:\n\tdef __init__(self, path):\n\t\tself.path = path\n\n\t\"\"\" Connect to Data Base \"\"\"\n\tdef connect(self):\n\t\ttry:\n\t\t\tself.conn = sq.connect(str(self.path))\n\t\t\tself.cursor = self.conn.cursor()\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] File DataBase error: \" + e)\n\n\t\"\"\" Close \"\"\"\n\tdef close(self):\n\t\tself.cursor.close()\n\t\tself.conn.close()\n\t\tprint(\"[INFO] Close connect to database, and close cursor\")\n\t\t\n\t\"\"\" Add in Data Base \"\"\"\n\tdef insert(self, nameTable:str, paramArray):\n\t\tself.connect()\n\t\trequest = 'INSERT INTO ' + nameTable + ' VALUES(?, ?)'\n\t\tself.cursor.execute(request, paramArray)\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_status(self, name:str, author:str):\n\t\tself.connect()\n\t\tself.cursor.execute('''INSERT INTO status(name, author) VALUES(?, ?)''', (name, author))\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_users(self, funcType:int, user:str, money:int=None, vip:int=None):\n\t\tself.connect()\n\n\t\tif funcType == 1:\n\t\t\ttry:\n\t\t\t\tself.cursor.execute('''INSERT INTO users(user) VALUES(?) ''', (str(user),))\n\t\t\texcept sqlite3.IntegrityError as e:\n\t\t\t\tprint('[ERROR] sqlite3 ' + e)\n\n\t\telif funcType == 2:\n\t\t\tself.cursor.execute()\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef insert_guild(self, funcType:int, guild_id, guild_name=None, channel=None):\n\t\tself.connect()\n\n\t\tif funcType == 1 and channel == None:\n\t\t\ttry:\n\t\t\t\tself.cursor.execute('''INSERT INTO guild(guild_id, guild_name) VALUES(?, ?)''', (guild_id, guild_name))\n\t\t\texcept Exception as e:\n\t\t\t\tprint('[ERROR] sqlite3 ' + e)\n\n\t\telse:\n\t\t\tprint(\"[ERROR] sqlite3: No func\")\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Update in Data Base \"\"\"\n\tdef update_guild(self, funcType:int, guild_id, channel_join=None):\n\t\tself.connect()\n\n\t\tif funcType == 1 and channel_join != None :\n\t\t\tself.cursor.execute(\"\"\"UPDATE guild SET channel_join=? WHERE guild_id=? \"\"\", (channel_join, guild_id))\n\t\telse:\n\t\t\tpass\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Remove in Data Base \"\"\"\n\tdef delete(self, nameTable:str, func:str):\n\t\tself.connect()\n\t\trequest = '''DELETE FROM {0} {1}'''.format(nameTable, func)\n\t\tself.cursor.execute(request)\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef delete_status(self, id):\n\t\tself.connect()\n\t\t\n\t\ttry:\n\t\t\tself.cursor.execute('''DELETE FROM status WHERE id=?''', (id,))\n\n\t\texcept Exception as e:\n\t\t\traise e\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\tdef delete_guild(self, id):\n\t\tself.connect()\n\t\t\n\t\ttry:\n\t\t\tself.cursor.execute('''DELETE FROM guild WHERE guild_id=?''', (int(id),))\n\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\n\t\tself.conn.commit()\n\t\tself.close()\n\n\t\"\"\" Select in Data Base \"\"\"\n\tdef _select_order_by(self, nameTable:str, sort:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = 'SELECT * FROM {0} ORDER BY {1}'.format(nameTable, sort)\n\t\t\tself.cursor.execute(request)\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()\n\n\tdef _select_where(self, nameTable:str, elements:str, lines:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = \"SELECT * FROM {0} WHERE {1}=?\".format(nameTable, elements)\n\t\t\tself.cursor.execute(request, (lines,))\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()\n\n\tdef _select_all(self, nameTable:str):\n\t\tself.connect()\n\t\ttry:\n\t\t\trequest = 'SELECT * FROM {0}'.format(nameTable,)\n\t\t\tself.cursor.execute(request)\n\t\t\tdata = self.cursor.fetchall()\n\t\t\treturn data\n\t\texcept Exception as e:\n\t\t\tprint(\"[ERROR] sqlite3 \" + e)\n\t\tself.close()","sub_path":"DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"408304325","text":"import pytest\nimport sys\nimport os\n\nsys.path.insert(0, os.path.abspath('.'))\nsys._called_from_test = True\n\nimport main\n\n\n@pytest.fixture\ndef app():\n return main.app\n\n\n@pytest.fixture\ndef test_client(app):\n return app.test_client()\n\n\ndef test_title(test_client):\n if hasattr(sys, '_called_from_test'):\n print(\"called from a test\")\n response = test_client.get(\"/\")\n assert \"Check Yo Self\" in response.data.decode(\"utf-8\")\n\n\ndef test_text_box(test_client):\n response = test_client.get(\"/\")\n assert \"Write something here to have it spell checked!\" in response.data.decode(\"utf-8\")\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"608153974","text":"import requests , json , argparse , sys , socket\nfrom termcolor import colored\ntry:\n import requests.packages.urllib3\n requests.packages.urllib3.disable_warnings()\nexcept:\n pass\ndef banner():\n print(\"\"\"\n _ __ _ _ \n | | / / | | (_) \n | |/ / ___ _ __ ___ | |__ _ _ __ ___ \n | \\ / _ \\| '_ \\ / __|| '_ \\ | || '__| / _ \\ \n | |\\ \\| __/| | | |\\__ \\| | | || || | | (_) |\n \\_| \\_/ \\___||_| |_||___/|_| |_||_||_| \\___/ \n Create By InfinitumIT \n { omae wa mou shindeiru! Nani? } \n \"\"\")\ndef parser_error():\n banner()\n if sys.argv[0]==None:\n print(\"Usage: python \" + sys.argv[0] + \" [Options] use -h for help\")\n sys.exit()\n else:\n pass\ndef parse_args():\n # parse the arguments\n parser = argparse.ArgumentParser(description='Web Information Gathering Tool.')\n parser.add_argument('-m', action=\"store\", help='Modules : header or domain .Usage:[-m header]')\n parser.add_argument('-f', action=\"store\", help='Url list load from path. Do not add https:// tag.')\n parser.add_argument('-o', action=\"store\" , help='Output File path.')\n return parser.parse_args()\n# Header Security Checker\n\ndef headersecurity(file):\n whitelist = [\"X-Frame-Options\",\"Strict-Transport-Security\",\"X-XSS-Protection\",\"X-Content-Type-Options\", \"Content-Security-Policy\"] \n with open(file) as fp: \n line = fp.readline()\n while line:\n user_agent = {'User-agent': 'Mozilla/5.0'}\n r = requests.get(line.strip(), headers=user_agent,verify=False)\n print(\"\\nScan Url -> \" + line.strip())\n for whiteitem in whitelist:\n if whiteitem in r.headers:\n print(colored(whiteitem, 'white'), colored(' available', 'green'))\n else:\n print(colored(whiteitem, 'white'), colored(' not available.', 'red'))\n line = fp.readline() \n# Domain To Ip Address Converter\ndef domaintoip(file):\n with open(file) as fp: \n line = fp.readline()\n while line:\n print(colored(\"Host: \" , 'red'), colored(line.strip() , 'white' ) , colored(\" IP: \", 'red'), colored(socket.gethostbyname(line.strip()), 'white'))\n line = fp.readline()\ndef DnsResolver(file):\n with open(file) as fp: \n line = fp.readline()\n while line:\n reversed_dns = socket.gethostbyaddr(line.strip())\n print(colored(\"Host: \" , 'red'), colored(line.strip() , 'white' ) , colored(\" DNS: \", 'red'), colored(reversed_dns[0], 'white'))\n line = fp.readline()\n#Main\ndef main():\n parser_error()\n args = parse_args()\n if (args.m == \"header\"): \n headersecurity(args.f)\n elif (args.m == \"domain\"):\n domaintoip(args.f)\n elif (args.m == \"dnsresolve\"):\n DnsResolver(args.f)\n#Load Main\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"616417904","text":"def maxoccchar(text):\r\n max_l=-1\r\n text=list(text)\r\n for i in text:\r\n if(text.count(i)>max_l):\r\n max_l=text.count(i)\r\n string = i \r\n return(string)\r\nprint(maxoccchar(\"bbbaaacc\"))\r\n\r\n","sub_path":"maximum_occuring_char.py","file_name":"maximum_occuring_char.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"104518878","text":"import numpy as nmp\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom scipy.integrate import odeint\r\n\r\na_1 = 7\r\nb_1 = 3.00\r\n\r\nTime_null = 0\r\nTime_Max = 37\r\nStep = 0.05\r\n\r\nt = nmp.arange(Time_null, Time_Max, Step)\r\nt = nmp.append(t, Time_Max)\r\n\r\ndef p(t):\r\n\treturn 0\r\n\r\ndef syst(x,t):\r\n\treturn x[1], -a_1 * a_1 * x[0] - b_1 * x[1] - p(t)\r\n\r\nv0 = (1, 1.2)\r\n\r\nyf = odeint(syst, v0, t)\r\n\r\nx = []\r\ny = []\r\n\r\nfor i in range(len(yf)):\r\n\tx.append(yf[i][0])\r\n\ty.append(yf[i][1])\r\n\r\nplt.figure(figsize = (10,10))\r\nplt.plot(x,y,'r', label = 'x')\r\nplt.show()\r\n","sub_path":"lab 4/lab4 2.py","file_name":"lab4 2.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"580317245","text":"from django.conf.urls import url\nfrom api import views\n\nurlpatterns = [\n url(r'^offers/$', views.OfferListAPIView.as_view(),\n name='offers-list-api'),\n url(r'^offers/(?P[0-9]+)/$', views.OfferDetailAPIView.as_view(),\n name='offer-detail-api'),\n url(r'^categories/$', views.CategoryListAPIView.as_view(),\n name='category-list-api'),\n url(r'^categories/(?P[0-9]+)/$', views.CategoryDetailAPIView.as_view(),\n name='category-detail-api'),\n url(r'statistics/$', views.StatisticsAPIView.as_view(),\n name='statistics-api'),\n]\n","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"565560160","text":"import argparse\nimport base64\nimport json\nimport sys\nimport random\nimport logging\nimport threading\n\nimport dns.query\nimport dns.message\nimport dns.rdatatype\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler(sys.stderr))\nlogger.setLevel(logging.INFO)\n\nrdtypes = [dns.rdatatype.A, dns.rdatatype.AAAA, dns.rdatatype.MX, dns.rdatatype.TXT, dns.rdatatype.SRV]\nresolvers = ['1.1.1.1', '8.8.8.8', '9.9.9.9', '208.67.222.222', '64.6.64.6']\n\nlock = threading.Lock()\n\ndef query_worker(infile: str, outfile: str):\n def read_data():\n _results = []\n with open(infile, 'r') as fp:\n for line in fp:\n qname = line.strip().split(',')[1] + '.'\n for t in rdtypes:\n q = dns.message.make_query(qname, t)\n q.use_edns(True)\n where = random.choice(resolvers)\n try:\n ans = dns.query.udp(q, where=where, timeout=2)\n except dns.exception.Timeout:\n continue\n except Exception as e:\n logger.exception(e)\n continue\n else:\n _results.append((base64.b64encode(q.to_wire()).decode(), base64.b64encode(ans.to_wire()).decode()))\n logger.info('{} -> {} ? {}'.format(qname, where, dns.rcode.to_text(ans.rcode())))\n return _results\n try:\n results = read_data()\n except Exception as e:\n logger.exception(e)\n else:\n with lock, open(outfile, 'a') as out:\n for r in results:\n print(json.dumps(r), file=out)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('domain_files', nargs='+', help='Files with domains in them to resolve')\n parser.add_argument('-o', '--output', required=True, help='Output file to store queries and responses in')\n args = parser.parse_args()\n threads = []\n for file in args.domain_files:\n t = threading.Thread(target=query_worker, args=(file, args.output))\n t.daemon = True\n t.start()\n threads.append(t)\n for t in threads:\n t.join()\n\nif __name__ == '__main__':\n main()","sub_path":"deepresolver/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"452603963","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n#转换颜色空间\r\n#在 OpenCV 的 HSV 格式中,H(色彩/色度)的取值范围是 [0,179], S(饱和度)的取值范围 [0,255],V(亮度)的取值范围 [0,255]。但是不同的软件使用的值可能不同。所以当你拿 OpenCV 的 HSV 值与其他软件的 HSV 值对比时,一定要记得归一化。\r\nimport cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile(1):\r\n #获取每一帧\r\n ret,frame = cap.read()\r\n #转换到HSV\r\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n #设定蓝色的阀值\r\n lower_blue = np.array([110,50,50])\r\n upper_blue = np.array([130,255,255])\r\n #根据阀值构建掩模\r\n mask = cv2.inRange(hsv,lower_blue,upper_blue)\r\n #对原图和掩模进行位运算\r\n res = cv2.bitwise_and(frame,frame,mask=mask)\r\n #显示图像\r\n cv2.imshow('frame',frame)\r\n cv2.imshow('mask',mask)\r\n cv2.imshow('res',res)\r\n k = cv2.waitKey(5)&0xFF\r\n if k == 27:\r\n break\r\n#关闭窗口\r\ncv2.destroyAllWindows()","sub_path":"转换颜色空间.py","file_name":"转换颜色空间.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"118925398","text":"\"\"\"\n@difficulty: easy\n@tags: misc\n@notes: max(abs(x1 - x0), abs(y1 - y0)) is the diff between nodes.\n\"\"\"\nclass Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n total = 0\n x0, y0 = points[0]\n for i in range(1, len(points)):\n x1, y1 = points[i]\n total += max(abs(x1 - x0), abs(y1 - y0))\n x0, y0 = x1, y1\n return total\n","sub_path":"solution/python/1266.py","file_name":"1266.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"457520108","text":"KNOWN_CODES = {\n 'af': 'ZA',\n 'agq': 'CM',\n 'ak': 'GH',\n 'am': 'ET',\n 'ar': 'AE',\n 'as': 'IN',\n 'asa': 'TZ',\n 'az': 'AZ',\n 'bas': 'CM',\n 'be': 'BY',\n 'bem': 'ZM',\n 'bez': 'IT',\n 'bg': 'BG',\n 'bm': 'ML',\n 'bn': 'BD',\n 'bo': 'CN',\n 'br': 'FR',\n 'brx': 'IN',\n 'bs': 'BA',\n 'ca': 'ES',\n 'cgg': 'UG',\n 'chr': 'US',\n 'cs': 'CZ',\n 'cy': 'GB',\n 'da': 'DK',\n 'dav': 'KE',\n 'de': 'DE',\n 'dje': 'NE',\n 'dua': 'CM',\n 'dyo': 'SN',\n 'ebu': 'KE',\n 'ee': 'GH',\n 'en': 'GB',\n 'el': 'GR',\n 'es': 'ES',\n 'et': 'EE',\n 'eu': 'ES',\n 'ewo': 'CM',\n 'fa': 'IR',\n 'fil': 'PH',\n 'fr': 'FR',\n 'ga': 'IE',\n 'gl': 'ES',\n 'gsw': 'CH',\n 'gu': 'IN',\n 'guz': 'KE',\n 'gv': 'GB',\n 'ha': 'NG',\n 'haw': 'US',\n 'he': 'IL',\n 'hi': 'IN',\n 'ff': 'CN',\n 'fi': 'FI',\n 'fo': 'FO',\n 'hr': 'HR',\n 'hu': 'HU',\n 'hy': 'AM',\n 'id': 'ID',\n 'ig': 'NG',\n 'ii': 'CN',\n 'is': 'IS',\n 'it': 'IT',\n 'ja': 'JP',\n 'jmc': 'TZ',\n 'ka': 'GE',\n 'kab': 'DZ',\n 'ki': 'KE',\n 'kam': 'KE',\n 'mer': 'KE',\n 'kde': 'TZ',\n 'kea': 'CV',\n 'khq': 'ML',\n 'kk': 'KZ',\n 'kl': 'GL',\n 'kln': 'KE',\n 'km': 'KH',\n 'kn': 'IN',\n 'ko': 'KR',\n 'kok': 'IN',\n 'ksb': 'TZ',\n 'ksf': 'CM',\n 'kw': 'GB',\n 'lag': 'TZ',\n 'lg': 'UG',\n 'ln': 'CG',\n 'lt': 'LT',\n 'lu': 'CD',\n 'lv': 'LV',\n 'luo': 'KE',\n 'luy': 'KE',\n 'mas': 'TZ',\n 'mfe': 'MU',\n 'mg': 'MG',\n 'mgh': 'MZ',\n 'ml': 'IN',\n 'mk': 'MK',\n 'mr': 'IN',\n 'ms': 'MY',\n 'mt': 'MT',\n 'mua': 'CM',\n 'my': 'MM',\n 'naq': 'NA',\n 'nb': 'NO',\n 'nd': 'ZW',\n 'ne': 'NP',\n 'nl': 'NL',\n 'nmg': 'CM',\n 'nn': 'NO',\n 'nus': 'SD',\n 'nyn': 'UG',\n 'om': 'ET',\n 'or': 'IN',\n 'pa': 'PK',\n 'pl': 'PL',\n 'ps': 'AF',\n 'pt': 'PT',\n 'rm': 'CH',\n 'rn': 'BI',\n 'ro': 'RO',\n 'ru': 'RU',\n 'rw': 'RW',\n 'rof': 'TZ',\n 'rwk': 'TZ',\n 'saq': 'KE',\n 'sbp': 'TZ',\n 'seh': 'MZ',\n 'ses': 'ML',\n 'sg': 'CF',\n 'shi': 'MA',\n 'si': 'LK',\n 'sk': 'SK',\n 'sl': 'SI',\n 'sn': 'ZW',\n 'so': 'SO',\n 'sq': 'AL',\n 'sr': 'RS',\n 'sv': 'SE',\n 'sw': 'TZ',\n 'swc': 'CD',\n 'ta': 'IN',\n 'te': 'IN',\n 'teo': 'UG',\n 'th': 'TH',\n 'ti': 'ET',\n 'to': 'TO',\n 'tr': 'TR',\n 'twq': 'NE',\n 'tzm': 'MA',\n 'uk': 'UA',\n 'ur': 'PK',\n 'uz': 'UZ',\n 'vai': 'LR',\n 'vi': 'VN',\n 'vun': 'TZ',\n 'xog': 'UG',\n 'yav': 'CM',\n 'yo': 'NG',\n 'zh': 'CN',\n 'zh-cn': 'CN',\n 'zh-tw': 'TW',\n 'zu': 'ZA'\n}\n\n# Returns a country's flag according to ISO 639-1 language code\n# Note: Some languages could return just two regional indicator letter emojis (if that combination doesn't create a flag emoji)\n# Doesn't cover every ISO 639-1 code\n# Returns empty string for invalid/unknown ISO 639-1 language codes\ndef code_to_country(code):\n if not code:\n return ''\n elif code in KNOWN_CODES:\n country = KNOWN_CODES.get(code)\n # Unicode: chr(ord('A') + 127397) = 🇦\n # 🇬 + 🇧 = 🇬🇧\n return chr(ord(country[0]) + 127397) + chr(ord(country[1]) + 127397)\n return ''\n","sub_path":"bot/emoji_locale.py","file_name":"emoji_locale.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"642261703","text":"'''Write a program which randomly picks an integer from 1 to 100. Your program should prompt the user for guesses – if the user guesses incorrectly, it should print whether the guess is too high or too low. If the user guesses correctly, the program should print how many guesses the user took to guess the right answer. You can assume that the user will enter valid input.\n'''\n\nimport tkinter as tk\nimport random\n\nsecret_n = random.randint(1, 100)\n\nclass GuessNumber():\n\tdef __init__(self, master):\n\t\t\n\t\tself.master = master\n\t\tmaster.title(\"Guess a Number - a simple game\")\n\t\t\n\t\t# build upper_frm for labels\n\t\tself.upper_frm = tk.Frame(master, bg='#66CDAA')\n\t\t\n\t\t# welcome_lbl welcomes + explain game\n\t\tself.welcome_lbl = tk.Label(self.upper_frm, text=\"Welcome to Guess a Number!\\nI'm thinking about a positive integer\\nbetween 1 and 100,\\ncan you guess which one?\", bg='#66CDAA')\n\t\t\n\t\t# build lower_frm for ent + btn\n\t\tself.lower_frm = tk.Frame(master, bg='#FFFFF0')\n\t\t\n\t\t# update_lbl shows how the game is developing\n\t\tself.update_lbl = tk.Label(self.lower_frm, text='Go ahead, you can press \"Guess\" now', bg='#FFFFF0')\n\t\t\n\t\t# entry width=20 IntVar()\n\t\t#self.ent_var = tk.IntVar()\n\t\tvcmd = master.register(self.validate) # we have to wrap the command\n\t\tself.ent = tk.Entry(self.lower_frm, width=10, validate='key', validatecommand=(vcmd, '%P'))\n\t\t\n\t\t# btn_guess\n\t\tself.btn_guess = tk.Button(self.lower_frm, text='Guess', bg='#59B395', relief=tk.RAISED, bd=3, command=self.choose)\n\t\t\n\t\t# btn_reset\n\t\tself.btn_reset = tk.Button(self.lower_frm, text='Reset', bg='#59B395', relief=tk.RAISED, bd=3, command=self.reset, state=tk.DISABLED)\n\t\t\n\t\t# btn_quit\n\t\tself.btn_quit = tk.Button(self.lower_frm, text='Quit', command=self.master.destroy, bg='#59B395', relief=tk.RAISED, bd=3)\n\t\t\n\t\t# build side_frm for score keeping\n\t\tself.side_frm = tk.Frame(master, bg='#CD6689')\n\t\tself.lbl_side = tk.Label(self.side_frm, bg='#CD6689', text='Guess count:')\n\t\tself.lbl_count = tk.Label(self.side_frm, bg='#CD6689', text='0')\n\t\tself.lbl_nums = tk.Label(self.side_frm, bg='#CD6689', text='')\n\t\t\n\t\t# LAYOUT\n\t\t# root\n\t\tmaster.rowconfigure([0, 1, 2, 3], minsize=100)\n\t\tmaster.columnconfigure([0, 1, 2, 3], minsize=100)\n\t\tmaster.resizable(False, False)\n\t\t\n\t\t# upper_frm\n\t\tself.upper_frm.grid(row=0,column=0, columnspan=3, sticky='nsew')\n\t\tself.welcome_lbl.grid(row=0, columnspan=3, sticky='ew', ipadx=50, pady=30)\n\t\t\n\t\t# lower_frm\n\t\tself.lower_frm.grid(row=1, column=0, rowspan=3, columnspan=3, sticky='nsew')\n\t\tself.lower_frm.rowconfigure([0, 1, 2, 3], minsize=75)\n\t\tself.lower_frm.columnconfigure([0, 1, 2], minsize=75)\n\t\tself.update_lbl.grid(row=0, column=1, sticky='ew', pady=20)\n\t\tself.ent.grid(row=1, column=1, padx=10, pady=10)\n\t\tself.btn_guess.grid(row=2, column=1, padx=10, pady=10)\n\t\tself.btn_reset.grid(row=3, column=1, padx=10, pady=30, sticky='e')\n\t\tself.btn_quit.grid(row=3, column=2, padx=10, pady=30, sticky='w')\n\t\t\n\t\t# side_frm\n\t\tself.side_frm.grid(row=0, rowspan=4, column=3, sticky='nsew')\n\t\tself.lbl_side.grid(row=0, ipadx=10, padx=10, pady=10, sticky='nsew')\n\t\tself.lbl_count.grid(row=1, padx=10, sticky='nsew')\n\t\tself.lbl_nums.grid(row=2, padx=10, sticky='nsew')\n\t\t\n\t\t# METHODS:\n\tdef choose(self):\n\t\t'''Evaluate the user's guess and display the result through self.update_lbl and self.lbl_count.\n\t\t'''\n\t\tuser_guess = int(self.ent.get())\n\t\told_value = self.lbl_count['text']\n\t\told_num = self.lbl_nums['text']\n\t\t\n\t\tif user_guess == secret_n:\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tself.update_lbl['text'] = 'Congratulations!!!\\nYou guessed my number after {} tries'.format(self.lbl_count['text'])\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\t\tself.btn_reset.configure(state=tk.NORMAL)\n\t\telif user_guess < secret_n:\n\t\t\tself.update_lbl['text'] = \"Too low!\"\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\telif user_guess > secret_n:\n\t\t\tself.update_lbl['text'] = \"Too high!\"\n\t\t\tnew_value = str(int(old_value) + 1)\n\t\t\tself.lbl_count['text'] = new_value\n\t\t\tnew_num = self.ent.get()\n\t\t\tself.lbl_nums['text'] = old_num + '\\n' + new_num\n\t\t\n\tdef reset(self):\n\t\tself.ent.delete(0, tk.END)\n\t\tself.update_lbl['text'] = 'Go ahead, you can press \"Guess\" now'\n\t\tself.lbl_count['text'] = '0'\n\t\tself.lbl_nums['text'] = ''\n\t\n\tdef validate(self, new_text):\n\t\tif not new_text:\n\t\t\t# the field is being cleared\n\t\t\tself.entered_number = 0\n\t\t\treturn True\n\t\ttry:\n\t\t\tguess = int(new_text)\n\t\t\tif 1 <= guess <= 100:\n\t\t\t\tself.entered_number = guess\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\texcept ValueError:\n\t\t\treturn False\n\t\nroot = tk.Tk()\nmy_game = GuessNumber(root)\nroot.mainloop()","sub_path":"guess_the_number.py","file_name":"guess_the_number.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"27117374","text":"'''\npython-elinks installs an encoding error handler that uses the same ASCII replacements as ELinks does.\n'''\n\nclassifiers = '''\nDevelopment Status :: 4 - Beta\nIntended Audience :: Developers\nLicense :: OSI Approved :: GNU General Public License (GPL)\nOperating System :: OS Independent\nProgramming Language :: Python\nProgramming Language :: Python :: 2\nProgramming Language :: Python :: 3\nTopic :: Software Development :: Libraries :: Python Modules\nTopic :: Text Processing :: Filters\n'''.strip().split('\\n')\n\nimport os\nimport distutils.core\n\ntry:\n # Python 3.X\n from distutils.command.build_py import build_py_2to3 as distutils_build_py\nexcept ImportError:\n # Python 2.X\n from distutils.command.build_py import build_py as distutils_build_py\n\ndef get_version():\n d = {}\n file = open(os.path.join('elinks', '__init__.py'))\n try:\n for line in file:\n if line.startswith('__version__ ='):\n exec(line, d)\n finally:\n file.close()\n try:\n return d['__version__']\n except LookupError:\n raise IOError('Unexpected end-of-file')\n\nos.putenv('TAR_OPTIONS', '--owner root --group root --mode a+rX')\n\ndistutils.core.setup(\n name = 'python-elinks',\n version = get_version(),\n license = 'GNU GPL 2',\n platforms = ['any'],\n description = 'ELinks-like encoding error handler',\n long_description = __doc__.strip(),\n classifiers = classifiers,\n url = 'http://jwilk.net/software/python-elinks',\n author = 'Jakub Wilk',\n author_email = 'jwilk@jwilk.net',\n packages = ['elinks'],\n cmdclass = dict(build_py=distutils_build_py),\n)\n\n# vim:ts=4 sw=4 et\n","sub_path":"pypi_install_script/python-elinks-0.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"391580297","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime\n\nimport guzzle_sphinx_theme\n\nextensions = [\n \"sphinx.ext.githubpages\",\n \"sphinx.ext.intersphinx\",\n \"sphinx.ext.mathjax\",\n \"sphinx.ext.todo\",\n \"guzzle_sphinx_theme\",\n]\n\nsource_suffix = \".rst\"\nmaster_doc = \"index\"\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\nproject = \"Nengo Enhancement Proposals\"\ncopyright = \"2017, Applied Brain Research\"\nauthor = \"Applied Brain Research\"\nversion = release = datetime.now().strftime(\"%Y-%m-%d\")\nlanguage = None\n\ntodo_include_todos = True\n\nintersphinx_mapping = {}\n\n# HTML theming\npygments_style = \"sphinx\"\ntemplates_path = [\"_templates\"]\nhtml_static_path = []\nhtml_use_smartypants = True\n\nhtml_theme_path = guzzle_sphinx_theme.html_theme_path()\nhtml_theme = \"guzzle_sphinx_theme\"\n\nhtml_theme_options = {\n \"project_nav_name\": \"NEPs\",\n \"base_url\": \"https://www.nengo.ai/enhancement-proposals\",\n}\n\n# Other builders\nhtmlhelp_basename = \"NEPs\"\n\nlatex_elements = {\n # \"papersize\": \"letterpaper\",\n # \"pointsize\": \"11pt\",\n # \"preamble\": \"\",\n # \"figure_align\": \"htbp\",\n}\n\nlatex_documents = [\n (master_doc, # source start file\n \"neps.tex\", # target name\n project, # title\n \"Applied Brain Research\", # author\n \"manual\"), # documentclass\n]\n\nman_pages = [\n # (source start file, name, description, authors, manual section).\n (master_doc, \"neps\", project, [author], 1)\n]\n\ntexinfo_documents = [\n (master_doc, # source start file\n \"NEPs\", # target name\n project, # title\n author, # author\n \"Nengo\", # dir menu entry\n project, # description\n \"Miscellaneous\"), # category\n]\n","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"229781969","text":"from sqlalchemy import Column, String, Integer, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom ..event_types import ADD_NEW_ITEM\n\n\nTABLE_NAME_ITEMS = \"items\"\nTABLE_NAME_INDEX = \"index\"\n\n\nBase = declarative_base()\n\n\nclass Items(Base):\n __tablename__ = TABLE_NAME_ITEMS\n\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\n\nclass Index(Base):\n __tablename__ = TABLE_NAME_INDEX\n\n id = Column(Integer, primary_key=True)\n index = Column(Integer)\n\n\nclass PostgresReadModel:\n\n # Constructor\n\n def __init__(self, event_store):\n self._event_store = event_store\n\n # Read model methods\n\n def get_items(self):\n engine = self._get_engine()\n self._ensure_updated(engine)\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n rows = session.query(Items).all()\n\n items = [{\"name\": r.name} for r in rows]\n\n return items\n\n # Helper methods\n\n def _get_engine(self):\n\n db_params = {\n \"host\": \"postgres\",\n \"port\": 5432,\n \"database\": \"postgres\",\n \"user\": \"postgres\",\n \"password\": \"notverysecret\",\n }\n\n db_link = \"postgresql://{}:{}@{}:{}/{}\".format(\n db_params[\"user\"],\n db_params[\"password\"],\n db_params[\"host\"],\n db_params[\"port\"],\n db_params[\"database\"],\n )\n\n return create_engine(db_link, echo=True)\n\n def _ensure_db_created(self, engine):\n\n has_tables = [\n engine.dialect.has_table(engine, TABLE_NAME_ITEMS),\n engine.dialect.has_table(engine, TABLE_NAME_INDEX),\n ]\n\n if not all(has_tables):\n Base.metadata.create_all(engine)\n\n def _get_index(self, engine):\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n indexes = session.query(Index).all()\n\n return indexes[0].index if indexes else 0\n\n def _set_index(self, engine, index):\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n indexes = session.query(Index).all()\n\n if indexes:\n indexes[0].index = index\n else:\n new_item = Index(index=index)\n session.add(new_item)\n\n session.commit()\n\n def _ensure_updated(self, engine):\n\n self._ensure_db_created(engine)\n index = self._get_index(engine)\n\n new_events = self._event_store.get_events(index + 1)\n\n event_handlers = self._get_event_handlers()\n\n if new_events:\n\n last_index = new_events[-1].get(\"index\")\n\n for event in new_events:\n\n handler = event_handlers.get(event.get(\"type\"))\n\n if handler:\n handler(engine, event)\n\n self._set_index(engine, last_index)\n\n def _get_event_handlers(self):\n return {ADD_NEW_ITEM: self._handle_add_new_item}\n\n def _handle_add_new_item(self, engine, event):\n Session = sessionmaker(bind=engine)\n session = Session()\n\n payload = event.get(\"payload\")\n name = payload.get(\"name\") if payload else None\n new_item = Items(name=name)\n\n session.add(new_item)\n session.commit()\n","sub_path":"fullstack/1/server/events/readmodels/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"112791935","text":"import numpy as np\r\nfrom scipy import ndimage\r\nfrom PIL import Image\r\n\r\nroberts_cross_v = np.array([[1, 0],\r\n [0, -1]])\r\n\r\nroberts_cross_h = np.array([[0, 1],\r\n [-1, 0]])\r\n\r\nstoch_bits = 5\r\nstoch = int(2**stoch_bits)\r\n\r\n\r\ndef load_image(infilename):\r\n img = Image.open(infilename)\r\n img.load()\r\n # note signed integer\r\n return np.asarray(img, dtype=\"int32\")\r\n\r\n\r\ndef save_image(data, outfilename):\r\n img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype=\"uint8\"), \"L\")\r\n img.save(outfilename)\r\n\r\n\r\nif __name__ == '__main__':\r\n np.set_printoptions(threshold=np.inf)\r\n\r\n infilename = 'edge_detection_original.jpg'\r\n outfilename = 'perm_ED_S3_' + str(stoch_bits) + '_stochastic_bits_subtraction.jpg'\r\n\r\n outfilename_1 = 'output_conv_circle.jpg'\r\n outfilename_2 = 'output_stoch_circle.jpg'\r\n image = load_image(infilename)\r\n image = image[..., 0]\r\n image_conv = (image // stoch) * stoch\r\n image_stoch = image % stoch\r\n\r\n # conventional part\r\n vertical = ndimage.convolve(image_conv, roberts_cross_v)\r\n horizontal = ndimage.convolve(image_conv, roberts_cross_h)\r\n\r\n output_image_conv = abs(vertical) + abs(horizontal)\r\n output_image_conv = output_image_conv[:-1, :-1]\r\n save_image(output_image_conv, outfilename_1)\r\n\r\n # stochastic part\r\n\r\n # fixed SN length -- 256\r\n # Is = np.random.randint(0, 255 % stoch + 1, (image.shape[0] - 1, image.shape[1] - 1, 256), dtype='uint8')\r\n # changing SN length -- stoch\r\n Is = np.random.randint(0, 255 % stoch + 1, (image.shape[0] - 1, image.shape[1] - 1, stoch), dtype='uint8')\r\n\r\n Is_1 = (Is < image_stoch[:-1, :-1, np.newaxis])\r\n Is_2 = (Is < image_stoch[1:, :-1, np.newaxis])\r\n Is_3 = (Is < image_stoch[:-1, 1:, np.newaxis])\r\n Is_4 = (Is < image_stoch[1:, 1:, np.newaxis])\r\n\r\n t_1 = np.logical_xor(Is_1, Is_4)\r\n t_2 = np.logical_xor(Is_2, Is_3)\r\n\r\n # Generate SNs for select lines\r\n Ss = np.random.randint(0, 2, t_1.shape, dtype='uint8')\r\n\r\n output_image_stoch = t_1 * Ss + t_2 * (1 - Ss)\r\n output_image_stoch = np.mean(output_image_stoch, axis=-1) * (stoch - 1)\r\n save_image(output_image_stoch, outfilename_2)\r\n\r\n save_image(output_image_conv - output_image_stoch, outfilename)\r\n","sub_path":"Design Set 3/hybrid_edge_detection.py","file_name":"hybrid_edge_detection.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"219560194","text":"from django.conf.urls import patterns, url\nfrom SABR import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^player/(?P[\\w\\-]+)/$', views.player, name='player'),\n # url(r'^search-form/$', views.search_form),\n url(r'^search/$', views.search),\n url(r'^api/get_players/', views.get_players, name='get_players'),\n url(r'^about', views.about, name='about'),\n \n \n \n \n \n \n\n \n )\n \n ","sub_path":"SABR/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"54982244","text":"\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\n\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport torchaudio\n\nimport audioset\n\n\nclass Dataset(audioset.Dataset):\n\n splits = {\n \"train\": [\"train-clean-100\"],\n \"validation\": [\"dev-clean\"],\n \"test\": [\"test-clean\", \"test-other\"],\n }\n\n sample_rate = 16000\n\n def __init__(self, data_path, preprocessor, split, augment=False):\n augmentation = []\n if augment:\n augmentation = [\n torchaudio.transforms.FrequencyMasking(27, iid_masks=True),\n torchaudio.transforms.FrequencyMasking(27, iid_masks=True),\n torchaudio.transforms.TimeMasking(100, iid_masks=True),\n torchaudio.transforms.TimeMasking(100, iid_masks=True),\n ]\n\n super(Dataset, self).__init__(\n data_path,\n preprocessor,\n split,\n self.splits,\n augmentation=augmentation,\n sample_rate=self.sample_rate,\n )\n\n\nif __name__ == \"__main__\":\n import argparse\n import torch\n\n parser = argparse.ArgumentParser(description=\"Compute data stats.\")\n parser.add_argument(\"--data_path\", type=str, help=\"Path to dataset JSON files.\")\n parser.add_argument(\n \"--save_text\", type=str, help=\"Path to save parsed train text.\", default=None\n )\n parser.add_argument(\n \"--save_tokens\", type=str, help=\"Path to save tokens.\", default=None\n )\n parser.add_argument(\n \"--compute_stats\",\n action=\"store_true\",\n help=\"Compute training data statistics.\",\n default=False,\n )\n args = parser.parse_args()\n\n preprocessor = audioset.Preprocessor(args.data_path, 80, Dataset.splits)\n print(f\"Number of tokens: {preprocessor.num_tokens}\")\n trainset = Dataset(args.data_path, preprocessor, split=\"train\", augment=False)\n if args.save_text is not None:\n with open(args.save_text, \"w\") as fid:\n fid.write(\"\\n\".join(t for _, t, _ in trainset.dataset))\n if args.save_tokens is not None:\n with open(args.save_tokens, \"w\") as fid:\n fid.write(\"\\n\".join(preprocessor.tokens))\n valset = Dataset(args.data_path, preprocessor, split=\"validation\")\n testset = Dataset(args.data_path, preprocessor, split=\"test\")\n print(\"Number of examples per dataset:\")\n print(f\"Training: {len(trainset)}\")\n print(f\"Validation: {len(valset)}\")\n print(f\"Test: {len(testset)}\")\n\n if not args.compute_stats:\n import sys\n\n sys.exit(0)\n\n # Compute mean and var stats:\n audio = torch.cat([trainset[i][0] for i in range(len(trainset))], dim=2)\n mean = torch.mean(audio)\n std = torch.std(audio)\n print(f\"Data mean {mean} and standard deviation {std}.\")\n\n # Compute average lengths of audio and targets:\n avg_in_t = sum(w for (w, _), _ in trainset.sample_sizes()) / len(trainset)\n avg_tgt_l = sum(l for _, l in trainset.sample_sizes()) / len(trainset)\n print(f\"Average audio length {avg_in_t} (s)\")\n print(f\"Average target length {avg_tgt_l}\")\n","sub_path":"datasets/librispeech.py","file_name":"librispeech.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"56118157","text":"import random\n\n\nclass Operation:\n \"\"\"\n Abstract base class for all types of operations that may be put into a pipeline.\n \"\"\"\n def __init__(self):\n \"\"\"\n Create the Operation.\n By default, `requires_full_dataset_in_memory` member variable is set to False to tell that\n the operation works with generators (may process just one sample at a time) and doesn't require the full dataset\n to be stored in the memory. It may be overriden in the subclasses.\n \"\"\"\n self.requires_full_dataset_in_memory = False\n\n def __str__(self):\n \"\"\" Stringify the operation \"\"\"\n return self.__class__.__name__\n\n def execute(self, images_and_density_maps):\n \"\"\" Abstract method that must be implemented in the subclasses, should take and return an iterable of img+DM pairs \"\"\"\n raise NotImplementedError(\"execute method not implemented in the child class\")\n\n\nclass Duplicate(Operation):\n \"\"\"\n Duplicates each sample in a dataset a specified number of times. One of the most helpful operations when it comes\n to data augmentation.\n \"\"\"\n def __init__(self, duplicates_num):\n \"\"\"\n Define duplication.\n\n :param duplicates_num: Each sample will be repeated that number of times.\n \"\"\"\n Operation.__init__(self)\n self.duplicates_num = duplicates_num\n\n def execute(self, images_and_density_maps):\n \"\"\" Duplicates samples \"\"\"\n for image_and_density_map in images_and_density_maps:\n for i in range(self.duplicates_num):\n yield image_and_density_map\n\n\nclass Dropout(Operation):\n \"\"\"\n Drops out samples with a given probability.\n \"\"\"\n def __init__(self, probability):\n \"\"\"\n Define dropout.\n\n :param probability: Each sample will be dropped out with this probability, meaning that the estimated number of output images for a dataset with `N` samples is `N*(1-probability)`.\n \"\"\"\n Operation.__init__(self)\n self.probability = probability\n\n def execute(self, images_and_density_maps):\n \"\"\" Drops out samples \"\"\"\n for image_and_density_map in images_and_density_maps:\n if random.random() >= self.probability:\n yield image_and_density_map\n\n\nclass RandomArgs(Operation):\n \"\"\"\n Allows running operations with randomized numeral arguments.\n \"\"\"\n def __init__(self, operation, const_args, random_args):\n \"\"\"\n Specify randomization by providing the operation to invoke, const arguments that must be passed as they are and\n random arguments that will be randomized.\n\n :param operation: Type of operation that will be invoked. Must come from this, .outputs or .transformations module.\n :param const_args: Dictionary of constant arguments, i.e. ones whose values (nor names) won't change.\n :param random_args: Dictionary of randomized arguments specified as (min, max) tuple for each arg name. Values are taken from uniform distribution and are either floats or ints, depending on the types of provided min and max values.\n \"\"\"\n Operation.__init__(self)\n self.operation = operation\n self.const_args = const_args\n self.random_args = random_args\n\n def _get_op_str(self):\n \"\"\"\n Retrieve string representation of the operation to invoke, in a form that is ready to be computed in eval. That\n means, a prefix with module name is added when necessary. Only operations from this, .outputs and\n .transformations modules are supported.\n\n :return: Potentially prefixed operation name.\n \"\"\"\n import CCAugmentation.outputs as cca_out\n import CCAugmentation.transformations as cca_trans\n\n op_name_str = self.operation.__name__\n\n try:\n getattr(cca_trans, op_name_str)\n op_str = f\"cca_trans.{op_name_str}\"\n except AttributeError:\n try:\n getattr(cca_out, op_name_str)\n op_str = f\"cca_out.{op_name_str}\"\n except AttributeError:\n op_str = op_name_str\n\n return op_str\n\n def _get_const_str(self):\n \"\"\"\n Transform dictionary of constant arguments to string that can be used inside parentheses in eval().\n\n :return: String representing constant arguments.\n \"\"\"\n const_components = []\n for k, v in self.const_args.items():\n v_str = f\"'{v}'\" if type(v) is str else str(v)\n const_components.append(f\"{k}={v_str}\")\n return \",\".join(const_components)\n\n def _get_rand_str(self):\n \"\"\"\n Randomize, cast and transform to string the arguments that are to be randomized.\n\n :return: String representing randomized arguments.\n \"\"\"\n rand_components = []\n for key, (min_val, max_val) in self.random_args.items():\n val = random.uniform(min_val, max_val)\n if type(min_val) is int and type(max_val) is int:\n val = int(val)\n rand_components.append(f\"{key}={str(val)}\")\n return \",\".join(rand_components)\n\n def execute(self, images_and_density_maps):\n \"\"\"\n Create and execute the given operation with a set of constant and randomized arguments.\n\n :param images_and_density_maps: Iterable of img+DM pairs that are to be used in the operation.\n :return: Result img+DM pairs from the operation.\n \"\"\"\n # these imports are used in eval(), don't remove them\n import CCAugmentation.outputs as cca_out\n import CCAugmentation.transformations as cca_trans\n _ = cca_out, cca_trans\n\n op_str = self._get_op_str()\n const_str = self._get_const_str()\n\n for image_and_density_map in images_and_density_maps:\n rand_str = self._get_rand_str()\n args_str = \",\".join([const_str, rand_str]) if const_str and rand_str else const_str + rand_str\n op = eval(f\"{op_str}({args_str})\")\n for result in op.execute([image_and_density_map]):\n yield result\n","sub_path":"shb-mcnn/exp/11-27_20-08_SHHB_MCNN_0.0001_[crop2]/code/CCAugmentation/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"212630053","text":"from os.path import dirname, join\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom load_data import load_dataset\nfrom model import XGboostModel\n\ndata_train = join(dirname(dirname(dirname(__file__))), \"data\", \"vlsp2018\", \"corpus\", \"restaurant\", \"train.xlsx\")\ndata_dev = join(dirname(dirname(dirname(__file__))), \"data\", \"vlsp2018\", \"corpus\", \"restaurant\", \"dev.xlsx\")\n\nX_train, y_train = load_dataset(data_train)\nX_dev, y_dev = load_dataset(data_dev)\nmodels = []\n\nX = X_train + X_dev\ny = y_train + y_dev\n\nfor n_iter in [100, 140, 160, 200, 500]:\n # for max_depth in [50, 100, 140, 160, 200, 300]:\n for max_depth in [200, 300, 400, 500]:\n # for max_features in [1000, 2000, 2200, 2400, 2600, 3000]:\n for max_features in [2000, 3000, 4000]:\n name = \"XGBoost(n_iter {0} max_depth {1}) + Count(bigram, max_features {2})\".format(n_iter, max_depth, max_features)\n params = {\"n_iter\": n_iter, \"max_depth\": max_depth}\n model = XGboostModel(\n name,\n params,\n CountVectorizer(ngram_range=(1, 2), max_features=max_features)\n )\n models.append(model)\n\nfor model in models:\n from datetime import datetime\n start = datetime.now()\n model.load_data(X, y)\n model.fit_transform()\n model.train()\n model.evaluate(X_dev, y_dev)\n print(datetime.now() - start)\n","sub_path":"experiments/restaurant/tuning_xgboost.py","file_name":"tuning_xgboost.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"162514626","text":"# -----------------------------------------------------------------------------\n#\n# This file is part of the ParaNut project.\n#\n# Copyright (C) 2023-2024 Daniel Bortkevych \n# Oleg Murashko \n# Haris Vojic \n# Hochschule Augsburg, University of Applied Sciences\n#\n# Description:\n# Transfers requests and responses between View and Model\n#\n# --------------------- LICENSE -----------------------------------------------\n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation \n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n# SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND \n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# -----------------------------------------------------------------------------\n\n## @package Controller\nimport math\nimport logging\nimport sys\n\nlogger\t\t\t= logging.getLogger(__name__)\n\nfile_handler\t= logging.FileHandler('logger/controll.log', mode = 'w')\nconsole_handler\t= logging.StreamHandler(stream = sys.stdout)\n\nformat = \"%(levelname)s:%(name)10.10s:%(funcName)20.20s:%(lineno)4d:%(message)s\"\nformatter\t\t= logging.Formatter(format)\n\nfile_handler.setFormatter(formatter)\nconsole_handler.setFormatter(formatter)\n\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(file_handler)\nlogger.addHandler(console_handler)\n\n##\tController class is responsible for the communication between the other \n#\tmodules\tof the MVC-model.\nclass Controller:\n\t## Constructor which takes external model and view to operate with.\n\t#\n\t# @param self The object pointer.\n\t# @param model Model object\n\t# @param view View object\n\t#\n\t# @return An instance of the Controller class initialized with the \n\t# specified View and Model object.\n\tdef __init__(self, model, view):\n\t\tlogger.debug(f'Initialization started')\n\t\tlogger.debug(f'Initializing model and view')\n\t\t\n\t\tself.model\t= model;\n\t\tself.view\t= view;\n\n\t\tlogger.debug(f'Initialization finished')\n\n\n\t\t\n\t# Getter methods\n\t#---------------------------------------------------------------------------\n\t@property\n\tdef model(self):\n\t\treturn self.__model\n\n\t@property\n\tdef view(self):\n\t\treturn self.__view\n\n\t# Setter methods\n\t#---------------------------------------------------------------------------\n\t@model.setter\n\tdef model(self, value):\n\t\tif value.__class__.__name__ == 'Model':\n\t\t\tself.__model = value\n\t\telse:\n\t\t\traise ValueError(f'Invalid model: {value}')\n\n\t@view.setter\n\tdef view(self, value):\n\t\tif value.__class__.__name__ == 'View':\n\t\t\tself.__view = value\n\t\telse:\n\t\t\traise ValueError(f'Invalid view: {value}')\n\n\t# Load/Store methods\n\t#---------------------------------------------------------------------------\n\n\t## Reloads configuration data from json file and saves them into a model \n\t# object.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef reload_object(self):\n\n\t\t## @var file\t\tThe JSON file to be opened.\n\t\tfile = f'{self.view.json_path}/{self.view.json_file}.json'\n\t\tlogger.debug(f'Reloading file: {file}')\n\t\tself.model._read_configuration(file)\n\t\n\t## Saves configuraiton as JSON.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\t# @param filename\t\tString name of the file to be saved.\n\tdef save_configuration(self, filename):\n\t\tlogger.debug(f'Saving configuration under: {filename}')\t\n\t\tself.model.save_configuration(filename)\n\n\t## Loads configuration from self.config to glade.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef load_configuration(self):\n\t\tlogger.debug(f'Loading configuration from objects to gtk_objects')\n\t\tfor unit in self.model.get_units():\n\t\t\t# NOTE: potential bug solution\n\t\t\tif unit == \"description\":\n\t\t\t\tcontinue\n\t\t\tmodule = getattr(self.model, unit)\n\n\t\t\tfor setting in module.get_attributes():\n\t\t\t\tgtk_object = self.view.builder.get_object(setting)\n\n\t\t\t\tattribute = getattr(module, setting)\n\t\t\t\ttry:\n\t\t\t\t\tif \"ld\" in setting:\n\t\t\t\t\t\tld = int(attribute.get('value'))\n\t\t\t\t\t\tld = str(2**ld)\n\n\t\t\t\t\t\tgtk_object.set_text(ld)\n\n\t\t\t\t\telif \"cap1\" in setting:\n\t\t\t\t\t\tgtk_object.set_text(attribute.get('value'))\n\t\t\t\t\t\tself.view.check_cores()\n\n\t\t\t\t\telif \"mem_size\" in setting:\n\t\t\t\t\t\tvalue = attribute.get('value')\n\t\t\t\t\t\tvalue = ''.join(ch for ch in value if ch.isdigit())\n\t\t\t\t\t\t\n\t\t\t\t\t\tgtk_object.set_text(value)\n\t\t\t\t\n\t\t\t\t\telif \"perfcounter_bits\" in setting:\n\t\t\t\t\t\tgtk_object.set_value(int(attribute.get('value')))\n\n\t\t\t\t\telse:\n\t\t\t\t\t\tgtk_object.set_text(attribute.get('value'))\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tgtk_object.set_active_id(attribute.get('value'))\n\t\t\t\t\t# TODO: checkbox and radiobuttons\n\t\t\t\t\texcept:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tif attribute.get('value') == '1':\n\t\t\t\t\t\t\t\tgtk_object.set_active(True)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tgtk_object.set_active(False)\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tlogger.error(f'Failed to edit: {setting}')\n\n\t## This function stores the configuration values from a View object into a \n\t# Model object.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef store_data(self):\n\t\tlogger.debug(f'Storing date from gtk_objects to objects')\n\t\tfor unit in self.model.get_units():\n\t\t\tif unit == \"description\":\n\t\t\t\tcontinue\n\t\t\tmodule = getattr(self.model, unit)\n\t\t\tfor setting in module.get_attributes():\n\t\t\t\tgtk_object = self.view.builder.get_object(setting)\n\t\t\t\t\n\t\t\t\tattribute = getattr(module, setting)\n\t\t\t\ttry:\n\t\t\t\t\tif gtk_object.__class__.__name__ == \"Entry\":\n\t\t\t\t\t\tif setting == \"mem_size\":\n\t\t\t\t\t\t\tvalue = f'({gtk_object.get_text()} * MB)'\n\t\t\t\t\t\t\tattribute.update({\"value\": value}) \n\n\t\t\t\t\t\telif \"ld\" in setting:\n\t\t\t\t\t\t\tld = gtk_object.get_text()\n\t\t\t\t\t\t\tld = int(ld)\n\t\t\t\t\t\t\tld = int(math.log2(ld))\n\t\t\t\t\t\t\tld = str(ld)\n\t\t\t\t\t\t\tattribute.update({\"value\": ld})\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tvalue = gtk_object.get_text()\n\t\t\t\t\t\t\tattribute.update({\"value\": value})\n\t\t\t\t\telif setting == \"perfcounter_bits\":\n\t\t\t\t\t\tvalue = int(gtk_object.get_value())\n\t\t\t\t\t\tvalue = str(value)\n\n\t\t\t\t\t\tattribute.update({\"value\": value})\n\n\t\t\t\t\telif gtk_object.__class__.__name__ == \"CheckButton\":\n\t\t\t\t\t\tif(gtk_object.get_active()):\n\t\t\t\t\t\t\tattribute.update({\"value\": \"1\"})\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tattribute.update({\"value\": \"0\"})\n\t\t\t\t\t\n\t\t\t\t\telif gtk_object.__class__.__name__ == \"ComboBoxText\":\n\t\t\t\t\t\tvalue = gtk_object.get_active_id()\n\t\t\t\t\t\tattribute.update({\"value\": value})\n\t\t\t\texcept:\n\t\t\t\t\tlogger.error(\"aloha\")\n\t\t\t\t\t\n\t## Creates \"config.mk\" configuration file.\n\t#\n\t#\n\t# @param self\t\t\tThe object pointer.\n\t# @pram path Path to the saving location of \"config.mk\"\n\tdef make_configuration(self, path = \"\"):\n\t\ttry:\n\t\t\tself.model.make_configuration(path = \"\")\n\t\texcept ValueError as error:\n\t\t\tself.view.show_error(error)\n\n\t## Reads data into objects from a JSON file.\n\t#\n\t# @param self\t\t\tThe object pointer.\n\tdef _load_configuration(self):\n\t\tjson_path = f'{self.view.json_path}/{self.view.json_file}'\n\t\tlogger.debug(f'Loading json configuration file {json_path}')\n\t\tself.model._read_configuration(json_path)\n","sub_path":"config-creator/src/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":7899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"545769035","text":"\"\"\"\n比较两个文件夹里面的内容,包括文件的大小,创建时间(比较同名文件),以及显示出不同文件(即不是共有的部分)\n\"\"\"\nimport os\nimport time\nfrom file_utils import paths\nfrom text_utils import text_diff\n\n\ndef listfiledetails(folder):\n assert os.path.exists(folder)\n\n foldercontents = []\n\n absfolder = os.path.abspath(folder)\n for file in os.listdir(absfolder):\n absfile = os.path.join(absfolder, file)\n filesize = os.path.getsize(absfile)\n createdtime = getreadabletime(os.path.getctime(absfile))\n contentitem = '%s\\t\\t%s\\t\\t%s' % (file, filesize, createdtime)\n\n foldercontents.append(contentitem)\n\n return foldercontents\n\n\ndef getreadabletime(seconds: float):\n \"\"\"\n 返回格式良好的时间,如果seconds为空,则返回当前时间的格式化字符串\n :param seconds: 时间秒数,\n :return:\n \"\"\"\n import time\n\n DEFAULT_FORMAT = '%y-%m-%d %H:%M:%S'\n\n return time.strftime(DEFAULT_FORMAT, time.gmtime(seconds))\n\n\ndef compareandgenerateresulthtml(folder1, folder2):\n assert folder1\n assert folder2\n\n assert paths.isvalidpath(folder1)\n assert paths.isvalidpath(folder2)\n\n fc1 = listfiledetails(folder1)\n fc2 = listfiledetails(folder2)\n\n rh = text_diff._diffstrtoHtml(fc1, fc2)\n\n with open('fs.html', 'w') as r:\n r.write(rh)\n\n pass\n\n\nif __name__ == '__main__':\n listfiledetails('test')\n","sub_path":"file_utils/dir_compare.py","file_name":"dir_compare.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"465114025","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom gezimeclise.blog import urls as blog_url\nfrom django.conf import settings\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^$', TemplateView.as_view(template_name=\"index.html\"),\n name=\"landing_page\"),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^kullanicilar/', include('gezimeclise.profiles.urls')),\n url(r'^yazilar/', include('gezimeclise.blog.urls')),\n url(r'^bildirimler/', include('gezimeclise.notifications.urls')),\n url(r'^facebook/', include('django_facebook.urls')),\n url(r'^forum/', TemplateView.as_view(template_name=\"moot_it_forum.html\"),\n name=\"forum\"),\n url(r'^accounts/', include('django_facebook.auth_urls')),\n url(r'^talepler/', include('gezimeclise.causes.urls'))\n)\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"gezimeclise/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"433897064","text":"from datetime import datetime\nfrom datetime import timedelta\nfrom get_actions import get_actions\nimport pandas as pd\nimport pickle\nimport os\n\n\n#计算日期差\ndef lasttime(the_time):\n end_date = end_date_line\n return int((datetime.strptime(end_date, '%Y-%m-%d') - datetime.strptime(the_time,'%Y-%m-%d')).total_days())\n\n#获取商品各种互动行为总数\ndef get_product_num(start_date, end_date):\n dump_path = './data/product/product_num_%s_%s.pkl' % (start_date, end_date)\n if os.path.exists(dump_path):\n actions = pickle.load(open(dump_path, 'rb'),)\n else:\n actions = get_actions(start_date, end_date)\n actions = actions[['product_id', 's_num', 'c_num', 'r_num', 'b_num']]\n\n #各项求和\n actions = actions.groupby(['product_id'], as_index=False).sum()\n pickle.dump(actions, open(dump_path, 'wb'))\n return actions\n\n#获取用户最近一次互动行为的时间与截止时��的间隔,最大间隔默认为30天\ndef get_product_lasttime(start_date, end_date):\n feature = ['product_id','product_s_lasttime','product_c_lasttime','product_r_lasttime','product_b_lasttime']\n dump_path = './data/product/product_lasttime_%s_%s.pkl' % (start_date, end_date)\n global end_date_line\n end_date_line = end_date\n\n if os.path.exists(dump_path):\n actions = pickle.load(open(dump_path, 'rb'),)\n else:\n actions = get_actions(start_date, end_date)\n actions = actions[['product_id', 's_num', 'c_num','r_num','b_num','Date']]\n\n actions = actions.groupby(['product_id', 's_num', 'c_num','r_num','b_num'], as_index=False).last()\n actions['product_s_lasttime'] = actions[actions.s_num != 0].Date.map(lasttime)\n actions['product_c_lasttime'] = actions[actions.c_num != 0].Date.map(lasttime)\n actions['product_r_lasttime'] = actions[actions.r_num != 0].Date.map(lasttime)\n actions['product_b_lasttime'] = actions[actions.b_num != 0].Date.map(lasttime)\n\n actions = actions.groupby(['product_id'], as_index=False).sum()\n actions = actions[feature]\n actions = actions.fillna(30)\n actions.to_csv('./data/product/product_lasttime_%s_%s.csv' % (start_date, end_date), index=False,index_label=False)\n pickle.dump(actions, open(dump_path, 'wb'))\n return actions\n\n\ndef get_product_feat(start_date, end_date):\n #读取product特征的两个分表\n product_action_num = get_product_num(start_date, end_date)\n product_lasttime = get_product_lasttime(start_date, end_date)\n\n #合成product特征总表\n actions = pd.merge(product_action_num, product_lasttime, how='left', on=['product_id'])\n\n # 空值填充\n actions = actions.fillna({'product_s_lasttime':360, 'product_c_lasttime':360,\n 'product_r_lasttime':360, 'product_b_lasttime':360})\n actions.to_csv('./data/product/product_feat_%s_%s.csv' % (start_date, end_date), index=False,\n index_label=False)\n\n\nif __name__ == '__main__':\n start_date1 = '2016-01-01'\n end_date1 = '2016-01-31'\n\n start_date2 = '2016-02-01'\n end_date2 = '2016-02-29'\n\n start_date3 = '2016-03-01'\n end_date3 = '2016-03-31'\n\n start_date4 = '2016-04-01'\n end_date4 = '2016-04-30'\n\n start_date5 = '2016-05-01'\n end_date5 = '2016-05-31'\n\n start_date6 = '2016-06-01'\n end_date6 = '2016-06-30'\n\n start_date = [start_date1, start_date2, start_date3, start_date4, start_date5, start_date6]\n end_date = [end_date1, end_date2, end_date3, end_date4, end_date5, end_date6]\n\n for i in range(0,6):\n get_product_feat(start_date[i], end_date[i])\n","sub_path":"2/2_product_feat.py","file_name":"2_product_feat.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"21706875","text":"#!/usr/bin/evn python\r\n# -*- coding: utf-8 -*-\r\n# Author: gaoxq@ruijie.com.cn\r\n# Date: 2015.11.06\r\n#\r\n# test topo: \r\n# +--------+\r\n# | intf | nettester\r\n# +----|---+\r\n# |\r\n# +----|---------------------------------+\r\n# | steintf intf1 intf2 ... |\r\n# | | | | switch\r\n# | intfm intfn ... |\r\n# +--------------------------------------+ \r\n#\r\n\r\nimport time\r\nimport re\r\nfrom libcom.lib_pub.logging_drv import log_info\r\nfrom libcom.console_drv.console_drv import *\r\nfrom port_pub_lib import *\r\n\r\n__all__ = [\"port_speed_cfg\"]\r\n\r\nmedium_ability = ['copper', 'fiber']\r\nspeed_ability = ['auto', '10G', '1000', '100', '10']\r\nduplex_ability = ['auto', 'full', 'half']\r\nflow_ctrl_ability = ['auto', 'on', 'off']\r\n\r\ndef port_intf_ability_init():\r\n ability = {}\r\n s_ab = {}\r\n d_ab = {}\r\n f_ab = {}\r\n\r\n for medium in medium_ability:\r\n for speed in speed_ability:\r\n for duplex in duplex_ability:\r\n for flow_ctrl in flow_ctrl_ability:\r\n f_ab[flow_ctrl] = False\r\n d_ab[duplex] = f_ab.copy()\r\n s_ab[speed] = d_ab.copy()\r\n ability[medium] = s_ab.copy()\r\n return ability\r\n\r\ndef port_intf_ability_get(dev, intf):\r\n ability = port_intf_ability_init()\r\n intf_medium = port_intf_medium_get(dev, intf)\r\n max_speed = port_intf_max_speed_get(intf)\r\n if max_speed == '10G':\r\n for speed in speed_ability[:3]:\r\n for duplex in duplex_ability[:2]:\r\n for flow_ctrl in flow_ctrl_ability:\r\n ability[intf_medium][speed][duplex][flow_ctrl] = True\r\n else:\r\n for speed in speed_ability[speed_ability.index(max_speed):] + ['auto']:\r\n for duplex in duplex_ability:\r\n for flow_ctrl in flow_ctrl_ability:\r\n ability[intf_medium][speed][duplex][flow_ctrl] = True\r\n\r\n return ability\r\n\r\ndef port_cmd_unsupport_promt_check(promt, intf, cmd_name, cmd):\r\n if promt.find('% fail to set speed or do not support the command.') == -1 \\\r\n and promt.find('% Invalid input detected') == -1:\r\n log_info(\"\\t####interface %s not prompt fail after setting invalid %s[%s]\" \\\r\n %(intf, cmd_name, cmd))\r\n return FAIL\r\n return PASS\r\n\r\ndef port_intf_an_get(speed, duplex, flow_ctrl):\r\n if speed != 'auto' and duplex != 'auto' and flow_ctrl != 'auto':\r\n return False\r\n else:\r\n return True\r\n\r\ndef port_intf_speed_single_auto(intf1_medium, intf1_max_speed, intf2_speed, intf2_an):\r\n \"\"\"\r\n intf1 as speed auto\r\n return as: (intf1_link, intf2_link)\r\n \"\"\"\r\n if intf1_max_speed != intf2_speed:\r\n if intf1_medium == 'fiber':\r\n return (False, False)\r\n\r\n if speed_ability.index(intf1_max_speed) > speed_ability.index(intf2_speed):\r\n return (False, False)\r\n \r\n if intf2_an:\r\n return (True, True)\r\n else:\r\n if intf1_medium == 'fiber' and intf1_max_speed == '1000':\r\n return (False, True)\r\n else:\r\n return (True, True)\r\n\r\ndef port_intf_duplex_single_auto(link_speed, intf1_medium, intf2_duplex, intf2_an):\r\n \"\"\"\r\n intf1 as duplex auto\r\n return as: (link, intf1_link_duplex, intf2_link_duplex)\r\n \"\"\"\r\n if link_speed == '10G':\r\n return (False, intf2_duplex, intf2_duplex)\r\n\r\n if link_speed == '1000' and intf1_medium == 'copper':\r\n return (True, intf2_duplex, intf2_duplex)\r\n\r\n if intf2_an:\r\n return (True, intf2_duplex, intf2_duplex)\r\n else:\r\n return (True, 'half', intf2_duplex)\r\n\r\ndef port_intf_link_check(intf1_cfg, intf2_cfg):\r\n \"\"\"\r\n intf1_cfg: (medium, max_speed, speed, duplex, flow_ctrl)\r\n intf2_cfg: (medium, max_speed, speed, duplex, flow_ctrl)\r\n return as: (intf1(link, speed, duplex, flow_ctrl), intf2(link, speed, duplex, flow_ctrl))\r\n \"\"\"\r\n (intf1_medium, intf1_max_speed, intf1_speed, intf1_duplex, intf1_flowctrl) = intf1_cfg\r\n (intf2_medium, intf2_max_speed, intf2_speed, intf2_duplex, intf2_flowctrl) = intf2_cfg\r\n\r\n link_down = (False, 'none', 'none', 'none')\r\n\r\n intf1_link = True\r\n intf2_link = True\r\n link_speed = intf1_max_speed\r\n intf1_link_duplex = intf1_duplex\r\n intf2_link_duplex = intf2_duplex\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n intf1_an = port_intf_an_get(intf1_speed, intf1_duplex, intf1_flowctrl)\r\n intf2_an = port_intf_an_get(intf2_speed, intf2_duplex, intf2_flowctrl)\r\n\r\n # link down when pair speed not equal\r\n if intf1_speed != 'auto' and intf2_speed != 'auto' and intf1_speed != intf2_speed:\r\n return (link_down, link_down)\r\n\r\n # link down when pair duplex not equal\r\n if intf1_duplex != 'auto' and intf2_duplex != 'auto' and intf1_duplex != intf2_duplex:\r\n return (link_down, link_down)\r\n\r\n # speed equal or 'auto' mode. duplex equal or 'auto' mode\r\n if intf1_speed == 'auto' and intf2_speed == 'auto':\r\n if intf1_max_speed != intf2_max_speed:\r\n if intf1_medium == 'fiber' or intf2_medium == 'fiber':\r\n return (link_down, link_down)\r\n link_speed = min(intf1_max_speed, intf2_max_speed)\r\n elif intf1_speed == 'auto':\r\n (intf1_link, intf2_link) = port_intf_speed_single_auto(intf1_medium, intf1_max_speed, intf2_speed, intf2_an)\r\n if not intf1_link and not intf2_link:\r\n return (link_down, link_down)\r\n link_speed = intf2_speed\r\n elif intf2_speed == 'auto':\r\n (intf2_link, intf1_link) = port_intf_speed_single_auto(intf2_medium, intf2_max_speed, intf1_speed, intf1_an)\r\n if not intf1_link and not intf2_link:\r\n return (link_down, link_down)\r\n link_speed = intf1_speed\r\n elif intf1_speed != intf2_speed:\r\n return (link_down, link_down)\r\n else:\r\n link_speed = intf1_speed\r\n\r\n if intf1_duplex == 'auto' and intf2_duplex == 'auto':\r\n intf1_link_duplex = 'full'\r\n intf2_link_duplex = 'full'\r\n elif intf1_duplex == 'auto':\r\n (link_stat, intf1_link_duplex, intf2_link_duplex) = port_intf_duplex_single_auto(link_speed, intf1_medium, intf2_duplex, intf2_an)\r\n if not link_stat:\r\n return (link_down, link_down)\r\n elif intf2_duplex == 'auto':\r\n (link_stat, intf2_link_duplex, intf2_link_duplex) = port_intf_duplex_single_auto(link_speed, intf2_medium, intf1_duplex, intf1_an)\r\n if not link_stat:\r\n return (link_down, link_down)\r\n elif intf1_duplex != intf2_duplex:\r\n return (link_down, link_down)\r\n else:\r\n intf1_link_duplex = intf1_duplex\r\n intf2_link_duplex = intf2_duplex\r\n\r\n if intf1_flowctrl == 'auto' or intf2_flowctrl == 'auto':\r\n if intf1_flowctrl != 'auto':\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf1_flowctrl\r\n elif intf2_flowctrl != 'auto':\r\n intf1_link_flowctrl = intf2_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n else:\r\n intf1_link_flowctrl = 'on'\r\n intf2_link_flowctrl = 'on'\r\n else:\r\n intf1_link_flowctrl = intf1_flowctrl\r\n intf2_link_flowctrl = intf2_flowctrl\r\n\r\n return ((intf1_link, link_speed, intf1_link_duplex, intf1_link_flowctrl), (intf2_link, link_speed, intf2_link_duplex, intf2_link_flowctrl))\r\n\r\ndef port_intf_result_check(dev, intf, cfg, link_stat):\r\n \"\"\"\r\n cfg: speed, duplex, flow_ctrl\r\n link_stat: link, speed, duplex, flow_ctrl\r\n \"\"\"\r\n duplex_show = {'auto' : 'AUTO', 'full' : 'Force Full Duplex', 'half' : 'Force Half Duplex'}\r\n speed_show = {'auto' : 'AUTO', '10G' : '10G', '1000' : '1000M', '100' : '100M', '10' : '10M'}\r\n\r\n result = run_cmd(dev, 'show int %s' %intf)\r\n if not link_stat[0]:\r\n if result.find('is DOWN , line protocol is DOWN') == -1:\r\n log_info('######interface %s should link down.' %intf)\r\n return FAIL\r\n return PASS\r\n \r\n if result.find('is UP , line protocol is UP') == -1:\r\n log_info('######interface %s should link up.' %intf)\r\n return FAIL\r\n if result.find('admin duplex mode is %s, oper duplex is %s' %(duplex_show[cfg[1]], link_stat[2].capitalize())) == -1 \\\r\n or result.find('admin speed is %s, oper speed is %s' %(speed_show[cfg[0]], speed_show[link_stat[1]])) == -1 \\\r\n or result.find('flow control admin status is %s, flow control oper status is %s' %(cfg[2].upper(), link_stat[3].upper())) == -1:\r\n log_info('######interface %s link error.' %intf)\r\n log_info('intf link cfg: %s, %s, %s. link stat: %s, %s, %s' %(cfg[0], cfg[1], cfg[2], link_stat[1], link_stat[2], link_stat[3]))\r\n return FAIL\r\n return PASS\r\n\r\ndef port_intf_pkt_check(dev, intf1, intf2):\r\n port_mode_enable(dev)\r\n run_cmd(dev, 'clear counters')\r\n\r\n port_nt_pkt_send(port_nettester_get(), port_nt_intf_list(port_nettester_get())[0])\r\n time.sleep(5)\r\n\r\n for intf in [intf1, intf2]:\r\n if not port_pkts_switch_ok(dev, intf):\r\n log_info('interface %s recv/send has no pkts.' % intf)\r\n return FAIL\r\n\r\n if port_has_error_pkts(dev, intf):\r\n log_info('interface %s recv/send error pkt.' % intf)\r\n return FAIL\r\n\r\n return PASS\r\n \r\ndef port_test_func(dev, intf_cfg, peer_cfg, test_func):\r\n \"\"\"\r\n intf_cfg: (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n peer_cfg: (peer_intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n \"\"\"\r\n intf = intf_cfg[0]\r\n rv = PASS\r\n ability = port_intf_ability_get(dev, intf)\r\n medium = port_intf_medium_get(dev, intf)\r\n max_speed = port_intf_max_speed_get(intf)\r\n\r\n for speed in speed_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'speed %s' %speed)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed]['auto']['auto']:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'speed', speed)\r\n continue\r\n for duplex in duplex_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'duplex %s' %duplex)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed][duplex]['auto']:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'duplex', duplex)\r\n continue\r\n for flow_ctrl in flow_ctrl_ability:\r\n port_intf_mode(dev, intf)\r\n ret_str = run_cmd(dev, 'flowcontrol %s' %flow_ctrl)\r\n time.sleep(STABLE_WAIT)\r\n if not ability[medium][speed][duplex][flow_ctrl]:\r\n rv |= port_cmd_unsupport_promt_check(ret_str, intf, 'flowcontrl', flow_ctrl)\r\n continue\r\n intf_cfg = (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n rv |= test_func(dev, intf_cfg, peer_cfg)\r\n \r\n return rv\r\n\r\ndef port_single_test(dev, intf_cfg, peer_cfg):\r\n \"\"\"\r\n intf_cfg: (intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n peer_cfg: (peer_intf, medium, max_speed, speed, duplex, flow_ctrl)\r\n \"\"\"\r\n rv = PASS\r\n log_info('#####interface test start:')\r\n\r\n result = port_intf_link_check(intf_cfg[1:], peer_cfg[1:])\r\n \r\n for i in range(2):\r\n if i == 0:\r\n cfg = intf_cfg\r\n else:\r\n cfg = peer_cfg\r\n log_info('interface %s, %s, speed: %s, duplex: %s, flow_ctrl: %s' \\\r\n %(cfg[0], cfg[1], cfg[3], cfg[4], cfg[5]))\r\n rv |= port_intf_result_check(dev, cfg[0], cfg[3:], result[i])\r\n\r\n if rv == PASS and result[0][0] == True and result[1][0] == True:\r\n rv |= port_intf_pkt_check(dev, intf_cfg[0], peer_cfg[0])\r\n \r\n if rv == PASS:\r\n log_info('#####test pass')\r\n else:\r\n log_info('#####test fail')\r\n\r\n return rv\r\n\r\ndef port_pair_test(dev, intf_cfg, peer_cfg):\r\n return port_test_func(dev, peer_cfg, intf_cfg, port_single_test)\r\n\r\ndef _port_speed_cfg(cb_arg):\r\n dev = cb_arg.dev_names[0]\r\n rv = PASS\r\n\r\n port_lldp_enable(dev)\r\n\r\n # get test pair\r\n test_pair_lst = port_get_test_intf_pair(dev)\r\n if len(test_pair_lst) == 0:\r\n log_info(\"Failed! 接口需要互联起来.\")\r\n return FAIL\r\n\r\n port_lldp_disable(dev)\r\n\r\n # shutdown test port\r\n for pair in test_pair_lst:\r\n port_intf_shutdown(dev, pair[0])\r\n port_intf_shutdown(dev, pair[1])\r\n\r\n # test each pair\r\n for pair in test_pair_lst:\r\n # default port\r\n port_intf_default(dev, pair[0])\r\n port_intf_default(dev, pair[1])\r\n rv |= port_test_func(dev, (pair[0], 0), (pair[1], 0), port_pair_test)\r\n port_intf_shutdown(dev, pair[0])\r\n port_intf_shutdown(dev, pair[1])\r\n\r\n for pair in test_pair_lst:\r\n port_intf_default(dev, pair[0])\r\n port_intf_default(dev, pair[1])\r\n\r\n # restore lldp\r\n port_lldp_enable(dev)\r\n\r\n return rv\r\n\r\ndef port_speed_cfg(cb_arg):\r\n if len(cb_arg.dev_names) < 1:\r\n log_info(\"Failed: Need one switch to be test.\")\r\n return FAIL\r\n\r\n dev_name = cb_arg.dev_names[0]\r\n wake_up_console(dev_name)\r\n \r\n port_nettester_add(cb_arg.nt_names[0])\r\n\r\n result = FAIL\r\n try:\r\n result = _port_speed_cfg(cb_arg)\r\n finally:\r\n exit_console(dev_name)\r\n\r\n return result\r\n\r\n","sub_path":"cases_set/dintf/l2pt/port_speed_cfg.py","file_name":"port_speed_cfg.py","file_ext":"py","file_size_in_byte":13373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"608670867","text":"\n\"\"\"\nThis is very usefull module in-case of cipher encrypting and decrypting of data.\nThis contains many cipher methods. The Best of all is the vigenere cipher which\nis also used in these modern times.\n\nThe Source code is taken from the book \"Cracking Codes with Python\". Although\nhacking methods for all the ciphers are not created, the hackers can still\nbreak the code by using different techniques.\n\"\"\"\n\n__version__ = \"2020.6.4\"\n__author__ = \"Xcodz\"\n\n# Copyright (c) 2020 Xcodz.\n# All Rights Reserved.\n\nimport math\nclass cryptomath:\n def gcd(a,b):\n while a != 0:\n a,b = b%a,a\n return b\n def findModInverse(a,m):\n if cryptomath.gcd(a,m) != 1:\n return None\n u1,u2,u3=1,0,a\n v1,v2,v3=0,1,m\n while v3!=0:\n q=u3//v3\n v1,v2,v3,u1,u2,u3 = (u1-q*v1),(u2-q*v2),(u3-q*v3),v1,v2,v3\n return u1%m\nclass cVig:\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n def translateMessage(key,message,mode):\n l = cVig.l\n t =[]\n ki= 0\n k = key.upper()\n for x in message:\n n = l.find(x.upper())\n if n != -1:\n if mode == 'e':\n n+=l.find(key[ki])\n elif mode == 'd':\n n-=l.find(key[ki])\n n%=len(l)\n if x.isupper():\n t.append(l[n])\n elif x.islower():\n t.append(l[n].lower())\n ki+=1\n if ki == len(key):\n ki =0\n else:\n t.append(x)\n return ''.join(t)\nclass cSub:\n l = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n def keyIsValid(key):\n keyList = list(key)\n lettersList = list(cSub.l)\n keyList.sort()\n return keyList == lettersList\n def translateMessage(key:str,message:str,mode):\n t = ''\n ca = cSub.l\n cb = key\n if mode == 'd':\n ca,cb=cb,ca\n for x in message:\n if x.upper() in ca:\n si = ca.find(x.upper())\n if x.isupper():\n t+=cb[si].upper()\n else:\n t+=cb[si].lower()\n else:\n t+=x\n return t\nclass cAffine:\n def getKeyParts(key):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n keyA = key//len(a)\n keyB = key%len(a)\n return keyA,keyB\n def checkKeys(keyA,keyB):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n if keyA <0 or keyB<0 or keyB>len(a)-1:\n return False\n if cryptomath.gcd(keyA, len(a)) != 1:\n return False\n return True\nclass crypt:\n class morse:\n table = {\n '.-':'A',\n '-...':'B',\n '-.-.':'C',\n '-..':'D',\n '.':'E',\n '..-.':'F',\n '--.':'G',\n '....':'H',\n '..':'I',\n '.---':'J',\n '-.-':'K',\n '.-..':'L',\n '--':'M',\n '-.':'N',\n '---':'O',\n '.--.':'P',\n '--.-':'Q',\n '.-.':'R',\n '...':'S',\n '-':'T',\n '..-':'U',\n '...-':'V',\n '.--':'W',\n '-..-':'X',\n '-.--':'Y',\n '--..':'Z',\n '.----':'1',\n '..---':'2',\n '...--':'3',\n '....-':'4',\n '.....':'5',\n '-....':'6',\n '--...':'7',\n '---..':'8',\n '----.':'9',\n '-----':'0'\n }\n def encode(st:str):\n \"\"\"MORSE CODE ENCODER\n\nA ' ' MEANS PARTITION BETWEEN LETTERS\nA '/' MEANS PARTITION BETWEEN WORDS\"\"\"\n t = ''\n tb = {v:k for k,v in crypt.morse.table.items()}\n s = list(st.upper())\n for x in s:\n if x not in tb.keys() and x != ' ':\n s.remove(x)\n w = []\n for x in s:\n if x == ' ':\n t+=' '.join(w)+'/'\n w = []\n else:\n w.append(tb[x])\n t+=' '.join(w)\n return t\n def decode(s:str):\n tb = crypt.morse.table.copy()\n d = [x.split() for x in s.split('/')]\n t= ''\n for x in d:\n for y in x:\n t+=tb[y]\n t+= ' '\n return t[0:-1]\n class basic:\n def encode(b:bytes = b''):\n \"\"\"Encode Bytes to String\"\"\"\n d = [hex(x)[2:] for x in list(b)]\n for x in range(len(d)):\n if len(d[x]) == 1:\n d[x] = '0'+d[x]\n return ''.join(d)\n def decode(s:str):\n return bytes([int('0x'+s[x]+s[x+1], 0) for x in range(0,len(s),2)])\n class cipher:\n class reverse:\n def crypt(s:str):\n \"\"\"ENCODING AND DECODING FUNCTIONS ARE SAME\"\"\"\n t = ''\n i = len(s)-1\n while i >= 0:\n t+=s[i]\n i-=1\n return t\n class caesar:\n def encrypt(s:str,k:int):\n \"\"\"Encrypts with ceasar cipher\"\"\"\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n t = ''\n for x in s:\n if x in a:\n si = a.find(x)\n ti = si+k\n if ti >= len(a):\n ti-=len(a)\n elif ti < 0:\n ti+=len(a)\n t+=a[ti]\n else:\n t+=x\n return t\n def decrypt(s:str,k:int):\n \"\"\"Decrypts with ceasar cipher\"\"\"\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n t = ''\n for x in s:\n if x in a:\n si = a.find(x)\n ti = si-k\n if ti >= len(a):\n ti-=len(a)\n elif ti < 0:\n ti+=len(a)\n t+=a[ti]\n else:\n t+=x\n return t\n class transposition:\n def encrypt(message:str,key:int):\n # Each string in ciphertext represents a column in the grid:\n ciphertext = [''] * key\n # Loop through each column in ciphertext:\n for column in range(key):\n currentIndex = column\n # Keep looping until currentIndex goes past the message length:\n while currentIndex < len(message):\n # Place the character at currentIndex in message at the\n # end of the current column in the ciphertext list:\n ciphertext[column] += message[currentIndex]\n # Move currentIndex over:\n currentIndex += key\n # Convert the ciphertext list into a single string value and return it:\n return ''.join(ciphertext)\n def decrypt(message:str,key:int):\n numOfColumns = int(math.ceil(len(message) / float(key)))\n numOfRows = key\n numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)\n plaintext = [''] * numOfColumns\n column = row = 0\n for symbol in message:\n plaintext[column] += symbol\n column+=1\n if (column == numOfColumns) or (column == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):\n column = 0\n row+=1\n return ''.join(plaintext)\n class affine:\n def encrypt(message:str,key:int):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n ka,kb=cAffine.getKeyParts(key)\n if cAffine.checkKeys(ka,kb):\n ct = ''\n for x in message:\n if x in a:\n si = a.find(x)\n ct+=a[(si*ka+kb)%len(a)]\n else:\n ct+= x\n return ct\n else:\n return message\n def decrypt(message:str,key:int):\n a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'\n ka,kb=cAffine.getKeyParts(key)\n if cAffine.checkKeys(ka,kb):\n pt = ''\n mioka = cryptomath.findModInverse(ka,len(a))\n for x in message:\n if x in a:\n si = a.find(x)\n pt+=a[(si-kb)*mioka%len(a)]\n else:\n pt+=x\n return pt\n else:\n return message\n class substitution:\n def encrypt(m:str,key:str):\n return cSub.translateMessage(key,m,'e')\n def decrypt(m:str,key:str):\n return cSub.translateMessage(key,m,'d')\n class vigenere:\n def encrypt(m:str,k:str):\n return cVig.translateMessage(k,m,'e')\n def decrypt(m:str,k:str):\n return cVig.translateMessage(k,m,'d')\n class hack:\n def caesar(st:str, s = 0, e = len('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.')):\n for x in range(s,e):\n print(f\"Cipher Caesar Hack; Key = {x} => \"+crypt.cipher.caesar.decrypt(st,x))","sub_path":"denver/crypt.py","file_name":"crypt.py","file_ext":"py","file_size_in_byte":9910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"99556423","text":"import pyrebase\n\nclass FireBaseUpdater():\n firebase = None\n info = None\n db = None\n\n firebase = None;\n def __init__(self, config):\n self.firebase = pyrebase.initialize_app(config)\n self.db = self.firebase.database()\n\n def get_information(self):\n self.info = self.db.child(\"OnGroundRobot\").child(\"Receive\").get().val()\n return self.info\n\n def write_information(self, ControllerLy: float, ControllerRx: float, light_on: bool):\n data = {'ControllerLy_Rx':[ControllerLy, ControllerRx], 'LightOn': light_on}\n self.db.child(\"OnGroundRobot\").child(\"Send\").set(data)\n\ndef main():\n config = {\n \"apiKey\": \"AIzaSyBBFze3rkgjPBwEkno8ZFOuHZLCWhbXstk\",\n \"authDomain\": \"synopsys2020-1.firebaseapp.com\",\n \"databaseURL\": \"https://synopsys2020-1.firebaseio.com/\",\n \"storageBucket\": \"synopsys2020-1.appspot.com\"\n }\n db = FireBaseUpdater(config)\n\n print(db.get_information())\n db.write_information(.2, .2, True)\n\nif __name__ == \"__main__\":\n main()","sub_path":"OnGroundRobot/FireBaseInterfacer.py","file_name":"FireBaseInterfacer.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"12511354","text":"import collections\n\nfrom flask import render_template\nfrom werkzeug.exceptions import abort\nimport datetime\nimport logging\nfrom uuid import UUID\n\nimport Items\nimport Regions\nfrom WebHostLib import app, cache, Room\nfrom Utils import Hint\n\n\ndef get_id(item_name):\n return Items.item_table[item_name][2]\n\n\napp.jinja_env.filters[\"location_name\"] = lambda location: Regions.lookup_id_to_name.get(location, location)\napp.jinja_env.filters['item_name'] = lambda id: Items.lookup_id_to_name.get(id, id)\n\nicons = {\n \"Progressive Sword\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/cc/ALttP_Master_Sword_Sprite.png?version=55869db2a20e157cd3b5c8f556097725\",\n \"Pegasus Boots\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Pegasus_Shoes_Sprite.png?version=405f42f97240c9dcd2b71ffc4bebc7f9\",\n \"Progressive Glove\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/53/ALttP_Titan's_Mitt_Sprite.png?version=6ac54c3016a23b94413784881fcd3c75\",\n \"Flippers\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/88/ALttP_Zora's_Flippers_Sprite.png?version=b9d7521bb3a5a4d986879f70a70bc3da\",\n \"Moon Pearl\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Moon_Pearl_Sprite.png?version=d601542d5abcc3e006ee163254bea77e\",\n \"Progressive Bow\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Bow_%26_Arrows_Sprite.png?version=cfb7648b3714cccc80e2b17b2adf00ed\",\n \"Blue Boomerang\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c3/ALttP_Boomerang_Sprite.png?version=96127d163759395eb510b81a556d500e\",\n \"Red Boomerang\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Magical_Boomerang_Sprite.png?version=47cddce7a07bc3e4c2c10727b491f400\",\n \"Hookshot\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/24/Hookshot.png?version=c90bc8e07a52e8090377bd6ef854c18b\",\n \"Mushroom\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/35/ALttP_Mushroom_Sprite.png?version=1f1acb30d71bd96b60a3491e54bbfe59\",\n \"Magic Powder\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Powder_Sprite.png?version=c24e38effbd4f80496d35830ce8ff4ec\",\n \"Fire Rod\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d6/FireRod.png?version=6eabc9f24d25697e2c4cd43ddc8207c0\",\n \"Ice Rod\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d7/ALttP_Ice_Rod_Sprite.png?version=1f944148223d91cfc6a615c92286c3bc\",\n \"Bombos\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/8c/ALttP_Bombos_Medallion_Sprite.png?version=f4d6aba47fb69375e090178f0fc33b26\",\n \"Ether\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/Ether.png?version=34027651a5565fcc5a83189178ab17b5\",\n \"Quake\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/56/ALttP_Quake_Medallion_Sprite.png?version=efd64d451b1831bd59f7b7d6b61b5879\",\n \"Lamp\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/6/63/ALttP_Lantern_Sprite.png?version=e76eaa1ec509c9a5efb2916698d5a4ce\",\n \"Hammer\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d1/ALttP_Hammer_Sprite.png?version=e0adec227193818dcaedf587eba34500\",\n \"Shovel\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/c/c4/ALttP_Shovel_Sprite.png?version=e73d1ce0115c2c70eaca15b014bd6f05\",\n \"Flute\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/db/Flute.png?version=ec4982b31c56da2c0c010905c5c60390\",\n \"Bug Catching Net\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/5/54/Bug-CatchingNet.png?version=4d40e0ee015b687ff75b333b968d8be6\",\n \"Book of Mudora\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/2/22/ALttP_Book_of_Mudora_Sprite.png?version=11e4632bba54f6b9bf921df06ac93744\",\n \"Bottle\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ef/ALttP_Magic_Bottle_Sprite.png?version=fd98ab04db775270cbe79fce0235777b\",\n \"Cane of Somaria\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e1/ALttP_Cane_of_Somaria_Sprite.png?version=8cc1900dfd887890badffc903bb87943\",\n \"Cane of Byrna\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/bc/ALttP_Cane_of_Byrna_Sprite.png?version=758b607c8cbe2cf1900d42a0b3d0fb54\",\n \"Cape\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1c/ALttP_Magic_Cape_Sprite.png?version=6b77f0d609aab0c751307fc124736832\",\n \"Magic Mirror\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e5/ALttP_Magic_Mirror_Sprite.png?version=e035dbc9cbe2a3bd44aa6d047762b0cc\",\n \"Triforce\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/4/4e/TriforceALttPTitle.png?version=dc398e1293177581c16303e4f9d12a48\",\n \"Small Key\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/f/f1/ALttP_Small_Key_Sprite.png?version=4f35d92842f0de39d969181eea03774e\",\n \"Big Key\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Big_Key_Sprite.png?version=136dfa418ba76c8b4e270f466fc12f4d\",\n \"Chest\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Treasure_Chest_Sprite.png?version=5f530ecd98dcb22251e146e8049c0dda\",\n\n \"Light World\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/e7/ALttP_Soldier_Green_Sprite.png?version=d650d417934cd707a47e496489c268a6\",\n \"Dark World\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/94/ALttP_Moblin_Sprite.png?version=ebf50e33f4657c377d1606bcc0886ddc\",\n \"Hyrule Castle\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/d/d3/ALttP_Ball_and_Chain_Trooper_Sprite.png?version=1768a87c06d29cc8e7ddd80b9fa516be\",\n \"Agahnims Tower\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/1/1e/ALttP_Agahnim_Sprite.png?version=365956e61b0c2191eae4eddbe591dab5\",\n \"Desert Palace\":\n r\"https://www.zeldadungeon.net/wiki/images/2/25/Lanmola-ALTTP-Sprite.png\",\n \"Eastern Palace\":\n r\"https://www.zeldadungeon.net/wiki/images/d/dc/RedArmosKnight.png\",\n \"Tower of Hera\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/3c/ALttP_Moldorm_Sprite.png?version=c588257bdc2543468e008a6b30f262a7\",\n \"Palace of Darkness\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/e/ed/ALttP_Helmasaur_King_Sprite.png?version=ab8a4a1cfd91d4fc43466c56cba30022\",\n \"Swamp Palace\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/7/73/ALttP_Arrghus_Sprite.png?version=b098be3122e53f751b74f4a5ef9184b5\",\n \"Skull Woods\":\n r\"https://alttp-wiki.net/images/6/6a/Mothula.png\",\n \"Thieves Town\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/86/ALttP_Blind_the_Thief_Sprite.png?version=3833021bfcd112be54e7390679047222\",\n \"Ice Palace\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/3/33/ALttP_Kholdstare_Sprite.png?version=e5a1b0e8b2298e550d85f90bf97045c0\",\n \"Misery Mire\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/8/85/ALttP_Vitreous_Sprite.png?version=92b2e9cb0aa63f831760f08041d8d8d8\",\n \"Turtle Rock\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/9/91/ALttP_Trinexx_Sprite.png?version=0cc867d513952aa03edd155597a0c0be\",\n \"Ganons Tower\":\n r\"https://gamepedia.cursecdn.com/zelda_gamepedia_en/b/b9/ALttP_Ganon_Sprite.png?version=956f51f054954dfff53c1a9d4f929c74\"\n}\n\nlinks = {\"Bow\": \"Progressive Bow\",\n \"Silver Arrows\": \"Progressive Bow\",\n \"Silver Bow\": \"Progressive Bow\",\n \"Progressive Bow (Alt)\": \"Progressive Bow\",\n \"Bottle (Red Potion)\": \"Bottle\",\n \"Bottle (Green Potion)\": \"Bottle\",\n \"Bottle (Blue Potion)\": \"Bottle\",\n \"Bottle (Fairy)\": \"Bottle\",\n \"Bottle (Bee)\": \"Bottle\",\n \"Bottle (Good Bee)\": \"Bottle\",\n \"Fighter Sword\": \"Progressive Sword\",\n \"Master Sword\": \"Progressive Sword\",\n \"Tempered Sword\": \"Progressive Sword\",\n \"Golden Sword\": \"Progressive Sword\",\n \"Power Glove\": \"Progressive Glove\",\n \"Titans Mitts\": \"Progressive Glove\"\n }\n\nlevels = {\"Fighter Sword\": 1,\n \"Master Sword\": 2,\n \"Tempered Sword\": 3,\n \"Golden Sword\": 4,\n \"Power Glove\": 1,\n \"Titans Mitts\": 2,\n \"Bow\": 1,\n \"Silver Bow\": 2}\n\nmulti_items = {get_id(name) for name in (\"Progressive Sword\", \"Progressive Bow\", \"Bottle\", \"Progressive Glove\")}\nlinks = {get_id(key): get_id(value) for key, value in links.items()}\nlevels = {get_id(key): value for key, value in levels.items()}\n\ntracking_names = [\"Progressive Sword\", \"Progressive Bow\", \"Book of Mudora\", \"Hammer\",\n \"Hookshot\", \"Magic Mirror\", \"Flute\",\n \"Pegasus Boots\", \"Progressive Glove\", \"Flippers\", \"Moon Pearl\", \"Blue Boomerang\",\n \"Red Boomerang\", \"Bug Catching Net\", \"Cape\", \"Shovel\", \"Lamp\",\n \"Mushroom\", \"Magic Powder\",\n \"Cane of Somaria\", \"Cane of Byrna\", \"Fire Rod\", \"Ice Rod\", \"Bombos\", \"Ether\", \"Quake\",\n \"Bottle\", \"Triforce\"] # TODO make sure this list has what we need and sort it better\n\ndefault_locations = {\n 'Light World': {1572864, 1572865, 60034, 1572867, 1572868, 60037, 1572869, 1572866, 60040, 59788, 60046, 60175,\n 1572880, 60049, 60178, 1572883, 60052, 60181, 1572885, 60055, 60184, 191256, 60058, 60187, 1572884,\n 1572886, 1572887, 1572906, 60202, 60205, 59824, 166320, 1010170, 60208, 60211, 60214, 60217, 59836,\n 60220, 60223, 59839, 1573184, 60226, 975299, 1573188, 1573189, 188229, 60229, 60232, 1573193,\n 1573194, 60235, 1573187, 59845, 59854, 211407, 60238, 59857, 1573185, 1573186, 1572882, 212328,\n 59881, 59761, 59890, 59770, 193020, 212605},\n 'Dark World': {59776, 59779, 975237, 1572870, 60043, 1572881, 60190, 60193, 60196, 60199, 60840, 1573190, 209095,\n 1573192, 1573191, 60241, 60244, 60247, 60250, 59884, 59887, 60019, 60022, 60028, 60031},\n 'Desert Palace': {1573216, 59842, 59851, 59791, 1573201, 59830},\n 'Eastern Palace': {1573200, 59827, 59893, 59767, 59833, 59773},\n 'Hyrule Castle': {60256, 60259, 60169, 60172, 59758, 59764, 60025, 60253},\n 'Agahnims Tower': {60082, 60085},\n 'Tower of Hera': {1573218, 59878, 59821, 1573202, 59896, 59899},\n 'Swamp Palace': {60064, 60067, 60070, 59782, 59785, 60073, 60076, 60079, 1573204, 60061},\n 'Thieves Town': {59905, 59908, 59911, 59914, 59917, 59920, 59923, 1573206},\n 'Skull Woods': {59809, 59902, 59848, 59794, 1573205, 59800, 59803, 59806},\n 'Ice Palace': {59872, 59875, 59812, 59818, 59860, 59797, 1573207, 59869},\n 'Misery Mire': {60001, 60004, 60007, 60010, 60013, 1573208, 59866, 59998},\n 'Turtle Rock': {59938, 59941, 59944, 1573209, 59947, 59950, 59953, 59956, 59926, 59929, 59932, 59935},\n 'Palace of Darkness': {59968, 59971, 59974, 59977, 59980, 59983, 59986, 1573203, 59989, 59959, 59992, 59962, 59995,\n 59965},\n 'Ganons Tower': {60160, 60163, 60166, 60088, 60091, 60094, 60097, 60100, 60103, 60106, 60109, 60112, 60115, 60118,\n 60121, 60124, 60127, 1573217, 60130, 60133, 60136, 60139, 60142, 60145, 60148, 60151, 60157},\n 'Total': set()}\n\nkey_only_locations = {\n 'Light World': set(),\n 'Dark World': set(),\n 'Desert Palace': {0x140031, 0x14002b, 0x140061, 0x140028},\n 'Eastern Palace': {0x14005b, 0x140049},\n 'Hyrule Castle': {0x140037, 0x140034, 0x14000d, 0x14003d},\n 'Agahnims Tower': {0x140061, 0x140052},\n 'Tower of Hera': set(),\n 'Swamp Palace': {0x140019, 0x140016, 0x140013, 0x140010, 0x14000a},\n 'Thieves Town': {0x14005e, 0x14004f},\n 'Skull Woods': {0x14002e, 0x14001c},\n 'Ice Palace': {0x140004, 0x140022, 0x140025, 0x140046},\n 'Misery Mire': {0x140055, 0x14004c, 0x140064},\n 'Turtle Rock': {0x140058, 0x140007},\n 'Palace of Darkness': set(),\n 'Ganons Tower': {0x140040, 0x140043, 0x14003a, 0x14001f},\n 'Total': set()\n}\n\nkey_locations = {\"Desert Palace\", \"Eastern Palace\", \"Hyrule Castle\", \"Agahnims Tower\", \"Tower of Hera\", \"Swamp Palace\",\n \"Thieves Town\", \"Skull Woods\", \"Ice Palace\", \"Misery Mire\", \"Turtle Rock\", \"Palace of Darkness\",\n \"Ganons Tower\"}\n\nbig_key_locations = {\"Desert Palace\", \"Eastern Palace\", \"Tower of Hera\", \"Swamp Palace\", \"Thieves Town\", \"Skull Woods\",\n \"Ice Palace\", \"Misery Mire\", \"Turtle Rock\", \"Palace of Darkness\", \"Ganons Tower\"}\nlocation_to_area = {}\nfor area, locations in default_locations.items():\n for location in locations:\n location_to_area[location] = area\n\nfor area, locations in key_only_locations.items():\n for location in locations:\n location_to_area[location] = area\n\nchecks_in_area = {area: len(checks) for area, checks in default_locations.items()}\nchecks_in_area[\"Total\"] = 216\n\nordered_areas = ('Light World', 'Dark World', 'Hyrule Castle', 'Agahnims Tower', 'Eastern Palace', 'Desert Palace',\n 'Tower of Hera', 'Palace of Darkness', 'Swamp Palace', 'Skull Woods', 'Thieves Town', 'Ice Palace',\n 'Misery Mire', 'Turtle Rock', 'Ganons Tower', \"Total\")\n\ntracking_ids = []\n\nfor item in tracking_names:\n tracking_ids.append(get_id(item))\n\nsmall_key_ids = {}\nbig_key_ids = {}\n\nfor item_name, data in Items.item_table.items():\n if \"Key\" in item_name:\n area = item_name.split(\"(\")[1][:-1]\n if \"Small\" in item_name:\n small_key_ids[area] = data[2]\n else:\n big_key_ids[area] = data[2]\n\nfrom MultiServer import get_item_name_from_id\n\n\ndef attribute_item(inventory, team, recipient, item):\n target_item = links.get(item, item)\n if item in levels: # non-progressive\n inventory[team][recipient][target_item] = max(inventory[team][recipient][target_item], levels[item])\n else:\n inventory[team][recipient][target_item] += 1\n\n\n@app.template_filter()\ndef render_timedelta(delta: datetime.timedelta):\n hours, minutes = divmod(delta.total_seconds() / 60, 60)\n hours = str(int(hours))\n minutes = str(int(minutes)).zfill(2)\n return f\"{hours}:{minutes}\"\n\n\n_multidata_cache = {}\n\ndef get_location_table(checks_table: dict) -> dict:\n loc_to_area = {}\n for area, locations in checks_table.items():\n if area == \"Total\":\n continue\n for location in locations:\n loc_to_area[location] = area\n return loc_to_area\n\ndef get_static_room_data(room: Room):\n result = _multidata_cache.get(room.seed.id, None)\n if result:\n return result\n multidata = room.seed.multidata\n # in > 100 players this can take a bit of time and is the main reason for the cache\n locations = {tuple(k): tuple(v) for k, v in multidata['locations']}\n names = multidata[\"names\"]\n seed_checks_in_area = checks_in_area.copy()\n\n use_door_tracker = False\n if \"tags\" in multidata:\n use_door_tracker = \"DR\" in multidata[\"tags\"]\n if use_door_tracker:\n for area, checks in key_only_locations.items():\n seed_checks_in_area[area] += len(checks)\n seed_checks_in_area[\"Total\"] = 249\n if \"checks_in_area\" not in multidata:\n player_checks_in_area = {playernumber: (seed_checks_in_area if use_door_tracker and\n (0x140031, playernumber) in locations else checks_in_area)\n for playernumber in range(1, len(names[0]) + 1)}\n player_location_to_area = {playernumber: location_to_area\n for playernumber in range(1, len(names[0]) + 1)}\n\n else:\n player_checks_in_area = {playernumber: {areaname: len(multidata[\"checks_in_area\"][f'{playernumber}'][areaname])\n if areaname != \"Total\" else multidata[\"checks_in_area\"][f'{playernumber}'][\"Total\"]\n for areaname in ordered_areas}\n for playernumber in range(1, len(names[0]) + 1)}\n player_location_to_area = {playernumber: get_location_table(multidata[\"checks_in_area\"][f'{playernumber}'])\n for playernumber in range(1, len(names[0]) + 1)}\n result = locations, names, use_door_tracker, player_checks_in_area, player_location_to_area\n _multidata_cache[room.seed.id] = result\n return result\n\n\n@app.route('/tracker/')\n@cache.memoize(timeout=30) # update every 30 seconds\ndef getTracker(tracker: UUID):\n room = Room.get(tracker=tracker)\n if not room:\n abort(404)\n locations, names, use_door_tracker, seed_checks_in_area, player_location_to_area = get_static_room_data(room)\n\n inventory = {teamnumber: {playernumber: collections.Counter() for playernumber in range(1, len(team) + 1)}\n for teamnumber, team in enumerate(names)}\n\n checks_done = {teamnumber: {playernumber: {loc_name: 0 for loc_name in default_locations}\n for playernumber in range(1, len(team) + 1)}\n for teamnumber, team in enumerate(names)}\n precollected_items = room.seed.multidata.get(\"precollected_items\", None)\n hints = {team: set() for team in range(len(names))}\n if \"hints\" in room.multisave:\n for key, hintdata in room.multisave[\"hints\"]:\n for hint in hintdata:\n hints[key[0]].add(Hint(*hint))\n\n for (team, player), locations_checked in room.multisave.get(\"location_checks\", {}):\n if precollected_items:\n precollected = precollected_items[player - 1]\n for item_id in precollected:\n attribute_item(inventory, team, player, item_id)\n for location in locations_checked:\n if (location, player) not in locations or location not in player_location_to_area[player]:\n continue\n\n item, recipient = locations[location, player]\n attribute_item(inventory, team, recipient, item)\n checks_done[team][player][player_location_to_area[player][location]] += 1\n checks_done[team][player][\"Total\"] += 1\n\n for (team, player), game_state in room.multisave.get(\"client_game_state\", []):\n if game_state:\n inventory[team][player][106] = 1 # Triforce\n\n activity_timers = {}\n now = datetime.datetime.utcnow()\n for (team, player), timestamp in room.multisave.get(\"client_activity_timers\", []):\n activity_timers[team, player] = now - datetime.datetime.utcfromtimestamp(timestamp)\n\n player_names = {}\n for team, names in enumerate(names):\n for player, name in enumerate(names, 1):\n player_names[(team, player)] = name\n long_player_names = player_names.copy()\n for (team, player), alias in room.multisave.get(\"name_aliases\", []):\n player_names[(team, player)] = alias\n long_player_names[(team, player)] = f\"{alias} ({long_player_names[(team, player)]})\"\n\n video = {}\n for (team, player), data in room.multisave.get(\"video\", []):\n video[(team, player)] = data\n\n return render_template(\"tracker.html\", inventory=inventory, get_item_name_from_id=get_item_name_from_id,\n lookup_id_to_name=Items.lookup_id_to_name, player_names=player_names,\n tracking_names=tracking_names, tracking_ids=tracking_ids, room=room, icons=icons,\n multi_items=multi_items, checks_done=checks_done, ordered_areas=ordered_areas,\n checks_in_area=seed_checks_in_area, activity_timers=activity_timers,\n key_locations=key_locations, small_key_ids=small_key_ids, big_key_ids=big_key_ids,\n video=video, big_key_locations=key_locations if use_door_tracker else big_key_locations,\n hints=hints, long_player_names = long_player_names)\n","sub_path":"WebHostLib/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":19910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"430387076","text":"\"\"\"\"Week 5 exercises regarding knapsack problem\"\"\"\n\nimport datetime\n\ndef knapsack(items, max_weight):\n \"\"\"\n Classical DP solution to knapsack problem\n items -- an iterable containing tuples (weight, value)\n max_weight -- integer indicating the max weight the knapsack can hold\n \"\"\"\n solutions = [0 for x in range(max_weight+1)]\n for i in range(0, max_weight + 1):\n for (weight, value) in items:\n if weight <= i:\n solutions[i] = max(solutions[i], solutions[i - weight] + value)\n\n return solutions\n\ndef get_solution(solutions, weight):\n \"\"\"\"Gets the solution from the given map\"\"\"\n if weight in solutions:\n return solutions[weight]\n return 0\n\ndef knapsack_map(items, max_weight):\n \"\"\"Same as the traditional DP solution but uses a map instead of an array\"\"\"\n solutions = {}\n for i in range(0, max_weight + 1):\n for (weight, value) in items:\n if weight <= i:\n solutions[i] = max(\n get_solution(solutions, weight),\n get_solution(solutions, i - weight) + value\n )\n return solutions\n\n# (weight, value)\nitems_arr = ((1, 10), (3, 40), (4, 50), (5, 70))\n\nprint(knapsack(items_arr, 8))\n\n","sub_path":"week5/unbounded_knapsack.py","file_name":"unbounded_knapsack.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"157386876","text":"# imports\n# end imports\n\n\nclass Constants:\n def __init__(self):\n self.DATA_IDX = 0\n self.LABEL_IDX = 1\n\n self.NO_MORE_SAMPLES = -1\n self.LEAF_CREATED_SUCCESSFULLY = 1\n\n self.TP_IDX = 0\n self.FP_IDX = 1\n self.TN_IDX = 2\n self.FN_IDX = 3","sub_path":"HW4/code/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"451666828","text":"#================================================================\n#Importing Libraries\nimport turtle \nimport random\n\n#head orientation\nh = [0]\n\n#score\na = [0]\nb = [0]\n\n#food coord\nfcoord = [0,0,0]\n\n#position\npos = []\n\n#===================================================================\n#homimg function\n\ndef home(x=0,y=0):\n a[0] = 0\n b[0] = 0\n h[0] = 0\n fcoord[2] = 0\n pos[:] = []\n turtle.hideturtle()\n turtle.clear()\n turtle.pu()\n turtle.color(\"black\")\n turtle.goto(0,0)\n turtle.write(\"Press Enter to Play\",align=\"center\",font=(50))\n turtle.title(\"SNAKE\")\n \n\n turtle.onkey(start, 'Return')\n \n turtle.listen()\n \n turtle.mainloop()\n\n #====================================================================\n#Define to Playable Area\n \ndef boundary_area():\n turtle.clear()\n turtle.pu()\n turtle.speed(0)\n turtle.pensize(20)\n turtle.color(\"grey\")\n turtle.goto(-300,300)\n turtle.pd()\n turtle.goto(300,300)\n turtle.goto(300,-300)\n turtle.goto(-300,-300)\n turtle.goto(-300,300)\n turtle.pu()\n turtle.goto(+100,0)\n\n#===================================================================\n#Controller Function\n \ndef start(x=0,y=0): \n\n boundary_area()\n\n tfood = turtle.Turtle()\n tfood.hideturtle()\n tfood.pu()\n tfood.speed(0)\n tfood.shape(\"square\")\n tfood.color(\"red\")\n\n tscore = turtle.Turtle()\n tscore.hideturtle()\n tscore.pu()\n tscore.speed(0)\n tscore.goto(250,-290)\n tscore.write(\"Score:\" + str(a[0]), align=\"center\",font=(10))\n \n while x > -290 and x < 290 and y > -290 and y <290:\n if fcoord[2] == 0:\n food(tfood)\n fcoord[2] = 1\n turtle.onkey(u,\"Up\")\n turtle.onkey(l,\"Left\")\n turtle.onkey(r,\"Right\")\n turtle.onkey(d,\"Down\")\n turtle.listen()\n move()\n x = turtle.xcor()\n y = turtle.ycor() \n if x > fcoord[0]*20-5 and x < fcoord[0]*20+5 and y > fcoord[1]*20-5 and y < fcoord[1]*20+5:\n fcoord[2] = 0\n tfood.clear()\n a[0] += 1\n tscore.clear()\n tscore.write(\"Score:\" + str(a[0]), align=\"center\",font=(10))\n \n if len(pos) > 1:\n for i in range(1,len(pos)):\n if x < pos[i][0]+5 and x > pos[i][0]-5 and y < pos[i][1]+5 and y > pos[i][1]-5:\n tscore.clear()\n tfood.clear()\n gameover()\n tscore.clear()\n tfood.clear()\n gameover()\n\n#===================================================================\n#Food\n \ndef food(tfood):\n x = random.randrange(-8,8,1)\n y = random.randrange(-8,8,1)\n fcoord[0] = x\n fcoord[1] = y\n tfood.hideturtle()\n tfood.pu()\n tfood.shape(\"square\")\n tfood.color(\"red\")\n tfood.goto(x*20,y*20)\n tfood.stamp()\n\n\n#===================================================================\n#Change Directions\n \ndef u():\n if h[0] == 270:\n pass\n else:\n h[0] = 90\n\ndef d():\n if h[0] == 90:\n pass\n else:\n h[0] = 270\n\ndef l():\n if h[0] == 0:\n pass\n else:\n h[0] = 180\n\ndef r():\n if h[0] == 180:\n pass\n else:\n h[0] = 0\n\n\n#===================================================================\n#movement of snake\n \ndef move():\n turtle.pensize(1)\n turtle.color(\"black\")\n turtle.pu()\n turtle.speed(5)\n turtle.setheading(h[0])\n turtle.shape(\"square\")\n turtle.stamp()\n turtle.fd(20)\n x = turtle.xcor()\n y = turtle.ycor()\n if b[0] > a[0]: \n turtle.clearstamps(1)\n pos.insert(0,[round(x),round(y)])\n pos.pop(-1)\n else:\n pos.insert(0,[round(x),round(y)]) \n b[0] += 1 \n\n\n\n#====================================================================\n#Game ending\n \ndef gameover():\n \n turtle.speed(0)\n turtle.pu()\n turtle.goto(0,150)\n turtle.color(\"red\")\n turtle.write(\"GAME OVER\",align=\"center\", font=(100))\n turtle.goto(0,50)\n turtle.write(\"Score:\" + str(a[0]),align=\"center\",font=(70))\n turtle.goto(0,-150)\n turtle.write(\"(Press 'ENTER' to Play Again)\",align=\"center\",font=(30))\n \n turtle.onkey(home, 'Return')\n \n turtle.listen()\n \n turtle.mainloop()\n\n#===================================================================\n#Main Function\n# Game Start\n\nhome()\n","sub_path":"snake v2.py","file_name":"snake v2.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"368898777","text":"def knapsack(items, weight):\n results = {i: {} for i in range(len(items) + 1)}\n calculated_results = {i: {} for i in range(len(items) + 1)}\n\n def knapsack_rec(n, w):\n if n == 0 or w == 0:\n return 0\n\n if w in calculated_results[n]:\n return calculated_results[n][w]\n\n it = items[n - 1]\n\n if it[1] > w:\n a = knapsack_rec(n - 1, w)\n calculated_results[n][w] = a\n return a\n\n else:\n a = it[0] + knapsack_rec(n - 1, w - it[1])\n b = knapsack_rec(n - 1, w)\n\n if a > b:\n results[n][w] = a\n calculated_results[n][w] = a\n return a\n\n else:\n calculated_results[n][w] = b\n return b\n\n total_value = knapsack_rec(len(items), weight)\n\n result_items = []\n w = weight\n\n for i in range(len(items), 0, -1):\n if w in results[i]:\n result_items.append(i - 1)\n w -= items[i-1][1]\n\n return total_value, result_items\n\n\nif __name__ == \"__main__\":\n it = [[7, 5], [8, 4], [9, 3], [10, 2], [1, 10], [3, 15], [8, 10], [6, 4], [5, 3], [7, 3]] # [9, 8, 3, 2, 1, 0]\n w = 20\n k = knapsack(it, w)\n res = k[1]\n s = 0\n print(k)\n for el in res:\n s += it[el][1]\n print(k, s)\n","sub_path":"optimized_knapsack.py","file_name":"optimized_knapsack.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"163847613","text":"\"\"\"\nAuthor: \nDate: \nClass:\nSection Leader: \n\nDescription:\nThis program uses turtle graphics to draw some polygons.\n\"\"\"\n\nimport turtle\n\ndef polygon(a_turtle, side_number, side_length):\n \"\"\"Draw a regular polygon of the given number of sides and given size with the given turtle.\"\"\"\n for i in range(side_number):\n a_turtle.forward(side_length)\n a_turtle.left(360/side_number)\n return None\n\ndef main():\n num = int(input(\"Enter the number of polygons you'd like to see: \"))\n for i in range(num):\n side_number = int(input(\"Enter the number of sides: \"))\n color = input(\"Enter the color: \")\n side_length = int(input(\"Enter the side length for your polygon: \"))\n a_turtle = turtle.Turtle()\n a_turtle.pencolor(color)\n a_turtle.speed(0)\n a_turtle.pensize(5)\n polygon(a_turtle, side_number, side_length)\n\n input('Press enter to end.') # keeps the turtle graphics window open\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n","sub_path":"HW_3/shapechooser.py","file_name":"shapechooser.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"117611704","text":"#! /usr/bin/env python\n\n\"\"\"\n A test program completely separate from main chronostar for astr3005,\n in order to test out the performance of swig and suitability of\n the code to find overlap in a simple test.\n\"\"\"\n\nimport sys\nsys.path.insert(0,'..')\nimport time\nimport argparse\n\nif sys.version[0] == '2':\n timer = time.clock\nelif sys.version[0] == '3':\n timer = time.perf_counter\n\nimport numpy as np\nimport chronostar._overlap as overlap\nfrom chronostar.component import SphereComponent\nfrom chronostar.traceorbit import trace_cartesian_orbit, trace_epicyclic_orbit\n\ndef timings(comp, noverlaps=10000):\n \"\"\"\n Executes each function a fixed number of times, timing for how\n long it takes.\n \"\"\"\n comp.trace_orbit_func = trace_cartesian_orbit\n\n galpystart = timer()\n for i in range(noverlaps):\n comp.get_currentday_projection()\n comp.update_attribute({'age':comp.get_age()+1.e-10})\n\n galpy_time = timer() - galpystart\n print(\"GALPY\")\n print(\"Time: %.5f s\"%galpy_time)\n print(\"Time per projection: %.5f micros\"%(galpy_time/nprojections * 1e6))\n\n comp.trace_orbit_func = trace_epicyclic_orbit\n epicycstart = timer()\n for i in range(noverlaps):\n comp.get_currentday_projection()\n comp.update_attribute({'age':comp.get_age()+1.e-10})\n epicyctime = timer() - epicycstart\n print(\"EPICYCLIC\")\n print(\"Time: \" + str(epicyctime))\n print(\"Time per projection: %.3f micros\"%(epicyctime/nprojections * 1e6))\n\n\n# ------------- MAIN PROGRAM -----------------------\nif __name__ == '__main__':\n\n print(\"___ Testing swig module ___\")\n #Parsing arguments\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-o', '--over', dest='o', default=10000,\n help='number of overlaps, def: 10000')\n # parser.add_argument('-b', '--batch', dest='b', default=10000,\n # help='batch size, must be <= and factor of noverlaps, def: 10000')\n args = parser.parse_args()\n\n nprojections = int(args.o)\n\n pars = np.hstack((np.zeros(6),[10.,5,100]))\n my_comp = SphereComponent(pars)\n\n print(\"Testing timings\")\n print(\"# of projections: {}\".format(nprojections))\n timings(my_comp, nprojections)\n\n\n","sub_path":"benchmarks/bm_orbital_methods.py","file_name":"bm_orbital_methods.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"447613394","text":"import vasp\nimport json\nimport time\na_users = {'jake':\n {'name':'Jake Tarnow',\n 'address':'42 Significance Pl, San Jose CA 95050',\n 'account':'J1111111111'},\n 'alice':\n {\"name\":\"Alice Lastnamersson\",\n \"address\":\"1234 Road Rd, City XY 01234\",\n \"account\":\"A0123456789\"},\n 'bob':\n {\"name\":\"Bob McSurname\",\n \"address\":\"4321 Shellcorp Ave, Town YZ 54321\",\n \"account\":\"B9876543210\"},\n}\n\nb_users = {'jake':\n {'name':'Jake Tarnow',\n 'address':'42 Significance Pl, San Jose CA 95050',\n 'account':'J1111111111'},\n 'alice':\n {\"name\":\"lice Lastnamersson\",\n \"address\":\"234 Road Rd, City XY 01234\",\n \"account\":\"0123456789\"},\n 'bob':\n {\"name\":\"ob McSurname\",\n \"address\":\"321 Shellcorp Ave, Town YZ 54321\",\n \"account\":\"9876543210\"},\n}\n\nprint(\"Example VASP PII Exchange between alice(sender) and bob(receiver)\")\ninput()\nprint(\"Initializing VASP A as sending VASP\")\nsender = vasp.VASPServer(\"A\", users=a_users)\nprint(\"Initializing VASP B as receiving VASP\")\nreceiver = vasp.VASPServer(\"B\", users=b_users)\n\ninput()\n\nprint(\"VASP A bit committing alice's PII on VASP B\")\nrec_result = json.loads(receiver.bit_commit(\"alice\", rcv=True))\nrec_hash = rec_result['hash']\nprint(\"Received hash of alice's PII from VASP B \" + rec_hash)\n\nprint(\"Saving VASP B's hash of alice's PII on VASP A\")\nsender.save_hash(\"alice\", rec_hash)\ninput()\n\nprint(\"VASP B bit committing bob's PII on VASP A\")\nsend_result = json.loads(sender.bit_commit(\"bob\"))\nsend_hash = send_result['hash']\nprint(\"Received hash of bob's PII from VASP A \" + send_hash)\n\nprint(\"Saving VASP A's hash of alice's PII on VASP B\")\nreceiver.save_hash(\"bob\", send_hash)\ninput()\n\nprint(\"Now that hashes have been exchanged, salts can be exchanged\")\nrec_salt = json.loads(receiver.reveal_salt(\"alice\"))\nsend_salt = json.loads(sender.reveal_salt(\"bob\"))\ninput()\n\nprint(\"Confirmation by VASP A of bob's PII\")\nsend_confirm = sender.confirm(\"bob\", send_salt['salt'])\nprint(send_confirm)\nprint(\"Confirmation by VASP B of alice's PII\")\nrec_confirm = receiver.confirm(\"alice\", rec_salt['salt'])\nprint(rec_confirm)\n","sub_path":"neg_demo.py","file_name":"neg_demo.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"321521379","text":"from src.Stack import Stack2\n\n\ndef calc(x, y, op):\n \"\"\"\n Returns the basic calculation result\n on x and y for the given operator.\n\n Complexity: O(1)\n \"\"\"\n if op == \"+\":\n return y + x\n elif op == \"-\":\n return y - x\n elif op == \"*\":\n return y * x\n elif op == \"/\":\n return y / x\n\n\ndef evaluate(expression):\n \"\"\"\n Evaluates the given math expression.\n\n Complexity: O(n), where n is the number of characters\n \"\"\"\n operands = Stack2.Stack()\n operators = Stack2.Stack()\n\n for i in expression:\n if i == \"(\" or i == \" \":\n pass\n elif i == \")\":\n op_to_use = operators.pop()\n x, y = operands.pop(), operands.pop()\n operands.push(calc(x, y, op_to_use))\n else:\n if i == \"+\" or i == \"-\" or i == \"*\" or i == \"/\":\n operators.push(i)\n elif float(i):\n operands.push(float(i))\n if operands.num_items > 1:\n op_to_use = operators.pop()\n x, y = operands.pop(), operands.pop()\n operands.push(calc(x, y, op_to_use))\n return operands.pop()","sub_path":"src/Stack/Dijkstra_2_Stack_Calculator.py","file_name":"Dijkstra_2_Stack_Calculator.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"571428301","text":"# coding: UTF-8\n\nimport csv\nimport numpy as np \nimport math\nimport statistics\nimport copy\n\n'''\n csvファイルへの書き込み\n'''\ndef write_csv(data, filename):\n header = []\n \n for dimention in range(1, len(data[0])):\n header.append('次元%i' % (dimention))\n header.append('平均')\n \n with open(filename + '.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(header)\n for row in data:\n writer.writerow(row)\n\n'''\n +1か-1をそれぞれ1/2の確率で出力する\n'''\ndef noise():\n return 1 if np.random.rand() >= 0.5 else -1\n\n'''\n ランダムベクトルの生成\n 要素は全て[-1, 1]の範囲\n'''\ndef make_random_vector(num_dimentions):\n random_vector = []\n for dimention in range(num_dimentions):\n random_vector.append(np.random.rand() * noise())\n\n return random_vector\n\n'''\n ランダム行列の生成\n 要素は全て[-1, 1]の範囲\n'''\ndef make_random_matrix(num_elements, num_dimentions):\n random_matrix = []\n for element in range(num_elements):\n random_matrix.append(make_random_vector(num_dimentions))\n return random_matrix\n\n'''\n ユークリッド距離\n'''\ndef euclid_distance(vector1, vector2):\n distance = 0\n for index in range(len(vector1)):\n distance += (vector1[index] - vector2[index]) * (vector1[index] - vector2[index])\n \n return math.sqrt(distance)\n\n'''\n 各要素と他の要素との距離の行列を返す\n'''\ndef get_distance_matrix(data):\n distance_matrix = []\n\n for vector1 in data:\n distance_vector = []\n for vector2 in data:\n distance_vector.append(euclid_distance(vector1, vector2))\n distance_matrix.append(distance_vector)\n\n return distance_matrix\n\n'''\n 各ベクトルのユークリッド距離を取って各ベクトルと他のベクトルとの距離の平均を出し\n 最小のもののインデックスを返す。\n 各ベクトルの平均と全体の平均と分散も出す。\n'''\ndef each_distance(distance_matrix):\n all_vecotors_mean = []\n for vector in distance_matrix:\n all_vecotors_mean.append(sum(vector) / len(vector))\n \n minimum = all_vecotors_mean[0]\n index = 0\n for current_index in range(1, len(distance_matrix)):\n if minimum > all_vecotors_mean[current_index]:\n minimum = all_vecotors_mean[current_index]\n index = current_index\n\n all_means = statistics.mean(all_vecotors_mean)\n # all_variance = statistics.variance(all_vecotors_mean)\n all_vecotors_mean.append(all_means)\n # all_vecotors_mean.append(all_variance)\n\n return index, all_vecotors_mean\n\n'''\n 指定したindexの要素を入れ替える\n'''\ndef replace_element(matrix, index, new_vector):\n matrix[index] = new_vector\n return matrix\n\n'''\n 指定したindexの要素と他の要素とのユークリッド距離を更新する\n'''\ndef update_distance(data, distance_matrix, index):\n new_distances_matrix = copy.deepcopy(distance_matrix)\n # 横成分の更新\n for vector in range(len(data)):\n distance = euclid_distance(data[index], data[vector])\n new_distances_matrix[index][vector] = distance\n\n # 縦成分の更新\n for vector in range(len(data)):\n new_distances_matrix[vector][index] = euclid_distance(data[vector], data[index])\n \n return new_distances_matrix\n\n'''\n ユークリッド距離の履歴のcsvファイル用のヘッダーを返す\n'''\ndef header(num_elements):\n header = []\n header.append('試行回数')\n for element in range(num_elements):\n header.append('要素%i' % (element))\n \n header.append('全体の平均')\n header.append('全体の分散')\n return header\n\n'''\n それぞれの要素にランダムになるようにリストの末尾に順位をつける\n'''\ndef add_ranking(random_matrix):\n rank = []\n for index in range(len(random_matrix)):\n rank.append(index + 1)\n \n for swap in range(len(random_matrix)):\n element_index1 = np.random.randint(0, len(random_matrix) - 1)\n element_index2 = np.random.randint(0, len(random_matrix) - 1)\n rank[element_index1], rank[element_index2] = rank[element_index2], rank[element_index1]\n\n for index in range(len(random_matrix)):\n random_matrix[index].append(rank[index])\n\n return random_matrix\n\n'''\n Main\n'''\n# 個体数\nnum_elements = 100\n# 次元数\nnum_dimentions = 100\n# ユークリッド距離の小さい要素を連続で入れ替えなかった回数\nnum_noreplace = 0\n\n\n\n# ユークリッド距離の履歴\neuclid_history = []\n\n# [-1, 1]の範囲でランダム行列を作成\nrandom_matrix = make_random_matrix(num_elements, num_dimentions)\n \n# ユークリッド距離の行列\neuclid_matrix = get_distance_matrix(random_matrix)\n\nindex, distances = each_distance(euclid_matrix)\nfor num in range(1, 2):\n while num_noreplace < 1000:\n print(num_noreplace)\n temp = euclid_matrix\n # ユークリッド距離の平均のリストと最も小さい距離のインデックスの取得\n index, distances = each_distance(euclid_matrix)\n # ユークリッド距離に関するリストの更新\n euclid_history.append(distances)\n # 差し替え候補のベクトルを作成\n new_vector = make_random_vector(num_dimentions)\n # 仮に差し替えた後の個体群行列の作成\n temp_matrix = replace_element(random_matrix, index, new_vector)\n # 仮に差し替えた行列のユークリッド距離の行列を取得\n temp_euclid_matrix = update_distance(temp_matrix, euclid_matrix, index)\n # 仮に差し替えた行列のユークリッド距離の平均のリストと最も小さい距離のインデックスの取得\n new_index, new_distances = each_distance(temp_euclid_matrix)\n\n # 差し替えた方が距離が大きい場合は個体群行列を差し替えて更新し、num_noreplaceをリセットする\n if distances[100] < new_distances[100]:\n random_matrix = temp_matrix\n num_noreplace = 0\n # ユークリッド距離行列を更新する\n euclid_matrix = temp_euclid_matrix\n # 差し替えない方が良い場合、個体群行列を更新せずnum_noreplaceを+1する\n else:\n num_noreplace += 1\n '''\n # 重み付け(解空間用)\n for row in random_matrix:\n row.append(np.random.rand() * 20)\n '''\n\n # それぞれの個体にランダムでランキングを割り振る\n # add_ranking(random_matrix)\n\n # 書き込むファイル\n filename = 'csv_files/mock_initial_individuals'\n\n # 結果をcsvに書き込む\n write_csv(random_matrix, filename)\n\n # ユークリッド距離の履歴をcsvファイルに書き込む\n write_csv(euclid_history, 'csv_files/euclid_history')\n","sub_path":"pre_experiment/search_alpha/random_matrix.py","file_name":"random_matrix.py","file_ext":"py","file_size_in_byte":6943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"598854758","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 31 12:43:07 2019\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport math\r\nfrom datetime import datetime\r\nfrom sklearn import preprocessing\r\n\r\n#1.变量预处理\r\n#将描述变量存储到cont_vars 这个list中去\r\n\r\nclass feature_preprocessing(object):\r\n def __init__(self,data,y):\r\n self.n_df=data.shape[0]\r\n self.n1_df=data[y].sum()\r\n self.n0_df=self.n_df-self.n1_df\r\n print(\"共有{row}行{col}列数据,{n1}个坏客户,{n0}个好客户\".format(\r\n row=data.shpae[0],\r\n col=data.shape[1],\r\n n1=self.n1_df,\r\n n0=self.n0_df\r\n ))\r\n self.cols=data.columns.to_list()\r\n self.cols.remove(y)\r\n del self.cols[0]\r\n self.num_vars_valid=[]\r\n self.char_vars_valid=[]\r\n self.num_vars_novalid=[]\r\n self.char_vars_novalid=[]\r\n self.null_count=[]\r\n self.sim_count=[]\r\n print(\"\\n单一变量和缺失值分析:\")\r\n for col in self.cols:\r\n if data[col].dtype!=\"object\":\r\n missing=self.n_df-np.count_nonzero(data[col].isnull().values)\r\n mis_perc=100-float(missing)/self.n_df*100\r\n self.null_count.append([col,mis_perc])\r\n value_cnt=data[col].value_counts()\r\n sim_perc=float(max(value_cnt,default=100))/self.n_df*100\r\n self.sim_count.append([col,sim_perc])\r\n if mis_perc<99 and sim_perc<99:self.num_vars_valid.append(col)\r\n else:\r\n print(\"{col}的缺失值比例是{miss}%,单一值比例是{simple}%\".format(col=col,miss=mis_perc,simple=sim_perc))\r\n self.num_vars_novalid.append(col)\r\n \r\n print (\"\\n连续有效变量有\\n:\")\r\n print(len(self.num_vars_valid))\r\n print(self.num_vars_valid)\r\n print (\"\\n连续无效变量有\\n:\")\r\n print(len(self.num_vars_novalid))\r\n print(self.num_vars_novalid)\r\n for col in self.cols:\r\n if data[col].dtype==\"object\":\r\n missing=self.n_df-np.count_nonzero(data[col].isnull().values)\r\n mis_perc=100-float(missing)/self.n_df*100\r\n self.null_count.append([col,mis_perc])\r\n value_cnt=data[col].value_counts()\r\n sim_perc=float(max(value_cnt,default=100))/self.n_df*100\r\n self.sim_count.append([col,sim_perc]) \r\n if mis_perc<99 and sim_perc<99:self.char_vars_valid.append(col)\r\n else:\r\n print(\"{col}的缺失值比例是{miss}%,单一值比例是{simple}%\".format(col=col,miss=mis_perc,simple=sim_perc))\r\n self.char_vars_novalid.append(col)\r\n print (\"\\n分类有效变量有\\n:\")\r\n print(len(self.char_vars_valid))\r\n print(self.char_vars_valid)\r\n print (\"\\n分类无效变量有\\n:\")\r\n print(len(self.char_vars_novalid))\r\n print(self.char_vars_novalid)\r\n print(self.null_count)\r\n print(self.sim_count)\r\n data.drop(self.num_vars_novalid,axis=1,inplace=True)\r\n data.drop(self.char_vars_novalid,axis=1,inplace=True)\r\n #获取有效的数值变量和文本变量\r\n def get_vars(self):\r\n return self.num_vars_valid,self.char_vars_valid\r\n","sub_path":"auto/cont_feature_discretization.py","file_name":"cont_feature_discretization.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"116512926","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 3. \nThe prime factors of 13195 are 5, 7, 13 and 29.\nWhat is the largest prime factor of the number 600851475143 ?\"\"\"\n\nimport math\nall_prime = [2, 3, 5 ]\n\ndef isPrime( num ):\n\tmax_try = math.sqrt( num ) + 1\n\tfor prime in ( v for v in all_prime if v < max_try ):\n\t\tif num % prime == 0:\n\t\t\treturn False\n\treturn True\n\ndef genPrime( num ):\n\tfor i in xrange( all_prime[-1], int(math.sqrt(num)) + 1 ):\n\t\tif i is all_prime[-1]:\n\t\t\tcontinue\n\n\t\tif isPrime( i ):\n\t\t\tall_prime.append( i )\n\ndef getForceLargestPrimeFactor( num ):\n\tgenPrime( num )\n\n\tfor i in xrange( len(all_prime) - 1, -1, -1):\n\t\tprime = all_prime[i]\n\t\tif num % prime == 0:\n\t\t\treturn prime\n\n\n#print getForceLargestPrimeFactor( 600851475143 )\n\n\ndef getFermatFactor( num ):\n\ta = math.ceil( math.sqrt( num ) )\n\tb = math.sqrt( a * a - num )\n\n\twhile b - int( b ) > 0.000000001:\n\t\ta += 1\n\t\tb = math.sqrt( a * a - num )\n\n\treturn a + b, a - b\n\n\n#print getFermatFactor( 13195 )\n\ndef getMaxPrime( num ):\n\td = 2\n\n\twhile num != d:\n\t\twhile num % d == 0:\n\t\t\tnum /= d\n\n\t\td += 1\n\treturn num\n\nDEFAULT_ARG = 600851475143\n\ndef solve( num ):\n return getMaxPrime( num )\n","sub_path":"solutions/p3.py","file_name":"p3.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"102670564","text":"import json\n\ndef detect(det):\n\n buffer = det['buffers']\n response = []\n expected_sections=['.text','.data','.rsrc']\n section_name=''\n\n for file in buffer:\n entryPoint=file['oh']['ep']\n sectionCount=1\n NumberOfSections=file['fh']['ns']\n md5=file['md5']\n print(NumberOfSections)\n for sec in file['sec']:\n virtualAdress=sec['va']\n sizeOfRawData=sec['s']\n\n if(entryPoint< virtualAdress+sizeOfRawData):\n section_name=sec['n']\n break\n else:\n sectionCount=sectionCount+1\n\n if sectionCount==int(NumberOfSections, 16) and section_name not in expected_sections:\n status='malware'\n else:\n\n status='clean'\n\n item = {'md5': md5, 'status': status}\n response.append(item)\n\n return response\n\n\n","sub_path":"server/workers/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"91235914","text":"\nimport sys\nsys.path.append(\"../\")\n\nimport pyskynet\nimport pyskynet.cluster as cluster\nimport pyskynet.foreign as foreign\nimport numpy as np\nimport time\n\n@foreign.dispatch(\"dosth\")\ndef dosth(a):\n print(a)\n return a\n\npyskynet.start()\n\n\ncluster.open(8080)\n\n\n\na1 = np.arange(100)\nt1 = time.time()\na2, = cluster.call(\"127.0.0.1:8080\", \".python\", \"dosth\", a1)\nt2 = time.time()\nprint(t2-t1)\n\nt1 = time.time()\na2, = cluster.call(\"127.0.0.1:8080\", \".python\", \"dosth\", a1)\nt2 = time.time()\nprint(t2-t1)\n\npyskynet.join()\n","sub_path":"test/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"255647464","text":"import pandas\nimport Quandl\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\nimport numpy\n\nnow = datetime.now()\ndef last_n_rows(n, df, start=\"\"):\n\t\"\"\"Returns the last n rows of a Pandas dataframe object.\n\n\tKeyword arguments:\n\tn \t\t-- the number of rows to be returned. If n is greater than the total number of rows in the datafrma, then the method will return the entire dataframe\n\tstart \t-- the start date of the rows to be returned. Defaults to current date\n\t\"\"\"\n\n\tif start == \"\":\n\t\tstart = now\n\tstart = date_to_string(start)\n\tstart_index = df.index.searchsorted(start)\n\tsliced_df = df.iloc[-n:start_index, :]\n\treturn sliced_df\ndef last_n_periods(dataframe, n, period_type, start_date=\"\"):\n\t\"\"\"Returns a dataframe whose index is n periods in the past from the start date\n\n\tKeyword arguments:\n\tdataframe -- the dataframe to be sliced\n\tn -- the number of periods to go back\n\tstart_date -- the start date of the dataframe. Defaults to current date\n\tperiod_type -- valid choices are \"years\", \"days\", \"monhts\", and \"weeks\"\n\t\"\"\"\n\tif start_date == \"\":\n\t\tstart_date = now\n\tend_date = last_n_date(n, start_date , period_type)\n\tdataframe = dataframe[date_to_string(end_date):start_date]\n\treturn dataframe\ndef last_n_date(n, period_type, start_date=\"\"):\n\t\"\"\"Returns a datetime that is n periods from the start date\n\n\tKeyword arguments:\n\tn -- the number of periods to go back\n\tperiod_type -- valid choices are \"years\", \"days\", \"months\", and \"weeks\"\n\tstart_date -- the start date of the dataframe. Defaults to current date\n\t\"\"\"\n\tif start_date == \"\":\n\t\tstart_date = now\n\t\t\n\tstart_date = string_to_date(start_date)\n\tif period_type == \"years\":\n\t\tend_date = start_date - relativedelta(years=n)\n\tif period_type == \"days\":\n\t\tend_date = start_date - relativedelta(days=n)\n\tif period_type == \"months\":\n\t\tend_date = start_date - relativedelta(months=n)\n\tif period_type == \"weeks\":\n\t\tend_date == start_date - relativedelta(days=7)\n\treturn end_date\n\ndef rows_between(df, start_date, end_date):\n\t\"\"\"Returns a dataframe whose index is between (and inclusive) the start and end dates entered.\n\n\tKeyword arguments:\n\tstar_date \t-- either a datetime or a string in the following format \"yyyy-mm-dd\"\n\tend_date \t-- either a datetime or a string in the following format \"yyyy-mm-dd\"\n\t\"\"\"\n\n\tstart_date = date_to_string(start_date)\n\tend_date = date_to_string(end_date)\n\tif start_date not in df.index:\n\t\tstart_date = df.head(1).index[0]\n\tif end_date not in df.index:\n\t\tend_date = df.tail(1).index[0]\n\treturn df.loc[start_date : end_date, :]\ndef year_to_date():\n\t\"\"\"Returns a dataframe whose index ranges from last trade date of last year to today\"\"\"\n\n\treturn rows_between(last_year_trade_date(), now)\ndef last_year_trade_date(dataframe, year=\"\"):\n\t\"\"\"Returns a datetime.datetime object of the last trade date of last year (or specifiec year)\"\"\"\n\tlast_year=None\n\tif year == \"\":\n\t\tlast_year = (now - relativedelta(years=1)).year\n\telse:\n\t\tthis_year_datetime = datetime(year, 1, 1)\n\t\tlast_year = (this_year_datetime - relativedelta(years=1)).year\n\tlast_year_trade_date = datetime(last_year,12 ,31)\n\twhile(last_year_trade_date not in dataframe.index):\n\t\tlast_year_trade_date = (last_year_trade_date - relativedelta(days=1))\n\treturn last_year_trade_date\n\ndef date_to_string(date_to_string):\n\t\"\"\"Returns a string representation of datetime formatted \"yyyy-mm-dd\"\"\"\n\n\tif type(date_to_string) is datetime:\n\t\treturn date_to_string.strftime(\"%Y-%m-%d\")\n\treturn date_to_string\ndef string_to_date(string_to_date):\n\tif type(string_to_date) is str:\n\t\treturn datetime.strptime(string_to_date,\"%Y-%m-%d\")\n\treturn string_to_date\n\n\n\n","sub_path":"Prometheus/CherryPy/test/dataframe_utils.py","file_name":"dataframe_utils.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"430696228","text":"# !/usr/bin/env python3\n# @Time : 2020-02-14\n# @Author : caicai\n# @File : es_export.py\nfrom elasticsearch import helpers\nfrom elasticsearch import Elasticsearch\nimport base64\nimport copy\nimport time\n\n\nclass plugin():\n def __init__(self, dictdata):\n self.dictdata = dictdata\n self.es = Elasticsearch()\n\n def run(self):\n dictdata=self.dictdata\n # 把请求体和响应体 base64解码,便于搜索\n dictdata[\"request\"][\"raw\"] = base64.b64decode(self.dictdata.get(\"request\").get(\"raw\")).decode(\"utf-8\",\n errors=\"ignore\")\n dictdata[\"response\"][\"raw\"] = base64.b64decode(self.dictdata.get(\"response\").get(\"raw\")).decode(\"utf-8\",\n errors=\"ignore\")\n if \"others\" in dictdata.keys():\n del dictdata[\"others\"]\n if \"filter\" in dictdata.keys():\n del dictdata[\"filter\"]\n dictdata[\"ts\"]=int(time.time())\n actions = []\n action = {\n \"_index\": \"burpdata\",\n \"_type\": \"doc\",\n \"_source\": dictdata\n }\n actions.append(action)\n helpers.bulk(self.es, actions)\n","sub_path":"myscan/plugins/es_export.py","file_name":"es_export.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"497159259","text":"import numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.version import cuda\n\nfrom gcommand_loader import GCommandLoader\n\n\ndef loadData(path, size):\n x1 = torch.utils.data.DataLoader(\n path, batch_size=size, shuffle=True,\n num_workers=20, pin_memory=True, sampler=None)\n return x1\n\n\ndef getDictionnary():\n labels = dict()\n labels.__setitem__(\"bed\", 0), labels.__setitem__(\"bird\", 1), labels.__setitem__(\"cat\", 2), labels.__setitem__(\n \"dog\", 3),labels.__setitem__(\"down\", 4),\n labels.__setitem__(\"eight\", 5), labels.__setitem__(\"five\", 6), labels.__setitem__(\"four\", 7), labels.__setitem__(\n \"go\", 8),\n labels.__setitem__(\"happy\", 9), labels.__setitem__(\"house\", 10), labels.__setitem__(\"left\", 11), labels.__setitem__(\n \"marvin\", 12),\n labels.__setitem__(\"nine\", 13), labels.__setitem__(\"no\", 14), labels.__setitem__(\"off\", 15), labels.__setitem__(\"on\",\n 16), labels.__setitem__(\n \"one\", 17)\n labels.__setitem__(\"right\", 18), labels.__setitem__(\"seven\", 19), labels.__setitem__(\"sheila\",\n 20), labels.__setitem__(\"six\",\n 21), labels.__setitem__(\n \"stop\", 22),\n labels.__setitem__(\"three\", 23), labels.__setitem__(\"tree\", 24), labels.__setitem__(\"two\", 25), labels.__setitem__(\n \"up\", 26), labels.__setitem__(\"wow\", 27),\n labels.__setitem__(\"yes\", 28), labels.__setitem__(\"zero\", 29)\n return labels\n\n\nclass ConvNet(nn.Module):\n\n def __init__(self):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 30, kernel_size=4, stride=1, padding=1),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n #self.layer2 = nn.Sequential(\n #nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),\n #nn.ReLU(),\n #nn.MaxPool2d(kernel_size=2, stride=2))\n self.drop_out = nn.Dropout()\n self.fc1 = nn.Linear(80 * 50 * 30, 1000)\n self.fc2 = nn.Linear(1000, 30)\n\n def forward(self, x):\n out = self.layer1(x)\n #out = self.layer2(out)\n out = out.reshape(out.size(0), -1)\n out = self.drop_out(out)\n out = self.fc1(out)\n out = self.fc2(out)\n return out\n\n def validation_model(self, set_validation):\n self.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n for examples, labels in set_validation:\n outputs = self(examples)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n print(\"accuracy : {} %\".format((correct/total)*100))\n\ndef main():\n\n dataSetTest = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Test\")\n dataSetTrain = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Train2\")\n dataSetValid = GCommandLoader(\"/home/herold55/PycharmProjects/ex4ML/Valid\")\n print(len(dataSetTest))\n print(len(dataSetTrain))\n print(len(dataSetValid))\n x_test = loadData(dataSetTest, 100)\n x_train = loadData(dataSetTrain, 100)\n x_valid = loadData(dataSetValid, 100)\n epochs = 5\n learning_rate = np.exp(-23)\n model = ConvNet()\n # Loss and optimizer\n criterion = nn.NLLLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n # Train the model\n total_step = len(x_train)\n loss_list = []\n acc_list = []\n for epoch in range(epochs):\n for (images, labels) in x_train:\n # Run the forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n loss_list.append(loss.item())\n\n # Backprop and perform Adam optimisation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # Track the accuracy\n total = labels.size(0)\n _, predicted = torch.max(outputs.data, 1)\n correct = (predicted == labels).sum().item()\n acc_list.append(correct / total)\n\n #if (True):\n # print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'\n # .format(epoch + 1, epochs, total_step, loss.item(),\n # (correct / total) * 100))\n model.validation_model(x_valid)\n\nmain()\n","sub_path":"Pytorch Model/Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"144133045","text":"\"\"\"\nThis module demonstrates the ACCUMULATOR pattern in three classic forms:\n SUMMING: total = total + number\n COUNTING: count = count + 1\n IN GRAPHICS: x = x + pixels\n\nAuthors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays,\n Aaron Wilkin, their colleagues, and Ben Hawkins.\n\"\"\" # Done: 1. PUT YOUR NAME IN THE ABOVE LINE.\n\n###############################################################################\n#\n# Done: 2.\n# RUN this program, then READ its code.\n# Then answer the following, GETTING HELP AS NEED! (Ask questions!!!)\n# Write your answers in any reasonable way (your choice).\n#\n# For the first several questions, some students find the following\n# picture helpful. (Your instructor may explain it in whole-group.)\n#\n# 0 1 2 3 4 ... r-1 r r+1 r+2 r+3 ... s\n# |..... r numbers .....|\n# |................ s+1 numbers ..................|\n# Hence: |... (s+1)-r numbers ...|\n#\n# a. If you want a loop that runs r times,\n# which of the following three choices would you use?\n#\n# for k in range(r - 1):\n# for k in range(r): <-- This one\n# for k in range(r + 1):\n#\n# b. If you want a loop that runs from 0 to s, inclusive,\n# what expression would you use in the _____ below?\n#\n# for k in range(s+1):\n#\n# c. If you want a loop that runs from r to s, inclusive, assuming s >= r,\n# what expression would you use in the ______below?\n#\n# for k in range(s-r+1):\n#\n# d. If you want a loop that runs from (r + 4) to (s - 10),\n# including the (r + 4) but not including the (s - 10),\n# what expression would you use in the _____ below?\n#\n# for k in range(s+r-6):\n#\n# e. The following code snippet attempts to return the number\n# of integers from r to s, inclusive, whose cosines are positive.\n# It has at least 5 distinct errors (one per line). What are they?\n#\n# for k in range(r - s):\n# count = 0\n# if math.cos(r) > 0:\n# count = 1\n# return count\n#\n# The range of the for loop is wrong (should be s-r+1), the count is within the for loop so it'll\n# constantly be reset,the math.cos uses r instead of k, it then sets count equal to 1 instead of adding\n# one, and then it returns everytime the loop runs, which is pointless and can be kept outside it.\n#\n# f. The code in the \"graphics accumulation\" example below includes:\n# for _ in range(n):\n# What does the _ (underscore) mean?\n#\n# Which iteration of the loop it is currently on when the index variable doesn't matter for the loop.\n#\n# g. The code in the \"graphics accumulation\" example below includes:\n#\n# x = starting_point.x\n# for _ in range(n):\n# center = rg.Point(x, y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n# x = x + diameter\n#\n# If you want the row-of-circles that the above creates,\n# one of the following two attempts is a CORRECT attempt\n# (i.e., is equivalent in its functionality to the above)\n# and one is WRONG. Which is the WRONG one?\n#\n# x = starting_point.x\n# for k in range(n):\n# center = rg.Point(x + (k * diameter), y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n#\n# x = starting_point.x\n# for k in range(n):\n# center = rg.Point(x + (k * diameter), y)\n# circle = rg.Circle(point, radius)\n# circle.attach_to(window)\n# x = x + (2 * radius)\n#\n# The second is correct\n#\n#\n###############################################################################\n# *** MAKE SURE YOU UNDERSTAND THE 3 ACCUMULATOR PATTERNS ***\n# *** shown in this module: SUMMING, COUNTING, and IN GRAPHICS ***\n###############################################################################\n#\n# When you are confident that you understand the 3 accumulator patterns\n# and have correct answers to the above questions (ASK QUESTIONS AS NEEDED!),\n# check your work by asking a student assistant to look at your answers.\n#\n# After checking your work (making corrections as needed),\n# change the above _TODO_ to DONE.\n#\n###############################################################################\n\nimport rosegraphics as rg\nimport math\n\n\ndef main():\n \"\"\" Calls the TEST functions in this module. \"\"\"\n run_test_summing_example()\n run_test_counting_example()\n run_test_draw_row_of_circles()\n\n\ndef run_test_summing_example():\n \"\"\" Tests the summing_example function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the summing_example function:')\n print('--------------------------------------------------')\n\n # Test 1:\n expected = 100\n answer = summing_example(4)\n print('Test 1 expected:', expected)\n print(' actual: ', answer)\n\n # Test 2:\n expected = 44100\n answer = summing_example(20)\n print('Test 2 expected:', expected)\n print(' actual: ', answer)\n\n # Test 3:\n expected = 0\n answer = summing_example(0)\n print('Test 3 expected:', expected)\n print(' actual: ', answer)\n\n\ndef summing_example(n):\n \"\"\"\n What comes in: The sole argument is a non-negative integer n.\n What goes out: Returns the sum\n (1 cubed) + (2 cubed) + (3 cubed) + ... + (n cubed).\n Side effects: None.\n Examples:\n -- If the integer is 4,\n this function returns (1 + 8 + 27 + 64), which is 100.\n -- If the integer is 20, this function returns 44,100.\n \"\"\"\n total = 0 # Initialize to 0 BEFORE the loop\n for k in range(n): # Loop\n total = total + ((k + 1) ** 3) # Accumulate INSIDE the loop.\n\n return total # Return the result AFTER the loop\n\n\ndef run_test_counting_example():\n \"\"\" Tests the counting_example function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the counting_example function:')\n print('--------------------------------------------------')\n\n # Test 1:\n expected = 2\n answer = counting_example(2)\n print('Test 1 expected:', expected)\n print(' actual: ', answer)\n\n # Test 2:\n expected = 12\n answer = counting_example(20)\n print('Test 2 expected:', expected)\n print(' actual: ', answer)\n\n # Test 3:\n expected = 1\n answer = counting_example(0)\n print('Test 3 expected:', expected)\n print(' actual: ', answer)\n\n\ndef counting_example(n):\n \"\"\"\n What comes in: The sole argument is a non-negative integer n.\n What goes out: Returns the number of integers from 0 to n,\n inclusive, whose cosine is positive.\n Side effects: None.\n Examples:\n -- counting_example(2) returns 2\n since the cosine(0) is 1 (positive)\n and the cosine(1) is about 0.54 (positive)\n and the cosine(2) is about -0.42 (negative)\n\n -- counting_example(20) returns 12\n since the cosines of 0, 1, 5, 6, 7, 11, 12, 13, 14, 18, 19 and 20\n are positive\n\n -- counting_example(0) returns 1\n since the cosine(0) is positive.\n \"\"\"\n count = 0 # Initialize to 0 BEFORE the loop\n for k in range(n + 1): # Loop\n if math.cos(k) > 0: # If the condition holds:\n count = count + 1 # Increment INSIDE the loop.\n\n return count # Return the result AFTER the loop\n\n\ndef run_test_draw_row_of_circles():\n \"\"\" Tests the draw_row_of_circles function. \"\"\"\n print()\n print('--------------------------------------------------')\n print('Testing the draw_row_of_circles function:')\n print(' See the graphics windows that pop up.')\n print('--------------------------------------------------')\n\n # -------------------------------------------------------------------------\n # TWO tests on ONE window.\n # -------------------------------------------------------------------------\n title = 'Tests 1 and 2 of DRAW_ROW_OF_CIRCLES:'\n title = title + ' 7 GREEN circles, 4 BLUE circles!'\n window1 = rg.RoseWindow(500, 250, title)\n\n # Test 1:\n center = rg.Point(50, 50)\n draw_row_of_circles(7, center, 'green', window1)\n\n # Test 2:\n center = rg.Point(100, 150)\n draw_row_of_circles(4, center, 'blue', window1)\n window1.close_on_mouse_click()\n\n # -------------------------------------------------------------------------\n # A third test on ANOTHER window.\n # -------------------------------------------------------------------------\n title = 'Test 3 of DRAW_ROW_OF_CIRCLES: Row of 12 RED circles!'\n window2 = rg.RoseWindow(600, 150, title)\n\n # Test 3:\n center = rg.Point(50, 50)\n draw_row_of_circles(12, center, 'red', window2)\n\n window2.close_on_mouse_click()\n\n\ndef draw_row_of_circles(n, starting_point, color, window):\n \"\"\"\n What comes in: The four arguments are:\n -- A positive integer n.\n -- An rg.Point.\n -- A color appropriate for rosegraphics (e.g. 'red')\n -- An rg.RoseWindow.\n What goes out: Nothing (i.e., None).\n Side effects:\n Draws n rg.Circle objects in a row,\n all on the given rg.RoseWindow, such that:\n -- The first rg.Circle is centered at the given starting_point.\n -- Each rg.Circle just touches the previous one (to its left).\n -- Each rg.Circle has radius 20.\n -- Each rg.Circle is filled with the given color.\n Must ** render ** but ** NOT close ** the rg.RoseWindow.\n\n Type hints:\n :type n: int\n :type starting_point: rg.Point\n :type color: str\n :type window: rg.RoseWindow\n \"\"\"\n # -------------------------------------------------------------------------\n # The example below shows one way to solve problems using\n # HELPER variables (aka AUXILIARY variables)\n # In this approach:\n # 1. You determine all the variables that you need\n # to construct/draw whatever the problem calls for.\n # We call these HELPER variables.\n # 2. You initialize them BEFORE the loop, choosing values that\n # make them just right for constructing and drawing the\n # FIRST object to be drawn, in the FIRST time through the loop.\n # For example, x = starting_point.x in the example below.\n # 3. You determine how many times the loop should run\n # (generally, however many objects you want to draw)\n # and write the FOR statement for the loop.\n # For example, for _ in range(n): in the example below.\n # 4. Inside the loop you write the statements to construct and\n # draw the FIRST object to be drawn, using your helper\n # variables. This is easy because you chose just the right\n # values for those helper variables for this FIRST object.\n # 5. Test: Make sure the FIRST object appears.\n # (It will be redrawn many times, that is OK).\n # 6. Add code at the BOTTOM of the loop that changes the helper\n # variables appropriately for the NEXT time through the loop.\n # For example, x = x + diameter in the example below.\n # 7. Test and fix as needed.\n #\n # Many students (and professionals) find this technique less\n # error-prone that using the loop variable to do all the work.\n # -------------------------------------------------------------------------\n\n radius = 20\n diameter = 2 * radius\n\n x = starting_point.x # Initialize x and y BEFORE the loop. Choose ...\n y = starting_point.y # ... values that make the FIRST object easy to draw.\n\n for _ in range(n): # Loop that does NOT use its index variable\n\n # ---------------------------------------------------------------------\n # Construct the relevant object(s),\n # based on the current x, y and other variables.\n # ---------------------------------------------------------------------\n center = rg.Point(x, y)\n circle = rg.Circle(center, radius)\n circle.fill_color = color\n\n # Attach the object(s) to the window.\n circle.attach_to(window)\n\n # ---------------------------------------------------------------------\n # Increment x (and in other problems, other variables)\n # for the thing(s) to draw in the NEXT iteration of the loop.\n # ---------------------------------------------------------------------\n x = x + diameter\n\n window.render()\n\n\n# -----------------------------------------------------------------------------\n# Calls main to start the ball rolling.\n# -----------------------------------------------------------------------------\nmain()\n","sub_path":"src/m1r_accumulator_examples.py","file_name":"m1r_accumulator_examples.py","file_ext":"py","file_size_in_byte":13120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"382556454","text":"#!/usr/bin/env python\r\n\r\nimport vtk\r\n\r\nx = [(0.5, 0.5, 0.5),\r\n (-0.5, 0.5, 0.5),\r\n (0.5, -0.5, 0.5),\r\n (-0.5, -0.5, 0.5),\r\n (0.5, 0.5, -0.5),\r\n (-0.5, 0.5, -0.5),\r\n (0.5, -0.5, -0.5),\r\n (-0.5, -0.5, -0.5)]\r\n\r\nsquares = [(0, 2, 6, 4),\r\n (4, 5, 1, 0),\r\n (1, 3, 2, 0),\r\n (1, 5, 7, 3),\r\n (2, 3, 7, 6),\r\n (7, 5, 4, 6)]\r\n\r\ntriangles = [(0, 2, 4),\r\n (2, 6, 4),\r\n (4, 5, 0),\r\n (5, 1, 0),\r\n (1, 3, 2),\r\n (1, 2, 0),\r\n (1, 5, 3),\r\n (5, 7, 3),\r\n (2, 3, 6),\r\n (3, 7, 6),\r\n (7, 5, 6),\r\n (5, 4, 6)]\r\n\r\ntriangleStrips = [[0, 1, 2, 3, 6, 7, 4, 5],\r\n [2, 6, 0, 4, 1, 5, 3, 7]]\r\n\r\n\r\ndef writeFile(filename, polydata):\r\n\twriter = vtk.vtkPolyDataWriter()\r\n\twriter.SetFileName(filename)\r\n\twriter.SetInputData(polydata)\r\n\twriter.Write()\r\n\r\n\r\n# Use squares\r\ncube = vtk.vtkPolyData()\r\npoints = vtk.vtkPoints()\r\npolys = vtk.vtkCellArray()\r\nscalars = vtk.vtkFloatArray()\r\n\r\nfor i in range(0, 8):\r\n\tpoints.InsertPoint(i, x[i])\r\n\r\nfor face in squares:\r\n\tpolys.InsertNextCell(4, face)\r\n\r\nfor i in range(0, 8):\r\n\tscalars.InsertTuple1(i, i)\r\n\r\ncube.SetPoints(points)\r\ncube.SetPolys(polys)\r\ncube.GetPointData().SetScalars(scalars)\r\n\r\nwriteFile('data/cubeSquares.vtk', cube)\r\n\r\n# Use triangles\r\npolys = vtk.vtkCellArray()\r\n\r\nfor face in triangles:\r\n\tpolys.InsertNextCell(3, face)\r\n\r\ncube.SetPolys(polys)\r\n\r\nwriteFile('data/cubeTriangles.vtk', cube)\r\n\r\n# Using two triangle strips\r\nstrip = vtk.vtkCellArray()\r\nfor s in triangleStrips:\r\n\tstrip.InsertNextCell(len(s))\r\n\tfor i in s:\r\n\t\tstrip.InsertCellPoint(i)\r\n\r\ncube = vtk.vtkPolyData()\r\ncube.SetPoints(points)\r\ncube.SetStrips(strip)\r\ncube.GetPointData().SetScalars(scalars)\r\n\r\nwriteFile('data/cubeStrip.vtk', cube)\r\n","sub_path":"src/polydata/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"560328911","text":"from django.utils.translation import ugettext as _\n\nfrom .constants import ABSENT, BHS, BHS_ELIGIBLE, BHS_SCREEN, HTC, HTC_ELIGIBLE, NOT_ELIGIBLE, NOT_REPORTED, REFUSED, UNDECIDED, REFUSED_HTC, BHS_LOSS\n\noptions = list(set([ABSENT, BHS, BHS_ELIGIBLE, BHS_SCREEN, HTC, HTC_ELIGIBLE, NOT_ELIGIBLE, NOT_REPORTED, REFUSED, UNDECIDED, REFUSED_HTC, BHS_LOSS]))\n\nHOUSEHOLD_MEMBER_PARTICIPATION = [(item, item) for item in options]\n\nFEMALE_RELATIONS = [\n ('wife', 'Wife'),\n ('daughter', 'Daughter'),\n ('mother', 'Mother'),\n ('sister', 'Sister'),\n ('grandmother', 'Grandmother'),\n ('granddaughter', 'Granddaughter'),\n ('great-Grandmother', 'Great-Grandmother'),\n ('great-Granddaughter', 'Great-Granddaughter'),\n ('aunt', 'Aunt'),\n ('niece', 'Niece'),\n ('mother-in-law', 'Mother-in-law'),\n ('daughter-in-law', 'Daughter-in-law'),\n ('sister-in-law', 'Sister-in-law'),\n ('housemaid', 'Housemaid'),\n ]\n\nANY_RELATIONS = [\n ('partner', 'Partner'),\n ('housemate', 'Housemate'),\n ('cousin', 'Cousin'),\n ('family_friend', 'Family friend'),\n ('friend', 'Friend'),\n ('helper', 'Helper'),\n ('employee', 'Employee'),\n ]\nMALE_RELATIONS = [\n ('husband', 'Husband'),\n ('son', 'Son'),\n ('father', 'Father'),\n ('brother', 'Brother'),\n ('grandfather', 'Grandfather'),\n ('grandson', 'Grandson'),\n ('great-Grandfather', 'Great-Grandfather'),\n ('great-Grandson', 'Great-Grandson'),\n ('uncle', 'Uncle'),\n ('nephew', 'Nephew'),\n ('father-in-law', 'Father-in-law'),\n ('son-in-law', 'Son-in-law'),\n ('brother-in-law', 'Brother in-law'),\n ]\n\n\nrelations = FEMALE_RELATIONS + MALE_RELATIONS + ANY_RELATIONS\nrelations.sort()\nRELATIONS = [('Head', 'HEAD of HOUSEHOLD')] + relations + [('UNKNOWN', 'UNKNOWN')]\n\nABSENTEE_STATUS = (\n ('ABSENT', _('Absent')),\n ('NOT_ABSENT', _('No longer absent')),\n)\n\nABSENTEE_REASON = (\n ('gone visiting (relatives,holidays,weddings,funerals)', _('Gone visiting')),\n ('stays at lands or cattlepost ', _('Stays at Lands/Cattlepost ')),\n ('stepped out(shops, errands etc) ', _('Stepped out (shops, errands, ) ')),\n ('works in village and comes home daily', _('Works in the village, home daily')),\n ('goes to school in village and comes home daily', _('Schools in this village, home daily')),\n ('works outside village and comes home daily', _('Works outside the village, home daily')),\n ('goes to school outside village and comes home daily', _('Schools outside village, home daily')),\n ('works outside village and comes home irregularly ', _('Works outside the village, home irregularly ')),\n ('goes to school outside village and comes home irregularly ', _('Schools outside village, home irregularly ')),\n ('works outside village and comes home monthly ', _('Works outside the village, home monthly ')),\n ('goes to school outside village and comes home monthly ', _('Schools outside village, home monthly ')),\n ('works outside village and comes home on weekends ', _('Works outside the village, home on weekends ')),\n ('goes to school outside village and comes home on weekends ', _('Schools outside village, home on weekends ')),\n ('OTHER', _('Other...')),\n)\n\nNEXT_APPOINTMENT_SOURCE = (\n ('participant', _('Participant')),\n ('household member', _('household member')),\n ('hbc', _('HBC')),\n ('other', _('Other'))\n)\n\nMOVED_REASON = (\n ('TRANSFER', _('Job Transfer')),\n ('MARRIAGE', _('Marriage')),\n ('INDEPENDENT', _('Independence')),\n ('OTHER', _('Other')),\n)\n\nPLACE_SUBJECT_MOVED = (\n ('IN_VILLAGE', _('Within Village')),\n ('OUT_VILLAGE', _('Outside Village')),\n)\n\nUNDECIDED_REASON = (\n ('afraid_to_test', _('afraid_to_test')),\n ('not ready to test', _('not ready to test')),\n ('wishes to test with partner', _('wishes to test with partner')),\n ('OTHER', _('Other...')),\n)","sub_path":"apps/bcpp_household_member/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"564754384","text":"#Модуль по сборке и выводу собранных данных об использова��ии различных команд пользователями\n\n#Подключаем бд\nfrom modules.db import Connection\n\n#ВРЕМЕЧКО\nimport time\n\n#Основной функционал\n\ndef addStat(command, user_id):\n cursor = Connection.db.cursor()\n sql = \"INSERT INTO stats VALUES (null, %s, %s, %s)\"\n cursor.execute(sql, (int(user_id), str(command), int(time.time())))\n Connection.db.commit()\n","sub_path":"modules/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"432812678","text":"import re\nimport datetime\n\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import get_model\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.template.defaultfilters import escape\nfrom django.utils import feedgenerator\nfrom django.db.models import Q\n\nfrom fedregsite.annotations.forms import SearchForm\nfrom fedregsite.annotations.models import Document\nfrom fedregsite.annotations.utils import get_doc_url, feed_to_response, days_ago, MIDNIGHT_EST\n\n\n# Django performs MySQL fulltext searches in \"Boolean Mode\". This means that \n# search terms can be preceded by operators with special meanings. By default, \n# Boolean Mode performs a search on the OR of the search terms. This function \n# prepends the '+' operator to each term to ensure that the search is done on \n# the AND of the terms unless the term is already preceded by an operator.\n#\n# See http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html\n#\ndef prep_fulltext(query, wildcard_last=False):\n qparts = re.split('\\s+', query)\n\n operators = set(['+', '-', '<', '>', '~'])\n qparts = map(lambda qp: qp[0] in operators and qp or '+' + qp, qparts)\n\n group_closers = set([')', '\"'])\n if wildcard_last and not qparts[-1] in group_closers:\n qparts[-1] = qparts[-1] + '*'\n \n return ' '.join(qparts)\n\n\ndef parse_query(form, is_rss=False):\n if not form.is_valid():\n return None\n \n docs = Document.objects\n\n # fields requiring fulltext search\n #fields = ['text', 'action', 'subject', 'rin']\n fields = ['text', 'action', 'subject'] \n for field in fields:\n f = form.cleaned_data[field]\n if f:\n if field == 'rin':\n f = '\"' + f + '\"'\n docs = docs.filter(**{field + '__search':prep_fulltext(f)})\n\n if not is_rss:\n date_range = form.cleaned_data['date_range']\n if date_range and date_range[0]:\n if date_range[1]:\n docs = docs.filter(dailyIssue__date__range=(date_range[0], date_range[1]))\n else:\n docs = docs.filter(dailyIssue__date__exact=date_range[0])\n\n types = form.cleaned_data['type']\n if types:\n q = Q()\n for type in types:\n if type.lower() != 'presidential':\n q = q | Q(type__xmlTag__iexact=type)\n else:\n types.extend(['DETERM', 'EXECORD', 'PRMEMO', 'PRNOTICE', 'PROCLA', 'PRORDER'])\n docs = docs.filter(q)\n\n agency = form.cleaned_data['agency']\n if agency:\n docs = docs.filter(agencies__name__search=prep_fulltext(agency))\n subagency = form.cleaned_data['subagency']\n if subagency:\n docs = docs.filter(subagencies__name__search=prep_fulltext(subagency))\n\n cfr_title = form.cleaned_data['cfr_title']\n if cfr_title:\n docs = docs.filter(cfr_affected__title__exact=cfr_title)\n cfr_part = form.cleaned_data['cfr_part']\n if cfr_part:\n docs = docs.filter(cfr_affected__part__exact=cfr_part)\n \n if docs == Document.objects:\n docs = None\n else:\n docs = docs.defer('xml', 'xmlHash')\n docs = docs.select_related('dailyIssue', 'type')\n # can't sort, too slow\n #docs = docs.order_by('-dailyIssue__date')\n \n return docs\n\ndef ajax_lookup(request, model=None):\n \n try:\n query = request.GET[\"q\"]\n except KeyError:\n return HttpResponseBadRequest()\n if len(query) < 3 or (model != 'agency' and model != 'subagency'):\n return HttpResponseBadRequest()\n\n query_model = get_model('annotations', model)\n qset = query_model.objects.filter(name__search=prep_fulltext(query, wildcard_last=True))[:10]\n results = [ x.name.title() for x in qset ]\n return HttpResponse(\"\\n\".join(results))\n\n\ndef new_search(request):\n form = SearchForm(request.GET)\n docs = parse_query(form)\n \n query_dict = request.GET.copy()\n try:\n del query_dict['page']\n except KeyError: pass\n\n query_str = query_dict.urlencode()\n if docs == None:\n query_str = u''\n\n return render_to_response('search/index.html',\n {'form': form,\n 'docs': docs, \n 'query_str': query_str, \n 'search_term': query_dict.get('text','')},\n context_instance=RequestContext(request))\n\ndef search(request):\n form = SearchForm(request.GET)\n docs = parse_query(form)\n \n query_dict = request.GET.copy()\n try:\n del query_dict['page']\n except KeyError: pass\n\n query_str = query_dict.urlencode()\n if docs == None:\n query_str = u''\n\n return render_to_response('search.html',\n {'form': form,\n 'docs': docs, \n 'query_str': query_str, \n 'search_term': query_dict.get('text','')},\n context_instance=RequestContext(request))\n\n\ndef feed(request):\n form = SearchForm(request.GET)\n docs = parse_query(form, is_rss=True)\n if docs == None:\n return HttpResponseBadRequest()\n\n # See: http://code.djangoproject.com/ticket/7074\n # docs = docs.filter(dailyIssue__date__gt=days_ago(5)).order_by('-dailyIssue__date')\n d = days_ago(5)\n docs = docs.extra(where=['`annotations_dailyissue`.`date` > DATE(%s)'], params=[d]).order_by('-dailyIssue__date')\n \n feed = feedgenerator.Rss201rev2Feed(title=u'Search Results Feed',\n link=request.build_absolute_uri(reverse('search-form') + '?' + request.GET.urlencode()),\n description='',\n language=u\"en\",\n ttl=u'1440') # Set a TTL of 1 day\n\n for doc in docs:\n pubdate = datetime.datetime.combine(doc.dailyIssue.date, MIDNIGHT_EST)\n feed.add_item(title=escape(doc.subject), \n link=request.build_absolute_uri(get_doc_url(doc)),\n description=escape(doc.snippet()),\n pubdate=pubdate)\n \n return feed_to_response(feed)\n","sub_path":"site/fedregsite/annotations/views/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"416910840","text":"import os\nimport string\nimport random\nimport hashlib\nimport json\nimport datetime,time\nimport pytz\nfrom collections import OrderedDict\nfrom bson import json_util, ObjectId\nimport collections\n\n\nfrom glygen.db import get_mongodb\nfrom glygen.util import cache_record_list, get_errors_in_query\n\n\ndef search_init(config_obj):\n \n dbh, error_obj = get_mongodb()\n if error_obj != {}:\n return error_obj\n\n collection = \"c_searchinit\"\n doc = dbh[collection].find_one({})\n\n doc[\"idmapping\"][\"glycan\"][\"organism\"] = doc[\"glycan\"][\"organism\"]\n doc[\"idmapping\"][\"protein\"][\"organism\"] = doc[\"protein\"][\"organism\"] \n\n\n res_obj = doc[\"idmapping\"]\n for k in res_obj:\n if \"namespace\" in res_obj[k]:\n tmp_dict = {}\n for obj in res_obj[k][\"namespace\"]:\n tmp_dict[obj[\"source\"]] = {\"target_list\":obj[\"targetlist\"], \"example_id_list\":obj[\"example_id_list\"]}\n res_obj[k][\"namespace\"] = tmp_dict\n \n return res_obj\n\n\n\ndef search(query_obj, config_obj):\n \n dbh, error_obj = get_mongodb()\n if error_obj != {}:\n return error_obj\n\n q_list = []\n for q in query_obj[\"input_idlist\"]:\n q_list.append(q)\n\n\n mongo_query = {\"crossref.id\":{\"$in\": q_list}}\n record_id_field = config_obj[\"record_type_info\"][query_obj[\"recordtype\"]][\"field\"]\n record_id_label = config_obj[\"record_type_info\"][query_obj[\"recordtype\"]][\"label\"]\n\n\n \n coll = \"c_\" + query_obj[\"recordtype\"]\n prj_obj = {\"crossref\":1, record_id_field:1}\n\n\n\n mapping_dict = {}\n for doc in dbh[coll].find(mongo_query,prj_obj):\n in_list, out_list = [], []\n for obj in doc[\"crossref\"]:\n if obj[\"id\"].strip() == \"\":\n continue\n if obj[\"database\"] == query_obj[\"input_namespace\"] and obj[\"id\"] in q_list:\n in_list.append(obj[\"id\"])\n if obj[\"database\"] == query_obj[\"output_namespace\"]:\n out_list.append(obj[\"id\"])\n for in_id in in_list:\n if in_id not in mapping_dict:\n mapping_dict[in_id] = []\n\n for out_id in out_list:\n if out_id not in mapping_dict[in_id]:\n i_id = int(in_id) if in_id.isdigit() == True else in_id\n o_id = int(out_id) if out_id.isdigit() == True else out_id\n o = {\"anchor\":doc[record_id_field], \"from\":i_id, \"to\":o_id,\"category\":\"mapped\"}\n mapping_dict[in_id].append(o)\n \n\n\n all_glytoucan_dict = {}\n #If input_namespace is GlyToucan, check all glytoucan_idlist\n if query_obj[\"input_namespace\"].lower() == \"glytoucan\":\n for doc in dbh[\"c_glytoucan\"].find({}):\n for ac in doc[\"aclist\"]:\n all_glytoucan_dict[ac] = True\n\n record_list = []\n for in_id in mapping_dict:\n for o in mapping_dict[in_id]:\n record_list.append(o)\n\n for in_id in q_list:\n if in_id not in mapping_dict:\n reason = \"Invalid ID\"\n if in_id in all_glytoucan_dict:\n reason = \"Valid GlyTouCan accession but not in GlyGen\"\n record_list.append({\"input_id\":in_id, \"reason\": reason, \"category\":\"unmapped\"})\n elif mapping_dict[in_id] == []:\n reason = \"Valid ID, no mapping found\"\n record_list.append({\"input_id\":in_id, \"reason\": reason, \"category\":\"unmapped\"})\n \n\n mapped_legends = {\n \"from\":query_obj[\"input_namespace\"],\n \"to\":query_obj[\"output_namespace\"],\n \"anchor\":record_id_label\n }\n unmapped_legends = {\n \"input_id\":\"Input ID\",\n \"reason\":\"Reason\"\n }\n record_type = \"idmap\"\n ts_format = \"%Y-%m-%d %H:%M:%S %Z%z\"\n ts = datetime.datetime.now(pytz.timezone('US/Eastern')).strftime(ts_format)\n cache_coll = \"c_cache\"\n \n cache_info = {\n \"query\":query_obj,\n \"mapped_legends\":mapped_legends,\n \"unmapped_legends\":unmapped_legends, \n \"ts\":ts\n }\n list_id = \"\"\n if len(record_list) != 0:\n hash_str = record_type + \"_\" + \",\".join(query_obj[\"input_idlist\"]).strip()\n hash_obj = hashlib.md5(hash_str.encode('utf-8'))\n list_id = hash_obj.hexdigest()\n cache_record_list(dbh,list_id,record_list,cache_info,cache_coll,config_obj)\n res_obj = {\"list_id\":list_id}\n\n return res_obj\n\n","sub_path":"build/lib/glygen/idmapping_apilib.py","file_name":"idmapping_apilib.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"138300724","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Apr 1 11:16:50 2019\r\n\r\n@author: sallejaune\r\n\"\"\"\r\n\r\n#%%Import\r\nfrom PyQt6 import QtCore\r\nfrom PyQt6.QtWidgets import QApplication\r\nfrom PyQt6.QtWidgets import QWidget,QMessageBox,QLineEdit,QToolButton\r\nfrom PyQt6.QtWidgets import QVBoxLayout,QHBoxLayout,QPushButton,QGridLayout,QDoubleSpinBox,QCheckBox\r\nfrom PyQt6.QtWidgets import QComboBox,QLabel\r\nfrom PyQt6.QtGui import QIcon\r\nfrom PyQt6.QtCore import QRect\r\n\r\nimport sys,time,os\r\nimport qdarkstyle\r\nimport pathlib\r\n\r\n \r\nfrom scanMotor import SCAN\r\n\r\nimport TirGui\r\n#__version__=__init__.__version__\r\n\r\n\r\n\r\nclass ONEMOTORGUI(QWidget) :\r\n \"\"\"\r\n User interface Motor class : \r\n MOTOGUI(str(mot1), str(motorTypeName),, nomWin,nomTilt, )\r\n mot0= 'name of the motor ' (child group of the ini file)\r\n \r\n nonWin= windows name\r\n\r\n motorTypeName= Controler name : 'RSAI' or 'A2V' or 'NewFocus' or 'SmartAct' or 'Newport' , Servo\r\n showRef =True show refrence widget\r\n unit : 0: step 1: um 2: mm 3: ps 4: °\r\n \r\n \r\n \r\n fichier de config des moteurs : 'configMoteurRSAI.ini' 'configMoteurA2V.ini' 'configMoteurNewFocus.ini' 'configMoteurSmartAct.ini'\r\n \"\"\"\r\n\r\n def __init__(self, mot='',motorTypeName='',nomWin='',showRef=False,unit=2,jogValue=1,parent=None):\r\n \r\n super(ONEMOTORGUI, self).__init__(parent)\r\n \r\n p = pathlib.Path(__file__)\r\n sepa=os.sep\r\n self.icon=str(p.parent) + sepa + 'icons' +sepa\r\n self.motor=[str(mot)]\r\n self.motorTypeName=[motorTypeName]\r\n self.motorType=[0]\r\n self.MOT=[0]\r\n self.configMotName=[0]\r\n self.conf=[0]\r\n self.path=str(p.parent)+sepa\r\n self.configPath=str(p.parent / \"fichiersConfig\")+sepa\r\n self.isWinOpen=False\r\n self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))\r\n self.refShowId=showRef\r\n self.indexUnit=unit\r\n self.jogValue=jogValue\r\n self.etat='ok'\r\n self.tir=TirGui.TIRGUI()\r\n self.setWindowIcon(QIcon(self.icon+'LOA.png'))\r\n\r\n self.iconPlay=self.icon+\"playGreen.PNG\"\r\n self.iconPlay=pathlib.Path(self.iconPlay)\r\n self.iconPlay=pathlib.PurePosixPath(self.iconPlay)\r\n\r\n self.iconMoins=self.icon+\"moinsBleu.PNG\"\r\n self.iconMoins=pathlib.Path(self.iconMoins)\r\n self.iconMoins=pathlib.PurePosixPath(self.iconMoins)\r\n\r\n self.iconPlus=self.icon+\"plusBleu.PNG\"\r\n self.iconPlus=pathlib.Path(self.iconPlus)\r\n self.iconPlus=pathlib.PurePosixPath(self.iconPlus)\r\n\r\n self.iconStop=self.icon+\"close.PNG\"\r\n self.iconStop=pathlib.Path(self.iconStop)\r\n self.iconStop=pathlib.PurePosixPath(self.iconStop)\r\n \r\n for zi in range (0,1): # list configuration et motor types \r\n \r\n if self.motorTypeName[zi]=='RSAI':\r\n self.configMotName[zi]=self.configPath+'configMoteurRSAI.ini'\r\n import moteurRSAI as RSAI\r\n \r\n self.motorType[zi]=RSAI\r\n self.MOT[zi]=self.motorType[zi].MOTORRSAI(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='SmartAct':\r\n self.configMotName[zi]=self.configPath+'configMoteurSmartAct.ini'\r\n import smartactmot as SmartAct\r\n self.motorType[zi]=SmartAct\r\n self.MOT[zi]=self.motorType[zi].MOTORSMART(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='A2V':\r\n self.configMotName[zi]=self.configPath+'configMoteurA2V.ini'\r\n import moteurA2V as A2V\r\n self.motorType[zi]=A2V\r\n self.MOT[zi]=self.motorType[zi].MOTORA2V(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='NewFocus':\r\n self.configMotName[zi]=self.configPath+'configMoteurNewFocus.ini'\r\n import moteurNewFocus as NewFoc\r\n self.motorType[zi]=NewFoc\r\n self.MOT[zi]=self.motorType[zi].MOTORNEWFOCUS(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='newport':\r\n self.configMotName[zi]=self.configPath+'confNewport.ini'\r\n import newportMotors as Newport\r\n self.motorType[zi]=Newport\r\n self.MOT[zi]=self.motorType[zi].MOTORNEWPORT(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='Servo':\r\n self.configMotName[zi]=self.configPath+'configMoteurServo.ini'\r\n import servo as servo\r\n self.motorType[zi]=servo\r\n self.MOT[zi]=self.motorType[zi].MOTORSERVO(self.motor[zi])\r\n \r\n elif self.motorTypeName[zi]=='Arduino':\r\n self.configMotName[zi]=self.configPath+'configMoteurArduino.ini'\r\n import moteurArduino as arduino\r\n self.motorType[zi]=arduino\r\n self.MOT[zi]=self.motorType[zi].MOTORARDUINO(self.motor[zi])\r\n \r\n else:\r\n print('Error config motor Type name')\r\n self.configMotName[zi]=self.configPath+'configMoteurTest.ini'\r\n import moteurtest as test\r\n self.motorType[zi]=test\r\n self.MOT[zi]=self.motorType[zi].MOTORTEST(self.motor[zi])\r\n print(self.configMotName[zi])\r\n \r\n self.conf[zi]=QtCore.QSettings(self.configMotName[zi], QtCore.QSettings.Format.IniFormat) # fichier config motor fichier .ini\r\n \r\n self.scanWidget=SCAN(MOT=self.MOT[0],motor=self.motor[0],configMotName=self.configMotName[0]) # for the scan\r\n \r\n self.stepmotor=[0,0,0]\r\n self.butePos=[0,0,0]\r\n self.buteNeg=[0,0,0]\r\n self.name=[0,0,0]\r\n \r\n for zzi in range(0,1):\r\n \r\n self.stepmotor[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/stepmotor\")) #list of stepmotor values for unit conversion\r\n self.butePos[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/buteePos\")) # list \r\n self.buteNeg[zzi]=float(self.conf[zzi].value(self.motor[zzi]+\"/buteeneg\"))\r\n self.name[zzi]=str(self.conf[zzi].value(self.motor[zzi]+\"/Name\"))\r\n \r\n self.setWindowTitle(nomWin+' : '+ self.name[0]+' V.')\r\n \r\n self.thread=PositionThread(self,mot=self.MOT[0],motorType=self.motorType[0]) # thread for displaying position\r\n self.thread.POS.connect(self.Position)\r\n self.thread.ETAT.connect(self.Etat)\r\n \r\n \r\n \r\n ## initialisation of the jog value \r\n if self.indexUnit==0: # step\r\n self.unitChange=1\r\n self.unitName='step'\r\n \r\n if self.indexUnit==1: # micron\r\n self.unitChange=float((1*self.stepmotor[0])) \r\n self.unitName='um'\r\n if self.indexUnit==2: # mm \r\n self.unitChange=float((1000*self.stepmotor[0]))\r\n self.unitName='mm'\r\n if self.indexUnit==3: # ps double passage : 1 microns=6fs\r\n self.unitChange=float(1*self.stepmotor[0]/0.0066666666) \r\n self.unitName='ps'\r\n if self.indexUnit==4: # en degres\r\n self.unitChange=1 *self.stepmotor[0]\r\n self.unitName='°' \r\n \r\n self.setup()\r\n \r\n self.unit()\r\n self.jogStep.setValue(self.jogValue)\r\n \r\n def startThread2(self):\r\n self.thread.ThreadINIT()\r\n self.thread.start()\r\n time.sleep(0.1)\r\n \r\n \r\n def setup(self):\r\n \r\n vbox1=QVBoxLayout() \r\n hboxTitre=QHBoxLayout()\r\n self.nom=QLabel(self.name[0])\r\n self.nom.setStyleSheet(\"font: bold 20pt;color:yellow\")\r\n hboxTitre.addWidget(self.nom)\r\n \r\n self.enPosition=QLineEdit()\r\n #self.enPosition.setMaximumWidth(50)\r\n self.enPosition.setStyleSheet(\"font: bold 15pt\")\r\n self.enPosition.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n hboxTitre.addWidget(self.enPosition)\r\n self.butNegButt=QCheckBox('But Neg',self)\r\n hboxTitre.addWidget(self.butNegButt)\r\n \r\n self.butPosButt=QCheckBox('But Pos',self)\r\n hboxTitre.addWidget(self.butPosButt)\r\n vbox1.addLayout(hboxTitre)\r\n #vbox1.addSpacing(10)\r\n \r\n hShoot=QHBoxLayout()\r\n self.shootCibleButton=QPushButton('Shot')\r\n self.shootCibleButton.setStyleSheet(\"font: 12pt;background-color: red\")\r\n self.shootCibleButton.setMaximumWidth(100)\r\n self.shootCibleButton.setMinimumWidth(100)\r\n hShoot.addWidget(self.shootCibleButton)\r\n vbox1.addLayout(hShoot)\r\n \r\n \r\n hbox0=QHBoxLayout()\r\n self.position=QLabel('1234567')\r\n self.position.setMaximumWidth(300)\r\n self.position.setStyleSheet(\"font: bold 40pt\" )\r\n \r\n self.unitBouton=QComboBox()\r\n self.unitBouton.addItem('Step')\r\n self.unitBouton.addItem('um')\r\n self.unitBouton.addItem('mm')\r\n self.unitBouton.addItem('ps')\r\n self.unitBouton.addItem('°')\r\n self.unitBouton.setMaximumWidth(100)\r\n self.unitBouton.setMinimumWidth(100)\r\n self.unitBouton.setStyleSheet(\"font: bold 12pt\")\r\n self.unitBouton.setCurrentIndex(self.indexUnit)\r\n \r\n \r\n self.zeroButton=QPushButton('Zero')\r\n self.zeroButton.setMaximumWidth(50)\r\n \r\n hbox0.addWidget(self.position)\r\n hbox0.addWidget(self.unitBouton)\r\n hbox0.addWidget(self.zeroButton)\r\n vbox1.addLayout(hbox0)\r\n #vbox1.addSpacing(10)\r\n \r\n hboxAbs=QHBoxLayout()\r\n absolueLabel=QLabel('Absolue mouvement')\r\n# absolueLabel.setStyleSheet(\"background-color: green\")\r\n self.MoveStep=QDoubleSpinBox()\r\n self.MoveStep.setMaximum(1000000)\r\n self.MoveStep.setMinimum(-1000000)\r\n #self.MoveStep.setStyleSheet(\"background-color: green\")\r\n \r\n self.absMvtButton=QToolButton()\r\n \r\n self.absMvtButton.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconPlay,self.iconPlay))\r\n \r\n self.absMvtButton.setMinimumHeight(50)\r\n self.absMvtButton.setMaximumHeight(50)\r\n self.absMvtButton.setMinimumWidth(50)\r\n self.absMvtButton.setMaximumWidth(50)\r\n #self.absMvtButton.setStyleSheet(\"background-color: green\")\r\n hboxAbs.addWidget(absolueLabel)\r\n hboxAbs.addWidget(self.MoveStep)\r\n hboxAbs.addWidget(self.absMvtButton)\r\n vbox1.addLayout(hboxAbs)\r\n vbox1.addSpacing(10)\r\n hbox1=QHBoxLayout()\r\n self.moins=QToolButton()\r\n self.moins.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconMoins,self.iconMoins))\r\n \r\n self.moins.setMinimumHeight(70)\r\n self.moins.setMaximumHeight(70)\r\n self.moins.setMinimumWidth(70)\r\n self.moins.setMaximumWidth(70)\r\n \r\n #self.moins.setStyleSheet(\"border-radius:20px\")\r\n hbox1.addWidget(self.moins)\r\n \r\n self.jogStep=QDoubleSpinBox()\r\n self.jogStep.setMaximum(1000000)\r\n self.jogStep.setMaximumWidth(130)\r\n self.jogStep.setStyleSheet(\"font: bold 12pt\")\r\n self.jogStep.setValue(self.jogValue)\r\n \r\n hbox1.addWidget(self.jogStep)\r\n \r\n \r\n self.plus=QToolButton()\r\n self.plus.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconPlus,self.iconPlus))\r\n self.plus.setMinimumHeight(70)\r\n self.plus.setMaximumHeight(70)\r\n self.plus.setMinimumWidth(70)\r\n self.plus.setMaximumWidth(70)\r\n #self.plus.setStyleSheet(\"border-radius:20px\")\r\n hbox1.addWidget(self.plus)\r\n \r\n vbox1.addLayout(hbox1)\r\n #vbox1.addStretch(10)\r\n vbox1.addSpacing(10)\r\n \r\n hbox2=QHBoxLayout()\r\n self.stopButton=QToolButton()\r\n self.stopButton.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconStop,self.iconStop))\r\n \r\n #self.stopButton.setStyleSheet(\"border-radius:20px;background-color: red\")\r\n self.stopButton.setMaximumHeight(70)\r\n self.stopButton.setMaximumWidth(70)\r\n self.stopButton.setMinimumHeight(70)\r\n self.stopButton.setMinimumWidth(70)\r\n hbox2.addWidget(self.stopButton)\r\n vbox2=QVBoxLayout()\r\n \r\n self.showRef=QPushButton('Show Ref')\r\n self.showRef.setMaximumWidth(90)\r\n vbox2.addWidget(self.showRef)\r\n self.scan=QPushButton('Scan')\r\n self.scan.setMaximumWidth(90)\r\n vbox2.addWidget(self.scan)\r\n hbox2.addLayout(vbox2)\r\n \r\n vbox1.addLayout(hbox2)\r\n vbox1.addSpacing(10)\r\n \r\n self.REF1 = REF1M(num=1)\r\n \r\n self.REF2 = REF1M(num=2)\r\n \r\n self.REF3 = REF1M(num=3)\r\n \r\n self.REF4 = REF1M(num=4)\r\n \r\n self.REF5 = REF1M(num=5)\r\n \r\n self.REF6 = REF1M(num=6)\r\n \r\n grid_layoutRef = QGridLayout()\r\n grid_layoutRef.setVerticalSpacing(4)\r\n grid_layoutRef.setHorizontalSpacing(4)\r\n grid_layoutRef.addWidget(self.REF1,0,0)\r\n grid_layoutRef.addWidget(self.REF2,0,1)\r\n grid_layoutRef.addWidget(self.REF3,1,0)\r\n grid_layoutRef.addWidget(self.REF4,1,1)\r\n grid_layoutRef.addWidget(self.REF5,2,0)\r\n grid_layoutRef.addWidget(self.REF6,2,1)\r\n \r\n self.widget6REF=QWidget()\r\n self.widget6REF.setLayout(grid_layoutRef)\r\n vbox1.addWidget(self.widget6REF)\r\n # vbox1.setContentsMargins(0,0,0,0)\r\n self.setLayout(vbox1)\r\n \r\n \r\n self.absRef=[self.REF1.ABSref,self.REF2.ABSref,self.REF3.ABSref,self.REF4.ABSref,self.REF5.ABSref,self.REF6.ABSref] \r\n self.posText=[self.REF1.posText,self.REF2.posText,self.REF3.posText,self.REF4.posText,self.REF5.posText,self.REF6.posText]\r\n self.POS=[self.REF1.Pos,self.REF2.Pos,self.REF3.Pos,self.REF4.Pos,self.REF5.Pos,self.REF6.Pos]\r\n self.Take=[self.REF1.take,self.REF2.take,self.REF3.take,self.REF4.take,self.REF5.take,self.REF6.take]\r\n \r\n self.actionButton()\r\n self.jogStep.setFocus()\r\n self.refShow()\r\n \r\n \r\n \r\n \r\n def actionButton(self):\r\n '''\r\n buttons action setup \r\n '''\r\n \r\n self.unitBouton.currentIndexChanged.connect(self.unit) # unit change\r\n self.absMvtButton.clicked.connect(self.MOVE)\r\n self.plus.clicked.connect(self.pMove) # jog + foc\r\n self.plus.setAutoRepeat(False)\r\n self.moins.clicked.connect(self.mMove)# jog - fo\r\n self.moins.setAutoRepeat(False) \r\n self.scan.clicked.connect(lambda:self.open_widget(self.scanWidget) ) \r\n self.zeroButton.clicked.connect(self.Zero) # reset display to 0\r\n \r\n #self.refZeroButton.clicked.connect(self.RefMark) # todo\r\n \r\n self.stopButton.clicked.connect(self.StopMot)#stop motors \r\n self.showRef.clicked.connect(self.refShow) # show references widgets\r\n self.shootCibleButton.clicked.connect(self.ShootAct)\r\n iii=1\r\n for saveNameButton in self.posText: # reference name\r\n nbRef=str(iii)\r\n saveNameButton.textChanged.connect(self.savName)\r\n saveNameButton.setText(str(self.conf[0].value(self.motor[0]+\"/ref\"+nbRef+\"Name\"))) # print ref name\r\n iii+=1 \r\n for posButton in self.POS: # button GO\r\n posButton.clicked.connect(self.ref) # go to reference value\r\n eee=1 \r\n for absButton in self.absRef: \r\n nbRef=str(eee)\r\n absButton.setValue(float(self.conf[0].value(self.motor[0]+\"/ref\"+nbRef+\"Pos\"))/self.unitChange) # save reference value\r\n absButton.editingFinished.connect(self.savRef) # sauv value\r\n eee+=1\r\n \r\n for takeButton in self.Take:\r\n takeButton.clicked.connect(self.take) # take the value \r\n \r\n \r\n def open_widget(self,fene):\r\n \r\n \"\"\" open new widget \r\n \"\"\"\r\n \r\n if fene.isWinOpen==False:\r\n #New widget\"\r\n fene.show()\r\n fene.isWinOpen=True\r\n \r\n else:\r\n #fene.activateWindow()\r\n fene.raise_()\r\n fene.showNormal()\r\n \r\n \r\n \r\n def refShow(self):\r\n \r\n if self.refShowId==True:\r\n #self.resize(368, 345)\r\n self.widget6REF.show()\r\n self.refShowId=False\r\n self.showRef.setText('Hide Ref')\r\n self.setFixedSize(430,800)\r\n \r\n else:\r\n #print(self.geometry())\r\n \r\n self.widget6REF.hide()\r\n self.refShowId=True\r\n #self.setGeometry(QRect(107, 75, 429, 315))\r\n #self.setMaximumSize(368, 345)\r\n self.showRef.setText('Show Ref')\r\n# print(self.sizeHint())\r\n# self.minimumSizeHint()\r\n# print(self.sizeHint())\r\n# self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)\r\n #self.setMaximumSize(300,300)\r\n self.setFixedSize(430,380)\r\n \r\n #self.updateGeometry()\r\n \r\n def MOVE(self):\r\n '''\r\n absolue mouvment\r\n '''\r\n \r\n a=float(self.MoveStep.value())\r\n a=float(a*self.unitChange) # changement d unite\r\n if aself.butePos[0] :\r\n print( \"STOP : Butée Positive\")\r\n self.butPosButt.setChecked(True)\r\n self.MOT[0].stopMotor()\r\n else :\r\n self.MOT[0].move(a)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False)\r\n \r\n def pMove(self):\r\n '''\r\n action jog + foc \r\n '''\r\n a=float(self.jogStep.value())\r\n a=float(a*self.unitChange)\r\n b=self.MOT[0].position()\r\n \r\n if b+a>self.butePos[0] :\r\n print( \"STOP : Positive switch\")\r\n self.MOT[0].stopMotor()\r\n self.butPosButt.setChecked(True)\r\n else :\r\n self.MOT[0].rmove(a)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False)\r\n def mMove(self): \r\n '''\r\n action jog - foc\r\n '''\r\n a=float(self.jogStep.value())\r\n a=float(a*self.unitChange)\r\n b=self.MOT[0].position()\r\n if b-aself.butePos[i] :\r\n print( \"STOP : positive switch\")\r\n self.butPosButt.setChecked(True)\r\n self.MOT[i].stopMotor()\r\n else :\r\n self.MOT[i].move(vref)\r\n self.butNegButt.setChecked(False)\r\n self.butPosButt.setChecked(False) \r\n#\r\n def savName(self) :\r\n '''\r\n Save reference name\r\n '''\r\n sender=QtCore.QObject.sender(self)\r\n nbRef=sender.objectName()[0] #PosTExt1\r\n vname=self.posText[int(nbRef)-1].text()\r\n for i in range (0,1):\r\n self.conf[i].setValue(self.motor[i]+\"/ref\"+nbRef+\"Name\",str(vname))\r\n self.conf[i].sync()\r\n#\r\n def savRef (self) :\r\n '''\r\n save reference value\r\n '''\r\n sender=QtCore.QObject.sender(self)\r\n nbRef=sender.objectName()[0] # nom du button ABSref1\r\n \r\n vref=int(self.absRef[int(nbRef)-1].value())*self.unitChange\r\n self.conf[0].setValue(self.motor[0]+\"/ref\"+nbRef+\"Pos\",vref) # on sauvegarde en step dans le fichier ini\r\n self.conf[0].sync()\r\n \r\n def ShootAct(self):\r\n try: \r\n self.tir.TirAct() \r\n except: pass\r\n \r\n def closeEvent(self, event):\r\n \"\"\" \r\n When closing the window\r\n \"\"\"\r\n self.fini()\r\n time.sleep(0.1)\r\n event.accept()\r\n \r\n def fini(self): \r\n '''\r\n a the end we close all the thread \r\n '''\r\n self.thread.stopThread()\r\n self.isWinOpen=False\r\n time.sleep(0.1) \r\n if self.scanWidget.isWinOpen==True:\r\n self.scanWidget.close()\r\n \r\nclass REF1M(QWidget):\r\n \r\n def __init__(self,num=0, parent=None):\r\n super(REF1M, self).__init__()\r\n self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt6'))\r\n self.wid=QWidget()\r\n self.id=num\r\n self.vboxPos=QVBoxLayout()\r\n p = pathlib.Path(__file__)\r\n sepa=os.sep\r\n self.icon=str(p.parent) + sepa + 'icons' +sepa\r\n self.posText=QLineEdit('ref')\r\n self.posText.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n self.posText.setStyleSheet(\"font: bold 15pt\")\r\n self.posText.setObjectName('%s'%self.id)\r\n# self.posText.setMaximumWidth(80)\r\n self.vboxPos.addWidget(self.posText)\r\n self.iconTake=self.icon+\"disquette.PNG\"\r\n self.iconTake=pathlib.Path(self.iconTake)\r\n self.iconTake=pathlib.PurePosixPath(self.iconTake)\r\n self.take=QToolButton()\r\n self.take.setObjectName('%s'%self.id)\r\n self.take.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconTake,self.iconTake))\r\n self.take.setMaximumWidth(30)\r\n self.take.setMinimumWidth(30)\r\n self.take.setMinimumHeight(30)\r\n self.take.setMaximumHeight(30)\r\n self.takeLayout=QHBoxLayout()\r\n self.takeLayout.addWidget(self.take)\r\n\r\n self.iconGo=self.icon+\"go.PNG\"\r\n self.iconGo=pathlib.Path(self.iconGo)\r\n self.iconGo=pathlib.PurePosixPath(self.iconGo)\r\n self.Pos=QToolButton()\r\n self.Pos.setStyleSheet(\"QToolButton:!pressed{border-image: url(%s);background-color: transparent ;border-color: gray;}\"\"QToolButton:pressed{image: url(%s);background-color: gray ;border-color: gray}\"%(self.iconGo,self.iconGo))\r\n self.Pos.setMinimumHeight(30)\r\n self.Pos.setMaximumHeight(30)\r\n self.Pos.setMinimumWidth(30)\r\n self.Pos.setMaximumWidth(30)\r\n self.PosLayout=QHBoxLayout()\r\n self.PosLayout.addWidget(self.Pos)\r\n self.Pos.setObjectName('%s'%self.id)\r\n #○self.Pos.setStyleSheet(\"background-color: rgb(85, 170, 255)\")\r\n Labelref=QLabel('Pos :')\r\n Labelref.setMaximumWidth(30)\r\n Labelref.setStyleSheet(\"font: 9pt\" )\r\n self.ABSref=QDoubleSpinBox()\r\n self.ABSref.setMaximum(500000000)\r\n self.ABSref.setMinimum(-500000000)\r\n self.ABSref.setValue(123456)\r\n self.ABSref.setMaximumWidth(80)\r\n self.ABSref.setObjectName('%s'%self.id)\r\n self.ABSref.setStyleSheet(\"font: 9pt\" )\r\n \r\n grid_layoutPos = QGridLayout()\r\n grid_layoutPos.setVerticalSpacing(5)\r\n grid_layoutPos.setHorizontalSpacing(10)\r\n grid_layoutPos.setAlignment(QtCore.Qt.AlignmentFlag.AlignHCenter | QtCore.Qt.AlignmentFlag.AlignVCenter)\r\n grid_layoutPos.addLayout(self.takeLayout,0,0)\r\n grid_layoutPos.addLayout(self.PosLayout,0,1)\r\n grid_layoutPos.addWidget(Labelref,1,0)\r\n grid_layoutPos.addWidget(self.ABSref,1,1)\r\n \r\n \r\n self.vboxPos.addLayout(grid_layoutPos)\r\n self.wid.setStyleSheet(\"background-color: rgb(60, 77, 87);border-radius:10px\")\r\n \r\n self.wid.setLayout(self.vboxPos)\r\n mainVert=QVBoxLayout()\r\n mainVert.addWidget(self.wid)\r\n mainVert.setContentsMargins(0,0,0,0)\r\n self.setLayout(mainVert)\r\n\r\n\r\nclass PositionThread(QtCore.QThread):\r\n '''\r\n Secon thread to display the position\r\n '''\r\n import time #?\r\n POS=QtCore.pyqtSignal(float) # signal of the second thread to main thread to display motors position\r\n ETAT=QtCore.pyqtSignal(str)\r\n def __init__(self,parent=None,mot='',motorType=''):\r\n super(PositionThread,self).__init__(parent)\r\n self.MOT=mot\r\n self.motorType=motorType\r\n self.parent=parent\r\n self.motorTypeName=self.parent.motorTypeName\r\n self.stop=False\r\n# print('motor type',self.motorTypeName)\r\n def run(self):\r\n while True:\r\n if self.stop==True:\r\n break\r\n else:\r\n \r\n Posi=(self.MOT.position())\r\n time.sleep(0.5)\r\n \r\n try :\r\n self.POS.emit(Posi)\r\n \r\n time.sleep(0.1)\r\n \r\n except:\r\n print('error emit')\r\n if self.motorTypeName[0]=='RSAI': \r\n try :\r\n etat=self.MOT.etatMotor()\r\n# print(etat)\r\n self.ETAT.emit(etat)\r\n except: pass\r\n #print('error emit etat') \r\n \r\n def ThreadINIT(self):\r\n self.stop=False \r\n \r\n def stopThread(self):\r\n self.stop=True\r\n time.sleep(0.1)\r\n self.terminate()\r\n \r\n\r\n\r\nif __name__ =='__main__':\r\n \r\n appli=QApplication(sys.argv)\r\n \r\n \r\n mot5=ONEMOTORGUI( mot='tiltLat',motorTypeName='A2V',showRef=False,unit=1,jogValue=1)\r\n mot5.show()\r\n mot5.startThread2()\r\n appli.exec_()","sub_path":"oneMotorGuiNew.py","file_name":"oneMotorGuiNew.py","file_ext":"py","file_size_in_byte":31499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"106347852","text":"# issue #1847\n\nfrom threading import Thread\nimport faulthandler\n\nimport gym\n\nfaulthandler.enable()\n\n\ndef make_t2():\n print(1)\n\n\ndef make_t1():\n th = Thread(target=make_t2)\n th.start()\n\n\n# env = gym.make('MsPacman-v4')\n# env = gym.make('CartPole-v0')\n\nt = Thread(target=make_t1)\nt.start()\n","sub_path":"issues/individual_issue.py","file_name":"individual_issue.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"572187389","text":"from lmfit import Parameter, Parameters, minimize\n\nfrom larch import Group, isgroup, parse_group_args\n\nfrom larch.utils import index_of\nfrom larch_plugins.xray import xray_edge, xray_line, f1_chantler, f2_chantler, f1f2\nfrom larch_plugins.xafs import set_xafsGroup, find_e0, preedge\n\nimport numpy as np\nfrom scipy.special import erfc\n\nMAXORDER = 6\n\ndef match_f2(p, en=0, mu=1, f2=1, e0=0, em=0, weight=1, theta=1, order=None,\n leexiang=False):\n \"\"\"\n Objective function for matching mu(E) data to tabulated f''(E) using the MBACK\n algorithm and, optionally, the Lee & Xiang extension.\n \"\"\"\n pars = p.valuesdict()\n eoff = en - e0\n\n norm = p['a']*erfc((en-em)/p['xi']) + p['c0'] # erfc function + constant term of polynomial\n for i in range(order): # successive orders of polynomial\n j = i+1\n attr = 'c%d' % j\n if attr in p:\n norm += p[attr] * eoff**j\n func = (f2 + norm - p['s']*mu) * theta / weight\n if leexiang:\n func = func / p['s']*mu\n return func\n\n\ndef mback(energy, mu=None, group=None, order=3, z=None, edge='K', e0=None, emin=None, emax=None,\n whiteline=None, leexiang=False, tables='chantler', fit_erfc=False, return_f1=False,\n _larch=None):\n \"\"\"\n Match mu(E) data for tabulated f''(E) using the MBACK algorithm and,\n optionally, the Lee & Xiang extension\n\n Arguments:\n energy, mu: arrays of energy and mu(E)\n order: order of polynomial [3]\n group: output group (and input group for e0)\n z: Z number of absorber\n edge: absorption edge (K, L3)\n e0: edge energy\n emin: beginning energy for fit\n emax: ending energy for fit\n whiteline: exclusion zone around white lines\n leexiang: flag to use the Lee & Xiang extension\n tables: 'chantler' (default) or 'cl'\n fit_erfc: True to float parameters of error function\n return_f1: True to put the f1 array in the group\n\n Returns:\n group.f2: tabulated f2(E)\n group.f1: tabulated f1(E) (if return_f1 is True)\n group.fpp: matched data\n group.mback_params: Group of parameters for the minimization\n\n References:\n * MBACK (Weng, Waldo, Penner-Hahn): http://dx.doi.org/10.1086/303711\n * Lee and Xiang: http://dx.doi.org/10.1088/0004-637X/702/2/970\n * Cromer-Liberman: http://dx.doi.org/10.1063/1.1674266\n * Chantler: http://dx.doi.org/10.1063/1.555974\n \"\"\"\n order=int(order)\n if order < 1: order = 1 # set order of polynomial\n if order > MAXORDER: order = MAXORDER\n\n ### implement the First Argument Group convention\n energy, mu, group = parse_group_args(energy, members=('energy', 'mu'),\n defaults=(mu,), group=group,\n fcn_name='mback')\n if len(energy.shape) > 1:\n energy = energy.squeeze()\n if len(mu.shape) > 1:\n mu = mu.squeeze()\n\n group = set_xafsGroup(group, _larch=_larch)\n\n if e0 is None: # need to run find_e0:\n e0 = xray_edge(z, edge, _larch=_larch)[0]\n if e0 is None:\n e0 = group.e0\n if e0 is None:\n find_e0(energy, mu, group=group)\n\n\n ### theta is an array used to exclude the regions emax, and\n ### around white lines, theta=0.0 in excluded regions, theta=1.0 elsewhere\n (i1, i2) = (0, len(energy)-1)\n if emin is not None: i1 = index_of(energy, emin)\n if emax is not None: i2 = index_of(energy, emax)\n theta = np.ones(len(energy)) # default: 1 throughout\n theta[0:i1] = 0\n theta[i2:-1] = 0\n if whiteline:\n pre = 1.0*(energye0+float(whiteline))\n theta = theta * (pre + post)\n if edge.lower().startswith('l'):\n l2 = xray_edge(z, 'L2', _larch=_larch)[0]\n l2_pre = 1.0*(energyl2+float(whiteline))\n theta = theta * (l2_pre + l2_post)\n\n\n ## this is used to weight the pre- and post-edge differently as\n ## defined in the MBACK paper\n weight1 = 1*(energye0)\n weight = np.sqrt(sum(weight1))*weight1 + np.sqrt(sum(weight2))*weight2\n ## get the f'' function from CL or Chantler\n if tables.lower() == 'chantler':\n f1 = f1_chantler(z, energy, _larch=_larch)\n f2 = f2_chantler(z, energy, _larch=_larch)\n else:\n (f1, f2) = f1f2(z, energy, edge=edge, _larch=_larch)\n group.f2=f2\n if return_f1:\n group.f1=f1\n\n em = xray_line(z, edge.upper(), _larch=_larch)[0] # erfc centroid\n\n params = Parameters()\n params.add(name='s', value=1, vary=True) # scale of data\n params.add(name='xi', value=50, vary=fit_erfc, min=0) # width of erfc\n params.add(name='a', value=0, vary=False) # amplitude of erfc\n if fit_erfc:\n params['a'].value = 1\n params['a'].vary = True\n\n for i in range(order): # polynomial coefficients\n params.add(name='c%d' % i, value=0, vary=True)\n\n out = minimize(match_f2, params, method='leastsq',\n gtol=1.e-5, ftol=1.e-5, xtol=1.e-5, epsfcn=1.e-5,\n kws = dict(en=energy, mu=mu, f2=f2, e0=e0, em=em,\n order=order, weight=weight, theta=theta, leexiang=leexiang))\n\n opars = out.params.valuesdict()\n eoff = energy - e0\n\n norm_function = opars['a']*erfc((energy-em)/opars['xi']) + opars['c0']\n for i in range(order):\n j = i+1\n attr = 'c%d' % j\n if attr in opars:\n norm_function += opars[attr]* eoff**j\n\n group.e0 = e0\n group.fpp = opars['s']*mu - norm_function\n group.mback_params = opars\n tmp = Group(energy=energy, mu=group.f2-norm_function, e0=0)\n\n # calculate edge step from f2 + norm_function: should be very smooth\n pre_f2 = preedge(energy, group.f2+norm_function, e0=e0, nnorm=2, nvict=0)\n group.edge_step = pre_f2['edge_step'] / opars['s']\n\n pre_fpp = preedge(energy, mu, e0=e0, nnorm=2, nvict=0)\n\n group.norm = (mu - pre_fpp['pre_edge']) / group.edge_step\n\n\ndef registerLarchPlugin(): # must have a function with this name!\n return ('_xafs', { 'mback': mback })\n","sub_path":"plugins/xafs/mback.py","file_name":"mback.py","file_ext":"py","file_size_in_byte":6255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"369267003","text":"\"\"\"\nOverview\n========\n\nHighlight html lines where errors/warnings were encountered by Html Tidy.\n\nWhen the plugin is installed in your vyrc, whenever an event\nof the type in BETA mode happens it runs tidy against the file\nand tags all regions where tidy found errors. \n\nIt is possible to jump to these regions by using the keycommands implemented by\nthe core text_spots plugin. \n\nOne would just jump back/next by pressing or \nin NORMAL mode. \n\nThe html checker plugin writes to sys.stdout all the errours\nthat were encountered in the html file. it is necessary\nto set an output target on areavi instance in order to check\nthe errors/warnings.\n\nFor more information see: vyapp.plugins.text_spots\n\nPlugin dependencies: \n vyapp.plugins.text_spots\n\nExtern dependencies:\n Html Tidy\n\nKey-Commands\n============\n\nNamespace: html-checker\n\n\"\"\"\n\nfrom subprocess import Popen, STDOUT, PIPE\nfrom vyapp.areavi import AreaVi\nfrom vyapp.plugins import ENV\nfrom vyapp.app import root\nfrom re import findall\nimport sys\n\nclass HtmlChecker(object):\n def __init__(self, area, path='tidy'):\n self.area = area\n # The path that tidy stays, in some\n # systems it may not be available in the\n # PATH variable.\n self.path = path\n\n area.install('html-checker', (-1, '<>', lambda event: \n self.area.hook('BETA', '', self.check)),\n (-1, '<>', lambda event: \n self.area.unhook('BETA', '')),\n (-1, '<>', lambda event: \n self.area.hook('BETA', '', self.check)),\n (-1, '<>', lambda event: \n self.area.unhook('BETA', '')))\n\n def check(self, event):\n child = Popen([self.path, '-e', '-quiet', \n self.area.filename], stdout=PIPE, stderr=STDOUT)\n output = child.communicate()[0]\n regex = 'line ([0-9]+) column ([0-9]+) - (.+)'\n ranges = findall(regex, output)\n\n sys.stdout.write('Errors:\\n%s\\n' % output)\n for line, col, error in ranges:\n self.area.tag_add('(SPOT)', '%s.0' % line, \n '%s.0 lineend' % line)\n\n if child.returncode:\n root.status.set_msg('Errors were found!')\n else:\n root.status.set_msg('No errors!')\n self.area.chmode('NORMAL')\n\ninstall = HtmlChecker\n\n\n\n\n","sub_path":"vyapp/plugins/html_checker.py","file_name":"html_checker.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"392551191","text":"# -*- coding: utf-8 -*-\n#---------------------------------------\n# Programming:QiuShiBaiKe\n# version:0.1\n# author:wyy\n# data:2017-01-06\n# language:Python 3.5.2\n# tools : requests\n# function:get text\n#---------------------------------------\n\nimport urllib.parse\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\nurl = \"http://www.qiushibaike.com/text/\"\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}\n\nflag = True\ni = 1\nwhile flag:\n html = requests.get(url, headers=headers)\n soup = BeautifulSoup(html.text, 'lxml')\n\n # get text\n qsbkText = soup.findAll('div', {'class': 'content'})\n with open('./Data/qsbkReq.txt', 'a+', encoding='utf-8') as textFile:\n textFile.write('\\n' + str(i) + '\\n')\n for item in qsbkText:\n textFile.write(item.text)\n textFile.write('\\n' + '---' * 30 + '\\n')\n time.sleep(3)\n\n # exist next url\n if soup.find('span', {'class': 'next'}) == None:\n flag = False\n\n # get link\n qsbkIndex = soup.find('ul', {'class': 'pagination'}).findAll('a')\n linkList = []\n for link in qsbkIndex:\n linkList.append(link['href'])\n url = 'http://' + urllib.parse.urlparse(url)[1] + linkList[-1]\n\n i = i + 1\n print(flag)\n","sub_path":"05Web/pachong/QSBK/QSBKRequests.py","file_name":"QSBKRequests.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"579854350","text":"#\n# meteo-station obv BME280 Digitale Barometer Druk en Vochtigheid Sensor Module\n#\n# bron: https://www.tinytronics.nl/shop/nl/sensoren/temperatuur-lucht-vochtigheid/bme280-digitale-barometer-druk-en-vochtigheid-sensor-module\n# Een zeer compacte barometer die werkt via I2C of SPI. De BME280 is een 3-in-1 module\n# die temperatuur, druk en vochtigheid kan meten.\n#\n# De module kan alleen gevoed worden met 3.3VDC. De I2C/SPI werkt dus ook met 3.3V en\n# je hebt dus een level converter nodig bij gebruik van bijv. een 5V Arduino Uno.\n#\n# Het standaard I2C adres van deze module is 0x76. Dit moet mogelijk in de\n# voorbeeldcode/library veranderd worden van 0x77 naar 0x76. Indien je de SDO pin\n# verbind met Vcc, dan wordt het I2C adres 0x77.\n#\n# (Arduino) project met de ESP2866 en BME280 (nuttig voor aansluitingen) is te vinden op\n# https://core-electronics.com.au/projects/thingspeak-temperature-pressure-logger\n#\n# MicroPython library voor de BME280 en ESP2866 gevonden op GitHub:\n# https://github.com/triplepoint/micropython_bme280_i2c\n#\n# upload files to device:\n# ampy --port /dev/ttyUSB0 put main.py\n# ampy --port /dev/ttyUSB0 put bme280_i2c.py\n#\n# open console en start programma\n# screen /dev/ttyUSB0 115200\n# type enter-toets\n# en type cntrl-D\n#\n# BvH, 26-05-2019\n#\n\n\n# LIBRARIES:\n#\n# We start by importing the Pin class from the machine library, as this will enable us to use\n# the GPIO pins. We need to use a wait-time in the loop and import the sleep function from the\n# time library.\nfrom machine import Pin, I2C\nfrom time import sleep\n# using mqtt for exchanging data\nfrom umqttsimple import MQTTClient\n#\n# The bme280_i2c library assumes the default connection of the I2C bus\n# On Wymos D1 mini devices that is SCL-to-D1 (pin5), SDA-to-D2 (pin4).\n#\nimport bme280_i2c\n\n# Variabelen:\n#temp_min = 100\n#temp_max = 0\n#pres_min = 10000\n#pres_max = 0\n#humi_min = 100\n#humi_max = 0\n\n# Functies:\ndef do_tripple_blink(n=3):\n # tripple blink\n for x in range(n):\n led.on()\n sleep(0.5)\n led.off()\n\ndef update_measurements():\n # how to deal with a 'dict'?\n # Example from https://www.tutorialspoint.com/python/python_dictionary.htm\n # dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\n # print \"dict['Name']: \", dict['Name']\n values = bme.read_compensated_data(result = None)\n\n# INITIALISATIE:\n#\n# Next we create an object called led which will store the GPIO pin that we wish to use, and\n# whether it is an input or an output. In this case it is an output as we wish to light up the LED.\n#\n# see pinout on https://escapequotes.net/esp8266-wemos-d1-mini-pins-and-diagram/\n# pin 16 = D0 (naar LED)\nled = Pin(16, Pin.OUT)\n# show succesfull\ndo_tripple_blink()\n\n# Initialise the i2c interface.\n# pin 5 (= D1) SCL naar BME280-SCL.\n# pin 4 (= D2) SDA naar BME280-SDA.\ni2cbus = I2C(sda=Pin(4), scl=Pin(5))\ni2cbus.scan()\n# Initialise the Bosch temperature/humidity/pressure sensor.\nbme = BME280_I2C(i2c=i2cbus)\n# show succesfull\ndo_tripple_blink()\n\n# setup MQTT connection\ndef sub_cb(topic, msg):\n print((topic, msg))\n if topic == b'notification' and msg == b'received':\n print('ESP8266-wijngaar-Achthoeven received a mqtt-message!')\n\ndef connect_and_subscribe():\n global client_id, mqtt_server, topic_sub\n client = MQTTClient(client_id, mqtt_server)\n client.set_callback(sub_cb)\n client.connect()\n client.subscribe(topic_sub)\n print('Connected to %s mqtt-broker, subscribed to %s topic' % (mqtt_server, topic_sub))\n return client\n\ndef restart_and_reconnect():\n print('Failed to connect to mqtt-broker. Reconnecting...')\n time.sleep(10)\n machine.reset()\n\ntry:\n client = connect_and_subscribe()\nexcept OSError as e:\n print('Failed connecting to mqtt-broker. Error=' + e)\n restart_and_reconnect()\n\n\n# All in an endless loop:\nwhile True:\n # So now we need to turn on the LED, and it is as easy as this!\n led.on()\n # retrieve BME280-measurements:\n update_measurements()\n # show BME280-measurements\n print('temperature : ' + values['temperature'])\n print('humidity : ' + values['humidity'])\n print('pressure : ' + values['pressure'])\n payload = values['temperature'] + ',' + values['humidity'] + ',' + values['pressure']\n # better version:\n #values = read_compensated_data(result = None)\n # wait\n sleep(0.5)\n # and turn off the LED\n led.off()\n # once a minute, send a message with the data to the mqtt broker\n try:\n client.check_msg()\n if (time.time() - last_message) > message_interval:\n msg = b'measurement #%d' % counter\n# msg = b'measurement #%d' + payload % counter\n client.publish(topic_pub, msg)\n last_message = time.time()\n counter += 1\n except OSError as e:\n restart_and_reconnect()\n\n # wait and measure approx. every 15 secs\n sleep(measure_interval-0.5)\n","sub_path":"esp8266_Wemos_d1_mini/temp_humi_pres_bme280_i2c_lib/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"442698926","text":"import configparser\nimport pymongo\nimport os\n\n# Get env variables for database configuration\nMONGODB_URL = os.environ.get('MONGODB_URL', None)\nDATABASE_NAME = os.environ.get('DATABASE_NAME', None)\nDATASET_COLLECTION_NAME = os.environ.get(\n 'DATASET_COLLECTION_NAME', 'future_trends')\n\nclass MongoDatabase:\n def __init__(self):\n print(\"Establishing connection to the database\")\n if MONGODB_URL is None or DATABASE_NAME is None:\n raise Exception(\n 'Database could not be identified. Make sure they are added to environment variables')\n\n self.connection_string = MONGODB_URL\n self.client = pymongo.MongoClient(self.connection_string)\n self.database = self.client[DATABASE_NAME]\n\n self.verify_connection()\n\n def reset_connection(self):\n self.client = pymongo.MongoClient(self.connection_string)\n\n def verify_connection(self):\n for _ in range(5):\n try:\n self.client.server_info()\n print(\"Connected to the database\")\n return\n except:\n self.reset_connection()\n\n raise \"Failed to connect to the database\"\n\n\nclass FutureTrendsDatabase(MongoDatabase):\n def __init__(self):\n MongoDatabase.__init__(self)\n\n def get_future_trends_collection(self) -> pymongo.collection:\n return self.database[DATASET_COLLECTION_NAME]\n\n def get_future_trends_by_filter(self, filter):\n return list(self.get_future_trends_collection().find(filter))\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"616975068","text":"import time\nimport pandas as pd\nimport numpy as np\nimport statistics\n\n\"\"\"\nTO_DO:\n- handle extraneous user input later for city and date filtering\n(see lesson referenced in 3.code walkthrough)\n\"\"\"\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n cities = ['chicago', 'new york', 'washington']\n city = input(\"Would you like to see information for Chicago, New York, or Washington?\\n\")\n city = city.lower()\n while (city not in cities):\n city = input(\"Sorry, that is not a valid city, please check your spelling and enter a valid city to proceed.\\n\")\n city = city.lower()\n\n # get user input for month (all, january, february, ... , june)\n date = input(\"Would you like to filter your data by month? (yes or no)\\n\")\n date = date.lower()\n\n elig_input = ['yes', 'y', 'no', 'n']\n while (date not in elig_input):\n date = input(\"Sorry, that is not a valid response, please respond 'yes' or 'no':\")\n date = date.lower()\n\n month = 'all'\n if date == 'yes' or date == 'y':\n month = input(\"Which month, January, February, March, April, May, or June?\\n\")\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = month.lower()\n while (month not in months):\n month = input(\"Sorry, that is an invalid month, please input one of the following months:['January', 'February', 'March', 'April', 'May', 'June']:\\n\")\n month = month.lower()\n\n # get user input for day of week (all, monday, tuesday, ... sunday)\n\n date = 'new'\n date = input(\"Would you like to filter your data by day of the week? (yes or no)\\n\")\n date = date.lower()\n\n elig_input = ['yes', 'y', 'no', 'n']\n while (date not in elig_input):\n date = input(\"Sorry, that is not a valid response, please respond 'yes' or 'no':\")\n date = date.lower()\n\n day = 'all'\n if date == 'yes' or date == 'y':\n day = input(\"Which day of the week (please input as 'Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday')\\n\")\n days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']\n day = day.lower()\n while(day not in days):\n day = input(\"Sorry, that is an invalid day, please input a valid day of the week:\")\n day = day.lower()\n day = day.lower()\n\n print (city, month, day)\n\n print('-'*40)\n return city, month, day\n\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['weekday_name'] = df['Start Time'].dt.weekday_name\n df['hour'] = df['Start Time'].dt.hour\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['weekday_name'] == day.title()]\n\n return df\n\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n print(\"The most common month is: %i.\" % statistics.mode(df['month']))\n\n # display the most common day of week\n print(\"The most common day of the week is: %s.\" % statistics.mode(df['weekday_name']))\n\n # display the most common start hour\n print(\"The most common hour is: %i.\" % statistics.mode(df['hour']))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n print(\"The most common start station is: %s\" % statistics.mode(df['Start Station']))\n\n\n # display most commonly used end station\n print(\"The most common end station is: %s\" % statistics.mode(df['End Station']))\n\n\n # display most frequent combination of start station and end station trip\n df['Round Trip'] = df['Start Station'] + \", \" + df['End Station']\n print(\"The most common combination of start and end station is: %s\" % statistics.mode(df['Round Trip']))\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n print(\"The total travel time for these rides is: %i minutes\" % (df['Trip Duration'].sum()/60 + df['Trip Duration'].sum() % 60))\n\n\n # display mean travel time\n print(\"The mean travel time for these rides is %i minutes\" % (df['Trip Duration'].mean()/60 + df['Trip Duration'].mean() % 60))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n print(\"Total users by type:\\n\")\n print(df['User Type'].value_counts())\n print(\"\\n\")\n\n # Display counts of gender\n print(\"Total users by gender:\\n\")\n print(df['Gender'].value_counts())\n print(\"\\n\")\n\n\n # Display earliest, most recent, and most common year of birth\n print(\"The earliest, most recent, and most common year of birth is %i, %i, and %i, respectively\"\n % (df['Birth Year'].min(), df['Birth Year'].max(), statistics.mode(df['Birth Year'])))\n print(\"\\n\")\n\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":7719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"569262307","text":"#!/usr/bin/python\n# coding=utf-8\nimport zipfile\nimport shutil\nimport os\nimport xlrd\nimport sys\n\nreload(sys) \nsys.setdefaultencoding('utf8') \n\n#当前目录\ncur_dir = sys.path[0]\n\n#输出目录\nout_dir = 'laka-apks'\n\ntmp_dir = os.path.abspath(os.path.join(cur_dir,os.path.pardir))\n\nout_dir = os.path.abspath(os.path.join(tmp_dir,os.path.pardir)) + '/' + out_dir\n\n# 目录不存在则创建\nif not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\n# 空文件 便于写入此空文件到apk包中作为channel文件\nsrc_empty_file = cur_dir + '/info/czt.txt'\n# 创建一个空文件(不存在则创建)\nf = open(src_empty_file, 'w') \nf.close()\n\nprint('cur_dir : ' + cur_dir)\n\n# 获取当前目录中所有的apk源包\nsrc_apks = []\n# python3 : os.listdir()即可,这里使用兼容Python2的os.listdir('.')\nfor file in os.listdir(cur_dir):\n fulldirfile = os.path.join(cur_dir, file)\n print('file : ' + file)\n if os.path.isfile(fulldirfile):\n extension = os.path.splitext(file)[1][1:]\n print('extension : ' + extension)\n if extension in 'apk':\n src_apks.append(fulldirfile)\n\n# 获取渠道列表\n# channel_file = 'info/channel.txt'\n# f = open(channel_file)\n# lines = f.readlines()\n# f.close()\n\n#读渠道excel\nchannel_file = cur_dir + '/info/channels.xls'\ndata = xlrd.open_workbook(channel_file)\ntable = data.sheets()[0]\nnrows = table.nrows\n\n\nfor src_apk in src_apks:\n # file name (with extension)\n src_apk_file_name = os.path.basename(src_apk)\n # 分割文件名与后缀\n temp_list = os.path.splitext(src_apk_file_name)\n # name without extension\n src_apk_name = temp_list[0]\n # 后缀名,包含. 例如: \".apk \"\n src_apk_extension = temp_list[1]\n \n # 创建生成目录,与文件名相关\n output_dir = out_dir + '/' + src_apk_name + '/'\n\n print('output_dir : ' + output_dir)\n \n # 目录不存在则创建\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n \n # 遍历渠道号并创建对应渠道号的apk文件\n # for line in lines:\n # 获取当前渠道号,因为从渠道文件中获得带有\\n,所有strip一下\n # target_channel = line.strip()\n # 拼接对应渠道号的apk\n # target_apk = output_dir + src_apk_name + \"-\" + target_channel + src_apk_extension \n # 拷贝建立新apk\n # shutil.copy(src_apk, target_apk)\n # zip获取新建立的apk文件\n # zipped = zipfile.ZipFile(target_apk, 'a', zipfile.ZIP_DEFLATED)\n # 初始化渠道信息\n # empty_channel_file = \"META-INF/cztchannel_{channel}\".format(channel = target_channel)\n # 写入渠道信息\n # zipped.write(src_empty_file, empty_channel_file)\n # 关闭zip流\n # zipped.close()\n \n # 遍历渠道号并创建对应渠道号的apk文件\n for i in range(1, nrows):\n # 获取当前渠道id\n target_channel_id = str(table.cell(i,0).value)\n\n # 获取当前渠道名\n target_channel_name = str(table.cell(i,1).value)\n # 拼接对应渠道号的apk\n target_apk = output_dir + src_apk_name + \"-\" + target_channel_id + \"-\" + target_channel_name + src_apk_extension\n # 拷贝建立新apk\n shutil.copy(src_apk, target_apk)\n # zip获取新建立的apk文件\n zipped = zipfile.ZipFile(target_apk, 'a', zipfile.ZIP_DEFLATED)\n # 初始化渠道信息\n empty_channel_file = \"META-INF/cztchannel_{channel}\".format(channel = target_channel_id)\n # 写入渠道信息\n zipped.write(src_empty_file, empty_channel_file)\n # 关闭zip流\n zipped.close()\n\n \n","sub_path":"channel/MultiChannelBuildTool.py","file_name":"MultiChannelBuildTool.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"131108856","text":"# Author: Harsh Kohli\n# Date created: 5/24/2018\n\nimport yaml\nfrom utils.ioutils import read_word_embeddings, read_marco_train_data, read_marco_dev_data\nimport pickle\n\nconfig = yaml.safe_load(open('config.yml', 'r'))\nword_to_id_lookup, embeddings = read_word_embeddings(config['embedding_path'])\n\nprimary_train_data = read_marco_train_data(config['train_path'], word_to_id_lookup)\ndev_data = read_marco_dev_data(config['dev_path'], word_to_id_lookup)\n\nall_data = {'train_data': primary_train_data, 'dev_data': dev_data, 'word_to_id_lookup': word_to_id_lookup,\n 'embeddings': embeddings}\npickle_file = open(config['preprocessed_data_path'], 'wb')\npickle.dump(all_data, pickle_file, protocol=pickle.HIGHEST_PROTOCOL)\npickle_file.close()\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"128759659","text":"\r\nwith open(\"data/day5.txt\") as data:\r\n\tfull_input=data.read().rstrip()\r\n\r\n\r\ndef reduce(long,remove_char):\r\n\treturn long.replace((remove_char)+(remove_char.upper()),\"\").replace((remove_char.upper())+(remove_char),\"\")\r\n\r\ndef polymer_reduction(polymer):\r\n\twhile True:\r\n\t\tlen_before = len(polymer)\r\n\t\tfor ch in range(ord(\"a\"),ord(\"z\")+1):\r\n\t\t\tpolymer = reduce(polymer,chr(ch))\r\n\t\tif(len(polymer)==len_before):\r\n\t\t\treturn polymer\r\n\r\nreduced_length = len(polymer_reduction(full_input))\r\n\r\nprint(f\"pt1: {reduced_length}\")\r\n\r\n# pt2\r\n\r\nmin_length = reduced_length\r\n\r\nfor ch in range(ord(\"a\"),ord(\"z\")+1):\r\n\tchar_stripped_polymer = full_input.replace(chr(ch),\"\").replace(chr(ch).upper(),\"\")\r\n\tchar_stripped_reduced = polymer_reduction(char_stripped_polymer)\r\n\tif(len(char_stripped_reduced) < min_length):\r\n\t\tmin_length = len(char_stripped_reduced)\r\n\r\nprint(f\"pt2: {min_length}\")\r\n\r\n","sub_path":"day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"23607691","text":"from django.conf.urls.defaults import *\nfrom django.views.generic import TemplateView\nfrom tastypie.api import Api\nfrom cart.resources import SocialCartResource, PersonalCartResource\nfrom cart import views\n\n\nv1_api = Api(api_name='v1')\nv1_api.register(SocialCartResource())\nv1_api.register(PersonalCartResource())\n\nurlpatterns = patterns('',\n (r'^api/', include(v1_api.urls)),\n\n url(r'^social_mockup/$', TemplateView.as_view(template_name='cart/social_mockup.j.html')),\n\n url(r'^personal/$', views.personal_cart, name='cart.personal_cart'),\n url(r'^social/$', views.social_cart, name='cart.social_cart'),\n\n url(r'^preview_social_cart/$', views.preview_social_cart, name='cart.preview_social_cart'),\n url(r'^preview_personal_cart/$', views.preview_personal_cart, name='cart.preview_personal_cart'),\n\n url(r'^approve_social_cart/$', views.approve_cart, { 'cart': 'social' }, name='cart.approve_social_cart'),\n url(r'^approve_personal_cart/$', views.approve_cart, { 'cart': 'personal' }, name='cart.approve_personal_cart'),\n\n url(r'^cancel_pending_transaction/$', views.cancel_pending_transaction, name='cart.cancel_pending_transaction'),\n\n #url(r'^approved/$', views.approved_tags, name='cart.approved_tags'),\n)\n","sub_path":"apps/cart/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"43876309","text":"#!/usr/bin/env python3.6\n# Daydreamer.py\n# Author: Shawn Beaulieu\n# August 7th, 2018\n\n\nfrom Daydreamer import Daydreamer\n\ndef main():\n\n\n params = {\n\n 'render': True,\n 'phi_length': 4,\n 'epochs': 20,\n 'environments': {0:'MontezumaRevenge-v0', 1:'Frostbite-v0'},\n 'latent_dim': 32,\n 'gamma': 0.9,\n 'epsilon': 1.0,\n 'action_space': 18,\n 'vae_params': {\n\n 'blueprint': [84*84, 200, 100, 32], #105*80 after flattening\n 'convolutions': 0,\n \"batch_size\": 4000,\n \"regularizer\": 1E-6,\n \"learning_rate\": 3E-4,\n \"dropout\": True,\n \"dropout_rate\": 0.50,\n \"num_classes\": 0\n\n }\n\n }\n\n Daydreamer(params)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Run_Daydreamer.py","file_name":"Run_Daydreamer.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"20741505","text":"_base_ = [\n '../_base_/datasets/imagenet_bs64_swin_224.py',\n '../_base_/schedules/imagenet_bs1024_adamw_swin.py',\n '../_base_/default_runtime.py',\n]\n\nmodel = dict(\n type='ImageClassifier',\n backbone=dict(\n type='XCiT',\n patch_size=8,\n embed_dims=512,\n depth=24,\n num_heads=8,\n mlp_ratio=4,\n qkv_bias=True,\n layer_scale_init_value=1e-5,\n tokens_norm=True,\n out_type='cls_token',\n ),\n head=dict(\n type='LinearClsHead',\n num_classes=1000,\n in_channels=512,\n loss=dict(type='CrossEntropyLoss', loss_weight=1.0),\n ),\n train_cfg=dict(augments=[\n dict(type='Mixup', alpha=0.8),\n dict(type='CutMix', alpha=1.0),\n ]),\n)\n\n# dataset settings\ntrain_dataloader = dict(batch_size=128)\n","sub_path":"configs/xcit/xcit-medium-24-p8_8xb128_in1k.py","file_name":"xcit-medium-24-p8_8xb128_in1k.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"438483641","text":"import heapq\ndef djikstra(graph,start,final,n):\n costs = {}\n pq = []\n heapq.heappush(pq,(0,start))\n while pq:\n cur_cost , cur_v = heapq.heappop(pq)\n if costs[cur_v] < cur_cost:\n continue\n if cur_v not in costs:\n costs[cur_v] = cur_cost\n for cost, next_v in graph[cur_v]:\n next_cost = cur_cost + cost\n heapq.heappush(pq,(next_cost,next_v))\n \n if len(costs) == start:\n return costs[final]\n else:\n return -1","sub_path":"DataStructures/Priority_Queue_and_HEAP/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"25187883","text":"main = input('Please enter a number: ')\ni = len(main)\ntry:\n main = int(main)\n calc = []\n a = 0\n while i != 1:\n a = (main // 10 ** (i-1)) % 10\n calc.append(a)\n i -= 1\n b = main % 10\n calc.append(b)\n print(max(calc))\nexcept ValueError:\n print('Number should be entered')\n\n\n","sub_path":"lesson_1/lesson1_task4.py","file_name":"lesson1_task4.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"114084740","text":"from vedo import *\n\nman = Mesh(dataurl+'man.vtk').c('k9').lighting('glossy')\nfloor = Box(length=9, width=9, height=0.1).z(-1.6).c('white')\ncube = Cube().pos(2,-2,-0.4)\n\np1 = Point([1,0,1], c='red5')\np2 = Point([0,1,2], c='green5')\np3 = Point([-1,-0.5,1], c='blue5')\n\n# Add light sources at the given positions\nl1 = Light(p1)\nl2 = Light(p2)\nl3 = Light(p3)\n\nplt = Plotter(bg='blackboard')\nplt.addShadows()\nplt.show(man, floor, cube, l1, l2, l3, p1, p2, p3)\n\n\n\n","sub_path":"examples/basic/shadow2.py","file_name":"shadow2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"72051522","text":"\"\"\"\nPlace news articles into the following 7 categories:\n\n Society (includes Politics, Elections, Legislation, Incidents, Crime)\n Economy (includes Markets, Finance, Business)\n Technology (includes Gadgets, Auto, Apps, Internet services)\n Sports (includes E-Sports)\n Entertainment (includes Movies, Music, Games, Books, Arts)\n Science (includes Health, Biology, Physics, Genetics)\n Other (news articles that don't fall into any of the above categories)\nFake implementation\n\"\"\"\nimport random\nfrom tgnews.etl import get_file\n\ndef category(file):\n\n return random.choice([\"society\", \"economy\", \"technology\", \"sports\", \n \"entertainment\", \"science\", \"other\"])\n\n\ndef categories(file_list):\n\n category_list = {\n \"society\": [],\n \"economy\": [],\n \"technology\": [],\n \"sports\": [],\n \"entertainment\": [],\n \"science\": [],\n \"other\": []\n }\n\n for f in file_list:\n\n file = get_file(f)\n cat = category(file)\n\n category_list[cat].append(f)\n\n return category_list\n","sub_path":"tgnews/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"564508626","text":"if __name__ != \"__main__\":\n # importing module\n from ciphers.Caesar import Caesar\n from ciphers.Vigenere import Vigenere\n\nelse:\n # __name__ == \"__main__\"\n from Caesar import Caesar\n from Vigenere import Vigenere\n import random\n\n print(\"String to be encrypted:\", \"--------------------------------\", sep='\\n')\n _data = \"Lorem ipsum dolor sit amet enim.\"\n print(_data, \"\\n\")\n\n caesar_offset = random.randint(0, 26)\n print(\"Caesar: %d\" % caesar_offset, \"--------------------------------\", sep='\\n')\n caesar_encrypted = Caesar.encrypt(_data, caesar_offset, original=True)\n caesar_decrypted = Caesar.decrypt(caesar_encrypted, caesar_offset, original=True)\n print(caesar_encrypted, caesar_decrypted, \"\", sep='\\n')\n\n vigenere_key = \"secret_key\"\n print(\"Vigenere: %s\" % vigenere_key, \"--------------------------------\", sep='\\n')\n vigenere_encrypted = Vigenere.encrypt(_data, vigenere_key, original=True)\n vigenere_decrypted = Vigenere.decrypt(vigenere_encrypted, vigenere_key, original=True)\n print(vigenere_encrypted, vigenere_decrypted, \"\", sep='\\n')\n","sub_path":"ciphers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"486918470","text":"# -*- encoding: utf-8 -*-\nfrom grab import Grab\nimport codecs\ng = Grab(log_file='out.html')\nfrom newspaper import Article\nfrom bs4 import BeautifulSoup\nimport re\nimport csv\nimport io\nimport gzip\nimport unicodedata as ucd\nimport sys\n\n#----------------------------------------------------------------\n\nsearch=\"Банан\"\n\n#----------------------------------------------------------------\n\n\n#file=open('C:\\\\Users\\\\USK\\\\Desktop\\\\aa\\\\parser\\\\out.txt','r')\n#e=list()\n#for i in file:\n# e.append(i.strip('\\n'))\n#e.pop(0)\n#d=dict()\n#for i in e:\n# d[i.split(':')[0]]=i.split(':')[1]\n \n#file.close()\n\n\n\n\n#sr=d['q']\npop=''\nurl='https://news.yandex.kz/yandsearch?text='+search+'+'+pop+'&rpt=nnews2&grhow=clutop'+'&p='\na=list()\n\n\nfor i in range(0,10):\n try:\n g.go(url+str(i))\n print(url+str(i))\n #g.doc.set_input(\"q\",\"grab\")\n #g.doc.submit(submit_name = 'btnK')\n #print g.doc.select('//head/title').text()\n\n for el in g.doc.select('//li[@class=\"search-item\"]'):\n soup=BeautifulSoup(el.html(),'lxml')\n for link in soup.findAll('a', attrs={'href': re.compile(\"^http://\")}):\n a.append(link.get('href'))\n except:\n break\n\nd=dict()\nc=0\nprint('---------------------------------')\n#from Com import Com\nr=list()\nwith codecs.open(\"withnewspaper.csv\", \"w\", \"utf-8\") as file:\n file.write('publishedAt,title,author,url,urlToImage,description,comments'+'\\r\\n')\n for i in a:\n print(i)\n url = i\n article = Article(url)\n article.download()\n article.parse()\n # p=Com(url)\n #print(p.get_comment)\n title=article.title\n authors=article.authors\n publish_date=article.publish_date\n text=article.text\n top_image=article.top_image\n '''print(type(title.encode('UTF-8')))\n print(type(authors))\n print(type(str(publish_date)))\n print(type(text))\n print(type(top_image))'''\n html=(article.html)\n soup = BeautifulSoup(html,'lxml')\n p=\"\"\n try:\n soup=(soup.find('div', {'id':'comments'}))\n data = soup.findAll(text=True)\n \n for i in (data):\n p+=(i.strip())+':'\n\n except:\n p= (\"None\")\n if(len(str(publish_date))>0):\n file.write(str(publish_date)+',')\n file.write(title+',')\n file.write(' '.join([str(x) for x in authors])+ ',')\n file.write(i+',')\n file.write(top_image+',')\n file.write(text+',')\n file.write(p)\n file.write('\\r\\n')\n\n\n \n \n \n\n\n\n\n\n '''print title\n print authors\n print publish_date\n print text\n print top_image'''\n \n '''if title!=None:\n r.append({'title':title})\n else:\n r.append({'title':''})\n \n if publish_date!=None:\n r.append({'publishedAt':publish_date})\n else:\n r.append({'publishedAt':''})\n \n if authors!=None:\n r.append({'author':authors})\n else:\n r.append({'author':''})\n \n if top_image!=None:\n r.append({'urlToImage':top_image})\n else:\n r.append({'urlToImage':''})\n \n if text!=None:\n r.append({'description':(text)})\n else:\n r.append({'description':''})\n r.append({'url':i})'''\n '''try:\n if(publish_date!=None):\n file.write(publish_date)\n file.write(',')\n if(len(title)>0):\n file.write(title)\n file.write(',')\n if(authors!=None):\n file.write(authors)\n file.write(',')\n file.write(str(i))\n file.write(',')\n if(top_image!=None):\n file.write(top_image)\n file.write(',')\n if(text!=None):\n file.write(text)\n file.write('\\n')\n except:\n file.write('\\n')'''\n \n \n \n \n\n \n #print \"----------------\"\n\n #writer.writerow(({'publishedAt': str(article.publish_date), 'title': str(article.title), 'author': str(article.authors), 'url': i, 'urlToImage': str(article.top_image), 'description': str(article.text) }))\n #writer.write( article.publish_date, article.title, article.authors, i, article.top_image, article.text,\"\\n\" )\n \n \n","sub_path":"Parser with Newspaper and Grab/yandexwithnewspaper.py","file_name":"yandexwithnewspaper.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"625668985","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Topic, Timer\nfrom .services import register_user_topic, is_topic_occupied, is_registration_open\nfrom .exceptions import NoStudentError, OccupiedTopicError, RegistrationClosedError\nfrom django.contrib import messages\n\n\n@login_required(login_url='/users/login/')\ndef topic_registration(request):\n topic_name_list = []\n for topic in Topic.objects.filter(professor=request.user.professor):\n occupied, by_current_user = is_topic_occupied(request.user, topic)\n topic_name_list.append((topic.name, occupied, by_current_user))\n timer = Timer.objects.first()\n context = {\n 'topic_name_list': topic_name_list,\n 'start_date': timer.start_date.strftime(\"%Y-%m-%d %H:%M\"),\n 'end_date': timer.end_date.strftime(\"%Y-%m-%d %H:%M\")\n }\n return render(request, 'topic_registration/topic_registration.html', context)\n\n\n@login_required(login_url='/users/login/')\ndef topic_register(request):\n try:\n if not is_registration_open():\n raise RegistrationClosedError\n selected_topic = request.POST['topic']\n register_user_topic(request.user, selected_topic)\n messages.success(request, 'Rejestracja zakonczona pomyslnie')\n except KeyError:\n messages.error(request, 'Nie wybrano tematu')\n except NoStudentError:\n messages.error(request, 'Tylko student moze zarejestrowac temat')\n except OccupiedTopicError:\n messages.error(request, 'Wybrany temat jest juz zarezerwowany')\n except RegistrationClosedError:\n messages.error(request, 'Rejestracja jest zamknieta')\n except Exception:\n messages.error(request, 'Nieoczekiwany blad')\n return redirect('topic_registration:topic_registration')\n","sub_path":"topic_registration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"267593509","text":"from pathlib import Path\n\ntry:\n from tqdm.auto import tqdm\nexcept ModuleNotFoundError:\n tqdm = list\n\nroot_path = Path(__file__) / \"..\"\nroot_path = root_path.resolve()\n\nsrc_file = root_path / \"russian.txt\"\nout_file = root_path / \"russian_utf-8.txt\"\n\nif out_file.exists():\n out_file.unlink()\n\nwith src_file.open(\"r\", encoding=\"windows-1251\") as src, out_file.open(\"w\", encoding=\"utf-8\") as out:\n for line in tqdm(src.readlines()):\n line = line.strip(\"- \\n\")\n out.write(line + \"\\n\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"569454178","text":"from collections import deque\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\r\n if not nums:\r\n return []\r\n\r\n ans = []\r\n # 单调双向队列,从左到右递减,存储数的下标\r\n q = deque()\r\n for i in range(len(nums)):\r\n # 移除队列右边所有不大于当前数的item\r\n while len(q) > 0 and nums[i] >= nums[q[-1]]:\r\n q.pop()\r\n # 队列右边添加当前数的索引\r\n q.append(i)\r\n # 如果队列左边的下标(对应滑动窗口的最大值)位于滑动窗口外,则移除它\r\n if i - k >= q[0]:\r\n q.popleft()\r\n # 添加当前的最大值到结果集中\r\n if i >= k - 1:\r\n ans.append(nums[q[0]])\r\n return ans\r\n","sub_path":"0239. Sliding Window Maximum/solution_deque.py","file_name":"solution_deque.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"366011559","text":"\"\"\"Send a slack notification.\"\"\"\n# coding: utf-8\n\nfrom slacker import Slacker\nimport envdir\nimport os\nimport tempfile\n\nfrom . import constants as c\n\n\nslack = None\nDON = '@dmmfll'\n\n\ndef get_slack_client():\n \"\"\"Slack client.\"\"\"\n global slack\n if slack is None:\n envdir.open(os.path.expanduser('/home/dmmmd/slack_envdir/'))\n token = os.environ['WYNCODE']\n slack = Slacker(token)\n return slack\n\n\ndef send_notification(message='test message', recipient=DON, as_user=True):\n \"\"\"Send slack message to me.\n\n If kwarg username is added, it is the name of the bot. as_user has to\n then be False.\n\n \"\"\"\n slack = get_slack_client()\n slack.chat.post_message(recipient, message, as_user=as_user)\n\n\ndef search_for_id(first, last):\n \"\"\"Search for slack user id from first, last.\n\n :returns: slack_id\n \"\"\"\n slack = get_slack_client()\n response = slack.users.list()\n members = response.body['members']\n slack_ids = tuple(member['name']\n for member in members\n if all(name_.lower()\n in member['profile']['real_name'].lower()\n for name_ in (first, last)))\n return slack_ids\n\n\ndef upload_grading_markdown(resources, content, recipient=DON):\n \"\"\"Post a file to a channel.\n\n :returns: response\n \"\"\"\n slack = get_slack_client()\n keys = (\n 'content',\n 'filetype',\n 'filename',\n 'title',\n 'initial_comment',\n 'channels'\n )\n values = [\n c.MD,\n c.DOT.join(('{}', c.MD)),\n 'Copy of Good Measure comments for {}',\n 'I graded the homework exercise _{}_',\n recipient,\n ]\n values = [item.format(\n resources\n .config['question'][c.TEXT].split(c.CR)[c.LAST]) or None\n for item in values]\n values.insert(c.FIRST, content) # can't format content has {}\n assert len(keys) == len(values)\n data = dict(zip(keys, values))\n # filepath = tempfile.NamedTemporaryFile(delete=False).name\n\n tmp = tempfile.NamedTemporaryFile(delete=False).name\n return slack.files.upload(tmp, **data)\n\n\ndef upload_grading_pdf(resources, filepath, recipient=DON):\n \"\"\"Post a file to a channel.\n\n :returns: response\n \"\"\"\n slack = get_slack_client()\n keys = (\n 'filetype',\n 'title',\n 'initial_comment',\n 'channels'\n )\n values = [\n c.PDF,\n 'Copy of Good Measure comments for {}',\n 'I graded the homework exercise _{}_',\n recipient,\n ]\n values = [item.format(\n resources\n .config['question'][c.TEXT].split(c.CR)[c.LAST]) or None\n for item in values]\n data = dict(zip(keys, values))\n\n return slack.files.upload(filepath, **data)\n\n\ndef main():\n \"\"\"Main.\"\"\"\n send_notification()\n return 0\n","sub_path":"goodmeasure_cli/slack_notification.py","file_name":"slack_notification.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"225438875","text":"import visualization\nimport xyPlot\nimport displayGroupOdbToolset as dgo\nimport os, glob, inspect\nimport sys\nsys.path.append('C:\\\\Users\\\\doktor\\\\PycharmProjects\\\\InputFilesBuild')\nimport globalPar as gp\n\nreload(gp)\n\ndef write_to_files(line, dispFiles):\n if isinstance(dispFiles, list):\n for file in dispFiles:\n file.write(line)\n else:\n dispFiles.write(line)\n\ndef write_header(dispFiles):\n # Header - only on file initialization\n line_with_param = 'id' + semicolon + 'delta' + semicolon + 'alpha' + semicolon + 'velocity' + semicolon + 'time' \\\n + semicolon + 's' + semicolon + 'Tm' + semicolon + 'm'\n write_to_files(line_with_param, dispFiles)\n\n # Header - only on file initialization\n for key in odbLabels.keys():\n if not odbLabels[key]['labels']:\n line = semicolon + str(key)\n write_to_files(line, dispFiles)\n\n else:\n for label in odbLabels[key]['labels']:\n line = semicolon + str(label)\n write_to_files(line, dispFiles)\n\ndef close_files(dispFiles):\n for file in dispFiles:\n file.close()\n\npc = gp.ParametersClass()\nsemicolon = ';'\ncomma = ','\n\npath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +'\\\\workingDirectory\\\\'\nos.chdir(path)\n\ngp.scandirs(path)\n\n\n# DispFiles\nfilenames=['vumat_approx.csv']\ndispFiles=[open(filenames[0], 'a')] #dispFiles=[open(filenames[0], 'a'), open(filenames[1], 'a')]\n\n# Reading ODB Labels - for that one of the ODB files has to be open\nfile = glob.glob(\"*.odb\")[0]\no1 = session.openOdb(name=path + file)\nodb = session.odbs[path + file]\nstep = odb.steps['Step-1']\n\nodbLabels = gp.get_labels(step)\nodb.close()\n\n# Writing Header\nfor df in dispFiles:\n try:\n if os.stat(df.name).st_size == 0:\n write_header(df)\n except OSError as e:\n print(e)\n\n\nfor file in glob.glob(\"*.odb\"):\n print('Opening file: {0}'.format(file))\n o1 = session.openOdb(name=path + file)\n odb = session.odbs[path + file]\n step = odb.steps['Step-1']\n\n #odbLabels = gp.get_labels(step)\n\n # Data rows\n alpha, Tm, m, velocity_m_s, Dxx = gp.get_additional_parameters_ext(file)\n time = pc.s / (float(velocity_m_s) * 1000) ##velocity in mm/s\n print('Retrieving data for: alpha = {0}, Tm = {1}, m = {2}, vel = {3}, Dxx = {4}'.format(alpha, Tm, m, velocity_m_s, Dxx))\n for id, frame in enumerate(step.frames):\n line ='\\n' + str(id) + semicolon + str(Dxx) + semicolon + str(alpha) + semicolon + str(velocity_m_s) \\\n + semicolon + str(time) + semicolon + str(pc.s) + semicolon + str(Tm) + semicolon + str(m)\n write_to_files(line, dispFiles)\n\n for key in odbLabels.keys():\n if not odbLabels[key]['labels']:\n line = semicolon + str(frame.fieldOutputs[key].values[0].data)\n write_to_files(line, dispFiles)\n\n else:\n for label in odbLabels[key]['labels']:\n if key == 'S':\n line = semicolon + str(frame.fieldOutputs[key].getScalarField(componentLabel=label).values[0].data)\n write_to_files(line, dispFiles)\n else:\n line = semicolon + str(frame.fieldOutputs[key].getScalarField(componentLabel=label).values[7].data)\n write_to_files(line, dispFiles)\n odb.close()\n print('Done.')\n\nclose_files(dispFiles)","sub_path":"3_2_abaqus_OdbReader.py","file_name":"3_2_abaqus_OdbReader.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"615865607","text":"import datetime\r\nfrom scapy.all import *\r\n\r\nPACKETS_TO_SNIFF = 32\r\nLOG_PATH = 'Log.txt'\r\nRESOURCES_PATH = 'resources/'\r\nIP_BLACKLIST_PATH = RESOURCES_PATH + 'ip_blacklist.txt'\r\nFILES_BLACKLIST_PATH = RESOURCES_PATH + 'files_blacklist.txt'\r\nURL_BLACKLIST_PATH = RESOURCES_PATH + 'url_blacklist.txt'\r\n\r\n\r\n\r\nclass firewall:\r\n\tdef __init__(self):\r\n\t\tself.log = open(LOG_PATH, 'a+')\r\n\t\tself.ip_black_list = ['']\r\n\t\tself.url_black_list = ['']\r\n\t\tself.file_black_list = ['']\r\n\t\twith open(IP_BLACKLIST_PATH, 'r') as ip_file:\r\n\t\t\tself.ip_black_list = [line.rstrip('\\n') for line in ip_file]\r\n\t\twith open(URL_BLACKLIST_PATH, 'r') as url_file:\r\n\t\t\tself.url_black_list = [line.rstrip('\\n') for line in url_file]\r\n\t\twith open(FILES_BLACKLIST_PATH, 'r') as files_file:\r\n\t\t\tself.file_black_list = [line.rstrip('\\n') for line in files_file]\r\n\r\n\r\n\tdef cheack_packet(self, packet):\r\n\t\tself.compare_to_blacklist(packet)\r\n\r\n\r\n\tdef compare_to_blacklist(self, packet):\r\n\r\n\t\tif IP in packet:\r\n\t\t\tif packet[IP].src in self.ip_black_list:\r\n\t\t\t\tself.log.write('%s\\nsuspicous ip source\\nsource:\\t%s\\tdestination:\\t%s\\t%s\\n\\n' \r\n\t\t\t\t\t% (str(datetime.datetime.now()), packet[IP].src, packet[IP].dst, packet.summary()))\r\n\t\t\tif packet[IP].dst in self.ip_black_list:\r\n\t\t\t\tself.log.write('%s\\nsuspicous ip destination\\nsource:\\t%s\\tdestination:\\t%s\\t%s\\n\\n' \r\n\t\t\t\t\t% (str(datetime.datetime.now()), packet[IP].src, packet[IP].dst, packet.summary()))\r\n\r\n\r\n\t\tself.log.flush()\r\n\r\n\tdef check_syn_flood(self, capture_list):\r\n\t\t\"\"\" CODE \"\"\"\r\n\t\tpass\r\n\r\n\tdef firewall_run(self): \r\n\t\ttime_text = \"\\nbegan snnifing at:\\t%s\\n\\n\" % str(datetime.datetime.now())\r\n\t\tself.log.write(time_text)\r\n\t\tself.log.flush()\r\n\t\twhile True:\r\n\t\t\tsniff(PACKETS_TO_SNIFF, prn=self.cheack_packet)\r\n\r\n\r\ndef main():\r\n\tmain_firewall = firewall()\r\n\tmain_firewall.firewall_run()\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"End_Project.py","file_name":"End_Project.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"470425299","text":"\"\"\"Routines for running Edward's spectrometer using the Leiker/Force\nI/O card for Raspberry Pis\"\"\"\n#from threading import Thread, Lock\n#lck = Lock()\nfrom scipy.optimize import curve_fit\n#execfile(\"spectrometer.py\")\nfrom spectrometer import *\nimport os\n\nclass SignalGenerator:\n \"\"\"Routines for use with the Hittite syntesizer\n frequencies in MHz and power in dBm\"\"\"\n def __init__(self, ipAddress=\"192.168.0.70\"):\n self.lanio = \"lanio \" + ipAddress + \" \"\n self.freq = 0.0\n\n def setFreq(self, freq):\n \"\"\"Set the signal generator frequency in MHz\"\"\"\n os.system(self.lanio + \"\\\":FREQ \" + str(freq) + \" MHz\\\"\")\n self.freq = freq\n\n def getFreq(self):\n \"\"\"Get the signal generator frequency in MHz\"\"\"\n return float(os.popen(self.lanio + \"\\\"FREQ?\\\"\").read()) / 1000000\n\n def setPower(self, pwr):\n \"\"\"Set the signal generator power in dBm. \n With the Httite, stay above -42 dBm\"\"\"\n\n os.system(self.lanio + \"\\\":POW \" + str(pwr) + \" dBm\\\"\")\n os.system(self.lanio + \"\\\":OUTP 1\\\"\")\n\n def powerOff(self):\n os.system(self.lanio + \"\\\":OUTP 0\\\"\")\n\n def getPower(self):\n return os.system(self.lanio + \"\\\"POW?\\\"\")\n\nclass TestSpectrometer:\n def __init__(self,spec):\n self.spec = spec\n self.attenVals = np.zeros(32)\n self.zeroFit = np.array([0.0,0.0])\n\n def scanAtten(self, attenNumber = 0):\n \"\"\" Scan the attenuator over its range and measure the power at the peak\"\"\"\n for i in range(32):\n self.spec.setAtten(i)\n self.spec.sweep()\n ch0 = np.argmax(spec.vals)\n self.attenVals[i] = np.sum(self.spec.vals[ch0-1:ch0+2]-self.spec.zeros[ch0-1:ch0+2])\n# self.attenVals[i] = max(self.spec.vals)\n print(\"%d %d\" % (i, self.attenVals[i]))\n plt.plot(np.arange(15.5, -0.1, -0.5), 10*(np.log10(self.attenVals)- np.log10(32768)))\n plt.xlabel(\"Attenuation\")\n plt.ylabel(\"Max Signal (dB-full Scale)\")\n plt.title(\"Spectormeter %d's attenuator\" %(attenNumber))\n plt.show(block = False)\n \n def gaussian(self, x, amp, cen, wid):\n return amp * np.exp(-(((x-cen)/wid)**2) /2)\n \n def measureFilter(self, freq=10, power = -38, plot=True):\n \"\"\"Measure the yig fiklter response by doing 5 scans offset by 5MHz\n to get a more accurate measurement\"\"\"\n numPoints=7\n numFreqs=5\n vals = np.zeros(numPoints*numFreqs, dtype=np.int16)\n freqs = np.zeros(numPoints*numFreqs, dtype=float)\n savefStart = self.spec.fStart\n sg.setFreq(freq*1000)\n sg.powerOff()\n self.spec.sweep()\n zeros=np.copy(self.spec.vals)\n sg.setPower(power)\n for n in range(numFreqs):\n self.spec.fStart = savefStart + n* self.spec.df/numFreqs\n self.spec.sweep()\n if n == 0:\n ch0 = np.argmax(self.spec.vals) - int(numPoints/2)\n zero = np.average(zeros[ch0:ch0+numPoints])\n vals[n: numPoints*numFreqs:numFreqs] = self.spec.vals[ch0:ch0+numPoints] - zero\n freqs[n: numPoints*numFreqs:numFreqs] = self.spec.freqs[ch0:ch0+numPoints]\n self.spec.fStart=savefStart\n ch0 = np.argmax(vals)\n init_vals = [vals[ch0], freqs[ch0], .012]\n [amp, ctr, wid], covar = curve_fit(self.gaussian, freqs, vals, p0=init_vals)\n if plot:\n print(\"amp %d ctr %.4f, wid %.4f\" % (amp, ctr, wid))\n plt.plot(freqs, vals, label = \"measured data\")\n plt.plot(freqs, self.gaussian(freqs, amp, ctr, wid), label = \"Gaussian fit\")\n plt.legend()\n plt.show(block=False)\n else:\n return((freq, amp, ctr, wid))\n # np.savetxt('filter.txt', np.c_[freqs, vals], fmt = \"%.3f %d\")\n # print np.c_[freqs, vals,]\n \n def measureFrequencyScale(self, fStart=4.5, fStop=16.1, df=1):\n \"\"\" Measure the yig filter's response to a series of frequencies.\n Print frequency, amplitude, measured center freq and sigma of a gaussian\n fit. save in the file \"yigMeasurements\" in the current directory.\n Solve for a linear fit to the measured frequencies and suggest changes\n to the file yigConstants for the current spectrometer.\"\"\"\n\n d = []\n for f in np.arange(fStart, fStop, df):\n v = self.measureFilter(f, plot=False)\n d.append(v)\n print(\"%.2f %d %.4f %.5f\" % (v[0],v[1], v[2], v[3]))\n dt = np.array(d).transpose()\n coef = np.polyfit(dt[0], dt[2], 1)\n print(coef)\n print(\"change yig.freqOffset from %.4f to %.4f\" % (yig.freqOffset, yig.freqOffset-coef[1]))\n print(\"change yig.scaleFactor from %.5f to %.5f\" % (yig.scaleFactor, yig.scaleFactor/coef[0]))\n np.savetxt(\"yigMeasurements\", d, \"%.2f %d %.4f %.5f\")\n\n def showPeak(self):\n ch = np.argmax(self.spec.vals)\n print(\"The peak is %d at %.3f GHz\" % (self.spec.vals[ch], self.spec.freqs[ch]))\n \n# def runTwo():\n# print time.time()\n# p0 = mp.Process(target=self.spec0.main)\n# p1 = mp.Process(target=self.spec1.main)\n# p0.start()\n# p1.start()\n# print time.time()\n\n def hot(self, numInts = 1):\n self.spec.sweep()\n self.hotVals = np.array(self.spec.vals)\n if numInts > 1:\n for i in range(numInts-1):\n self.spec.sweep()\n self.hotVals += self.spec.vals\n# print \"i =%d val = %d hotVal = %d\" % (i, self.spec.vals[0], self.hotVals[0])\n self.hotVals /= numInts\n self.hotVals -= self.spec.zeros\n if self.spec.doPlot:\n plt.clf()\n plt.plot(self.spec.freqs, self.hotVals)\n plt.show(block = False)\n\n def cold(self, numInts = 1):\n self.spec.sweep()\n self.coldVals = np.array(self.spec.vals)\n if numInts > 1:\n for i in range(numInts-1):\n self.spec.sweep()\n self.coldVals += self.spec.vals\n# print \"i =%d val = %d coldVal = %d\" % (i, self.spec.vals[240], self.coldVals[240])\n self.coldVals /= numInts\n self.coldVals -= self.spec.zeros\n if self.spec.doPlot:\n plt.plot(self.spec.freqs, self.coldVals)\n plt.show(block = False)\n \n def zero(self):\n avg = np.zeros(self.spec.nSamp)\n \n for i in range(5):\n self.spec.sweep()\n avg += self.spec.vals\n avg /= 5\n self.zeroFit = np.polyfit(self.spec.freqs[20:],avg[20:],1)\n self.spec.zeros = np.polyval(self.zeroFit, self.spec.freqs)\n if self.spec.doPlot:\n plt.plot(self.spec.freqs,avg, self.spec.freqs, self.spec.zeros)\n plt.show(block = False)\n print(\"Fit const = %.1f slope %.2f std = %.2f\" % \\\n ( self.zeroFit[1], self.zeroFit[0], np.std(avg-self.spec.zeros)))\n \n def saveZero(self, fname=\"zeroParams\"):\n fn = '/instance/configFiles/' + fname + ( \"%d\" % (self.spec.number))\n# fd = open(fn, 'w')\n# fd.write(\"%.3f %.3f\" % (test.zeroFit[0], self.zeroFit[1]))\n np.savetxt(fn, self.zeroFit, \"%.3f\")\n\n def readZero(self, fname=\"zeroParams\"):\n fn = '/instance/configFiles/' + fname + ( \"%d\" % (self.spec.number))\n# fn = \"/home/smauser/\"+fname+\"%d\" % (self.spec.number)\n# fd = open(fn, 'r')\n self.zeroFit = np.genfromtxt(fn)\n freq = self.spec.fStart\n for i in range(self.spec.nSamp):\n self.spec.freqs[i] = freq\n freq += self.spec.df\n self.spec.zeros = np.polyval(self.zeroFit, self.spec.freqs)\n\n def Y(self, fname=\"Y.txt\"):\n Y = (self.hotVals)/(self.coldVals)\n np.savetxt(fname, np.c_[self.spec.freqs, self.hotVals, self.coldVals, Y], fmt = \"%.3f %d %d %.3f\")\n if self.spec.doPlot:\n plt.clf()\n plt.plot(self.spec.freqs, Y)\n plt.draw()\n","sub_path":"online/Linux/applications/pi/ScanningSpectrometer/test_spectrometer.py","file_name":"test_spectrometer.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"486587132","text":"#!/usr/bin/python\nimport argparse, os, tempfile, shutil, sys,math,pickle,itertools\nfrom subprocess import call, PIPE, STDOUT, Popen\nimport argparse\nimport datetime\nimport os\nparser = argparse.ArgumentParser(description='Submit job to batch')\nparser.add_argument('--config_file',type=str,dest=\"config_file\",default=1, help=\" config_file of the era\")\nparser.add_argument('--outputname',type=str,dest=\"outputname\",default=1, help=\"Run era\")\nparser.add_argument('--list',type=str,dest=\"list\",default=1, help=\"list of file to run\")\nparser.add_argument('--dirlist',type=str,dest=\"dirlist\",default=1, help=\"directory where are lists of file to run\")\nargs = parser.parse_args()\nconfig_file = args.config_file #path to the processed lumi JSON file\noutputname = args.outputname # which run\nlisttorun = args.list\ndirlist = args.dirlist\noutputdir = \"/eos/user/${USER:0:1}/$USER/JEC-task/HT_Condor_output/DijetRootTreeAnalyzer/\"+dirlist+'/'+datetime.date.today().isoformat()+'/'\ncmd4=\"./main \"+dirlist+listtorun+\" \"+config_file+\" dijets/events \"+outputdir+outputname+\" \"+outputdir+outputname\ncmd1=\"cd /afs/cern.ch/work/${USER:0:1}/$USER/JEC-task/CMSSW_8_0_31/src/CMSDIJET/DijetRootTreeAnalyzer/\"\ncmd2=\"export SCRAM_ARCH=slc6_amd64_gcc530\"\ncmd3=\"eval `scramv1 runtime -sh`\"\ncmd5=\"export X509_USER_PROXY=/afs/cern.ch/user/${USER:0:1}/$USER/.globus/gridproxy.cert\" \ncall(\"mkdir -p \"+outputdir+\" && \"+cmd1+\" && \"+cmd5+\" && \"+cmd2+\" && \"+cmd3+\" && \"+cmd4, shell=True )\nprint(cmd4)\n\n","sub_path":"Run_Analyser_short.py","file_name":"Run_Analyser_short.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"138282039","text":"import cv2\nimport RobotRaconteur as RR\nRRN = RR.RobotRaconteurNode.s\nimport RobotRaconteurCompanion as RRC\nimport argparse\nimport sys\nimport platform\nimport threading\nimport numpy as np\nfrom RobotRaconteurCompanion.Util.InfoFileLoader import InfoFileLoader\nfrom RobotRaconteurCompanion.Util.DateTimeUtil import DateTimeUtil\nfrom RobotRaconteurCompanion.Util.SensorDataUtil import SensorDataUtil\nfrom RobotRaconteurCompanion.Util.AttributesUtil import AttributesUtil\n\n\nclass CameraImpl(object):\n \n def __init__(self, device_id, width, height, fps, camera_info):\n \n #if platform.system() == \"Windows\":\n # self._capture = cv2.VideoCapture(device_id + cv2.CAP_DSHOW)\n #else:\n self._capture = cv2.VideoCapture(device_id)\n assert self._capture.isOpened(), f\"Could not open device: {device_id}\"\n\n self._seqno = 0\n\n self._capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n self._capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n self._capture.set(cv2.CAP_PROP_FPS, fps)\n\n self._imaging_consts = RRN.GetConstants('com.robotraconteur.imaging')\n self._image_consts = RRN.GetConstants('com.robotraconteur.image')\n self._image_type = RRN.GetStructureType('com.robotraconteur.image.Image')\n self._image_info_type = RRN.GetStructureType('com.robotraconteur.image.ImageInfo')\n self._compressed_image_type = RRN.GetStructureType('com.robotraconteur.image.CompressedImage')\n self._date_time_utc_type = RRN.GetPodDType('com.robotraconteur.datetime.DateTimeUTC')\n self._isoch_info = RRN.GetStructureType('com.robotraconteur.device.isoch.IsochInfo')\n self._capture_lock = threading.Lock()\n self._streaming = False\n self._fps = self._capture.get(cv2.CAP_PROP_FPS)\n self._camera_info = camera_info\n self._date_time_util = DateTimeUtil(RRN)\n self._sensor_data_util = SensorDataUtil(RRN)\n\n def RRServiceObjectInit(self, ctx, service_path):\n self._downsampler = RR.BroadcastDownsampler(ctx)\n self._downsampler.AddPipeBroadcaster(self.frame_stream)\n self._downsampler.AddPipeBroadcaster(self.frame_stream_compressed)\n self._downsampler.AddPipeBroadcaster(self.preview_stream)\n self._downsampler.AddWireBroadcaster(self.device_clock_now)\n self.frame_stream.MaxBacklog = 2\n self.frame_stream_compressed.MaxBacklog = 2\n self.preview_stream.MaxBacklog = 2\n \n # TODO: Broadcaster peek handler in Python\n self.device_clock_now.PeekInValueCallback = lambda ep: self._date_time_util.FillDeviceTime(self._camera_info.device_info,self._seqno)\n\n @property\n def device_info(self):\n return self._camera_info.device_info\n\n @property\n def camera_info(self):\n return self._camera_info\n\n def _cv_mat_to_image(self, mat):\n\n is_mono = False\n if (len(mat.shape) == 2 or mat.shape[2] == 1):\n is_mono = True\n\n image_info = self._image_info_type()\n image_info.width =mat.shape[1]\n image_info.height = mat.shape[0]\n if is_mono:\n image_info.step = mat.shape[1]\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"mono8\"]\n else:\n image_info.step = mat.shape[1]*3\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"bgr888\"]\n image_info.data_header = self._sensor_data_util.FillSensorDataHeader(self._camera_info.device_info,self._seqno)\n \n\n image = self._image_type()\n image.image_info = image_info\n image.data=mat.reshape(mat.size, order='C')\n return image\n\n def _cv_mat_to_compressed_image(self, mat, quality = 100):\n\n is_mono = False\n if (len(mat.shape) == 2 or mat.shape[2] == 1):\n is_mono = True\n\n image_info = self._image_info_type()\n image_info.width =mat.shape[1]\n image_info.height = mat.shape[0]\n \n image_info.step = 0\n image_info.encoding = self._image_consts[\"ImageEncoding\"][\"compressed\"]\n image_info.data_header = self._sensor_data_util.FillSensorDataHeader(self._camera_info.device_info,self._seqno)\n \n image = self._compressed_image_type()\n image.image_info = image_info\n res, encimg = cv2.imencode(\".jpg\",mat,[int(cv2.IMWRITE_JPEG_QUALITY), quality])\n assert res, \"Could not compress frame!\"\n image.data=encimg\n return image\n\n def capture_frame(self):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n raise RR.OperationFailedException(\"Could not read from camera\")\n self._seqno+=1\n return self._cv_mat_to_image(mat)\n\n def capture_frame_compressed(self):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n raise RRN.OperationFailedException(\"Could not read from camera\")\n self._seqno+=1\n return self._cv_mat_to_compressed_image(mat)\n\n def trigger(self):\n raise RR.NotImplementedException(\"Not available on this device\")\n\n def frame_threadfunc(self):\n while(self._streaming):\n with self._capture_lock:\n ret, mat=self._capture.read()\n if not ret:\n #TODO: notify user?\n self._streaming=False\n continue\n self._seqno+=1\n \n self.frame_stream.AsyncSendPacket(self._cv_mat_to_image(mat),lambda: None)\n self.frame_stream_compressed.AsyncSendPacket(self._cv_mat_to_compressed_image(mat),lambda: None)\n self.preview_stream.AsyncSendPacket(self._cv_mat_to_compressed_image(mat,70),lambda: None)\n device_now = self._date_time_util.FillDeviceTime(self._camera_info.device_info,self._seqno)\n self.device_clock_now.OutValue = device_now\n\n def start_streaming(self):\n if (self._streaming):\n raise RR.InvalidOperationException(\"Already streaming\")\n self._streaming=True\n t=threading.Thread(target=self.frame_threadfunc)\n t.start()\n\n def stop_streaming(self):\n if (not self._streaming):\n raise RR.InvalidOperationException(\"Not streaming\")\n self._streaming=False\n\n @property\n def isoch_downsample(self):\n return self._downsampler.GetClientDownsample(RR.ServerEndpoint.GetCurrentEndpoint())\n\n @isoch_downsample.setter\n def isoch_downsample(self, value):\n return self._downsampler.SetClientDownsample(RR.ServerEndpoint.GetCurrentEndpoint(),value)\n\n @property\n def isoch_info(self):\n ret = self._isoch_info()\n ret.update_rate = self._fps\n ret.max_downsample = 100\n ret.isoch_epoch = np.zeros((1,),dtype=self._date_time_utc_type)\n\n @property\n def capabilities(self):\n return 0x1 | 0x2 | 0x4\n\n \n\ndef main():\n parser = argparse.ArgumentParser(description=\"OpenCV based camera driver service for Robot Raconteur\")\n parser.add_argument(\"--camera-info-file\", type=argparse.FileType('r'),default=None,required=True,help=\"Camera info file (required)\")\n parser.add_argument(\"--device-id\", type=int, default=0, help=\"the device to open (default 0)\")\n parser.add_argument(\"--width\", type=int, default=1280, help=\"try to set width of image (default 1280)\")\n parser.add_argument(\"--height\", type=int, default=720, help=\"try to set height of image (default 720)\")\n parser.add_argument(\"--fps\", type=int, default=15, help=\"try to set rate of video capture (default 15 fps)\")\n parser.add_argument(\"--wait-signal\",action='store_const',const=True,default=False, help=\"wait for SIGTERM orSIGINT (Linux only)\")\n\n args, _ = parser.parse_known_args()\n\n rr_args = [\"--robotraconteur-jumbo-message=true\"] + sys.argv\n\n #RRN.RegisterServiceTypesFromFiles(['com.robotraconteur.imaging'],True)\n RRC.RegisterStdRobDefServiceTypes(RRN)\n\n with args.camera_info_file:\n camera_info_text = args.camera_info_file.read()\n\n info_loader = InfoFileLoader(RRN)\n camera_info, camera_ident_fd = info_loader.LoadInfoFileFromString(camera_info_text, \"com.robotraconteur.imaging.camerainfo.CameraInfo\", \"camera\")\n\n attributes_util = AttributesUtil(RRN)\n camera_attributes = attributes_util.GetDefaultServiceAttributesFromDeviceInfo(camera_info.device_info)\n\n camera = CameraImpl(args.device_id,args.width,args.height,args.fps, camera_info)\n for _ in range(10):\n camera.capture_frame()\n \n with RR.ServerNodeSetup(\"com.robotraconteur.imaging.camera\",59823,argv=rr_args):\n\n service_ctx = RRN.RegisterService(\"camera\",\"com.robotraconteur.imaging.Camera\",camera)\n service_ctx.SetServiceAttributes(camera_attributes)\n\n if args.wait_signal: \n #Wait for shutdown signal if running in service mode \n print(\"Press Ctrl-C to quit...\")\n import signal\n signal.sigwait([signal.SIGTERM,signal.SIGINT])\n else:\n #Wait for the user to shutdown the service\n if (sys.version_info > (3, 0)):\n input(\"Server started, press enter to quit...\")\n else:\n raw_input(\"Server started, press enter to quit...\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"robotraconteur_camera_driver.py","file_name":"robotraconteur_camera_driver.py","file_ext":"py","file_size_in_byte":9311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"343622347","text":"# Copyright (c) 2016-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# pyre-strict\n\nimport json\nimport logging\nimport os\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\n\nfrom .command import Command, profiling_log_path\n\n\nLOG: logging.Logger = logging.getLogger(__name__)\n\n\n@dataclass(frozen=True)\nclass EventMetadata:\n name: str\n pid: int\n timestamp: int\n tags: Dict[str, str]\n\n\n@dataclass(frozen=True)\nclass Event:\n # pyre-ignore[13]: We shouldn't throw an uninitialized attribute error here\n metadata: EventMetadata\n\n def __init__(self, metadata: EventMetadata) -> None:\n raise NotImplementedError\n\n\n@dataclass(frozen=True)\nclass DurationEvent(Event):\n duration: int\n\n\n@dataclass(frozen=True)\nclass CounterEvent(Event):\n description: Optional[str]\n\n\ndef _parse_tags(input: List[List[str]]) -> Dict[str, str]:\n return {key: value for [key, value] in input}\n\n\ndef _parse_metadata(input_json: Dict[str, Any]) -> EventMetadata:\n return EventMetadata(\n name=input_json[\"name\"],\n pid=input_json[\"pid\"],\n timestamp=input_json[\"timestamp\"],\n tags=_parse_tags(input_json.get(\"tags\", [])),\n )\n\n\ndef parse_event(input_string: str) -> Event:\n input_json: Dict[str, Any] = json.loads(input_string)\n event_type = input_json[\"event_type\"]\n metadata = _parse_metadata(input_json)\n if event_type[0] == \"Duration\":\n duration = event_type[1]\n return DurationEvent(duration=duration, metadata=metadata)\n elif event_type[0] == \"Counter\":\n description = None if len(event_type) <= 1 else event_type[1]\n return CounterEvent(description=description, metadata=metadata)\n else:\n raise ValueError(\"Unrecognized event type: {}\".format(input))\n\n\ndef parse_events(input_string: str) -> List[Event]:\n output: List[Event] = []\n for index, line in enumerate(input_string.splitlines()):\n try:\n line = line.strip()\n if len(line) == 0:\n continue\n output.append(parse_event(line))\n except Exception:\n raise RuntimeError(\n \"Malformed log entry detected on line {}\".format(index + 1)\n )\n return output\n\n\ndef to_traceevents(events: List[Event]) -> List[Dict[str, Any]]:\n def to_traceevent(event: Event) -> Optional[Dict[str, Any]]:\n if isinstance(event, DurationEvent):\n duration_ms = event.duration\n start_time_ms = event.metadata.timestamp - duration_ms\n return {\n \"pid\": event.metadata.pid,\n \"tid\": 0,\n \"ts\": start_time_ms * 1000,\n \"ph\": \"X\",\n \"name\": event.metadata.name,\n \"dur\": duration_ms * 1000,\n \"args\": event.metadata.tags,\n }\n elif isinstance(event, CounterEvent):\n timestamp_ms = event.metadata.timestamp\n arguments: Dict[str, Any] = {\n key: int(value) for key, value in event.metadata.tags.items()\n }\n return {\n \"pid\": event.metadata.pid,\n \"tid\": 0,\n \"ts\": timestamp_ms * 1000,\n \"ph\": \"C\",\n \"name\": event.metadata.name,\n \"args\": arguments,\n }\n else:\n return None\n\n return [\n trace_event\n for trace_event in map(to_traceevent, events)\n if trace_event is not None\n ]\n\n\nclass Profile(Command):\n NAME = \"profile\"\n\n def _run(self) -> None:\n try:\n profiling_output = Path(profiling_log_path())\n if not profiling_output.is_file():\n raise RuntimeError(\n \"Cannot find profiling output at `{}`. \"\n \"Please run Pyre with `--enable-profiling` option first.\".format(\n profiling_output\n )\n )\n events = parse_events(profiling_output.read_text())\n print(json.dumps(to_traceevents(events)))\n except Exception as e:\n LOG.error(\"Failed to inspect profiling log: {}\".format(e))\n","sub_path":"client/commands/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":4280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"421849510","text":"# -*- coding:utf-8 -*-\n'''\nCreated on 14 de set de 2017\n\n@author: Guilherme C.\n@author: Eduardo Miranda\n'''\nfrom Util import Util;\n\nclass Individuo(object):\n\n #def __init__(self, idNum, cor, vitalidade, deslocamento, classeIndividuo, vit1, vit2):\n def __init__(self, idNum, cor, vitalidade, deslocamento, classeIndividuo, vit1, vit2, KC, KD, KS, KW, KI):\n '''Constructor'''\n #Informacoes basicas do individuo\n self.idNum = idNum\n self.cor = cor\n self.ultimaDirecao = 0\n self.classeIndividuo = classeIndividuo\n self.vitalidade = vitalidade\n self.deslocamentoBase = deslocamento\n self.deslocamento = deslocamento\n self.qtdPassos = 0\n self.vit1 = vit1\n self.vit2 = vit2\n self.KC = KC\n self.KD = KD\n self.KS = KS\n self.KW = KW\n self.KI = KI\n self.iteracoesGastas = 0\n \n #Estatisticas\n self.movimentosFeitos = 0\n self.movimentosWaiting = 0\n \n #Posicionamento do individuo no mapa\n self.coluna = 0\n self.linha = 0\n self.idMapa = 0\n self.saiu = False\n '''\n self.idade = idade\n self.escolaridade = escolaridade\n self.contadorNoRound = 0\n self.status = Util.I_NAO_MOVIDO\n '''\n\n def posicionaIndividuoMapa(self, coluna, linha, idMapa):\n self.coluna = coluna\n self.linha = linha\n self.idMapa = idMapa\n\n def diminuiVitalidade(self, distancia):\n\n if (distancia == 0):\n return self.vitalidade\n \n return self.vitalidade - (16-distancia)\n\n def corrigeDeslocamento(self):\n if self.vitalidade < self.vit1:\n return self.deslocamentoBase + 1\n elif self.vitalidade < self.vit2:\n return self.deslocamentoBase + 2\n return self.deslocamentoBase \n ","sub_path":"Experimentos/Experimento Nishihari/Individuo.py","file_name":"Individuo.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"376070820","text":"import numpy as np\nimport tensorflow as tf\nimport os\nfrom os.path import join as pjoin\n\nprint(tf.__version__)\n\nx_train = np.load(\"./info/task2/x_train.npy\")\ny_train = np.load(\"./info/task2/y_train.npy\")\nx_test = np.load(\"./info/task2/x_test.npy\")\ny_test = np.load(\"./info/task2/y_test.npy\")\n\nx_train = x_train * 1.0 / 127.5 - 1\nx_test = x_test * 1.0 / 127.5 - 1\nprint(\"data load finish\")\n# Training Parameters\nlearning_rate = 0.0005\nnum_steps = 1000\n\nbatch_size = 64\nnum_epochs = 10\ntf.logging.set_verbosity(tf.logging.INFO)\n\n# Network Parameters\nnum_input = 7500 # MNIST data input (img shape: 28*28)\nnum_classes = 5 # MNIST total classes (0-9 digits)\ndropout = 0.25 # Dropout, probability to drop a unit\n\n\n# Create the neural network\ndef conv_net(x_dict, n_classes, dropout, reuse, is_training):\n # Define a scope for reusing the variables\n with tf.variable_scope('ConvNet', reuse=reuse):\n # TF Estimator input is a dict, in case of multiple inputs\n x = x_dict['images']\n\n # MNIST data input is a 1-D vector of 784 features (28*28 pixels)\n # Reshape to match picture format [Height x Width x Channel]\n # Tensor input become 4-D: [Batch Size, Height, Width, Channel]\n # x = tf.reshape(x, shape=[-1, 28, 28, 1])\n\n # Convolution Layer with 32 filters and a kernel size of 5\n conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv1 = tf.layers.max_pooling2d(conv1, 2, 2)\n\n # Convolution Layer with 64 filters and a kernel size of 5\n conv2 = tf.layers.conv2d(conv1, 64, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv2 = tf.layers.max_pooling2d(conv2, 2, 2)\n\n conv3 = tf.layers.conv2d(conv2, 128, 5, activation=tf.nn.relu)\n # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n conv3 = tf.layers.max_pooling2d(conv3, 2, 2)\n\n # Flatten the data to a 1-D vector for the fully connected layer\n fc1 = tf.contrib.layers.flatten(conv3)\n\n # Fully connected layer (in tf contrib folder for now)\n fc1 = tf.layers.dense(fc1, 1024)\n # Apply Dropout (if is_training is False, dropout is not applied)\n fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)\n\n # Output layer, class prediction\n out = tf.layers.dense(fc1, n_classes)\n\n return out\n\n\n# Define the model function (following TF Estimator Template)\ndef model_fn(features, labels, mode):\n # Build the neural network\n # Because Dropout have different behavior at training and prediction time, we\n # need to create 2 distinct computation graphs that still share the same weights.\n logits_train = conv_net(features, num_classes, dropout, reuse=False, is_training=True)\n logits_test = conv_net(features, num_classes, dropout, reuse=True, is_training=False)\n\n # Predictions\n pred_classes = tf.argmax(logits_test, axis=1)\n pred_probas = tf.nn.softmax(logits_test)\n\n # If prediction mode, early return\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)\n\n # Define loss and optimizer\n loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)), name='loss')\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())\n\n # Evaluate the accuracy of the model\n acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)\n # TF Estimators requires to return a EstimatorSpec, that specify\n # the different ops for training, evaluating, ...\n estim_specs = tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=pred_classes,\n loss=loss_op,\n train_op=train_op,\n eval_metric_ops={'accuracy': acc_op})\n\n return estim_specs\n\n\nprint('Training model...')\n# Build the Estimator\n\nmodel = tf.estimator.Estimator(model_fn, model_dir=\"./log/task2/\",\n config=tf.estimator.RunConfig(save_summary_steps=10, keep_checkpoint_max=1,\n log_step_count_steps=10))\n\n# Define the input function for training\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_train}, y=y_train,\n batch_size=batch_size, num_epochs=None, shuffle=True)\n# Train the Model\n\nmodel.train(input_fn, steps=num_steps)\nprint('Done training!')\n\n# Evaluate the Model\n# Define the input function for evaluating\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_test}, y=y_test,\n batch_size=batch_size, shuffle=False)\n# Use the Estimator 'evaluate' method\nprint('total accuracy: {}'.format(model.evaluate(input_fn)['accuracy']))\n\nfor c in np.nditer(np.unique(y_test)):\n x_temp = np.array([x_test[i] for i in range(0, len(y_test)) if y_test[i] == c])\n y_temp = np.zeros((x_temp.shape[0],), dtype=np.int) + c\n input_fn = tf.estimator.inputs.numpy_input_fn(\n x={'images': x_temp}, y=y_temp,\n batch_size=batch_size, shuffle=False)\n print('class{} accuracy: {}'.format(c, model.evaluate(input_fn)['accuracy']))\n\nprint('Done exporting!')\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"574363717","text":"import collections\nimport random\nimport typing\n\nimport numpy as np\n\n\nDirection = collections.namedtuple(\"Direction\", [\"name\", \"transpose\", \"reverse\"])\n\ndirections = [\n Direction(\"down\", True, True),\n Direction(\"left\", False, False),\n Direction(\"right\", False, True),\n Direction(\"up\", True, False),\n]\n\n\nclass Game(object):\n def __init__(self):\n self.board = np.zeros((4, 4), dtype=\"int\")\n self.score = 0\n self.steps = 0\n self.spawn()\n self.spawn()\n\n def spawn(self) -> None:\n new_number = random.choices([2, 4], [0.9, 0.1])[0]\n free_cols, free_rows = self.get_free_fields()\n new_coord = random.choice(list(zip(free_cols, free_rows)))\n self.board[new_coord] = new_number\n\n def get_free_fields(self) -> typing.Tuple[np.array, np.array]:\n free_cols, free_rows = np.where(self.board == 0)\n return free_cols, free_rows\n\n def is_game_over(self) -> bool:\n return not np.any(self.board == 0)\n\n def move(self, direction: Direction) -> int:\n sum_merges = 0\n board = transform_board(self.board, direction, True)\n for i in range(board.shape[0]):\n row = board[i]\n non_zero = list(row[row != 0])\n j = 0\n while j < len(non_zero) - 1:\n if non_zero[j] == non_zero[j + 1]:\n non_zero[j] += non_zero[j + 1]\n sum_merges += non_zero[j]\n del non_zero[j + 1]\n j += 1\n row = non_zero + [0] * (4 - len(non_zero))\n board[i, :] = row\n self.board = transform_board(board, direction, False)\n self.score += sum_merges\n self.steps += 1\n return sum_merges\n\n def __str__(self) -> str:\n return str(self.board)\n\n\ndef transform_board(board: np.array, direction: Direction, forward: bool) -> np.array:\n if forward:\n if direction.transpose:\n board = board.T\n if direction.reverse:\n board = board[:, ::-1]\n else:\n if direction.reverse:\n board = board[:, ::-1]\n if direction.transpose:\n board = board.T\n return board\n","sub_path":"game_simulation_sandbox/ri2048/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"75297430","text":"#http serv\r\n\r\nimport socket\r\nimport time\r\nimport sqlite3\r\nimport threading\r\ndef console():\r\n \"\"\"Constantly read from stdin and discard\"\"\"\r\n try:\r\n while 1:\r\n a = input()\r\n if a == \"d\":\r\n s.delall()\r\n except (KeyboardInterrupt, EOFError):\r\n socket.socket().connect((socket.gethostname()+\".home\",80))\r\n\r\ndef log(data):\r\n t = time.strftime(\"%d/%m/%Y %X : \")\r\n text = t + data + \"\\n\"\r\n f = open(\"log.txt\",\"a\")\r\n f.write(text)\r\n f.close()\r\ndef readPage(p):\r\n r = \"\"\r\n i = 3\r\n while 1:\r\n i+=1\r\n if p[i] == \" \":\r\n break\r\n else:\r\n r += p[i]\r\n return r\r\ndef readFile(name):\r\n try:\r\n file = open(name,\"r\")\r\n r = file.read()\r\n file.close()\r\n except FileNotFoundError:\r\n return nofile()\r\n return r, \"200 OK\"\r\ndef readImage(name):\r\n file = open(name,\"rb\")\r\n r = file.read()\r\n file.close()\r\n return r, \"200 OK\"\r\ndef nofile():\r\n rp = \"404404 PAGE NOT FOUND
\"\r\n code = \"404 File Not Found\"\r\n return rp, code\r\nclass server():\r\n def __init__(self):\r\n self.ip = socket.gethostname()+\".home\"\r\n self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n self.sock.bind((self.ip,80))\r\n self.sock.listen(1024)\r\n self.threads = []\r\n def start(self):\r\n log(\"Started\")\r\n try:\r\n self.loop()\r\n except KeyboardInterrupt:\r\n print(\"Goodbye\")\r\n log(\"Ended\")\r\n def loop(self):\r\n print(\"Server starting on host: {0}\".format(self.ip))\r\n while 1:\r\n s, a = self.sock.accept()\r\n threading.Thread(target=self.conHandle,args=(s,a,)).start()\r\n def conHandle(self,s,addr):\r\n print(\"{0} threads running. {1}\".format(threading.active_count(),threading.current_thread()))\r\n data = \"\"\r\n t = time.time()\r\n while data == \"\":\r\n data += str(s.recv(1024),\"UTF-8\")\r\n if time.time()-t > 5:\r\n print(\"Connection timed out\")\r\n break\r\n if data == \"\":\r\n s.sendall(bytes(\"HTTP/1.1 500 Invalid request\\r\\n\",\"UTF-8\"))\r\n log(\"New connection from {0} with no data recieved\".format(addr[0]))\r\n s.close()\r\n return \"\"\r\n page = readPage(data)\r\n log(\"New connection from {0} reqeusting {1}\".format(addr[0],page))\r\n print(\"PAGE: \" + page)\r\n code = \"500 internal error\"\r\n mime = \"text/html\"\r\n if page == \"/\":\r\n rp, code = readFile(\"testing.html\")\r\n elif page == \"/app.js\":\r\n rp, code = readFile(\"app.js\")\r\n mime = \"text/javascript\"\r\n elif page == \"/home.html\":\r\n rp, code = readFile(\"home.html\")\r\n elif page == \"/favicon.png\":\r\n mime = \"image/png\"\r\n rp, code = readImage(\"favicon.png\")\r\n else:\r\n rp, code = nofile()\r\n if type(rp) == str:\r\n resp = \"HTTP/1.1 {0}\\r\\nDate: {1}\\r\\nServer: Non-Existent\\r\\nContent-Type: {2}\\r\\n\\r\\n{3}\".format(code,time.strftime(\"%D $X\"),mime,rp)\r\n s.sendall(bytes(resp,\"UTF-8\"))\r\n elif type(rp) == bytes:\r\n resp = bytes(\"HTTP/1.1 {0}\\r\\nDate: {1}\\r\\nServer: Non-Existent\\r\\nContent-Type: {2}\\r\\n\\r\\n\".format(code,time.strftime(\"%D $X\"),mime),\"UTF-8\")\r\n resp = resp + rp\r\n s.sendall(resp)\r\n else:\r\n print(\"Invalid type of response page\")\r\n s.close()\r\nthreading.Thread(target=console).start()\r\ns = server()\r\ns.start()\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"61894621","text":"from django.http import HttpResponse\nimport json as simplejson\nfrom supra import views as supra\nfrom Citas.settings import ORIGIN\nfrom usuarios.models import Medico, Paciente\n\n# Create your views here.\nsupra.SupraConf.ACCECC_CONTROL[\"allow\"] = True\nsupra.SupraConf.ACCECC_CONTROL[\"origin\"] = ORIGIN\nsupra.SupraConf.ACCECC_CONTROL[\"credentials\"] = \"true\"\nsupra.SupraConf.ACCECC_CONTROL[\"headers\"] = \"origin, content-type, accept\"\nsupra.SupraConf.ACCECC_CONTROL[\"methods\"] = \"POST, GET, PUT, DELETE ,OPTIONS\"\n\n\ndef check_login(function):\n @supra.access_control\n def check(request, *args, **kwargs):\n if request.user.is_authenticated() or request.method == \"OPTIONS\":\n paciente = Paciente.objects.filter(id=request.user.pk).first()\n if paciente:\n if paciente.activado:\n return function(request, *args, **kwargs)\n # end if\n else:\n medico = Medico.objects.filter(id=request.user.pk).first()\n if medico:\n if medico.activado:\n return function(request, *args, **kwargs)\n # end if\n return HttpResponse(simplejson.dumps({\"error\": \"Debes activar tu cuenta\"}), status=403)\n # end if\n return HttpResponse(simplejson.dumps({\"error\": \"Debes iniciar sesion\"}), status=403)\n # end def\n return check\n# end def\n","sub_path":"Citas/decorator.py","file_name":"decorator.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"41986043","text":"#!/usr/bin/env python3\nimport time\nimport unittest\n\nfrom ..common import Checksum, log as common_log, retry_fn, RpmShard\n\n\nclass TestCommon(unittest.TestCase):\n\n\n def test_rpm_shard(self):\n self.assertEqual(\n RpmShard(shard=3, modulo=7), RpmShard.from_string('3:7'),\n )\n\n class FakeRpm:\n def __init__(self, filename):\n self._filename = filename\n\n def filename(self):\n return self._filename\n\n self.assertEqual(\n [('foo', True), ('bar', False), ('foo', False), ('bar', True)],\n [\n (rpm, shard.in_shard(FakeRpm(rpm)))\n for shard in [RpmShard(1, 7), RpmShard(2, 7)]\n for rpm in ['foo', 'bar']\n ],\n )\n\n def test_checksum(self):\n cs = Checksum(algorithm='oops', hexdigest='dada')\n self.assertEqual('oops:dada', str(cs))\n self.assertEqual(cs, Checksum.from_string(str(cs)))\n for algo in ['sha1', 'sha']:\n h = Checksum(algo, 'ignored').hasher()\n h.update(b'banana')\n self.assertEqual(\n '250e77f12a5ab6972a0895d290c4792f0a326ea8', h.hexdigest(),\n )\n\n def test_retry_fn(self):\n\n class Retriable:\n def __init__(self, attempts_to_fail=0):\n self.attempts = 0\n self.first_success_attempt = attempts_to_fail + 1\n\n def run(self):\n self.attempts += 1\n if self.attempts >= self.first_success_attempt:\n return self.attempts\n raise RuntimeError(self.attempts)\n\n self.assertEqual(1, retry_fn(\n Retriable().run, delays=[], what='succeeds immediately'\n ))\n\n # Check log messages, and ensure that delays add up as expected\n start_time = time.time()\n with self.assertLogs(common_log) as log_ctx:\n self.assertEqual(4, retry_fn(\n Retriable(3).run, delays=[0, 0.1, 0.2], what='succeeds on try 4'\n ))\n self.assertTrue(any(\n '\\n[Retry 3 of 3] succeeds on try 4 -- waiting 0.2 seconds.\\n' in o\n for o in log_ctx.output\n ))\n self.assertGreater(time.time() - start_time, 0.3)\n\n # Check running out of retries\n with self.assertLogs(common_log) as log_ctx, \\\n self.assertRaises(RuntimeError) as ex_ctx:\n retry_fn(Retriable(100).run, delays=[0] * 7, what='never succeeds')\n self.assertTrue(any(\n '\\n[Retry 7 of 7] never succeeds -- waiting 0 seconds.\\n' in o\n for o in log_ctx.output\n ))\n self.assertEqual((8,), ex_ctx.exception.args)\n","sub_path":"fs_image/rpm/tests/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"20903374","text":"#! /usr/bin/env python3\n\nimport os\nimport shutil\nimport datetime\nimport math\n\n# Variaveis da simulacao\nnum_nos = 5\nsimulacoes = 3\n\nraio = 30\ndensidade = 0.03\ntipoSimulacao = 'raio'\nnum_rounds = int(86400 * 1)\nmultiplicadorIntensidade = 0.4\nmaxTimeBetweenSends = 7200\nminTimeBetweenSends = 120\nmaxEnergyOfBattery = 1000 \nminEnergyOfBattery = 0\nmaxSolarIntensity = 1000 * multiplicadorIntensidade\nminSolarIntensity = 0\nwattPico = 0.15\nconstBattery = 1\t# Divisor\nconstIntensity = 1 # Multiplicador\n\nvaria_min = 20\nvaria_max = 60\nvaria_tic = 10\n\npathExist = True\t\n# Gera um arquivo para logs\ndebbugfile = open('logs_simulacoes/' + tipoSimulacao + '_sem.log', 'a+')\ndebbugfile.write('Iniciando a verificacao ' + tipoSimulacao + '_sem em: ')\ndebbugfile.write(str(datetime.datetime.now().strftime(\"%d/%m/%y %H:%M\")) + '\\n')\n\nfor varia_atual in range(varia_min, varia_max+1, varia_tic):\n\t\n\tfor simulacao in range(1, simulacoes+1):\n\t\tpathTX = 'logs/' + tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao)\n\t\tpath = 'logs/' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao)\n\n\t\tif os.path.isdir(pathTX):\n\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... ok\\n' )\n\t\telse:\n\t\t\tpathExist = False\n\t\t\t\n\t\t\tif os.path.isdir(path):\n\t\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... erro\\n' )\n\t\t\t\tdebbugfile.write('Deletando a pasta ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\tshutil.rmtree(path)\n\t\t\t\tdebbugfile.write(' ... ok\\n')\n\t\t\t\tdebbugfile.write('Iniciando ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\t\n\t\t\t\t# chama a simulacao faltante\n\t\t\t\tos.system('./r_varia_' + tipoSimulacao + '.py ' + str(num_nos) + ' ' + str(simulacoes) + ' ' + str(simulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(raio) + ' ' + str(densidade) + ' ' + str(tipoSimulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(num_rounds) + ' ' + str(multiplicadorIntensidade) + ' ' + str(maxTimeBetweenSends) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(minTimeBetweenSends) + ' ' + str(maxEnergyOfBattery) + ' ' + str(minEnergyOfBattery) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(maxSolarIntensity) + ' ' + str(minSolarIntensity) + ' ' + str(wattPico) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(constBattery) + ' ' + str(constIntensity) + ' ' + str(varia_min) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(varia_max) + ' ' + str(varia_tic) + ' ' + str(varia_atual))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\tdebbugfile.write(' ... ok\\n')\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tdebbugfile.write(tipoSimulacao+ '_SimulacaoTX_' + str(varia_atual) + str(simulacao) + ' ... erro\\n' )\n\t\t\t\tdebbugfile.write('Iniciando ' + tipoSimulacao+ '_Simulacao_' + str(varia_atual) + str(simulacao))\n\t\t\t\t\n\t\t\t\t# chama a simulacao faltante\n\t\t\t\tos.system('./r_varia_' + tipoSimulacao + '.py ' + str(num_nos) + ' ' + str(simulacoes) + ' ' + str(simulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(raio) + ' ' + str(densidade) + ' ' + str(tipoSimulacao) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(num_rounds) + ' ' + str(multiplicadorIntensidade) + ' ' + str(maxTimeBetweenSends) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(minTimeBetweenSends) + ' ' + str(maxEnergyOfBattery) + ' ' + str(minEnergyOfBattery) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(maxSolarIntensity) + ' ' + str(minSolarIntensity) + ' ' + str(wattPico) + ' ' +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(constBattery) + ' ' + str(constIntensity) + ' ' + str(varia_min) + ' ' + \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr(varia_max) + ' ' + str(varia_tic) + ' ' + str(varia_atual))\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\t\tdebbugfile.write(' ... ok\\n')\t\t\t\t\n\t\t\tbreak\n\t\t\t\n\tif(pathExist == False):\n\t\tbreak\n\nif pathExist == True:\n\tos.system('python3 r_processa_' + tipoSimulacao + '.py ' + str(simulacoes) + ' ' + str(num_nos) + ' ' + str(varia_min) + ' ' + str(varia_max) + ' '+ str(varia_tic))\t\t\t\n\ndebbugfile.close()\n\n\n\n","sub_path":"r_raio_GAFEH.py","file_name":"r_raio_GAFEH.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"474809407","text":"'''\nBSD Licence\nCopyright (c) 2012, Science & Technology Facilities Council (STFC)\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n* Neither the name of the Science & Technology Facilities Council (STFC)\nnor the names of its contributors may be used to endorse or promote\nproducts derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\nBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nCreated on 12 Apr 2013\n\n@author: mnagni\n'''\n\nfrom rdflib import Graph, URIRef\nimport logging\nfrom django.conf import settings\nfrom rdflib.namespace import Namespace\nimport uuid\nfrom djcharme.charme_middleware import CharmeMiddleware\nfrom rdflib.graph import ConjunctiveGraph\nfrom urllib2 import URLError\nfrom djcharme.exception import StoreConnectionError\n\nLOGGING = logging.getLogger(__name__)\n'''\nSELECT_ANNOTATION = \"\"\"\n PREFIX an: \n SELECT ?s ?p ?o\n WHERE {\n an:%s ?p ?o \n }\n\"\"\"\n\nSELECT_ANNOTATIONS = \"\"\"\nPREFIX charm: \nSELECT * WHERE {\n ?s a charm:anno .\n ?s ?p ?o \n}\n\"\"\"\n\nDESCRIBE_ANNOTATIONS = \"\"\"\nPREFIX charm: \nDESCRIBE ?s\nWHERE {\n ?s a charm:anno .\n}\n\"\"\"\n\nDESCRIBE_ANNOTATION = \"\"\"\n PREFIX an: \n DESCRIBE an:%s \n\"\"\"\n\nCONSTRUCT_ANNOTATION = \"\"\"\nPREFIX an: \nprefix oa: \nprefix charm: \n\nCONSTRUCT { an:%s ?p ?o .}\n\nWHERE {\n an:%s ?p ?o .\n}\n\"\"\"\n'''\nFORMAT_MAP = {'json-ld': 'application/ld+json',\n 'xml': 'application/rdf+xml',\n 'turtle': 'text/turtle'}\n\ndef rdf_format_from_mime(mimetype):\n for k,v in FORMAT_MAP.iteritems():\n if mimetype == v:\n return k \n\n# Create a namespace object for the CHARMe namespace.\nCHARM = Namespace(\"http://charm.eu/ch#\")\nRDF = Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\nOA = Namespace(\"http://www.w3.org/ns/oa#\")\n\nANNO_SUBMITTED = 'submitted'\nANNO_INVALID = 'invalid'\nANNO_STABLE = 'stable'\nANNO_RETIRED = 'retired'\n\nNODE_URI = 'http://localhost/'\nANNO_URI = 'annoID'\nBODY_URI = 'bodyID'\nCH_NODE = 'chnode'\n\nRESOURCE = 'resource'\nDATA = 'data'\nPAGE = 'page'\n\nLOGGING = logging.getLogger(__name__)\n\n\ndef format_graphIRI(graph, baseurl = 'http://dummyhost'):\n '''\n Builds a named graph URIRef using, if exists, \n a settings.SPARQL_QUERY parameter.\n \n - string **graph** \n the graph name\n * return String\n '''\n if 'http://' in graph:\n return graph\n \n return '%s/%s' % (getattr(settings, 'SPARQL_DATA', baseurl), graph)\n\ndef generate_graph(store, graph):\n '''\n Generate a new Graph\n - string **graph** \n the graph name\n * return:rdflib.Graph - Returns an RDFlib graph containing the given data\n '''\n return Graph(store=store, identifier = format_graphIRI(graph))\n\ndef insert_rdf(data, mimetype, graph = None, store=None):\n '''\n Inserts an RDF/json-ld document into the triplestore\n - string **data** \n a document\n - string **mimetype** \n the document mimetype\n - string **graph** \n the graph name\n - rdflib.Store **store** \n if none use the return of get_store() \n '''\n if store is None:\n store = CharmeMiddleware.get_store()\n tmp_g = Graph()\n #Necessary as RDFlib does not contain the json-ld lib\n\n tmp_g.parse(data = data, format = rdf_format_from_mime(mimetype))\n _formatSubmittedAnnotation(tmp_g)\n final_g = generate_graph(store, graph)\n \n for ns in tmp_g.namespaces():\n final_g.store.bind(str(ns[0]), ns[1])\n \n for res in tmp_g:\n final_g.add(res)\n \n return final_g\n\ndef _formatResourceURIRef(resource_id):\n '''\n Returns the URIRef associated with the id for this specific node\n '''\n if resource_id.startswith('http:'):\n return URIRef(resource_id) \n return URIRef('%s/%s/%s' % (getattr(settings, 'NODE_URI', NODE_URI), \n RESOURCE,\n resource_id))\n \ndef _formatNodeURIRef(uriref, anno_uri, body_uri):\n '''\n Rewrite a URIRef according to the node configuration\n * uriref:rdflib.URIRef \n * anno_uri:String as hexadecimal \n * body_uri:String as hexadecimal\n ''' \n if isinstance(uriref, URIRef) and NODE_URI in uriref:\n uriref = URIRef(uriref.replace(NODE_URI,\n getattr(settings,\n 'NODE_URI', \n NODE_URI) + '/'))\n\n if isinstance(uriref, URIRef) and CH_NODE in uriref:\n uriref = URIRef(uriref.replace(CH_NODE + ':', \n getattr(settings, 'NODE_URI', NODE_URI) + '/')) \n if isinstance(uriref, URIRef) and ANNO_URI in uriref:\n uriref = URIRef(uriref.replace(ANNO_URI, \"resource/\" + anno_uri))\n if isinstance(uriref, URIRef) and BODY_URI in uriref:\n uriref = URIRef(uriref.replace(BODY_URI, \"resource/\" + body_uri)) \n return uriref\n\ndef _formatSubmittedAnnotation(graph):\n '''\n Formats the graph according to the node configuration\n '''\n anno_uri = uuid.uuid4().hex\n body_uri = uuid.uuid4().hex\n \n for s,p,o in graph:\n graph.remove((s, p, o))\n s =_formatNodeURIRef(s, anno_uri, body_uri)\n p = _formatNodeURIRef(p, anno_uri, body_uri)\n o = _formatNodeURIRef(o, anno_uri, body_uri)\n graph.add((s, p, o))\n\ndef change_annotation_state(resource_id, new_graph):\n '''\n Advance the status of an annotation\n - string **resource_id**\n the resource URL\n - string **new_graph**\n the name of the state where more the annotation\n ''' \n old_graph = find_annotation_graph(resource_id)\n old_g = generate_graph(CharmeMiddleware.get_store(), old_graph)\n new_g = generate_graph(CharmeMiddleware.get_store(), new_graph)\n for res in old_g.triples((_formatResourceURIRef(resource_id), None, None)):\n old_g.remove(res) \n new_g.add(res)\n return new_g\n\ndef find_annotation_graph(resource_id): \n triple = (_formatResourceURIRef(resource_id), None, None)\n for graph in [ANNO_SUBMITTED, ANNO_STABLE, ANNO_RETIRED, ANNO_INVALID]:\n new_g = generate_graph(CharmeMiddleware.get_store(), graph)\n if triple in new_g:\n return graph \n \n \n\ndef find_resource_by_id(resource_id):\n '''\n Returns the charme resource associated with the given resource_id\n * resource_id:String\n * return: an rdflib.Graph object\n '''\n g = ConjunctiveGraph(store=CharmeMiddleware.get_store())\n tmp_g = Graph()\n for res in g.triples((_formatResourceURIRef(resource_id), None, None)):\n tmp_g.add(res) \n return tmp_g\n\ndef _collect_annotations(graph):\n ''' \n Returns a graph containing all the node annotations\n - string **graph** \n the graph name \n '''\n g = generate_graph(CharmeMiddleware.get_store(), graph)\n\n tmp_g = Graph()\n try:\n for res in g.triples((None, None, OA['Annotation'])):\n tmp_g.add(res)\n for res in g.triples((None, OA['hasTarget'], None)):\n tmp_g.add(res) \n for res in g.triples((None, OA['hasBody'], None)):\n tmp_g.add(res)\n except URLError as e:\n raise StoreConnectionError(\"Cannot open a connection with triple store \\n\" + str(e))\n return tmp_g","sub_path":"djcharme/djcharme/node/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"199520209","text":"from django.core.management.base import BaseCommand, CommandError\n# from polls.models import Question as Poll\n\n\nclass Command(BaseCommand):\n help = 'loads from json file'\n\n def add_arguments(self, parser):\n parser.add_argument('dumpFile', nargs='+', type=str)\n\n def handle(self, *args, **options):\n from subprocess import call\n import os\n\n path, dirs, files = next(os.walk(\"/usr/lib\"))\n file_count = len(files)\n\n try:\n import psycopg2\n from psycopg2 import sql\n from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT\n except Exception as e:\n print(\"could not import psycopg2\")\n SystemExit(0)\n\n from django.contrib.contenttypes.models import ContentType\n\n def getAndWriteNewSetting():\n try:\n fs.close()\n except Exception as e:\n raise\n fs = open(\"databaseConnect.txt\", \"w+\")\n connectionDataTypes = [\"dbname\", \"user\", \"host\", \"password\"]\n connectionData = {}\n databaseSetting = \"\"\n for i in connectionDataTypes:\n connectionData[i] = input(str(i) + \" \")\n for i in range(len(connectionData)):\n\n databaseSetting = databaseSetting + \\\n connectionDataTypes[i] + \"='\" + \\\n connectionData[connectionDataTypes[i]] + \"'\"\n fs.write(databaseSetting)\n fs.close()\n return databaseSetting\n\n try:\n fs = open(\"databaseConnect.txt\", \"r\")\n fsText = fs.read()\n if fsText != None:\n text = input(\"would to use previos settings? (y/n) \")\n global databaseSetting\n if text == \"y\":\n # fs = open(\"databaseConnect.txt\",\"r\")\n\n databaseSetting = fs.read()\n fs.close()\n if text == \"n\":\n\n databaseSetting = getAndWriteNewSetting()\n\n except:\n raise\n\n try:\n database = psycopg2.connect(databaseSetting)\n except Exception as e:\n raise\n\n def backup():\n if not os.path.exists(\"backups\"):\n os.makedirs(\"backups\")\n call(\"python3 manage.py dumpdata > backups/dumpdataBackup.json\", shell=True)\n\n fs = open(\"databaseConnect.txt\", \"r\")\n databaseSetting = fs.read()\n fs.close()\n\n databaseSettingList = databaseSetting.split('=')\n ln = len(databaseSettingList[1])\n\n cursor = database.cursor()\n\n try:\n backup()\n except Exception as e:\n print(\"no database\")\n\n database.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)\n\n cursor.execute(sql.SQL(\"drop database if exists {};\").format(\n sql.Identifier(databaseSettingList[1][1:ln-4].replace(\"'\", \"\"))))\n cursor.execute(sql.SQL(\"create database {};\").format(\n sql.Identifier(databaseSettingList[1][1:ln-4].replace(\"'\", \"\"))))\n try:\n call(\"python3 manage.py migrate\", shell=True)\n except Exception as e:\n pass\n\n ContentType.objects.all().delete()\n call(\"python3 manage.py loaddata dump.json\", shell=True)\n from django.contrib.auth.models import User\n text = input(\"do you want to create/fix super user (y/n) \")\n if text == \"y\":\n try:\n text = input(\"your username \")\n User.objects.get(username=text, is_superuser=True).delete()\n call(\"python3 manage.py createsuperuser\", shell=True)\n except Exception as e:\n call(\"python3 manage.py createsuperuser\", shell=True)\n # text = input(\"your username\")\n # User.objects.get(username=\"joebloggs\", is_superuser=True).delete()\n\n\n# quit()\n","sub_path":"the_photohub_website/management/commands/reload.py","file_name":"reload.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"555522272","text":"from collections import defaultdict\nd=defaultdict(list)\n#list append\nd['a'].append(1)\nd['a'].append(2)\nd['b'].append(4)\nprint(d)\n#set add\ne=defaultdict(set)\ne['a'].add(1)\ne['a'].add(2)\ne['b'].add(4)\nprint(e)\n\nprice={\n 'acme':45.23,\n 'aapl':612.78,\n 'ibm':205.55,\n 'hpq':37.20,\n 'fb':10.75,\n 'ffb':10.75,\n 'if':205.55\n}\nmin_price=min(zip(price.values(),price.keys()))\nprint(min_price)\nmax_price=max(zip(price.values(),price.keys()))\nprint(max_price)\nprice_sorted=sorted(zip(price.values(),price.keys()))\nprint(price_sorted)\nprint(price.items())\n\na=[1,2,5,6,5,2,2,5,4,2,1,9,8,5]\ndef clean(items):\n seen=set()\n for item in items:\n if item not in seen:\n yield item\n seen.add(item)\nprint(list(clean(a)))\n\n#序列出现次数最多的元素\nfrom collections import Counter\n#通过一个或多个字典中的值来对列表排序\nfrom operator import itemgetter\n#分组\nfrom itertools import groupby\nrow=[\n {'job':111,'data':'07/01/2012'},\n {'job':211,'data':'09/01/2012'},\n {'job':311,'data':'08/01/2012'},\n {'job':411,'data':'07/01/2012'},\n {'job':511,'data':'09/01/2012'},\n]\nrow.sort(key=itemgetter('data'))\nfor data,items in groupby(row,key=itemgetter('data')):\n print(data)\n for i in items :\n print(' ',i)\n#返回满足布尔值为true的相应元素\nfrom itertools import compress\naddress=[\n '5412 a clark',\n '5421 b asdf'\n]\ncounts=[0,1]\na=[n==1 for n in counts]\nprint(list(compress(address,a)))\n\n#多个映射或字典中合并为一个单独的映射并进行查找和检查建是否存在\nfrom collections import ChainMap\na={'x':1,'z':4}\nb={'y':2,'z':3}\nc=ChainMap(a,b)\nprint(c['x'],end=' ')\nprint(c['y'],end=' ')\nprint(c['z'],end='')\n\n","sub_path":"代码2.py","file_name":"代码2.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"34114556","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('civilireports', '0003_merge'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='report',\n name='date_of_report',\n field=models.DateTimeField(default=datetime.datetime(2014, 11, 15, 17, 0, 56, 805291), verbose_name=b'date of report'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='report',\n name='status',\n field=models.CharField(default=b'reported', max_length=255, verbose_name=b'status', choices=[(b'reported', b'reported'), (b'in_progress', b'in progress'), (b'finished', b'finished')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"civili/civilireports/migrations/0004_auto_20141115_1700.py","file_name":"0004_auto_20141115_1700.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"306887177","text":"import numpy as np\nimport cv2\nimport time\nimport os\nfrom epsareas import epsareas_func\n\n\n\ndef main(frame_count, kernel, red_mask_mass, filename):\n frame_skip = 1 # не работает\n frame_size_mult = 0.8\n\n # границы красного цвета BGR\n lower_red = np.array([0, 0, 120], dtype=\"uint8\") # 198, 110\n upper_red = np.array([100, 100, 255], dtype=\"uint8\")\n\n # границы красного цвета HSV\n # lower_red = np.array([0, 0, 120], dtype=\"uint8\") # 198, 110\n # upper_red = np.array([100, 100, 255], dtype=\"uint8\")\n\n\n lower_black = 0\n upper_black = 0\n while True:\n # cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count)\n if frame_count % frame_skip == 0:\n try:\n ret1, s_frame = cap.read()\n # s_frame = cv2.resize(s_frame, (int(cap_w * frame_size_mult), int(cap_h * frame_size_mult)),\n # interpolation=cv2.INTER_CUBIC)\n s_frame = s_frame[0:int(cap_h*0.7), 0:int(cap_w)]\n except:\n return -1\n\n black = np.zeros([s_frame.shape[:2][0], s_frame.shape[:2][1], 1], dtype=\"uint8\") # для фильтра черный фон\n\n # покадровая маска\n mask_red = cv2.inRange(cv2.medianBlur(s_frame, 5), lower_red, upper_red) # blured\n\n # морфологические преобразования\n mask_red1 = cv2.morphologyEx(mask_red, cv2.MORPH_OPEN, kernel)\n mask_red1 = cv2.morphologyEx(mask_red1, cv2.MORPH_CLOSE, kernel)\n\n # магия с последовательным изчезновением красного\n if len(red_mask_mass) < 4: # задержка в кадрах перед исчезновением красной области\n red_mask_mass.append(mask_red1)\n else:\n red_mask_mass.pop(0)\n red_mask_mass.append(mask_red1)\n\n sum_rmask = mask_red1\n if len(red_mask_mass) > 0:\n for rmask in red_mask_mass:\n sum_rmask = cv2.addWeighted(rmask, 0.5, sum_rmask, 1, 1)\n # cv2.imshow('summ_rmask', sum_rmask)\n\n # порог\n ret, thresh = cv2.threshold(sum_rmask, 127, 255, cv2.THRESH_BINARY)\n _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # разобраться\n\n res = epsareas_func(contours, s_frame, frame_count, filename, black)\n if res:\n return res\n frame_count += frame_skip #\n else:\n # ret1, s_frame = cap.read()\n frame_count += 1 #\n\n if cv2.waitKey(50) & 0xFF == ord('q'):\n print(-1)\n break\n\n return -1\n\nstart_time = time.time()\ntext_file = \"C:/Users/janch/PycharmProjects/visionhack/output1_rev8.txt\"\n# r = re.compile(\".*avi\")\nfiles = [f for f in os.listdir('C:/Users/janch/Desktop/validationset')]\n# files = filter(r.match, files)\n\nfor file in files:\n filepath = ('C:/Users/janch/Desktop/validationset/%s' % file)\n\n cap_timestart = time.time()\n\n cap = cv2.VideoCapture(filepath)\n cap_w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\n cap_h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\n\n ret1, s_frame = cap.read()\n\n # cv2.imshow(\"s_frm\", s_frame)\n frame_count = 0\n kernel = np.ones((4, 4), np.uint8) # ядро для красного цвета\n red_mask_mass = []\n\n out = main(frame_count, kernel, red_mask_mass, file)\n\n if out <= 15:\n out = -1\n with open(text_file, 'a') as text:\n text.write(\"%s %s \\n\" % (file, out))\n cap.release()\n cv2.destroyAllWindows()\n print(\"--- %s seconds --- %s\" % (time.time() - cap_timestart, file))\n\n# time\nprint(\"--- %s seconds at all ---\" % (time.time() - start_time))\n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"46544353","text":"# main imports\nimport sys, os, argparse, json\nimport numpy as np\n\n# models imports\nfrom keras.models import model_from_json\nfrom sklearn.externals import joblib\n\n# image processing imports\nfrom ipfml import processing, utils\nfrom PIL import Image\n\n# modules imports\nsys.path.insert(0, '') # trick to enable import of main folder module\n\nimport custom_config as cfg\nfrom data_attributes import get_image_features\n\n# variables and parameters\npath = cfg.dataset_path\nmin_max_ext = cfg.min_max_filename_extension\nfeatures_choices = cfg.features_choices_labels\nnormalization_choices = cfg.normalization_choices\n\ncustom_min_max_folder = cfg.min_max_custom_folder\n\ndef main():\n\n # getting all params\n parser = argparse.ArgumentParser(description=\"Script which detects if an image is noisy or not using specific model\")\n\n parser.add_argument('--image', type=str, help='Image path')\n parser.add_argument('--solution', type=str, help='Data of solution to specify filters to use')\n parser.add_argument('--model', type=str, help='.joblib or .json file (sklearn or keras model)')\n parser.add_argument('--mode', type=str, help='Kind of normalization level wished', choices=normalization_choices)\n parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)\n parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)\n\n args = parser.parse_args()\n\n p_img_file = args.image\n p_model_file = args.model\n p_solution = list(map(int, args.solution.split(' ')))\n p_mode = args.mode\n p_feature = args.feature\n p_custom = args.custom\n\n if '.joblib' in p_model_file:\n kind_model = 'sklearn'\n\n if '.json' in p_model_file:\n kind_model = 'keras'\n\n if kind_model == 'sklearn':\n # load of model file\n model = joblib.load(p_model_file)\n\n if kind_model == 'keras':\n with open(p_model_file, 'r') as f:\n json_model = json.load(f)\n model = model_from_json(json_model)\n model.load_weights(p_model_file.replace('.json', '.h5'))\n\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n features=['accuracy'])\n\n # load image\n img = Image.open(p_img_file)\n\n data = get_image_features(p_feature, img)\n\n # get indices of filters data to use (filters selection from solution)\n indices = []\n\n for index, value in enumerate(p_solution): \n if value == 1: \n indices.append(index)\n\n # No need to use custom normalization with this kind of process \n # check mode to normalize data\n if p_mode == 'svdne':\n\n # set min_max_filename if custom use\n min_max_file_path = os.path.join(path, p_feature + min_max_ext)\n\n # need to read min_max_file\n with open(min_max_file_path, 'r') as f:\n min_val = float(f.readline().replace('\\n', ''))\n max_val = float(f.readline().replace('\\n', ''))\n\n l_values = utils.normalize_arr_with_range(data, min_val, max_val)\n\n elif p_mode == 'svdn':\n l_values = utils.normalize_arr(data)\n else:\n l_values = data\n\n test_data = np.array(l_values)[indices]\n\n # get prediction of model\n if kind_model == 'sklearn':\n prediction = model.predict([test_data])[0]\n\n if kind_model == 'keras':\n test_data = np.asarray(test_data).reshape(1, len(test_data), 1)\n prediction = model.predict_classes([test_data])[0][0]\n\n # output expected from others scripts\n print(prediction)\n\nif __name__== \"__main__\":\n main()\n","sub_path":"prediction/predict_noisy_image_svd_attributes.py","file_name":"predict_noisy_image_svd_attributes.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"52461787","text":"# -*- coding: UTF-8 -*-\n'''\n@author: Andrewzhj\n@contact: andrew_zhj@126.com\n@file: logistic_regression.py\n@time: 3/25/19 10:37 PM\n@desc: 良/恶性乳腺癌肿瘤数据训练\n@note:\n'''\n\nimport pandas as pd\nimport numpy as np\nimport ssl\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.svm import LinearSVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.feature_extraction import DictVectorizer\nssl._create_default_https_context = ssl._create_unverified_context\n\n\n# 良/恶性乳腺癌肿瘤数据训练\nclass LogisticRegressionTrain(object):\n '''\n 初始化数据地址\n '''\n\n def __init__(self):\n self.bathUrl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/\"\n self.dataFile = \"breast-cancer-wisconsin.data\"\n self.column_names = ['Sample code number', 'Clump Thickness', 'Uniformity of Cell Size',\n 'Uniformity of Cell Shape', 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei',\n 'Blan Chromatin', 'Normal Nucleoli', 'Mitoses', 'Class']\n\n '''\n 获取数据\n '''\n\n def get_data(self):\n url = self.bathUrl + self.dataFile\n # 读取数据\n data = pd.read_csv(url, names=self.column_names)\n # 将?转换为标准缺失值\n data = data.replace(to_replace='?', value=np.nan)\n # 丢弃带有缺失值的数据\n data = data.dropna(how='any')\n return data\n\n '''\n 逻辑回归训练\n 精确计算逻辑回归参数\n '''\n\n def logistic_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n lr = LogisticRegression()\n lr.fit(x_train, y_train)\n lr_y_predict = lr.predict(x_test)\n print(\"Accuracy of LR Classifier: \", lr.score(x_test, y_test))\n print(classification_report(y_test, lr_y_predict, target_names=['Benign', 'Malignant']))\n\n '''\n 随机梯度参数估计\n 采用梯度法估计参数\n '''\n\n def sgdc_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n sgdc = SGDClassifier()\n sgdc.fit(x_train, y_train)\n sgdc_y_predict = sgdc.predict(x_test)\n print(\"Accuracy of SGD Classifier: \", sgdc.score(x_test, y_test))\n print(classification_report(y_test, sgdc_y_predict, target_names=['Benign', 'Malignant']))\n\n '''\n 支持向量机分类器\n '''\n def svc_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n ss = StandardScaler()\n x_train = ss.fit_transform(x_train)\n x_test = ss.transform(x_test)\n lsvc = LinearSVC()\n lsvc.fit(x_train, y_train)\n y_predict = lsvc.predict(x_test)\n print(\"The Accuracy of Liner SVC is\", lsvc.score(x_test, y_test))\n print(classification_report(y_test, y_predict))\n\n '''\n 决策树模型,不需要线性假设\n '''\n def decision_tree_train(self):\n data = self.get_data()\n # 创建特征列表\n x_train, x_test, y_train, y_test = train_test_split(data[self.column_names[1:10]], data[self.column_names[10]],\n test_size=0.25, random_state=33)\n print(y_train.value_counts())\n print(y_test.value_counts())\n print(data.shape)\n vec = DictVectorizer(sparse=False)\n x_train = vec.fit_transform(x_train.to_dict(orient='record'))\n print(vec.feature_names_)\n x_test = vec.transform(x_test.to_dict(orient='record'))\n dtc = DecisionTreeClassifier()\n dtc.fit(x_train, y_train)\n y_predict = dtc.predict(x_test)\n print(\"The Accuracy of decision tree is \", dtc.score(x_test, y_test))\n print(classification_report(y_test, y_predict))\n\n\nif __name__ == '__main__':\n cancerTrain = LogisticRegressionTrain()\n cancerTrain.logistic_train()\n cancerTrain.sgdc_train()\n cancerTrain.svc_train()\n cancerTrain.decision_tree_train()","sub_path":"classifier_tutorial/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"546552700","text":"from opsgenie.response import BaseResponse\nfrom opsgenie.utility import convert_to_date\n\n\nclass GetAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.tags = self.pop('tags')\n self.count = self.pop('count')\n self.status = self.pop('status')\n self.teams = self.pop('teams')\n self.recipients = self.pop('recipients')\n self.tiny_id = self.pop('tinyId')\n self.alias = self.pop('alias')\n self.entity = self.pop('entity')\n self.id = self.pop('id')\n self.updated_at = convert_to_date(self.pop('updatedAt'))\n self.message = self.pop('message')\n self.details = self.pop('details')\n self.source = self.pop('source')\n self.description = self.pop('description')\n self.created_at = convert_to_date(self.pop('createdAt'))\n self.is_seen = self.pop('isSeen')\n self.acknowledged = self.pop('acknowledged')\n self.owner = self.pop('owner')\n self.actions = self.pop('actions')\n self.system_data = self.pop('systemData')\n\n self.decode()\n\n\nclass ListAlertsResponse(BaseResponse):\n class AlertResponse:\n def __init__(self, **kwargs):\n self.id = kwargs.get('id')\n self.alias = kwargs.get('alias')\n self.message = kwargs.get('message')\n self.status = kwargs.get('status')\n self.is_seen = kwargs.get('isSeen')\n self.acknowledged = kwargs.get('acknowledged')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n self.updated_at = convert_to_date(kwargs.get('updatedAt'))\n self.tiny_id = kwargs.get('tinyId')\n self.owner = kwargs.get('owner')\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.alerts = []\n for alert in self.pop('alerts', []):\n self.alerts.append(ListAlertsResponse.AlertResponse(**alert))\n\n self.decode()\n\n\nclass ListAlertLogsResponse(BaseResponse):\n class AlertLogResponse:\n def __init__(self, **kwargs):\n self.log = kwargs.get('log')\n self.log_type = kwargs.get('logType')\n self.owner = kwargs.get('owner')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.logs = []\n for log in self.pop('logs', []):\n self.logs.append(ListAlertLogsResponse.AlertLogResponse(**log))\n\n self.lastKey = self.pop('lastKey')\n\n self.decode()\n\n\nclass ListAlertNotesResponse(BaseResponse):\n class AlertNoteResponse:\n def __init__(self, **kwargs):\n self.note = kwargs.get('note')\n self.owner = kwargs.get('owner')\n self.created_at = convert_to_date(kwargs.get('createdAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.took = self.pop('took')\n self.last_key = self.pop('lastKey')\n self.notes = []\n for note in self.pop('notes', []):\n self.notes.append(ListAlertNotesResponse.AlertNoteResponse(**note))\n\n self.decode()\n\n\nclass ListAlertRecipientsResponse(BaseResponse):\n class UserResponse:\n def __init__(self, **kwargs):\n self.username = kwargs.get('username')\n self.state = kwargs.get('state')\n self.method = kwargs.get('method')\n self.state_changed_at = convert_to_date(kwargs.get('stateChangedAt'))\n\n class GroupResponse:\n def __init__(self, **kwargs):\n self.username = kwargs.get('username')\n self.state = kwargs.get('state')\n self.method = kwargs.get('method')\n self.state_changed_at = convert_to_date(kwargs.get('stateChangedAt'))\n\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.users = []\n for user in self.pop('users', []):\n self.users.append(ListAlertRecipientsResponse.UserResponse(**user))\n\n self.groups = []\n for group in self.pop('groups', []):\n self.groups.append(ListAlertRecipientsResponse.GroupResponse(**group))\n\n self.decode()\n\n\nclass CreateAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.message = self.pop('message')\n self.alert_id = self.pop('alertId')\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass CloseAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass DeleteAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass CountAlertsResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.count = self.pop('count')\n\n self.decode()\n\n\nclass AcknowledgeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass UnAcknowledgeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass SnoozeAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RenotifyAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass TakeOwnershipOfAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AssignOwnerToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddTeamToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddRecipientToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddNoteToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddTagsToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RemoveTagsFromAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AddDetailsToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass RemoveDetailsFromAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass ExecuteActionOfAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass AttachFileToAlertResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n\n\nclass EscalateToNextResponse(BaseResponse):\n def __init__(self, json_str):\n BaseResponse.__init__(self, json_str)\n self.status = self.pop('status')\n self.code = self.pop('code')\n\n self.decode()\n","sub_path":"opsgenie/alert/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":8860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"317980937","text":"#!/usr/bin/env python\n__author__ = ''\n\nimport random\nfrom math import sqrt\n\nl1 = [2, -5, 8, 9, -25, 25, 4]\n\ndate = '01.11.2013'\n\nMONTHS = {\"Jan\": \"1\", \"Feb\": 2, \"Mar\": 3, \"Apr\": 4, \"May\": 5, \"Jun\": 6,\n \"Jul\": \"7\", \"Aug\": 8, \"Sep\":9, \"Oct\": 10, \"11\": \"Nov\", \"Dec\": 12\n }\nDAYS = {\"01\": \"first\" , \"second\": \"02\", \"third\": \"03\", \"fourth\": \"04\", \"fifth\": \"05\",\n \"sixth\": \"06\", \"seventh\": \"07\", \"eight\": \"08\", \"ninth\": \"09\", \"tenth\": \"10\",\n \"eleventh\": \"11\", \"twelfth\": \"12\", \"thirteen\": \"13\", \"fourteenth\": \"14\",\n \"fifteenth\": \"15\", \"sixteenth\": \"16\", \"seventeenth\": \"17\",\n \"eighteenth\": \"18\", \"nineteenth\": \"19\", \"twentieth\": \"20\", \"twenty first\": \"21\",\n \"twenty second\": \"22\", \"twenty third\": \"23\", \"twenty fourth\": \"24\",\n \"twenty fifth\": \"25\", \"twenty sixth\": \"26\", \"twenty seventh\": \"27\",\n \"twenty eight\": \"28\", \"twenty ninth\": \"29\", \"thirtieth\": \"30\",\n \"thirty first\": \"31\"\n }\n\n\ndef represent_date(date):\n\n date_elements = date.split('.')\n day = date_elements[0]\n month = date_elements[1]\n year = date_elements[2]\n formatted_date = f\"Date: {DAYS.get(day)} {MONTHS.get(month)} {year}\"\n return formatted_date\n\n\ndef whole_sqrt_list(origin_list):\n new_list = []\n for num in origin_list:\n if num >= 0:\n new_el = sqrt(num)\n if new_el.is_integer(): # float(5.0).is_integer == True\n new_list.append(int(new_el))\n return new_list\n\n\ndef main():\n print(f\"OldList: {l1}\\nNewList: {whole_sqrt_list(l1)}\")\n print(represent_date(date))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"practice/hw02_normal01.py","file_name":"hw02_normal01.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"113580876","text":"# This file is Copyright 2010 Dean Hall.\n#\n# This file is part of the Python-on-a-Chip program.\n# Python-on-a-Chip is free software: you can redistribute it and/or modify\n# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1.\n#\n# Python-on-a-Chip 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.\n# A copy of the GNU LESSER GENERAL PUBLIC LICENSE Version 2.1\n# is seen in the file COPYING up one directory from this.\n\nPM_FEATURES = {\n \"HAVE_PRINT\": True,\n \"HAVE_GC\": True,\n \"HAVE_FLOAT\": False,\n \"HAVE_DEL\": True,\n \"HAVE_IMPORTS\": True,\n \"HAVE_DEFAULTARGS\": True,\n \"HAVE_REPLICATION\": True,\n \"HAVE_CLASSES\": True,\n \"HAVE_ASSERT\": True,\n \"HAVE_GENERATORS\": True,\n \"HAVE_BACKTICK\": True,\n \"HAVE_STRING_FORMAT\": False,\n \"HAVE_CLOSURES\": True,\n \"HAVE_BYTEARRAY\": True,\n \"HAVE_DEBUG_INFO\": True,\n}\n","sub_path":"pmfeatures.py","file_name":"pmfeatures.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"108374035","text":"from typing import Optional, Callable\nfrom datetime import datetime\nfrom time import time\nimport hashlib\nfrom xml.dom.minidom import parseString as parser_xml_from_str\n\nimport arrow\n\n\nasync def send_response_in_one_call(send, status: int, message: bytes = b\"\") -> None:\n \"\"\"moved to DAVResponse.send_in_one_call()\"\"\"\n headers = [\n (b\"Content-Type\", b\"text/html\"),\n # (b'Content-Type', b'application/xml'),\n (b\"Content-Length\", bytes(str(len(message)), encoding=\"utf8\")),\n (b\"Date\", bytes(datetime.utcnow().isoformat(), encoding=\"utf8\")),\n ]\n await send(\n {\n \"type\": \"http.response.start\",\n \"status\": status,\n \"headers\": headers,\n }\n )\n await send(\n {\n \"type\": \"http.response.body\",\n \"body\": message,\n }\n )\n\n return\n\n\nasync def receive_all_data_in_one_call(receive: Callable) -> bytes:\n data = b\"\"\n more_body = True\n while more_body:\n request_data = await receive()\n data += request_data.get(\"body\", b\"\")\n more_body = request_data.get(\"more_body\")\n\n return data\n\n\nclass DAVTime:\n def __init__(self, timestamp: Optional[float] = None):\n if timestamp is None:\n timestamp = time()\n\n self.timestamp = timestamp\n self.arrow = arrow.get(timestamp)\n\n def iso_850(self) -> str:\n # https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Last-Modified\n # Last-Modified:\n # , :: GMT\n return self.arrow.format(arrow.FORMAT_RFC850)\n\n def iso_8601(self) -> str:\n return self.arrow.format(arrow.FORMAT_W3C)\n\n\ndef generate_etag(f_size: [float, int], f_modify_time: float) -> str:\n \"\"\"\n https://tools.ietf.org/html/rfc7232#section-2.3 ETag\n https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/ETag\n \"\"\"\n return 'W/\"{}\"'.format(\n hashlib.md5(\"{}{}\".format(f_size, f_modify_time).encode(\"utf-8\")).hexdigest()\n )\n\n\ndef pprint_xml(xml_str):\n xml = parser_xml_from_str(xml_str).toprettyxml()\n print(xml)\n","sub_path":"asgi_webdav/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"154546281","text":"import web\n\nfrom datetime import datetime, date, timedelta\n\nfrom databaseoperations import *\n\n\nrender = web.template.render('templates/')\n\nurls = (\n '/', 'solar_home',\n '/system_overview/([s]\\d+)', 'system_overview',\n '/api/add/([s]\\d+)', 'add'\n)\napp = web.application(urls, globals())\napp = app.wsgifunc()\n\nclass solar_home:\n def GET(self):\n return 'hi'\n\nclass system_overview: \n def GET(self, system):\n '''\n Send a page with data on the requested system\n \n @parameter system - the system number\n\n @return - a html page with information on the system\n ''' \n current_timestamp = datetime.now()\n days_ago = current_timestamp - timedelta(7)\n hours_ago = current_timestamp - timedelta(hours = 7)\n\n data1 = get_many(str(system), 'hour', hours_ago, current_timestamp)\n\n data2 = get_many(str(system), 'day', days_ago, current_timestamp)\n \n\n return render.solar_home(data1, data2)\n\nclass add:\n def GET(self, system):\n return 'add entries here for ' + system + ' here' \n\n def POST(self, system):\n pass \n\n\n\nif __name__ == \"__main__\":\n app = web.application(urls, globals())\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"444224","text":"import numpy as np\nimport os\nfrom random import shuffle\nimport re\nimport tensorflow as tf\nimport sys\nimport urllib.request\nimport zipfile\nimport lxml.etree\nimport json\nimport math\nfrom shuffle import Shuffle as SF\nfrom prepare_sentences import Preparer\nfrom dataParser import DataParser\nfrom config import CONFIG\nimport tensorflow.contrib.seq2seq as seq2seq\nfrom tensorflow.contrib.rnn import LSTMCell, GRUCell, BasicRNNCell\n \nclass SummaryModel(object):\n \n def output_fn(self, outputs):\n return tf.contrib.layers.linear(outputs, CONFIG.DIM_VOCAB) \n def project_encoder_last_states(self, encoder_last_states):\n return tf.contrib.layers.linear(encoder_last_states, 2* CONFIG.DIM_WordEmbedding)\n def __init__(self, is_training):\n \n ''' Init all constants, embedding, and cell'''\n self.is_training = is_training\n # load the word embedding, init by random\n #self.embedding = tf.get_variable('embedding',initializer=CONFIG.w2vMatrix)\n self.embedding = tf.get_variable('embedding', shape=[CONFIG.DIM_VOCAB, CONFIG.DIM_WordEmbedding], initializer=tf.random_uniform_initializer(-0.1, 0.1)) \n #self.embedding = tf.get_variable('embedding', shape = [CONFIG.DIM_VOCAB, CONFIG.DIM_WordEmbedding], initializer = tf.contrib.layers.xavier_initializer())\n self.addPlaceholders()\n self.addEncoder()\n self.addDecoder()\n print ('model built') \n \n if (self.is_training):\n self.decoder_outputs = tf.nn.dropout(self.decoder_outputs, CONFIG.KEEPPROB)\n # this is before projection, try masking here\n \n self.u = self.output_fn(self.decoder_outputs)\n self.cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self.label_placeholder, logits=self.u)\n #self.cross_entropy = tf.reduce_sum(self.u)\n \n # mask entropy with mask\n self.masked_cross_entropy = self.cross_entropy * self.Mplaceholder\n mean_loss_by_example = tf.reduce_sum(self.masked_cross_entropy, reduction_indices = 1)\n self.mean_loss = tf.reduce_mean(mean_loss_by_example)\n \n #self.train_op = tf.train.AdamOptimizer(learning_rate = self.learning_rate).minimize(self.mean_loss)\n optimizer = tf.train.AdamOptimizer(learning_rate = self.learning_rate)\n #self.var_grad = tf.gradients(self.mean_loss, [self._decoder_in_state])[0]\n gvs = optimizer.compute_gradients(self.mean_loss)\n #capped_gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]\n self.train_op = optimizer.apply_gradients(gvs)\n else:\n\n self.output_words = tf.cast(tf.argmax(self.decoder_outputs, axis = -1),tf.int32)\n \n \n \n # helper functions \n def addEncoder(self):\n print ('adding encoder...')\n self.encoder_inputs = tf.nn.embedding_lookup(self.embedding, self.x_placeholder)\n if (self.is_training):\n self.encoder_inputs = tf.nn.dropout(self.encoder_inputs, CONFIG.KEEPPROB)\n cell_fw = GRUCell(CONFIG.DIM_WordEmbedding)\n cell_bw = GRUCell(CONFIG.DIM_WordEmbedding)\n (encoder_output_fw, encoder_output_bw), (fw_state, bw_state) = tf.nn.bidirectional_dynamic_rnn(cell_fw, cell_bw, self.encoder_inputs, dtype=tf.float32, sequence_length=self.x_lens)\n # concatenate the bidirectional inputs\n self._encoder_outputs = tf.concat([encoder_output_fw, encoder_output_bw],2)\n self._decoder_in_state = self.project_encoder_last_states(bw_state)\n #self._decoder_in_state = tf.concat([fw_state, bw_state],1)\n self.attention_states = self._encoder_outputs\n #self._decoder_in_state = tf.zeros(shape=[CONFIG.BATCH_SIZE, CONFIG.DIM_WordEmbedding *2], dtype=tf.float32)\n #self.attention_states = tf.zeros(shape=[CONFIG.BATCH_SIZE, CONFIG.DIM_RNN, CONFIG.DIM_WordEmbedding * 2])\n def addDecoder(self):\n print ('adding decoder...')\n cell = GRUCell(2* CONFIG.DIM_WordEmbedding)\n self.attention_states = self._encoder_outputs\n self.decoder_inputs_embedded = tf.nn.embedding_lookup(self.embedding, self.y_placeholder)\n # prepare attention: \n (attention_keys, attention_values, attention_score_fn, attention_construct_fn) = seq2seq.prepare_attention(attention_states=self.attention_states, attention_option='bahdanau', num_units=2* CONFIG.DIM_WordEmbedding)\n \n if (self.is_training): \n # new Seq2seq train version\n self.check_op = tf.add_check_numerics_ops()\n decoder_fn_train = seq2seq.attention_decoder_fn_train(encoder_state=self._decoder_in_state, attention_keys=attention_keys, attention_values=attention_values, attention_score_fn=attention_score_fn, attention_construct_fn=attention_construct_fn, name='attention_decoder')\n (self.decoder_outputs_train, self.decoder_state_train, self.decoder_context_state_train) = seq2seq.dynamic_rnn_decoder(cell=cell, decoder_fn=decoder_fn_train, inputs=self.decoder_inputs_embedded, sequence_length=self.y_lens, time_major=False)\n self.decoder_outputs = self.decoder_outputs_train\n \n else:\n \n # new Seq2seq version\n start_id = CONFIG.WORDS[CONFIG.STARTWORD]\n stop_id = CONFIG.WORDS[CONFIG.STOPWORD]\n decoder_fn_inference = seq2seq.attention_decoder_fn_inference(encoder_state=self._decoder_in_state, attention_keys = attention_keys, attention_values=attention_values, attention_score_fn=attention_score_fn, attention_construct_fn=attention_construct_fn, embeddings=self.embedding, start_of_sequence_id=start_id, end_of_sequence_id = stop_id, maximum_length = CONFIG.DIM_DECODER, num_decoder_symbols=CONFIG.DIM_VOCAB, output_fn = self.output_fn )\n (self.decoder_outputs_inference, self.decoder_state_inference, self.decoder_context_state_inference) = seq2seq.dynamic_rnn_decoder(cell=cell, decoder_fn=decoder_fn_inference, time_major=False)\n self.decoder_outputs = self.decoder_outputs_inference\n \n \n def addPlaceholders(self):\n self.x_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, CONFIG.DIM_RNN])\n self.y_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, CONFIG.DIM_DECODER-1])\n self.label_placeholder = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE, None])\n self.x_lens = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE])\n self.y_lens = tf.placeholder(tf.int32, [CONFIG.BATCH_SIZE])\n self.learning_rate = tf.placeholder(tf.float32)\n self.Mplaceholder = tf.placeholder(tf.float32, [CONFIG.BATCH_SIZE, None]) # Mask for the output sequence\n \n def getMask(self, lens, DIM_RNN):\n mask = []\n for i in range(CONFIG.BATCH_SIZE):\n temp = [1.0 if j0):\n break\n it += 1\n _,doc_valid, summary_valid, docLens_valid, sumLens_valid = tup\n doc_batch_v = _get_doc_batch(doc_valid)\n summary_batch_v = _get_summary_batch(summary_valid)\n label_batch_v = _get_label_batch(summary_valid)\n m_valid.run_valid_step(sess, doc_batch_v, summary_batch_v, label_batch_v, np.array(docLens_valid), np.array(sumLens_valid)) \n iters += 1\n \n \ndef _initWordDic(from_word2Vec=False):\n# Load the words into WORDS dictionary of CONFIG\n if not (from_word2Vec):\n with open(CONFIG.WORDFILE, 'r') as wordsFile:\n for l in wordsFile:\n word, freq = l.split()\n freq = int(freq)\n if (freq > 1):\n # only record the words having frequency > 1\n CONFIG.WORDS[word] = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.append(word)\n else:\n #CONFIG.WORDS[word] = len(CONFIG.WORDS)\n #CONFIG.WORDSLIST.append(word)\n break \n # now update the dimension\n CONFIG.WORDS[CONFIG.PADDING] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.UNKNOWN] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STARTWORD] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STOPWORD] = len(CONFIG.WORDS)\n CONFIG.DIM_VOCAB = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.extend([CONFIG.PADDING, CONFIG.UNKNOWN, CONFIG.STARTWORD, CONFIG.STOPWORD]) \n else:\n # load the word2vec model\n from gensim.models import Word2Vec\n model_ted = Word2Vec.load(CONFIG.WORDMODELFILE)\n w2vMatrix = model_ted.syn0\n #TODO: add random vectors rep padding, unknown, startword, stopword\n w2vIndex = model_ted.index2word\n for wd in w2vIndex:\n CONFIG.WORDS[wd] = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.append(wd)\n CONFIG.WORDS[CONFIG.PADDING] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.UNKNOWN] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STARTWORD] = len(CONFIG.WORDS)\n CONFIG.WORDS[CONFIG.STOPWORD] = len(CONFIG.WORDS)\n CONFIG.DIM_VOCAB = len(CONFIG.WORDS)\n CONFIG.WORDSLIST.extend([CONFIG.PADDING, CONFIG.UNKNOWN, CONFIG.STARTWORD, CONFIG.STOPWORD])\n append_vec = np.random.uniform(low=0.0, high = 1.0, size=[4,CONFIG.DIM_WordEmbedding])\n # concatenate this vector to the w2vMatrix\n CONFIG.w2vMatrix = np.concatenate((w2vMatrix, append_vec), axis=0)\n \n \n\ndef main():\n _initWordDic(True)\n # parse the data using dataParser\n parser = DataParser()\n docs, summary = parser.parseFile()\n p_doc = Preparer(docs)\n p_summary = Preparer(summary, is_summary=True)\n p_doc.cutDocs()\n p_summary.cutDocs()\n docLens = p_doc.countDocs()\n sumLens = p_summary.countDocs()\n print (max(sumLens))\n #sys.exit()\n p_doc.doc2Int()\n p_summary.doc2Int()\n # docs, docLens, summary, sumLens are the data\n data = list(zip(docs, summary, docLens, sumLens))\n training_data = data[:1585]\n validation_data = data[:1835]\n testing_data = data[1835:] \n \n ''' FIXING THE DIMENSION ISSUES OF BATCHES\n sf_train = SF(training_data, CONFIG.BATCH_SIZE, is_training = True)\n sf_valid = SF(validation_data, CONFIG.BATCH_SIZE, is_training = False)\n for tup in sf_train.get_batch(): \n _, doc, summary, docLens, sumLens = tup\n doc_batch = _get_doc_batch(doc)\n summary_batch = _get_summary_batch(summary)\n label_batch = _get_label_batch(summary)\n docLens = np.array(docLens)\n summaryLens = np.array(sumLens) \n print (doc_batch[0])\n print (summary_batch[0])\n print (label_batch[0])\n print (list(doc for doc in docLens))\n print (list(doc for doc in summaryLens))\n sys.exit()'''\n \n with tf.Graph().as_default():\n initializer = tf.random_uniform_initializer(-0.1, 0.1)\n with tf.name_scope('Train'):\n with tf.variable_scope('Model', reuse=None, initializer=initializer):\n m = SummaryModel(is_training=True) \n with tf.name_scope('Valid'):\n with tf.variable_scope('Model', reuse=True, initializer=initializer):\n m_valid = SummaryModel(is_training=False) \n with tf.name_scope('Test'):\n with tf.variable_scope('Model', reuse=True, initializer=initializer):\n m_test = SummaryModel(is_training=False)\n \n init_op = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init_op)\n for epoch in range(CONFIG.EPOCH):\n print ('---------------running ' + str(epoch) + 'th epoch ----------------')\n run_epoch(sess, m, m_valid, training_data, validation_data)\n\nmain()\n \n \n \n \n \n","sub_path":"open/summarizer_debug.py","file_name":"summarizer_debug.py","file_ext":"py","file_size_in_byte":16168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"158141886","text":"\nimport pickle\nfrom collections import namedtuple\nimport logging\nimport os\n\nimport master_data_creation as mdc\nimport conditional_volatility_model as cvm\nimport classification_models as cm\nimport sharpe_ratio_generation as srg\n\n\nclass MasterRunResults:\n\n def __init__(self, stock, fitted_classifier_ensemble, class_predictions, sharpe_projection, current_price,\n cointegration_set, estimated_variance):\n self.stock = stock\n self.fitted_classifier_ensemble = fitted_classifier_ensemble\n self.class_predictions = class_predictions\n self.sharpe_projection = sharpe_projection\n self.current_price = current_price\n self.cointegration_set = cointegration_set\n self.estimated_variance = estimated_variance\n\n# Create master run function to perform data engineering, classification fit, classification predict for a single stock\nclass MasterRun:\n def __init__(self, data):\n self.data = data\n\n def master_run(self, stock):\n try:\n logging.info('Running for {}'.format(stock))\n current_price = self.data.stock_dict[stock]['ADJ_CLOSE'][-1:].item()\n\n # Fit conditional volatility models to Returns\n mean_returns = self.data.stock_dict[stock]['RETURN'].mean()\n variance_of_returns = ((self.data.stock_dict[stock]['RETURN']-mean_returns)**2)\n vm = cvm.VolatilityModels(variance_of_returns)\n #volatility, fitted_model = vm.create_hmm_model()\n fitted_volatility, fitted_model = vm.create_hmm_model(n_states=3)\n\n # Create master table, a collection of labels and key exogenous variables\n engineer = mdc.CreateMasterTable(stock, self.data, fitted_volatility, mean_returns, bound_limits=1.5)\n master_table, cointegration_set = engineer.base_table_create()\n\n # Fit classification models\n modeler = cm.ClassifierEnsemble(stock, master_table)\n fitted_ensemble = modeler.fit_classifier_ensemble()\n\n # Predict Classification\n current_state = master_table[-1:]\n predicted_probabilities = fitted_ensemble.predict(current_state)\n\n # Simulate returns based on the assigned classification and volatility estimates\n simulation = srg.SharpePredict(fitted_model, predicted_probabilities, bound_limits=1.5)\n sharpe_ratio_projection, sigma_estimate = simulation.generate_sharpe_projection()\n\n # Save the results\n results = MasterRunResults(stock, fitted_ensemble, predicted_probabilities, sharpe_ratio_projection,\n current_price, cointegration_set, sigma_estimate)\n self.save_master_results(stock, results)\n\n except Exception as e:\n logging.info('Master run failed on {}, failure was {}'.format(stock, e))\n\n def save_master_results(self, stock, results):\n file_path = open(os.path.join(self.data.results_data_path, '{}_results.p'.format(stock)), 'wb')\n pickle.dump(results, file_path)\n file_path.close()\n","sub_path":"code/master_run_functions.py","file_name":"master_run_functions.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"166212296","text":"def loop_daily_load(start_year, end_year, start_month, end_month, start_day, end_day):\n # Update the database as NASA adds data\n import MakeDailyCsv\n import LoadDailyMysql\n from generator import generate\n\n year_list = generate(start_year, end_year, 4)\n month_list = generate(start_month, end_month, 2)\n day_list = generate(start_day, end_day, 2)\n\n for year in year_list:\n for month in month_list:\n for day in day_list:\n MakeDailyCsv.make_daily_csv(year, month, day)\n LoadDailyMysql.Load_Daily_Mysql(year, month, day)\n\n","sub_path":"python/Updator/Updator.py","file_name":"Updator.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"137724161","text":"# -*- coding: utf-8 -*-\nimport datetime\n\nfrom django.db import models\n\ndef purificador(nombre):\n \n nombre_copia = nombre\n \n nombre = \"\"\n \n for n in nombre_copia.split(' '):\n \n if not n.isalpha():\n raise\n \n nombre = nombre + \" \" + n.capitalize()\n \n if nombre.startswith(' '):\n nombre = nombre[1:]\n \n return nombre\n\ndef esCUITValida(cuit):\n \n cuit = str(cuit)\n cuit = cuit.replace(\"-\", \"\")\n cuit = cuit.replace(\" \", \"\")\n cuit = cuit.replace(\".\", \"\")\n \n if len(cuit) != 11:\n return False\n \n if not cuit.isdigit():\n return False\n \n base = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]\n aux = 0\n for i in xrange(10):\n aux += int(cuit[i]) * base[i]\n \n aux = 11 - (aux % 11)\n \n if aux == 11:\n aux = 0\n elif aux == 10:\n aux = 9\n \n if int(cuit[10]) == aux:\n return True\n else:\n return False\n\nclass Persona(models.Model):\n \n nombre = models.CharField(max_length=100, null=False, blank=False)\n apellido = models.CharField(max_length=100, null=False, blank=False)\n fecha_nacimiento = models.DateField(null=False, blank=False)\n cuil = models.CharField(max_length=13, null=False, blank=False)\n genero = models.CharField(max_length=1,\n choices=[('F', 'F'), ('M', 'M')],\n default='F')\n estado = models.CharField(max_length=3,\n choices=[('ON', 'ON'), ('OFF', 'OFF')],\n default='ON')\n usuario_creador = models.CharField(max_length=30, default='admin')\n fecha_creacion = models.DateTimeField(auto_now_add=True)\n usuario_modificador = models.CharField(max_length=30, default='admin')\n fecha_modificacion = models.DateTimeField(auto_now=True)\n \n def __str__(self, ):\n return (self.apellido + \", \" + self.nombre).encode('utf-8')\n \n def __eq__(self, o):\n return self.cuil == o.cuil\n \n def set_nombre(self, nombre):\n \n if nombre == \"\":\n raise Exception(\"El nombre no puede estar vacío.\")\n \n try:\n nombre = purificador(nombre)\n except:\n raise Exception(\"El nombre posee caracteres no permitidos.\")\n \n self.nombre = nombre\n \n def set_apellido(self, apellido):\n \n if apellido == \"\":\n raise Exception(\"El apellido no puede estar vacío.\")\n \n try:\n apellido = purificador(apellido)\n except:\n raise Exception(\"El apellido posee caracteres no permitidos.\")\n \n self.apellido = apellido\n \n def set_cuil(self, cuil):\n \n if not esCUITValida(cuil):\n raise Exception(\"El cuil no es válido.\")\n \n self.cuil = cuil\n \n def set_fecha_nacimiento(self, fecha_nacimiento):\n \n try:\n fecha_nacimiento = datetime.datetime.strptime(fecha_nacimiento, \"%Y-%m-%d\").date()\n except:\n raise Exception(\"La fecha de nacimiento no es válida.\")\n \n self.fecha_nacimiento = fecha_nacimiento\n \n def set_genero(self, genero):\n \n self.genero = genero\n","sub_path":"perfil/objects/persona.py","file_name":"persona.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"144012100","text":"import re\n\ndef sgn(i):\n\tif i > 0:\n\t\treturn 1\n\telif i == 0:\n\t\treturn 0\n\telse:\n\t\treturn -1\n\npattern = re.compile(r'')\npositions = []\nvelocities = [[0] * 3 for i in range(4)]\nwith open('12.dat', 'r') as file:\n\tfor line in file:\n\t\tmatch = pattern.match(line.strip())\n\t\tassert match\n\t\tpositions.append([int(match.group(1)), int(match.group(2)), int(match.group(3))])\n\nfor cycle in range(1000):\n\tfor moon in range(4):\n\t\tfor other_moon in range(4):\n\t\t\tfor index in range(3):\n\t\t\t\tvelocities[moon][index] += sgn(positions[other_moon][index] - positions[moon][index])\n\n\tfor moon in range(4):\n\t\tfor index in range(3):\n\t\t\tpositions[moon][index] += velocities[moon][index]\n\nenergy = 0\nfor moon in range(4):\n\tenergy += (abs(positions[moon][0]) + abs(positions[moon][1]) + abs(positions[moon][2])) * (\n\t\t\t\tabs(velocities[moon][0]) + abs(velocities[moon][1]) + abs(velocities[moon][2]))\n\nprint(energy)\n","sub_path":"2019/12a.py","file_name":"12a.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"7020200","text":"from django.contrib import admin\r\nfrom .models import tblStudent, tblUnits, tblClasses\r\n\r\nclass StudentAdmin(admin.ModelAdmin):\r\n list_display = ('name_first', 'name_last', 'date_of_birth' ,'gender' ,'id_foreign_classes')\r\n list_filter = ['gender']\r\n search_fields = ['name_first', 'name_last']\r\n\r\n\r\nclass ClassAdmin(admin.ModelAdmin):\r\n list_display = ('class_code', 'id_foreign_unit_1', 'id_foreign_unit_2', 'id_foreign_unit_3')\r\n fieldsets = [\r\n (None, {'fields':['class_code']}),\r\n ('Units', {'fields': ['id_foreign_unit_1',\r\n 'id_foreign_unit_2',\r\n 'id_foreign_unit_3']}),\r\n ]\r\n\r\nclass UnitAdmin(admin.ModelAdmin):\r\n list_display = ('name_unit','description')\r\n\r\n\r\nadmin.site.register(tblStudent, StudentAdmin)\r\nadmin.site.register(tblClasses, ClassAdmin)\r\nadmin.site.register(tblUnits, UnitAdmin)\r\n","sub_path":"Student_information_system/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"321672522","text":"\"\"\"Test dashboard.services.summaries.\"\"\"\n\nimport pytest\nfrom dateutil.relativedelta import relativedelta\n\n\n@pytest.fixture\ndef summaries():\n \"\"\"Get the module under test.\"\"\"\n from ..services import summaries\n return summaries\n\n\n@pytest.fixture\ndef datetime():\n \"\"\"Provide fixture for datetime.\"\"\"\n import datetime\n return datetime\n\n\n@pytest.fixture\ndef make_one(summaries):\n \"\"\"Provide an function to make an instance of the CUT.\"\"\"\n def _make_one(**kwargs):\n defaults = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n defaults.update(**kwargs)\n s = summaries.create(**defaults)\n return s\n return _make_one\n\n\ndef test_make_one(make_one):\n \"\"\"Ensure our maker makes properly.\"\"\"\n s = make_one(incomplete=3, complete=2, total=5)\n assert s.incomplete == 3\n assert s.complete == 2\n assert s.total == 5\n\n\ndef test_setup(summaries):\n \"\"\"Ensure we wired the test up.\"\"\"\n assert summaries\n\n\ndef test_make_summary(summaries):\n \"\"\"Ensure we can create a summary.\"\"\"\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n\n s = summaries.create(**data)\n\n for key, value in data.items():\n assert getattr(s, key) == value\n\n\ndef test_make_summary_adds_the_date(summaries, datetime):\n \"\"\"A date is added to the summary when created.\"\"\"\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n )\n\n s = summaries.create(**data)\n assert s.created_on == datetime.date.today()\n\n\ndef test_make_summary_honors_date_arg(summaries, datetime):\n \"\"\"A date arg is honored when passed.\"\"\"\n yesterday = datetime.date.today() - relativedelta(days=1)\n data = dict(\n filter_id=6292809552232448,\n incomplete=5,\n complete=10,\n total=15,\n created_on=yesterday,\n )\n s = summaries.create(**data)\n assert s.created_on == yesterday\n\n\ndef test_summary_object_provides_pct_complete(make_one):\n \"\"\"A summary object provides a percent complete.\"\"\"\n kwargs = dict(\n incomplete=2,\n complete=4,\n total=6\n )\n s = make_one()\n assert s.pct_complete == kwargs['complete'] / float(kwargs['total'])\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_store(summaries, make_one):\n \"\"\"Ensure we can store summary objects.\"\"\"\n s = make_one()\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_update(summaries, make_one):\n \"\"\"Ensure multiple calls to create on the same date return the same obj.\"\"\"\n s = make_one()\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n s2 = make_one(incomplete=1, complete=2, total=3)\n s2, result = summaries.store(s2)\n assert result == summaries.UPDATED\n assert s2.id == s.id\n assert (1, 2, 3) == (s2.incomplete, s2.complete, s2.total)\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_update_different_filters(summaries, make_one):\n \"\"\"Ensure multiple calls to create on the same date/diff filter return the same obj.\"\"\"\n s = make_one(filter_id=1234)\n s, result = summaries.store(s)\n assert result == summaries.SAVED\n assert s.id\n\n s2 = make_one(filter_id=5678)\n s2, result = summaries.store(s2)\n assert result == summaries.SAVED\n assert s2.id != s.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_for_date(summaries, make_one, datetime):\n \"\"\"Ensure we can find summaries from the past.\"\"\"\n week_ago = datetime.date.today() - relativedelta(days=7)\n\n s1 = make_one(created_on=week_ago)\n s2 = make_one()\n\n s1, result = summaries.store(s1)\n s2, result = summaries.store(s2)\n\n s3 = summaries.for_date(filter_id=s2.filter_id, date=week_ago)\n assert s3.id == s1.id\n\n\n@pytest.mark.system\n@pytest.mark.django_db\ndef test_for_date_sad(summaries, make_one, datetime):\n \"\"\"Validate what happens when we can't find summaries from the past.\"\"\"\n week_ago = datetime.date.today() - relativedelta(days=7)\n\n s1 = make_one()\n s2 = summaries.for_date(filter_id=s1.filter_id, date=week_ago)\n assert s2 is None\n","sub_path":"dashboard/tests/test_services_summaries.py","file_name":"test_services_summaries.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"206530634","text":"# coding:utf-8\n# 2019/10/15\n# 线性回归\n\nimport sys\nsys.path.append('../../')\n\nfrom sklearn import linear_model\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor, AdaBoostRegressor, BaggingRegressor\nfrom sklearn.svm import SVR, LinearSVR\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom xgboost import XGBRegressor\n\nimport numpy as np\nimport pickle \n\nfrom util import io\n\ndef getModel(modelName):\n\t\"\"\"选择模型\"\"\"\n\tmodelDict = {\n\t\t\"Linear\" : linear_model.LinearRegression(),\n\t\t\"Ridge\": linear_model.Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,\n\t \tnormalize=False, random_state=None, solver='auto', tol=0.001),\n\t\t\"Lasso\" : linear_model.Lasso(alpha=0.1, copy_X=True, fit_intercept=True, max_iter=1000,\n \t\t\tnormalize=False, positive=False, precompute=False, random_state=None,\n \t\t\tselection='cyclic', tol=0.0001, warm_start=False),\n\t\t\"ElasticNet\" : linear_model.ElasticNet(alpha=0.001,max_iter=10000),\n\t\t\"GradientBoosting\" : GradientBoostingRegressor(),\n\t\t\"SVR\" : SVR(),\n\t\t\"XGB\" : XGBRegressor(), \n\t\t\"AdaBoost\" : AdaBoostRegressor(n_estimators=50),\n\t\t\"Bagging\" : BaggingRegressor(),\n\t}\n\n\treturn modelDict[modelName]\n\ndef train(reg, X, Y):\n\t\"\"\"\n\t@param reg 训练模型\n\t@param X 训练数据\n\t@param Y 标签\n\t\"\"\"\n\t# reg = linear_model.Ridge(alpha=0.5, copy_X=True, fit_intercept=True, max_iter=None,\n\t# normalize=False, random_state=None, solver='auto', tol=0.001)\n\treg.fit(X, Y) \n\tprint(\"w: {}\\n, b: {}\".format(reg.coef_, reg.intercept_))\n\n\treturn reg\n\ndef main():\n\tdataFilePath = \"../../data/samples-data.data\"\n\tlabelsFilePath = \"../../data/samples-data-labels.data\"\n\tX = io.getData(dataFilePath)\n\tY = io.getData(labelsFilePath)\n\tmodelNames = [\"Linear\", \"Ridge\", \"Lasso\", \"ElasticNet\", \"GradientBoosting\"]\n\tfor modelName in modelNames:\n\t\treg = getModel(modelName)\n\n\t\tmodel = train(reg, X, Y)\n\t\tio.saveData(model, \"../../data/{}.model\".format(modelName))\n\nif __name__ == '__main__':\n\tmain()","sub_path":"tool/毕设代码/algorithms/regression/Regression.py","file_name":"Regression.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"449476124","text":"from __future__ import absolute_import, division\nimport numpy as np\nfrom numba import jit\nimport timeit\n#from test_arrays import X_train,expand_window_input\n\ntry:\n range = xrange\nexcept NameError:\n pass\n\n@jit(nopython=True)\ndef __difference_numba(a, b):\n return abs(a-b)\n\n@jit(nopython=True)\ndef __reduce_by_half_numba(x):\n return [(x[i] + x[1+i]) / 2 for i in range(0, len(x) - len(x) % 2, 2)]\n\n@jit(nopython=True)\ndef __expand_window_numba(path, len_x, len_y, radius):\n path_ = set(path)\n for i, j in path:\n for a, b in [(i + a, j + b) for a in range(-radius, radius+1) for b in range(-radius, radius+1)]:\n path_.add((a, b))\n\n window_ = set()\n for i, j in path_:\n for a, b in ((i * 2, j * 2), (i * 2, j * 2 + 1),\n (i * 2 + 1, j * 2), (i * 2 + 1, j * 2 + 1)):\n window_.add((a, b))\n\n window = []\n start_j = 0\n for i in range(0, len_x):\n new_start_j = None\n for j in range(start_j, len_y):\n if (i, j) in window_:\n window.append((i, j))\n if new_start_j is None:\n new_start_j = j\n elif new_start_j is not None:\n break\n start_j = new_start_j\n\n return window\n\n@jit(nopython=True)\ndef __dtw_numba(x, y, window):\n len_x, len_y = len(x), len(y)\n if window is None:\n window = [(i, j) for i in range(len_x) for j in range(len_y)]\n window = [(i + 1, j + 1) for i, j in window]\n\n #my code\n D=np.full((window[-1][0]+1,window[-1][1]+1,3),np.inf)\n D[0, 0] = np.array([0, 0, 0])\n\n for i,j in window:\n dt = __difference_numba(x[i-1], y[j-1])\n priors=np.array([(D[i-1, j][0], i-1, j), (D[i, j-1][0], i, j-1),\n (D[i-1, j-1][0], i-1, j-1)])\n D[i,j] = priors[np.argmin(priors[:,0])]\n D[i,j][0]+=dt\n\n path = []\n i, j = len_x, len_y\n while not (i == j == 0):\n path.append((i-1, j-1))\n i, j = int(D[i, j][1]), int(D[i, j][2])\n path.reverse()\n return (D[len_x, len_y][0], path)\n\n@jit(nopython=True)\ndef __fastdtw_numba(x, y, radius):\n min_time_size = radius + 2\n\n if len(x) < min_time_size or len(y) < min_time_size:\n return dtw(x, y)\n\n x_shrinked = __reduce_by_half_numba(x)\n y_shrinked = __reduce_by_half_numba(y)\n distance, path = \\\n __fastdtw_numba(x_shrinked, y_shrinked, radius=radius)\n window = __expand_window_numba(path, len(x), len(y), radius)\n return __dtw_numba(x, y, window)\n\n@jit(nopython=True)\ndef dtw(x, y):\n ''' return the distance between 2 time series without approximation\n Parameters\n ----------\n x : array_like\n input array 1\n y : array_like\n input array 2\n dist : function or int\n The method for calculating the distance between x[i] and y[j]. If\n dist is an int of value p > 0, then the p-norm will be used. If\n dist is a function then dist(x[i], y[j]) will be used. If dist is\n None then abs(x[i] - y[j]) will be used.\n Returns\n -------\n distance : float\n the approximate distance between the 2 time series\n path : list\n list of indexes for the inputs x and y\n Examples\n --------\n >>> import numpy as np\n >>> import fastdtw\n >>> x = np.array([1, 2, 3, 4, 5], dtype='float')\n >>> y = np.array([2, 3, 4], dtype='float')\n >>> fastdtw.dtw(x, y)\n (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])\n '''\n return __dtw_numba(x, y, None)\n\n@jit(nopython=True)\ndef fastdtw(x, y, radius=1):\n ''' return the approximate distance between 2 time series with O(N)\n time and memory complexity\n Parameters\n ----------\n x : array_like\n input array 1\n y : array_like\n input array 2\n radius : int\n size of neighborhood when expanding the path. A higher value will\n increase the accuracy of the calculation but also increase time\n and memory consumption. A radius equal to the size of x and y will\n yield an exact dynamic time warping calculation.\n dist : function or int\n The method for calculating the distance between x[i] and y[j]. If\n dist is an int of value p > 0, then the p-norm will be used. If\n dist is a function then dist(x[i], y[j]) will be used. If dist is\n None then abs(x[i] - y[j]) will be used.\n ##### Currently not functional, always will use abs.\n Returns\n -------\n distance : float\n the approximate distance between the 2 time series\n path : list\n list of indexes for the inputs x and y\n Examples\n --------\n >>> import numpy as np\n >>> import fastdtw\n >>> x = np.array([1, 2, 3, 4, 5], dtype='float')\n >>> y = np.array([2, 3, 4], dtype='float')\n >>> fastdtw.fastdtw(x, y)\n (2.0, [(0, 0), (1, 0), (2, 1), (3, 2), (4, 2)])\n '''\n return __fastdtw_numba(x, y, radius)\n\na=np.array([1.0,2.0,3.0],dtype=np.float)\nb=np.array([2.0,3.0,4.0],dtype=np.float)\nd=2.0\nc=4.7\ne=2\nf=[1.0,2.0,3.0]\ng=[1.0,2.0,3.0]\n\ndef main():\n '''a=np.array([1.0,2.0,3.0],dtype=np.float)\n b=np.array([2.0,3.0,4.0],dtype=np.float)\n d=2.0\n c=4.7\n e=2'''\n fastdtw(X_train[0],X_train[-1])\n #__expand_window(expand_window_input[0],expand_window_input[1],expand_window_input[2],expand_window_input[3])\n #cProfile.run('fastdtw(f,g)')\n #__dtw(a,b,None,__difference)\n #fastdtw.inspect_types()\n\n\nif __name__==\"__main__\":\n main()\n #print (timeit.timeit(\"main()\",\"gc.enable; from __main__ import main\",number=100))\n","sub_path":"dtw_stuff/fastdtw_numba.py","file_name":"fastdtw_numba.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"100085346","text":"import os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\nimport random\nimport torch\ntorch.set_num_threads(1)\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport argparse\nimport numpy as np\nfrom torch.utils.tensorboard import SummaryWriter\n\n\nfrom experiment import ex\nfrom model import load_model, save_model\nfrom utils import post_config_hook\n\nfrom modules import LogisticRegression\nfrom modules.deepmil import Attention\nfrom modules.transformations import TransformsSimCLR\nfrom modules.losses.focal_loss import FocalLoss\nfrom modules.Splitter import split_indices_by_patient, split_indices, get_train_val_indices\n\nfrom msidata.dataset_msi import PreProcessedMSIDataset as dataset_msi\nfrom msidata.save_feature_vectors import infer_and_save, aggregate_patient_vectors\nfrom msidata.dataset_msi_features_with_patients import PreProcessedMSIFeatureDataset\nfrom msidata.dataset_tcga_tiles import TiledTCGADataset as dataset_tcga\n\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport time\nimport datetime\nimport json\n\nfrom sklearn import metrics\n\n\ndef infer(args, loader, context_model, device):\n # get encoding of images\n feature_vector, labels_vector, patients, imgs = [], [], [], []\n for step, (x, y, patient, img_name, _) in enumerate(loader):\n x = x.to(device)\n with torch.no_grad():\n if args.logistic_extractor == 'simclr':\n h, z = context_model(x)\n else:\n h = context_model(x)\n h = h.detach()\n feature_vector.extend(h.cpu().detach().numpy())\n labels_vector.extend(y.numpy())\n\n if step % 20 == 0:\n print(f\"Step [{step}/{len(loader)}]\\t Computing features...\")\n\n patients+=patient\n imgs+=img_name\n\n feature_vector = np.array(feature_vector)\n labels_vector = np.array(labels_vector)\n return feature_vector, labels_vector, patients, imgs\n\n\ndef get_features(args, context_model, train_loader, val_loader, test_loader, device):\n train_X, train_y, train_patients, train_imgs = infer(args, train_loader, context_model, device)\n val_X, val_y, val_patients, val_imgs = infer(args, val_loader, context_model, device)\n test_X, test_y, test_patients, test_imgs = infer(args, test_loader, context_model, device)\n return train_X, train_y, val_X, val_y, test_X, test_y, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs\n\n\ndef create_data_loaders_from_arrays(X_train, y_train, X_val, y_val, X_test, y_test, batch_size, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs):\n train = torch.utils.data.TensorDataset(\n torch.from_numpy(X_train), torch.from_numpy(y_train), torch.Tensor(train_patients)\n )\n train_loader = torch.utils.data.DataLoader(\n train, batch_size=batch_size, shuffle=False\n )\n\n val = torch.utils.data.TensorDataset(\n torch.from_numpy(X_val), torch.from_numpy(y_val), torch.Tensor(val_patients)\n )\n val_loader = torch.utils.data.DataLoader(\n val, batch_size=batch_size, shuffle=False\n )\n\n test = torch.utils.data.TensorDataset(\n torch.from_numpy(X_test), torch.from_numpy(y_test), torch.Tensor(test_patients)\n )\n test_loader = torch.utils.data.DataLoader(\n test, batch_size=batch_size, shuffle=False\n )\n return train_loader, val_loader, test_loader\n\n\ndef train(args, train_loader, val_loader, extractor, model, criterion, optimizer, val_losses, val_roc, global_step, epoch, writer):\n loss_epoch = 0\n accuracy_epoch = 0\n for step, data in enumerate(train_loader):\n global_step += 1\n print(f\"[ Step {global_step} / {len(train_loader)} ] @ {datetime.datetime.now()}\")\n optimizer.zero_grad()\n x = data[0].to(args.device) \n y = data[1].to(args.device)\n\n if not (args.precompute_features or args.use_precomputed_features):\n if args.freeze_encoder:\n extractor.eval()\n with torch.no_grad():\n out = extractor.forward(x)\n else:\n extractor.train()\n out = extractor.forward(x)\n \n if args.logistic_extractor=='simclr': # Simclr returns (h, z)\n h = out[0]\n x = h\n else: # Torchvision models return h\n h = out\n x = h # We name it x, since it's the input for the logistic regressors, and it saves some memory\n \n model.train()\n if args.classification_head == 'logistic':\n y = y.long()\n output = model(x)\n if not args.use_focal_loss:\n loss = criterion(output, y)\n else: # use focal loss\n focal = FocalLoss(args.focal_loss_alpha, args.focal_loss_gamma)\n loss = torch.nn.functional.cross_entropy(output,y, reduction='none')\n loss = focal(loss)\n\n predicted = output.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n\n elif args.classification_head == 'linear':\n output = model(x).flatten() # output \\in R^(batch_size*1)\n loss = criterion(output.flatten(), y.flatten())\n loss_epoch += loss.item() \n acc = 0 # accuracy is not meaningful here\n \n elif args.classification_head == 'deepmil':\n y = y.long() # Might be a float if we use TCGA since we do a groupby.mean() operation\n Y_prob, Y_hat, A = model.forward(x)\n loss = criterion(Y_prob, y)\n train_loss = loss.item()\n loss_epoch += train_loss\n error, _ = model.calculate_classification_error(y, Y_hat)\n acc = 1. - error\n\n elif args.classification_head == 'linear-deepmil':\n Y_prob, Y_hat, A = model.forward(x) # Y_prob == Y_hat, in the linear case\n y = y.flatten() # shape([1, 1]) -> shape([1])\n loss = criterion(Y_prob.flatten(), y.flatten())\n train_loss = loss.item()\n loss_epoch += train_loss\n acc = 0 # meaningless here\n\n elif 'cnn' in args.classification_head:\n y = y.long()\n out = model.forward(x)\n loss = criterion(out, y)\n predicted = out.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n\n if not args.freeze_encoder and args.debug:\n previous_weights_of_last_layer = [param.clone().detach() for param in extractor.parameters()][-2]\n\n accuracy_epoch += acc\n loss.backward() # Depending on the setup: Computes gradients for classifier and possibly extractor\n optimizer.step() # Can update both the classifier and the extractor, depending on the options\n \n if not args.freeze_encoder and args.debug:\n new_weights_of_last_layer = [param.clone().detach() for param in extractor.parameters()][-2]\n assert(not torch.eq(new_weights_of_last_layer, previous_weights_of_last_layer).all()), \"The weights are not being updated!\"\n\n # Evaluate on validation set\n if global_step % args.evaluate_every == 0:\n # evaluate\n val_loss, val_accuracy, val_labels, val_preds, val_patients, _, _, _, _, _ = validate(args, val_loader, extractor, model, criterion, optimizer, final_test=False)\n val_losses.append(val_loss / len(val_loader))\n\n if args.classification_head not in ['linear', 'linear-deepmil']:\n # COMPUTE ROCAUC PER PATIENT. If we use a patient-level prediction, group and mean doesn't do anything. \n # If we use a tile-level prediciton, group and mean create a fraction prediction\n val_data, rocauc = compute_roc_auc(args, val_patients, val_labels, val_preds, save_curve=False)\n writer.add_scalar(\"loss/val\", val_loss / len(val_loader), epoch)\n writer.add_scalar(\"loss/train\", loss.cpu().item(), epoch)\n writer.add_scalar(\"rocauc/val\", rocauc, epoch)\n val_roc.append(rocauc)\n print(f\"{datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')} | Epoch [{epoch+1}/{args.logistic_epochs}]\\tStep [{step}/{len(train_loader)}]\\t Train loss: {loss.cpu().item()}\\tVal Loss: {val_loss / len(val_loader)}\\tAccuracy: {val_accuracy / len(val_loader)}\\tROC AUC: {rocauc}\")\n else:\n # COMPUTE R2 PER PATIENT.\n val_data, r2 = compute_r2(val_patients, val_labels, val_preds)\n writer.add_scalar(\"loss/val\", val_loss / len(val_loader), epoch)\n writer.add_scalar(\"r2/val\", r2, epoch)\n val_roc.append(r2)\n print(f\"{datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d %H:%M:%S')} | Epoch [{epoch+1}/{args.logistic_epochs}]\\tStep [{step}/{len(train_loader)}]\\tVal Loss: {val_loss / len(val_loader)}\\tAccuracy: {val_accuracy / len(val_loader)}\\tR2: {r2}\")\n \n # Save model with each evaluation\n args.global_step = global_step\n if extractor:\n # We don't always have an extractor, e.g. when we use precomputed features\n save_model(args, extractor, None, prepend='extractor_')\n # Save classification model, which is the primary model being trained here\n save_model(args, model, None, prepend='classifier_')\n \n\n return loss_epoch, accuracy_epoch, val_losses, val_roc, global_step\n\n\ndef validate(args, loader, extractor, model, criterion, optimizer, final_test=False):\n loss_epoch, accuracy_epoch = 0, 0\n labels, preds, patients, img_names, attentions, attention_gradients, subsample_indices, predicted_probs = [], [], [], [], [], [], [], []\n\n model.eval()\n\n for step, data in enumerate(loader):\n model.zero_grad()\n\n x = data[0]\n y = data[1]\n patient = data[2]\n img_names += data[3] # a list of strings, each of one patient -> e.g. ['grid_123.pt', 'grid_234.pt', 'grid_345.pt', 'grid_456.pt']\n subsample_indices += data[4] # a list of indices per patient -> e.g. [ [1, 2, 6, 7] , [4, 6, 8, 10] , [1, 14, 17, 200] ]\n\n x = x.to(args.device)\n y = y.to(args.device)\n\n if not (args.precompute_features or args.use_precomputed_features):\n # x is an image not yet a feature vector\n extractor.eval()\n\n with torch.no_grad():\n out = extractor.forward(x)\n\n if args.logistic_extractor=='simclr': # Simclr returns (h, z)\n h = out[0]\n x = h\n else: # Torchvision models return h\n h = out\n x = h # We name it x, since it's the input for the logistic regressors\n \n else:\n # x is already a feature vector, and can go straight into the classifier\n pass\n\n if args.classification_head == 'logistic':\n y = y.long()\n with torch.no_grad():\n output = model(x)\n if not args.use_focal_loss:\n loss = criterion(output, y)\n else:\n # use focal loss\n focal = FocalLoss(args.focal_loss_alpha, args.focal_loss_gamma)\n loss = torch.nn.functional.cross_entropy(output,y, reduction='none')\n loss = focal(loss)\n\n predicted = output.argmax(1)\n predicted_prob = torch.nn.functional.softmax(output, dim=1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n predicted_probs += predicted_prob.cpu().tolist()\n\n elif args.classification_head == 'linear':\n with torch.no_grad():\n output = model(x).flatten()\n loss = criterion(output.flatten(), y.flatten())\n predicted = output\n acc = 0 # meaningless for linear regression\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n\n elif args.classification_head == 'deepmil':\n if final_test:\n x.requires_grad = True\n with torch.set_grad_enabled(final_test): ## We do want gradients for the final test, in order to do some nice visualization with the gradients & attention\n\n y = y.long() # Might be a float when using TCGA data due to groupby.mean() operator\n Y_prob, Y_hat, A = model.forward(x)\n loss = criterion(Y_prob, y)\n train_loss = loss.item()\n loss_epoch += train_loss\n error, _ = model.calculate_classification_error(y, Y_hat)\n acc = 1. - error \n binary_Y_prob = Y_prob.softmax(dim=1)[:,1] # Get the probability of it being class 1\n preds += binary_Y_prob.cpu().tolist() \n if final_test:\n # print(f\"Shape of x: {x.shape}\")\n # print(f\"Shape of A: {A.shape}\")\n # print(f\"Shape of binary_Y_prob: {binary_Y_prob}\")\n\n ## Get the DeepMIL attention gradients\n for i, patient_probability in enumerate(binary_Y_prob): # Pytorch can't do elemnt-wise backwards\n\n # print(f\"Shape of patient probability: {patient_probability}\")\n \n patient_probability.backward(retain_graph=True) # So we do a backward pass per patient\n dPositiveClassdA = model.A_grad[i].flatten() # Which means we now get a gradient from attention to class probability for each tile for the patient\n # since attention is batch x tiles x 1, we want the index of the patient we look at now, and flatten it.\n \n # print(f\"Shape of a single dPositiveClassdA: {dPositiveClassdA.shape}\")\n # print(f\"{i}: {dPositiveClassdA}\")\n attention_gradients.append(dPositiveClassdA.cpu().tolist()) # We save these as a list per patient\n model.zero_grad() # We remove the created gradients, so that they are not accumulated\n\n attentions += A.flatten(start_dim=1, end_dim=-1).cpu().tolist() # save attention as a list of attentions per patient\n\n elif args.classification_head == 'linear-deepmil':\n with torch.no_grad():\n Y_prob, Y_hat, A = model.forward(x)\n y = y.flatten() # torch.size([1,1]) -> torch.size([1])\n loss = criterion(Y_prob.flatten(), y.flatten())\n train_loss = loss.item()\n loss_epoch += train_loss\n acc = 0\n preds += Y_prob.cpu().tolist()\n\n elif 'cnn' in args.classification_head:\n with torch.no_grad():\n y = y.long()\n out = model.forward(x)\n loss = criterion(out, y)\n predicted = out.argmax(1)\n acc = (predicted == y).sum().item() / y.size(0)\n loss_epoch += loss.item()\n preds += predicted.cpu().tolist()\n\n accuracy_epoch += acc\n labels += y.cpu().tolist()\n \n if isinstance(patient, torch.Tensor):\n # Happens when using dataset_msi, as we return a hash, which is an integer, which is made into a tensor\n patients += patient.cpu().tolist()\n else:\n # Happens when using dataset_Msi_features_with_patients, as we return the patient id as a string, which can't be tensorfied\n patients += list(patient)\n\n return loss_epoch, accuracy_epoch, labels, preds, patients, attentions, attention_gradients, img_names, subsample_indices, predicted_probs\n\n\ndef get_precomputed_dataloader(args, run_id):\n print(f\"### Loading precomputed feature vectors from run id: {run_id} ####\")\n\n if args.dataset in ['msi-tcga', 'basis']:\n assert ('load_wsi_level_tensors' in vars(args).keys()), \"For TCGA we switched to WSI-level tensors. Please add 'load_wsi_level_tensors' (bool) to your config file\"\n\n #assert(args.load_patient_level_tensors and args.logistic_batch_size==1) or not args.load_patient_level_tensors, \"We can only use batch size=1 for patient-level tensors, due to different size of tensors\"\n\n if args.load_patient_level_tensors:\n sampling_strategy='patient'\n else:\n sampling_strategy='tile'\n\n if 'deepmil' in args.classification_head:\n stack_grid = True\n else:\n stack_grid = False\n\n if args.dataset=='msi-kather':\n\n train_dataset = PreProcessedMSIFeatureDataset(\n root_dir=args.path_to_msi_data, \n transform=None, \n data_fraction=1,\n sampling_strategy=sampling_strategy,\n append_img_path_with=f'_{run_id}',\n tensor_per_patient=args.load_patient_level_tensors,\n seed=args.seed,\n pad_tiles=args.logistic_batch_size > 1\n \n )\n test_dataset = PreProcessedMSIFeatureDataset(\n root_dir=args.path_to_test_msi_data, \n transform=None, \n data_fraction=1,\n sampling_strategy=sampling_strategy,\n append_img_path_with=f'_{run_id}',\n tensor_per_patient=args.load_patient_level_tensors,\n seed=args.seed,\n pad_tiles=args.logistic_batch_size > 1\n )\n\n elif args.dataset in ['msi-tcga', 'basis']:\n train_dataset, test_dataset, val_dataset = [dataset_tcga(\n args=args,\n csv_file=args.path_to_msi_data, \n root_dir=args.root_dir_for_tcga_tiles, \n transform=None,\n precomputed=True,\n precomputed_from_run=run_id,\n tensor_per_wsi=args.load_wsi_level_tensors,\n split_num=args.kfold,\n label=args.ddr_label,\n split=current_split,\n load_tensor_grid=args.load_tensor_grid,\n stack_grid=stack_grid,\n load_normalized_tiles=args.load_normalized_tiles,\n dataset=args.dataset\n ) for current_split in ['train', 'test', 'val']]\n\n if args.dataset=='msi-kather':\n train_indices, val_indices = get_train_val_indices(train_dataset, val_split=args.validation_split)\n train_sampler = SubsetRandomSampler(train_indices)\n val_sampler = SubsetRandomSampler(val_indices)\n val_dataset=train_dataset\n elif args.dataset in ['msi-tcga','basis']:\n train_sampler=None\n val_sampler=None\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=False,\n num_workers=args.workers,\n sampler=train_sampler\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=False,\n num_workers=args.workers,\n sampler=val_sampler\n )\n\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=args.logistic_batch_size,\n shuffle=False,\n drop_last=False,\n num_workers=args.workers,\n )\n\n assert (len(train_loader) != len(test_loader))\n assert (len(train_loader) != len(val_loader))\n assert (len(val_loader) != len(test_loader))\n\n return train_loader, val_loader, test_loader\n\ndef set_seed(seed):\n np.random.seed(seed)\n random.seed(seed)\n torch.manual_seed(seed)\n\ndef write_hparams(writer, config, metric):\n config_vars = vars(config)\n for key in config_vars.keys():\n if isinstance(config_vars[key], bool):\n if config_vars[key]:\n config_vars[key] = 1\n else:\n config_vars[key] = 0\n \n del config_vars['device']\n\n writer.add_hparams(config_vars, metric)\n\ndef compute_roc_auc(args, patients, labels, preds, save_curve=False, epoch=0):\n data = pd.DataFrame(data={'patient': patients, 'labels': labels, 'preds': preds})\n dfgroup = data.groupby(['patient']).mean()\n labels = dfgroup['labels'].values\n preds = dfgroup['preds'].values\n print(f\"Y_true: {labels}\")\n print(f\"Y_score: {preds}\")\n rocauc = metrics.roc_auc_score(y_true=labels, y_score=preds)\n\n if save_curve:\n fpr, tpr, threshold = metrics.roc_curve(labels, preds)\n\n plt.title('Receiver Operating Characteristic')\n plt.plot(fpr, tpr, 'b', label = 'AUC = %0.2f' % rocauc)\n plt.legend(loc = 'lower right')\n plt.plot([0, 1], [0, 1],'r--')\n plt.xlim([0, 1])\n plt.ylim([0, 1])\n plt.ylabel('True Positive Rate')\n plt.xlabel('False Positive Rate')\n\n plt.savefig(f'{args.out_dir}/roc_curve_epoch_{epoch}.png')\n\n return data, rocauc\n\ndef compute_r2(patients, labels, preds):\n data = pd.DataFrame(data={'patient': patients, 'labels': labels, 'preds': preds})\n dfgroup = data.groupby(['patient']).mean() # Let's just try taking the mean of all the tile predictions.. for now.. if it's linear-deepmil this will keep them as is\n labels = dfgroup['labels'].values # all continues values\n preds = dfgroup['preds'].values # all continues values\n r2=metrics.r2_score(y_true=labels, y_pred=preds)\n return data, r2\n\ndef save_attention(args, img_names, attentions, attention_gradients, subsample_indices, out_dir, humane_readable_time, epoch):\n\n all_x_coords, all_y_coords, all_tile_names, all_patient_ids = [], [], [], []\n\n for img_name, subsample_indices_per_patient, attention_per_patient, attention_gradient_per_patient in zip(img_names, subsample_indices, attentions, attention_gradients):\n\n # read grid with tiles\n meta_img_name = img_name.replace('grid_extractor', 'grid_paths_and_coords_extractor')\n meta_img = torch.load(meta_img_name, map_location='cpu')\n if args.dataset == 'msi-tcga':\n patient_id = img_name.split('/')[5].split('case-')[1] # all img names are from the same patient ID\n elif args.dataset == 'basis':\n patient_id = img_name.split('/')[4].split('case-')[1] # this is incorrect. img_name e.g. = /project/schirris/tiled_data_large/case-PD9578a/pid_YID161_tile_grid_extractor_585.pt\n tile_names = list(meta_img[0])\n coords = meta_img[1]\n tile_names = [tile_names[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n x_coords_unsampled = coords[:,0]\n y_coords_unsampled = coords[:,1]\n x_coords = [x_coords_unsampled[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n y_coords = [y_coords_unsampled[int(i)] if not torch.isnan(i) else np.nan for i in subsample_indices_per_patient]\n\n\n # We pad the left withe [None]s, because the subsample indices might be smaller than the actual array, and therefore smaller than the attention array\n # In order to make DeepMIL work with a bigger batch_size than 1, we pad each \"bag\" with zero-vectors. For consistency's sake, we continued doing this when\n # subsampling. However, in this case, this would lead to a larger attention vector than there are actual images. This would not be savable.\n # However, since we want to see how much attention there is on zero-vectors (as a sanity check) we want to save this, but with empty tile names and empty\n # coordinates\n tile_names = [np.nan] * (len(attention_per_patient) - len(tile_names)) + tile_names\n x_coords = [np.nan] * (len(attention_per_patient) - len(x_coords)) + x_coords\n y_coords = [np.nan] * (len(attention_per_patient) - len(y_coords)) + y_coords\n patient_ids = [patient_id] * len(tile_names)\n \n\n all_x_coords += x_coords # These are all a single list of objects now\n all_y_coords += y_coords\n all_tile_names += tile_names\n all_patient_ids += patient_ids\n\n\n attention_df = pd.DataFrame({\"tile_name\": all_tile_names, \"patient_id\": all_patient_ids, \"attention\": np.array(attentions).flatten(), \"attention_gradients\": np.array(attention_gradients).flatten(), 'x': all_x_coords, 'y': all_y_coords})\n\n attention_df.to_csv(f'{out_dir}/attention_output_epoch_{epoch}_{humane_readable_time}.csv')\n\n\ndef save_probabilities(args, img_names, predicted_probs, labels, out_dir, humane_readable_time, epoch):\n data = pd.DataFrame(data={'img': img_names, 'labels': labels, 'probs': predicted_probs})\n data.to_csv(f'{out_dir}/probabilities_output_epoch_{epoch}_{humane_readable_time}.csv')\n\n\n@ex.automain\ndef main(_run, _log):\n args = argparse.Namespace(**_run.config)\n args = post_config_hook(args, _run)\n args.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n if 'debug' not in vars(args).keys():\n args.debug = False\n\n if 'load_normalized_tiles' not in vars(args).keys():\n args.load_normalized_tiles = False\n\n if 'test_deepmil_subsample' in vars(args).keys():\n print(f\"*=*=*=*=* We will perform a subsampling experiment with {args.test_deepmil_subsample} subsampled tiles *=*=*=*=*\")\n\n if 'deepmil_intermediate_hidden' not in vars(args).keys():\n args.deepmil_intermediate_hidden = 128\n \n if 'reload_classifier' not in vars(args).keys():\n args.reload_classifier = False\n\n\n set_seed(args.seed)\n\n if 'train_extractor_on_generated_labels' in vars(args).keys():\n if args.train_extractor_on_generated_labels:\n assert('generated_labels_id' in vars(args).keys()), \"Please set the ID of the run that generated the labels\"\n assert('generated_label' in vars(args).keys()), \"Please set the label you want to use\"\n assert(args.generated_label != 'label'), \"Please set a non-standard label, otherwise we're not doing anything interesting\"\n assert(not args.freeze_encoder), \"If we want to finetune, we should not freeze the encoder\"\n assert(not args.precompute_features), \"If we want to finetune, we should not precompute any features. We should run the images through the encoder\"\n assert(args.classification_head == 'logistic'), \"We want to do tilewise predictions with our new tile-level labels!\"\n with open(f'./logs/{args.generated_labels_id}/config.json') as f:\n config_of_label_creation = json.load(f)\n assert(args.seed == config_of_label_creation['seed']), f\"Current seed: {args.seed}. Seed during label creation of run {args.generated_labels_id}: {config_of_label_creation['seed']}. Ensure they are equal to get the same train-test split\"\n\n tb_dir = os.path.join(args.out_dir, _run.experiment_info[\"name\"])\n os.makedirs(tb_dir)\n writer = SummaryWriter(log_dir=tb_dir)\n\n if 'train_extractor_on_generated_labels' in vars(args).keys():\n if args.train_extractor_on_generated_labels:\n label = args.generated_label\n load_labels_from_run = args.generated_labels_id\n else:\n label = 'label'\n load_labels_from_run=''\n else:\n label = 'label'\n load_labels_from_run=''\n\n if args.dataset == \"msi-kather\":\n train_dataset = dataset_msi(\n root_dir=args.path_to_msi_data, \n transform=TransformsSimCLR(size=224).test_transform, \n data_fraction=args.data_testing_train_fraction,\n seed=args.seed,\n label=label,\n load_labels_from_run=load_labels_from_run\n )\n test_dataset = dataset_msi(\n root_dir=args.path_to_test_msi_data, \n transform=TransformsSimCLR(size=224).test_transform, \n data_fraction=args.data_testing_test_fraction,\n seed=args.seed,\n label=label,\n load_labels_from_run=load_labels_from_run\n )\n elif args.dataset in [\"msi-tcga\", \"basis\"]:\n args.data_pretrain_fraction=1 \n assert ('.csv' in args.path_to_msi_data), \"Please provide the tcga .csv file in path_to_msi_data\"\n assert ('root_dir_for_tcga_tiles' in vars(args).keys()), \"Please provide the root dir for the tcga tiles\"\n\n\n # TODO Add the HE normalization from config arguments to the code below\n # Then commit\n # Then push\n # Then test\n if ('he_norm' in vars(args).keys()) and ('he_norm_method' in vars(args).keys()):\n if args.he_norm:\n he_normalization=args.he_norm_method\n if he_normalization == 'macenko':\n assert(os.path.isfile(args.he_norm_target)), f\"he_norm_target: {args.he_norm_target} is not an existing file\"\n he_norm_target = args.he_norm_target\n else:\n he_normalization = ''\n he_norm_target = ''\n else:\n he_normalization = ''\n he_norm_target = ''\n\n tcga_transform = TransformsSimCLR(size=224, henorm=he_normalization, path_to_target_im=he_norm_target).test_transform\n\n train_dataset, test_dataset, val_dataset = [dataset_tcga(\n args=args,\n csv_file=args.path_to_msi_data, \n root_dir=args.root_dir_for_tcga_tiles, \n transform=tcga_transform,\n split_num=args.kfold,\n label=args.ddr_label,\n split=current_split,\n load_normalized_tiles=args.load_normalized_tiles,\n dataset=args.dataset\n ) for current_split in ['train', 'test', 'val']]\n else:\n raise NotImplementedError\n\n # Get the extractor\n if args.logistic_extractor == 'byol':\n # We get the rn18 backbone with the loaded state dict\n print(\"Loading BYOL model ... \")\n _, _, _, extractor, n_features = load_model(args, reload_model=args.reload_model, model_type=args.logistic_extractor)\n else:\n extractor, _, _ = load_model(args, reload_model=args.reload_model, model_type=args.logistic_extractor)\n\n extractor = extractor.to(args.device)\n\n # Set extractor to eval if asked for\n if args.freeze_encoder:\n print(\"===== Extractor is frozen =====\")\n extractor.eval()\n else:\n print(\"===== Extractor is NOT frozen =====\")\n extractor.train()\n\n # Get number of features that feature extractor produces\n if args.logistic_extractor == 'simclr':\n n_features = extractor.n_features\n elif args.logistic_extractor == 'byol':\n # We returned n_features in load_model()..\n pass\n else:\n n_features = {'imagenet-resnet18': 512, 'imagenet-resnet50': 2048, 'imagenet-shufflenetv2_x1_0': 1024}[args.logistic_extractor]\n\n if 'linear' in args.classification_head:\n n_classes = 1 # Doing linear regression\n else:\n n_classes = 2 # Doing logistic regression\n\n\n ## Get classifier. Logistic / linear / deepmil / linear-deepmil\n if 'reload_classifier' not in vars(args).keys():\n args.reload_classifier = False\n model, _, _ = load_model(args, reload_model=args.reload_classifier, model_type=args.classification_head, prepend='', n_features=n_features, n_classes=n_classes)\n\n ## Get optimizer\n if args.classification_head == 'logistic' or args.classification_head == 'linear':\n if args.freeze_encoder:\n optimizer = torch.optim.Adam(model.parameters(), lr=args.logistic_lr)\n else:\n optimizer = torch.optim.Adam(list(extractor.parameters()) + list(model.parameters()), lr=args.logistic_lr)\n elif args.classification_head in ['deepmil', 'linear-deepmil', 'cnn-resnet18', 'cnn-densenet']:\n if args.freeze_encoder:\n optimizer = torch.optim.Adam(model.parameters(), lr=args.deepmil_lr, betas=(0.9, 0.999), weight_decay=args.deepmil_reg)\n else:\n optimizer = torch.optim.Adam(list(extractor.parameters()) + list(model.parameters()), lr=args.deepmil_lr, betas=(0.9, 0.999), weight_decay=args.deepmil_reg)\n else:\n print(f\"{args.classification_head} has not been implemented as classification head\")\n raise NotImplementedError\n\n model = model.to(args.device)\n print(model)\n \n\n ### ============= GET THE CORRECT DATA LOADERS ============= ###\n\n if args.precompute_features or not args.use_precomputed_features:\n # If we precompute features, we need an image loader\n # If we use precomputed features, we don't need an image loader\n # If we don't use any preocomputed features, which happens if we finetune, we do want an image loader \n\n assert not (args.precompute_features and args.use_precomputed_features), \"Ambiguous config. Precompute features or use precomputed features?\"\n\n drop_last = not (args.precompute_features and not args.precompute_features_in_memory) # if we precompute features, but NOT in memory, do not drop last\n\n if args.dataset in ['msi-tcga','basis']:\n # For msi-tcga, we have pre-split everything\n train_sampler=None\n val_sampler=None\n \n else:\n train_indices, val_indices = get_train_val_indices(train_dataset, val_split=args.validation_split)\n train_sampler = SubsetRandomSampler(train_indices)\n val_sampler = SubsetRandomSampler(val_indices) \n val_dataset = train_dataset\n # for non-msi-tcga, we have to split, still\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers,\n sampler=train_sampler\n )\n\n val_loader = torch.utils.data.DataLoader(\n val_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers,\n sampler=val_sampler\n )\n\n test_loader = torch.utils.data.DataLoader(\n test_dataset,\n batch_size=args.logistic_batch_size,\n drop_last=drop_last,\n num_workers=args.workers\n )\n \n\n ### ============ Precompute and/or load precomputed features ============= ###\n\n if args.precompute_features:\n # We need the image loader defined above \n \n if args.precompute_features_in_memory:\n print(\"### Creating features from pre-trained context model ###\")\n \n (train_X, train_y, val_X, val_y, test_X, test_y, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs) = get_features(\n args, extractor, train_loader, val_loader, test_loader, args.device\n )\n\n arr_train_loader, arr_val_loader, arr_test_loader = create_data_loaders_from_arrays(\n train_X, train_y, val_X, val_y, test_X, test_y, args.logistic_batch_size, train_patients, train_imgs, val_patients, val_imgs, test_patients, test_imgs\n )\n else:\n print(\"### Creating and saving features from pre-trained context model ###\")\n print(args.data_testing_train_fraction)\n assert args.data_testing_train_fraction == 1 and args.data_testing_test_fraction == 1, \"Bugs might occur when we do not save feature vectors for all data due to sampling issues\"\n\n run_id = args.out_dir.split('/')[-1] # \"./logs/pretrain/\"\n\n infer_and_save(loader=train_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n infer_and_save(loader=val_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n infer_and_save(loader=test_loader, context_model=extractor, device=args.device, append_with=f'_{run_id}', model_type=args.logistic_extractor)\n\n print(\"### Aggregating saved feature vectors into patient-level tensors ###\")\n print(\"### Aggregating for train...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=train_dataset.labels)\n print(\"### Aggregating for val...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=val_dataset.labels)\n print(\"### Aggregating for test...\")\n aggregate_patient_vectors(args, root_dir=args.path_to_msi_data, append_with=f'_{run_id}', grid=True, data=test_dataset.labels)\n \n # Overwriting previous variable names to reduce memory load\n train_loader, val_loader, test_loader = get_precomputed_dataloader(args, run_id)\n\n arr_train_loader, arr_val_loader, arr_test_loader = train_loader, val_loader, test_loader\n\n elif args.use_precomputed_features:\n # Did not need any image loader, as we create a new vector-based dataset\n \n assert (args.use_precomputed_features_id), 'Please set the run ID of the features you want to use'\n print(f\"Removing SIMCLR model from memory, as we use precomputed features..\")\n del extractor\n extractor = None\n arr_train_loader, arr_val_loader, arr_test_loader = get_precomputed_dataloader(args, args.use_precomputed_features_id)\n else:\n # We use the image loader as defined above\n arr_train_loader, arr_val_loader, arr_test_loader = train_loader, val_loader, test_loader\n\n\n ### ============= TRAINING ============= ###\n\n if 'linear' in args.classification_head:\n criterion = torch.nn.MSELoss()\n else:\n criterion = torch.nn.CrossEntropyLoss(weight=arr_train_loader.dataset.get_class_balance().float().to(args.device)) #TODO add class balance\n\n val_losses = []\n val_roc = []\n global_step = 0\n for epoch in range(args.logistic_epochs):\n args.current_epoch = epoch\n loss_epoch, accuracy_epoch, val_losses, val_roc, global_step = train(args, arr_train_loader, arr_val_loader, extractor, model, criterion, optimizer, val_losses, val_roc, global_step, epoch, writer)\n writer.add_scalar(\"loss/train\", loss_epoch / len(arr_train_loader), epoch)\n\n\n ### ============= TESTING ============= ###\n\n if args.logistic_epochs > 0:\n # If we have run epochs in the current run, we will take the best model from the current run\n if not 'best_model_evaluation' in vars(args).keys():\n args.best_model_evaluation = 'auc'\n\n if args.best_model_evaluation == 'auc' or args.best_model_evaluation == 'r2': # r2 for linear regression, which is saved in the roc array\n # This seems like it would make most sense for the logistic regression (tile-level prediction & majority vote)\n best_model_num = np.argmax(val_roc)\n elif args.best_model_evaluation == 'loss':\n # This is probably most sensible for patient-level prediction methods like deepmil\n best_model_num = np.argmin(val_losses)\n \n best_model_epoch = best_model_num * args.evaluate_every + args.evaluate_every\n\n print(f'Validation ROCs: {val_roc}\\nValidation loss: {val_losses}.\\nBest performance by model @ epoch # {best_model_epoch}')\n\n if extractor:\n extractor_fp = os.path.join(args.out_dir, \"extractor_checkpoint_{}.tar\".format(best_model_epoch))\n extractor.load_state_dict(torch.load(extractor_fp, map_location=args.device.type))\n model_fp = os.path.join(args.out_dir, \"classifier_checkpoint_{}.tar\".format(best_model_epoch))\n model.load_state_dict(torch.load(model_fp, map_location=args.device.type))\n\n else:\n # clarifying that we have not trained at all\n best_model_epoch=epoch=0\n\n # If we haven't run any epochs, we won't do anything, because we've already loaded the model before...\n\n # if args.reload_model:\n # if extractor:\n # extractor_fp = os.path.join(args.model_path, \"extractor_checkpoint_{}.tar\".format(args.epoch_num))\n # extractor.load_state_dict(torch.load(extractor_fp, map_location=args.device.type))\n # model_fp = os.path.join(args.model_path, \"classifier_checkpoint_{}.tar\".format(args.epoch_num))\n # model.load_state_dict(torch.load(model_fp, map_location=args.device.type))\n \n loss_epoch, accuracy_epoch, labels, preds, patients, attentions, attention_gradients, img_names, subsample_indices, predicted_probs = validate(\n args, arr_test_loader, extractor, model, criterion, optimizer, final_test=True\n )\n\n\n ### ============= Compute final metrics and write them to tensorboard ============= ###\n\n writer.add_scalar(\"loss/test\", loss_epoch / len(arr_test_loader))\n if 'linear' not in args.classification_head:\n # Logistic regression, using ROC AUC as metric\n final_data, rocauc = compute_roc_auc(args, patients, labels, preds, save_curve=True, epoch=best_model_epoch)\n writer.add_scalar(\"rocauc/test\", rocauc)\n write_hparams(writer, args, {'hparam/rocauc': rocauc })\n _run.log_scalar('test/rocauc', rocauc, 0)\n print(\n f\"======\\n[Final test with best model]\\t ROCAUC: {rocauc} \\t Loss: {loss_epoch / len(arr_test_loader)}\\t Accuracy: {accuracy_epoch / len(arr_test_loader)}\"\n )\n else:\n # Linear regression, using R2 score as metric\n final_data, r2 = compute_r2(patients, labels, preds)\n writer.add_scalar(\"r2/test\", r2)\n write_hparams(writer, args, {'hparam/r2': r2 })\n _run.log_scalar('test/r2', r2, 0)\n print(\n f\"======\\n[Final test with best model]\\t R2: {r2} \\t Loss: {loss_epoch / len(arr_test_loader)}\\t\"\n )\n\n\n ### ============= Save the predictions ============= ###\n\n humane_readable_time = datetime.datetime.fromtimestamp(int(time.time())).strftime('%Y-%m-%d-%H-%M-%S')\n print(f'This is the out dir {args.out_dir}')\n\n final_data.to_csv(f'{args.out_dir}/regression_output_epoch_{best_model_epoch}_{humane_readable_time}.csv') \n\n if args.classification_head == 'deepmil':\n # This means we'll have loaded a stacked grid, we'll have returned subsample indices, we'll have meaningful attentions.\n # Now save it for easy visualization..\n save_attention(args, img_names, attentions, attention_gradients, subsample_indices, args.out_dir, humane_readable_time, best_model_epoch)\n elif args.classification_head == 'logistic':\n save_probabilities(args, img_names, predicted_probs, labels, args.out_dir, humane_readable_time, best_model_epoch)\n\n \n \n\n","sub_path":"testing/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":42594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"405776077","text":"# __author__ = 'Fabian'\n# __project__ = erste_Programme\n# __file__ = rock_paper_scissor_gui.py\n# __version__ = 0.9\n\n\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom PIL import Image, ImageTk\nimport random\n\n# ToDo Bestenliste mit gesuchter Zahl, Versuchen, mit/ohne Hinweis\n# ToDo Fehler: Bestätigen, Neustart, Modus auswählen -> Zähler bleibt eingeblendet\n# ToDo Fehler: Modus unbegrenzt, Unentschieden\n# ToDo Hintergrund, wenn Stop-Button (Modus: unbegrenzt) wieder ausgeblendet\n# ToDo Formatierung\n\n# Debug\nclass debug():\n global counter_debug\n # Debug anzeigen\n def debug_show(event):\n if counter_debug.get() == 0:\n counter_debug.set(\"1\")\n txdebug = tk.Text(main, width=47, height=9, relief = \"sunken\", bd = 2)\n txdebug.grid(column=0, row=7)\n txdebug.insert(\"end\", \"\")\n\n main.minsize(width=400, height=450) # min. Fenstergröße\n main.maxsize(width=400, height=450) # max. Fenstergröße\n else:\n debug.debug_update()\n # Debug aktualisieren\n def debug_update():\n debug.debug_invisible()\n txdebug = tk.Text(main, width=47, height=9, relief=\"sunken\", bd=2)\n txdebug.grid(column=0, row=7)\n txdebug.insert(\"end\", \"\")\n main.minsize(width=400, height=450) # min. Fenstergröße\n main.maxsize(width=400, height=450) # max. Fenstergröße\n # Debug ausblenden\n def debug_invisible():\n children = main.winfo_children()\n for child in children:\n if str(type(child)) == \"\":\n child.destroy()\n main.minsize(width=400, height=320) # min. Fenstergröße\n main.maxsize(width=400, height=320) # max. Fenstergröße\n return\n # Debug ausblenden Menü\n def debug_invisible_menu():\n counter_debug.set(\"0\")\n children = main.winfo_children()\n for child in children:\n if str(type(child)) == \"\":\n child.destroy()\n main.minsize(width=400, height=320) # min. Fenstergröße\n main.maxsize(width=400, height=320) # max. Fenstergröße\n return\n\n# Bilder\nclass images():\n # Image Player\n def image_player():\n load = Image.open(symbol[0])\n render = ImageTk.PhotoImage(load)\n img = tk.Label(frplayer, bg = bg, image=render)\n img.image = render\n img.grid(column=0, row=2, columnspan=2, rowspan=3)\n # Image Computer\n def image_computer():\n load = Image.open(symbol[1])\n render = ImageTk.PhotoImage(load)\n img = tk.Label(frcomputer, bg = bg, image=render)\n img.image = render\n img.grid(column=0, row=2, columnspan=2, rowspan=3)\n\n# # Auswahl Modus\n# class mode():\n#\n# # Interface Änderungen\n# class interface():\n#\n# # Eingabe\n# class guess():\n#\n# Werte zurücksetzten\ndef reset():\n pass\n\n# Programm Ende\ndef end():\n main.destroy()\n\n# Optionen\nbg = \"beige\" # Allgemeine Hintergrundfarbe\n\n# Hauptfenster\nmain = tk.Tk()\nmain.title(\"Spielesammlung\") # Fenstername\nmain.configure(bg = bg) # Hintergrundfarbe\nmain.minsize(width=400, height=320) # min. Fenstergröße\nmain.maxsize(width=400, height=320) # max. Fenstergröße\nmain.columnconfigure(0, weight = 3) # Zentrieren\n\n# Startwerte Variablen\ncounter_debug = tk.IntVar()\ncounter_debug.set(\"0\") # Zähler Debug\nsymbol = [\"X.png\", \"O.png\"] # Bilder\n\n\n# Hauptfenster Header\nlbheader = tk.Label(main, width = 43, bg = \"brown\", fg = \"white\", text = \"************** Tic Tac Toe **************\",\n font = \"Times 16 bold\", relief = \"raised\", bd = 4)\nlbheader.bind(\"\", debug.debug_show)\nlbheader.grid(column = 0, row = 0, columnspan = 3)\n\n# Menü\nmBar = tk.Menu(main)\n\nmFile = tk.Menu(mBar)\nmDebug = tk.Menu(mBar)\n\nmBar.add_cascade(label = \"Datei\", menu = mFile, underline = 0)\nmBar.add_cascade(label = \"Debugger\", menu = mDebug, underline = 0)\n\nmFile.add_command(label = \"Neustart\", underline = 0, command = reset)\nmFile.add_separator()\nmFile.add_command(label = \"Beenden\", command = end)\n\nmDebug.add_command(label = \"Debugger aus\", command = debug.debug_invisible_menu)\n\nmain[\"menu\"] = mBar\n\n# Anweisung\n # Anweisung Frame\nfrintroduction = tk.Frame(main, relief = \"sunken\", bd = 3)\nfrintroduction.configure(bg = bg)\nfrintroduction.grid(column = 0, row = 1, columnspan = 3)\n # Anweisung Text\ntxinstruction = tk.Text(frintroduction, bg = bg, width = 48, height = 2)\ntxinstruction.grid(column = 0, row = 0, columnspan = 3)\ntxinstruction.insert(tk.INSERT, \"Gewinne, indem du von deinen Symbolen,\\n\"\n \"3 in einer Reihe platzierst!\")\n\n# Spielfeld\n # Hauptfenster\ncatable = tk.Canvas(main, width = 210, height = 210, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\ncatable.grid(column = 0, row = 2, sticky = \"w\", padx = 25, pady = 5)\ncatable_bg = tk.Canvas(catable, width = 210, height = 210, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\ncatable_bg.grid(column = 0, row = 0)\n\ntable = tk.PhotoImage(file = \"table.png\")\ncatable_bg.create_image(113,113,image = table)\n\n # Feld 1\n# img_player = tk.PhotoImage(file = \"X.png\")\n# cafield_1 = tk.Canvas(catable, width = 9, height = 4)\n# cafield_1.grid(column = 0, row = 0)\n# cafield_1.create_image(60,60,image=img_player)\n# field_2 = tk.Text(frtable, width = 9, height = 4)\n# field_2.grid(column = 1, row = 0)\n# field_3 = tk.Text(frtable, width = 9, height = 4, bg = \"green\")\n# field_3.grid(column = 2, row = 0)\n# field_4 = tk.Text(frtable, width = 9, height = 4, bg = \"red\")\n# field_4.grid(column = 1, row = 1)\n# field_5 = tk.Text(frtable, width = 9, height = 4, bg = \"orange\")\n# field_5.grid(column = 0, row = 2)\n\n # Canvas\n# catable = tk.Canvas(main, width = 200, height = 200, highlightbackground = \"sandybrown\", bg = \"peru\", relief = \"groove\", bd = 5)\n# catable.grid_columnconfigure(2, weight = 5)\n# catable.grid_rowconfigure(2, weight = 5)\n# catable.grid(column = 0, row = 2, sticky = \"w\", padx = 25, pady = 5)\n # Linien\n# catable.create_line(5, 70, 205, 70, fill = \"black\", width = 3)\n# catable.create_line(5, 140, 205, 140, fill = \"black\", width = 3)\n# catable.create_line(70, 5, 70, 205, fill = \"black\", width = 3)\n# catable.create_line(140, 5, 140, 205, fill = \"black\", width = 3)\n\n# field_1 = tk.Canvas(catable, width = 60, height = 60)\n# # field_1.grid(column = 0, row = 0)\n# # catable.create_window(20,20, window = field_1)\n# catable.create_window(20,20, window=field_1)\n\n# Interface\n # Interface Frame\n\n\n # Interface Bilder\n# # Spieler\n# frplayer = tk.Frame(catable, bg = \"red\", relief = \"sunken\", bd = 0)\n# frplayer.configure(height = 60, width = 60)\n# frplayer.grid(column = 0, row = 0)\n# # Computer\n# frcomputer = tk.Frame(frinterface, bg = bg, relief = \"sunken\", bd = 0)\n# frcomputer.configure(height = 100, width = 120)\n# frcomputer.grid(column = 5, row = 1)\n\n # Interface Knöpfe\n # Frame Mitte\n# frmiddle = tk.Frame(frinterface, bg=\"peru\", relief=\"raised\", bd=4)\n# frmiddle.configure(height=100, width=120)\n# frmiddle.grid(column=3, row=1)\n\n # Interface Radiobutton\n # Frame Radio\nfrradio = tk.Frame(main, bg = \"sandybrown\", relief=\"groove\", bd=2)\nfrradio.grid(column = 1, row = 2)\n # Schere\n# rbscissor = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Schere\", variable = pic_player, value = 0)\n# rbscissor.grid(column = 0, row = 0, sticky = \"w\")\n# # Stein\n# rbrock = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Stein\", variable = pic_player, value = 1)\n# rbrock.grid(column = 0, row = 1, sticky = \"w\")\n# # Papier\n# rbpaper = tk.Radiobutton(frradio, bg = \"sandybrown\", text = \"Papier\", variable = pic_player, value = 2)\n# rbpaper.grid(column = 0, row = 2, sticky = \"w\")\n\n # Interface Bottom\n # Accept\n# buaccept = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Bestätigen\", relief = \"ridge\", command = guess.guess)\n# buaccept.grid(column = 0, row = 3)\n # Restart\nburestart = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Neustart\", relief = \"ridge\", command = reset)\nburestart.grid(column = 1, row = 0, rowspan = 2)\n # Beenden\nbuend = tk.Button(frradio, highlightbackground = \"sandybrown\", text = \"Beenden\", relief = \"ridge\", command = end)\nbuend.grid(column = 1, row = 2, rowspan = 2)\n\n# Hauptprogrammschleife starten\nmain.mainloop()","sub_path":"Spielesammlung/Spielesammlung_mit_GUI/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":9277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"361818733","text":"import pygame\nfrom groundcell import GroundCell\nfrom brickcell import BrickCell\nfrom watercell import WaterCell\nfrom stonecell import StoneCell\n\n\nCELL_WIDTH = 60\nCELL_HEIGHT = 60\nNUM_ROWS = 10\nNUM_COLS = 10\n\nclass Board():\n def __init__(self): \n self.grid = [[0]*NUM_COLS for a in range(NUM_ROWS)]\n self.cells = pygame.sprite.Group()\n\n def init_board(self,data):\n for i in xrange(2,len(data)):\n for c in data[i].split(\";\"):\n tmp = c.split(\",\")\n self.grid[int(tmp[1])][int(tmp[0])] = 1-i\n \n def draw_board(self):\n for i in xrange(NUM_ROWS):\n for j in xrange(NUM_COLS):\n if self.grid[i][j] == 0:\n cell = GroundCell()\n elif self.grid[i][j] == -1:\n cell = BrickCell()\n elif self.grid[i][j] == -2:\n cell = StoneCell()\n elif self.grid[i][j] == -3:\n cell = WaterCell()\n \n x = j*CELL_WIDTH\n y = i*CELL_HEIGHT\n \n cell.rect = pygame.Rect(x,y,CELL_WIDTH,CELL_HEIGHT)\n self.cells.add(cell)\n\n def move_tank(self,dire,i,j):\n if dire == 0 :\n if self.grid[i-1][j] == 0 and i != 0 :\n i -= 1\n elif dire == 1:\n if j != NUM_ROWS - 1 and self.grid[i][j+1] == 0:\n j += 1\n elif dire == 2:\n if i != NUM_COLS - 1 and self.grid[i+1][j] == 0:\n i += 1\n elif dire == 3:\n if self.grid[i][j-1] == 0 and j != 0:\n j -= 1\n \n x = j*CELL_WIDTH\n y = i*CELL_HEIGHT\n \n return [i,j,x,y] \n\n \n \n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"586413930","text":"import random\nfrom datetime import datetime\nimport time\n\ndef sorting(the_list):\n starter=0\n smallest=9999\n index=0\n\n while starterthe_list[number]:\n smallest=the_list[number]\n index=number\n\n the_list[starter], the_list[index] = the_list[index], the_list[starter]\n starter+=1\n smallest = 9999\n\n return(the_list)\n\nrandom.seed(int(str(datetime.now()).split(\".\")[1]))\n\nourlist=[]\nfor num in range(0,10000):\n ourlist.append(random.randint(0,100))\n\nprint(ourlist)\nstart_time = time.time()\n\nprint(sorting(ourlist))\n\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\nstart_time = time.time()\nourlist.sort()\nprint(ourlist)\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"80476936","text":"\"\"\"\nA collection of activation functions.\n\"\"\"\n\nimport numpy as np\n\n\ndef sigmoid(n, derivative=False):\n \"\"\"\n The classical sigmoid function.\n :param n: (int/np.ndarray) The input to be 'activated'\n :param derivative: (bool/default=False) If this parameter is set to True, the derivative\n of the function will be returned.\n :return: The 'activated' value of 'n'...\n \"\"\"\n s1 = np.asscalar(np.array([1.], dtype=\"float64\"))\n if derivative:\n return n * (s1 - n)\n\n return s1 / (s1 + np.exp(-n))\n\n\ndef relu(n, derivative=False):\n if derivative:\n return (n > 0).astype(float)\n\n return np.maximum(0, n)\n\n\ndef softmax(n, axis=-1, derivative=False):\n if derivative:\n return np.asscalar(np.array([1.], dtype=\"float64\"))\n e = np.exp(n - np.max(n, axis=axis, keepdims=True))\n s = np.sum(e, axis=axis, keepdims=True)\n return e / s\n\n\ndef lrelu(n, derivative=False, leakage=0.01):\n if derivative:\n return np.clip(n > 0, leakage, 1.0)\n\n output = np.copy(n)\n output[output < 0] *= leakage\n return output\n\n\ndef tanh(n, derivative=False):\n n = np.tanh(n)\n if derivative:\n return 1 - np.power(n, 2)\n\n return n\n\n\ndef linear(n, derivative=False):\n if derivative:\n return 1\n return n\n\n\nactivation_functions = {\n \"sigmoid\": sigmoid,\n \"relu\": relu,\n \"softmax\": softmax,\n \"lrelu\": lrelu,\n \"tanh\": tanh,\n \"linear\": linear\n}","sub_path":"bull/layers/activation_functions.py","file_name":"activation_functions.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"409519099","text":"import imageio\nimport SimpleITK as sitk\nimport numpy as np\n\nimg = sitk.GetArrayFromImage(sitk.ReadImage(\"../datasets/BRATS_Dataset/brats_dataset/HGG/Brats18_2013_10_1/Brats18_2013_10_1_flair.nii.gz\"))\nimg = (img/img.max())*255\nimg = img.astype(np.uint8)\nimg = np.stack((img,)*3, axis=-1)\n\nseg = sitk.GetArrayFromImage(sitk.ReadImage(\"../datasets/BRATS_Dataset/brats_dataset/HGG/Brats18_2013_10_1/Brats18_2013_10_1_seg.nii.gz\"))\nncr = seg == 1\ned = seg == 2\net = seg == 4\n\nseg = (np.stack([ncr, ed, et])*255).astype(np.uint8)\nseg = seg.transpose(1,2,3,0)\n\nwith imageio.get_writer('mri.gif', mode='I', fps=15) as writer:\n alpha = 0.5\n images = (img*alpha + seg*(1-alpha)).astype(np.uint8)\n for i in images:\n writer.append_data(i)","sub_path":"mri_to_gif.py","file_name":"mri_to_gif.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"229764109","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 19 13:10:07 2014\n\n@author: W4TB\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom collections import defaultdict\nfrom selenium.webdriver.common.keys import Keys\nfrom csv import DictWriter\n\ndirectorySearch_url = \"http://mydoctor.kaiserpermanente.org/mas/mdo/\"\n\ndriver = webdriver.Chrome()\ndriver.get(directorySearch_url)\ndriver.implicitly_wait(15)\n\nfirstNameBox = driver.find_element_by_id(\"firstName\")\nfirstNameBox.send_keys(\"\")\n\nlastNameBox = driver.find_element_by_id(\"lastName\")\nlastNameBox.send_keys(\"Jo\")\n\ndriver.find_element_by_name(\"Submit\").submit()\n\ndocResults = (driver.find_elements_by_xpath(\"//tr[@class = 'odd']\") +\n driver.find_elements_by_xpath(\"//tr[@class = 'even']\"))\n\ndocList = []\nresultsPage = driver.current_window_handle\n\nfor result in docResults:\n doc = defaultdict()\n lastAndFirst = result.find_elements_by_xpath(\".//a\")\n link = lastAndFirst[0]\n doc['Link'] = link.get_attribute(\"href\")\n doc['Last Name'] = link.text\n doc['First Name'] = lastAndFirst[1].text\n \n newTabActions = ActionChains(driver)\n newTabActions.key_down(Keys.CONTROL)\n newTabActions.click(link)\n newTabActions.key_up(Keys.CONTROL)\n newTabActions.perform()\n \n driver.switch_to_window(driver.window_handles[-1])\n officeLink = driver.find_element_by_xpath(\"//li[@id = 'tab-offices']/a\")\n officeLink.click()\n \n addressList = []\n for element in driver.find_elements_by_xpath(\"//div[@class = 'drOffices']//ul//li\"):\n addressList.append(element.text)\n \n addressNum = 1 \n for i in range(0, len(addressList) - 1, 2):\n keyString = \"Address \" + str(addressNum)\n doc[keyString] = (addressList[i] + \" \" + addressList[i + 1])\n addressNum += 1\n driver.close()\n \n driver.switch_to_window(resultsPage)\n\n docList.append(doc)\n \nwith open(\"F:\\\\KaiserScrapeOutput.csv\", 'w') as f:\n fieldnames = set() \n for doc in docList:\n for key in doc.keys():\n fieldnames.add(key)\n \n for doc in docList:\n for fieldname in fieldnames:\n if fieldname not in doc.keys():\n doc[fieldname] = \"\"\n \n writer = DictWriter(f, fieldnames)\n for doc in docList:\n writer.writerow(doc)\n \ndriver.close()","sub_path":"KaiserScrapeTest.py","file_name":"KaiserScrapeTest.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"186772296","text":"import re\nfrom six import iteritems\nfrom whatsopt.utils import simple_value, to_camelcase, extract_disc_var, format_shape\nfrom .logging import debug, log\nfrom openmdao.api import IndepVarComp\n\ntry: # openmdao < 2.9\n from openmdao.devtools.problem_viewer.problem_viewer import _get_viewer_data\nexcept ImportError: # openmdao >= 2.9\n from openmdao.visualization.n2_viewer.n2_viewer import _get_viewer_data\n\nNULL_DRIVER_NAME = \"__DRIVER__\" # check WhatsOpt Discipline model\n\n\nclass PushCommand(object):\n def __init__(self, problem, scalar_format):\n data = _get_viewer_data(problem)\n self.problem = problem\n self.scalar_format = scalar_format\n self.tree = data[\"tree\"]\n self.connections = data[\"connections_list\"]\n self.vars = {}\n self.vardescs = {}\n self.discmap = {}\n\n def get_mda_attributes(self, group, tree, group_prefix=\"\"):\n self._collect_disc_infos()\n self._collect_var_infos()\n driver_attrs = {\"name\": NULL_DRIVER_NAME, \"variables_attributes\": []}\n mda_attrs = {\n \"name\": group.__class__.__name__,\n \"disciplines_attributes\": [driver_attrs],\n }\n if \"children\" not in tree:\n return\n\n for i, child in enumerate(tree[\"children\"]):\n if child[\"type\"] == \"subsystem\" and child[\"subsystem_type\"] == \"group\":\n prefix = group_prefix + child[\"name\"] + \".\"\n sub_analysis_attrs = self._get_sub_analysis_attributes(\n group._subsystems_myproc[i], child, prefix\n )\n mda_attrs[\"disciplines_attributes\"].append(sub_analysis_attrs)\n else:\n if not isinstance(group._subsystems_myproc[i], IndepVarComp):\n mda = group_prefix[:-1]\n discname = group_prefix + child[\"name\"]\n discattrs = self._get_discipline_attributes(\n driver_attrs, mda, discname\n )\n\n self._set_varattrs_from_outputs(\n group._subsystems_myproc[i]._var_abs2prom[\"output\"],\n \"out\",\n discattrs[\"variables_attributes\"],\n )\n\n mda_attrs[\"disciplines_attributes\"].append(discattrs)\n else:\n self._set_varattrs_from_outputs(\n group._subsystems_myproc[i]._var_abs2prom[\"output\"],\n \"out\",\n driver_attrs[\"variables_attributes\"],\n )\n\n self._set_varattrs_from_outputs(\n group._var_abs2prom[\"output\"], \"in\", driver_attrs[\"variables_attributes\"]\n )\n\n # remove fullname in driver varattrs\n for vattr in driver_attrs[\"variables_attributes\"]:\n vattr[\"desc\"] = self.vardescs[vattr[\"name\"]]\n if (\n vattr[\"io_mode\"] == \"out\"\n ): # set init value for design variables and parameters (outputs of driver)\n v = self.vars[vattr[\"fullname\"]]\n vattr[\"parameter_attributes\"] = {\"init\": simple_value(v)}\n if \"fullname\" in vattr:\n del vattr[\"fullname\"] # indeed for WhatsOpt var name is a primary key\n\n for discattr in mda_attrs[\"disciplines_attributes\"]:\n if \"variables_attributes\" in discattr:\n for vattr in discattr[\"variables_attributes\"]:\n if \"fullname\" in vattr:\n del vattr[\n \"fullname\"\n ] # indeed for WhatsOpt var name is a primary key\n\n return mda_attrs\n\n def _get_sub_analysis_attributes(self, group, child, prefix):\n submda_attrs = self.get_mda_attributes(group, child, prefix)\n submda_attrs[\"name\"] = to_camelcase(child[\"name\"])\n superdisc_attrs = {\n \"name\": child[\"name\"],\n \"sub_analysis_attributes\": submda_attrs,\n }\n return superdisc_attrs\n\n def _get_discipline_attributes(self, driver_attrs, mda, dname):\n varattrs = self._get_variables_attrs(\n driver_attrs[\"variables_attributes\"], mda, dname\n )\n discattrs = {\n \"name\": to_camelcase(self.discmap[dname]),\n \"variables_attributes\": varattrs,\n }\n return discattrs\n\n def _set_varattrs_from_outputs(self, outputs, io_mode, varattrs):\n for absname, varname in iteritems(outputs):\n if varname not in [varattr[\"name\"] for varattr in varattrs]:\n var = self.vars[absname]\n vattr = {\n \"name\": varname,\n \"fullname\": absname,\n \"io_mode\": io_mode,\n \"desc\": self.vardescs[varname],\n \"type\": var[\"type\"],\n \"shape\": var[\"shape\"],\n \"units\": var[\"units\"],\n }\n varattrs.append(vattr)\n\n def _get_varattr_from_connection(\n self, varattrs, driver_varattrs, mda, dname, connection\n ):\n fnamesrc = connection[\"src\"]\n mdasrc, discsrc, varsrc = extract_disc_var(fnamesrc)\n fnametgt = connection[\"tgt\"]\n mdatgt, disctgt, vartgt = extract_disc_var(fnametgt)\n debug(\"++++ MDA=%s DISC=%s\" % (mda, dname))\n debug(\n \"######### SRC=%s DISCSRC=%s TGT=%s DISCTGT=%s\"\n % (mdasrc, discsrc, mdatgt, disctgt)\n )\n\n varstoadd = []\n if mda == mdasrc and discsrc == dname:\n varattrsrc = {\n \"name\": varsrc,\n \"fullname\": fnamesrc,\n \"io_mode\": \"out\",\n \"type\": self.vars[fnamesrc][\"type\"],\n \"shape\": self.vars[fnamesrc][\"shape\"],\n \"units\": self.vars[fnamesrc][\"units\"],\n }\n varstoadd.append((discsrc, varattrsrc, \"source\"))\n if mda != \"\" and mda not in mdatgt:\n discsrc = NULL_DRIVER_NAME\n varattrsrc = {\n \"name\": varsrc,\n \"fullname\": fnamesrc,\n \"io_mode\": \"in\",\n \"type\": self.vars[fnametgt][\"type\"],\n \"shape\": self.vars[fnametgt][\"shape\"],\n \"units\": self.vars[fnametgt][\"units\"],\n }\n varstoadd.append((discsrc, varattrsrc, \"source\"))\n\n if mda == mdatgt and disctgt == dname:\n varattrtgt = {\n \"name\": vartgt,\n \"fullname\": fnametgt,\n \"io_mode\": \"in\",\n \"type\": self.vars[fnametgt][\"type\"],\n \"shape\": self.vars[fnametgt][\"shape\"],\n \"units\": self.vars[fnametgt][\"units\"],\n }\n varstoadd.append((disctgt, varattrtgt, \"target\"))\n if mda != \"\" and mda not in mdasrc:\n disctgt = NULL_DRIVER_NAME\n varattrtgt = {\n \"name\": vartgt,\n \"fullname\": fnametgt,\n \"io_mode\": \"out\",\n \"type\": self.vars[fnamesrc][\"type\"],\n \"shape\": self.vars[fnamesrc][\"shape\"],\n \"units\": self.vars[fnamesrc][\"units\"],\n }\n varstoadd.append((disctgt, varattrtgt, \"target\"))\n\n for disc, varattr, orig in varstoadd:\n debug(\"**************\", connection)\n if disc == dname:\n if varattr not in varattrs:\n debug(\n \">>>>>>>>>>>>> from\",\n orig,\n \" ADD to \",\n mda,\n dname,\n \": \",\n varattr[\"name\"],\n varattr[\"io_mode\"],\n )\n varattrs.append(varattr)\n else:\n if varattr[\"name\"] not in [vattr[\"name\"] for vattr in driver_varattrs]:\n debug(\n \">>>>>>>>>>>>> from\",\n orig,\n \" ADD to \",\n mda,\n \"__DRIVER__ :\",\n varattr[\"name\"],\n varattr[\"io_mode\"],\n )\n driver_varattrs.append(varattr)\n\n def _get_variables_attrs(self, driver_varattrs, mda, dname):\n varattrs = []\n for conn in self.connections:\n self._get_varattr_from_connection(\n varattrs, driver_varattrs, mda, dname, conn\n )\n for vattr in varattrs:\n vattr[\"desc\"] = self.vardescs[vattr[\"name\"]]\n if \"fullname\" in vattr:\n del vattr[\"fullname\"] # indeed for WhatsOpt var name is a primary key\n return varattrs\n\n # # see _get_tree_dict at\n # # https://github.com/OpenMDAO/OpenMDAO/blob/master/openmdao/devtools/problem_viewer/problem_viewer.py\n def _collect_disc_infos(self, group_prefix=\"\"):\n if \"children\" not in self.tree:\n return\n\n for i, child in enumerate(self.tree[\"children\"]):\n # retain only components, not intermediates (subsystem or group)\n if child[\"type\"] == \"subsystem\" and child[\"subsystem_type\"] == \"group\":\n self.discmap[group_prefix + child[\"name\"]] = child[\"name\"]\n prefix = group_prefix + child[\"name\"] + \".\"\n self._collect_disc_infos(prefix)\n else:\n # do not represent IndepVarComp\n if not isinstance(\n self.problem.model._subsystems_myproc[i], IndepVarComp\n ):\n self.discmap[group_prefix + child[\"name\"]] = child[\"name\"]\n else:\n self.discmap[group_prefix + child[\"name\"]] = \"__DRIVER__\"\n\n # see _get_tree_dict at\n # https://github.com/OpenMDAO/OpenMDAO/blob/master/openmdao/devtools/problem_viewer/problem_viewer.py\n def _collect_var_infos(self):\n for typ in [\"input\", \"output\"]:\n for abs_name in self.problem.model._var_abs_names[typ]:\n if typ == \"input\":\n io_mode = \"in\"\n elif typ == \"output\":\n io_mode = \"out\"\n else:\n raise Exception(\"Unhandled variable type \" + typ)\n meta = self.problem.model._var_abs2meta[abs_name]\n\n vtype = \"Float\"\n if re.match(\"int\", type(meta[\"value\"]).__name__):\n vtype = \"Integer\"\n shape = str(meta[\"shape\"])\n shape = format_shape(self.scalar_format, shape)\n name = self.problem.model._var_abs2prom[typ][abs_name]\n self.vars[abs_name] = {\n \"fullname\": abs_name,\n \"name\": name,\n \"io_mode\": io_mode,\n \"type\": vtype,\n \"shape\": shape,\n \"units\": meta[\"units\"],\n #'desc': meta['desc'],\n \"value\": meta[\"value\"],\n }\n\n # retrieve initial conditions\n var = self.vars[abs_name]\n if abs_name in self.problem.model._outputs._views:\n var[\"value\"] = self.problem.model._outputs[abs_name]\n elif abs_name in self.problem.model._inputs._views:\n var[\"value\"] = self.problem.model._inputs[abs_name]\n elif abs_name in self.problem.model._discrete_outputs:\n var[\"value\"] = self.problem.model._discrete_outputs[abs_name]\n elif abs_name in self.problem.model._discrete_inputs:\n var[\"value\"] = self.problem.model._discrete_inputs[abs_name]\n\n desc = self.vardescs.setdefault(name, \"\")\n if desc == \"\":\n self.vardescs[name] = meta[\"desc\"]\n elif desc != meta[\"desc\"] and meta[\"desc\"] != \"\":\n log(\n 'Find another description for {}: \"{}\", keep \"{}\"'.format(\n name, meta[\"desc\"], self.vardescs[name]\n )\n )\n","sub_path":"whatsopt/push_command.py","file_name":"push_command.py","file_ext":"py","file_size_in_byte":12241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"508983693","text":"from django.urls import reverse\n\nfrom AutoParts.accounts.models import Profile\nfrom AutoParts.store.models import Order\nfrom Tests.base.tests import AutoPartsTestCase\n\n\nclass CartViewTest(AutoPartsTestCase):\n\n def test_cart_view__if_right_template_is_used_with_authenticated_user(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse('cart'))\n\n self.assertTemplateUsed(response, 'store/cart.html')\n\n def test_cart_view__if_user_is_not_authenticated(self):\n response = self.client.get(reverse('cart'))\n messages = list(response.context['messages'])\n self.assertEqual('You need to be sign in', str(messages[0]))\n\n def test_cart_view__with_is_authenticated_user_and_no_orders(self):\n self.client.force_login(self.user)\n response = self.client.get(reverse('cart'))\n order = response.context['order']\n self.assertEqual(None, order)\n\n def test_cart_view__with_is_authenticated_user_and_orders(self):\n self.client.force_login(self.user)\n customer = Profile.objects.first()\n order = Order.objects.create(customer=customer, complete=False)\n\n response = self.client.get(reverse('cart'))\n self.assertEqual(order, response.context['order'])","sub_path":"AutoParts/Tests/store/views/cart_view.py","file_name":"cart_view.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"561623980","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\n\n# initialize the driver\ndriver = webdriver.Chrome(\n executable_path='/Users/ingabukhvalova/PycharmProjects/python-selenium-automation/chromedriver')\ndriver.maximize_window()\n\n\n# open the url\ndriver.get('https://www.amazon.com/s?k=echo+dot&ref=nb_sb_noss_2')\ndriver.implicitly_wait(4)\n\n\n\n#click on element\nelement_found = driver.find_element(By.XPATH, \"//img[@alt='Echo Dot (3rd Gen) - Smart speaker with clock and Alexa - Sandstone']\")\nprint (\"found element = {0}\".format(element_found))\nelement_found.click()\n\n#wait\nwait=WebDriverWait(driver, 10)\nsomething=wait.until(EC.presence_of_element_located((By.XPATH, '//meta[@content=\"echo dot\"]')))\n\n#add to cart\ndriver.find_element_by_xpath('//input[@id=\"add-to-cart-button\"]').click()\n\n\n\ntry:\n WebDriverWait(driver, 3).until(EC.new_window_is_opened,\n 'Timed out waiting for popup window to appear.')\n alert = driver.switch_to.window()\n alert.dismiss()\n print(\"alert accepted\")\nexcept TimeoutException:\n print(\"no alert\")\n\n\n\n#verify and quit\ntext_expected = driver.find_element(By.XPATH, \"//span[contains(text(),'(1 item):')]\")\n\ndriver.quit()\n\n","sub_path":"add_product_script.py","file_name":"add_product_script.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"152310499","text":"import warnings\n\nfrom django.test import TestCase\nfrom django.test.client import Client as BaseClient\n\n\nclass Client(BaseClient):\n def login(self, *args, **kwargs):\n with warnings.catch_warnings(record=True) as w:\n ret = super(Client, self).login(*args, **kwargs)\n assert len(w) == 1\n return ret\n\n\nclass FeedHQTestCase(TestCase):\n client_class = Client\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"70020","text":"# -*- encoding: utf-8 -*-\nimport logging\nimport urllib\nimport urlparse\nimport json\nimport string\nimport random\nimport time\nfrom tornado import web, gen, httpclient\nfrom .. import validator, exception\nfrom ..model import manager\nfrom ..auth import httpbasicauth, signature\n\n\n# (r\"/template\", template.IndexHandler),\nclass IndexHandler(web.RequestHandler):\n @httpbasicauth\n @web.asynchronous\n @gen.coroutine\n def get(self):\n itemPerPage = 20\n try:\n page = int(self.get_argument('page', 1))\n except ValueError:\n page = 1\n tab = self.get_argument('t', 'wait4audit')\n limit = page * itemPerPage\n offset = (page - 1) * itemPerPage\n query = {\n 'wait4audit': {'approved': manager.WAIT4AUD},\n 'approved': {'approved': manager.APPROVED},\n 'rejected': {'approved': manager.REJECTED},\n }\n\n db = self.settings['db']\n tm = manager.TplManager(db)\n res = yield tm.find(query.get(tab), offset, limit)\n count = yield tm.count(query.get('wait4audit'))\n acount = yield tm.count(query.get('approved'))\n rcount = yield tm.count(query.get('rejected'))\n tabcnt = {\n 'wait4audit': count,\n 'approved': acount,\n 'rejected': rcount\n }\n params = dict(\n tab=tab,\n page=page,\n itemPerPage=itemPerPage,\n count=count,\n acount=acount,\n rcount=rcount,\n total=tabcnt.get(tab, 0),\n tpls=res,\n )\n self.render('template/index.html.twig', **params)\n\n\n# post data:\n# content: string with variables \"this is the {key} field of template\" {key}\n# will be replaced with value which you've registered.\n# keys: [key, key1]\n# tag: tag for group of template\n\n# (r\"/template/register\", template.RegisterHandler),\nclass RegisterHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n def genTplId(len=6):\n return ''.join(random.choice(string.letters) for x in range(len))\n\n tplid = genTplId()\n tpl = {\n 'tplid': tplid,\n 'content': self.get_argument('content', ''),\n 'name': self.get_argument('name', ''),\n 'tags': self.get_argument('tags', '').split(','),\n 'keys': self.get_argument('keys', '').split(','),\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n 'callback': self.get_argument('callback', ''),\n 'created_at': int(time.time()),\n 'type': 'marketing',\n 'approved': manager.WAIT4AUD,\n 'approved_at': '',\n }\n try:\n res = yield self.register(tpl)\n if res:\n self.write({'res': 'succ', 'data': {'tplid': tplid}})\n else:\n self.write({'res': 'fail', 'info': 'insert data error'})\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n @validator.required(\"entid\")\n @validator.required(\"name\")\n @validator.required(\"content\")\n @validator.required(\"product\")\n @gen.coroutine\n def register(self, tpl):\n db = self.settings['db']\n tm = manager.TplManager(db)\n result = yield tm.insert(tpl)\n raise gen.Return(result)\n\n\nclass ListHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def get(self):\n try:\n offset = int(self.get_argument('offset', 0))\n except ValueError:\n offset = 0\n try:\n limit = int(self.get_argument('limit', 10))\n except ValueError:\n limit = 10\n try:\n db = self.settings['db']\n tm = manager.TplManager(db)\n query = {\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n }\n total = yield tm.count(query)\n tag = self.get_argument('tag', None)\n if tag:\n query['tag'] = tag\n res = yield tm.find(query, offset, limit)\n self.write({\n 'res': 'succ',\n 'count': total,\n 'offset': offset,\n 'limit': limit,\n 'data': res,\n })\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n\nclass UpdateHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n tplid = self.get_argument('tplid', '')\n data = {\n 'content': self.get_argument('content', ''),\n 'approved': manager.WAIT4AUD,\n }\n callback = self.get_argument('callback', None)\n if callback or callback != '':\n data['callback'] = callback\n tags = self.get_argument('tags', None)\n if tags:\n data['tags'] = tags.split(',')\n keys = self.get_argument('keys', None)\n if keys:\n data['keys'] = keys.split(',')\n update = {'$set': data}\n q = {\n 'tplid': tplid,\n 'entid': self.get_argument('entid', ''),\n 'product': self.get_argument('product', ''),\n }\n db = self.settings['db']\n tm = manager.TplManager(db)\n try:\n result = yield tm.update(q, update)\n if result:\n self.write({'res': 'succ', 'data': result})\n else:\n self.write({\n 'res': 'fail',\n 'msg': 'tpl {0} not found or \\\n fail for update.'.format(tplid),\n })\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n\n### for administrator ###\nclass OperateHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self, action):\n act = {\n 'approve': self._approve,\n 'marketing': self._marketing,\n 'recover': self._recover,\n 'reject': self._reject\n }\n tplids = self.get_arguments('tplid[]', '')\n db = self.settings['db']\n self.tm = manager.TplManager(db)\n try:\n result = yield act.get(action)(tplids)\n self.write(json.dumps({'res': 'succ', 'msg': result}))\n except exception.SmsException as e:\n logging.error(e)\n self.write(str(e))\n finally:\n self.finish()\n\n @gen.coroutine\n def _approve(self, tplids):\n result = yield self.tm.approve(tplids, sendType='notice')\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _marketing(self, tplids):\n result = yield self.tm.approve(tplids)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _recover(self, tplids):\n query = {'tplid': {'$in': tplids}}\n update = {'$set': {'approved': manager.WAIT4AUD}}\n result = yield self.tm.update(query, update)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def _reject(self, tplids):\n reason = self.get_argument('reason', None),\n query = {'tplid': {'$in': tplids}}\n update = {'$set': {'approved': manager.REJECTED, 'reason': reason[0]}}\n result = yield self.tm.update(query, update)\n self.callback(tplids)\n raise gen.Return(result)\n\n @gen.coroutine\n def callback(self, tplids):\n query = {'tplid': {'$in': tplids}, 'callback': {'$exists': True}}\n results = yield self.tm.find(query)\n for tpl in results:\n callback = tpl.get('callback')\n logging.debug(callback)\n url = urlparse.urlparse(callback)\n if url.netloc == '':\n continue\n message = {'tplid': tpl.get('tplid'), 'status': tpl.get('approved')}\n if message['status'] == manager.REJECTED:\n message['reason'] = tpl.get('reason').encode('utf-8')\n\n client = httpclient.AsyncHTTPClient()\n httpclient.AsyncHTTPClient.configure(\n \"tornado.curl_httpclient.CurlAsyncHTTPClient\")\n yield client.fetch(callback,\n _handle_request, method='POST',\n body=urllib.urlencode(message))\n\n\n#path: /sendByTmpl\nclass SendHandler(web.RequestHandler):\n @web.asynchronous\n @gen.coroutine\n def post(self):\n tplid = self.get_argument('tplid', '')\n db = self.settings['db']\n tm = manager.TplManager(db)\n try:\n tpl = yield tm.findApproved(tplid)\n if tpl:\n result = yield self.send(tpl)\n self.write(result)\n else:\n self.write({'res': 'fail',\n 'info': 'tpl {0} not found or not approved.'\n .format(tplid)})\n except Exception as e:\n logging.error(e)\n self.write({'res': 'fail', 'info': str(e)})\n finally:\n self.finish()\n\n @validator.required(\"entid\")\n @validator.required(\"entpwd\")\n @validator.required(\"license\")\n @validator.required(\"product\")\n @validator.required(\"phones\")\n @validator.required(\"timestamp\")\n @validator.required(\"replace\")\n @validator.required(\"tplid\")\n #@validator.authenticate\n @gen.coroutine\n def send(self, tpl):\n logging.info(\"send message from {0}.\"\n .format(self.get_argument('product')))\n try:\n msg = self.buildMessage(tpl)\n response = yield self.directSend(msg)\n body = json.loads(response.body)\n except Exception as e:\n raise gen.Return({'res': 'fail', 'info': str(e)})\n raise gen.Return(body)\n\n # 发送给短信平台,需要重新计算签名\n @signature('certi_ac')\n def buildMessage(self, tpl):\n m = {\n 'format': 'json',\n 'version': '1.0',\n 'encoding': 'utf8',\n 'certi_app': 'sms.send',\n 'timestamp': int(time.time()),\n 'license': self.get_argument('license'),\n 'source': self.get_argument('product'),\n 'entId': self.get_argument('entid'),\n 'entPwd': self.get_argument('entpwd'),\n }\n use_reply = self.get_argument('use_reply', 0)\n if use_reply == '':\n m['use_reply'] = 0\n backlist = self.get_argument('use_backlist', 1)\n if backlist == '':\n m['use_backlist'] = 1\n\n m['sendType'] = 'fan-out' if tpl.get('type') == 'marketing' else 'notice'\n replace = self.get_argument('replace')\n try:\n r = json.loads(replace)\n content = tpl.get('content')\n keys = tpl.get('keys')\n for k, v in r.items():\n if k in keys:\n if isinstance(v, int):\n v = str(v)\n elif isinstance(v, float):\n v = str(v)\n elif v is None:\n v = ''\n content = content.replace('{{{0}}}'.format(k), v)\n contents = [{\n 'phones': self.get_argument('phones'),\n 'content': content,\n }]\n m['contents'] = json.dumps(contents)\n except Exception as e:\n raise exception.SmsException(\n 20001, 'template content error: {0}'.format(str(e)))\n return m\n\n @gen.coroutine\n def directSend(self, message={}):\n logging.info(message)\n client = httpclient.AsyncHTTPClient()\n httpclient.AsyncHTTPClient.configure(\n \"tornado.curl_httpclient.CurlAsyncHTTPClient\")\n response = yield client.fetch(\n self.settings.get('smsapi'),\n _handle_request,\n method='POST',\n body=urllib.urlencode(message))\n raise gen.Return(response)\n\n\ndef _handle_request(response):\n if response.error:\n logging.error(response.error)\n else:\n logging.info(response.body)\n","sub_path":"app/controller/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":12309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"608568264","text":"from statistics import mean\nnum_iterations = 3\nnum_processor_counts = ['24', '28', '32', '36', '40']\nnum_k = ['2', '25', '50', '100']\nwrite_lines = []\nsums = []\n\n# Build up values dict for population\nvals = {}\nfor p in num_processor_counts:\n vals.update({p:{}})\n for k in num_k:\n vals[p].update({k: {}})\n vals[p][k].update({'distance': 0})\n vals[p][k].update({'centroid': 0})\n vals[p][k].update({'total': 0})\n\n# Read in timing data\nwith open(\"./timings.txt\", \"r\") as fp:\n lines = fp.readlines()\n\n for line in lines:\n if line[0] == 'k':\n short = line[6:].strip()\n nprocs, k = short.split(sep='_')\n\n try:\n spl = line.split()\n for word in range(len(spl)):\n spl[word] = spl[word].rstrip(',')\n distance = float(spl[4])\n centroid = float(spl[-1])\n total = float(spl[2])\n vals[nprocs][k]['distance'] += distance\n vals[nprocs][k]['centroid'] += centroid\n vals[nprocs][k]['total'] += total\n except ValueError:\n pass\n except IndexError:\n pass\n\n for p in num_processor_counts:\n for k in num_k:\n d_mean = vals[p][k]['distance'] / num_iterations\n c_mean = vals[p][k]['centroid'] / num_iterations\n tot_mean = vals[p][k]['total'] / num_iterations\n write_lines.append(\n f\"NPROCS = {p}\\t\"\n f\"K = {k}\\t\"\n f\"dist = {round(d_mean, 4)}\\t\"\n f\"centroid = {round(c_mean, 4)}\\t\"\n f\"total = {round(tot_mean, 4)}\")\n\n# Write to a summary document\nwith open(\"./summary.txt\", \"w\") as w_fp:\n for timing in write_lines:\n w_fp.write(timing + \"\\n\")\n # w_fp.write(f\"global sum: {str(sum)}\\n\\n\")\n\nprint(\"Wrote summary.txt\")\n","sub_path":"a5/a2/out/mean_times.py","file_name":"mean_times.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"400351471","text":"import re\r\nimport pprint\r\n\r\ndt = open(\"FastFoodRestaurants.csv\")\r\ndt.readline()\r\nline_num = 1\r\n\r\n\r\ndef getel(line):\r\n result = re.split(r\",\", line, maxsplit=1)\r\n element = result[0].strip(\"\\\"\")\r\n return element, result[1]\r\n\r\n\r\ndef getaddress(line):\r\n address, line = getel(line)\r\n return address, line\r\n\r\n\r\ndef getcity(line):\r\n city, line = getel(line)\r\n return city, line\r\n\r\n\r\ndef getcountry(line):\r\n country, line = getel(line)\r\n return country, line\r\n\r\n\r\ndef getkeys(line):\r\n keys, line = getel(line)\r\n return keys, line\r\n\r\n\r\ndef getlatitude(line):\r\n latitude, line = getel(line)\r\n return latitude, line\r\n\r\n\r\ndef getlongitude(line):\r\n longitude, line = getel(line)\r\n return longitude, line\r\n\r\n\r\ndataset = {}\r\nfor line in dt:\r\n line = line.strip().rstrip()\r\n address, line = getaddress(line)\r\n city, line = getcity(line)\r\n country, line = getcountry(line)\r\n keys, line = getkeys(line)\r\n latitude, line = getlatitude(line)\r\n if keys[9:30] in latitude:\r\n latitude, line = getlatitude(line)\r\n longitude, line = getlongitude(line)\r\n# print(line_num, country, keys, latitude, longitude)\r\n line_num += 1\r\n if country not in dataset:\r\n dataset[country] = {}\r\n if keys not in dataset[country]:\r\n dataset[country][keys] = dict()\r\n if latitude not in dataset[country][keys]:\r\n dataset[country][keys][latitude] = dict()\r\n dataset[country][keys][latitude] = longitude\r\n\r\npprint.pprint(dataset)\r\ndt.close()\r\n","sub_path":"km-81/Krasnova_Yana/datamess.py","file_name":"datamess.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"513928615","text":"#!/usr/bin/env python\n# encoding: utf-8\n#\n# Copyright SAS Institute\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''' Common layers for the deep learning models '''\n\nfrom .utils import prod_without_none\n\n\nclass Layer(object):\n '''\n Base class for all layers\n\n Parameters\n ----------\n name : str\n Specifies the name of the layer.\n config : dict\n Specifies the configuration of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Layer`\n\n '''\n\n def __init__(self, name=None, config=None, src_layers=None):\n self.name = name\n self.config = config\n if isinstance(src_layers, list):\n self.src_layers = src_layers\n elif src_layers is None:\n self.src_layers = None\n else:\n self.src_layers = list(src_layers)\n\n if 'act' in self.config.keys():\n self.activation = config['act'].title()\n else:\n self.activation = None\n\n self.output_size = None\n self.kernel_size = None\n self.num_weights = None\n self.num_bias = None\n\n def to_model_params(self):\n '''\n Convert the model configuration to SAS Viya parameters\n\n Returns\n -------\n dict\n\n '''\n if self.config['type'].lower() == 'input':\n return dict(name=self.name, layer=self.config)\n else:\n return dict(name=self.name, layer=self.config,\n srclayers=[item.name for item in self.src_layers])\n\n @property\n def summary_str(self):\n '''\n Generate the summary string describing the configuration of the layer.\n '''\n if self.config['type'].lower() == 'input':\n self.output_size = (int(self.config['width']),\n int(self.config['height']),\n int(self.config['nchannels']))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() in ('convo', 'convolution'):\n self.output_size = (int(self.src_layers[0].output_size[0] //\n self.config['stride']),\n int(self.src_layers[0].output_size[1] //\n self.config['stride']),\n int(self.config['nfilters']))\n self.kernel_size = (int(self.config['width']), int(self.config['height']))\n self.num_weights = int(self.config['width'] *\n self.config['height'] *\n self.config['nfilters'] *\n self.src_layers[0].output_size[2])\n if 'includeBias' in self.config.keys():\n if self.config['includeBias'] is False:\n self.num_bias = 0\n else:\n self.num_bias = int(self.config['nfilters'])\n else:\n self.num_bias = int(self.config['nfilters'])\n\n elif self.config['type'].lower() in ('pool', 'pooling'):\n self.output_size = (int(self.src_layers[0].output_size[0] //\n self.config['stride']),\n int(self.src_layers[0].output_size[1] //\n self.config['stride']),\n int(self.src_layers[0].output_size[2]))\n self.kernel_size = (int(self.config['width']), int(self.config['height']))\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() == 'batchnorm':\n self.output_size = self.src_layers[0].output_size\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = int(2 * self.src_layers[0].output_size[2])\n\n elif self.config['type'].lower() == 'residual':\n self.output_size = (int(min([item.output_size[0]\n for item in self.src_layers])),\n int(min([item.output_size[1]\n for item in self.src_layers])),\n int(max([item.output_size[2]\n for item in self.src_layers])))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() == 'concat':\n self.output_size = (int(self.src_layers[0].output_size[0]),\n int(self.src_layers[0].output_size[1]),\n int(sum([item.output_size[2]\n for item in self.src_layers])))\n self.kernel_size = None\n self.num_weights = 0\n self.num_bias = 0\n\n elif self.config['type'].lower() in ('fc', 'fullconnect'):\n if isinstance(self.src_layers[0].output_size, int):\n num_features = self.src_layers[0].output_size\n else:\n num_features = prod_without_none(self.src_layers[0].output_size)\n self.output_size = int(self.config['n'])\n self.kernel_size = (int(num_features), int(self.config['n']))\n self.num_weights = int(num_features * self.config['n'])\n self.num_bias = int(self.config['n'])\n\n elif self.config['type'].lower() == 'output':\n self.type_name = 'Output'\n if isinstance(self.src_layers[0].output_size, int):\n num_features = self.src_layers[0].output_size\n else:\n num_features = prod_without_none(self.src_layers[0].output_size)\n\n if 'n' in self.config.keys():\n self.output_size = int(self.config['n'])\n self.kernel_size = (int(num_features), int(self.config['n']))\n self.num_weights = int(num_features * self.config['n'])\n self.num_bias = int(self.config['n'])\n else:\n self.kernel_size = None\n self.num_weights = None\n self.num_bias = None\n self.output_size = None\n\n name = '{}({})'.format(self.name, self.type_name)\n if len(name) > 17:\n col1 = '| {:<17}'.format('{}'.format(name[:14] + '...'))\n else:\n col1 = '| {:<17}'.format('{}'.format(name))\n\n col2 = '|{:^15}'.format('{}'.format(self.kernel_size))\n\n if 'stride' not in self.config.keys():\n col3 = '|{:^8}'.format('None')\n else:\n col3 = '|{:^8}'.format('{}'.format(int(self.config['stride'])))\n\n col4 = '|{:^12}'.format('{}'.format(self.activation))\n\n col5 = '|{:^17}'.format('{}'.format(self.output_size))\n\n num_paras = '{} / {}'.format(self.num_weights, self.num_bias)\n col6 = '|{:^22}|\\n'.format(num_paras)\n\n return col1 + col2 + col3 + col4 + col5 + col6\n\n\nclass InputLayer(Layer):\n '''\n Input layer\n \n Parameters\n ----------\n n_channels : int\n Specifies the number of channels of the input images.\n width : int\n Specifies the width of the input images.\n height : int\n Specifies the height of the input images.\n scale : double, between 0 and 1.\n Specifies the scaling parameter of the image.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n offsets : iter-of-doubles\n Specifies the offset values.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`InputLayer`\n\n '''\n\n def __init__(self, n_channels=3, width=224, height=224, scale=1,\n dropout=0, offsets=None, name=None, **kwargs):\n if offsets is None:\n offsets = [0] * n_channels\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'input'\n Layer.__init__(self, name, config)\n self.color_code = '#F0FF00'\n self.type_name = 'Input'\n\n\nclass Conv2d(Layer):\n '''\n 2D convolutional layer\n\n Parameters\n ----------\n n_filters : int\n Specifies the number of filters.\n width : int\n Specifies the width of pooling window.\n height : int\n Specifies the height of pooling window.\n stride : int\n Specifies the step size of the moving window.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Conv2d`\n\n '''\n\n def __init__(self, n_filters, width=None, height=None, stride=1,\n act='relu', dropout=0, name=None, src_layers=None, **kwargs):\n if (width is None) and (height is None):\n width = 3\n if width is None:\n width = height\n if height is None:\n height = width\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'convo'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#6CFF00'\n self.type_name = 'Convo.'\n\n\nclass Pooling(Layer):\n '''\n Pooling layer\n\n Parameters\n ----------\n width : int\n Specifies the width of pooling window.\n height : int\n Specifies the height of pooling window.\n stride : int\n Specifies the step size of the moving window.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Pooling`\n\n '''\n\n def __init__(self, width=None, height=None, stride=None,\n pool='max', dropout=0, name=None, src_layers=None, **kwargs):\n if (width is None) and (height is None):\n width = 2\n if width is None:\n width = height\n if height is None:\n height = width\n if stride is None:\n stride = width\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'pool'\n Layer.__init__(self, name, config, src_layers)\n self.activation = pool.title()\n self.color_code = '#FF9700'\n self.type_name = 'Pool'\n\n\nclass Dense(Layer):\n '''\n Fully connected layer\n\n Parameters\n ----------\n n : int\n Specifies the number of neurons.\n act : str\n Specifies the activation types.\n dropout : double, between 0 and 1\n Specifies the dropout rate.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Dense`\n\n '''\n\n def __init__(self, n, act='relu', dropout=0,\n name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'fc'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#00ECFF'\n self.type_name = 'F.C.'\n\n\nclass Recurrent(Layer):\n '''\n Recurrent layer\n\n Parameters\n ----------\n n : int\n Specifies the number of neurons.\n act : str\n Specifies the activation types.\n rnn_type : str\n Specifies the type of RNN gate.\n output_type : str\n Specifies the type of output neurons.\n reversed_ : bool\n Specifies whether to reverse the sequence.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Recurrent`\n\n '''\n\n def __init__(self, n, act='AUTO', rnn_type='RNN', output_type='ENCODING',\n reversed_=False, name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'recurrent'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFA4A4'\n self.type_name = 'Rec.'\n\n\nclass BN(Layer):\n '''\n Batch Normalization layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`BN`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'batchnorm'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFF999'\n self.type_name = 'B.N.'\n\n\nclass Res(Layer):\n '''\n Residual layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional.\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Res`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'residual'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FF0000'\n self.type_name = 'Resid.'\n\n\nclass Concat(Layer):\n '''\n Concatenation layer\n\n Parameters\n ----------\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Concat`\n\n '''\n\n def __init__(self, act='AUTO', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'concat'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#DD5022'\n self.type_name = 'Concat.'\n\n\nclass Proj(Layer):\n '''\n Projection layer\n\n Parameters\n ----------\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`Proj`\n\n '''\n\n def __init__(self, name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'projection'\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#FFA2A3'\n self.type_name = 'Proj.'\n\n\nclass OutputLayer(Layer):\n '''\n Output layer\n\n Parameters\n ----------\n n : int\n Specifies the number of output neurons.\n act : str\n Specifies the activation types.\n name : str\n Specifies the name of the layer.\n src_layers : iter-of-Layers, optional\n Specifies the source layer(s).\n\n Returns\n -------\n :class:`OutputLayer`\n \n '''\n\n def __init__(self, n=None, act='softmax', name=None, src_layers=None, **kwargs):\n config = locals()\n config = _unpack_config(config)\n config['type'] = 'output'\n if config['n'] is None:\n del config['n']\n Layer.__init__(self, name, config, src_layers)\n self.color_code = '#C8C8C8'\n self.type_name = 'Output.'\n\n\ndef _unpack_config(config):\n ''' Unpack the configuration from the keyword-argument-only input '''\n kwargs = config['kwargs']\n del config['self'], config['name'], config['kwargs']\n try:\n del config['src_layers']\n except:\n pass\n out = {}\n out.update(config)\n out.update(kwargs)\n for key in out:\n if '_' in key:\n new_key = key.replace('_', '')\n out[new_key] = out[key]\n out.pop(key)\n return out\n","sub_path":"dlpy/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":16548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"118440965","text":"import naoqi\nimport time\nimport almath\nimport math\n\nNIp = \"10.16.96.41\"\nPORT = 9559\n\nmotion = naoqi.ALProxy(\"ALMotion\", NIp, PORT)\nposture = naoqi.ALProxy(\"ALRobotPosture\", NIp, PORT)\ntts = naoqi.ALProxy(\"ALTextToSpeech\", NIp,PORT)\nmarkProxy = naoqi.ALProxy(\"ALLandMarkDetection\", NIp, PORT)\nanimatedMode = naoqi.ALProxy(\"ALAutonomousLife\", NIp, PORT)\n\nid = posture.goToPosture(\"Stand\", 1.)\n\ns = tts.post.say(\"I feel pretty!\")\nmotion.wait(s, 0)\nid = motion.post.moveTo(0, 0, math.pi / 2)\nmotion.wait(id, 0)\ns = tts.post.say(\"Does my ass look fat in this outfit?\")\nmotion.wait(s, 0)\nmotion.rest()\n\n","sub_path":"ifp.py","file_name":"ifp.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"415471063","text":"#\n# [3] Longest Substring Without Repeating Characters\n#\n# https://leetcode.com/problems/longest-substring-without-repeating-characters/description/\n#\n# algorithms\n# Medium (24.81%)\n# Total Accepted: 516.4K\n# Total Submissions: 2.1M\n# Testcase Example: '\"abcabcbb\"'\n#\n# Given a string, find the length of the longest substring without repeating\n# characters.\n# \n# Examples: \n# \n# Given \"abcabcbb\", the answer is \"abc\", which the length is 3.\n# \n# Given \"bbbbb\", the answer is \"b\", with the length of 1.\n# \n# Given \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the\n# answer must be a substring, \"pwke\" is a subsequence and not a substring.\n#\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n l = 0 \n r = 0 \n dict = {}\n track = 0 \n while r < len(s): \n if s[r] not in dict.keys() or dict[s[r]] < l: \n dict[s[r]] = r \n track = max(r - l + 1, track) \n r = r + 1 \n else: \n l = dict[s[r]] + 1 \n dict[s[r]] = r\n track = max(r - l + 1, track) \n r = r + 1 \n return track \n","sub_path":"3.longest-substring-without-repeating-characters.python3.py","file_name":"3.longest-substring-without-repeating-characters.python3.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}
+{"seq_id":"399638731","text":"\"\"\"\n\nProgram: create_variant_seqs.py\n\nPurpose: Read in a variant table and a reference sequence, and use them to\n create a file of variant sequences.\n\nInputs: var_table_file (variant table)\n refseq_file (reference sequence file)\n out_file (output file)\n\nOutputs: csv file\n\nExecution: python3 create_variant_seqs.py \n